text
stringlengths
2
1.04M
meta
dict
package ucar.nc2.ui.op; import ucar.nc2.ui.OpPanel; import ucar.nc2.ui.ToolsUI; import ucar.nc2.ui.grib.Grib2CollectionPanel; import ucar.ui.widget.BAMutil; import ucar.util.prefs.PreferencesExt; import java.awt.BorderLayout; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Formatter; import javax.swing.AbstractButton; import javax.swing.JOptionPane; /** * */ public class Grib2CollectionOpPanel extends OpPanel { private Grib2CollectionPanel gribTable; /** * */ public Grib2CollectionOpPanel(PreferencesExt p) { super(p, "collection:", true, false); gribTable = new Grib2CollectionPanel(prefs, buttPanel); add(gribTable, BorderLayout.CENTER); gribTable.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("openGrib2Collection")) { String collectionName = (String) e.getNewValue(); ToolsUI.getToolsUI().openGrib2Collection(collectionName); } } }); AbstractButton showButt = BAMutil.makeButtcon("Information", "Show Collection", false); showButt.addActionListener(e -> { Formatter f = new Formatter(); gribTable.showCollection(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); }); buttPanel.add(showButt); AbstractButton infoButton = BAMutil.makeButtcon("Information", "Check Problems", false); infoButton.addActionListener(e -> { Formatter f = new Formatter(); gribTable.checkProblems(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); }); buttPanel.add(infoButton); AbstractButton gdsButton = BAMutil.makeButtcon("Information", "Show GDS use", false); gdsButton.addActionListener(e -> { Formatter f = new Formatter(); gribTable.showGDSuse(f); detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); }); buttPanel.add(gdsButton); AbstractButton writeButton = BAMutil.makeButtcon("nj22/Netcdf", "Write index", false); writeButton.addActionListener(e -> { Formatter f = new Formatter(); try { if (!gribTable.writeIndex(f)) { return; } f.format("WriteIndex was successful%n"); } catch (IOException e1) { e1.printStackTrace(); } detailTA.setText(f.toString()); detailTA.gotoTop(); detailWindow.show(); }); buttPanel.add(writeButton); } /** * */ public void setCollection(String collection) { if (process(collection)) { cb.addItem(collection); } } /** */ @Override public boolean process(Object o) { String command = (String) o; boolean err = false; try { gribTable.setCollection(command); } catch (FileNotFoundException ioe) { JOptionPane.showMessageDialog(null, "NetcdfDataset cannot open " + command + "\n" + ioe.getMessage()); err = true; } catch (Exception e) { e.printStackTrace(); StringWriter sw = new StringWriter(5000); e.printStackTrace(new PrintWriter(sw)); detailTA.setText(sw.toString()); detailWindow.show(); err = true; } return !err; } /** */ @Override public void closeOpenFiles() throws IOException { gribTable.closeOpenFiles(); } /** */ @Override public void save() { gribTable.save(); super.save(); } }
{ "content_hash": "ce7513969a0fd7db325de4e4adfa7190", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 108, "avg_line_length": 26.71323529411765, "alnum_prop": 0.6614368290668868, "repo_name": "Unidata/netcdf-java", "id": "90b1e9a1457f18f1b77484d928e84802a2aa44bd", "size": "3762", "binary": false, "copies": "1", "ref": "refs/heads/maint-5.x", "path": "uicdm/src/main/java/ucar/nc2/ui/op/Grib2CollectionOpPanel.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AGS Script", "bytes": "708007" }, { "name": "C", "bytes": "404428" }, { "name": "C++", "bytes": "10772" }, { "name": "CSS", "bytes": "13861" }, { "name": "Groovy", "bytes": "95588" }, { "name": "HTML", "bytes": "3774351" }, { "name": "Java", "bytes": "21758821" }, { "name": "Makefile", "bytes": "2434" }, { "name": "Objective-J", "bytes": "28890" }, { "name": "Perl", "bytes": "7860" }, { "name": "PowerShell", "bytes": "678" }, { "name": "Python", "bytes": "20750" }, { "name": "Roff", "bytes": "34262" }, { "name": "Shell", "bytes": "18859" }, { "name": "Tcl", "bytes": "5307" }, { "name": "Vim Script", "bytes": "88" }, { "name": "Visual Basic 6.0", "bytes": "1269" }, { "name": "Yacc", "bytes": "25086" } ], "symlink_target": "" }
/** * Technically, a Change expresses an intention for alter the structure of the Database. An example would be: * "Drop all foreign keys from a table". However, it abstracts from the way this is actually archieved: While one * DBMS might provide a syntax for that (maybe something like "ALTER TABLE myTable DROP ALL FOREIGN KEYS"), others * do not have a 1:1 translation and need to perform the change in several steps (e.g. enumerating all foreign keys * and then dropping them one-by-one).<p> * <p> * This package contains all the possible basic Changes that should be possible with every DBMS supported by DB-Manul / * Liquibase. Most classes here extend the {@link liquibase.change.AbstractChange} class that provides the general * frame for the Change. */ package liquibase.change.core;
{ "content_hash": "319e5f7d052648f66957a533255ba357", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 119, "avg_line_length": 66.91666666666667, "alnum_prop": 0.763387297633873, "repo_name": "dbmanul/dbmanul", "id": "9a23460073f1e0fca5defd4274d6f697358ed676", "size": "803", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "liquibase-core/src/main/java/liquibase/change/core/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "552" }, { "name": "CSS", "bytes": "1202" }, { "name": "Groovy", "bytes": "588876" }, { "name": "HTML", "bytes": "2223" }, { "name": "Inno Setup", "bytes": "2522" }, { "name": "Java", "bytes": "4499069" }, { "name": "PLSQL", "bytes": "6836" }, { "name": "PLpgSQL", "bytes": "682" }, { "name": "Puppet", "bytes": "5196" }, { "name": "Roff", "bytes": "3104" }, { "name": "Ruby", "bytes": "5624" }, { "name": "SQLPL", "bytes": "5342" }, { "name": "Shell", "bytes": "4834" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Linq; namespace AdventOfCode.Day5 { public static class SantaWordValidator { public static bool IsNice(string input) { var word = input.ToLowerInvariant().Trim('\n', '\t', '\r'); // At least three vowels is needed var vowels = new HashSet<char> { 'a','e','i','o','u' }; var numVowels = word.Count(x => vowels.Contains(x)); if (numVowels < 3) return false; // No bad substrings var badSubStr = new List<string> { "ab", "cd", "pq", "xy" }; if (badSubStr.Any(word.Contains)) return false; // At least one letter twice in a row for (int x = 1; x < word.Length; ++x) { if(word[x-1] == word[x]) return true; } return false; } public static bool IsNewNice(string input) { var word = input.ToLowerInvariant().Trim('\n', '\t', '\r'); return HasRepeatOfLetterWithExcatlyOneBetween(word) && HasDoublePairThatIsNotConsecqutive(word); } private static bool HasDoublePairThatIsNotConsecqutive(string word) { for (int x = 3; x < word.Length; ++x) { var first = word[x - 3]; var second = word[x - 2]; for (int y = 0; y + x < word.Length; ++y) { var third = word[x + y - 1]; var fourth = word[x + y]; if (first == third && second == fourth) return true; } } return false; } private static bool HasRepeatOfLetterWithExcatlyOneBetween(string word) { for (int x = 2; x < word.Length; ++x) { if (word[x - 2] == word[x]) return true; } return false; } } }
{ "content_hash": "d5f3e3fd75ba6458e3b5639f5138b670", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 108, "avg_line_length": 29.134328358208954, "alnum_prop": 0.47848360655737704, "repo_name": "SirCAS/AdventOfCode", "id": "ee53b00a5d3f4d849b701a8dc8ad8a8783a9c813", "size": "1952", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "Day05/SantaWordValidator.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "142141" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "1d969269a35f58054239a11ab65cfdc6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "cd8a4119fe24fe9369ee18f4e37ee9e30fe985b4", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Linaceae/Reinwardtia/Reinwardtia sinensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
{% if paginator.total_pages %}<hr class="post-list__divider " />{% endif %} <nav class="pagination" role="navigation"> {% if paginator.previous_page %} <a class="newer-posts pagination__newer btn btn-small btn-tertiary" href="{{ paginator.previous_page_path }}#blog">&larr; 最近</a> {% endif %} <span class="pagination__page-number">{{ paginator.page }}{% if paginator.total_pages %} / {% endif %}{{ paginator.total_pages }}</span> {% if paginator.next_page %} <a class="older-posts pagination__older btn btn-small btn-tertiary" href="{{ paginator.next_page_path }}#blog">更早 &rarr;</a> {% endif %} </nav>
{ "content_hash": "a76f50d9c31063faa642df83958d34e3", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 140, "avg_line_length": 58.18181818181818, "alnum_prop": 0.6375, "repo_name": "VOREVER/vorever.github.io", "id": "bf06cef8a7a5fc8df6e17e7d9e2e5fb39759101a", "size": "648", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/pagination.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "31211" }, { "name": "HTML", "bytes": "15458" }, { "name": "JavaScript", "bytes": "2338" }, { "name": "Python", "bytes": "5512" }, { "name": "Ruby", "bytes": "2041" } ], "symlink_target": "" }
package com.nico.app.ui.activity.basicimage; import com.nico.app.ui.base.BaseActivity; /** * Created by 就这样子 on 2016/4/29. */ public class LoadImageActivity extends BaseActivity { }
{ "content_hash": "6a5bca4428922bd50670590bdffba0b0", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 53, "avg_line_length": 20.666666666666668, "alnum_prop": 0.7526881720430108, "repo_name": "wubin001/fresco_dome", "id": "03e456ce052f36c91292ad1b18c3853b208ac333", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/nico/app/ui/activity/basicimage/LoadImageActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "19441" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "f9da40e6e5e06e1001dcc6e4479fd08e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "1d9186584600cb8a083738456b20151d154f1e9f", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pinophyta/Pinopsida/Pinales/Pinaceae/Pinus/Pinus rhaetica/ Syn. Pinus sylvestris hybrida/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /* SVN FILE: $Id$ */ /** * SassReturnNode class file. * @author Richard Lyon <richthegeek@gmail.com> * @copyright none * @license http://phamlp.googlecode.com/files/license.txt * @package PHamlP * @subpackage Sass.tree */ /** * SassReturnNode class. * Represents a Return. * @package PHamlP * @subpackage Sass.tree */ class SassWarnNode extends SassNode { const NODE_IDENTIFIER = '+'; const MATCH = '/^(@warn\s+)(["\']?)(.*?)(["\']?)$/i'; const IDENTIFIER = 1; const STATEMENT = 3; /** * @var statement to execute and return */ private $statement; /** * SassReturnNode constructor. * @param object source token * @return SassReturnNode */ public function __construct($token) { parent::__construct($token); preg_match(self::MATCH, $token->source, $matches); if (empty($matches)) { return new SassBoolean('false'); } $this->statement = $matches[self::STATEMENT]; } /** * Parse this node. * Set passed arguments and any optional arguments not passed to their * defaults, then render the children of the return definition. * @param SassContext the context in which this node is parsed * @return array the parsed node */ public function parse($pcontext) { $context = new SassContext($pcontext); $statement = $this->statement; try { $statement = $this->evaluate($this->statement, $context)->toString(); } catch (Exception $e) {} if (SassParser::$instance->options['callbacks']['warn']) { call_user_func(SassParser::$instance->options['callbacks']['warn'], $statement, $context); } if (SassParser::$instance->getQuiet()) { return array(new SassString('')); } else { return array(new SassString('/* @warn: ' . str_replace('*/', '', $statement) . ' */')); } } /** * Returns a value indicating if the token represents this type of node. * @param object token * @return boolean true if the token represents this type of node, false if not */ public static function isa($token) { return $token->source[0] === self::NODE_IDENTIFIER; } }
{ "content_hash": "ba0da120f75efd07c57d040adf96a95d", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 96, "avg_line_length": 26.54320987654321, "alnum_prop": 0.6227906976744186, "repo_name": "FrediBach/Fourstatic", "id": "f583e8d4a8e92656039320d6bd1e461afb84ef4c", "size": "2150", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "fourstatic/lib/phpsass/tree/SassWarnNode.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "196652" }, { "name": "PHP", "bytes": "1287323" }, { "name": "Shell", "bytes": "963" } ], "symlink_target": "" }
package org.apache.kylin.metadata.tuple; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import org.junit.Test; public class EmptyTupleIteratorTest { @Test public void testListAllTables() throws Exception { ITupleIterator it = ITupleIterator.EMPTY_TUPLE_ITERATOR; assertFalse(it.hasNext()); assertNull(it.next()); it.close(); // for coverage } }
{ "content_hash": "51d90e488c100b2c7ea72ae2f770eb7a", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 64, "avg_line_length": 21.8, "alnum_prop": 0.7018348623853211, "repo_name": "lemire/incubator-kylin", "id": "1e64d1f189803fb343629fca7e620af3efb66745", "size": "1241", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "metadata/src/test/java/org/apache/kylin/metadata/tuple/EmptyTupleIteratorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "168428" }, { "name": "HTML", "bytes": "264513" }, { "name": "Java", "bytes": "3625055" }, { "name": "JavaScript", "bytes": "229379" }, { "name": "PLSQL", "bytes": "905" }, { "name": "Protocol Buffer", "bytes": "759" }, { "name": "Shell", "bytes": "28018" } ], "symlink_target": "" }
class Forge::DispatchesController < ForgeController load_and_authorize_resource before_filter :uses_ckeditor, :only => [:edit, :new, :update, :create] def index respond_to do |format| format.html { @dispatches = Dispatch.paginate(:per_page => 10, :page => params[:page]) } format.js { @dispatches = Dispatch.where("title LIKE ?", "%#{params[:q]}%") render :partial => "dispatch", :collection => @dispatches } end end def new @dispatch = Dispatch.new end def edit end def show @dispatch = Dispatch.find(params[:id], :include => [:messages, :queued_messages, :opens, :sent_messages, :failed_messages]) end def chart_data render :json => @dispatch.chart_data end def opens @opens = @dispatch.opens.paginate(:per_page => 15, :page => params[:page]) end def clicks @clicks = DispatchLinkClick.includes(:dispatch_link).where("dispatch_links.dispatch_id = ?", @dispatch.id).paginate(:per_page => 15, :page => params[:page]) end def unsubscribes @unsubscribes = @dispatch.unsubscribes.paginate(:per_page => 15, :page => params[:page]) end def create @dispatch = Dispatch.new(params[:dispatch]) if @dispatch.save flash[:notice] = 'Dispatch was successfully created.' redirect_to(forge_dispatches_path) else render :action => "new" end end def update if @dispatch.update_attributes(params[:dispatch]) flash[:notice] = 'Dispatch was successfully updated.' redirect_to(forge_dispatches_path) else render :action => "edit" end end def destroy @dispatch.destroy redirect_to(forge_dispatches_path) end def queue @groups = SubscriberGroup.all @total_subscribers = Subscriber.count end def test_send DispatchMailer.dispatch(@dispatch, params[:test_send_email], "Admin", current_user.id).deliver flash[:notice] = "A copy of the dispatch was sent to #{params[:test_send_email]}." redirect_to queue_forge_dispatch_path(@dispatch) end def send_all if params[:group_send] && params[:group_ids].blank? flash[:warning] = "You must select the groups to send the dispatch to." redirect_to queue_forge_dispatch_path(@dispatch) else @dispatch.deliver!(params[:group_ids]) flash[:notice] = "Your dispatch is currently sending." redirect_to forge_dispatches_path end end private def get_dispatch @dispatch = Dispatch.find(params[:id]) end end
{ "content_hash": "2697e632a370f5014caa2869dfb54c5f", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 160, "avg_line_length": 27.51086956521739, "alnum_prop": 0.6495456341367049, "repo_name": "socialtech/forge", "id": "72d4b16c14c66acc76f517132d41330791f511a6", "size": "2531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "f3-rails/app/controllers/forge/dispatches_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "1700" }, { "name": "JavaScript", "bytes": "3002359" }, { "name": "Ruby", "bytes": "385559" } ], "symlink_target": "" }
/* * Constants used in multiple source files and messages. */ 'use strict'; var constants = {}; constants.events = {}; constants.events.TAG_FOUND = 'tagFound'; constants.events.TAG_ERROR = 'tagError'; constants.values = {}; constants.values.TAG_HEADER_LENGTH = 10; constants.values.FRAME_HEADER_LENGTH = 10; constants.values.SIZE_BYTES_LENGTH = 4; constants.values.FRAME_ID_LENGTH = 4; constants.values.bitMasks = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80]; constants.messages = {}; constants.messages.NOT_A_TAG_HEADER = 'Array does not contain a ID3v2 tag header.'; constants.messages.NOT_A_FRAME_HEADER = 'Array does not contain a ID3v2 frame header.'; constants.messages.START_NOT_WITHIN_ARRAY = 'The start position is not within the array.'; constants.messages.BYTE_ADDED_AFTER_COMPLETE = 'The tag or frame is already complete.'; constants.messages.DONT_CALL_ON_BASE_CLASS = 'This function should not be called on the base class.'; constants.messages.FRAME_MUST_BE_COMPLETE = 'The frame must be complete if the tag is complete.'; constants.messages.PADDING_ONLY_WITH_0 = 'For padding only 0 can be used.'; constants.messages.NOT_IMPLEMENTED = 'This feature is not yet implemented.'; constants.messages.ONLY_ON_TEXT_FRAMES = 'This function can only be called on TEXT frames.'; constants.messages.ONLY_ON_COMPLETE_FRAMES = 'This function can only be called on COMPLETE frames.'; constants.messages.UNKNOWN_ENCODING = 'The encoding byte is not a known encoding type.'; constants.messages.NO_FRAMES_FOUND = 'There is no frame to add the byte to.' constants.enums = {}; constants.enums.frameStates = {ADDING_DATA: 1, COMPLETE: 2, NO_FRAME_FOUND: 3}; constants.enums.frameTypes = {TEXT: 1, OTHER: 2}; constants.enums.tagStates = {CREATING_FRAME_HEADER: 1, ADDING_FRAME_BYTES: 2, PADDING: 3, COMPLETE: 4}; module.exports = constants;
{ "content_hash": "ad30a9523041dac803ed1ddb78143e8f", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 103, "avg_line_length": 47.333333333333336, "alnum_prop": 0.7513542795232936, "repo_name": "taeke/ID3V2", "id": "667e8aacda1be896365f881061ec65ebd7fb66e3", "size": "1846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/constants.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "90320" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FloatOrDouble { class FloatOrDouble { static void Main() { double a = 34.567839023; float b = 12.345f; double c = 8923.1234857; float d = 3456.091f; Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); } } }
{ "content_hash": "9a4c7c057a318faa8511dc97235ee40a", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 36, "avg_line_length": 21.869565217391305, "alnum_prop": 0.5546719681908548, "repo_name": "ihris7ov/CSharpPartOneHomeworkTasks", "id": "1a38557ff41b590cc54572442eb1c400f9ed8490", "size": "505", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DataTypesAndVariables/DataTypesAndVariables/FloatOrDouble/FloatOrDouble.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "180730" } ], "symlink_target": "" }
/*************************************************************************/ /* file_access_compressed.h */ /*************************************************************************/ /* 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. */ /*************************************************************************/ #ifndef FILE_ACCESS_COMPRESSED_H #define FILE_ACCESS_COMPRESSED_H #include "core/io/compression.h" #include "core/io/file_access.h" class FileAccessCompressed : public FileAccess { Compression::Mode cmode = Compression::MODE_ZSTD; bool writing = false; uint64_t write_pos = 0; uint8_t *write_ptr = nullptr; uint32_t write_buffer_size = 0; uint64_t write_max = 0; uint32_t block_size = 0; mutable bool read_eof = false; mutable bool at_end = false; struct ReadBlock { uint32_t csize; uint64_t offset; }; mutable Vector<uint8_t> comp_buffer; uint8_t *read_ptr = nullptr; mutable uint32_t read_block = 0; uint32_t read_block_count = 0; mutable uint32_t read_block_size = 0; mutable uint64_t read_pos = 0; Vector<ReadBlock> read_blocks; uint64_t read_total = 0; String magic = "GCMP"; mutable Vector<uint8_t> buffer; FileAccess *f = nullptr; public: void configure(const String &p_magic, Compression::Mode p_mode = Compression::MODE_ZSTD, uint32_t p_block_size = 4096); Error open_after_magic(FileAccess *p_base); virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(uint64_t p_position); ///< seek to a given position virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file virtual uint64_t get_position() const; ///< get position in the file virtual uint64_t get_length() const; ///< get size of the file virtual bool eof_reached() const; ///< reading passed EOF virtual uint8_t get_8() const; ///< get a byte virtual uint64_t get_buffer(uint8_t *p_dst, uint64_t p_length) const; virtual Error get_error() const; ///< get last error virtual void flush(); virtual void store_8(uint8_t p_dest); ///< store a byte virtual bool file_exists(const String &p_name); ///< return true if a file exists virtual uint64_t _get_modified_time(const String &p_file); virtual uint32_t _get_unix_permissions(const String &p_file); virtual Error _set_unix_permissions(const String &p_file, uint32_t p_permissions); FileAccessCompressed() {} virtual ~FileAccessCompressed(); }; #endif // FILE_ACCESS_COMPRESSED_H
{ "content_hash": "4990a4a5f6afdee3468f71440e12cf52", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 120, "avg_line_length": 44.24, "alnum_prop": 0.5793399638336347, "repo_name": "Faless/godot", "id": "97ef3fbdeb072ff900c90efc39fa7e7940289b0d", "size": "4424", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/io/file_access_compressed.h", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "1633" }, { "name": "C", "bytes": "820090" }, { "name": "C#", "bytes": "954253" }, { "name": "C++", "bytes": "36679303" }, { "name": "CMake", "bytes": "538" }, { "name": "GAP", "bytes": "62" }, { "name": "GDScript", "bytes": "59146" }, { "name": "GLSL", "bytes": "802565" }, { "name": "Java", "bytes": "512268" }, { "name": "JavaScript", "bytes": "184665" }, { "name": "Kotlin", "bytes": "16172" }, { "name": "Makefile", "bytes": "1421" }, { "name": "Objective-C", "bytes": "20550" }, { "name": "Objective-C++", "bytes": "315906" }, { "name": "PowerShell", "bytes": "2713" }, { "name": "Python", "bytes": "427946" }, { "name": "Shell", "bytes": "27482" } ], "symlink_target": "" }
@implementation SEGUXCamIntegration #pragma mark - Initialization + (void)load { [SEGAnalytics registerIntegration:self withIdentifier:@"UXCam"]; NSLog(@"UXCam load method called"); } - (id)init { if (self = [super init]) { self.name = @"UXCam"; self.valid = NO; self.initialized = NO; self.uxcamClass = [UXCam class]; } return self; } - (void)start { NSString *apiKey = [self.settings objectForKey:@"apiKey"]; [self.uxcamClass startWithKey:apiKey]; [super start]; } #pragma mark - Settings - (void)validate { BOOL hasAPIKey = [self.settings objectForKey:@"apiKey"] != nil; self.valid = hasAPIKey; } #pragma mark - Analytics API - (void)identify:(NSString *)userId traits:(NSDictionary *)traits options:(NSDictionary *)options { if (userId.length > 0) { [self.uxcamClass tagUsersName:userId additionalData:nil]; // Any traits/options we could put into additionalData??? } } - (void)screen:(NSString *)screenTitle properties:(NSDictionary *)properties options:(NSDictionary *)options { if (screenTitle.length > 0) { [self.uxcamClass tagScreenName:screenTitle]; } } - (void)track:(NSString *)event properties:(NSDictionary *)properties options:(NSDictionary *)options { if (event.length > 0) { [self.uxcamClass addTag:event]; // Just the basic event - no properties/options added. } } @end
{ "content_hash": "a216d5dc7d0cc8a1d6e8d27cc894d3af", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 123, "avg_line_length": 22.919354838709676, "alnum_prop": 0.6643209007741028, "repo_name": "jonathannorris/analytics-ios", "id": "027adf6e31ea0ff73e0892be21ea613ffdf2bfe6", "size": "1658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Analytics/Integrations/UXCam/SEGUXCamIntegration.m", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "625" }, { "name": "Makefile", "bytes": "333" }, { "name": "Objective-C", "bytes": "248654" }, { "name": "Ruby", "bytes": "5962" }, { "name": "Shell", "bytes": "6502" } ], "symlink_target": "" }
package main import ( "context" "log" "strconv" "time" amqp "github.com/rabbitmq/amqp091-go" ) func failOnError(err error, msg string) { if err != nil { log.Panicf("%s: %s", msg, err) } } func fib(n int) int { if n == 0 { return 0 } else if n == 1 { return 1 } else { return fib(n-1) + fib(n-2) } } func main() { conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") failOnError(err, "Failed to connect to RabbitMQ") defer conn.Close() ch, err := conn.Channel() failOnError(err, "Failed to open a channel") defer ch.Close() q, err := ch.QueueDeclare( "rpc_queue", // name false, // durable false, // delete when unused false, // exclusive false, // no-wait nil, // arguments ) failOnError(err, "Failed to declare a queue") err = ch.Qos( 1, // prefetch count 0, // prefetch size false, // global ) failOnError(err, "Failed to set QoS") msgs, err := ch.Consume( q.Name, // queue "", // consumer false, // auto-ack false, // exclusive false, // no-local false, // no-wait nil, // args ) failOnError(err, "Failed to register a consumer") var forever chan struct{} go func() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for d := range msgs { n, err := strconv.Atoi(string(d.Body)) failOnError(err, "Failed to convert body to integer") log.Printf(" [.] fib(%d)", n) response := fib(n) err = ch.PublishWithContext(ctx, "", // exchange d.ReplyTo, // routing key false, // mandatory false, // immediate amqp.Publishing{ ContentType: "text/plain", CorrelationId: d.CorrelationId, Body: []byte(strconv.Itoa(response)), }) failOnError(err, "Failed to publish a message") d.Ack(false) } }() log.Printf(" [*] Awaiting RPC requests") <-forever }
{ "content_hash": "05c7e61dd3db80c9d3cefe6913a3a222", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 73, "avg_line_length": 20.13684210526316, "alnum_prop": 0.5938316779926817, "repo_name": "rabbitmq/rabbitmq-tutorials", "id": "bbca71aef882ed1a7155ff73421db97de83bb5d9", "size": "1913", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "go/rpc_server.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "83" }, { "name": "C#", "bytes": "62138" }, { "name": "Clojure", "bytes": "10096" }, { "name": "Dart", "bytes": "12121" }, { "name": "Dockerfile", "bytes": "269" }, { "name": "Elixir", "bytes": "8697" }, { "name": "Erlang", "bytes": "12632" }, { "name": "Go", "bytes": "20065" }, { "name": "Haskell", "bytes": "14634" }, { "name": "Java", "bytes": "77025" }, { "name": "JavaScript", "bytes": "11013" }, { "name": "Julia", "bytes": "16726" }, { "name": "Kotlin", "bytes": "20296" }, { "name": "Makefile", "bytes": "4130" }, { "name": "Objective-C", "bytes": "20582" }, { "name": "PHP", "bytes": "36920" }, { "name": "Perl", "bytes": "9823" }, { "name": "PowerShell", "bytes": "834" }, { "name": "Python", "bytes": "18544" }, { "name": "Ruby", "bytes": "7789" }, { "name": "Rust", "bytes": "19868" }, { "name": "Scala", "bytes": "15766" }, { "name": "Shell", "bytes": "13637" }, { "name": "Swift", "bytes": "17938" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "15744fedee7101ffca9724f35ff5f887", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "447d729e3ab03e66e93f5972d5f63eb09a4ecc43", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Proteales/Proteaceae/Panopsis/Panopsis hameliifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* Generated By:JJTree: Do not edit this line. ASTUpperCase.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package org.openrdf.query.parser.sparql.ast; public class ASTUpperCase extends SimpleNode { public ASTUpperCase(int id) { super(id); } public ASTUpperCase(SyntaxTreeBuilder p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(SyntaxTreeBuilderVisitor visitor, Object data) throws VisitorException { return visitor.visit(this, data); } } /* JavaCC - OriginalChecksum=612e77ae933491e0df62fc69e5abfded (do not edit this line) */
{ "content_hash": "ad4a2478b6575582eeb7a7918653ddc2", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 166, "avg_line_length": 34.80952380952381, "alnum_prop": 0.7482900136798906, "repo_name": "ConstantB/ontop-spatial", "id": "c9fcdbde27bdb98dcf850feb7fa7781940362c29", "size": "731", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "obdalib-sesame/src/main/java/org/openrdf/query/parser/sparql/ast/ASTUpperCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "725" }, { "name": "CSS", "bytes": "2676" }, { "name": "GAP", "bytes": "43623" }, { "name": "HTML", "bytes": "2860560" }, { "name": "Java", "bytes": "6929671" }, { "name": "PLpgSQL", "bytes": "75540766" }, { "name": "Ruby", "bytes": "52622" }, { "name": "Shell", "bytes": "18315" }, { "name": "TeX", "bytes": "10376" }, { "name": "Web Ontology Language", "bytes": "52563785" } ], "symlink_target": "" }
<?php namespace Timber; use Timber\CoreInterface; use Timber\Helper; use Timber\Post; use Timber\URLHelper; /** * If TimberPost is the class you're going to spend the most time, TimberImage is the class you're going to have the most fun with. * @example * ```php * $context = Timber::get_context(); * $post = new TimberPost(); * $context['post'] = $post; * * // lets say you have an alternate large 'cover image' for your post stored in a custom field which returns an image ID * $cover_image_id = $post->cover_image; * $context['cover_image'] = new TimberImage($cover_image_id); * Timber::render('single.twig', $context); * ``` * * ```twig * <article> * <img src="{{cover_image.src}}" class="cover-image" /> * <h1 class="headline">{{post.title}}</h1> * <div class="body"> * {{post.content}} * </div> * * <img src="{{ Image(post.custom_field_with_image_id).src }}" alt="Another way to initialize images as TimberImages, but within Twig" /> * </article> * ``` * * ```html * <article> * <img src="http://example.org/wp-content/uploads/2015/06/nevermind.jpg" class="cover-image" /> * <h1 class="headline">Now you've done it!</h1> * <div class="body"> * Whatever whatever * </div> * <img src="http://example.org/wp-content/uploads/2015/06/kurt.jpg" alt="Another way to initialize images as TimberImages, but within Twig" /> * </article> * ``` */ class Image extends Post implements CoreInterface { protected $_can_edit; protected $_dimensions; public $abs_url; /** * @var string $object_type what does this class represent in WordPress terms? */ public $object_type = 'image'; /** * @var string $representation what does this class represent in WordPress terms? */ public static $representation = 'image'; /** * @var array of supported relative file types */ private $file_types = array('jpg', 'jpeg', 'png', 'svg', 'bmp', 'ico', 'gif', 'tiff', 'pdf'); /** * @api * @var string $file_loc the location of the image file in the filesystem (ex: `/var/www/htdocs/wp-content/uploads/2015/08/my-pic.jpg`) */ public $file_loc; public $file; /** * @api * @var integer the ID of the image (which is a WP_Post) */ public $id; public $sizes = array(); /** * @api * @var string $caption the string stored in the WordPress database */ public $caption; /** * @var $_wp_attached_file the file as stored in the WordPress database */ protected $_wp_attached_file; /** * Creates a new TimberImage object * @example * ```php * // You can pass it an ID number * $myImage = new TimberImage(552); * * //Or send it a URL to an image * $myImage = new TimberImage('http://google.com/logo.jpg'); * ``` * @param bool|int|string $iid */ public function __construct( $iid ) { $this->init($iid); } /** * @return string the src of the file */ public function __toString() { if ( $src = $this->src() ) { return $src; } return ''; } /** * Get a PHP array with pathinfo() info from the file * @return array */ public function get_pathinfo() { return pathinfo($this->file); } /** * @internal * @param string $dim * @return array|int */ protected function get_dimensions( $dim ) { if ( isset($this->_dimensions) ) { return $this->get_dimensions_loaded($dim); } if ( file_exists($this->file_loc) && filesize($this->file_loc) ) { list($width, $height) = getimagesize($this->file_loc); $this->_dimensions = array(); $this->_dimensions[0] = $width; $this->_dimensions[1] = $height; return $this->get_dimensions_loaded($dim); } } /** * @internal * @param string|null $dim * @return array|int */ protected function get_dimensions_loaded( $dim ) { $dim = strtolower($dim); if ( $dim == 'h' || $dim == 'height' ) { return $this->_dimensions[1]; } return $this->_dimensions[0]; } /** * @return array */ protected function get_post_custom( $iid ) { $pc = get_post_custom($iid); if ( is_bool($pc) ) { return array(); } return $pc; } /** * @internal * @param int $iid the id number of the image in the WP database */ protected function get_image_info( $iid ) { $image_info = $iid; if ( is_numeric($iid) ) { $image_info = wp_get_attachment_metadata($iid); if ( !is_array($image_info) ) { $image_info = array(); } $image_custom = self::get_post_custom($iid); $basic = get_post($iid); if ( $basic ) { if ( isset($basic->post_excerpt) ) { $this->caption = $basic->post_excerpt; } $image_custom = array_merge($image_custom, get_object_vars($basic)); } return array_merge($image_info, $image_custom); } if ( is_array($image_info) && isset($image_info['image']) ) { return $image_info['image']; } if ( is_object($image_info) ) { return get_object_vars($image_info); } return $iid; } /** * @internal * @param string $url for evaluation * @return string with http/https corrected depending on what's appropriate for server */ protected static function _maybe_secure_url( $url ) { if ( is_ssl() && strpos($url, 'https') !== 0 && strpos($url, 'http') === 0 ) { $url = 'https'.substr($url, strlen('http')); } return $url; } public static function wp_upload_dir() { static $wp_upload_dir = false; if ( !$wp_upload_dir ) { $wp_upload_dir = wp_upload_dir(); } return $wp_upload_dir; } /** * @internal * @param int|bool|string $iid */ public function init( $iid = false ) { //Make sure we actually have something to work with if ( !$iid ) { Helper::error_log('Initalized TimberImage without providing first parameter.'); return; } //If passed TimberImage, grab the ID and continue if ( $iid instanceof self ) { $iid = (int) $iid->ID; } //If passed ACF image array if ( is_array($iid) && isset($iid['ID']) ) { $iid = $iid['ID']; } if ( !is_numeric($iid) && is_string($iid) ) { if ( strpos($iid, '//') === 0 || strstr($iid, '://') ) { $this->init_with_url($iid); return; } if ( strstr($iid, ABSPATH) ) { $this->init_with_file_path($iid); return; } $relative = false; $iid_lower = strtolower($iid); foreach ( $this->file_types as $type ) { if ( strstr($iid_lower, $type) ) { $relative = true; break; } }; if ( $relative ) { $this->init_with_relative_path($iid); return; } } else if ( $iid instanceof \WP_Post ) { $ref = new \ReflectionClass($this); $post = $ref->getParentClass()->newInstance($iid->ID); if ( isset($post->_thumbnail_id) && $post->_thumbnail_id ) { return $this->init((int) $post->_thumbnail_id); } return $this->init($iid->ID); } else if ( $iid instanceof Post ) { /** * This will catch TimberPost and any post classes that extend TimberPost, * see http://php.net/manual/en/internals2.opcodes.instanceof.php#109108 * and https://timber.github.io/docs/guides/extending-timber/ */ $iid = (int) $iid->_thumbnail_id; } $image_info = $this->get_image_info($iid); $this->import($image_info); $basedir = self::wp_upload_dir(); $basedir = $basedir['basedir']; if ( isset($this->file) ) { $this->file_loc = $basedir.DIRECTORY_SEPARATOR.$this->file; } else if ( isset($this->_wp_attached_file) ) { $this->file = reset($this->_wp_attached_file); $this->file_loc = $basedir.DIRECTORY_SEPARATOR.$this->file; } if ( isset($image_info['id']) ) { $this->ID = $image_info['id']; } else if ( is_numeric($iid) ) { $this->ID = $iid; } if ( isset($this->ID) ) { $custom = self::get_post_custom($this->ID); foreach ( $custom as $key => $value ) { $this->$key = $value[0]; } $this->id = $this->ID; } else { if ( is_array($iid) || is_object($iid) ) { Helper::error_log('Not able to init in TimberImage with iid='); Helper::error_log($iid); } else { Helper::error_log('Not able to init in TimberImage with iid='.$iid); } } } /** * @internal * @param string $relative_path */ protected function init_with_relative_path( $relative_path ) { $this->abs_url = home_url($relative_path); $file_path = URLHelper::get_full_path($relative_path); $this->file_loc = $file_path; $this->file = $file_path; } /** * @internal * @param string $file_path */ protected function init_with_file_path( $file_path ) { $url = URLHelper::file_system_to_url($file_path); $this->abs_url = $url; $this->file_loc = $file_path; $this->file = $file_path; } /** * @internal * @param string $url */ protected function init_with_url( $url ) { $this->abs_url = $url; if ( URLHelper::is_local($url) ) { $this->file = URLHelper::remove_double_slashes(ABSPATH.URLHelper::get_rel_url($url)); $this->file_loc = URLHelper::remove_double_slashes(ABSPATH.URLHelper::get_rel_url($url)); } } /** * @api * @example * ```twig * <img src="{{ image.src }}" alt="{{ image.alt }}" /> * ``` * ```html * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" alt="W3 Checker told me to add alt text, so I am" /> * ``` * @return string alt text stored in WordPress */ public function alt() { $alt = trim(strip_tags(get_post_meta($this->ID, '_wp_attachment_image_alt', true))); return $alt; } /** * @api * @example * ```twig * {% if post.thumbnail.aspect < 1 %} * {# handle vertical image #} * <img src="{{ post.thumbnail.src|resize(300, 500) }}" alt="A basketball player" /> * {% else %} * <img src="{{ post.thumbnail.src|resize(500) }}" alt="A sumo wrestler" /> * {% endif %} * ``` * @return float */ public function aspect() { $w = intval($this->width()); $h = intval($this->height()); return $w / $h; } /** * @api * @example * ```twig * <img src="{{ image.src }}" height="{{ image.height }}" /> * ``` * ```html * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" height="900" /> * ``` * @return int */ public function height() { return $this->get_dimensions('height'); } /** * Returns the link to an image attachment's Permalink page (NOT the link for the image itself!!) * @api * @example * ```twig * <a href="{{ image.link }}"><img src="{{ image.src }} "/></a> * ``` * ```html * <a href="http://example.org/my-cool-picture"><img src="http://example.org/wp-content/uploads/2015/whatever.jpg"/></a> * ``` */ public function link() { if ( strlen($this->abs_url) ) { return $this->abs_url; } return get_permalink($this->ID); } /** * @api * @return bool|TimberPost */ public function parent() { if ( !$this->post_parent ) { return false; } return new $this->PostClass($this->post_parent); } /** * @api * @example * ```twig * <img src="{{ image.path }}" /> * ``` * ```html * <img src="/wp-content/uploads/2015/08/pic.jpg" /> * ``` * @return string the /relative/path/to/the/file */ public function path() { return URLHelper::get_rel_path($this->src()); } /** * @param string $size a size known to WordPress (like "medium") * @api * @example * ```twig * <h1>{{ post.title }}</h1> * <img src="{{ post.thumbnail.src }}" /> * ``` * ```html * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" /> * ``` * @return bool|string */ public function src( $size = 'full' ) { if ( isset($this->abs_url) ) { return $this->_maybe_secure_url($this->abs_url); } if (!$this->is_image()) { return wp_get_attachment_url($this->ID); } $src = wp_get_attachment_image_src($this->ID, $size); $src = $src[0]; $src = apply_filters('timber/image/src', $src, $this->ID); $src = apply_filters('timber_image_src', $src, $this->ID); return $src; } /** * @param string $size a size known to WordPress (like "medium") * @api * @example * ```twig * <h1>{{ post.title }}</h1> * <img src="{{ post.thumbnail.src }}" srcset="{{ post.thumnbail.srcset }}" /> * ``` * ```html * <img src="http://example.org/wp-content/uploads/2018/10/pic.jpg" srcset="http://example.org/wp-content/uploads/2018/10/pic.jpg 1024w, http://example.org/wp-content/uploads/2018/10/pic-600x338.jpg 600w, http://example.org/wp-content/uploads/2018/10/pic-300x169.jpg 300w" /> * ``` * @return bool|string */ public function srcset( $size = "full" ) { if( $this->is_image() ){ return wp_get_attachment_image_srcset($this->ID, $size); } } /** * @param string $size a size known to WordPress (like "medium") * @api * @example * ```twig * <h1>{{ post.title }}</h1> * <img src="{{ post.thumbnail.src }}" srcset="{{ post.thumnbail.srcset }}" sizes="{{ post.thumbnail.img_sizes }}" /> * ``` * ```html * <img src="http://example.org/wp-content/uploads/2018/10/pic.jpg" srcset="http://example.org/wp-content/uploads/2018/10/pic.jpg 1024w, http://example.org/wp-content/uploads/2018/10/pic-600x338.jpg 600w, http://example.org/wp-content/uploads/2018/10/pic-300x169.jpg 300w sizes="(max-width: 1024px) 100vw, 102" /> * ``` * @return bool|string */ public function img_sizes( $size = "full" ) { if( $this->is_image() ){ return wp_get_attachment_image_sizes($this->ID, $size); } } /** * @internal * @return bool true if media is an image */ protected function is_image() { $src = wp_get_attachment_url($this->ID); $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ); $check = wp_check_filetype(basename($src), null); return in_array($check['ext'], $image_exts); } /** * @api * @example * ```twig * <img src="{{ image.src }}" width="{{ image.width }}" /> * ``` * ```html * <img src="http://example.org/wp-content/uploads/2015/08/pic.jpg" width="1600" /> * ``` * @return int */ public function width() { return $this->get_dimensions('width'); } /** * @deprecated 0.21.9 use TimberImage::src * @codeCoverageIgnore * @internal * @param string $size * @return bool|string */ public function get_src( $size = '' ) { Helper::warn('{{image.get_src}} is deprecated and will be removed in 1.1; use {{image.src}}'); return $this->src($size); } /** * @deprecated since 0.21.9 use src() instead * @codeCoverageIgnore * @return string */ public function url( $size = '' ) { Helper::warn('{{image.url}} is deprecated and will be removed in 1.1; use {{image.src}}'); return $this->src($size); } /** * @deprecated since 0.21.9 use src() instead * @codeCoverageIgnore * @return string */ public function get_url( $size = '' ) { Helper::warn('{{image.get_url}} is deprecated and will be removed in 1.1; use {{image.src}}'); return $this->src($size); } }
{ "content_hash": "a836afbb5cc5598ee6dc15024e381363", "timestamp": "", "source": "github", "line_count": 552, "max_line_length": 314, "avg_line_length": 26.458333333333332, "alnum_prop": 0.5970558028072578, "repo_name": "jarednova/timber", "id": "9d67c49e3d20065aed567ab2bf7c6d56a39e3278", "size": "14605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Image.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "486" }, { "name": "HTML", "bytes": "4159" }, { "name": "PHP", "bytes": "618234" }, { "name": "Shell", "bytes": "7317" } ], "symlink_target": "" }
import { NgModule } from '@angular/core'; import { Module as RouterConfigModule } from './router-config'; import { View as BaseView } from './view'; import { View as SignInView } from './sign-in/view'; @NgModule({ imports: [ RouterConfigModule ], declarations: [ BaseView, SignInView ] }) export class Module { }
{ "content_hash": "d18fc9c1806f6b6c5f9c0c81cffaaa6d", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 63, "avg_line_length": 22.1875, "alnum_prop": 0.6225352112676056, "repo_name": "petervyvey/angular2-origin", "id": "b56f67baa3fa69f437f425433ec4342a892b1b4b", "size": "400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/view/account/module.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "48" }, { "name": "HTML", "bytes": "898" }, { "name": "JavaScript", "bytes": "24693" }, { "name": "TypeScript", "bytes": "4686" } ], "symlink_target": "" }
/// <reference path="game_object_creature.ts" /> /// <reference path="game_object_apple.ts" /> /// <reference path="skin_dragon.ts" /> // The enemy finds apples and eats them, whilst evading the player. // class GameObjectEnemy extends GameObjectCreature implements Consumable { private static readonly enemyColor: number = 0xffaaaa; private static readonly enemyEyeColor: number = 0xaa0000; private static readonly distancePerceive: number = 5.0; private static readonly distanceEvade: number = 0.5; private static readonly matureLenght: number = 14; private static readonly destructionDuration: number = 2.5; // Performing evasive move private isEvasive: boolean; // Closest object we can eat private distanceMin: number; constructor( renderer: Renderer, position: VectorAreal = new VectorAreal(0.0, 0.0, 0.01), speedLinear: number = 0.15, speedTurn: number = 3.0, segments: number = 5, velocity: Vector = new Vector(1.0, 0.0) ) { super( renderer, position, speedLinear, speedTurn, segments, velocity ); this.isEvasive = false; this.distanceMin = GameObjectEnemy.distancePerceive; } protected createNewSkin(): Skin { return new SkinDragon( this.renderer, GameObjectEnemy.enemyColor, GameObjectEnemy.enemyEyeColor ); } // Someone i.e. the player, has consumed an enemy // consume(): number { if( this.tail.isDestructionRequested() ) { return 0; } let consumedValue: number = Math.ceil(this.tail.getCount() / 3.0); this.tail.animateDestruction( GameObjectEnemy.destructionDuration ); return consumedValue; } // Perceive something // perceive( another: any ): void { if( another instanceof GameObjectCreature ) { this.perceiveCreature( another ); } else if( another instanceof GameObjectApple ) { this.perceiveApple( another ); } } // Perceive another creature // perceiveCreature( another: GameObjectCreature ) { let pos: Vector = this.getPosition(); let nearest: Vector = another.getNearestPosition( pos ); let posToPlayer: Vector = Vector.minus( another.getPosition(), pos ); let d: number = posToPlayer.distance(); // Evade the creature if( d <= GameObjectEnemy.distanceEvade ) { let evade: Vector = Vector.scale( posToPlayer, GameObjectEnemy.distanceEvade/d ); this.moveTarget = Vector.minus( pos, evade ); this.isEvasive = true; this.distanceMin = GameObjectEnemy.distancePerceive; } else { this.isEvasive = false; } } // Perceive an apple // perceiveApple( another: GameObjectApple ) { if( this.isEvasive ) { return; } let d = Vector.minus( this.getPosition(), another.getPosition() ).distance(); // Greedily approach the nearest apple if( d < this.distanceMin ) { this.moveTarget = another.getPosition(); this.distanceMin = d; // Eat the apple if it is within reach if( d < this.position.areal + another.getPosition().areal ) { this.eat( another ); this.distanceMin = GameObjectEnemy.distancePerceive; } } } // The glutton eats apples // eat( consumable: Consumable ) { super.eat(consumable); // Spawn a child creature if( this.tail.getCount() + 1 >= GameObjectEnemy.matureLenght ) { let childPosition = this.tail.getLast().getPosition(); let divisionLenght = Math.floor(GameObjectEnemy.matureLenght / 2.0); this.tail.getNext(divisionLenght-1).truncate(); this.skin.append( this.tail, 0 ); this.spawnPending.push( new GameObjectEnemy( this.renderer, childPosition, this.speedLinear, this.speedTurn, divisionLenght-1, Vector.scale(this.velocity, -1.0) )); } } // Get perceive distance // getPreceiveDistance(): number { return GameObjectEnemy.distancePerceive; } // Is object perceiving // isPerceptive() { return true; } }
{ "content_hash": "b87fadf604aa6c77bba667b84b6054c0", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 102, "avg_line_length": 28.916083916083917, "alnum_prop": 0.6425634824667473, "repo_name": "latanas/golden", "id": "272c35658104f9289fad975e5518333e34da2364", "size": "4297", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/game_object_enemy.ts", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "892" }, { "name": "HTML", "bytes": "794" }, { "name": "JavaScript", "bytes": "1803" }, { "name": "Shell", "bytes": "130" }, { "name": "TypeScript", "bytes": "62251" } ], "symlink_target": "" }
class OkpoFormatValidator < ValidatesRussian::Validator validates_using do |okpo| next false unless okpo =~ /^\d+$/ okpo = okpo.split(//).map(&:to_i) next false unless okpo.size == 8 || okpo.size == 10 next false unless calc(okpo) == okpo.last end private def self.calc(okpo) nums = okpo[0..-2] check_digit = weight(nums, 1) % 11 check_digit = weight(nums, 3) % 11 if check_digit == 10 check_digit == 10 ? 0 : check_digit end def self.weight(nums, shift) nums.each_with_index.inject(0) { |a, e| a + e[0] * calc_weight(e[1] + shift) } end def self.calc_weight(num) num == 11 ? 1 : num end end
{ "content_hash": "6a2adbf49b20b2e58b0103eccdaf7580", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 82, "avg_line_length": 24.296296296296298, "alnum_prop": 0.6097560975609756, "repo_name": "asiniy/validates_russian", "id": "69e899f1275f682ec67f93a5b3ebb32c2e5b72c5", "size": "656", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/validators/okpo_format_validator.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "15157" } ], "symlink_target": "" }
package org.openqa.selenium.interactions; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.TestWaiter; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.JavascriptEnabled; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.openqa.selenium.TestWaiter.waitFor; import static org.openqa.selenium.WaitingConditions.elementTextToContain; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.WaitingConditions.elementValueToEqual; import static org.openqa.selenium.WaitingConditions.pageTitleToBe; import static org.openqa.selenium.testing.Ignore.Driver.ALL; import static org.openqa.selenium.testing.Ignore.Driver.ANDROID; import static org.openqa.selenium.testing.Ignore.Driver.CHROME; import static org.openqa.selenium.testing.Ignore.Driver.FIREFOX; import static org.openqa.selenium.testing.Ignore.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Ignore.Driver.IE; import static org.openqa.selenium.testing.Ignore.Driver.IPHONE; import static org.openqa.selenium.testing.Ignore.Driver.OPERA; import static org.openqa.selenium.testing.Ignore.Driver.OPERA_MOBILE; import static org.openqa.selenium.testing.Ignore.Driver.REMOTE; import static org.openqa.selenium.testing.Ignore.Driver.SAFARI; import static org.openqa.selenium.testing.Ignore.Driver.SELENESE; import static org.openqa.selenium.testing.TestUtilities.isFirefox; import static org.openqa.selenium.testing.TestUtilities.isFirefox30; import static org.openqa.selenium.testing.TestUtilities.isFirefox35; import static org.openqa.selenium.testing.TestUtilities.isNativeEventsEnabled; /** * Tests operations that involve mouse and keyboard. */ @Ignore(value = {SAFARI}, reason = "Safari: not implemented (issue 4136)", issues = {4136}) public class BasicMouseInterfaceTest extends JUnit4TestBase { private Actions getBuilder(WebDriver driver) { return new Actions(driver); } private void performDragAndDropWithMouse() { driver.get(pages.draggableLists); WebElement dragReporter = driver.findElement(By.id("dragging_reports")); WebElement toDrag = driver.findElement(By.id("rightitem-3")); WebElement dragInto = driver.findElement(By.id("sortable1")); Action holdItem = getBuilder(driver).clickAndHold(toDrag).build(); Action moveToSpecificItem = getBuilder(driver) .moveToElement(driver.findElement(By.id("leftitem-4"))) .build(); Action moveToOtherList = getBuilder(driver).moveToElement(dragInto).build(); Action drop = getBuilder(driver).release(dragInto).build(); assertEquals("Nothing happened.", dragReporter.getText()); try { holdItem.perform(); moveToSpecificItem.perform(); moveToOtherList.perform(); String text = dragReporter.getText(); assertTrue(text, text.matches("Nothing happened. (?:DragOut *)+")); } finally { drop.perform(); } } @JavascriptEnabled @Ignore({ANDROID, IPHONE, SELENESE}) @Test public void testDraggingElementWithMouseMovesItToAnotherList() { performDragAndDropWithMouse(); WebElement dragInto = driver.findElement(By.id("sortable1")); assertEquals(6, dragInto.findElements(By.tagName("li")).size()); } @JavascriptEnabled @Ignore( value = {HTMLUNIT, ANDROID, IPHONE, SELENESE}, reason = "Advanced mouse actions only implemented in rendered browsers") // This test is very similar to testDraggingElementWithMouse. The only // difference is that this test also verifies the correct events were fired. @Test public void testDraggingElementWithMouseFiresEvents() { performDragAndDropWithMouse(); WebElement dragReporter = driver.findElement(By.id("dragging_reports")); // This is failing under HtmlUnit. A bug was filed. String text = dragReporter.getText(); assertTrue(text, text.matches("Nothing happened. (?:DragOut *)+DropIn RightItem 3")); } private boolean isElementAvailable(WebDriver driver, By locator) { try { driver.findElement(locator); return true; } catch (NoSuchElementException e) { return false; } } @JavascriptEnabled @Ignore({ANDROID, IPHONE, SELENESE}) @Test public void testDoubleClickThenGet() { // Fails in ff3 if WebLoadingListener removes browser listener driver.get(pages.javascriptPage); WebElement toClick = driver.findElement(By.id("clickField")); Action dblClick = getBuilder(driver).doubleClick(toClick).build(); dblClick.perform(); driver.get(pages.droppableItems); } @JavascriptEnabled @Ignore({ANDROID, IPHONE, SELENESE}) @Test public void testDragAndDrop() throws InterruptedException { driver.get(pages.droppableItems); long waitEndTime = System.currentTimeMillis() + 15000; while (!isElementAvailable(driver, By.id("draggable")) && (System.currentTimeMillis() < waitEndTime)) { Thread.sleep(200); } if (!isElementAvailable(driver, By.id("draggable"))) { throw new RuntimeException("Could not find draggable element after 15 seconds."); } WebElement toDrag = driver.findElement(By.id("draggable")); WebElement dropInto = driver.findElement(By.id("droppable")); Action holdDrag = getBuilder(driver).clickAndHold(toDrag).build(); Action move = getBuilder(driver) .moveToElement(dropInto).build(); Action drop = getBuilder(driver).release(dropInto).build(); holdDrag.perform(); move.perform(); drop.perform(); dropInto = driver.findElement(By.id("droppable")); String text = dropInto.findElement(By.tagName("p")).getText(); assertEquals("Dropped!", text); } @JavascriptEnabled @Ignore({ANDROID, IPHONE, OPERA, SELENESE}) @Test public void testDoubleClick() { driver.get(pages.javascriptPage); WebElement toDoubleClick = driver.findElement(By.id("doubleClickField")); Action dblClick = getBuilder(driver).doubleClick(toDoubleClick).build(); dblClick.perform(); String testFieldContent = TestWaiter.waitFor( elementValueToEqual(toDoubleClick, "DoubleClicked"), 5, TimeUnit.SECONDS); assertEquals("Value should change to DoubleClicked.", "DoubleClicked", testFieldContent); } @JavascriptEnabled @Ignore({ANDROID, HTMLUNIT, IPHONE, SELENESE}) @Test public void testContextClick() { driver.get(pages.javascriptPage); WebElement toContextClick = driver.findElement(By.id("doubleClickField")); Action contextClick = getBuilder(driver).contextClick(toContextClick).build(); contextClick.perform(); assertEquals("Value should change to ContextClicked.", "ContextClicked", toContextClick.getAttribute("value")); } @JavascriptEnabled @Ignore({ANDROID, IPHONE, SELENESE}) @Test public void testMoveAndClick() { driver.get(pages.javascriptPage); WebElement toClick = driver.findElement(By.id("clickField")); Action contextClick = getBuilder(driver).moveToElement(toClick).click().build(); contextClick.perform(); waitFor(elementValueToEqual(toClick, "Clicked")); assertEquals("Value should change to Clicked.", "Clicked", toClick.getAttribute("value")); } @JavascriptEnabled @Ignore({ANDROID, CHROME, IE, IPHONE, SELENESE, FIREFOX}) @Test public void testCannotMoveToANullLocator() { driver.get(pages.javascriptPage); try { Action contextClick = getBuilder(driver).moveToElement(null).build(); contextClick.perform(); fail("Shouldn't be allowed to click on null element."); } catch (IllegalArgumentException expected) { // Expected. } } @JavascriptEnabled @Ignore({ANDROID, CHROME, IE, IPHONE, SELENESE, FIREFOX, OPERA, HTMLUNIT, OPERA_MOBILE}) @Test public void testMousePositionIsNotPreservedInActionsChain() { driver.get(pages.javascriptPage); WebElement toMoveTo = driver.findElement(By.id("clickField")); getBuilder(driver).moveToElement(toMoveTo).build().perform(); // TODO(andreastt): Is this correct behaviour? Should the last known mouse position be // disregarded if calling click() from a an Actions chain? try { getBuilder(driver).click().build().perform(); fail("Shouldn't be allowed to click without a context."); } catch (InvalidCoordinatesException expected) { // expected } } @Ignore(value = {ANDROID, IE, HTMLUNIT, IPHONE, REMOTE, SELENESE, FIREFOX, OPERA}, reason = "Behaviour not finalized yet regarding linked images.") @Test public void testMovingIntoAnImageEnclosedInALink() { driver.get(pages.linkedImage); if (isFirefox30(driver) || isFirefox35(driver)) { System.out.println("Not performing testMovingIntoAnImageEnclosedInALink - no way to " + "compensate for accessibility-provided offsets on Firefox 3.0 or 3.5"); return; } // Note: For some reason, the Accessibility API in Firefox will not be available before we // click on something. As a work-around, click on a different element just to get going. driver.findElement(By.id("linkToAnchorOnThisPage")).click(); WebElement linkElement = driver.findElement(By.id("linkWithEnclosedImage")); // Image is 644 x 41 - move towards the end. // Note: The width of the link element itself is correct - 644 pixels. However, // the height is 17 pixels and the rectangle containing it is *below* the image. // For this reason, this action will fail. new Actions(driver).moveToElement(linkElement, 500, 30).click().perform(); waitFor(pageTitleToBe(driver, "We Arrive Here")); } private Map<String, Object> getElementSize(WebElement element) { return (Map<String, Object>) ((JavascriptExecutor) driver).executeScript( "return arguments[0].getBoundingClientRect()", element); } private int getHeight(Map<String, Object> sizeRect) { if (sizeRect.containsKey("height")) { return getFieldValue(sizeRect, "height"); } else { return getFieldValue(sizeRect, "bottom") - getFieldValue(sizeRect, "top"); } } private int getFieldValue(Map<String, Object> sizeRect, String fieldName) { return (int) Double.parseDouble(sizeRect.get(fieldName).toString()); } @Ignore(value = {ANDROID, IE, HTMLUNIT, IPHONE, SELENESE, CHROME}, reason = "Not implemented yet.") @Test public void testMovingMousePastViewPort() { if (!isNativeEventsEnabled(driver)) { System.out.println("Skipping testMovingMousePastViewPort: Native events are disabled."); return; } driver.get(pages.javascriptPage); WebElement keyUpArea = driver.findElement(By.id("keyPressArea")); new Actions(driver).moveToElement(keyUpArea).click().perform(); Map<String, Object> keyUpSize = getElementSize(keyUpArea); // When moving to an element using the interactions API, the element is not scrolled // using scrollElementIntoView so the top of the element may not end at 0. // Estimate the mouse position based on the distance of the element from the top plus // half its size (the mouse is moved to the middle of the element by default). int assumedMouseY = getHeight(keyUpSize) / 2 + getFieldValue(keyUpSize, "top"); // Calculate the scroll offset by figuring out the distance of the 'parent' element from // the top (adding half it's height), then substracting the current mouse position. // Regarding width, the event attached to this element will only be triggered if the mouse // hovers over the text in this element. Use a simple negative offset for this. Map<String, Object> parentSize = getElementSize(driver.findElement(By.id("parent"))); int verticalMove = getFieldValue(parentSize, "top") + getHeight(parentSize) / 2 - assumedMouseY; // Move by verticalMove pixels down and -50 pixels left: // we should be hitting the element with id 'parent' new Actions(driver).moveByOffset(-50, verticalMove).perform(); WebElement resultArea = driver.findElement(By.id("result")); waitFor(elementTextToContain(resultArea, "parent matches")); } @Ignore(value = {ANDROID, IE, HTMLUNIT, IPHONE, SELENESE, CHROME, OPERA, OPERA_MOBILE}, reason = "Not implemented yet.") @Test public void testMovingMouseBackAndForthPastViewPort() { if (isFirefox(driver) && !isNativeEventsEnabled(driver)) { System.out.println("Skipping testMovingMouseBackAndForthPastViewPort: " + "Native events are disabled."); return; } driver.get(pages.veryLargeCanvas); WebElement firstTarget = driver.findElement(By.id("r1")); new Actions(driver).moveToElement(firstTarget).click().perform(); WebElement resultArea = driver.findElement(By.id("result")); String expectedEvents = "First"; waitFor(elementTextToEqual(resultArea, expectedEvents)); // Move to element with id 'r2', at (2500, 50) to (2580, 100) new Actions(driver).moveByOffset(2540 - 150, 75 - 125).click().perform(); expectedEvents += " Second"; waitFor(elementTextToEqual(resultArea, expectedEvents)); // Move to element with id 'r3' at (60, 1500) to (140, 1550) new Actions(driver).moveByOffset(100 - 2540, 1525 - 75).click().perform(); expectedEvents += " Third"; waitFor(elementTextToEqual(resultArea, expectedEvents)); // Move to element with id 'r4' at (220,180) to (320, 230) new Actions(driver).moveByOffset(270 - 100, 205 - 1525).click().perform(); expectedEvents += " Fourth"; waitFor(elementTextToEqual(resultArea, expectedEvents)); } @Ignore(ALL) @Test public void testShouldClickElementInIFrame() { driver.get(pages.clicksPage); try { driver.switchTo().frame("source"); WebElement element = driver.findElement(By.id("otherframe")); new Actions(driver).moveToElement(element).click().perform(); driver.switchTo().defaultContent() .switchTo().frame("target"); waitFor(elementTextToEqual(driver, By.id("span"), "An inline element")); } finally { driver.switchTo().defaultContent(); } } }
{ "content_hash": "3b2fe96dbb976f406d784f98cf3df880", "timestamp": "", "source": "github", "line_count": 393, "max_line_length": 96, "avg_line_length": 37.05089058524173, "alnum_prop": 0.7178078428679349, "repo_name": "winhamwr/selenium", "id": "35c9f27787fcfcf3f9516195d17ecd3dbd0a6203", "size": "15133", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "java/client/test/org/openqa/selenium/interactions/BasicMouseInterfaceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "22777" }, { "name": "C", "bytes": "308726" }, { "name": "C#", "bytes": "2121309" }, { "name": "C++", "bytes": "1430920" }, { "name": "Java", "bytes": "7891557" }, { "name": "JavaScript", "bytes": "14095000" }, { "name": "Objective-C", "bytes": "1255264" }, { "name": "Python", "bytes": "608723" }, { "name": "Ruby", "bytes": "759494" }, { "name": "Shell", "bytes": "8622" } ], "symlink_target": "" }
""" """ import requests from requests.auth import HTTPBasicAuth import argparse import json import logging import os import sys import traceback LOG = logging.getLogger() LOG.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) LOG.addHandler(ch) def main(main_args): """ Read environment variables to envvars_dict Open file with file_path Read contents as template_contents Render template_contents as rendered_file_contents with envvars_dict Send rendered_file_contents to file or stdout """ appdef_contents = read_file_contents(main_args.appdef_file) send_to_marathon(appdef_contents, main_args) def parse_cli_args(): p = argparse.ArgumentParser(description="Deploy To Marathon") p.add_argument("appdef_file", type=str, help="Path to application definition file") p.add_argument("--marathon-uri", dest="marathon_uri", type=str, required=True, help="The Marathon Endpoint") p.add_argument("--marathon-user", dest="marathon_user", type=str, required=False, help="Username for Marathon access") p.add_argument("--marathon-pass", dest="marathon_pass", type=str, required=False, help="Password for Marathon access") return p.parse_known_args() def read_file_contents(file_path): contents = None if os.path.isfile(file_path): with open(file_path, "r") as f: contents = f.read() return contents def send_to_marathon(app_def_contents, cli_args): app_def_obj = json.loads(app_def_contents) request_args = ["{}/v2/apps/{}".format( cli_args.marathon_uri, app_def_obj.get("id"))] request_kwargs = dict(data=json.dumps(app_def_obj)) if cli_args.marathon_user: request_kwargs.update(auth=HTTPBasicAuth(cli_args.marathon_user, cli_args.marathon_pass)) response = requests.put(*request_args, **request_kwargs) LOG.info(response.headers) LOG.info(response.status_code) LOG.info(response.content) if __name__ == "__main__": try: args, args_other = parse_cli_args() main(args) except Exception as main_ex: LOG.error("An error occurred in running the application!") LOG.error(main_ex) LOG.error(traceback.print_tb(sys.exc_info()[2])) finally: sys.exit(0)
{ "content_hash": "403788d858772a1b192f3fb94a1d2ae6", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 97, "avg_line_length": 30.204819277108435, "alnum_prop": 0.6605504587155964, "repo_name": "tendrilinc/marathon-autoscaler", "id": "799ee59e51fe914d417cecd59fe7e5cfa9317d0c", "size": "2529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/deploy_to_marathon.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "547" }, { "name": "Python", "bytes": "85119" }, { "name": "Shell", "bytes": "416" } ], "symlink_target": "" }
module Mongo module Crypt # A Context object initialized specifically for the purpose of creating # a data key in the key management system. # # @api private class DataKeyContext < Context # Create a new DataKeyContext object # # @param [ Mongo::Crypt::Handle ] mongocrypt a Handle that # wraps a mongocrypt_t object used to create a new mongocrypt_ctx_t # @param [ Mongo::Crypt::EncryptionIO ] io An object that performs all # driver I/O on behalf of libmongocrypt # @param [ Mongo::Crypt::KMS::MasterKeyDocument ] master_key_document The master # key document that contains master encryption key parameters. # @param [ Array<String> | nil ] key_alt_names An optional array of strings specifying # alternate names for the new data key. # @param [ String | nil ] :key_material Optional # 96 bytes to use as custom key material for the data key being created. # If :key_material option is given, the custom key material is used # for encrypting and decrypting data. def initialize(mongocrypt, io, master_key_document, key_alt_names, key_material) super(mongocrypt, io) Binding.ctx_setopt_key_encryption_key(self, master_key_document.to_document) set_key_alt_names(key_alt_names) if key_alt_names Binding.ctx_setopt_key_material(self, BSON::Binary.new(key_material)) if key_material initialize_ctx end private # Set the alt names option on the context def set_key_alt_names(key_alt_names) unless key_alt_names.is_a?(Array) raise ArgumentError.new, 'The :key_alt_names option must be an Array' end unless key_alt_names.all? { |key_alt_name| key_alt_name.is_a?(String) } raise ArgumentError.new( "#{key_alt_names} contains an invalid alternate key name. All " + "values of the :key_alt_names option Array must be Strings" ) end Binding.ctx_setopt_key_alt_names(self, key_alt_names) end # Initializes the underlying mongocrypt_ctx_t object def initialize_ctx Binding.ctx_datakey_init(self) end end end end
{ "content_hash": "9b3fa63e5a0d6082aae4c1f4ba96c9bc", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 93, "avg_line_length": 39.82142857142857, "alnum_prop": 0.6542600896860986, "repo_name": "mongodb/mongo-ruby-driver", "id": "f7d0c6e1bf73805f5e1854813e3a6de65509cf6d", "size": "2863", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/mongo/crypt/data_key_context.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "745" }, { "name": "HTML", "bytes": "49593" }, { "name": "Ruby", "bytes": "5008268" }, { "name": "Shell", "bytes": "44951" } ], "symlink_target": "" }
import {AppointmentAbstract} from './AppointmentAbstract' import {AppointmentData} from './AppointmentData' import {SalonCloudResponse} from './../../Core/SalonCloudResponse' export class PhoneCallAppointment extends AppointmentAbstract { protected validation(appointment : AppointmentData) : SalonCloudResponse<string>{ return; } protected normalizationData(appointment: AppointmentData): AppointmentData{ return; } }
{ "content_hash": "3c4f50990db697224d3c8d831aceb82c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 85, "avg_line_length": 26.823529411764707, "alnum_prop": 0.7521929824561403, "repo_name": "salonhelps/salon-cloud", "id": "13f7498db6f8c643ce86df7558238d435b069f4d", "size": "524", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Modules/AppointmentManagement/PhoneCallAppointment.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "421" }, { "name": "JavaScript", "bytes": "1903" }, { "name": "TypeScript", "bytes": "724122" } ], "symlink_target": "" }
angular.module('futurism') .factory('servers', function(ServerResource, _) { 'use strict'; return { getUri: function(serverId, callback) { ServerResource.query({}, function(serverList) { var matches = _.filter(serverList, function(server) { return server.id === serverId; }); if(matches.length === 0) { return callback('server not found'); } return callback(null, matches[0].uri); }); } } });
{ "content_hash": "0aff60ff315aa17ccbce8a6917873701", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 73, "avg_line_length": 27.565217391304348, "alnum_prop": 0.43217665615141954, "repo_name": "Jiggmin/futurism-client", "id": "900a8b81c4f0f0dec81e61e530693b66c51077e6", "size": "634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scripts/services/servers.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "35735" }, { "name": "JavaScript", "bytes": "249577" } ], "symlink_target": "" }
require_dependency "team_blog/admin/application_controller" module TeamBlog class Admin::HomeController < Admin::ApplicationController def index end end end
{ "content_hash": "1aa4f486aa41fba19ac71c96c907cb20", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 60, "avg_line_length": 21.25, "alnum_prop": 0.7764705882352941, "repo_name": "jasl/team_blog", "id": "d161cf28f47f021c7f8858871fcc3fe0d1e1c77f", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/team_blog/admin/home_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1054" }, { "name": "Ruby", "bytes": "56572" } ], "symlink_target": "" }
package org.adligo.tests4j.shared.asserts.common; /** * This interface represents a expected Throwable. * @see {@link ExpectedThrowable} * @author scott * */ public interface I_ExpectedThrowable { /** * * @return * This method returns the expected message that the throwable * should match against {@link #getMatchType()}. */ public abstract String getMessage(); /** * * @return * This method returns the expected class of the throwable * which is expected to be thrown. */ public abstract Class<? extends Throwable> getThrowableClass(); /** * * @return * This method returns the actual instance of the throwable or null. */ public Throwable getInstance(); /** * * @return * This method returns the expected cause of the * Throwable to allow infinite recursive testing of Throwable * causation chain. */ public I_ExpectedThrowable getExpectedCause(); /** * @return * This method returns the type of message matching to use. */ public I_MatchType getMatchType(); }
{ "content_hash": "54f20bc6d2f1409c2d71a659b0c3dade", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 69, "avg_line_length": 21.285714285714285, "alnum_prop": 0.6874400767018217, "repo_name": "adligo/tests4j.adligo.org", "id": "9034efad9855f651ed7a24a757f2ffc0a46802b7", "size": "1043", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/adligo/tests4j/shared/asserts/common/I_ExpectedThrowable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2967320" }, { "name": "Java", "bytes": "1354306" }, { "name": "Kotlin", "bytes": "1263" }, { "name": "Shell", "bytes": "82" } ], "symlink_target": "" }
/** * match.h * * \date Jun 20, 2011 * \author <a href="mailto:dev@celix.apache.org">Apache Celix Project Team</a> * \copyright Apache License, Version 2.0 */ #ifndef MATCH_H_ #define MATCH_H_ #include <service_reference.h> struct match { service_reference_pt reference; int matchValue; }; typedef struct match *match_pt; #endif /* MATCH_H_ */
{ "content_hash": "299afe1ab2790b191de7988d626926a0", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 83, "avg_line_length": 16.863636363636363, "alnum_prop": 0.6522911051212938, "repo_name": "apache/celix", "id": "25b13faf016887367f9d8a881c2fcdbe8660cb75", "size": "1179", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bundles/device_access/device_access/include/match.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2190" }, { "name": "C", "bytes": "4907267" }, { "name": "C++", "bytes": "1718056" }, { "name": "CMake", "bytes": "466066" }, { "name": "HTML", "bytes": "3361" }, { "name": "JavaScript", "bytes": "27661" }, { "name": "Python", "bytes": "12206" }, { "name": "Shell", "bytes": "14359" } ], "symlink_target": "" }
<?php return array ( 'template' => 'default', 'tablePrefix' => '', 'modelPath' => 'application.models', 'baseClass' => 'EMongoDocument', );
{ "content_hash": "dd3fcff9dcaf057cb2bd9d2c24f5de34", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 38, "avg_line_length": 21.142857142857142, "alnum_prop": 0.6013513513513513, "repo_name": "sevenseez/eticaret", "id": "5a0dec378d2fbf4d2fcd4e9cbd33399a5c35652a", "size": "148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "protected/runtime/gii-1.1.15/MongoModelCode.php", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ApacheConf", "bytes": "215" }, { "name": "CSS", "bytes": "104915" }, { "name": "JavaScript", "bytes": "275259" }, { "name": "PHP", "bytes": "365713" }, { "name": "Shell", "bytes": "380" } ], "symlink_target": "" }
extern "C"{ void assert(uint8_t expression); }; #endif //EXOS_ASSERT_H
{ "content_hash": "cc3bf35a92c7abead253ac8279370f49", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 32, "avg_line_length": 12.166666666666666, "alnum_prop": 0.6712328767123288, "repo_name": "gwoplock/ExOS", "id": "a6799ca72291d2688b3d1f0bec70341a74b3d562", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/clib_misc/Assert.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "6525" }, { "name": "C", "bytes": "20497" }, { "name": "C++", "bytes": "88304" }, { "name": "Makefile", "bytes": "3275" } ], "symlink_target": "" }
#include "nbvplanner.h" NBVPlanner::NBVPlanner(RobotSensor* rs, PartialModelBase* pm) { robotWithSensor = rs; partialModel = pm; std_distance = 0.0; std_accu_distance = 0.0; std_mp_time = 0.0; std_v_time =0.0; } void NBVPlanner::setConfigFolder(std::string folder) { configFolder = folder; } void NBVPlanner::setDataFolder(std::string folder) { dataFolder = folder; } bool NBVPlanner::init() { // Read some parameters std::string config_file(configFolder); config_file.append("/"); config_file.append("plannerConfig.ini"); mrpt::utils::CConfigFile parser; ASSERT_FILE_EXISTS_(config_file); parser.setFileName(config_file); plannerDeltaT = parser.read_double("MotionPlanning", "deltaT", 1.0, true); rrtNodes = parser.read_int("MotionPlanning", "NumNodes", 10000, true); std::cout << "---------- NBV Planner -------" << std::endl; std::cout << "Delta T: " << plannerDeltaT << std::endl; std::cout << "Number of Nodes: " << rrtNodes << std::endl; std::cout << "------------------------------" << std::endl; return true; } void NBVPlanner::finishPlanning() { //this->savePartialModel(); } void NBVPlanner::getSolutionControls(std::vector< std::vector< double > >& controls, double& delta_t) { controls = solutionControls; delta_t = plannerDeltaT; } void NBVPlanner::getSolutionPath(std::vector< std::vector< double > >& path) { path = solutionPath; } // double NBVPlanner::accumulatedDistance(list< MSLVector > path, Model* m) // { // double d = 0; // // list< MSLVector >::iterator a = path.begin(); // list< MSLVector >::iterator b = path.begin(); // b++; // while(b != path.end()){ // d += m->Metric(*a, *b); // a = b; // b++; // } // // return d; // } float NBVPlanner::updateWithPoinCloud(std::string pc_file, std::string origin_file) { return partialModel->updateWithScan(pc_file, origin_file); } bool NBVPlanner::savePartialModel(std::string file_name) { partialModel->savePartialModel(file_name); } bool NBVPlanner::savePlannerData() { std::string file_name; vpFileReader reader; /// Guardar datos del RRTNBV file_name.clear(); file_name = configFolder + "/InitialState"; std::vector<double> current_config; robotWithSensor->getCurrentConfiguration(current_config); reader.saveToMSLVector<double>(current_config, file_name); /// Save Obstacle information // Read environment file_name.clear(); file_name = configFolder + "/ObstEnvironment.raw"; vpTriangleList triangles; triangles.readFile(file_name); vpTriangleList tris; partialModel->getOccupiedTriangles(tris); triangles.insert(triangles.end(), tris.begin(), tris.end()); tris.clear(); partialModel->getUnknownTriangles(tris); triangles.insert(triangles.end(), tris.begin(), tris.end()); file_name.clear(); file_name = configFolder + "/Obst"; triangles.saveToMSLTriangle(file_name); file_name.clear(); file_name = dataFolder + "/occupied.raw"; partialModel->saveObjectAsRawT(file_name); file_name.clear(); file_name = dataFolder + "/unknown.raw"; partialModel->saveUnknownVolumeAsRawT(file_name); // TODO //file_name.clear(); //file_name = dataFolder + "/FrontierVertices.dat"; //std::string file_name2; //file_name2 = dataFolder + "/FrontierNormals.dat"; //partialModel->saveFrontierUnknown(file_name, file_name2); return true; }
{ "content_hash": "4f5040eb825bb362eb160f7c522bd3ee", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 101, "avg_line_length": 23.41780821917808, "alnum_prop": 0.6633518572682071, "repo_name": "irvingvasquez/vpl", "id": "8cc3a2861224f4d41b519fed90535392bd59cae6", "size": "5024", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "viewplanning/nbvplanner.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "622680" }, { "name": "CMake", "bytes": "15246" } ], "symlink_target": "" }
// Copyright 2017 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/storage_partition_impl.h" #include <string> #include "base/test/bind.h" #include "build/build_config.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_client.h" #include "content/public/test/browser_test.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/simple_url_loader_test_helper.h" #include "content/public/test/url_loader_interceptor.h" #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_browser_context.h" #include "content/test/io_thread_shared_url_loader_factory_owner.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "net/ssl/client_cert_identity.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/mojom/network_service.mojom.h" #include "services/network/public/mojom/url_loader.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "services/network/test/test_url_loader_client.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace content { namespace { class StoragePartitionImplBrowsertest : public ContentBrowserTest { public: StoragePartitionImplBrowsertest() = default; ~StoragePartitionImplBrowsertest() override = default; GURL GetTestURL() const { // Use '/echoheader' instead of '/echo' to avoid a disk_cache bug. // See https://crbug.com/792255. return embedded_test_server()->GetURL("/echoheader"); } private: }; class ClientCertBrowserClient : public ContentBrowserClient { public: explicit ClientCertBrowserClient( base::OnceClosure select_certificate_callback, base::OnceClosure delete_delegate_callback) : select_certificate_callback_(std::move(select_certificate_callback)), delete_delegate_callback_(std::move(delete_delegate_callback)) {} ClientCertBrowserClient(const ClientCertBrowserClient&) = delete; ClientCertBrowserClient& operator=(const ClientCertBrowserClient&) = delete; ~ClientCertBrowserClient() override = default; // Returns a cancellation callback for the imaginary client certificate // dialog. The callback simulates Android's cancellation callback by deleting // |delegate|. base::OnceClosure SelectClientCertificate( WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<ClientCertificateDelegate> delegate) override { std::move(select_certificate_callback_).Run(); // Unblock the test. return base::BindOnce(&ClientCertBrowserClient::DeleteDelegateOnCancel, base::Unretained(this), std::move(delegate)); } void DeleteDelegateOnCancel( std::unique_ptr<ClientCertificateDelegate> delegate) { std::move(delete_delegate_callback_).Run(); } private: scoped_refptr<base::SequencedTaskRunner> task_runner_; base::OnceClosure select_certificate_callback_; base::OnceClosure delete_delegate_callback_; }; class ClientCertBrowserTest : public ContentBrowserTest { public: ClientCertBrowserTest() : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) { // Configure test server to request client certificates. net::SSLServerConfig ssl_server_config; ssl_server_config.client_cert_type = net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT; https_test_server_.SetSSLConfig( net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN, ssl_server_config); https_test_server_.ServeFilesFromSourceDirectory(GetTestDataFilePath()); } ~ClientCertBrowserTest() override { // This is to avoid having a dangling pointer in `ContentClient`. content::SetBrowserClientForTesting(nullptr); } protected: void SetUpOnMainThread() override { ContentBrowserTest::SetUpOnMainThread(); select_certificate_run_loop_ = std::make_unique<base::RunLoop>(); delete_delegate_run_loop_ = std::make_unique<base::RunLoop>(); client_ = std::make_unique<ClientCertBrowserClient>( select_certificate_run_loop_->QuitClosure(), delete_delegate_run_loop_->QuitClosure()); content::SetBrowserClientForTesting(client_.get()); } net::EmbeddedTestServer https_test_server_; std::unique_ptr<ClientCertBrowserClient> client_; std::unique_ptr<base::RunLoop> select_certificate_run_loop_; std::unique_ptr<base::RunLoop> delete_delegate_run_loop_; }; // Creates a SimpleURLLoader and starts it to download |url|. Blocks until the // load is complete. std::unique_ptr<network::SimpleURLLoader> DownloadUrl( const GURL& url, StoragePartition* partition) { auto request = std::make_unique<network::ResourceRequest>(); request->url = url; std::unique_ptr<network::SimpleURLLoader> url_loader = network::SimpleURLLoader::Create(std::move(request), TRAFFIC_ANNOTATION_FOR_TESTS); SimpleURLLoaderTestHelper url_loader_helper; url_loader->DownloadToString( partition->GetURLLoaderFactoryForBrowserProcess().get(), url_loader_helper.GetCallback(), /*max_body_size=*/1024 * 1024); url_loader_helper.WaitForCallback(); return url_loader; } void CheckSimpleURLLoaderState(network::SimpleURLLoader* url_loader, int net_error, net::HttpStatusCode http_status_code) { EXPECT_EQ(net_error, url_loader->NetError()); if (net_error != net::OK) return; ASSERT_TRUE(url_loader->ResponseInfo()); ASSERT_TRUE(url_loader->ResponseInfo()->headers); EXPECT_EQ(http_status_code, url_loader->ResponseInfo()->headers->response_code()); } } // namespace // Make sure that the NetworkContext returned by a StoragePartition works, both // with the network service enabled and with it disabled, when one is created // that wraps the URLRequestContext created by the BrowserContext. IN_PROC_BROWSER_TEST_F(StoragePartitionImplBrowsertest, NetworkContext) { ASSERT_TRUE(embedded_test_server()->Start()); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->process_id = network::mojom::kBrowserProcessId; params->automatically_assign_isolation_info = true; params->is_corb_enabled = false; mojo::Remote<network::mojom::URLLoaderFactory> loader_factory; shell() ->web_contents() ->GetBrowserContext() ->GetDefaultStoragePartition() ->GetNetworkContext() ->CreateURLLoaderFactory(loader_factory.BindNewPipeAndPassReceiver(), std::move(params)); network::ResourceRequest request; network::TestURLLoaderClient client; request.url = embedded_test_server()->GetURL("/set-header?foo: bar"); request.method = "GET"; mojo::PendingRemote<network::mojom::URLLoader> loader; loader_factory->CreateLoaderAndStart( loader.InitWithNewPipeAndPassReceiver(), 1, network::mojom::kURLLoadOptionNone, request, client.CreateRemote(), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS)); // Just wait until headers are received - if the right headers are received, // no need to read the body. client.RunUntilResponseBodyArrived(); ASSERT_TRUE(client.response_head()->headers); EXPECT_EQ(200, client.response_head()->headers->response_code()); std::string foo_header_value; ASSERT_TRUE(client.response_head()->headers->GetNormalizedHeader( "foo", &foo_header_value)); EXPECT_EQ("bar", foo_header_value); } // Make sure the factory info returned from // |StoragePartition::GetURLLoaderFactoryForBrowserProcessIOThread()| works. IN_PROC_BROWSER_TEST_F(StoragePartitionImplBrowsertest, GetURLLoaderFactoryForBrowserProcessIOThread) { ASSERT_TRUE(embedded_test_server()->Start()); base::ScopedAllowBlockingForTesting allow_blocking; auto pending_shared_url_loader_factory = shell() ->web_contents() ->GetBrowserContext() ->GetDefaultStoragePartition() ->GetURLLoaderFactoryForBrowserProcessIOThread(); auto factory_owner = IOThreadSharedURLLoaderFactoryOwner::Create( std::move(pending_shared_url_loader_factory)); EXPECT_EQ(net::OK, factory_owner->LoadBasicRequestOnIOThread(GetTestURL())); } // Make sure the factory info returned from // |StoragePartition::GetURLLoaderFactoryForBrowserProcessIOThread()| doesn't // crash if it's called after the StoragePartition is deleted. IN_PROC_BROWSER_TEST_F(StoragePartitionImplBrowsertest, BrowserIOPendingFactoryAfterStoragePartitionGone) { ASSERT_TRUE(embedded_test_server()->Start()); base::ScopedAllowBlockingForTesting allow_blocking; std::unique_ptr<ShellBrowserContext> browser_context = std::make_unique<ShellBrowserContext>(true); auto* partition = browser_context->GetDefaultStoragePartition(); auto pending_shared_url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcessIOThread(); browser_context.reset(); auto factory_owner = IOThreadSharedURLLoaderFactoryOwner::Create( std::move(pending_shared_url_loader_factory)); EXPECT_EQ(net::ERR_FAILED, factory_owner->LoadBasicRequestOnIOThread(GetTestURL())); } // Make sure the factory constructed from // |StoragePartition::GetURLLoaderFactoryForBrowserProcessIOThread()| doesn't // crash if it's called after the StoragePartition is deleted. IN_PROC_BROWSER_TEST_F(StoragePartitionImplBrowsertest, BrowserIOFactoryAfterStoragePartitionGone) { ASSERT_TRUE(embedded_test_server()->Start()); base::ScopedAllowBlockingForTesting allow_blocking; std::unique_ptr<ShellBrowserContext> browser_context = std::make_unique<ShellBrowserContext>(true); auto* partition = browser_context->GetDefaultStoragePartition(); auto factory_owner = IOThreadSharedURLLoaderFactoryOwner::Create( partition->GetURLLoaderFactoryForBrowserProcessIOThread()); EXPECT_EQ(net::OK, factory_owner->LoadBasicRequestOnIOThread(GetTestURL())); browser_context.reset(); EXPECT_EQ(net::ERR_FAILED, factory_owner->LoadBasicRequestOnIOThread(GetTestURL())); } // Checks that the network::URLLoaderIntercpetor works as expected with the // SharedURLLoaderFactory returned by StoragePartitionImpl. IN_PROC_BROWSER_TEST_F(StoragePartitionImplBrowsertest, URLLoaderInterceptor) { ASSERT_TRUE(embedded_test_server()->Start()); const GURL kEchoUrl(embedded_test_server()->GetURL("/echo")); base::ScopedAllowBlockingForTesting allow_blocking; std::unique_ptr<ShellBrowserContext> browser_context = std::make_unique<ShellBrowserContext>(true); auto* partition = browser_context->GetDefaultStoragePartition(); // Run a request the first time without the interceptor set, as the // StoragePartitionImpl lazily creates the factory and we want to make sure // it will create a new one once the interceptor is set (and not simply reuse // the cached one). { std::unique_ptr<network::SimpleURLLoader> url_loader = DownloadUrl(kEchoUrl, partition); CheckSimpleURLLoaderState(url_loader.get(), net::OK, net::HTTP_OK); } // Use a URLLoaderInterceptor to simulate an error. { URLLoaderInterceptor interceptor(base::BindLambdaForTesting( [&](URLLoaderInterceptor::RequestParams* params) -> bool { if (params->url_request.url != kEchoUrl) return false; params->client->OnComplete( network::URLLoaderCompletionStatus(net::ERR_NOT_IMPLEMENTED)); return true; })); std::unique_ptr<network::SimpleURLLoader> url_loader = DownloadUrl(kEchoUrl, partition); CheckSimpleURLLoaderState(url_loader.get(), net::ERR_NOT_IMPLEMENTED, net::HTTP_OK); } // Run one more time without the interceptor, we should be back to the // original behavior. { std::unique_ptr<network::SimpleURLLoader> url_loader = DownloadUrl(kEchoUrl, partition); CheckSimpleURLLoaderState(url_loader.get(), net::OK, net::HTTP_OK); } } IN_PROC_BROWSER_TEST_F(ClientCertBrowserTest, InvokeClientCertCancellationCallback) { ASSERT_TRUE(https_test_server_.Start()); // Navigate to "/echo". We expect this to get blocked on the client cert. shell()->LoadURL(https_test_server_.GetURL("/echo")); // Wait for SelectClientCertificate() to be invoked. select_certificate_run_loop_->Run(); // Navigate away to cancel the original request, triggering the cancellation // callback that was returned by SelectClientCertificate. shell()->LoadURL(GURL("about:blank")); // Wait for DeleteDelegateOnCancel() to be invoked. delete_delegate_run_loop_->Run(); } } // namespace content
{ "content_hash": "a289f3f02ce678face171b897154c222", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 80, "avg_line_length": 39.955089820359284, "alnum_prop": 0.7303109778943424, "repo_name": "nwjs/chromium.src", "id": "cf6c562673284ef4d0fe9779e26bbf8fa0666b76", "size": "13345", "binary": false, "copies": "6", "ref": "refs/heads/nw70", "path": "content/browser/storage_partition_impl_browsertest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
namespace Nancy.Session.InProc.InProcSessionsManagement.PeriodicTasks { using System; using Xunit; public class PeriodicTaskFactoryFixture { private readonly PeriodicTaskFactory _periodicTaskFactory; public PeriodicTaskFactoryFixture() { _periodicTaskFactory = new PeriodicTaskFactory(); } [Fact] public void Given_null_action_then_throws() { Assert.Throws<ArgumentNullException>(() => _periodicTaskFactory.Create(null)); } [Fact] public void Given_valid_action_then_returns_new_periodic_task() { Action action = () => Console.WriteLine("ok"); var actual = _periodicTaskFactory.Create(action); Assert.NotNull(actual); Assert.IsAssignableFrom<IPeriodicTask>(actual); } } }
{ "content_hash": "c8e1ce744691175e6faf4435aba90ab9", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 84, "avg_line_length": 29.115384615384617, "alnum_prop": 0.7067371202113606, "repo_name": "DavidLievrouw/Nancy.Session.InProc", "id": "22000a89f21f1c6221d2e3e432080e091f3ccc02", "size": "759", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Nancy.Session.InProc.Tests/InProcSessionsManagement/PeriodicTasks/PeriodicTaskFactoryFixture.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3032" }, { "name": "C#", "bytes": "132631" } ], "symlink_target": "" }
This application makes use of the following third party libraries: ## ZGTooltipView Copyright (c) 2016 Alexandre Guibert <alexandre@evaneos.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Generated by CocoaPods - https://cocoapods.org
{ "content_hash": "71274e9f302fad558d09c0dd0f6411cc", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 77, "avg_line_length": 48.76, "alnum_prop": 0.8047579983593109, "repo_name": "Zigzag968/ZGTooltipView", "id": "9ed9c70d5d18afa2180ad28ed70a910adf110ff0", "size": "1238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/Pods-ZGTooltipView_Example/Pods-ZGTooltipView_Example-acknowledgements.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1054" }, { "name": "Swift", "bytes": "16401" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <com.shaubert.ui.phone.PhoneInputLayout android:id="@+id/phone_input_layout" android:layout_width="260dp" android:layout_height="wrap_content" android:gravity="center_vertical"> <com.shaubert.ui.phone.CountryPickerTextView android:id="@+id/country_textview" android:layout_width="36dp" android:layout_height="36dp" android:background="?android:attr/selectableItemBackground" android:gravity="center" android:textColor="?android:attr/textColorPrimary" android:textSize="24dp"/> <com.shaubert.ui.phone.masked.PhoneInputMaskedEditText android:id="@+id/input_layout_edittext" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:layout_weight="1" app:pi_phoneNumberFormat="international" /> </com.shaubert.ui.phone.PhoneInputLayout> <com.shaubert.ui.phone.PhoneInputLayout android:id="@+id/phone_input_layout2" android:layout_width="260dp" android:layout_height="wrap_content" android:gravity="center_vertical"> <com.shaubert.ui.phone.CountryPickerTextView android:id="@+id/country_textview2" android:layout_width="36dp" android:layout_height="36dp" android:background="?android:attr/selectableItemBackground" android:gravity="center" android:textColor="?android:attr/textColorPrimary" android:textSize="24dp" /> <com.shaubert.ui.phone.PhoneInputEditText android:id="@+id/input_layout_edittext2" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:layout_weight="1" app:pi_phoneNumberFormat="international" app:pi_autoChangeCountry="true" app:pi_displayCountryCode="true" /> </com.shaubert.ui.phone.PhoneInputLayout> <com.shaubert.ui.phone.PhoneInputLayout android:id="@+id/phone_input_layout3" android:layout_width="260dp" android:layout_height="wrap_content" android:gravity="center_vertical" app:pi_customCountries="true"> <com.shaubert.ui.phone.CountryPickerTextView android:id="@+id/country_textview3" android:layout_width="36dp" android:layout_height="36dp" android:background="?android:attr/selectableItemBackground" android:gravity="center" android:textColor="?android:attr/textColorPrimary" android:textSize="24dp" app:pi_customCountries="true" /> <com.shaubert.ui.phone.PhoneInputEditText android:id="@+id/input_layout_edittext3" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginLeft="8dp" android:layout_weight="1" app:pi_autoChangeCountry="true" app:pi_customCountries="true" app:pi_displayCountryCode="true" app:pi_phoneNumberFormat="international" /> </com.shaubert.ui.phone.PhoneInputLayout> <Button android:id="@+id/validate" android:layout_width="260dp" android:layout_height="wrap_content" android:text="Validate" /> <Button android:id="@+id/set_random_phone" android:layout_width="260dp" android:layout_height="wrap_content" android:text="Set Random Phone" /> </LinearLayout> </ScrollView> </LinearLayout>
{ "content_hash": "3c158ef0daf36a18edcdb20b479aa689", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 79, "avg_line_length": 42.1900826446281, "alnum_prop": 0.5457394711067581, "repo_name": "shaubert/phone-input", "id": "8cbda3a4c8e115e59f8a9b33d40ecf9cacd1b1e9", "size": "5105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample/src/main/res/layout/phone_input_layout_sample.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "39" }, { "name": "Java", "bytes": "109955" } ], "symlink_target": "" }
source "tools/functions.sh"; for xx in `getApps`; do python manage.py sqlreset $xx | grep '^DROP' | sed 's/;/ CASCADE;/'; done
{ "content_hash": "216d0c9159a2e193324d6c2971dc4341", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 69, "avg_line_length": 26.4, "alnum_prop": 0.6439393939393939, "repo_name": "abztrakt/labtracker", "id": "17306273820498023868928904ec78056f578f78", "size": "145", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/drop_all.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "79222" }, { "name": "Python", "bytes": "550215" }, { "name": "Shell", "bytes": "4496" } ], "symlink_target": "" }
import logging; log = logging.getLogger(__name__) from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase class EventsEndpointTestCase(BaseAuthenticatedEndpointTestCase): """ General """ def test_event(self): response = self.api.events(self.default_eventid) assert 'event' in response def test_categories(self): response = self.api.events.categories() assert 'categories' in response def test_search(self): response = self.api.events.search(params={'domain': u'songkick.com', 'eventId': u'8183976'}) assert 'events' in response class EventsUserlessEndpointTestCase(BaseUserlessEndpointTestCase): """ General """ def test_categories(self): response = self.api.events.categories() assert 'categories' in response def test_search(self): response = self.api.events.search(params={'domain': u'songkick.com', 'eventId': u'8183976'}) assert 'events' in response
{ "content_hash": "66b6c25ac66d10f120c7ddaac3031c4e", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 100, "avg_line_length": 26.68421052631579, "alnum_prop": 0.6765285996055227, "repo_name": "CzechHackathon2014/juice-my-device", "id": "9ce0affc99ba70de6119b05fecfcdc7a887e7835", "size": "1082", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jmd/foursquare/tests/test_events.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9031" }, { "name": "JavaScript", "bytes": "36697" }, { "name": "Python", "bytes": "342440" } ], "symlink_target": "" }
package android.content.pm; import android.os.Parcel; import android.os.Parcelable; public class VersionedPackage implements Parcelable { protected VersionedPackage() {} public String getPackageName(){ return null; } public String toString(){ return null; } public VersionedPackage(String p0, int p1){} public VersionedPackage(String p0, long p1){} public boolean equals(Object p0){ return false; } public int describeContents(){ return 0; } public int getVersionCode(){ return 0; } public int hashCode(){ return 0; } public long getLongVersionCode(){ return 0; } public static Parcelable.Creator<VersionedPackage> CREATOR = null; public void writeToParcel(Parcel p0, int p1){} }
{ "content_hash": "db46f0420ffda2c719e0274fb5e40d54", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 70, "avg_line_length": 36.5, "alnum_prop": 0.7246575342465753, "repo_name": "github/codeql", "id": "4d4e37f54bc6d1ca07da1484ee929b17a2e512bd", "size": "820", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "java/ql/test/stubs/google-android-9.0.0/android/content/pm/VersionedPackage.java", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "3739" }, { "name": "Batchfile", "bytes": "3534" }, { "name": "C", "bytes": "410440" }, { "name": "C#", "bytes": "21146000" }, { "name": "C++", "bytes": "1352639" }, { "name": "CMake", "bytes": "1809" }, { "name": "CodeQL", "bytes": "32583145" }, { "name": "Dockerfile", "bytes": "496" }, { "name": "EJS", "bytes": "1478" }, { "name": "Emacs Lisp", "bytes": "3445" }, { "name": "Go", "bytes": "697562" }, { "name": "HTML", "bytes": "58008" }, { "name": "Handlebars", "bytes": "1000" }, { "name": "Java", "bytes": "5417683" }, { "name": "JavaScript", "bytes": "2432320" }, { "name": "Kotlin", "bytes": "12163740" }, { "name": "Lua", "bytes": "13113" }, { "name": "Makefile", "bytes": "8631" }, { "name": "Mustache", "bytes": "17025" }, { "name": "Nunjucks", "bytes": "923" }, { "name": "Perl", "bytes": "1941" }, { "name": "PowerShell", "bytes": "1295" }, { "name": "Python", "bytes": "1649035" }, { "name": "RAML", "bytes": "2825" }, { "name": "Ruby", "bytes": "299268" }, { "name": "Rust", "bytes": "234024" }, { "name": "Shell", "bytes": "23973" }, { "name": "Smalltalk", "bytes": "23" }, { "name": "Starlark", "bytes": "27062" }, { "name": "Swift", "bytes": "204309" }, { "name": "Thrift", "bytes": "3020" }, { "name": "TypeScript", "bytes": "219623" }, { "name": "Vim Script", "bytes": "1949" }, { "name": "Vue", "bytes": "2881" } ], "symlink_target": "" }
Factory.define(:admin_defined_role_project, class: AdminDefinedRoleProject) do |_f| end # AdminDefinedRoleProgramme Factory.define(:admin_defined_role_programme, class: AdminDefinedRoleProgramme) do |_f| end # ProjectPosition Factory.define(:project_position) do |f| f.name 'A Role' end #:pal relies on Role.pal_role being able to find an appropriate role in the db. Factory.define(:pal_position, parent: :project_position) do |f| f.name 'A Pal' end
{ "content_hash": "b876d92e6c1c374d49f47a971b72d104", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 87, "avg_line_length": 28.5625, "alnum_prop": 0.7636761487964989, "repo_name": "HITS-SDBV/seek", "id": "a18cbbfcff81b8ad6ad49f46638b040b340c413f", "size": "483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/factories/roles.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "37470" }, { "name": "Dockerfile", "bytes": "1866" }, { "name": "HTML", "bytes": "945737" }, { "name": "JavaScript", "bytes": "237557" }, { "name": "Ruby", "bytes": "3855118" }, { "name": "Shell", "bytes": "5899" } ], "symlink_target": "" }
define([ 'rendr/shared/app', 'app/lib/handlebarsHelpers' ], function(BaseApp, handlebarsHelpers) { /** * Extend the `BaseApp` class, adding any custom methods or overrides. */ return BaseApp.extend({ /** * Client and server. * * `initialize` is called on app initialize, both on the client and server. * On the server, an app is instantiated once for each request, and in the * client, it's instantiated once on page load. * * This is a good place to initialize any code that needs to be available to * app on both client and server. */ initialize: function() { /** * Register our Handlebars helpers. * * `this.templateAdapter` is, by default, the `rendr-handlebars` module. * It has a `registerHelpers` method, which allows us to register helper * modules that can be used on both client & server. */ this.templateAdapter.registerHelpers(handlebarsHelpers); }, /** * Client-side only. * * `start` is called at the bottom of `__layout.hbs`. Calling this kicks off * the router and initializes the application. * * Override this method (remembering to call the superclass' `start` method!) * in order to do things like bind events to the router, as shown below. */ start: function() { // Show a loading indicator when the app is fetching. this.router.on('action:start', function() { this.set({loading: true}); }, this); this.router.on('action:end', function() { this.set({loading: false}); }, this); // Call 'super'. BaseApp.prototype.start.call(this); } }); });
{ "content_hash": "504f9c8e0c02adf1c75c02a76fc8e80f", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 87, "avg_line_length": 31.69811320754717, "alnum_prop": 0.6273809523809524, "repo_name": "rendrjs/rendr-examples", "id": "33572e3c16a6a78b4dd2257d06581b6d2db22862", "size": "1680", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "08_multibundle_requirejs/app/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2332" }, { "name": "HTML", "bytes": "27672" }, { "name": "JavaScript", "bytes": "128527" } ], "symlink_target": "" }
This is a tool to simply invoke shellcheck [`shellcheck`](https://github.com/koalaman/shellcheck) command. Shellcheck is tool used to lint bash scripts. Arguments passed to this builder will be passed to `shellcheck` directly. ## Examples Please check [`examples`](examples/)
{ "content_hash": "0c0ff81078272a2c83967d27dd72cb10", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 73, "avg_line_length": 31, "alnum_prop": 0.7741935483870968, "repo_name": "GoogleCloudPlatform/cloud-builders-community", "id": "a35d8ad37eace82536a026b873c02880466ec9d4", "size": "293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shellcheck/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "18" }, { "name": "Clojure", "bytes": "111" }, { "name": "Dockerfile", "bytes": "38628" }, { "name": "Go", "bytes": "48290" }, { "name": "HCL", "bytes": "5993" }, { "name": "HTML", "bytes": "961" }, { "name": "Java", "bytes": "138" }, { "name": "JavaScript", "bytes": "1563" }, { "name": "Jsonnet", "bytes": "155" }, { "name": "Makefile", "bytes": "26" }, { "name": "Nix", "bytes": "369" }, { "name": "Open Policy Agent", "bytes": "170" }, { "name": "PowerShell", "bytes": "3569" }, { "name": "Puppet", "bytes": "152" }, { "name": "Python", "bytes": "6774" }, { "name": "Ruby", "bytes": "1448" }, { "name": "Scala", "bytes": "2808" }, { "name": "Shell", "bytes": "36980" }, { "name": "Starlark", "bytes": "2079" }, { "name": "TypeScript", "bytes": "3205" } ], "symlink_target": "" }
package modules import ( "fmt" lazlo "github.com/djosephsen/hustlebot/lib" "strings" ) var Help = &lazlo.Module{ Name: `Help`, Usage: `"%BOTNAME% help": prints the usage information of every registered plugin`, Run: helpRun, } func helpRun(b *lazlo.Broker) { cb := b.MessageCallback(`(?i)help`, true) for { pm := <-cb.Chan go getHelp(b, &pm) } } func getHelp(b *lazlo.Broker, pm *lazlo.PatternMatch) { dmChan := b.GetDM(pm.Event.User) reply := `########## Modules In use: ` for _, m := range b.Modules { if strings.Contains(m.Usage, `%HIDDEN%`) { continue } usage := strings.Replace(m.Usage, `%BOTNAME%`, b.Config.Name, -1) reply = fmt.Sprintf("%s\n%s", reply, usage) } b.Say(reply, dmChan) }
{ "content_hash": "2ee97758c68adb907599b75c3e4abada", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 84, "avg_line_length": 21.441176470588236, "alnum_prop": 0.6337448559670782, "repo_name": "evangelistcollective/hustlebot", "id": "6bd1b14c7c7c033e273939f783f77783e83a0bf7", "size": "729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/help.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "60862" }, { "name": "Lua", "bytes": "112" }, { "name": "Makefile", "bytes": "124" }, { "name": "Shell", "bytes": "1248" } ], "symlink_target": "" }
using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public class Demo6_Queue { public static void Init() { Console.WriteLine(""); Console.WriteLine("#### Queue Start ####"); SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.MySql, ConnectionString = Config.ConnectionString, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true, AopEvents = new AopEvents { OnLogExecuting = (sql, p) => { Console.WriteLine(sql); Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); } } }); db.Insertable<Order>(new Order() { Name = "a" }).AddQueue(); db.Insertable<Order>(new Order() { Name = "b" }).AddQueue(); db.SaveQueues(); db.Insertable<Order>(new Order() { Name = "a" }).AddQueue(); db.Insertable<Order>(new Order() { Name = "b" }).AddQueue(); db.Insertable<Order>(new Order() { Name = "c" }).AddQueue(); db.Insertable<Order>(new Order() { Name = "d" }).AddQueue(); var ar = db.SaveQueuesAsync(); ar.Wait(); db.Queryable<Order>().AddQueue(); db.Queryable<Order>().AddQueue(); db.AddQueue("select * from `order` where id=@id", new { id = 10000 }); var result2 = db.SaveQueues<Order, Order, Order>(); Console.WriteLine("#### Queue End ####"); } } }
{ "content_hash": "399f628c3c6cb85a455049d725e66088", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 112, "avg_line_length": 34.75, "alnum_prop": 0.5013835085777532, "repo_name": "sunkaixuan/SqlSugar", "id": "f88cd773c297e3d10bb2668b5bfb1e0330636f49", "size": "1809", "binary": false, "copies": "2", "ref": "refs/heads/SqlSugar5", "path": "Src/Asp.Net/MySqlTest/Demo/Demo6_Queue.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "133" }, { "name": "C#", "bytes": "5086205" }, { "name": "Smalltalk", "bytes": "14" }, { "name": "TSQL", "bytes": "3635" } ], "symlink_target": "" }
package com.microsoft.azure.management.dns.implementation; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.apigeneration.LangDefinition; import com.microsoft.azure.management.dns.NSRecordSet; import com.microsoft.azure.management.dns.NSRecordSets; import com.microsoft.azure.management.dns.RecordType; import rx.Observable; /** * Implementation of NSRecordSets. */ @LangDefinition class NSRecordSetsImpl extends DnsRecordSetsBaseImpl<NSRecordSet, NSRecordSetImpl> implements NSRecordSets { NSRecordSetsImpl(DnsZoneImpl dnsZone) { super(dnsZone, RecordType.NS); } @Override public NSRecordSetImpl getByName(String name) { RecordSetInner inner = this.parent().manager().inner().recordSets().get( this.dnsZone.resourceGroupName(), this.dnsZone.name(), name, this.recordType); return new NSRecordSetImpl(this.dnsZone, inner); } @Override protected PagedList<NSRecordSet> listIntern(String recordSetNameSuffix, Integer pageSize) { return super.wrapList(this.parent().manager().inner().recordSets().listByType( this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType, pageSize, recordSetNameSuffix)); } @Override protected Observable<NSRecordSet> listInternAsync(String recordSetNameSuffix, Integer pageSize) { return wrapPageAsync(this.parent().manager().inner().recordSets().listByTypeAsync( this.dnsZone.resourceGroupName(), this.dnsZone.name(), this.recordType)); } @Override protected NSRecordSetImpl wrapModel(RecordSetInner inner) { if (inner == null) { return null; } return new NSRecordSetImpl(this.dnsZone, inner); } }
{ "content_hash": "55b68559d402a0eb965e0606941ce405", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 101, "avg_line_length": 33.01724137931034, "alnum_prop": 0.6637075718015666, "repo_name": "hovsepm/azure-sdk-for-java", "id": "bdfa0c2f1347793979bf7296af39dd4af9191e42", "size": "2082", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "archive/azure-mgmt-dns/src/main/java/com/microsoft/azure/management/dns/implementation/NSRecordSetsImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6821" }, { "name": "HTML", "bytes": "1250" }, { "name": "Java", "bytes": "103388992" }, { "name": "JavaScript", "bytes": "8139" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Python", "bytes": "3855" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
using System.IO; using System.Web; using System.Web.UI; namespace CommonModules { public class TotalTimeModule : IHttpModule { private static float totalTime = 0; private static int requestCount = 0; private static string timerModuleName = null; public void Init(HttpApplication app) { var timerModule = FindTimerModule(app.Modules); if (timerModule != null) { timerModule.RequestTimed += (src, args) => { totalTime += args.Duration; requestCount++; }; } app.EndRequest += (src, args) => { app.Context.Response.Write(CreateSummary()); }; } private TimerModule FindTimerModule(HttpModuleCollection modules) { TimerModule timerModule = null; if (timerModuleName == null) { foreach (var moduleName in modules.AllKeys) { if (moduleName.Contains("CommonModules.Timer")) { timerModule = modules[moduleName] as TimerModule; if (timerModule != null) { timerModuleName = moduleName; break; } } } } else { timerModule = modules[timerModuleName] as TimerModule; } return timerModule; } private string CreateSummary() { var stringWriter = new StringWriter(); var htmlWriter = new HtmlTextWriter(stringWriter); htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "table table-bordered"); htmlWriter.RenderBeginTag(HtmlTextWriterTag.Table); htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "success"); htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tr); htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td); htmlWriter.Write("Requests"); htmlWriter.RenderEndTag(); htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td); htmlWriter.Write(requestCount); htmlWriter.RenderEndTag(); htmlWriter.RenderEndTag(); htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "success"); htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tr); htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td); htmlWriter.Write("Total Time"); htmlWriter.RenderEndTag(); htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td); htmlWriter.Write("{0:F5} seconds", totalTime); htmlWriter.RenderEndTag(); htmlWriter.RenderEndTag(); htmlWriter.RenderEndTag(); return stringWriter.ToString(); } public void Dispose() { } } }
{ "content_hash": "583945fb84618366297fa21ea2ad09e0", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 91, "avg_line_length": 39.973333333333336, "alnum_prop": 0.5433622414943295, "repo_name": "countzyx/MVC5Training", "id": "485d15c9cdb6e0293d7d043ac8c7f64d00c58dad", "size": "3000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SimpleApp/CommonModules/TotalTimeModule.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "512" }, { "name": "C#", "bytes": "144432" }, { "name": "CSS", "bytes": "382257" }, { "name": "JavaScript", "bytes": "452804" } ], "symlink_target": "" }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using Vstack.Common.Utilities; using Vstack.Externals.Geography; namespace Vstack.Externals.Tests.Geography { [TestClass] public class GeographyCalculatorTests { [TestMethod] public void ChangeInLatitude() { Distance distance = new Distance(10000, DistanceUnit.Miles); double changeInLatitude = GeographyCalculator.ChangeInLatitude(distance); double expectedChangeInLatitude = 144.73142332692495; double percentDifference = MathUtilities.GetPercentDifference(changeInLatitude, expectedChangeInLatitude); Assert.IsTrue(percentDifference < 0.0005); } [TestMethod] public void ChangeInLongitude() { Distance distance = new Distance(10000, DistanceUnit.Miles); double latitude = 45; double changeInLongitude = GeographyCalculator.ChangeInLongitude(latitude, distance); double expectedChangeInLongitude = 204.681141770499; double percentDifference = MathUtilities.GetPercentDifference(changeInLongitude, expectedChangeInLongitude); Assert.IsTrue(percentDifference < 0.0005); } [TestMethod] public void ChangeFromLatitude() { double changeInLatitude = 144.73142332692495; Distance changeInDistance = GeographyCalculator.ChangeFromLatitude(changeInLatitude); Distance expectedChangeInDistance = new Distance(10000, DistanceUnit.Miles); double percentDifference = MathUtilities.GetPercentDifference(expectedChangeInDistance.Meters, changeInDistance.Meters); Assert.IsTrue(percentDifference < 0.0005); } [TestMethod] public void ChangeFromLongitude() { double latitude = 45; double changeInLongitude = 204.681141770499; Distance changeInDistance = GeographyCalculator.ChangeFromLongitude(latitude, changeInLongitude); Distance expectedChangeInDistance = new Distance(10000, DistanceUnit.Miles); double percentDifference = MathUtilities.GetPercentDifference(expectedChangeInDistance.Meters, changeInDistance.Meters); Assert.IsTrue(percentDifference < 0.0005); } [TestMethod] public void CalculateDistance() { ICoordinate sanFransisco = new Coordinate(37.7749, -122.4194); ICoordinate newYork = new Coordinate(40.7128, -74.0059); Distance distance = GeographyCalculator.CalculateDistance(sanFransisco, newYork); Distance expectedDistance = new Distance(2565.8585474755773, DistanceUnit.Miles); double percentDiference = MathUtilities.GetPercentDifference(expectedDistance.Meters, distance.Meters); Assert.IsTrue(percentDiference < 0.0005); } [TestMethod] public void GetAverageCoordinate() { ICoordinate coordinate1 = new Coordinate(0, 0); ICoordinate coordinate2 = new Coordinate(50, 50); ICoordinate coordinate3 = new Coordinate(90, 90); List<ICoordinate> coordinates = new List<ICoordinate>() { coordinate1, coordinate2, coordinate3 }; ICoordinate averageCoordinate = GeographyCalculator.GetAverageCoordinate(coordinates); ICoordinate expectedAverageCoordinate = new Coordinate(36.063497821606482, 19.210266971167851); Assert.IsTrue(CoordinatesAreEqual(averageCoordinate, expectedAverageCoordinate)); } [TestMethod] public void FixLatitude() { double invalidLatitude1 = 8456; double invalidLatitude2 = -976559999; double validLatitude1 = GeographyCalculator.FixLatitude(invalidLatitude1); double validLatitude2 = GeographyCalculator.FixLatitude(invalidLatitude2); Assert.IsTrue(IsValidLatitude(validLatitude1)); Assert.IsTrue(IsValidLatitude(validLatitude2)); } [TestMethod] public void FixLongitude() { double invalidLongitude1 = 8456; double invalidLongitude2 = -976559999; double validLongitude1 = GeographyCalculator.FixLongitude(invalidLongitude1); double validLongitude2 = GeographyCalculator.FixLongitude(invalidLongitude2); Assert.IsTrue(IsValidLongitude(validLongitude1)); Assert.IsTrue(IsValidLongitude(validLongitude2)); } [TestMethod] public void ConvertDegreesToRadians() { double degrees = 180; double radians = GeographyCalculator.ConvertDegreesToRadians(degrees); double expectedRadians = Math.PI; double percentDifference = MathUtilities.GetPercentDifference(radians, expectedRadians); Assert.IsTrue(percentDifference < 0.0005); } [TestMethod] public void ConvertRadiansToDegrees() { double radians = Math.PI; double degrees = GeographyCalculator.ConvertRadiansToDegrees(radians); double expectedDegrees = 180; double percentDifference = MathUtilities.GetPercentDifference(degrees, expectedDegrees); Assert.IsTrue(percentDifference < 0.0005); } private static bool CoordinatesAreEqual(ICoordinate coordinate1, ICoordinate coordinate2) { double totalPercentDifference = 0; totalPercentDifference += MathUtilities.GetPercentDifference(coordinate1.Latitude, coordinate2.Latitude); totalPercentDifference += MathUtilities.GetPercentDifference(coordinate1.Longitude, coordinate2.Longitude); return totalPercentDifference < 0.25; } private static bool IsValidLatitude(double latitude) { return latitude <= GeographyCalculator.MaximumLatitude & latitude >= GeographyCalculator.MinimumLatitude; } private static bool IsValidLongitude(double longitude) { return longitude <= GeographyCalculator.MaximumLongitude & longitude >= GeographyCalculator.MinimumLongitude; } } }
{ "content_hash": "cc2e16984fbccabd81c57119a3db4cc0", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 132, "avg_line_length": 42.02013422818792, "alnum_prop": 0.6796038971410318, "repo_name": "vintage-software/vstack", "id": "986cd82975f8919a8304df3099456d963737b232", "size": "6263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Vstack.Externals.Tests/Geography/GeographyCalculatorTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1038916" }, { "name": "Smalltalk", "bytes": "588" } ], "symlink_target": "" }
<!-- 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <groupId>org.apache.felix</groupId> <artifactId>felix-parent</artifactId> <version>5</version> <relativePath>../pom/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <packaging>bundle</packaging> <name>Apache Felix Resolver</name> <description> Provide OSGi resolver service. </description> <version>2.1.0-SNAPSHOT</version> <artifactId>org.apache.felix.resolver</artifactId> <scm> <connection>scm:git:https://github.com/apache/felix-dev.git</connection> <developerConnection>scm:git:https://github.com/apache/felix-dev.git</developerConnection> <url>https://gitbox.apache.org/repos/asf?p=felix-dev.git</url> <tag>HEAD</tag> </scm> <dependencies> <dependency> <groupId>org.osgi</groupId> <artifactId>osgi.annotation</artifactId> <version>6.0.1</version> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.core</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.felix</groupId> <artifactId>org.apache.felix.utils</artifactId> <version>1.8.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.10.19</version> <scope>test</scope> </dependency> </dependencies> <properties> <felix.java.version>6</felix.java.version> </properties> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.5.4</version> <extensions>true</extensions> <configuration> <instructions> <_sources>true</_sources> <_sourcepath>${project.build.sourceDirectory}</_sourcepath> <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName> <Bundle-Activator> org.apache.felix.resolver.Activator </Bundle-Activator> <Private-Package>org.apache.*</Private-Package> <Export-Package> org.apache.felix.resolver.reason, org.osgi.service.resolver.*;provide:=true </Export-Package> <Import-Package> org.osgi.resource.*;provide:=true, * </Import-Package> </instructions> </configuration> </plugin> <plugin> <groupId>org.apache.rat</groupId> <artifactId>apache-rat-plugin</artifactId> <executions> <execution> <phase>verify</phase> <goals> <goal>check</goal> </goals> </execution> </executions> <configuration> <includes> <include>src/**</include> </includes> <excludes> <exclude>src/**/packageinfo</exclude> <exclude>src/main/appended-resources/**</exclude> <exclude>src/test/resources/resolution.json</exclude> <exclude>src/test/resources/felix-4914.json</exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <failOnError>false</failOnError> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "40678fa898c19939babaa8a32e29a5e4", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 201, "avg_line_length": 35.458015267175576, "alnum_prop": 0.626264800861141, "repo_name": "apache/felix-dev", "id": "76942f67e08897248573f72b88b13ab44a218dd3", "size": "4645", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "resolver/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53237" }, { "name": "Groovy", "bytes": "9231" }, { "name": "HTML", "bytes": "372812" }, { "name": "Java", "bytes": "28836360" }, { "name": "JavaScript", "bytes": "248796" }, { "name": "Scala", "bytes": "40378" }, { "name": "Shell", "bytes": "12628" }, { "name": "XSLT", "bytes": "151258" } ], "symlink_target": "" }
from msrest.serialization import Model class ApplicationHealthPolicy(Model): """Defines a health policy used to evaluate the health of an application or one of its children entities. . :param consider_warning_as_error: Indicates whether warnings are treated with the same severity as errors. Default value: False . :type consider_warning_as_error: bool :param max_percent_unhealthy_deployed_applications: The maximum allowed percentage of unhealthy deployed applications. Allowed values are Byte values from zero to 100. The percentage represents the maximum tolerated percentage of deployed applications that can be unhealthy before the application is considered in error. This is calculated by dividing the number of unhealthy deployed applications over the number of nodes where the application is currently deployed on in the cluster. The computation rounds up to tolerate one failure on small numbers of nodes. Default percentage is zero. . Default value: 0 . :type max_percent_unhealthy_deployed_applications: int :param default_service_type_health_policy: The health policy used by default to evaluate the health of a service type. :type default_service_type_health_policy: ~azure.servicefabric.models.ServiceTypeHealthPolicy :param service_type_health_policy_map: The map with service type health policy per service type name. The map is empty be default. :type service_type_health_policy_map: list[~azure.servicefabric.models.ServiceTypeHealthPolicyMapItem] """ _attribute_map = { 'consider_warning_as_error': {'key': 'ConsiderWarningAsError', 'type': 'bool'}, 'max_percent_unhealthy_deployed_applications': {'key': 'MaxPercentUnhealthyDeployedApplications', 'type': 'int'}, 'default_service_type_health_policy': {'key': 'DefaultServiceTypeHealthPolicy', 'type': 'ServiceTypeHealthPolicy'}, 'service_type_health_policy_map': {'key': 'ServiceTypeHealthPolicyMap', 'type': '[ServiceTypeHealthPolicyMapItem]'}, } def __init__(self, consider_warning_as_error=False, max_percent_unhealthy_deployed_applications=0, default_service_type_health_policy=None, service_type_health_policy_map=None): super(ApplicationHealthPolicy, self).__init__() self.consider_warning_as_error = consider_warning_as_error self.max_percent_unhealthy_deployed_applications = max_percent_unhealthy_deployed_applications self.default_service_type_health_policy = default_service_type_health_policy self.service_type_health_policy_map = service_type_health_policy_map
{ "content_hash": "6bee5ecc7ecfd5fb57cb98d40922b22d", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 181, "avg_line_length": 56.638297872340424, "alnum_prop": 0.7407963936889557, "repo_name": "lmazuel/azure-sdk-for-python", "id": "3f6f7142de675ef9b51c2e75d3536465300c0d87", "size": "3136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-servicefabric/azure/servicefabric/models/application_health_policy.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42572767" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in in Millspaugh & Nuttall, Publications of the Field Museum of Natural History, Botany Series 5(no. 212): 326 (1923) #### Original name Phoma megarrhizae Fairm. ### Remarks null
{ "content_hash": "6d0e29edaa413cc5fe2a12f7c28415f1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 114, "avg_line_length": 18.384615384615383, "alnum_prop": 0.7322175732217573, "repo_name": "mdoering/backbone", "id": "b1704e74e5d6c6270e311700496ebbdb36435634", "size": "287", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phoma/Phoma megarrhizae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
var socket = require( 'socket.io' ); var express = require( 'express' ); var http = require( 'http' ); var app = express(); var server = http.createServer( app ); var io = socket.listen( server ); io.sockets.on( 'connection', function( client ) { console.log( "New client !" ); client.on( 'message', function( data ) { // console.log(data); // console.log('Message sender ' + data.name + ":" + data.message ); // console.log('Message received ', data.receive + ":" + data.message); // console.log('Roomname : ' + data.roomname); // client.broadcast.emit( 'message', { name: data.name, message: data.message } ); console.log('first : ' + data.name + data.receive); client.join(data.name + data.receive); //·ëÀÔÀå client.set('room', data.name + data.receive); console.log('JOIN ROOM LIST'); global.message = data.message; global.name = data.name; //io.sockets.in(data.name + data.receive).emit( 'message', {name: data.name, message: data.message}); io.sockets.emit('receiver_messages', {name: data.name, message: data.message, receiver : data.receive, open_check : data.open_check}); }); client.on('passive_message', function(data){ console.log('passive : '+ data.receive + data.name); client.join(data.receive + data.name); //·ëÀÔÀå io.sockets.in(data.receive + data.name).emit('passive_message', {name: data.name, message: data.message}); }); client.on('join', function(data){ console.log('join!!!! : '+ data.receive + data.name); client.join(data.receive + data.name); //·ëÀÔÀå // io.sockets.broadcast.to(data.receive + data.name).emit('join_response', {name: global.name, message: global.message}); io.sockets.in(data.receive + data.name).emit('join_response', {name: global.name, message: global.message}); }); client.on( 'second_message', function( data ) { console.log('second_message : ' + data.name + data.receive); //console.log(io.sockets.manager.rooms); client.join(data.name + data.receive); //·ëÀÔÀå io.sockets.in(data.name + data.receive).emit( 'second_message', {name: data.name, message: data.message}); }); client.on('new_count_message', function(data) { console.log('dochack : ' + data); io.sockets.emit('note', {current_number: data.message, note_receiver : data.note_receiver, send_date : data.send_date, read_status : data.read_status, message_content : data.message_content}); console.log('success!!!'); io.sockets.emit('new_message', {current_number: data.message, note_receiver : data.note_receiver, send_date : data.send_date, read_status : data.read_status, message_content : data.message_content}); console.log('success00000000000000000000000000000!!'); }); }); server.listen( 3000 );
{ "content_hash": "e9aa01ebe8bfcbf43de81011ee77cbe9", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 201, "avg_line_length": 39.11594202898551, "alnum_prop": 0.6761763616154132, "repo_name": "SangDeukLee/futsal", "id": "d3354ef77187b0839b33c29ecfeb4b7c7774ec0e", "size": "2699", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "public/assets/node_js/nodeServer.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "321" }, { "name": "CSS", "bytes": "181091" }, { "name": "HTML", "bytes": "8823705" }, { "name": "JavaScript", "bytes": "860396" }, { "name": "PHP", "bytes": "2427301" } ], "symlink_target": "" }
def get_coord_box(centre_x, centre_y, distance): """Get the square boundary coordinates for a given centre and distance""" """Todo: return coordinates inside a circle, rather than a square""" return { 'top_left': (centre_x - distance, centre_y + distance), 'top_right': (centre_x + distance, centre_y + distance), 'bottom_left': (centre_x - distance, centre_y - distance), 'bottom_right': (centre_x + distance, centre_y - distance), } UNIT_SCOUT = 1 UNIT_DESTROYER = 2 UNIT_BOMBER = 3 UNIT_CRUISER = 4 UNIT_STARBASE = 5 def fleet_ttb(unit_type, quantity, factories, is_techno=False, is_dict=False, stasis_enabled=False): """ Calculate the time taken to construct a given fleet """ unit_weights = { UNIT_SCOUT: 1, UNIT_DESTROYER: 13, UNIT_BOMBER: 10, UNIT_CRUISER: 85, UNIT_STARBASE: 1, } govt_weight = 80 if is_dict else 100 prod_weight = 85 if is_techno else 100 weighted_qty = unit_weights[unit_type] * quantity ttb = (weighted_qty * govt_weight * prod_weight) * (2 * factories) # TTB is 66% longer with stasis enabled return ttb + (ttb * 0.66) if stasis_enabled else ttb
{ "content_hash": "bddfffbf3e86cae0ed62063a9ef8f08a", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 100, "avg_line_length": 30.35, "alnum_prop": 0.6309719934102141, "repo_name": "Hypex/hyppy", "id": "85acff076ee0472b3f1dfd3a01effaec9abb4bcd", "size": "1214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hyppy/func.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "13668" } ], "symlink_target": "" }
class matcherCtrl{ constructor(getterSvc, $scope, $rootScope){ this.$scope = $scope; this.$rootScope = $rootScope; this.getterSvc = getterSvc; this.basket = []; this.machine = 'restaurant.svg'; this.products = []; this.productsId = []; this.recipe = { name:'milkshake', products:'banane', steps: ['mélanger les bananes'] }; this.recipeAvatar = 'cake.svg'; this.recipesList = []; this.stepsList = []; this.url = { products: 'products', recipes: 'recipes', recipes_match: 'recipes_match', steps: 'steps', } this.$rootScope.$on('recipe-refresh', this.recipeRefresh()); this.productResult(); this.updateRecipe(); } recipeRefresh(event, recipes){ return (event, recipes)=>{ if (recipes !== undefined) { this.recipesList = recipes; this.stepHandler(); } } } updateRecipe(){ this.getterSvc.get(this.url.recipes_match, 'products=' + this.productsId).then( d => { this.recipesList = d.data.results; } ); this.stepHandler(); } stepHandler(){ this.getterSvc.get(this.url.steps).then( d => { this.stepsList = d.data.steps; for (let i = 0; i < this.recipesList.length; i++) { this.recipesList[i].steps = []; for (let j = 0; j < this.stepsList.length; j++) { if (this.stepsList[j].recipe_id === this.recipesList[i].id) { this.recipesList[i].steps.push(this.stepsList[j].description); } } } } ); } move(id, list){ let basket; switch (list) { case 'products': this.products = this.products.filter(product=>{ if (product.id === id) { this.basket.push(product); this.productsId.push(product.id); } return product.id !== id; }); break; case 'basket': this.basket = this.basket.filter(product=>{ if (product.id === id) { this.products.push(product); this.productsId.splice(this.productsId.indexOf(product.id), 1); } return product.id !== id; }); break; default: } this.updateRecipe(); } productResult(){ this.getterSvc.get(this.url.products) .then( d => { this.products = d.data.products; for (var i = 0; i < this.basket.length; i++) { for (var j = 0; j < this.products.length; j++) { if (this.basket[i].id === this.products[j].id) { this.products.splice(j,1); } } } } ) } } matcherCtrl.$inject = ['getterSvc', '$scope', '$rootScope']; export default matcherCtrl;
{ "content_hash": "b9939f3785767633d19f316d762ca8ae", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 90, "avg_line_length": 30.081818181818182, "alnum_prop": 0.4412209126624358, "repo_name": "apoplexe/fridge-meal", "id": "d838829c9443ce38787b2ae5da31c10aa902ada6", "size": "3310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "front_angular/src/matcher/js/controllers/matcherCtrl.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13172" }, { "name": "HTML", "bytes": "6348" }, { "name": "JavaScript", "bytes": "31198" }, { "name": "Python", "bytes": "8766" }, { "name": "Shell", "bytes": "119" } ], "symlink_target": "" }
<!DOCTYPE html> <html ng-app="taskList"> <head lang="en"> <meta charset="UTF-8"> <title>Task List</title> <link rel="stylesheet" href="/css/style.css"> <!-- <link rel="stylesheet" href="/css/mobile.css"> --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-touch.js"></script> <script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script> <script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script> <!-- <script src="angular-touch.js"></script> --> <script src="/js/app.js"></script> </head> <body> <div class='navbar-header'> <a ui-sref='landing'>Current Tasks</a> <a ui-sref='past'>Past Tasks</a> </div> <div ui-view></div> </body> </html>
{ "content_hash": "0db6a7ec915f9db3f843e89ce145acaf", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 110, "avg_line_length": 42.17391304347826, "alnum_prop": 0.6474226804123712, "repo_name": "ksedlmeyer/TaskList", "id": "6424ade8172046ab9ffebc1aa655295d0a75f25e", "size": "970", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/pages/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1605" }, { "name": "HTML", "bytes": "5680" }, { "name": "JavaScript", "bytes": "8853" } ], "symlink_target": "" }
var attr = Ember.attr; module("Ember.HasManyArray - non embedded objects saving"); test("new records should remain after parent is saved", function() { expect(3); var json = { id: 1, title: 'foo', comment_ids: [] }; var Comment = Ember.Model.extend({ id: attr(), text: attr() }); Comment.adapter = Ember.RESTAdapter.create(); Comment.url = '/comments'; var Article = Ember.Model.extend({ id: attr(), title: attr(), comments: Ember.hasMany(Comment, { key: 'comment_ids' }) }); Article.adapter = Ember.RESTAdapter.create(); Article.url = '/articles'; Article.adapter._ajax = function() { return new Ember.RSVP.Promise(function(resolve) { resolve(json); }); }; var article = Article.create({ title: 'bar' }); var comment = Comment.create({ text: 'comment text' }); article.get('comments').addObject(comment); var promise = Ember.run(article, article.save); promise.then(function(record) { start(); ok(record.get('comments.firstObject') === comment, "Comment is the same object"); equal(record.get('comments.length'), 1, "Article should still have one comment after save"); equal(record.get('comments.firstObject.text'), comment.get('text'), 'Comment is the same'); }); stop(); });
{ "content_hash": "0e5d13e4dd6e76cd3f283b8081f0e57c", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 96, "avg_line_length": 25.54901960784314, "alnum_prop": 0.6331542594013815, "repo_name": "hypexr/grunt-version-copy-bower-components", "id": "6591a28b975323a6a256b2e031ed2e0445187b60", "size": "1303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/fixtures/bower_components/ember-model/packages/ember-model/tests/has_many/nonembedded_objects_save_test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "155" }, { "name": "HTML", "bytes": "910" }, { "name": "JavaScript", "bytes": "11260" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Mycosphaerella wichuriana var. wichuriana J. Schröt. ### Remarks null
{ "content_hash": "1f3c45ef411da758b2399f9cd1e5c923", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 52, "avg_line_length": 12.076923076923077, "alnum_prop": 0.7261146496815286, "repo_name": "mdoering/backbone", "id": "8bca34a19fa6073bee55d0f2169d52535581e5a6", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Mycosphaerella/Mycosphaerella wichuriana/Mycosphaerella wichuriana wichuriana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Orchestra\Foundation\Http\Handlers; use Orchestra\Foundation\Support\MenuHandler; use Orchestra\Contracts\Authorization\Authorization; class SettingMenuHandler extends MenuHandler { /** * Menu configuration. * * @var array */ protected $menu = [ 'id' => 'settings', 'position' => '*', 'title' => 'orchestra/foundation::title.settings.list', 'link' => 'orchestra::settings', 'icon' => null, ]; /** * Get the title. * * @param string $value * * @return string */ public function getTitleAttribute($value) { return $this->container['translator']->trans($value); } /** * Check authorization to display the menu. * * @param \Orchestra\Contracts\Authorization\Authorization $acl * * @return bool */ public function authorize(Authorization $acl) { return $acl->canIf('manage-orchestra'); } }
{ "content_hash": "d81cfb616b0221d7dfe4002724780de1", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 69, "avg_line_length": 22.863636363636363, "alnum_prop": 0.5715705765407555, "repo_name": "stevebauman/foundation", "id": "5a792aa56bc8c8ba3149f63621606e33ad0959a4", "size": "1006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Http/Handlers/SettingMenuHandler.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8751" }, { "name": "CoffeeScript", "bytes": "1564" }, { "name": "PHP", "bytes": "445451" } ], "symlink_target": "" }
package com.amazonaws.services.kinesisfirehose.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Describes the HTTP endpoint selected as the destination. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/HttpEndpointDescription" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class HttpEndpointDescription implements Serializable, Cloneable, StructuredPojo { /** * <p> * The URL of the HTTP endpoint selected as the destination. * </p> */ private String url; /** * <p> * The name of the HTTP endpoint selected as the destination. * </p> */ private String name; /** * <p> * The URL of the HTTP endpoint selected as the destination. * </p> * * @param url * The URL of the HTTP endpoint selected as the destination. */ public void setUrl(String url) { this.url = url; } /** * <p> * The URL of the HTTP endpoint selected as the destination. * </p> * * @return The URL of the HTTP endpoint selected as the destination. */ public String getUrl() { return this.url; } /** * <p> * The URL of the HTTP endpoint selected as the destination. * </p> * * @param url * The URL of the HTTP endpoint selected as the destination. * @return Returns a reference to this object so that method calls can be chained together. */ public HttpEndpointDescription withUrl(String url) { setUrl(url); return this; } /** * <p> * The name of the HTTP endpoint selected as the destination. * </p> * * @param name * The name of the HTTP endpoint selected as the destination. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the HTTP endpoint selected as the destination. * </p> * * @return The name of the HTTP endpoint selected as the destination. */ public String getName() { return this.name; } /** * <p> * The name of the HTTP endpoint selected as the destination. * </p> * * @param name * The name of the HTTP endpoint selected as the destination. * @return Returns a reference to this object so that method calls can be chained together. */ public HttpEndpointDescription withName(String name) { setName(name); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getUrl() != null) sb.append("Url: ").append("***Sensitive Data Redacted***").append(","); if (getName() != null) sb.append("Name: ").append(getName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof HttpEndpointDescription == false) return false; HttpEndpointDescription other = (HttpEndpointDescription) obj; if (other.getUrl() == null ^ this.getUrl() == null) return false; if (other.getUrl() != null && other.getUrl().equals(this.getUrl()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getUrl() == null) ? 0 : getUrl().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); return hashCode; } @Override public HttpEndpointDescription clone() { try { return (HttpEndpointDescription) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kinesisfirehose.model.transform.HttpEndpointDescriptionMarshaller.getInstance().marshall(this, protocolMarshaller); } }
{ "content_hash": "8544ea53a0c9d69bd2a806de5927e943", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 146, "avg_line_length": 28.45505617977528, "alnum_prop": 0.5964461994076999, "repo_name": "aws/aws-sdk-java", "id": "5e218f1395fa52ada8f19f6622150462781a5ff4", "size": "5645", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/HttpEndpointDescription.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing.Design; namespace Igneel.Design.UITypeEditors { public class UIActionEditor:UITypeEditor { Action action; public Action Action { get { return action; } set { action = value; } } public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value) { if (action != null) { //if (context.PropertyDescriptor.Attributes.Contains(LockOnSetAttribute.Yes)) //{ // Engine.Lock(action); //} //else action(); } return value; } } }
{ "content_hash": "292af9e66a42217e897fbdf257b4b84a", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 135, "avg_line_length": 27.885714285714286, "alnum_prop": 0.5942622950819673, "repo_name": "ansel86castro/Igneel", "id": "94f22fca4a42180bdb711a0eb84f664f17532a46", "size": "978", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Engine/__Igneel/Design/UITypeEditors/UIActionEditor.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2447393" }, { "name": "C#", "bytes": "3648197" }, { "name": "C++", "bytes": "2006279" }, { "name": "GAP", "bytes": "40914" }, { "name": "HLSL", "bytes": "383999" }, { "name": "Makefile", "bytes": "477" }, { "name": "Objective-C", "bytes": "311" }, { "name": "PLpgSQL", "bytes": "19049" }, { "name": "Perl", "bytes": "22989" }, { "name": "PowerShell", "bytes": "98800" }, { "name": "Shell", "bytes": "4387" } ], "symlink_target": "" }
package org.elasticsearch.xpack.ml.rest.dataframe; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.RestToXContentListener; import org.elasticsearch.xpack.core.ml.action.DeleteDataFrameAnalyticsAction; import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsConfig; import java.io.IOException; import java.util.List; import static org.elasticsearch.rest.RestRequest.Method.DELETE; import static org.elasticsearch.xpack.ml.MachineLearning.BASE_PATH; public class RestDeleteDataFrameAnalyticsAction extends BaseRestHandler { @Override public List<Route> routes() { return List.of(new Route(DELETE, BASE_PATH + "data_frame/analytics/{" + DataFrameAnalyticsConfig.ID + "}")); } @Override public String getName() { return "xpack_ml_delete_data_frame_analytics_action"; } @Override protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { String id = restRequest.param(DataFrameAnalyticsConfig.ID.getPreferredName()); DeleteDataFrameAnalyticsAction.Request request = new DeleteDataFrameAnalyticsAction.Request(id); request.setForce(restRequest.paramAsBoolean(DeleteDataFrameAnalyticsAction.Request.FORCE.getPreferredName(), request.isForce())); request.timeout(restRequest.paramAsTime(DeleteDataFrameAnalyticsAction.Request.TIMEOUT.getPreferredName(), request.timeout())); return channel -> client.execute(DeleteDataFrameAnalyticsAction.INSTANCE, request, new RestToXContentListener<>(channel)); } }
{ "content_hash": "9a8b6a2f09732ae752d8254717abf47f", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 137, "avg_line_length": 45.54054054054054, "alnum_prop": 0.7905044510385757, "repo_name": "GlenRSmith/elasticsearch", "id": "4ac68777051cc39bb97bb6d5d4df4bac28f4251f", "size": "1937", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/dataframe/RestDeleteDataFrameAnalyticsAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "11057" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "337461" }, { "name": "HTML", "bytes": "2186" }, { "name": "Java", "bytes": "43224931" }, { "name": "Perl", "bytes": "11756" }, { "name": "Python", "bytes": "19852" }, { "name": "Shell", "bytes": "99571" } ], "symlink_target": "" }
--- title: Hero Image module: 11 --- # The Hero Image One of the current trends in web development, that has been ongoing for a number of years now, is the "Hero Image". A hero image is effective for the reason that, "a picture is worth a thousand words". A hero image takes a large image, of high quality, that is as wide as the browser, and often as tall, and places minimal text over it (usually just a header and maybe navigation). This serves to add "depth" to a site, and visually direct the view as to what the site might be about. To get a better idea about the diversity and possibility of the hero image, check out the following articles, which present and discuss sites utilizing hero images; - ["The Power Of Hero Image Design: 35 Striking Case Studies" by Mary Stribley](https://designschool.canva.com/blog/hero-images/) - ["Exploring the Hero Image Trend in Web Design" by Jake Rocheleau](https://envato.com/blog/exploring-hero-image-trend-web-design/) - ["Using background and hero images on websites" by Brenda Stokes Barron](https://envato.com/blog/use-background-hero-images-websites/) ## Details The hero image utilizes the `background-image:` property. Set an elements background using this property. Then set this element to take up the full width of a screen. Then depending on your image, specify if the hero image should always be a certain size, or whether its height should instead stay in relation to the width of the screen. Finally, lay your other text-based (heading, sub-heading, short description, and/or navigation) over the image. This can be done using `position: absolute;` or by including these elements as children to the containing hero image element. Notice in the following example, that the basic operation of including the hero image occurs in the `.hero` class. Also notice how this example was made responsive with the use of media queries that adjust text size and element sizing based on browser width. <div id="code-heading">HTML</div> ```html <div class="hero"> <div class="title"> <h1>Chateua Musića</h1> <h2>Fine Al Fresco Dining</h2> <h2>On the private porch</h2> <div class="nav"> <a href="#"><div class="nav-item">Hours</div></a> <a href="#"><div class="nav-item">About</div></a> <a href="#"><div class="nav-item">Location</div></a> <a href="#"><div class="nav-item">Menus</div></a> </div> </div> </div> ``` <div id="code-ruler"></div> <div id="code-heading">CSS</div> ```css body { padding: 0; margin: 0; } .hero { /* the 'vh' unit asks the browser to */ /* return the height of the viewport */ /* we can then use that to set the height of an element */ height: 100vh; background-image: url("imgs/hero-image-2.jpg"); /*background-image: url("imgs/hero-image.jpg");*/ background-position: center; background-repeat: no-repeat; background-size: cover; } .hero .title { font-size: 22pt; color: #fff; float: right; margin-top: 170px; margin-left: 1em; margin-right: 1em; padding: 2em; text-align: center; background-color: rgba(120, 120, 120, 0.3); } .title h1 { font-family: 'Princess Sofia', cursive; font-size: 2.5em; letter-spacing: 0.2em; } .title h2 { font-family: 'Josefin Sans', sans-serif; font-weight: 300; font-style: italic; line-height: 0.5em; } .hero .nav { font-family: 'Josefin Sans', sans-serif; font-style: italic; font-weight: 300; color: #fff; margin-top: 2em; font-size: 1.5em; display: flex; flex-direction: row; } .hero .nav a { flex-grow: 1; color: #fff; text-decoration: none; } .hero .nav-item { font-size: 0.5em; padding: 0.5em 1em; margin: 0 0.5em; text-align: center; border: 1px solid #d9d9d9; border-width: 1px 0; } .hero .nav-item:hover { color: #fff; background-color: rgba(207, 200, 222, 0.5); } @media (max-width: 865px) { .hero .title { font-size: 18pt; } } @media (max-width: 585px) { .hero .title { font-size: 14pt; margin: 0; margin-top: 50px; } } @media (max-width: 445px) { .hero .title { font-size: 12pt; } } ``` <div class="displayed_code_example"> <div class="embed-responsive" style="padding-bottom:800px"><iframe class="embed-responsive-item" src="https://montana-media-arts.github.io/341-work/lectureCode/11/hero-image-01/" frameborder="0" allowfullscreen></iframe></div> </div> | [**[Code Download]**](https://github.com/Montana-Media-Arts/341-work/raw/master/lectureCode/11/hero-image-01/hero-image-01.zip) | [**[View on GitHub]**](https://github.com/Montana-Media-Arts/341-work/raw/master/lectureCode/11/hero-image-01/) | [**[Live Example]**](https://montana-media-arts.github.io/341-work/lectureCode/11/hero-image-01/) | ## More Details For more resources on implementing this technique please read; - ["How TO - Hero Image" by w3schools](https://www.w3schools.com/howto/howto_css_hero_image.asp) - ["Perfect Full Page Background Image" by Chris Coyier](https://css-tricks.com/perfect-full-page-background-image/) - [Basic "Full Height hero image" Code Pen](https://codepen.io/pooley182/pen/vEYPaR) - Also, when creating hero images, you will need to utilize your graphic design skills to consider color palettes, image contrast, text legibility, etc. A good hero image requires an artistic touch. I would suggest you mock-up your hero image in a program such as Illustrator first. Determine if you need to do any processing to the image to assist in its readability. Export the image from this program (not the text overlays). Use this image for your site, and use CSS to position the textual overlays.
{ "content_hash": "20964ca37c20de434386d62231c88f40", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 345, "avg_line_length": 34.73053892215569, "alnum_prop": 0.6829310344827586, "repo_name": "Montana-Media-Arts/mart341-webDev", "id": "b10036f10176df89d56d01874f34fd6a5722cb16", "size": "5801", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "modules/week-11/_posts/2017-01-05-hero-section.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "48579" }, { "name": "HTML", "bytes": "12698" }, { "name": "Ruby", "bytes": "5854" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <title> 标签: JSON Web Token </title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta name="author" content="John Doe"> <meta name="description"> <meta property="og:type" content="website"> <meta property="og:title" content="标签: JSON Web Token"> <meta property="og:url" content="http://hechunhi.github.io/tags/JSON-Web-Token/index.html"> <meta property="og:site_name" content="落尘惜"> <meta property="og:description"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="标签: JSON Web Token"> <meta name="twitter:description"> <link rel="icon" type="image/x-icon" href="/favicon.png"> <link rel="stylesheet" href="/css/uno.css"> <link rel="stylesheet" href="/css/highlight.css"> <link rel="stylesheet" href="/css/archive.css"> <link rel="stylesheet" href="/css/china-social-icon.css"> </head> <body> <span class="mobile btn-mobile-menu"> <i class="icon icon-list btn-mobile-menu__icon"></i> <i class="icon icon-x-circle btn-mobile-close__icon hidden"></i> </span> <header class="panel-cover panel-cover--collapsed"> <div class="panel-main"> <div class="panel-main__inner panel-inverted"> <div class="panel-main__content"> <h1 class="panel-cover__title panel-title"><a href="/" title="link to homepage">落尘惜</a></h1> <hr class="panel-cover__divider" /> <p class="panel-cover__description"> 零落成泥碾作尘,唯有香如故。 </p> <hr class="panel-cover__divider panel-cover__divider--secondary" /> <div class="navigation-wrapper"> <nav class="cover-navigation cover-navigation--primary"> <ul class="navigation"> <li class="navigation__item"><a href="/#blog" title="" class="blog-button">首页</a></li> <li class="navigation__item"><a href="/archive" title="" class="">分类</a></li> </ul> </nav> <!-- ---------------------------- To add a new social icon simply duplicate one of the list items from below and change the class in the <i> tag to match the desired social network and then add your link to the <a>. Here is a full list of social network classes that you can use: icon-social-500px icon-social-behance icon-social-delicious icon-social-designer-news icon-social-deviant-art icon-social-digg icon-social-dribbble icon-social-facebook icon-social-flickr icon-social-forrst icon-social-foursquare icon-social-github icon-social-google-plus icon-social-hi5 icon-social-instagram icon-social-lastfm icon-social-linkedin icon-social-medium icon-social-myspace icon-social-path icon-social-pinterest icon-social-rdio icon-social-reddit icon-social-skype icon-social-spotify icon-social-stack-overflow icon-social-steam icon-social-stumbleupon icon-social-treehouse icon-social-tumblr icon-social-twitter icon-social-vimeo icon-social-xbox icon-social-yelp icon-social-youtube icon-social-zerply icon-mail --------------------------------> <!-- add social info here --> </div> </div> </div> <div class="panel-cover--overlay"></div> </div> </header> <div class="content-wrapper"> <div class="content-wrapper__inner entry"> <h1 class="archive-title">标签: JSON Web Token</h1> <hr class="post-list__divider" /> <div class="main-post-list"> <ol class="post-list"> <li> <h2 class="post-list__post-title post-title"> <a href="/2016/05/02/JWT的使用/" title="link to JSON Web Token的使用">JSON Web Token的使用</a> </h2> <div class="post-list__meta"> <time datetime="2016-05-02" class="post-list__meta--date date">2016-05-02</time> </div> <div class="excerpt"> </div> <hr class="post-list__divider" /> </li> </ol> <hr class="post-list__divider " /> <nav class="pagination" role="navigation"> <span class="pagination__page-number"> 1 / 1</span> </nav> </div> <footer class="footer"> </footer> </div> </div> <!-- js files --> <script src="/js/jquery.min.js"></script> <script src="/js/main.js"></script> <script src="/js/scale.fix.js"></script> <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript"> $(document).ready(function(){ MathJax.Hub.Config({ tex2jax: {inlineMath: [['[latex]','[/latex]'], ['\\(','\\)']]} }); }); </script> <!--kill ie6 --> <!--[if IE 6]> <script src="//letskillie6.googlecode.com/svn/trunk/2/zh_CN.js"></script> <![endif]--> </body> </html>
{ "content_hash": "0b57de2ab41ac5945510d3b64f1c5b9d", "timestamp": "", "source": "github", "line_count": 224, "max_line_length": 123, "avg_line_length": 23.294642857142858, "alnum_prop": 0.5801073208125719, "repo_name": "hechunhi/hechunhi.github.com", "id": "fb4eeeda96a2043b0194244019f5665c2c0d6724", "size": "5300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tags/JSON-Web-Token/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59922" }, { "name": "HTML", "bytes": "98597" }, { "name": "JavaScript", "bytes": "1589" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>NaiveBroadphase - cannon</title> <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css"> <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css"> <link rel="stylesheet" href="../assets/css/main.css" id="site_styles"> <link rel="icon" href="../assets/favicon.ico"> <script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script> </head> <body class="yui3-skin-sam"> <div id="doc"> <div id="hd" class="yui3-g header"> <div class="yui3-u-3-4"> <h1><img src="../assets/css/logo.png" title="cannon" width="117" height="52"></h1> </div> <div class="yui3-u-1-4 version"> <em>API Docs for: 0.6.1</em> </div> </div> <div id="bd" class="yui3-g"> <div class="yui3-u-1-4"> <div id="docs-sidebar" class="sidebar apidocs"> <div id="api-list"> <h2 class="off-left">APIs</h2> <div id="api-tabview" class="tabview"> <ul class="tabs"> <li><a href="#api-classes">Classes</a></li> <li><a href="#api-modules">Modules</a></li> </ul> <div id="api-tabview-filter"> <input type="search" id="api-filter" placeholder="Type to filter APIs"> </div> <div id="api-tabview-panel"> <ul id="api-classes" class="apis classes"> <li><a href="../classes/AABB.html">AABB</a></li> <li><a href="../classes/ArrayCollisionMatrix.html">ArrayCollisionMatrix</a></li> <li><a href="../classes/Body.html">Body</a></li> <li><a href="../classes/Box.html">Box</a></li> <li><a href="../classes/Broadphase.html">Broadphase</a></li> <li><a href="../classes/ConeEquation.html">ConeEquation</a></li> <li><a href="../classes/ConeTwistConstraint.html">ConeTwistConstraint</a></li> <li><a href="../classes/Constraint.html">Constraint</a></li> <li><a href="../classes/ContactEquation.html">ContactEquation</a></li> <li><a href="../classes/ContactMaterial.html">ContactMaterial</a></li> <li><a href="../classes/ConvexPolyhedron.html">ConvexPolyhedron</a></li> <li><a href="../classes/Cylinder.html">Cylinder</a></li> <li><a href="../classes/Demo.html">Demo</a></li> <li><a href="../classes/DistanceConstraint.html">DistanceConstraint</a></li> <li><a href="../classes/Equation.html">Equation</a></li> <li><a href="../classes/EventTarget.html">EventTarget</a></li> <li><a href="../classes/FrictionEquation.html">FrictionEquation</a></li> <li><a href="../classes/GridBroadphase.html">GridBroadphase</a></li> <li><a href="../classes/GSSolver.html">GSSolver</a></li> <li><a href="../classes/Heightfield.html">Heightfield</a></li> <li><a href="../classes/HingeConstraint.html">HingeConstraint</a></li> <li><a href="../classes/JacobianElement.html">JacobianElement</a></li> <li><a href="../classes/LockConstraint.html">LockConstraint</a></li> <li><a href="../classes/Mat3.html">Mat3</a></li> <li><a href="../classes/Material.html">Material</a></li> <li><a href="../classes/NaiveBroadphase.html">NaiveBroadphase</a></li> <li><a href="../classes/Narrowphase.html">Narrowphase</a></li> <li><a href="../classes/ObjectCollisionMatrix.html">ObjectCollisionMatrix</a></li> <li><a href="../classes/Octree.html">Octree</a></li> <li><a href="../classes/OctreeNode.html">OctreeNode</a></li> <li><a href="../classes/Particle.html">Particle</a></li> <li><a href="../classes/Plane.html">Plane</a></li> <li><a href="../classes/PointToPointConstraint.html">PointToPointConstraint</a></li> <li><a href="../classes/Pool.html">Pool</a></li> <li><a href="../classes/Quaternion.html">Quaternion</a></li> <li><a href="../classes/Ray.html">Ray</a></li> <li><a href="../classes/RaycastResult.html">RaycastResult</a></li> <li><a href="../classes/RaycastVehicle.html">RaycastVehicle</a></li> <li><a href="../classes/RigidVehicle.html">RigidVehicle</a></li> <li><a href="../classes/RotationalEquation.html">RotationalEquation</a></li> <li><a href="../classes/RotationalMotorEquation.html">RotationalMotorEquation</a></li> <li><a href="../classes/SAPBroadphase.html">SAPBroadphase</a></li> <li><a href="../classes/Shape.html">Shape</a></li> <li><a href="../classes/Solver.html">Solver</a></li> <li><a href="../classes/Sphere.html">Sphere</a></li> <li><a href="../classes/SPHSystem.html">SPHSystem</a></li> <li><a href="../classes/SplitSolver.html">SplitSolver</a></li> <li><a href="../classes/Spring.html">Spring</a></li> <li><a href="../classes/Transform.html">Transform</a></li> <li><a href="../classes/Trimesh.html">Trimesh</a></li> <li><a href="../classes/TupleDictionary.html">TupleDictionary</a></li> <li><a href="../classes/Vec3.html">Vec3</a></li> <li><a href="../classes/Vec3Pool.html">Vec3Pool</a></li> <li><a href="../classes/WheelInfo.html">WheelInfo</a></li> <li><a href="../classes/World.html">World</a></li> </ul> <ul id="api-modules" class="apis modules"> </ul> </div> </div> </div> </div> </div> <div class="yui3-u-3-4"> <div id="api-options"> Show: <label for="api-show-inherited"> <input type="checkbox" id="api-show-inherited" checked> Inherited </label> <label for="api-show-protected"> <input type="checkbox" id="api-show-protected"> Protected </label> <label for="api-show-private"> <input type="checkbox" id="api-show-private"> Private </label> <label for="api-show-deprecated"> <input type="checkbox" id="api-show-deprecated"> Deprecated </label> </div> <div class="apidocs"> <div id="docs-main"> <div class="content"> <h1>NaiveBroadphase Class</h1> <div class="box meta"> <div class="extends"> Extends <a href="../classes/Broadphase.html" class="crosslink">Broadphase</a> </div> <div class="foundat"> Defined in: <a href="../files/src_collision_NaiveBroadphase.js.html#l6"><code>src&#x2F;collision&#x2F;NaiveBroadphase.js:6</code></a> </div> </div> <div class="box intro"> <p>Naive broadphase implementation, used in lack of better ones.</p> </div> <div class="constructor"> <h2>Constructor</h2> <div id="method_NaiveBroadphase" class="method item"> <h3 class="name"><code>NaiveBroadphase</code></h3> <span class="paren">()</span> <div class="meta"> <p> Defined in <a href="../files/src_collision_NaiveBroadphase.js.html#l6"><code>src&#x2F;collision&#x2F;NaiveBroadphase.js:6</code></a> </p> </div> <div class="description"> </div> </div> </div> <div id="classdocs" class="tabview"> <ul class="api-class-tabs"> <li class="api-class-tab index"><a href="#index">Index</a></li> <li class="api-class-tab methods"><a href="#methods">Methods</a></li> <li class="api-class-tab properties"><a href="#properties">Properties</a></li> </ul> <div> <div id="index" class="api-class-tabpanel index"> <h2 class="off-left">Item Index</h2> <div class="index-section methods"> <h3>Methods</h3> <ul class="index-list methods extends"> <li class="index-item method inherited"> <a href="#method_aabbQuery">aabbQuery</a> </li> <li class="index-item method inherited"> <a href="#method_boundingSphereCheck">boundingSphereCheck</a> </li> <li class="index-item method inherited"> <a href="#method_collisionPairs">collisionPairs</a> </li> <li class="index-item method inherited"> <a href="#method_doBoundingBoxBroadphase">doBoundingBoxBroadphase</a> </li> <li class="index-item method inherited"> <a href="#method_doBoundingSphereBroadphase">doBoundingSphereBroadphase</a> </li> <li class="index-item method inherited"> <a href="#method_intersectionTest">intersectionTest</a> </li> <li class="index-item method inherited"> <a href="#method_makePairsUnique">makePairsUnique</a> </li> <li class="index-item method inherited"> <a href="#method_needBroadphaseCollision">needBroadphaseCollision</a> </li> <li class="index-item method inherited"> <a href="#method_setWorld">setWorld</a> </li> </ul> </div> <div class="index-section properties"> <h3>Properties</h3> <ul class="index-list properties extends"> <li class="index-item property inherited"> <a href="#property_dirty">dirty</a> </li> <li class="index-item property inherited"> <a href="#property_useBoundingBoxes">useBoundingBoxes</a> </li> <li class="index-item property inherited"> <a href="#property_world">world</a> </li> </ul> </div> </div> <div id="methods" class="api-class-tabpanel"> <h2 class="off-left">Methods</h2> <div id="method_aabbQuery" class="method item"> <h3 class="name"><code>aabbQuery</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>world</code> </li> <li class="arg"> <code>aabb</code> </li> <li class="arg"> <code>result</code> </li> </ul><span class="paren">)</span> </div> <span class="returns-inline"> <span class="type">Array</span> </span> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_aabbQuery"> Broadphase </a> but overwritten in <a href="../files/src_collision_NaiveBroadphase.js.html#l49"><code>src&#x2F;collision&#x2F;NaiveBroadphase.js:49</code></a> </p> </div> <div class="description"> <p>Returns all the bodies within an AABB.</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">world</code> <span class="type"><a href="../classes/World.html" class="crosslink">World</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">aabb</code> <span class="type"><a href="../classes/AABB.html" class="crosslink">AABB</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">result</code> <span class="type">Array</span> <div class="param-description"> <p>An array to store resulting bodies in.</p> </div> </li> </ul> </div> <div class="returns"> <h4>Returns:</h4> <div class="returns-description"> <span class="type">Array</span>: </div> </div> </div> <div id="method_boundingSphereCheck" class="method item inherited"> <h3 class="name"><code>boundingSphereCheck</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>bodyA</code> </li> <li class="arg"> <code>bodyB</code> </li> </ul><span class="paren">)</span> </div> <span class="returns-inline"> <span class="type">Boolean</span> </span> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_boundingSphereCheck">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l183"><code>src&#x2F;collision&#x2F;Broadphase.js:183</code></a> </p> </div> <div class="description"> <p>Check if the bounding spheres of two bodies overlap.</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">bodyA</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">bodyB</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> </ul> </div> <div class="returns"> <h4>Returns:</h4> <div class="returns-description"> <span class="type">Boolean</span>: </div> </div> </div> <div id="method_collisionPairs" class="method item"> <h3 class="name"><code>collisionPairs</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>world</code> </li> <li class="arg"> <code>pairs1</code> </li> <li class="arg"> <code>pairs2</code> </li> </ul><span class="paren">)</span> </div> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_collisionPairs"> Broadphase </a> but overwritten in <a href="../files/src_collision_NaiveBroadphase.js.html#l19"><code>src&#x2F;collision&#x2F;NaiveBroadphase.js:19</code></a> </p> </div> <div class="description"> <p>Get all the collision pairs in the physics world</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">world</code> <span class="type"><a href="../classes/World.html" class="crosslink">World</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs1</code> <span class="type">Array</span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs2</code> <span class="type">Array</span> <div class="param-description"> </div> </li> </ul> </div> </div> <div id="method_doBoundingBoxBroadphase" class="method item inherited"> <h3 class="name"><code>doBoundingBoxBroadphase</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>bodyA</code> </li> <li class="arg"> <code>bodyB</code> </li> <li class="arg"> <code>pairs1</code> </li> <li class="arg"> <code>pairs2</code> </li> </ul><span class="paren">)</span> </div> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_doBoundingBoxBroadphase">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l112"><code>src&#x2F;collision&#x2F;Broadphase.js:112</code></a> </p> </div> <div class="description"> <p>Check if the bounding boxes of two bodies are intersecting.</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">bodyA</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">bodyB</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs1</code> <span class="type">Array</span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs2</code> <span class="type">Array</span> <div class="param-description"> </div> </li> </ul> </div> </div> <div id="method_doBoundingSphereBroadphase" class="method item inherited"> <h3 class="name"><code>doBoundingSphereBroadphase</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>bodyA</code> </li> <li class="arg"> <code>bodyB</code> </li> <li class="arg"> <code>pairs1</code> </li> <li class="arg"> <code>pairs2</code> </li> </ul><span class="paren">)</span> </div> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_doBoundingSphereBroadphase">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l89"><code>src&#x2F;collision&#x2F;Broadphase.js:89</code></a> </p> </div> <div class="description"> <p>Check if the bounding spheres of two bodies are intersecting.</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">bodyA</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">bodyB</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs1</code> <span class="type">Array</span> <div class="param-description"> <p>bodyA is appended to this array if intersection</p> </div> </li> <li class="param"> <code class="param-name">pairs2</code> <span class="type">Array</span> <div class="param-description"> <p>bodyB is appended to this array if intersection</p> </div> </li> </ul> </div> </div> <div id="method_intersectionTest" class="method item inherited"> <h3 class="name"><code>intersectionTest</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>bodyA</code> </li> <li class="arg"> <code>bodyB</code> </li> <li class="arg"> <code>pairs1</code> </li> <li class="arg"> <code>pairs2</code> </li> </ul><span class="paren">)</span> </div> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_intersectionTest">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l73"><code>src&#x2F;collision&#x2F;Broadphase.js:73</code></a> </p> </div> <div class="description"> <p>Check if the bounding volumes of two bodies intersect.</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">bodyA</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">bodyB</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs1</code> <span class="type">Array</span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs2</code> <span class="type">Array</span> <div class="param-description"> </div> </li> </ul> </div> </div> <div id="method_makePairsUnique" class="method item inherited"> <h3 class="name"><code>makePairsUnique</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>pairs1</code> </li> <li class="arg"> <code>pairs2</code> </li> </ul><span class="paren">)</span> </div> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_makePairsUnique">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l135"><code>src&#x2F;collision&#x2F;Broadphase.js:135</code></a> </p> </div> <div class="description"> <p>Removes duplicate pairs from the pair arrays.</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">pairs1</code> <span class="type">Array</span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">pairs2</code> <span class="type">Array</span> <div class="param-description"> </div> </li> </ul> </div> </div> <div id="method_needBroadphaseCollision" class="method item inherited"> <h3 class="name"><code>needBroadphaseCollision</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>bodyA</code> </li> <li class="arg"> <code>bodyB</code> </li> </ul><span class="paren">)</span> </div> <span class="returns-inline"> <span class="type">Bool</span> </span> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_needBroadphaseCollision">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l48"><code>src&#x2F;collision&#x2F;Broadphase.js:48</code></a> </p> </div> <div class="description"> <p>Check if a body pair needs to be intersection tested at all.</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">bodyA</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> <li class="param"> <code class="param-name">bodyB</code> <span class="type"><a href="../classes/Body.html" class="crosslink">Body</a></span> <div class="param-description"> </div> </li> </ul> </div> <div class="returns"> <h4>Returns:</h4> <div class="returns-description"> <span class="type">Bool</span>: </div> </div> </div> <div id="method_setWorld" class="method item inherited"> <h3 class="name"><code>setWorld</code></h3> <div class="args"> <span class="paren">(</span><ul class="args-list inline commas"> <li class="arg"> <code>world</code> </li> </ul><span class="paren">)</span> </div> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#method_setWorld">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l175"><code>src&#x2F;collision&#x2F;Broadphase.js:175</code></a> </p> </div> <div class="description"> <p>To be implemented by subcasses</p> </div> <div class="params"> <h4>Parameters:</h4> <ul class="params-list"> <li class="param"> <code class="param-name">world</code> <span class="type"><a href="../classes/World.html" class="crosslink">World</a></span> <div class="param-description"> </div> </li> </ul> </div> </div> </div> <div id="properties" class="api-class-tabpanel"> <h2 class="off-left">Properties</h2> <div id="property_dirty" class="property item inherited"> <h3 class="name"><code>dirty</code></h3> <span class="type">Boolean</span> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#property_dirty">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l30"><code>src&#x2F;collision&#x2F;Broadphase.js:30</code></a> </p> </div> <div class="description"> <p>Set to true if the objects in the world moved.</p> </div> </div> <div id="property_useBoundingBoxes" class="property item inherited"> <h3 class="name"><code>useBoundingBoxes</code></h3> <span class="type">Boolean</span> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#property_useBoundingBoxes">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l23"><code>src&#x2F;collision&#x2F;Broadphase.js:23</code></a> </p> </div> <div class="description"> <p>If set to true, the broadphase uses bounding boxes for intersection test, else it uses bounding spheres.</p> </div> </div> <div id="property_world" class="property item inherited"> <h3 class="name"><code>world</code></h3> <span class="type"><a href="../classes/World.html" class="crosslink">World</a></span> <div class="meta"> <p>Inherited from <a href="../classes/Broadphase.html#property_world">Broadphase</a>: <a href="../files/src_collision_Broadphase.js.html#l16"><code>src&#x2F;collision&#x2F;Broadphase.js:16</code></a> </p> </div> <div class="description"> <p>The world to search for collisions in.</p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <script src="../assets/vendor/prettify/prettify-min.js"></script> <script>prettyPrint();</script> <script src="../assets/js/yui-prettify.js"></script> <script src="../assets/../api.js"></script> <script src="../assets/js/api-filter.js"></script> <script src="../assets/js/api-list.js"></script> <script src="../assets/js/api-search.js"></script> <script src="../assets/js/apidocs.js"></script> </body> </html>
{ "content_hash": "b897ec840989f14a645d11f6cddabcca", "timestamp": "", "source": "github", "line_count": 1090, "max_line_length": 145, "avg_line_length": 32.81100917431193, "alnum_prop": 0.420562576892965, "repo_name": "mcanthony/cannon.js", "id": "248cf81fd89eef9babb4d08d12de22ada45bc1ef", "size": "35764", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "docs/classes/NaiveBroadphase.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "93" }, { "name": "HTML", "bytes": "156875" }, { "name": "JavaScript", "bytes": "1936020" } ], "symlink_target": "" }
namespace _16.Comparing_floats { using System; public class ComparingFloats { //// Write a program that safely compares floating-point numbers(double) //// with precision eps = 0.000001. Note that we cannot directly compare //// two floating-point numbers "a" and "b" by "a==b" because of the nature //// of the floating-point arithmetic.Therefore, we assume two numbers are equal //// if they are more closely to each other than some fixed constant eps. //// Example: Input: 5.3, 6.1 -> Output: False Explanation: The difference of 0.71 is too big (> eps) public static void Main() { double numberA = double.Parse(Console.ReadLine()); double numberB = double.Parse(Console.ReadLine()); double epsPercision = 0.000001; double differenceNumAnumB = Math.Abs(numberA - numberB); if (differenceNumAnumB <= epsPercision) { Console.WriteLine("True"); } else { Console.WriteLine("False"); } } } }
{ "content_hash": "e3d313eaedbc9afbef38f2509a1168a9", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 110, "avg_line_length": 34.61764705882353, "alnum_prop": 0.5556499575191164, "repo_name": "Menkachev/Software-University", "id": "fac326fbb7866ff39b1d3bfa18a5bb21eb128fd1", "size": "1179", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Programming Fundamentals - January 2017/01. Data Types and Variables/02. Data Types and Variables - Exercises, January 19, 2017/16. Comparing floats/ComparingFloats.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "498662" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>breakcipher: File Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">breakcipher </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('globals.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented file members with links to the documentation:</div><ul> <li>main() : <a class="el" href="main_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4">main.cpp</a> </li> <li>operator&lt;&lt;() : <a class="el" href="vigenere__square_8cpp.html#a0ad7f7c243abc9fd02ba9086c7f73504">vigenere_square.cpp</a> , <a class="el" href="vigenere__square_8hpp.html#a0ad7f7c243abc9fd02ba9086c7f73504">vigenere_square.hpp</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Wed Apr 19 2017 21:45:02 for breakcipher by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
{ "content_hash": "08efacdb5daef566b4ea9e4ea5e924b4", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 121, "avg_line_length": 37.21568627450981, "alnum_prop": 0.6809799789251844, "repo_name": "tuokri/breakcipher", "id": "25be96f42f47ce201bb40f68142b79a65aa47283", "size": "3796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/globals.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "394158" } ], "symlink_target": "" }
/* IMPORTANT! This file is auto-generated each time you save your project - if you alter its contents, your changes may be overwritten! There's a section below where you can add your own custom code safely, and the Introjucer will preserve the contents of that block, but the best way to change any of these definitions is by using the Introjucer's project settings. Any commented-out settings will assume their default values. */ #ifndef __JUCE_APPCONFIG_TTAKTK1S__ #define __JUCE_APPCONFIG_TTAKTK1S__ //============================================================================== // [BEGIN_USER_CODE_SECTION] // (You can add your own code in this section, and the Introjucer will not overwrite it) // [END_USER_CODE_SECTION] //============================================================================== #define JUCE_MODULE_AVAILABLE_juce_core 1 #define JUCE_MODULE_AVAILABLE_juce_data_structures 1 #define JUCE_MODULE_AVAILABLE_juce_events 1 #define JUCE_MODULE_AVAILABLE_juce_graphics 1 #define JUCE_MODULE_AVAILABLE_juce_gui_basics 1 #define JUCE_MODULE_AVAILABLE_juce_gui_extra 1 //============================================================================== // juce_core flags: #ifndef JUCE_FORCE_DEBUG //#define JUCE_FORCE_DEBUG #endif #ifndef JUCE_LOG_ASSERTIONS //#define JUCE_LOG_ASSERTIONS #endif #ifndef JUCE_CHECK_MEMORY_LEAKS //#define JUCE_CHECK_MEMORY_LEAKS #endif #ifndef JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES //#define JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES #endif #ifndef JUCE_INCLUDE_ZLIB_CODE //#define JUCE_INCLUDE_ZLIB_CODE #endif //============================================================================== // juce_graphics flags: #ifndef JUCE_USE_COREIMAGE_LOADER //#define JUCE_USE_COREIMAGE_LOADER #endif #ifndef JUCE_USE_DIRECTWRITE //#define JUCE_USE_DIRECTWRITE #endif //============================================================================== // juce_gui_basics flags: #ifndef JUCE_ENABLE_REPAINT_DEBUGGING //#define JUCE_ENABLE_REPAINT_DEBUGGING #endif #ifndef JUCE_USE_XSHM //#define JUCE_USE_XSHM #endif #ifndef JUCE_USE_XRENDER //#define JUCE_USE_XRENDER #endif #ifndef JUCE_USE_XCURSOR //#define JUCE_USE_XCURSOR #endif //============================================================================== // juce_gui_extra flags: #ifndef JUCE_WEB_BROWSER //#define JUCE_WEB_BROWSER #endif #ifndef JUCE_ENABLE_LIVE_CONSTANT_EDITOR //#define JUCE_ENABLE_LIVE_CONSTANT_EDITOR #endif #endif // __JUCE_APPCONFIG_TTAKTK1S__
{ "content_hash": "d0321cdc0b6876e7da785c8260e5fd58", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 88, "avg_line_length": 27.20618556701031, "alnum_prop": 0.5839333080712391, "repo_name": "Xaetrz/AddSyn", "id": "84a7ae500e42ccfb629e51b7479215a11374cb98", "size": "2639", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JUCE/examples/HelloWorld/JuceLibraryCode/AppConfig.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5791370" }, { "name": "C++", "bytes": "15922598" }, { "name": "GLSL", "bytes": "507" }, { "name": "HTML", "bytes": "44518" }, { "name": "Java", "bytes": "49234" }, { "name": "Makefile", "bytes": "65606" }, { "name": "Objective-C", "bytes": "59268" }, { "name": "Objective-C++", "bytes": "563166" }, { "name": "R", "bytes": "2856" }, { "name": "Rebol", "bytes": "330" } ], "symlink_target": "" }
* Change theme name from Roots to Sage * Add namespace * Switch from Grunt to gulp, new workflow * Use wiredep for Sass and Less injection * Implement JSON file based asset pipeline * Re-organize asset file structure * Remove theme activation, move to [wp-cli-theme-activation](https://github.com/roots/wp-cli-theme-activation) * Add Travis CI * Update to jQuery 1.11.2 * Update sidebar to fix default template check ### 7.0.3: December 18th, 2014 * Use `get_the_archive_title` * Remove `wp_title`, add title-tag theme support * Remove `Roots_Nav_Walker` as default for all menus * Update to Bootstrap 3.3.1 * Add some base comment styling * Make search tearm `required` in search form ### 7.0.2: October 24th, 2014 * Simplify comments, use core comment form and list * Remove HTML5 shiv from Modernizr build * Move JavaScript to footer * Update hEntry schema to use `updated` instead of `published` * Move variables into `main.less` * Add `roots_body_class` function that checks for page slug in `body_class` * Move `wp_footer` from footer template into `base.php` ### 7.0.1: August 15th, 2014 * Move `<main>` and `.sidebar` markup out of PHP and into LESS * Define `WP_ENV` if it is not already defined * Only load Google Analytics in production environment ### 7.0.0: July 3rd, 2014 * Updated Grunt workflow * Use grunt-modernizr to make a lean Modernizr build * Use Bower for front-end package management * Update to Bootstrap 3.2.0 * Update to Modernizr 2.8.2 * Update to jQuery 1.11.1 * Move clean up, relative URLs, and nice search to [Soil](https://github.com/roots/soil) * Update LESS organization * Move [community translations](https://github.com/roots/roots-translations) to separate repository ### 6.5.2: February 4th, 2014 * Update to Bootstrap 3.1.0 * Move DOM routing into an anonymous function to support jQuery noConflict * Update to jQuery 1.11.0 * Add notice to theme activation, tidy activation table markup * Remove changing media folder from theme activation (use [Bedrock](https://github.com/roots/bedrock) for clean URLs out of the box) * Switch `div.main` to `main` element now that Modernizr uses the latest HTML5 Shiv * Update to Modernizr 2.7.0 * Don't run JSHint on plugins (`assets/js/plugins/`) * Disable warnings about undefined variables (JSHint) * Merge in updates from HTML5 Boilerplate * Add JS source map (disabled by default) * Replace `grunt-recess` with `grunt-contrib-less`, add LESS source map support ### 6.5.1: November 5th, 2013 * Move clean URLs to a [plugin](https://github.com/roots/roots-rewrites) * Update to Bootstrap 3.0.1 ### 6.5.0: August 23rd, 2013 * Reference new site, [http://roots.io/](http://roots.io/) * Remove bundled docs, reference [http://roots.io/docs/](http://roots.io/docs/) * Use Bootstrap variables for media queries * Update to Bootstrap 3.0.0 * Update to jQuery 1.10.2 * Change media directory from `/assets/` to `/media/` * Update to Google Universal Analytics * Show author display name for author archives * Add Serbian translation * Remove post tags from templates * Remove TinyMCE valid elements tweaks (no longer necessary) * Remove additional widget classes * Move `/assets/css/less/` to `/assets/less/` * Add wrapper templates filter * Fix relative external URLs issue ### 6.4.0: May 1st, 2013 * Fix Theme Activation page issues * Fix issues with root relative URLs and rewrites on non-standard setups * Make sure rewrites are added to `.htaccess` immediately after activation * Move HTML5 Boilerplate's `.htaccess` to a [plugin](https://github.com/roots/wp-h5bp-htaccess) * Rename `page-custom.php` to `template-custom.php` * Don't warn about unwritable htaccess if that option is disabled * Add missing collapse class for top navbar * Add comment template * Update is_dropdown evaluation in nav walker * Re-organize archives template * Add missing comment ID * hNews consistency with entry-title class * Add `wp_title()` filter * Fix missing closing div in comments * Fix for navbar dropdowns * Add option for using jQuery on Google CDN * Correct logic in `roots_enable_root_relative_urls` * Add Greek translation, update Brazilian Portuguese translation * Update to Bootstrap 2.3.1 * Simplify alerts * Remove disabled post nav links * Use Bootstrap media object for listing comments * Move Google Analytics to `lib/scripts.php` * Static top navbar instead of fixed ### 6.3.0: February 8th, 2013 * Update to Bootstrap 2.3.0 * Update to jQuery 1.9.1 * Output author title with `get_the_author()` * Add EditorConfig * Update 404 template based on H5BP * Update H5BP's included .htaccess * Don't show comments on passworded posts * Add `do_action('get_header')` for WooSidebars compatibility * Simplify entry meta * Allow `get_search_form()` to be called more than once per request * Move plugins.js and main.js to footer * JavaScript clean up (everything is now enqueued) * Remove conditional feed * Introduce `add_theme_support('bootstrap-gallery')` * Rewrites organization (introduce `lib/rewrites.php`) * Fix `add_editor_style` path * Updated translations: French, Bulgarian, Turkish, Korean * Enable `add_theme_support` for Nice Search * Replace ID's with classes * Add support for dynamic sidebar templates * Fix PHP notice on search with no results * Update to jQuery 1.9.0 ### 6.2.0: January 13th, 2013 * Implement latest Nice Search * Update [gallery] shortcode * Add Simplified Chinese, Indonesian, Korean translations * Move template title to `lib/utils.php` * Update to Bootstrap 2.2.2 * Update to jQuery 1.8.3 * Use `entry-summary` class for excerpts per Readability's Article Publishing Guidelines * Cleanup/refactor `lib/activation.php` * Remove `lib/post-types.php` and `lib/metaboxes.php` * Make sure Primary Navigation menu always gets created and has the location set upon activation, update activation permalink method * Update to Bootstrap 2.2.1 * Update conditional feed method * Update to Bootstrap 2.2.0 * Return instead of echo class names in `roots_main_class` and `roots_sidebar_class` * Move nav customizations into `lib/nav.php` ### 6.1.0: October 2nd, 2012 * Change roots_sidebar into a more explicit configuration array * Re-organize configuration/setup files * Update to jQuery 1.8.2 * Refactor/simplify Roots vCard Widget * Move custom entry_meta code into template * Move Google Analytics code into footer template * Add CONTRIBUTING.md to assist with the new GitHub UI * Add nav walker support for CSS dividers and nav-header ### 6.0.0: September 16th, 2012 * Simplify nav walker and support 3rd level dropdowns * Update to Bootstrap 2.1.1, jQuery 1.8.1, Modernizr 2.6.2 * Add bundled docs * Update all templates to use [PHP Alternative Syntax](http://php.net/manual/en/control-structures.alternative-syntax.php) * Add MIT License * Implement scribu's [Theme Wrapper](http://scribu.net/wordpress/theme-wrappers.html) (see `base.php`) * Move `css/`, `img/`, and `js/` folders within a new `assets/` folder * Move templates, `comments.php`, and `searchform.php` to `templates/` folder * Rename `inc/` to `lib/` * Add placeholder `lib/post-types.php` and `lib/metaboxes.php` files * Rename `loop-` files to `content-` * Remove all hooks * Use `templates/page-header.php` for page titles * Use `head.php` for everything in `<head>` ### 5.2.0: August 18th, 2012 * Update to jQuery 1.8.0 and Modernizr 2.6.1 * Fix duplicate active class in `wp_nav_menu` items * Merge `Roots_Navbar_Nav_Walker` into `Roots_Nav_Walker` * Add and update code documentation * Use `wp_get_theme()` to get the theme name on activation * Use `<figure>` & `<figcaption>` for captions * Wrap embedded media as suggested by Readability * Remove unnecessary `remove_action`'s on `wp_head` as of WordPress 3.2.1 * Add updates from HTML5 Boilerplate * Remove well class from sidebar * Flush permalinks on activation to avoid 404s with clean URLs * Show proper classes on additional `wp_nav_menu()`'s * Clean up `inc/cleanup.php` * Remove old admin notice for tagline * Remove default tagline admin notice, hide from feed * Fix for duplicated classes in widget markup * Show title on custom post type archive template * Fix for theme preview in WordPress 3.3.2 * Introduce `inc/config.php` with options for clean URLs, H5BP's `.htaccess`, root relative URLs, and Bootstrap features * Allow custom CSS classes in menus, walker cleanup * Remove WordPress version numbers from stylesheets * Don't include HTML5 Boilerplate's `style.css` by default * Allow `inc/htaccess.php` to work with Litespeed * Update to Bootstrap 2.0.4 * Update Bulgarian translation * Don't use clean URLs with default permalink structure * Add translations for Catalan, Polish, Hungarian, Norwegian, Russian ### 5.1.0: April 14th, 2012 * Various bugfixes for scripts, stylesheets, root relative URLs, clean URLs, and htaccess issues * Add a conditional feed link * Temporarily remove Gravity Forms customizations * Update to Bootstrap 2.0.2 * Update `roots.pot` for translations * Add/update languages: Vietnamese, Swedish, Bulgarian, Turkish, Norwegian, Brazilian Portugese * Change widgets to use `<section>` instead of `<article>` * Add comment-reply.js * Remove optimized robots.txt * HTML5 Boilerplate, Modernizr, and jQuery updates ### 5.0.0: February 5th, 2012 * Remove all frameworks except Bootstrap * Update to Bootstrap 2.0 * Remove `roots-options.php` and replaced with a more simple `roots-config.php` * Now using Bootstrap markup on forms, page titles, image galleries, alerts and errors, post and comment navigation * Remove Roots styles from `style.css` and introduced `app.css` for site-specific CSS * Remove almost all previous default Roots styling * Latest updates from HTML5 Boilerplate ### 4.1.0: February 1st, 2012 * Update translations * HTML5 Boilerplate updates * Fix for Server 500 errors * Add `roots-scripts.php`, now using `wp_enqueue_script` * Re-organize `roots-actions.php` * Allow `<script>` tags in TinyMCE * Add full width class and search form to 404 template * Remove Blueprint CSS specific markup * Use Roots Nav Walker as default * Add author name and taxonomy name to archive template title * Add Full Width CSS class options ### 4.0.0: January 4th, 2012 * Add theme activation options * HTML5 Boilerplate updates * Add CSS frameworks: Bootstrap, Foundation * Add translations: Dutch, Italian, Macedonian, German, Finnish, Danish, Spanish, and Turkish * Update jQuery * Remove included jQuery plugins * Clean up whitespace, switched to two spaces for tabs * Clean up `body_class()` some more with `roots_body_class()` * Post meta information is now displayed using a function (similar to Twenty Eleven) * Bugfixes for 1140 options * Add first and last classes to widgets * Fix bug with initial options save * Remove sitemap and listing subpages templates * Child themes can now unregister sidebars * Add fix for empty search query * Update README * Blocking access to readme.html and license.txt to hide WordPress version information ### 3.6.0: August 12th, 2011 * HTML5 Boilerplate 2.0 updates * Cleaner output of enqueued styles and scripts * Adde option for root relative URLs * Small fixes to root relative URLs and clean assets * Update included jQuery plugins * Add French translation (thanks @johnraz) * Add Brazilian Portuguese translation (thanks @weslly) * Switch the logo to use `add_custom_image_header` * Add a function that strips unnecessary self-closing tags * Code cleanup and re-organization ### 3.5.0: July 30th, 2011 * Complete rewrite of theme options based on Twenty Eleven * CSS frameworks: refactor code and add default classes for each framework * CSS frameworks: add support for Adapt.js and LESS * CSS frameworks: add option for None * Add support for WPML and theme translation * Add option for cleaner nav menu output * Add option for FOUT-B-Gone * Add authorship rel attribute to post author link * Activation bugfix for pages being added multiple times * Bugfixes to the root relative URL function * Child themes will now load their CSS automatically and properly * HTML5 Boilerplate updates (including Normalize.css, Modernizr 2.0, and Respond.js) * Introduce cleaner way of including HTML5 Boilerplate's `.htaccess` * Add hooks &amp; actions * Rename `includes/` directory to `inc/` * Add a blank `inc/roots-custom.php` file ### 3.2.4: May 19th, 2011 * Bugfixes * Match latest changes to HTML5 Boilerplate and Blueprint CSS * Update jQuery to 1.6.1 ### 3.2.3: May 10th, 2011 * Bugfixes * Add `language_attributes()` to `<html>` * Match latest changes to HTML5 Boilerplate and Blueprint CSS * Update jQuery to 1.6 ### 3.2.2: April 24th, 2011 * Bugfixes ### 3.2.1: April 20th, 2011 * Add support for child themes ### 3.2.0: April 15th, 2011 * Add support for the 1140px Grid * Update the conditional comment code to match latest changes to HTML5 Boilerplate ### 3.1.1: April 7th, 2011 * Fix relative path function to work correctly when WordPress is installed in a subdirectory * Update jQuery to 1.5.2 * Fix comments to show avatars correctly ### 3.1.0: April 1st, 2011 * Add support for 960.gs thanks to John Liuti * Add more onto the `.htaccess` from HTML5 Boilerplate * Allow the theme directory and name to be renamable ### 3.0.0: March 28th, 2011 * Change name from BB to Roots and release to the public * Update various areas to match the latest changes to HTML5 Boilerplate * Change the theme markup based on hCard/Readability Guidelines and work by Jonathan Neal * Create the navigation menus and automatically set their locations during theme activation * Set permalink structure to `/%year%/%postname%/` * Set uploads folder to `/assets/` * Rewrite static folders in `/wp-content/themes/roots/` (`css/`, `js/`, `img/`) to the root (`/css/`, `/js/`, `/img/`) * Rewrite `/wp-content/plugins/` to `/plugins/` * Add more root relative URLs on WordPress functions * Search results (`/?s=query`) rewrite to `/search/query/` * `l10n.js` is deregistered * Change [gallery] to output `<figure>` and `<figcaption>` and link to file by default * Add more `loop.php` templates * Made the HTML editor have a monospaced font * Add `front-page.php` * Update CSS for Gravity Forms 1.5 * Add `searchform.php template` ### 2.4.0: January 25th, 2011 * Add a notification when saving the theme settings * Add support for navigation menus * Create function that makes sure there is a Home page on theme activation * Update various areas to match the latest changes to HTML5 Boilerplate ### 2.3.0: December 8th, 2010 * Logo is no longer an `<h1>` * Add ARIA roles again * Change `ul#nav` to `nav#nav-main` * Add vCard to footer * Made all URL's root relative * Add Twitter and Facebook widgets to footer * Add SEO optimized `robots.txt` from WordPress codex ### 2.2.0: September 20th, 2010 * Add asynchronous Google Analytics * Update `.htaccess` with latest changes from HTML5 Boilerplate ### 2.1.0: August 19th, 2010 * Remove optimizeLegibility from headings * Update jQuery to latest version * Implement HTML5 Boilerplate `.htaccess` ### 2.0.1: August 2nd, 2010 * Add some presentational CSS classes * Add footer widget * Add more Gravity Forms default styling ### 2.0.0: July 19th, 2010 * Add HTML5 Boilerplate changes * Implement `loop.php` * wp_head cleanup * Add `page-subpages.php` template ### 1.5.0: April 15th, 2010 * Integrate Paul Irish's frontend-pro-template (the original HTML5 Boilerplate) ### 1.0.0: December 18th, 2009 * Add Blueprint CSS to Starkers
{ "content_hash": "ab37c98f3ca99b4c58fdd0f99f953d3f", "timestamp": "", "source": "github", "line_count": 374, "max_line_length": 132, "avg_line_length": 41.22192513368984, "alnum_prop": 0.7552052928585328, "repo_name": "palpalani/m3school", "id": "9ca5f519dd43a8a679d3e7df813d3b644e3eda66", "size": "15432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15785" }, { "name": "JavaScript", "bytes": "5524" }, { "name": "PHP", "bytes": "245846" } ], "symlink_target": "" }
#include "config.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include "region-allocator.h" #include "util.h" /** This value is enough so that x*y does not overflow if both < than this */ #define REGION_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) #ifdef ALIGNMENT #undef ALIGNMENT #endif #define REGION_ALIGN_UP(x, s) (((x) + s - 1) & (~(s - 1))) #if SIZEOF_OFF_T > SIZEOF_VOIDP #define ALIGNMENT (sizeof(off_t)) #else #define ALIGNMENT (sizeof(void *)) #endif /* #define CHECK_DOUBLE_FREE 0 */ /* set to 1 to perform expensive check for double recycle() */ typedef struct cleanup cleanup_type; struct cleanup { void (*action)(void *); void *data; }; struct recycle_elem { struct recycle_elem* next; }; struct large_elem { struct large_elem* next; struct large_elem* prev; }; struct region { size_t total_allocated; size_t small_objects; size_t large_objects; size_t chunk_count; size_t unused_space; /* Unused space due to alignment, etc. */ size_t allocated; char *initial_data; char *data; void *(*allocator)(size_t); void (*deallocator)(void *); size_t maximum_cleanup_count; size_t cleanup_count; cleanup_type *cleanups; struct large_elem* large_list; size_t chunk_size; size_t large_object_size; /* if not NULL recycling is enabled. * It is an array of linked lists of parts held for recycle. * The parts are all pointers to within the allocated chunks. * Array [i] points to elements of size i. */ struct recycle_elem** recycle_bin; /* amount of memory in recycle storage */ size_t recycle_size; }; static region_type * alloc_region_base(void *(*allocator)(size_t size), void (*deallocator)(void *), size_t initial_cleanup_count) { region_type *result = (region_type *) allocator(sizeof(region_type)); if (!result) return NULL; result->total_allocated = 0; result->small_objects = 0; result->large_objects = 0; result->chunk_count = 1; result->unused_space = 0; result->recycle_bin = NULL; result->recycle_size = 0; result->large_list = NULL; result->allocated = 0; result->data = NULL; result->initial_data = NULL; result->allocator = allocator; result->deallocator = deallocator; assert(initial_cleanup_count > 0); result->maximum_cleanup_count = initial_cleanup_count; result->cleanup_count = 0; result->cleanups = (cleanup_type *) allocator( result->maximum_cleanup_count * sizeof(cleanup_type)); if (!result->cleanups) { deallocator(result); return NULL; } result->chunk_size = DEFAULT_CHUNK_SIZE; result->large_object_size = DEFAULT_LARGE_OBJECT_SIZE; return result; } region_type * region_create(void *(*allocator)(size_t size), void (*deallocator)(void *)) { region_type* result = alloc_region_base(allocator, deallocator, DEFAULT_INITIAL_CLEANUP_SIZE); if(!result) return NULL; result->data = (char *) allocator(result->chunk_size); if (!result->data) { deallocator(result->cleanups); deallocator(result); return NULL; } result->initial_data = result->data; return result; } region_type *region_create_custom(void *(*allocator)(size_t), void (*deallocator)(void *), size_t chunk_size, size_t large_object_size, size_t initial_cleanup_size, int recycle) { region_type* result = alloc_region_base(allocator, deallocator, initial_cleanup_size); if(!result) return NULL; assert(large_object_size <= chunk_size); result->chunk_size = chunk_size; result->large_object_size = large_object_size; if(result->chunk_size > 0) { result->data = (char *) allocator(result->chunk_size); if (!result->data) { deallocator(result->cleanups); deallocator(result); return NULL; } result->initial_data = result->data; } if(recycle) { result->recycle_bin = allocator(sizeof(struct recycle_elem*) * result->large_object_size); if(!result->recycle_bin) { region_destroy(result); return NULL; } memset(result->recycle_bin, 0, sizeof(struct recycle_elem*) * result->large_object_size); } return result; } void region_destroy(region_type *region) { void (*deallocator)(void *); if (!region) return; deallocator = region->deallocator; region_free_all(region); deallocator(region->cleanups); deallocator(region->initial_data); if(region->recycle_bin) deallocator(region->recycle_bin); if(region->large_list) { struct large_elem* p = region->large_list, *np; while(p) { np = p->next; deallocator(p); p = np; } } deallocator(region); } size_t region_add_cleanup(region_type *region, void (*action)(void *), void *data) { assert(action); if (region->cleanup_count >= region->maximum_cleanup_count) { cleanup_type *cleanups = (cleanup_type *) region->allocator( 2 * region->maximum_cleanup_count * sizeof(cleanup_type)); if (!cleanups) return 0; memcpy(cleanups, region->cleanups, region->cleanup_count * sizeof(cleanup_type)); region->deallocator(region->cleanups); region->cleanups = cleanups; region->maximum_cleanup_count *= 2; } region->cleanups[region->cleanup_count].action = action; region->cleanups[region->cleanup_count].data = data; ++region->cleanup_count; return region->cleanup_count; } void region_remove_cleanup(region_type *region, void (*action)(void *), void *data) { size_t i; for(i=0; i<region->cleanup_count; i++) { if(region->cleanups[i].action == action && region->cleanups[i].data == data) { region->cleanup_count--; region->cleanups[i] = region->cleanups[region->cleanup_count]; return; } } } void * region_alloc(region_type *region, size_t size) { size_t aligned_size; void *result; if (size == 0) { size = 1; } aligned_size = REGION_ALIGN_UP(size, ALIGNMENT); if (aligned_size >= region->large_object_size) { result = region->allocator(size + sizeof(struct large_elem)); if (!result) return NULL; ((struct large_elem*)result)->prev = NULL; ((struct large_elem*)result)->next = region->large_list; if(region->large_list) region->large_list->prev = (struct large_elem*)result; region->large_list = (struct large_elem*)result; region->total_allocated += size; ++region->large_objects; return result + sizeof(struct large_elem); } if (region->recycle_bin && region->recycle_bin[aligned_size]) { result = (void*)region->recycle_bin[aligned_size]; region->recycle_bin[aligned_size] = region->recycle_bin[aligned_size]->next; region->recycle_size -= aligned_size; region->unused_space += aligned_size - size; return result; } if (region->allocated + aligned_size > region->chunk_size) { void *chunk = region->allocator(region->chunk_size); size_t wasted; if (!chunk) return NULL; wasted = (region->chunk_size - region->allocated) & (~(ALIGNMENT-1)); if(wasted >= ALIGNMENT) { /* put wasted part in recycle bin for later use */ region->total_allocated += wasted; ++region->small_objects; region_recycle(region, region->data+region->allocated, wasted); region->allocated += wasted; } ++region->chunk_count; region->unused_space += region->chunk_size - region->allocated; if(!region_add_cleanup(region, region->deallocator, chunk)) { region->deallocator(chunk); region->chunk_count--; region->unused_space -= region->chunk_size - region->allocated; return NULL; } region->allocated = 0; region->data = (char *) chunk; } result = region->data + region->allocated; region->allocated += aligned_size; region->total_allocated += aligned_size; region->unused_space += aligned_size - size; ++region->small_objects; return result; } void * region_alloc_init(region_type *region, const void *init, size_t size) { void *result = region_alloc(region, size); if (!result) return NULL; memcpy(result, init, size); return result; } void * region_alloc_zero(region_type *region, size_t size) { void *result = region_alloc(region, size); if (!result) return NULL; memset(result, 0, size); return result; } void * region_alloc_array_init(region_type *region, const void *init, size_t num, size_t size) { if((num >= REGION_NO_OVERFLOW || size >= REGION_NO_OVERFLOW) && num > 0 && SIZE_MAX / num < size) { log_msg(LOG_ERR, "region_alloc_array_init failed because of integer overflow"); exit(1); } return region_alloc_init(region, init, num*size); } void * region_alloc_array_zero(region_type *region, size_t num, size_t size) { if((num >= REGION_NO_OVERFLOW || size >= REGION_NO_OVERFLOW) && num > 0 && SIZE_MAX / num < size) { log_msg(LOG_ERR, "region_alloc_array_zero failed because of integer overflow"); exit(1); } return region_alloc_zero(region, num*size); } void * region_alloc_array(region_type *region, size_t num, size_t size) { if((num >= REGION_NO_OVERFLOW || size >= REGION_NO_OVERFLOW) && num > 0 && SIZE_MAX / num < size) { log_msg(LOG_ERR, "region_alloc_array failed because of integer overflow"); exit(1); } return region_alloc(region, num*size); } void region_free_all(region_type *region) { size_t i; assert(region); assert(region->cleanups); i = region->cleanup_count; while (i > 0) { --i; assert(region->cleanups[i].action); region->cleanups[i].action(region->cleanups[i].data); } if(region->recycle_bin) { memset(region->recycle_bin, 0, sizeof(struct recycle_elem*) * region->large_object_size); region->recycle_size = 0; } if(region->large_list) { struct large_elem* p = region->large_list, *np; void (*deallocator)(void *) = region->deallocator; while(p) { np = p->next; deallocator(p); p = np; } region->large_list = NULL; } region->data = region->initial_data; region->cleanup_count = 0; region->allocated = 0; region->total_allocated = 0; region->small_objects = 0; region->large_objects = 0; region->chunk_count = 1; region->unused_space = 0; } char * region_strdup(region_type *region, const char *string) { return (char *) region_alloc_init(region, string, strlen(string) + 1); } void region_recycle(region_type *region, void *block, size_t size) { size_t aligned_size; if(!block || !region->recycle_bin) return; if (size == 0) { size = 1; } aligned_size = REGION_ALIGN_UP(size, ALIGNMENT); if(aligned_size < region->large_object_size) { struct recycle_elem* elem = (struct recycle_elem*)block; /* we rely on the fact that ALIGNMENT is void* so the next will fit */ assert(aligned_size >= sizeof(struct recycle_elem)); #ifdef CHECK_DOUBLE_FREE if(CHECK_DOUBLE_FREE) { /* make sure the same ptr is not freed twice. */ struct recycle_elem *p = region->recycle_bin[aligned_size]; while(p) { assert(p != elem); p = p->next; } } #endif elem->next = region->recycle_bin[aligned_size]; region->recycle_bin[aligned_size] = elem; region->recycle_size += aligned_size; region->unused_space -= aligned_size - size; return; } else { struct large_elem* l; /* a large allocation */ region->total_allocated -= size; --region->large_objects; l = (struct large_elem*)(block-sizeof(struct large_elem)); if(l->prev) l->prev->next = l->next; else region->large_list = l->next; if(l->next) l->next->prev = l->prev; region->deallocator(l); } } void region_dump_stats(region_type *region, FILE *out) { fprintf(out, "%lu objects (%lu small/%lu large), %lu bytes allocated (%lu wasted) in %lu chunks, %lu cleanups, %lu in recyclebin", (unsigned long) (region->small_objects + region->large_objects), (unsigned long) region->small_objects, (unsigned long) region->large_objects, (unsigned long) region->total_allocated, (unsigned long) region->unused_space, (unsigned long) region->chunk_count, (unsigned long) region->cleanup_count, (unsigned long) region->recycle_size); if(1 && region->recycle_bin) { /* print details of the recycle bin */ size_t i; for(i=0; i<region->large_object_size; i++) { size_t count = 0; struct recycle_elem* el = region->recycle_bin[i]; while(el) { count++; el = el->next; } if(i%ALIGNMENT == 0 && i!=0) fprintf(out, " %lu", (unsigned long)count); } } } size_t region_get_recycle_size(region_type* region) { return region->recycle_size; } size_t region_get_mem(region_type* region) { return region->total_allocated; } size_t region_get_mem_unused(region_type* region) { return region->unused_space; } /* debug routine */ void region_log_stats(region_type *region) { char buf[10240], *str=buf; int strl = sizeof(buf); int len; snprintf(str, strl, "%lu objects (%lu small/%lu large), %lu bytes allocated (%lu wasted) in %lu chunks, %lu cleanups, %lu in recyclebin", (unsigned long) (region->small_objects + region->large_objects), (unsigned long) region->small_objects, (unsigned long) region->large_objects, (unsigned long) region->total_allocated, (unsigned long) region->unused_space, (unsigned long) region->chunk_count, (unsigned long) region->cleanup_count, (unsigned long) region->recycle_size); len = strlen(str); str+=len; strl-=len; if(1 && region->recycle_bin) { /* print details of the recycle bin */ size_t i; for(i=0; i<region->large_object_size; i++) { size_t count = 0; struct recycle_elem* el = region->recycle_bin[i]; while(el) { count++; el = el->next; } if(i%ALIGNMENT == 0 && i!=0) { snprintf(str, strl, " %lu", (unsigned long)count); len = strlen(str); str+=len; strl-=len; } } } log_msg(LOG_INFO, "memory: %s", buf); }
{ "content_hash": "870111487dfb51ed49c52588f7a106ff", "timestamp": "", "source": "github", "line_count": 544, "max_line_length": 138, "avg_line_length": 24.924632352941178, "alnum_prop": 0.662069474150011, "repo_name": "jmkeyes/nsd", "id": "5a280d832aa797c5d63cdeff20e9fa7eeb94682b", "size": "13723", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "region-allocator.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Bison", "bytes": "61283" }, { "name": "C", "bytes": "1575043" }, { "name": "Python", "bytes": "92028" }, { "name": "Shell", "bytes": "47761" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2dceccc82899067ab369ec227d595c0f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7227ac3b276e7d7e5b85b523b964ca267dadb4e9", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Microdontocharis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@interface ViewController4 : UIViewController @end
{ "content_hash": "3e9b0e50b487b97311c2881c1e62496c", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 45, "avg_line_length": 17.333333333333332, "alnum_prop": 0.8269230769230769, "repo_name": "QiaokeZ/HSKModel", "id": "e1470b2e01c488dbf3f3f01608ff81cf3239bb85", "size": "215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HSKModel-master/HSKModel-master/ViewController4.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "42367" } ], "symlink_target": "" }
/** * Get the list of exercises to shoot from a file or from standard in, as * denoted by the string "-" * * done(err, selected) is called with the parsed JSON data */ var getStdin = require('./get-stdin'); var path = require('path'); function getFile(file, done) { if (file === '-') { return getStdin(done); } var selected; try { selected = require(path.resolve(file)); } catch (e) { console.error(e); return done(new Error('Unable to read file ' + file + '. Aborting.')); } done(null, selected); } module.exports = getFile;
{ "content_hash": "5ce40b024110de0c5cd0ab81e04447b3", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 78, "avg_line_length": 22.884615384615383, "alnum_prop": 0.5932773109243697, "repo_name": "Khan/exercise-icons", "id": "e3e064c8934d6bf89f54880e233440a131d8564a", "size": "595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/get-file.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "51823" }, { "name": "Makefile", "bytes": "141" }, { "name": "Shell", "bytes": "781" } ], "symlink_target": "" }
"use strict" const stdin = process.stdin; stdin.setRawMode(true); stdin.resume(); stdin.setEncoding('utf8'); let nice_words = 0; let last_char = ''; let have_two_in_a_row = false; let vowels = 0; let have_forbidden_combination = false; let super_nice_words = 0; let third = ''; let repeat_with_one_between = false; let pairs = []; let have_pair = false; stdin.on('data', function(data){ for (const k of data) { switch(k) { case '\r': if (have_two_in_a_row && vowels >= 3 && !have_forbidden_combination) nice_words += 1; have_two_in_a_row = false; vowels = 0; have_forbidden_combination = false; if (repeat_with_one_between && have_pair) super_nice_words += 1; repeat_with_one_between = false; pairs = []; have_pair = false; if (last_char === '\r') { // stop when two new lines are seen in a row console.log(`Part1: ${nice_words}, Part2: ${super_nice_words}`); process.exit(); } break; case 'a': case 'e': case 'i': case 'o': case 'u': vowels += 1; break; case 'b': have_forbidden_combination = have_forbidden_combination || last_char == 'a'; break; case 'd': have_forbidden_combination = have_forbidden_combination || last_char == 'c'; break; case 'q': have_forbidden_combination = have_forbidden_combination || last_char == 'p'; break; case 'y': have_forbidden_combination = have_forbidden_combination || last_char == 'x'; break; } if (k === last_char) have_two_in_a_row = true; if (k === third) repeat_with_one_between = true; let pair_index = pairs.findIndex(e => e === (last_char + k)); if (pair_index >= 0 && pair_index !== pairs.length - 1) have_pair = true; pairs.push(last_char + k); third = last_char; last_char = k; } }); console.log("Paste input, end with enter.");
{ "content_hash": "904d9b0c22687942ac252aac36ff4224", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 84, "avg_line_length": 26.546666666666667, "alnum_prop": 0.5600200904068308, "repo_name": "reggna/advent-of-code-2015", "id": "26bc7fccaf3f4535f0499ba48ffc830cfa1d4ba5", "size": "1991", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "5.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "21324" } ], "symlink_target": "" }
class Cinch::Plugins::UStream include Cinch::Plugin set :help, <<-EOF fix channel mode - reset the channel mode -U+g EOF match /fix channel mode\s*$/, :method => :fix_channel_mode def fix_channel_mode(msg) if msg.channel.voiced?(msg.user) || msg.channel.opped?(msg.user) msg.reply 'Fixing channel mode' msg.channel.mode('-U') end end end
{ "content_hash": "807689961931047d83de1f373018a69f", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 69, "avg_line_length": 22.529411764705884, "alnum_prop": 0.6422976501305483, "repo_name": "demonsheepgit/demonasimov", "id": "56184183d600000d92f051822102338160c1de14", "size": "553", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/ustream.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "41295" } ], "symlink_target": "" }
"use strict"; var router_1 = require('@angular/router'); var welcome_component_1 = require('./welcome/welcome.component'); var dive_log_component_1 = require('./logs/dive-log.component'); var sites_routes_1 = require('./sites/sites.routes'); var logged_in_guard_1 = require('./logged-in.guard'); var user_auth_service_1 = require('./login/user-auth.service'); var login_component_1 = require('./login/login.component'); var routes = [ { path: 'divelogs', component: dive_log_component_1.DiveLogComponent, canActivate: [logged_in_guard_1.LoggedInGuard] }, { path: 'login', component: login_component_1.LoginComponent }, { path: '', pathMatch: 'full', component: welcome_component_1.WelcomeComponent } ].concat(sites_routes_1.sitesRoutes); exports.routingProviders = [ logged_in_guard_1.LoggedInGuard, user_auth_service_1.UserAuthService ]; exports.routingModule = router_1.RouterModule.forRoot(routes); //# sourceMappingURL=app.routes.js.map
{ "content_hash": "c08c5cf6b71c0969551d10d49ad32635", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 123, "avg_line_length": 50.526315789473685, "alnum_prop": 0.7291666666666666, "repo_name": "mtraina/unraveling-angular-2", "id": "c77a88139f03f75053a47347223c6d5f524558af", "size": "960", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Samples/Chapter09/Exercise-09-04/app/app.routes.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1853" }, { "name": "HTML", "bytes": "185834" }, { "name": "JavaScript", "bytes": "82905" }, { "name": "TypeScript", "bytes": "278153" } ], "symlink_target": "" }
<?php namespace CsvMigrations\Exception; use InvalidArgumentException; use Throwable; class UnsupportedPrimaryKeyException extends InvalidArgumentException { /** * @param string $message Exception message * @param int $code Exception code * @param \Throwable|null $previous Previous exception */ public function __construct(string $message = "", int $code = 0, Throwable $previous = null) { if (empty($message)) { $message = 'Composite primary keys are not supported. Primary key must be a string'; } parent::__construct($message, $code, $previous); } }
{ "content_hash": "4955e6e9bd5488c41c05f0fd02c20956", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 96, "avg_line_length": 25.28, "alnum_prop": 0.6629746835443038, "repo_name": "QoboLtd/cakephp-csv-migrations", "id": "a754f123047577f0650e77c6cec052b3539cc0e4", "size": "1010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Exception/UnsupportedPrimaryKeyException.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3777" }, { "name": "JavaScript", "bytes": "72091" }, { "name": "PHP", "bytes": "1186744" }, { "name": "Twig", "bytes": "5848" } ], "symlink_target": "" }
// 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. using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { using Workspace = Microsoft.CodeAnalysis.Workspace; [Export(typeof(IAttachedCollectionSourceProvider))] [Name(nameof(CpsDiagnosticItemSourceProvider))] [Order] [AppliesToProject("(CSharp | VB) & CPS")] internal sealed class CpsDiagnosticItemSourceProvider : AttachedCollectionSourceProvider<IVsHierarchyItem> { private readonly IAnalyzersCommandHandler _commandHandler; private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService; private readonly Workspace _workspace; private IHierarchyItemToProjectIdMap? _projectMap; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CpsDiagnosticItemSourceProvider( [Import(typeof(AnalyzersCommandHandler))] IAnalyzersCommandHandler commandHandler, IDiagnosticAnalyzerService diagnosticAnalyzerService, VisualStudioWorkspace workspace) { _commandHandler = commandHandler; _diagnosticAnalyzerService = diagnosticAnalyzerService; _workspace = workspace; } protected override IAttachedCollectionSource? CreateCollectionSource(IVsHierarchyItem item, string relationshipName) { if (item != null && item.HierarchyIdentity != null && item.HierarchyIdentity.NestedHierarchy != null && relationshipName == KnownRelationships.Contains) { if (NestedHierarchyHasProjectTreeCapability(item, "AnalyzerDependency")) { var projectRootItem = FindProjectRootItem(item, out var targetFrameworkMoniker); if (projectRootItem != null) { var hierarchyMapper = TryGetProjectMap(); if (hierarchyMapper != null && hierarchyMapper.TryGetProjectId(projectRootItem, targetFrameworkMoniker, out var projectId)) { var hierarchy = projectRootItem.HierarchyIdentity.NestedHierarchy; var itemId = projectRootItem.HierarchyIdentity.NestedItemID; if (hierarchy.GetCanonicalName(itemId, out var projectCanonicalName) == VSConstants.S_OK) { return new CpsDiagnosticItemSource(_workspace, projectCanonicalName, projectId, item, _commandHandler, _diagnosticAnalyzerService); } } } } } return null; } /// <summary> /// Starting at the given item, walks up the tree to find the item representing the project root. /// If the item is located under a target-framwork specific node, the corresponding /// TargetFrameworkMoniker will be found as well. /// </summary> private static IVsHierarchyItem? FindProjectRootItem(IVsHierarchyItem item, out string? targetFrameworkMoniker) { targetFrameworkMoniker = null; for (var parent = item; parent != null; parent = parent.Parent) { targetFrameworkMoniker ??= GetTargetFrameworkMoniker(parent); if (NestedHierarchyHasProjectTreeCapability(parent, "ProjectRoot")) { return parent; } } return null; } /// <summary> /// Given an item determines if it represents a particular target frmework. /// If so, it returns the corresponding TargetFrameworkMoniker. /// </summary> private static string? GetTargetFrameworkMoniker(IVsHierarchyItem item) { var hierarchy = item.HierarchyIdentity.NestedHierarchy; var itemId = item.HierarchyIdentity.NestedItemID; var projectTreeCapabilities = GetProjectTreeCapabilities(hierarchy, itemId); var isTargetNode = false; string? potentialTFM = null; foreach (var capability in projectTreeCapabilities) { if (capability.Equals("TargetNode")) { isTargetNode = true; } else if (capability.StartsWith("$TFM:")) { potentialTFM = capability["$TFM:".Length..]; } } return isTargetNode ? potentialTFM : null; } private static bool NestedHierarchyHasProjectTreeCapability(IVsHierarchyItem item, string capability) { var hierarchy = item.HierarchyIdentity.NestedHierarchy; var itemId = item.HierarchyIdentity.NestedItemID; var projectTreeCapabilities = GetProjectTreeCapabilities(hierarchy, itemId); return projectTreeCapabilities.Any(static (c, capability) => c.Equals(capability), capability); } private static ImmutableArray<string> GetProjectTreeCapabilities(IVsHierarchy hierarchy, uint itemId) { if (hierarchy.GetProperty(itemId, (int)__VSHPROPID7.VSHPROPID_ProjectTreeCapabilities, out var capabilitiesObj) == VSConstants.S_OK) { var capabilitiesString = (string)capabilitiesObj; return ImmutableArray.Create(capabilitiesString.Split(' ')); } else { return ImmutableArray<string>.Empty; } } private IHierarchyItemToProjectIdMap? TryGetProjectMap() { _projectMap ??= _workspace.Services.GetService<IHierarchyItemToProjectIdMap>(); return _projectMap; } } }
{ "content_hash": "a83508adc648a921a5fd01bdd6f58d16", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 163, "avg_line_length": 42.02597402597402, "alnum_prop": 0.6274721878862793, "repo_name": "shyamnamboodiripad/roslyn", "id": "a4ea81eaa6ab895dde1c86b95dd287927aa37ebb", "size": "6474", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/CpsDiagnosticItemSourceProvider.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "257760" }, { "name": "Batchfile", "bytes": "8186" }, { "name": "C#", "bytes": "175466619" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "12939" }, { "name": "Dockerfile", "bytes": "441" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "285141" }, { "name": "Shell", "bytes": "133800" }, { "name": "Vim Snippet", "bytes": "6353" }, { "name": "Visual Basic .NET", "bytes": "73892766" } ], "symlink_target": "" }
module Yoke class Alias class << self def list return {} unless Yoke::Base.has_alias_file? aliases = {} File.readlines(Yoke::Base.alias_file_path).each do |line| if line.start_with? "alias" alias_extract = line.scan(/^alias\s(\w+)\=\"cd '(.+)'\"$/).last aliases[alias_extract[0]] = alias_extract[1] end end aliases end def add(path, name) Yoke::Base.create_alias_file if list.has_key?(name) false else content = [] added = false File.readlines(Yoke::Base.alias_file_path).each do |line| if line.start_with? "alias" alias_extract = line.scan(/^alias\s(\w+)\=\"cd '(.+)'\"$/).last if alias_extract[1] == path content << alias_string(name, path) added = true else content << line end else content << line end end File.open(Yoke::Base.alias_file_path, "w") do |file| content.each { |line| file.puts line } end unless added File.open(Yoke::Base.alias_file_path, 'a') do |file| file.puts alias_string(name, path) end end true end end def remove(path, name) return false unless Yoke::Base.has_alias_file? if list.has_key?(name) content = [] File.readlines(Yoke::Base.alias_file_path).each do |line| if line.start_with? "alias" alias_extract = line.scan(/^alias\s(\w+)\=\"cd '(.+)'\"$/).last if alias_extract[0] != name content << line end else content << line end end File.open(Yoke::Base.alias_file_path, "w") do |file| content.each { |line| file.puts line } end else false end end def alias_string(name, path) "alias #{name.split.join('_').downcase}=\"cd '#{path}'\"" end end end end
{ "content_hash": "17f94d3ec2fa80bddce352fc75f528ec", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 77, "avg_line_length": 28.363636363636363, "alnum_prop": 0.4674908424908425, "repo_name": "fousa/yoke", "id": "9046e2cd989c76220747303a04261c802629320d", "size": "2184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/yoke/alias.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "8268" } ], "symlink_target": "" }
#import <Foundation/Foundation.h> #import "DBConnection.h" #import "Statement.h" #import "AddressBookFuns.h" typedef enum { EAddressBookSyncGroup= 0, //存储群组的同步信息 EAddressBookSyncContact //存储联系人的同步信息 } EAddressBokkSynctype; @interface AddressBookSyncDBAccess : NSObject { EAddressBokkSynctype idType; sqlite3 * shareDB; NSMutableDictionary *changeMutableDic; NSMutableDictionary *idMutableDic; } - (AddressBookSyncDBAccess *)init:(EAddressBokkSynctype)type; - (void)dealloc; //创建空表 - (BOOL)AddressBookSyncTableCreate; //将生成的MD5值入库 - (BOOL)addSyncMD5Data:(NSMutableDictionary *)hashData; - (NSMutableDictionary *)getMD5Data; - (BOOL)updateSyncTable:(NSMutableDictionary *) add Update:(NSMutableDictionary *)update Del:(NSArray *)del; - (BOOL)cleanTable; - (NSMutableDictionary *)getAllHashString; //外部调用哈希值写入本地库中 - (BOOL)wirteToSyncTable; - (NSString *)getHashGroupString:(id)group; - (NSString *)getHashContactString:(id)contact addressBookFuns:(AddressBookFuns *)addressBookFuns; //根据当前通讯录数据,更新数据库,会替换以前版本 - (BOOL)updateDBFromAdressBook; - (void)composeDBFromAdressBook; //和通讯录比较,返回差别的id,字典的key为:0:添加  1:删除  2:修改,对应的为id数组 - (NSMutableDictionary *)getChangedInfo; - (BOOL)updateDBWithChangedInfo:(NSMutableArray *)contactIDArray; //和通讯录里面的数据同步 - (BOOL)addItemByID:(NSInteger)itemID; - (BOOL)updateItemByID:(NSInteger)itemID; - (BOOL)delItmByID:(NSInteger)itemID; - (NSMutableDictionary*)getContactsChangedCount;//获取联系人的变更 NSMutableDictionary内 addCount为增加的联系人数目,editCount是修改的,delCount是删除的 @end
{ "content_hash": "7bd8abad212ff7b284d96416244b4628", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 124, "avg_line_length": 27.963636363636365, "alnum_prop": 0.7828348504551366, "repo_name": "guohaiyang/yuntongxun", "id": "d8b12c2b3bf60632621b33284e52b6c1b96be5cf", "size": "2804", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CCPVoipDemo/MangeAddressBook/AddressBookSyncDBAccess.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4954" }, { "name": "Objective-C", "bytes": "2202084" }, { "name": "Objective-C++", "bytes": "454390" }, { "name": "Ruby", "bytes": "4853" } ], "symlink_target": "" }
"use strict"; define("ace/snippets/elixir", ["require", "exports", "module"], function (e, t, n) { "use strict"; t.snippetText = undefined, t.scope = ""; });
{ "content_hash": "60e421a8770f7d2c20ee19e4707ad029", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 84, "avg_line_length": 27, "alnum_prop": 0.6111111111111112, "repo_name": "IonicaBizau/arc-assembler", "id": "9dd3955dc496d14b1f8d9d239d32645fc1cbd101", "size": "162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clients/ace-builds/src-min/snippets/elixir.js", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "346" }, { "name": "CSS", "bytes": "459098" }, { "name": "HTML", "bytes": "236653" }, { "name": "JavaScript", "bytes": "865404" }, { "name": "Shell", "bytes": "1142" } ], "symlink_target": "" }
<!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Django Market Theme Designer - Django Market auctions.html</title> <meta name="description" content=" " /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../assets_url/bootstrap.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://d4dqt8qzmbeux.cloudfront.net/themes/bootstrap/2.3/js/bootstrap.min.gzip.js"></script> <script src="https://d4dqt8qzmbeux.cloudfront.net/themes/bootstrap/2.3/js/modernizr-2.6.2.min.gzip.js"></script> </head> <body> <div class="navbar"> <div class="navbar-inner"> <div class="container-fluid"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="nav-collapse"> <ul class="nav"> <li><a href="home.html">Home</a></li> <li><a href="for_sale.html">For Sale</a></li> <li><a href="auctions.html">Auctions</a></li> <li><a href="blog.html">Blog</a></li> <li><a href="about_us.html">About Us</a></li> <li><a href="login.html" id="">Login</a></li> <li><a href="register.html">Register</a></li> </ul> <form action="search.html" method="get" class="navbar-search span3"> <input type="text" class="search-query span2" placeholder=" Search " name="q" id="q" data-provide="typeahead" data-items="4" data-source="[]" /> </form> <p class="navbar-text pull-right"> <a class="text-error" href="my_shopping.html">Cart 10</a> &nbsp;<a class="text-error" href="my_orders.html">Orders</a> </p> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container-fluid"> <!-- FLASH MESSAGE --> <!-- Page Content is added here from the other pages--> <div class="row-fluid" id="content"> <div id="alert alert-block fade in"> </div> <div class="span12"> <h2>Auctions</h2> </div> <ul class="well span3 unstyled"> <li class="side-header">Auction Sessions</li> {{ sessions }} </ul> <div class="span4"> <h3 class="title">No lots in this session.</h3> </div> <div class="span4"> <table class="table table-condensed" id="AuctionResult"> <thead> <tr> <th></th> <th></th> </tr> </thead> <tr> <td class="span4"> <a href="{{lot.url}}"> <img src="" alt="{{ lot.title }}"/> </a> </td> <td> <h5>{{lot.title|title}}</h5> <h6>{{lot.price}}</h6> </td> </tr> </tbody> </table> </div> <div class="row-fluid"> <div class="pagination"> {{ paginator }} </div> </div> <!-- {# Page: auctions.html Purpose: Display List of Auction Sessions & Lots Status: Required. This Template is Passed to the layout.html as {{ content }} Variables on This Page: session_title Description: Session Title for the Auctions lot Description: Basic Variable for the lot viewed. .url Description: URL for the lot at that shop .image.medium Description: medium sized image for the shop. Options: original .title Description: Lot title as entered by the shop owner .price Description: price entered by the shop owner i.e current bid Description: checks if there are any items for auction Filters on this Page None Additional Reference: See Jinja2 documentation for string filters available Variable to iterate over lots Description: object passes to template with the lots, if any available Author: Stephen Power #} --> </div> <!-- FOOTER --> <hr> <footer> {{ footer }} <div id="label-info"> <div class="span3"> <h5>About Us</h5> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a blandit lectus. Praesent cras amet.</p> <a href="/about_us/">Read more</a> </div> <div class="span3"> <h5>Quick Search</h5> <p><a href="/search/?q={{categories.name}}">{{ categories.name }}</a></p> <h5>Quick Navigation</h5> <P><A HREF="home.html">Home</A></P> <P><A HREF="auctions.html">Auctions</A></P> <P><A HREF="for_sale.html">For Sale</A></P> <P><A HREF="login.html">Login</A></P> <P><A HREF="register.html">Register</A></P> </div> <div class="span3"> <h5>Quick Search</h5> <form action="search.html" method="get"> <input type="text" `placeholder="Search " name="q" id="s" class="span2"/> </form> <p><a href="/search/?q={{categories.name}}">{{ categories.name }}</a></p> <hr /> <h5>Website Policies</h5> <ul class="unstyled"> <li><a href="privacy_policies.html">Privacy Policy</a></li> <li><a href="refund.html">Refund Policy</a></li> <li><a href="terms_of_service.html">Terms of Service Policy</a></li> </ul> </div> <div class="span2"> <h5>Latest Blog Posts</h5> <p><a href="blog.html">Django Market Blog Post</a></p> <p>Posted on 2013-02-14 16:59</p> <p>{{ last_post.body|truncate(100) }}</p> </div> </div> </footer> </div> <!-- /container --> </body> </html>
{ "content_hash": "06eaacbac869670e21076a117f8f3a67", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 170, "avg_line_length": 33.74874371859296, "alnum_prop": 0.47215604526503874, "repo_name": "StephenPower/Collector-City-Market-Place-Themes", "id": "1d5d07c060a52ed06a4d3c21f3f02895cc67b692", "size": "6716", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Bootstrap/2.3/cosmo/design/auctions.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3961484" }, { "name": "JavaScript", "bytes": "495981" }, { "name": "Python", "bytes": "88992" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Class Hierarchy (Play! 2.x Provider for Play! 2.1.x 1.0.0-alpha6 API)</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Class Hierarchy (Play! 2.x Provider for Play! 2.1.x 1.0.0-alpha6 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="com/google/code/play2/provider/play21/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li> <li><a href="overview-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For All Packages</h1> <span class="strong">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="com/google/code/play2/provider/play21/package-tree.html">com.google.code.play2.provider.play21</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/1.6.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="strong">Object</span></a> <ul> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21CoffeescriptCompiler.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21CoffeescriptCompiler</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2CoffeescriptCompiler.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2CoffeescriptCompiler</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21CoffeescriptCompiler.CompileResult.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21CoffeescriptCompiler.CompileResult</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/CoffeescriptCompilationResult.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">CoffeescriptCompilationResult</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21EbeanEnhancer.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21EbeanEnhancer</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2EbeanEnhancer.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2EbeanEnhancer</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21JavaEnhancer.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21JavaEnhancer</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2JavaEnhancer.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2JavaEnhancer</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21JavascriptCompiler.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21JavascriptCompiler</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2JavascriptCompiler.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2JavascriptCompiler</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21JavascriptCompiler.CompileResult.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21JavascriptCompiler.CompileResult</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/JavascriptCompilationResult.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">JavascriptCompilationResult</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21LessCompiler.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21LessCompiler</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2LessCompiler.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2LessCompiler</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21LessCompiler.CompileResult.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21LessCompiler.CompileResult</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/LessCompilationResult.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">LessCompilationResult</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21Provider.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21Provider</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2Provider.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2Provider</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21RoutesCompiler.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21RoutesCompiler</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2RoutesCompiler.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2RoutesCompiler</a>)</li> <li type="circle">com.google.code.play2.provider.play21.<a href="com/google/code/play2/provider/play21/Play21TemplateCompiler.html" title="class in com.google.code.play2.provider.play21"><span class="strong">Play21TemplateCompiler</span></a> (implements com.google.code.play2.provider.api.<a href="https://play2-maven-plugin.googlecode.com/svn/mavensite/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/Play2TemplateCompiler.html?is-external=true" title="class or interface in com.google.code.play2.provider.api">Play2TemplateCompiler</a>)</li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="com/google/code/play2/provider/play21/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li> <li><a href="overview-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2013&#x2013;2014. All rights reserved.</small></p> </body> </html>
{ "content_hash": "784a6928a574801f187cd812c27a9411", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 622, "avg_line_length": 75.65441176470588, "alnum_prop": 0.7424433861405384, "repo_name": "play2-maven-plugin/play2-maven-plugin.github.io", "id": "d0dc1cd4e2f4289595c1ed6a58f066bd848d586e", "size": "10289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play2-maven-plugin/1.0.0-alpha6/play2-providers/play2-provider-play21/apidocs/overview-tree.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2793124" }, { "name": "HTML", "bytes": "178221432" }, { "name": "JavaScript", "bytes": "120742" } ], "symlink_target": "" }
function os::util::environment::use_sudo() { USE_SUDO=true export USE_SUDO } readonly -f os::util::environment::use_sudo # os::util::environment::setup_time_vars sets up environment variables that describe durations of time # These variables can be used to specify times for other utility functions # # Globals: # None # Arguments: # None # Returns: # - export TIME_MS # - export TIME_SEC # - export TIME_MIN function os::util::environment::setup_time_vars() { TIME_MS=1 export TIME_MS TIME_SEC="$(( 1000 * ${TIME_MS} ))" export TIME_SEC TIME_MIN="$(( 60 * ${TIME_SEC} ))" export TIME_MIN } readonly -f os::util::environment::setup_time_vars # os::util::environment::setup_all_server_vars sets up all environment variables necessary to configure and start an OpenShift server # # Globals: # - OS_ROOT # - PATH # - TMPDIR # - LOG_DIR # - ARTIFACT_DIR # - KUBELET_SCHEME # - KUBELET_BIND_HOST # - KUBELET_HOST # - KUBELET_PORT # - BASETMPDIR # - ETCD_PORT # - ETCD_PEER_PORT # - API_BIND_HOST # - API_HOST # - API_PORT # - API_SCHEME # - PUBLIC_MASTER_HOST # - USE_IMAGES # Arguments: # - 1: the path under the root temporary directory for OpenShift where these subdirectories should be made # Returns: # - export PATH # - export BASETMPDIR # - export LOG_DIR # - export VOLUME_DIR # - export ARTIFACT_DIR # - export FAKE_HOME_DIR # - export HOME # - export KUBELET_SCHEME # - export KUBELET_BIND_HOST # - export KUBELET_HOST # - export KUBELET_PORT # - export ETCD_PORT # - export ETCD_PEER_PORT # - export ETCD_DATA_DIR # - export API_BIND_HOST # - export API_HOST # - export API_PORT # - export API_SCHEME # - export SERVER_CONFIG_DIR # - export MASTER_CONFIG_DIR # - export NODE_CONFIG_DIR # - export USE_IMAGES # - export TAG function os::util::environment::setup_all_server_vars() { local subtempdir=$1 os::util::environment::setup_tmpdir_vars "${subtempdir}" os::util::environment::setup_kubelet_vars os::util::environment::setup_etcd_vars os::util::environment::setup_server_vars os::util::environment::setup_images_vars } readonly -f os::util::environment::setup_all_server_vars # os::util::environment::update_path_var updates $PATH so that OpenShift binaries are available # # Globals: # - OS_ROOT # - PATH # Arguments: # None # Returns: # - export PATH function os::util::environment::update_path_var() { PATH="${OS_OUTPUT_BINPATH}/$(os::util::host_platform):${PATH}" export PATH } readonly -f os::util::environment::update_path_var # os::util::environment::setup_tmpdir_vars sets up temporary directory path variables # # Globals: # - TMPDIR # - LOG_DIR # - ARTIFACT_DIR # - USE_SUDO # Arguments: # - 1: the path under the root temporary directory for OpenShift where these subdirectories should be made # Returns: # - export BASETMPDIR # - export LOG_DIR # - export VOLUME_DIR # - export ARTIFACT_DIR # - export FAKE_HOME_DIR # - export HOME function os::util::environment::setup_tmpdir_vars() { local sub_dir=$1 BASETMPDIR="${TMPDIR:-/tmp}/openshift/${sub_dir}" export BASETMPDIR LOG_DIR="${LOG_DIR:-${BASETMPDIR}/logs}" export LOG_DIR VOLUME_DIR="${BASETMPDIR}/volumes" export VOLUME_DIR ARTIFACT_DIR="${ARTIFACT_DIR:-${BASETMPDIR}/artifacts}" export ARTIFACT_DIR # change the location of $HOME so no one does anything naughty FAKE_HOME_DIR="${BASETMPDIR}/openshift.local.home" export FAKE_HOME_DIR HOME="${FAKE_HOME_DIR}" export HOME # ensure that the directories are clean for target in $( ${USE_SUDO:+sudo} findmnt --output TARGET --list ); do if [[ "${target}" == "${BASETMPDIR}"* ]]; then ${USE_SUDO:+sudo} umount "${target}" fi done for directory in "${BASETMPDIR}" "${LOG_DIR}" "${VOLUME_DIR}" "${ARTIFACT_DIR}" "${HOME}"; do ${USE_SUDO:+sudo} rm -rf "${directory}" mkdir -p "${directory}" done } readonly -f os::util::environment::setup_tmpdir_vars # os::util::environment::setup_kubelet_vars sets up environment variables necessary for interacting with the kubelet # # Globals: # - KUBELET_SCHEME # - KUBELET_BIND_HOST # - KUBELET_HOST # - KUBELET_PORT # Arguments: # None # Returns: # - export KUBELET_SCHEME # - export KUBELET_BIND_HOST # - export KUBELET_HOST # - export KUBELET_PORT function os::util::environment::setup_kubelet_vars() { KUBELET_SCHEME="${KUBELET_SCHEME:-https}" export KUBELET_SCHEME KUBELET_BIND_HOST="${KUBELET_BIND_HOST:-$(openshift start --print-ip || echo "127.0.0.1")}" export KUBELET_BIND_HOST KUBELET_HOST="${KUBELET_HOST:-${KUBELET_BIND_HOST}}" export KUBELET_HOST KUBELET_PORT="${KUBELET_PORT:-10250}" export KUBELET_PORT } readonly -f os::util::environment::setup_kubelet_vars # os::util::environment::setup_etcd_vars sets up environment variables necessary for interacting with etcd # # Globals: # - BASETMPDIR # - ETCD_HOST # - ETCD_PORT # - ETCD_PEER_PORT # Arguments: # None # Returns: # - export ETCD_HOST # - export ETCD_PORT # - export ETCD_PEER_PORT # - export ETCD_DATA_DIR function os::util::environment::setup_etcd_vars() { ETCD_HOST="${ETCD_HOST:-127.0.0.1}" export ETCD_HOST ETCD_PORT="${ETCD_PORT:-4001}" export ETCD_PORT ETCD_PEER_PORT="${ETCD_PEER_PORT:-7001}" export ETCD_PEER_PORT ETCD_DATA_DIR="${BASETMPDIR}/etcd" export ETCD_DATA_DIR mkdir -p "${ETCD_DATA_DIR}" } readonly -f os::util::environment::setup_etcd_vars # os::util::environment::setup_server_vars sets up environment variables necessary for interacting with the server # # Globals: # - BASETMPDIR # - KUBELET_HOST # - API_BIND_HOST # - API_HOST # - API_PORT # - API_SCHEME # - PUBLIC_MASTER_HOST # Arguments: # None # Returns: # - export API_BIND_HOST # - export API_HOST # - export API_PORT # - export API_SCHEME # - export SERVER_CONFIG_DIR # - export MASTER_CONFIG_DIR # - export NODE_CONFIG_DIR function os::util::environment::setup_server_vars() { # turn on cache mutation detector every time we start a server KUBE_CACHE_MUTATION_DETECTOR="${KUBE_CACHE_MUTATION_DETECTOR:-true}" export KUBE_CACHE_MUTATION_DETECTOR API_BIND_HOST="${API_BIND_HOST:-$(openshift start --print-ip || echo "127.0.0.1")}" export API_BIND_HOST API_HOST="${API_HOST:-${API_BIND_HOST}}" export API_HOST API_PORT="${API_PORT:-8443}" export API_PORT API_SCHEME="${API_SCHEME:-https}" export API_SCHEME MASTER_ADDR="${API_SCHEME}://${API_HOST}:${API_PORT}" export MASTER_ADDR PUBLIC_MASTER_HOST="${PUBLIC_MASTER_HOST:-${API_HOST}}" export PUBLIC_MASTER_HOST SERVER_CONFIG_DIR="${BASETMPDIR}/openshift.local.config" export SERVER_CONFIG_DIR MASTER_CONFIG_DIR="${SERVER_CONFIG_DIR}/master" export MASTER_CONFIG_DIR NODE_CONFIG_DIR="${SERVER_CONFIG_DIR}/node-${KUBELET_HOST}" export NODE_CONFIG_DIR mkdir -p "${SERVER_CONFIG_DIR}" "${MASTER_CONFIG_DIR}" "${NODE_CONFIG_DIR}" } readonly -f os::util::environment::setup_server_vars # os::util::environment::setup_images_vars sets up environment variables necessary for interacting with release images # # Globals: # - OS_ROOT # - USE_IMAGES # Arguments: # None # Returns: # - export USE_IMAGES # - export TAG # - export MAX_IMAGES_BULK_IMPORTED_PER_REPOSITORY function os::util::environment::setup_images_vars() { # Use either the latest release built images, or latest. if [[ -z "${USE_IMAGES-}" ]]; then TAG='latest' export TAG USE_IMAGES="openshift/origin-\${component}:latest" export USE_IMAGES if [[ -e "${OS_ROOT}/_output/local/releases/.commit" ]]; then TAG="$(cat "${OS_ROOT}/_output/local/releases/.commit")" export TAG USE_IMAGES="openshift/origin-\${component}:${TAG}" export USE_IMAGES fi fi export MAX_IMAGES_BULK_IMPORTED_PER_REPOSITORY="${MAX_IMAGES_BULK_IMPORTED_PER_REPOSITORY:-3}" } readonly -f os::util::environment::setup_images_vars
{ "content_hash": "3fafbc46efab269db21d43a9e64e71d3", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 133, "avg_line_length": 28.666666666666668, "alnum_prop": 0.6646462147451756, "repo_name": "chmouel/origin", "id": "a57866bc240b91aa1ed87340072353a958af7d5c", "size": "8444", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hack/lib/util/environment.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "921" }, { "name": "DIGITAL Command Language", "bytes": "117" }, { "name": "Go", "bytes": "13144121" }, { "name": "Groff", "bytes": "2049" }, { "name": "Makefile", "bytes": "8481" }, { "name": "Protocol Buffer", "bytes": "542565" }, { "name": "Python", "bytes": "16665" }, { "name": "Ruby", "bytes": "363" }, { "name": "Shell", "bytes": "2332694" } ], "symlink_target": "" }
// Package welcome implements a prow plugin to welcome new contributors package welcome import ( "bytes" "fmt" "html/template" "strings" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/pluginhelp" "k8s.io/test-infra/prow/plugins" ) const ( pluginName = "welcome" defaultWelcomeMessage = "Welcome @{{.AuthorLogin}}! It looks like this is your first PR to {{.Org}}/{{.Repo}} 🎉" ) // PRInfo contains info used provided to the welcome message template type PRInfo struct { Org string Repo string AuthorLogin string AuthorName string } func init() { plugins.RegisterPullRequestHandler(pluginName, handlePullRequest, helpProvider) } func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) { welcomeConfig := map[string]string{} for _, repo := range enabledRepos { parts := strings.Split(repo, "/") var messageTemplate string switch len(parts) { case 1: messageTemplate = welcomeMessageForRepo(config, repo, "") case 2: messageTemplate = welcomeMessageForRepo(config, parts[0], parts[1]) default: return nil, fmt.Errorf("invalid repo in enabledRepos: %q", repo) } welcomeConfig[repo] = fmt.Sprintf("The welcome plugin is configured to post using following welcome template: %s.", messageTemplate) } // The {WhoCanUse, Usage, Examples} fields are omitted because this plugin is not triggered with commands. return &pluginhelp.PluginHelp{ Description: "The welcome plugin posts a welcoming message when it detects a user's first contribution to a repo.", Config: welcomeConfig, }, nil } type githubClient interface { CreateComment(owner, repo string, number int, comment string) error FindIssues(query, sort string, asc bool) ([]github.Issue, error) } type client struct { GitHubClient githubClient Logger *logrus.Entry } func getClient(pc plugins.Agent) client { return client{ GitHubClient: pc.GitHubClient, Logger: pc.Logger, } } func handlePullRequest(pc plugins.Agent, pre github.PullRequestEvent) error { return handlePR(getClient(pc), pre, welcomeMessageForRepo(pc.PluginConfig, pre.Repo.Owner.Login, pre.Repo.Name)) } func handlePR(c client, pre github.PullRequestEvent, welcomeTemplate string) error { // Only consider newly opened PRs if pre.Action != github.PullRequestActionOpened { return nil } // search for PRs from the author in this repo org := pre.PullRequest.Base.Repo.Owner.Login repo := pre.PullRequest.Base.Repo.Name user := pre.PullRequest.User.Login query := fmt.Sprintf("is:pr repo:%s/%s author:%s", org, repo, user) issues, err := c.GitHubClient.FindIssues(query, "", false) if err != nil { return err } // if there are no results, this is the first! post the welcome comment if len(issues) == 0 || len(issues) == 1 && issues[0].Number == pre.Number { // load the template, and run it over the PR info parsedTemplate, err := template.New("welcome").Parse(welcomeTemplate) if err != nil { return err } var msgBuffer bytes.Buffer err = parsedTemplate.Execute(&msgBuffer, PRInfo{ Org: org, Repo: repo, AuthorLogin: user, AuthorName: pre.PullRequest.User.Name, }) if err != nil { return err } // actually post the comment return c.GitHubClient.CreateComment(org, repo, pre.PullRequest.Number, msgBuffer.String()) } return nil } func welcomeMessageForRepo(config *plugins.Configuration, org, repo string) string { opts := optionsForRepo(config, org, repo) if opts.MessageTemplate != "" { return opts.MessageTemplate } return defaultWelcomeMessage } // optionsForRepo gets the plugins.Welcome struct that is applicable to the indicated repo. func optionsForRepo(config *plugins.Configuration, org, repo string) *plugins.Welcome { fullName := fmt.Sprintf("%s/%s", org, repo) // First search for repo config for _, c := range config.Welcome { if !strInSlice(fullName, c.Repos) { continue } return &c } // If you don't find anything, loop again looking for an org config for _, c := range config.Welcome { if !strInSlice(org, c.Repos) { continue } return &c } // Return an empty config, and default to defaultWelcomeMessage return &plugins.Welcome{} } func strInSlice(str string, slice []string) bool { for _, elem := range slice { if elem == str { return true } } return false }
{ "content_hash": "0263b9267249b7f6463d621286544304", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 134, "avg_line_length": 27.490683229813666, "alnum_prop": 0.7119295074559422, "repo_name": "lavalamp/test-infra", "id": "28937baaf346dd856a6539e333dade127fcfb8b5", "size": "4998", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "prow/plugins/welcome/welcome.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "33021" }, { "name": "Dockerfile", "bytes": "31806" }, { "name": "Go", "bytes": "5061108" }, { "name": "HTML", "bytes": "54898" }, { "name": "JavaScript", "bytes": "74872" }, { "name": "Makefile", "bytes": "34958" }, { "name": "Python", "bytes": "1079244" }, { "name": "Shell", "bytes": "139373" }, { "name": "TypeScript", "bytes": "175375" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/progressbar" android:orientation="vertical" android:background="@color/colorPrimary" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" android:layout_marginTop="?attr/actionBarSize"> <ProgressBar style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center|center_horizontal|center_vertical" android:layout_marginBottom="8dp" /> </LinearLayout>
{ "content_hash": "4b16d37a84d84dc3dcf544a011dce634", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 73, "avg_line_length": 40.35294117647059, "alnum_prop": 0.7084548104956269, "repo_name": "joaoibarra/moclimao", "id": "16e91f5c5034cfb5070747734c7aef00a068db59", "size": "686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/content_progressbar.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "31123" } ], "symlink_target": "" }
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/storagetransfer/v1/transfer_types.proto namespace Google\Cloud\StorageTransfer\V1; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * A summary of errors by error code, plus a count and sample error log * entries. * * Generated from protobuf message <code>google.storagetransfer.v1.ErrorSummary</code> */ class ErrorSummary extends \Google\Protobuf\Internal\Message { /** * Required. * * Generated from protobuf field <code>.google.rpc.Code error_code = 1 [(.google.api.field_behavior) = REQUIRED];</code> */ private $error_code = 0; /** * Required. Count of this type of error. * * Generated from protobuf field <code>int64 error_count = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ private $error_count = 0; /** * Error samples. * At most 5 error log entries are recorded for a given * error code for a single transfer operation. * * Generated from protobuf field <code>repeated .google.storagetransfer.v1.ErrorLogEntry error_log_entries = 3;</code> */ private $error_log_entries; /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * @type int $error_code * Required. * @type int|string $error_count * Required. Count of this type of error. * @type array<\Google\Cloud\StorageTransfer\V1\ErrorLogEntry>|\Google\Protobuf\Internal\RepeatedField $error_log_entries * Error samples. * At most 5 error log entries are recorded for a given * error code for a single transfer operation. * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Storagetransfer\V1\TransferTypes::initOnce(); parent::__construct($data); } /** * Required. * * Generated from protobuf field <code>.google.rpc.Code error_code = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return int */ public function getErrorCode() { return $this->error_code; } /** * Required. * * Generated from protobuf field <code>.google.rpc.Code error_code = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param int $var * @return $this */ public function setErrorCode($var) { GPBUtil::checkEnum($var, \Google\Rpc\Code::class); $this->error_code = $var; return $this; } /** * Required. Count of this type of error. * * Generated from protobuf field <code>int64 error_count = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return int|string */ public function getErrorCount() { return $this->error_count; } /** * Required. Count of this type of error. * * Generated from protobuf field <code>int64 error_count = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @param int|string $var * @return $this */ public function setErrorCount($var) { GPBUtil::checkInt64($var); $this->error_count = $var; return $this; } /** * Error samples. * At most 5 error log entries are recorded for a given * error code for a single transfer operation. * * Generated from protobuf field <code>repeated .google.storagetransfer.v1.ErrorLogEntry error_log_entries = 3;</code> * @return \Google\Protobuf\Internal\RepeatedField */ public function getErrorLogEntries() { return $this->error_log_entries; } /** * Error samples. * At most 5 error log entries are recorded for a given * error code for a single transfer operation. * * Generated from protobuf field <code>repeated .google.storagetransfer.v1.ErrorLogEntry error_log_entries = 3;</code> * @param array<\Google\Cloud\StorageTransfer\V1\ErrorLogEntry>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setErrorLogEntries($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\StorageTransfer\V1\ErrorLogEntry::class); $this->error_log_entries = $arr; return $this; } }
{ "content_hash": "e3413698a2e5a4119202b7dcdc328a54", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 148, "avg_line_length": 30.90277777777778, "alnum_prop": 0.6271910112359551, "repo_name": "googleapis/google-cloud-php-storage-transfer", "id": "8e51ed1dc46bbd41efb2f6bd4047111ee90decf4", "size": "4450", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "src/V1/ErrorSummary.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "114631" }, { "name": "Python", "bytes": "3020" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_02) on Wed Oct 17 22:44:35 PDT 2012 --> <title>All Classes</title> <meta name="date" content="2012-10-17"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <h1 class="bar">All Classes</h1> <div class="indexContainer"> <ul> <li><a href="com/stevenmz/project1/domainTypes/Address.html" title="class in com.stevenmz.project1.domainTypes">Address</a></li> <li><a href="com/stevenmz/project1/domainTypes/AddressBook.html" title="class in com.stevenmz.project1.domainTypes">AddressBook</a></li> <li><a href="com/stevenmz/project1/applicationRunners/AddressBookApplication.html" title="class in com.stevenmz.project1.applicationRunners">AddressBookApplication</a></li> <li><a href="com/stevenmz/project1/tests/AddressBookTest.html" title="class in com.stevenmz.project1.tests">AddressBookTest</a></li> <li><a href="com/stevenmz/project1/domainTypes/AddressEntry.html" title="class in com.stevenmz.project1.domainTypes">AddressEntry</a></li> <li><a href="com/stevenmz/project1/comparators/AddressEntryComparator.html" title="class in com.stevenmz.project1.comparators">AddressEntryComparator</a></li> <li><a href="com/stevenmz/project1/tests/AddressEntryComparatorTest.html" title="class in com.stevenmz.project1.tests">AddressEntryComparatorTest</a></li> <li><a href="com/stevenmz/project1/tests/AddressEntryTest.html" title="class in com.stevenmz.project1.tests">AddressEntryTest</a></li> <li><a href="com/stevenmz/project1/tests/AddressTest.html" title="class in com.stevenmz.project1.tests">AddressTest</a></li> <li><a href="com/stevenmz/project1/domainTypes/Menu.html" title="class in com.stevenmz.project1.domainTypes">Menu</a></li> <li><a href="com/stevenmz/project1/tests/MenuTest.html" title="class in com.stevenmz.project1.tests">MenuTest</a></li> </ul> </div> </body> </html>
{ "content_hash": "4fae16f6a09a617e79ab1b0c1ced3338", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 172, "avg_line_length": 72.64285714285714, "alnum_prop": 0.7482792527040315, "repo_name": "stevenmz/DatabaseContactBook", "id": "4c45f201e69abfc6e272da791d3cfca4603b54a8", "size": "2034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/allclasses-noframe.html", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "104759" } ], "symlink_target": "" }
namespace ServicoDeBooking.Areas.HelpPage.ModelDescriptions { public class SimpleTypeModelDescription : ModelDescription { } }
{ "content_hash": "9c5cee2f6eb26dcfb6d1c7693d74f945", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 62, "avg_line_length": 23, "alnum_prop": 0.782608695652174, "repo_name": "fabiomargarito/ExemplosCursoFundamentosEmArquiteturaDeSoftware", "id": "fee0f809cbbb29f77a245d1216a631d7c55940ab", "size": "138", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Curso DDD/src/ExemploDDDTurmaOnline1/MBCorpHealthTest/ServicoDeBooking/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "60786" }, { "name": "C#", "bytes": "1598576" }, { "name": "CSS", "bytes": "22339" }, { "name": "HTML", "bytes": "56261" }, { "name": "JavaScript", "bytes": "597751" }, { "name": "PowerShell", "bytes": "150803" } ], "symlink_target": "" }
AddRectState = AbstractState:extends{} function AddRectState:enterState() AbstractState.enterState(self) SB.SetGlobalRenderingFunction(function(...) self:__DrawInfo(...) end) end function AddRectState:leaveState() AbstractState.leaveState(self) SB.SetGlobalRenderingFunction(nil) end function AddRectState:MousePress(mx, my, button) if button == 1 then if self.addSecondPoint then return end local result, coords = Spring.TraceScreenRay(mx, my, true) if result == "ground" then self.startX = coords[1] self.startZ = coords[3] self.endX = coords[1] self.endZ = coords[3] self.addSecondPoint = true return true end else SB.stateManager:SetState(DefaultState()) end end function AddRectState:MouseMove(mx, my, mdx, mdy, button) if not self.addSecondPoint then return end local result, coords = Spring.TraceScreenRay(mx, my, true) if result == "ground" then self.endX = coords[1] self.endZ = coords[3] end end function AddRectState:MouseRelease(mx, my, button) if not self.addSecondPoint then return end if button ~= 1 then return end local result, coords = Spring.TraceScreenRay(mx, my, true) if result == "ground" then self.endX = coords[1] self.endZ = coords[3] end if self.endX == nil or self.endZ == nil then return end local cmd = AddObjectCommand(areaBridge.name, { pos = { x = (self.startX + self.endX)/2, y = 0, z = (self.startZ + self.endZ)/2}, size = { x = math.abs(self.endX - self.startX), y = 0, z = math.abs(self.endZ - self.startZ)}, }) SB.commandManager:execute(cmd) SB.stateManager:SetState(DefaultState()) end function AddRectState:DrawWorld() gl.PushMatrix() gl.Color(0, 1, 0, 0.2) if self.addSecondPoint then areaBridge.DrawObject(nil, {self.startX, self.startZ, self.endX, self.endZ}) end gl.PopMatrix() end function AddRectState:__GetInfoText() return "Add area" end local _displayColor = {1.0, 0.7, 0.1, 0.8} function AddRectState:__DrawInfo() if not self.__displayFont then self.__displayFont = Chili.Font:New { size = 12, color = _displayColor, outline = true, } end local mx, my, _, _, _, outsideSpring = Spring.GetMouseState() -- Don't draw if outside Spring if outsideSpring then return true end local _, vsy = Spring.GetViewGeometry() local x = mx local y = vsy - my - 30 self.__displayFont:Draw(self:__GetInfoText(), x, y) -- return true to keep redrawing return true end
{ "content_hash": "432e7dcd7aabc2ed9382aab845e8a99b", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 102, "avg_line_length": 24.839285714285715, "alnum_prop": 0.6132278936017254, "repo_name": "Spring-SpringBoard/SpringBoard-Core", "id": "b6cbacc5777b3bf8a5158e914d0e44aa7655bb7f", "size": "2782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scen_edit/state/add_rect_state.lua", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "39517" }, { "name": "JavaScript", "bytes": "12585" }, { "name": "Jupyter Notebook", "bytes": "9164" }, { "name": "Lua", "bytes": "1311716" }, { "name": "Python", "bytes": "306" } ], "symlink_target": "" }
'''OpenGL extension SUNX.constant_data Automatically generated by the get_gl_extensions script, do not edit! ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions from OpenGL.GL import glget import ctypes EXTENSION_NAME = 'GL_SUNX_constant_data' _DEPRECATED = False GL_UNPACK_CONSTANT_DATA_SUNX = constant.Constant( 'GL_UNPACK_CONSTANT_DATA_SUNX', 0x81D5 ) GL_TEXTURE_CONSTANT_DATA_SUNX = constant.Constant( 'GL_TEXTURE_CONSTANT_DATA_SUNX', 0x81D6 ) glFinishTextureSUNX = platform.createExtensionFunction( 'glFinishTextureSUNX',dll=platform.GL, extension=EXTENSION_NAME, resultType=None, argTypes=(), doc='glFinishTextureSUNX() -> None', argNames=(), deprecated=_DEPRECATED, ) def glInitConstantDataSUNX(): '''Return boolean indicating whether this extension is available''' return extensions.hasGLExtension( EXTENSION_NAME )
{ "content_hash": "25fbd6acb849fa0412e60ffb77d0f2c7", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 92, "avg_line_length": 33.69230769230769, "alnum_prop": 0.7831050228310502, "repo_name": "Universal-Model-Converter/UMC3.0a", "id": "a609ab2d2abd58ab756da710cb282451f9315dea", "size": "876", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "data/Python/x86/Lib/site-packages/OpenGL/raw/GL/SUNX/constant_data.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "226" }, { "name": "C", "bytes": "1082640" }, { "name": "C#", "bytes": "8440" }, { "name": "C++", "bytes": "3621086" }, { "name": "CSS", "bytes": "6226" }, { "name": "F#", "bytes": "2310" }, { "name": "FORTRAN", "bytes": "7795" }, { "name": "Forth", "bytes": "506" }, { "name": "GLSL", "bytes": "1040" }, { "name": "Groff", "bytes": "5943" }, { "name": "HTML", "bytes": "1196266" }, { "name": "Java", "bytes": "5793" }, { "name": "Makefile", "bytes": "1109" }, { "name": "Mask", "bytes": "969" }, { "name": "Matlab", "bytes": "4346" }, { "name": "Python", "bytes": "33351557" }, { "name": "R", "bytes": "1370" }, { "name": "Shell", "bytes": "6931" }, { "name": "Tcl", "bytes": "2084458" }, { "name": "Visual Basic", "bytes": "481" } ], "symlink_target": "" }
/** * Created by Mauriel on 3/28/2017. */ var coordinatesPicker; var currentInstance; // Keeps track of the instance to work with var allOverlays = []; var drawingManager; (function( $ ){ $.fn.coordinatesPicker = function () { // If component already initiated, return if ($(this).hasClass("has-coordinates-picker")) { return this; } var items = $(this).find("input[data-map-item]"); items.each(function () { var item = $(this); // Wrap the element and append a button next to it to trigger the map modal // The button adapts to the size of the input (bootstrap classes: input-sm and input-lg) if (item.hasClass("input-sm")) { item.wrap('<div class="input-group input-group-sm"></div>'); } else if (item.hasClass("input-lg")) { item.wrap('<div class="input-group input-group-lg"></div>'); } else { item.wrap('<div class="input-group"></div>'); } item.parent().append('<span class="input-group-btn btn-choose-coordinates" title="Choose coordinates">' + '<span class="btn btn-default" type="button">' + '<i class="fa fa-map-marker" aria-hidden="true"></i>' + '</span>' + '</span>'); item.toggleClass("form-control", true); // Map trigger event handler item.parent().find(".btn-choose-coordinates").click(function () { currentInstance = item.closest("[data-coordinates-type]"); var type = currentInstance.attr("data-coordinates-type"); // Set the type of controls if (type == "point") { drawingManager.drawingControlOptions.drawingModes = [ google.maps.drawing.OverlayType.MARKER ]; drawingManager.drawingMode = null; // Set the default hand control drawingManager.setMap(coordinatesPicker); } else if (type == "rectangle") { drawingManager.drawingControlOptions.drawingModes = [ google.maps.drawing.OverlayType.RECTANGLE ]; drawingManager.drawingMode = null; // Set the default hand control drawingManager.setMap(coordinatesPicker); } // Delete previous drawings for (var i = 0; i < allOverlays.length; i++) { allOverlays[i].overlay.setMap(null); } allOverlays = []; // Set default behavior. It is overridden once coordinates are selected. $("#btn-confirm-coordinates").unbind("click"); $("#btn-confirm-coordinates").click(function () { $('#coordinates-picker-modal').modal('hide') }); $("#coordinates-picker-modal").modal("show"); }); }); $(this).addClass("has-coordinates-picker"); return this; }; })( jQuery ); $(document).ready(function () { $('#coordinates-picker-modal').on('shown.bs.modal', function () { google.maps.event.trigger(coordinatesPicker, 'resize'); }); // Initialize Map coordinatesPicker = new google.maps.Map(document.getElementById('picker-map-container'), { zoom: 3, streetViewControl: false, center: {lat: 41.850033, lng: -87.6500523}, // Default center mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, mapTypeIds: [ google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE ], position: google.maps.ControlPosition.TOP_RIGHT } }); drawingManager = new google.maps.drawing.DrawingManager({ drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, }, rectangleOptions: { editable: true, draggable: true } }); drawingManager.setMap(coordinatesPicker); // When a rectangle is drawn google.maps.event.addListener(drawingManager, 'rectanglecomplete', function (rectangle) { var coordinates = (rectangle.getBounds()); processDrawing(coordinates, "rectangle"); // When this rectangle is modified rectangle.addListener('bounds_changed', function () { var coordinates = (rectangle.getBounds()); processDrawing(coordinates, "rectangle"); }); }); // When a point is selected google.maps.event.addListener(drawingManager, 'markercomplete', function (marker) { var coordinates = (marker.getPosition()); processDrawing(coordinates, "marker"); }); google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) { allOverlays.push(e); }); function processDrawing(coordinates, shape) { // Delete previous drawings if (allOverlays.length > 1) { for (var i = 1; i < allOverlays.length; i++) { allOverlays[i - 1].overlay.setMap(null); } allOverlays.shift(); } if (shape == "rectangle") { var bounds = { north: parseFloat(coordinates.getNorthEast().lat()), south: parseFloat(coordinates.getSouthWest().lat()), east: parseFloat(coordinates.getNorthEast().lng()), west: parseFloat(coordinates.getSouthWest().lng()) }; $("#btn-confirm-coordinates").unbind("click"); $("#btn-confirm-coordinates").click(function () { currentInstance.find("input[data-map-item='northlimit']").val(bounds.north.toFixed(4)); currentInstance.find("input[data-map-item='eastlimit']").val(bounds.east.toFixed(4)); currentInstance.find("input[data-map-item='southlimit']").val(bounds.south.toFixed(4)); currentInstance.find("input[data-map-item='westlimit']").val(bounds.west.toFixed(4)); $('#coordinates-picker-modal').modal('hide') }); } else { $("#btn-confirm-coordinates").unbind("click"); $("#btn-confirm-coordinates").click(function () { currentInstance.find("input[data-map-item='longitude']").val(coordinates.lng().toFixed(4)); currentInstance.find("input[data-map-item='latitude']").val(coordinates.lat().toFixed(4)); $('#coordinates-picker-modal').modal('hide') }); } } $(".hs-coordinates-picker").each(function() { const instance = $(this); instance.coordinatesPicker(); }) });
{ "content_hash": "0bb5744beb8c505c22a0b8650e0dd72b", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 117, "avg_line_length": 38.2967032967033, "alnum_prop": 0.5516499282639885, "repo_name": "RENCI/xDCIShare", "id": "bc443c426b8db2a2f8f6da900dac80f5d88665eb", "size": "6970", "binary": false, "copies": "1", "ref": "refs/heads/xdci-develop", "path": "theme/static/js/coordinates-picker.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "381782" }, { "name": "HTML", "bytes": "964877" }, { "name": "JavaScript", "bytes": "2011819" }, { "name": "Python", "bytes": "4334769" }, { "name": "R", "bytes": "4472" }, { "name": "Shell", "bytes": "52665" }, { "name": "XSLT", "bytes": "790987" } ], "symlink_target": "" }
package sim.app.guidedps.agents; import sim.app.guidedps.gridworld.State; public class Demonstration { State s; int a; public Demonstration(State s, int a) { this.s = s; this.a = a; } @Override public boolean equals(Object obj) { Demonstration that = (Demonstration)obj; if(that.s.equals(this.s)&&that.a==this.a) return true; return false; } @Override public int hashCode() { return 100*s.hashCode() + a; } }
{ "content_hash": "9e66adce6b4324643840b2279f9e2f15", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 43, "avg_line_length": 17, "alnum_prop": 0.6742081447963801, "repo_name": "nosyndicate/GuidedPS", "id": "22ad12a5e53db217d2714215b11ee09c105b554d", "size": "442", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sim/app/guidedps/agents/Demonstration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "59372" }, { "name": "TeX", "bytes": "4965" } ], "symlink_target": "" }
import React, {Component} from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import {connect} from 'react-redux'; import PropTypes from 'prop-types'; import '../../../style/component/page/common.css'; import InfoID from './InfoID'; import ProduceIndex from './ProduceIndex'; class ProducePage extends Component{ constructor(props){ super(props); this.state = { current: '' } this.handleClick = this.handleClick.bind(this); } handleClick(event){ let elem = event.currentTarget; if(this.state.current != elem){ this.state.current.className = ''; elem.className = 'current'; this.setState({ current: elem }); } } componentDidMount(){ this.setState({ current: this.init }); } render(){ const {isSmall} = this.props; return ( <div className='main'> {!isSmall && <div> <div className='sub_sidebar'> <div className='cover_layer'></div> <ul className="sub_sidebar_list" > <li className='current'onClick={this.handleClick} ref={(input) => {this.init = input}}> <Link className='link' to={`${this.props.match.url}/silage`}>青贮产品</Link> </li> <li onClick={this.handleClick}><Link className='link' to={`${this.props.match.url}/yellow`}>黄贮产品</Link></li> <li onClick={this.handleClick}><Link className='link' to={`${this.props.match.url}/lucerne`}>紫花苜蓿青贮</Link></li> <li onClick={this.handleClick}><Link className='link' to={`${this.props.match.url}/pack`}>打包技术</Link></li> </ul> </div> <div className="article_content"> <Route path={`${this.props.match.url}/:infoID`} component={InfoID} /> <Route exact path={`${this.props.match.url}`} component={ProduceIndex}/> </div> </div> } {isSmall && <div className="mobile_page"> <ProduceIndex /> </div> } </div> ); } } ProducePage.propTypes = { isSmall: PropTypes.bool.isRequired } const mapStateToProps = (state, ownProps) => { const isSmall = state.screen.isSmall; return { isSmall } } const Produce = connect(mapStateToProps)(ProducePage); export default Produce;
{ "content_hash": "a819ecd4071b1e796f8fab2b3a7b4c57", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 125, "avg_line_length": 28.621951219512194, "alnum_prop": 0.57988922028121, "repo_name": "lujinming1/hejicaoye", "id": "feac2f6bf9d1af7885a8cd61d65cadef77d297e7", "size": "2383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/component/page/produce/Produce.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5677" }, { "name": "HTML", "bytes": "2218" }, { "name": "JavaScript", "bytes": "24283" } ], "symlink_target": "" }
p html, body { height: 100%; width: 100%; } body { font-family: 'Merriweather', 'Helvetica Neue', Arial, sans-serif; } hr { border-color: #F05F40; border-width: 3px; max-width: 50px; } hr.light { border-color: white; } a { -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; color: #F05F40; } a:hover, a:focus { color: #eb3812; } h1, h2, h3, h4, h5, h6 { font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; } p { font-size: 16px; line-height: 1.5; margin-bottom: 20px; } .bg-primary { background-color: #F05F40; } .bg-dark { background-color: #222222; color: white; } .text-faded { color: rgba(255, 255, 255, 0.7); } section { padding: 100px 0; } aside { padding: 50px 0; } .no-padding { padding: 0; } .navbar-default { background-color: white; border-color: rgba(34, 34, 34, 0.05); font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .navbar-default .navbar-header .navbar-brand { color: #F05F40; font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; font-weight: 700; text-transform: uppercase; } .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus { color: #eb3812; } .navbar-default .navbar-header .navbar-toggle { font-weight: 700; font-size: 12px; color: #222222; text-transform: uppercase; } .navbar-default .nav > li > a, .navbar-default .nav > li > a:focus { text-transform: uppercase; font-weight: 700; font-size: 13px; color: #222222; } .navbar-default .nav > li > a:hover, .navbar-default .nav > li > a:focus:hover { color: #F05F40; } .navbar-default .nav > li.active > a, .navbar-default .nav > li.active > a:focus { color: #F05F40 !important; background-color: transparent; } .navbar-default .nav > li.active > a:hover, .navbar-default .nav > li.active > a:focus:hover { background-color: transparent; } @media (min-width: 768px) { .navbar-default { background-color: transparent; border-color: rgba(255, 255, 255, 0.3); } .navbar-default .navbar-header .navbar-brand { color: rgba(255, 255, 255, 0.7); } .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus { color: white; } .navbar-default .nav > li > a, .navbar-default .nav > li > a:focus { color: rgba(255, 255, 255, 0.7); } .navbar-default .nav > li > a:hover, .navbar-default .nav > li > a:focus:hover { color: white; } .navbar-default.affix { background-color: white; border-color: rgba(34, 34, 34, 0.05); } .navbar-default.affix .navbar-header .navbar-brand { color: #F05F40; font-size: 14px; } .navbar-default.affix .navbar-header .navbar-brand:hover, .navbar-default.affix .navbar-header .navbar-brand:focus { color: #eb3812; } .navbar-default.affix .nav > li > a, .navbar-default.affix .nav > li > a:focus { color: #222222; } .navbar-default.affix .nav > li > a:hover, .navbar-default.affix .nav > li > a:focus:hover { color: #F05F40; } } header { position: relative; width: 100%; min-height: auto; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; background-position: center; background-image: url('../img/picture_1.jpg'); text-align: center; color: white; } header .header-content { position: relative; text-align: center; padding: 100px 15px 100px; width: 100%; } header .header-content .header-content-inner h1 { font-weight: 700; text-transform: uppercase; margin-top: 0; margin-bottom: 0; font-size: 30px; } header .header-content .header-content-inner hr { margin: 30px auto; } header .header-content .header-content-inner p { font-weight: 300; color: rgba(255, 255, 255, 0.7); font-size: 16px; margin-bottom: 50px; } @media (min-width: 768px) { header { min-height: 100%; } header .header-content { position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); padding: 0 50px; } header .header-content .header-content-inner { max-width: 1000px; margin-left: auto; margin-right: auto; } header .header-content .header-content-inner h1 { font-size: 50px; } header .header-content .header-content-inner p { font-size: 18px; max-width: 80%; margin-left: auto; margin-right: auto; } } .section-heading { margin-top: 0; } .service-box { max-width: 400px; margin: 50px auto 0; } @media (min-width: 992px) { .service-box { margin: 20px auto 0; } } .service-box p { margin-bottom: 0; } .port-box { position: relative; display: block; max-width: 650px; margin: 0 auto; } .portfolio-box .portfolio-box-caption { color: white; opacity: 0; display: block; background: rgba(240, 95, 64, 0.9); position: absolute; bottom: 0; text-align: center; width: 100%; height: 100%; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content { width: 100%; text-align: center; position: absolute; top: 50%; transform: translateY(-50%); } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category, .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; padding: 0 15px; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category { text-transform: uppercase; font-weight: 600; font-size: 14px; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-size: 18px; } .portfolio-box:hover .portfolio-box-caption { opacity: 1; } .portfolio-box:focus { outline: none; } @media (min-width: 768px) { .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category { font-size: 16px; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-size: 22px; } } .call-to-action h2 { margin: 0 auto 20px; } .text-primary { color: #F05F40; } .no-gutter > [class*='col-'] { padding-right: 0; padding-left: 0; } .btn-default { color: #222222; background-color: white; border-color: white; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .btn-default:hover, .btn-default:focus, .btn-default.focus, .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { color: #222222; background-color: #f2f2f2; border-color: #ededed; } .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { background-image: none; } .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, .btn-default.disabled:hover, .btn-default[disabled]:hover, fieldset[disabled] .btn-default:hover, .btn-default.disabled:focus, .btn-default[disabled]:focus, fieldset[disabled] .btn-default:focus, .btn-default.disabled.focus, .btn-default[disabled].focus, fieldset[disabled] .btn-default.focus, .btn-default.disabled:active, .btn-default[disabled]:active, fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { background-color: white; border-color: white; } .btn-default .badge { color: white; background-color: #222222; } .btn-primary { color: white; background-color: #F05F40; border-color: #F05F40; -webkit-transition: all 0.35s; -moz-transition: all 0.35s; transition: all 0.35s; } .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { color: white; background-color: #ee4b28; border-color: #ed431f; } .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { background-image: none; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled.focus, .btn-primary[disabled].focus, fieldset[disabled] .btn-primary.focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { background-color: #F05F40; border-color: #F05F40; } .btn-primary .badge { color: #F05F40; background-color: white; } .btn { font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; border: none; border-radius: 300px; font-weight: 700; text-transform: uppercase; } .btn-xl { padding: 15px 30px; } ::-moz-selection { color: white; text-shadow: none; background: #222222; } ::selection { color: white; text-shadow: none; background: #222222; } img::selection { color: white; background: transparent; } img::-moz-selection { color: white; background: transparent; } body { webkit-tap-highlight-color: #222222; }
{ "content_hash": "7ce7c58ac578923d677ad51ccec8fc29", "timestamp": "", "source": "github", "line_count": 412, "max_line_length": 90, "avg_line_length": 22.611650485436893, "alnum_prop": 0.6819450407900386, "repo_name": "rmladenov/rmladenov.github.io", "id": "c5d5cdf514b7dd54b05b26f1479e971acf476b57", "size": "9554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "css/creative.css", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "18287" }, { "name": "HTML", "bytes": "11563" }, { "name": "JavaScript", "bytes": "4918" } ], "symlink_target": "" }
package net.ihiroky.reservoir; import net.ihiroky.reservoir.accessor.HeapCacheAccessor; import net.ihiroky.reservoir.coder.JSONCoder; import net.ihiroky.reservoir.index.LRUIndex; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; /** * Created on 12/09/26, 16:49 * * @author Hiroki Itoh */ public class BasicCacheTest { private Set<BasicCache<?, ?>> disposeInAfterSet; @Before public void before() { disposeInAfterSet = new HashSet<BasicCache<?, ?>>(); } @After public void after() { for (BasicCache<?, ?> basicCache : disposeInAfterSet) { basicCache.dispose(); } } private <K, V> BasicCache<K, V> createBasicCache(int initialSize, int maxSize) { Index<K, Ref<V>> index = new LRUIndex<K, Ref<V>>(initialSize, maxSize); CacheAccessor<K, V> cacheAccessor = new HeapCacheAccessor<K, V>(); BasicCache<K, V> basicCache = new BasicCache<K, V>("test", index, cacheAccessor); disposeInAfterSet.add(basicCache); return basicCache; } @Test public void testPut() { BasicCache<Integer, Integer> basicCache = createBasicCache(32, Integer.MAX_VALUE); basicCache.put(1, 11); assertThat(basicCache.get(1), is(11)); assertThat(basicCache.size(), is(1)); basicCache.put(2, 22); assertThat(basicCache.get(2), is(22)); assertThat(basicCache.size(), is(2)); basicCache.put(2, 222); assertThat(basicCache.get(2), is(222)); assertThat(basicCache.size(), is(2)); } @Test public void testPutMulti() { BasicCache<Integer, Integer> basicCache = createBasicCache(32, Integer.MAX_VALUE); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(1, 11); map.put(2, 22); basicCache.put(map); assertThat(basicCache.get(map.keySet()), is(map)); assertThat(basicCache.size(), is(2)); map.clear(); map.put(2, 222); map.put(3, 333); basicCache.put(map); map.put(1, 11); assertThat(basicCache.get(map.keySet()), is(map)); assertThat(basicCache.size(), is(3)); } @Test public void testRemove() { BasicCache<Integer, Integer> basicCache = createBasicCache(32, Integer.MAX_VALUE); basicCache.remove(0); assertThat(basicCache.size(), is(0)); basicCache.put(1, 11); basicCache.put(2, 22); basicCache.put(3, 33); basicCache.remove(2); assertThat(basicCache.get(2), is(nullValue())); assertThat(basicCache.size(), is(2)); basicCache.remove(1); assertThat(basicCache.get(1), is(nullValue())); assertThat(basicCache.size(), is(1)); } @Test public void testRemoveMulti() { BasicCache<Integer, Integer> basicCache = createBasicCache(32, Integer.MAX_VALUE); basicCache.remove(new HashSet<Integer>(Arrays.asList(0, 1))); assertThat(basicCache.size(), is(0)); basicCache.put(1, 11); basicCache.put(2, 22); basicCache.put(3, 33); basicCache.put(4, 44); basicCache.remove(new HashSet<Integer>(Arrays.asList(2))); assertThat(basicCache.get(2), is(nullValue())); assertThat(basicCache.size(), is(3)); basicCache.remove(new HashSet<Integer>(Arrays.asList(1, 4))); assertThat(basicCache.get(1), is(nullValue())); assertThat(basicCache.get(4), is(nullValue())); assertThat(basicCache.size(), is(1)); } @Test public void testPoll() { BasicCache<Integer, Integer> basicCache = createBasicCache(32, Integer.MAX_VALUE); basicCache.remove(0); assertThat(basicCache.size(), is(0)); basicCache.put(1, 11); basicCache.put(2, 22); basicCache.put(3, 33); Integer ret = basicCache.poll(2); assertThat(ret, is(22)); assertThat(basicCache.get(2), is(nullValue())); assertThat(basicCache.size(), is(2)); ret = basicCache.poll(1); assertThat(ret, is(11)); assertThat(basicCache.get(1), is(nullValue())); assertThat(basicCache.size(), is(1)); } @Test public void testPollMulti() { BasicCache<Integer, Integer> basicCache = createBasicCache(32, Integer.MAX_VALUE); basicCache.remove(new HashSet<Integer>(Arrays.asList(0, 1))); assertThat(basicCache.size(), is(0)); basicCache.put(1, 11); basicCache.put(2, 22); basicCache.put(3, 33); basicCache.put(4, 44); Map<Integer, Integer> ret = basicCache.poll(new HashSet<Integer>(Arrays.asList(2))); assertThat(ret.get(2), is(22)); assertThat(ret.size(), is(1)); assertThat(basicCache.get(2), is(nullValue())); assertThat(basicCache.size(), is(3)); ret = basicCache.poll(new HashSet<Integer>(Arrays.asList(1, 4))); assertThat(ret.get(1), is(11)); assertThat(ret.get(4), is(44)); assertThat(ret.size(), is(2)); assertThat(basicCache.get(1), is(nullValue())); assertThat(basicCache.get(4), is(nullValue())); assertThat(basicCache.size(), is(1)); } @Test public void testClear() { BasicCache<Integer, Integer> basicCache = createBasicCache(32, Integer.MAX_VALUE); basicCache.clear(); assertThat(basicCache.size(), is(0)); basicCache.put(1, 11); basicCache.put(2, 22); basicCache.put(3, 33); basicCache.clear(); assertThat(basicCache.size(), is(0)); } @Test(timeout = 3000) public void testEventListener() throws Exception { BasicCache<Integer, Integer> basicCache = createBasicCache(3, 3); MockCacheEventListener<Integer, Integer> eventListener = new MockCacheEventListener<Integer, Integer>(); basicCache.addEventListener(eventListener); basicCache.put(1, 11); basicCache.put(2, 22); basicCache.remove(1); basicCache.put(3, 33); basicCache.put(1, 111); while (eventListener.argsList.size() != 5) { Thread.sleep(10); } MockCacheEventListener.Args<Integer, Integer> args = eventListener.argsList.get(0); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(1, 11))); args = eventListener.argsList.get(1); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(2, 22))); args = eventListener.argsList.get(2); assertThat(args.method, is(MockCacheEventListener.Method.REMOVE)); assertThat(args.entry, is(Pair.newImmutableEntry(1, 11))); args = eventListener.argsList.get(3); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(3, 33))); args = eventListener.argsList.get(4); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(1, 111))); eventListener.argsList.clear(); basicCache.put(4, 444); while (eventListener.argsList.size() != 2) { Thread.sleep(10); } args = eventListener.argsList.get(0); assertThat(args.method, is(MockCacheEventListener.Method.CACHE_OUT)); assertThat(args.entry, is(Pair.newImmutableEntry(2, 22))); args = eventListener.argsList.get(1); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(4, 444))); } @Test(timeout = 3000) public void testEventListenerMulti() throws Exception { BasicCache<Integer, Integer> basicCache = createBasicCache(3, 3); MockCacheEventListener<Integer, Integer> eventListener = new MockCacheEventListener<Integer, Integer>(); basicCache.addEventListener(eventListener); Map<Integer, Integer> put0 = new HashMap<Integer, Integer>(); put0.put(1, 11); put0.put(2, 22); put0.put(3, 33); Set<Integer> remove0 = new HashSet<Integer>(Arrays.asList(1, 2)); basicCache.put(put0); basicCache.remove(remove0); while (eventListener.argsList.size() != 5) { Thread.sleep(10); } MockCacheEventListener.Args<Integer, Integer> args = eventListener.argsList.get(0); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(1, 11))); args = eventListener.argsList.get(1); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(2, 22))); args = eventListener.argsList.get(2); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(3, 33))); args = eventListener.argsList.get(3); assertThat(args.method, is(MockCacheEventListener.Method.REMOVE)); assertThat(args.entry, is(Pair.newImmutableEntry(1, 11))); args = eventListener.argsList.get(4); assertThat(args.method, is(MockCacheEventListener.Method.REMOVE)); assertThat(args.entry, is(Pair.newImmutableEntry(2, 22))); assertThat(eventListener.argsList.size(), is(5)); basicCache.clear(); while (eventListener.argsList.size() != 6) { Thread.sleep(10); } eventListener.argsList.clear(); Map<Integer, Integer> put1 = new HashMap<Integer, Integer>(); put1.put(1, 111); put1.put(2, 222); put1.put(3, 333); put1.put(4, 444); put1.put(5, 555); basicCache.put(put1); while (eventListener.argsList.size() != 7) { Thread.sleep(10); } args = eventListener.argsList.get(0); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(1, 111))); args = eventListener.argsList.get(1); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(2, 222))); args = eventListener.argsList.get(2); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(3, 333))); args = eventListener.argsList.get(3); assertThat(args.method, is(MockCacheEventListener.Method.CACHE_OUT)); assertThat(args.entry, is(Pair.newImmutableEntry(1, 111))); args = eventListener.argsList.get(4); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(4, 444))); args = eventListener.argsList.get(5); assertThat(args.method, is(MockCacheEventListener.Method.CACHE_OUT)); assertThat(args.entry, is(Pair.newImmutableEntry(2, 222))); args = eventListener.argsList.get(6); assertThat(args.method, is(MockCacheEventListener.Method.PUT)); assertThat(args.entry, is(Pair.newImmutableEntry(5, 555))); assertThat(eventListener.argsList.size(), is(7)); } @Test public void testIterator() { BasicCache<Integer, Integer> basicCache = createBasicCache(3, 3); basicCache.put(0, 10); basicCache.put(1, 11); basicCache.put(2, 12); basicCache.put(3, 13); Iterator<Map.Entry<Integer, Integer>> iterator = basicCache.iterator(); List<Map.Entry<Integer, Integer>> resultList = new ArrayList<Map.Entry<Integer, Integer>>(); while (iterator.hasNext()) { resultList.add(iterator.next()); } Collections.sort(resultList, new Comparator<Map.Entry<Integer, Integer>>() { @Override public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return o1.getKey() - o2.getKey(); } }); assertThat(resultList.get(0), is(Pair.newImmutableEntry(1, 11))); assertThat(resultList.get(1), is(Pair.newImmutableEntry(2, 12))); assertThat(resultList.get(2), is(Pair.newImmutableEntry(3, 13))); assertThat(resultList.size(), is(3)); } private String json(int key, int value) { return "{\"k\":" + key + ",\"v\":" + value + "}"; } @Test public void testWriteTo() throws Exception { BasicCache<Integer, Integer> basicCache = createBasicCache(16, 16); for (int i = 0; i < 3; i++) { basicCache.put(i, i * i + i); } ByteArrayOutputStream out = new ByteArrayOutputStream(); basicCache.writeTo(out, new IntegerJSONCoder()); assertThat(out.toString("UTF-8"), is("[" + json(0, 0) + "," + json(1, 2) + "," + json(2, 6) + "]")); } @Test public void testReadFrom() throws Exception { ByteArrayInputStream in = new ByteArrayInputStream( ("[" + json(0, 0) + "," + json(1, 2) + "," + json(2, 6) + "]").getBytes("UTF-8")); BasicCache<Integer, Integer> basicCache = createBasicCache(16, 16); basicCache.readFrom(in, new IntegerJSONCoder()); assertThat(basicCache.get(0), is(0)); assertThat(basicCache.get(1), is(2)); assertThat(basicCache.get(2), is(6)); assertThat(basicCache.size(), is(3)); } } class IntegerJSONCoder extends JSONCoder<Integer, Integer> { @Override protected void writeKey(JsonWriter writer, Integer key) throws Exception { writer.setNumber(key); } @Override protected void writeValue(JsonWriter writer, Integer value) throws Exception { writer.setNumber(value); } @Override protected Integer readKey(JsonReader reader) throws Exception { return reader.getInt(); } @Override protected Integer readValue(JsonReader reader) throws Exception { return reader.getInt(); } @Override protected String toKeyString(Integer key) throws Exception { return String.valueOf(key); } @Override protected Integer toKey(String key) throws Exception { return Integer.parseInt(key); } }
{ "content_hash": "aaaef1662d58f76bf173ae052491ebab", "timestamp": "", "source": "github", "line_count": 390, "max_line_length": 112, "avg_line_length": 37.743589743589745, "alnum_prop": 0.6313858695652174, "repo_name": "ihiroky/reservoir", "id": "1c7c690f15ec19cc9bea2e2f33d14480d98c50be", "size": "14720", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/net/ihiroky/reservoir/BasicCacheTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "3149" }, { "name": "Java", "bytes": "351319" } ], "symlink_target": "" }
import logging import os import sys from django.conf import settings from django.core.management.base import BaseCommand from django.test.utils import get_runner class Command(BaseCommand): help = 'Discover and run tests in the specified modules or the current directory.' requires_system_checks = False def __init__(self): self.test_runner = None super(Command, self).__init__() def run_from_argv(self, argv): """ Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments. """ option = '--testrunner=' for arg in argv[2:]: if arg.startswith(option): self.test_runner = arg[len(option):] break super(Command, self).run_from_argv(argv) def add_arguments(self, parser): parser.add_argument('args', metavar='test_label', nargs='*', help='Module paths to test; can be modulename, modulename.TestCase or modulename.TestCase.test_method') parser.add_argument('--noinput', '--no-input', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), parser.add_argument('--failfast', action='store_true', dest='failfast', default=False, help='Tells Django to stop running the test suite after first ' 'failed test.'), parser.add_argument('--testrunner', action='store', dest='testrunner', help='Tells Django to use specified test runner class instead of ' 'the one specified by the TEST_RUNNER setting.'), parser.add_argument('--liveserver', action='store', dest='liveserver', default=None, help='Overrides the default address where the live server (used ' 'with LiveServerTestCase) is expected to run from. The ' 'default value is localhost:8081-8179.'), parser.add_argument('--tag', action='append', dest='tags', help='Run only tests with the specified tag.' 'You can use this option multiple times.') parser.add_argument('--exclude-tag', action='append', dest='exclude_tags', help='Do not run tests with the specified tag.' 'You can use this option multiple times.') test_runner_class = get_runner(settings, self.test_runner) if hasattr(test_runner_class, 'add_arguments'): test_runner_class.add_arguments(parser) def execute(self, *args, **options): if options['verbosity'] > 0: # ensure that deprecation warnings are displayed during testing # the following state is assumed: # logging.capturewarnings is true # a "default" level warnings filter has been added for # DeprecationWarning. See django.conf.LazySettings._configure_logging logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) super(Command, self).execute(*args, **options) if options['verbosity'] > 0: # remove the testing-specific handler logger.removeHandler(handler) def handle(self, *test_labels, **options): from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings, options.get('testrunner')) if options.get('liveserver') is not None: os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options['liveserver'] del options['liveserver'] tags = set(options.get('tags') or []) exclude_tags = set(options.get('exclude_tags') or []) test_runner = TestRunner(**options) failures = test_runner.run_tests(test_labels, tags=tags, exclude_tags=exclude_tags) if failures: sys.exit(bool(failures))
{ "content_hash": "9efbf2cef8a6e7358408e1b098914a36", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 115, "avg_line_length": 42.8936170212766, "alnum_prop": 0.6190476190476191, "repo_name": "mrbox/django", "id": "bf0da0df1271e2fe1aca2ba35779c08d33a67715", "size": "4032", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django/core/management/commands/test.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "52334" }, { "name": "HTML", "bytes": "170436" }, { "name": "JavaScript", "bytes": "255321" }, { "name": "Makefile", "bytes": "125" }, { "name": "Python", "bytes": "11425411" }, { "name": "Shell", "bytes": "809" }, { "name": "Smarty", "bytes": "130" } ], "symlink_target": "" }
<?php namespace yii2mod\linkpreview; use yii\helpers\ArrayHelper; use yii2mod\linkpreview\helpers\ContentHelper; use yii2mod\linkpreview\helpers\MediaHelper; use yii2mod\linkpreview\helpers\UrlHelper; use yii\base\Exception; use yii\base\Object; use yii\helpers\HtmlPurifier; /** * Class Crawler * @package yii2mod\linkpreview */ class Crawler extends Object { /** * @var string content given from widget */ public $content; /** * @var array default curl options */ public $curlOptions = []; /** * @var string page url */ protected $url; /** * @var string page title */ protected $title; /** * @var string page description */ protected $description; /** * @var string image url from page content */ protected $imageUrl; /** * Initialize object */ public function init() { $this->curlOptions = ArrayHelper::merge([ CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36', CURLOPT_FOLLOWLOCATION => true, CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_ENCODING => 'UTF-8' ], $this->curlOptions); parent::init(); } /** * Return page preview array data in json format * @return null|array */ public function getPagePreview() { $this->url = $this->getUrlFromContent(); if ($this->url !== null) { if (ContentHelper::isImageUrl($this->url)) { $this->imageUrl = $this->url; } else { $pageData = $this->performRequest(); if (!$pageData["content"] && strpos($this->url, "//www.") === false) { if (strpos($this->url, "http://") !== false) { $this->url = str_replace("http://", "http://www.", $this->url); } elseif (strpos($this->url, "https://") !== false) { $this->url = str_replace("https://", "https://www.", $this->url); } $pageData = $this->performRequest(); } if ($pageData === null) { return $this->getResponseData(); } $this->url = $pageData['url']; $content = $pageData['content']; $metaTags = ContentHelper::getMetaTags($content); $this->title = $this->getTitle($content, $metaTags); $this->description = $this->getDescription($content, $metaTags); $media = $this->getMedia(); $this->imageUrl = count($media) === 0 ? ContentHelper::trimText($metaTags["image"]) : $media['imgUrl']; if (empty($this->imageUrl)) { $this->imageUrl = ContentHelper::getImageSrc($content, $this->url); } } return $this->getResponseData(); } return null; } /** * Get link from content * @param null $default * @return mixed|null */ protected function getUrlFromContent($default = null) { $this->content = str_replace("\n", " ", $this->content); if (preg_match(ContentHelper::$regexList['url'], $this->content, $match)) { if (strpos($match[0], " ") === 0) { $match[0] = "http://" . substr($match[0], 1); } return str_replace("https://", "http://", $match[0]); } return $default; } /** * Performs HTTP request * Return page content, url and header info * * @throws Exception if request failed * @return mixed */ protected function performRequest() { $response = []; $curl = curl_init($this->url); curl_setopt_array($curl, $this->curlOptions); $body = curl_exec($curl); $header = curl_getinfo($curl); if ($body !== false) { $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($responseCode >= 200 && $responseCode < 300) { $response['content'] = $body; $response['url'] = $header['url']; return $response; } } return null; } /** * Get page media data * @return array */ protected function getMedia() { $result = []; foreach (MediaHelper::$videoServiceConfig as $domainName => $methodName) { if (strpos($this->url, $domainName) !== false) { $result = MediaHelper::$methodName($this->url); } } return $result; } /** * Get page title * @param $content * @param $metaTags * @return string */ protected function getTitle($content, $metaTags) { $title = ContentHelper::trimText($metaTags["title"]); if (empty($title)) { if (preg_match(ContentHelper::$regexList['title'], str_replace("\n", " ", $content), $matching)) { $title = $matching[2]; } } if (ContentHelper::isJson($title)) { $title = ""; } return ContentHelper::trimText($title); } /** * Get page description * @param $content * @param $metaTags * @return mixed|string */ protected function getDescription($content, $metaTags) { $description = ContentHelper::trimText($metaTags["description"]); if (empty($description)) { $description = ContentHelper::parse($content); } if (ContentHelper::isJson($description)) { $description = ""; } $description = HtmlPurifier::process($description); return ContentHelper::trimText($description); } /** * Return response array data * @return array */ protected function getResponseData() { return [ 'status' => 'success', 'title' => $this->title, 'url' => $this->url, 'canonicalUrl' => UrlHelper::canonicalPage($this->url), 'description' => $this->description, 'image' => $this->imageUrl ]; } }
{ "content_hash": "a86ffb30c68d93f64212420d4bf29e02", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 140, "avg_line_length": 29.402714932126695, "alnum_prop": 0.5096952908587258, "repo_name": "fhferreira/yii2-link-preview", "id": "f2edf0e9d986c352a6fa98372431e350ec279660", "size": "6498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Crawler.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1020" }, { "name": "JavaScript", "bytes": "3977" }, { "name": "PHP", "bytes": "29236" } ], "symlink_target": "" }
package io.kraken.client.model; import java.util.HashMap; import java.util.Map; /** * @author Emir Dizdarevic * @since 1.0.0 */ public enum ImageFormat { JPEG("jpeg"), PNG("png"), GIF("gif"); private static Map<String, ImageFormat> REVERSE_LOOKUP = new HashMap<String, ImageFormat>(); static { for (ImageFormat strategy : values()) { REVERSE_LOOKUP.put(strategy.getValue(), strategy); } } private final String value; ImageFormat(String value) { this.value = value; } public String getValue() { return value; } public static ImageFormat fromString(String value) { return REVERSE_LOOKUP.get(value); } @Override public String toString() { return value; } }
{ "content_hash": "3d0f5f86bc5fa9fe21961f505b65696a", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 96, "avg_line_length": 19.26829268292683, "alnum_prop": 0.6075949367088608, "repo_name": "kraken-io/kraken-java", "id": "cfd4d956f46dbb3ab1ac170784a1335ccd64b2b5", "size": "1407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/kraken/client/model/ImageFormat.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "109615" } ], "symlink_target": "" }
<?php namespace ZendTest\Cache\Storage\Adapter; use Zend\Cache\Storage\Adapter\AdapterOptions; use Zend\Cache\Storage\Adapter\AbstractZendServer; /** * @group Zend_Cache */ class AbstractZendServerTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->_options = new AdapterOptions(); $this->_storage = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractZendServer'); $this->_storage->setOptions($this->_options); $this->_storage->expects($this->any()) ->method('getOptions') ->will($this->returnValue($this->_options)); } public function testGetOptions() { $options = $this->_storage->getOptions(); $this->assertInstanceOf('Zend\Cache\Storage\Adapter\AdapterOptions', $options); $this->assertInternalType('boolean', $options->getWritable()); $this->assertInternalType('boolean', $options->getReadable()); $this->assertInternalType('integer', $options->getTtl()); $this->assertInternalType('string', $options->getNamespace()); $this->assertInternalType('string', $options->getKeyPattern()); } public function testGetItem() { $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcFetch') ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue('value')); $this->assertEquals('value', $this->_storage->getItem('key')); } public function testGetItemFailed() { $success = null; $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcFetch') ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue(null)); $this->assertNull($this->_storage->getItem('key', $success)); $this->assertFalse($success); } public function testGetMetadata() { $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcFetch') ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue('value')); $this->assertEquals(array(), $this->_storage->getMetadata('key')); } public function testHasItem() { $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcFetch') ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue('value')); $this->assertEquals(true, $this->_storage->hasItem('key')); } public function testSetItem() { $this->_options->setTtl(10); $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcStore') ->with( $this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key'), $this->equalTo('value'), $this->equalTo(10) ) ->will($this->returnValue(true)); $this->assertEquals(true, $this->_storage->setItem('key', 'value')); } public function testRemoveItem() { $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcDelete') ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue(true)); $this->assertEquals(true, $this->_storage->removeItem('key')); } }
{ "content_hash": "ece6e744217e6c58a37ecc451811e013", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 106, "avg_line_length": 35.203539823008846, "alnum_prop": 0.5399698340874811, "repo_name": "bourkhimehaytam/zf2", "id": "1d695cf45af19a1fb1e1d2edfc0b1b595e98938b", "size": "4280", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/ZendTest/Cache/Storage/Adapter/AbstractZendServerTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "18268008" }, { "name": "Shell", "bytes": "1602" } ], "symlink_target": "" }
import datetime from ironic_lib import metrics_utils from oslo_utils import uuidutils import pecan from pecan import rest from six.moves import http_client import wsme from wsme import types as wtypes from ironic.api.controllers import base from ironic.api.controllers import link from ironic.api.controllers.v1 import collection from ironic.api.controllers.v1 import notification_utils as notify from ironic.api.controllers.v1 import types from ironic.api.controllers.v1 import utils as api_utils from ironic.api import expose from ironic.common import exception from ironic.common.i18n import _ from ironic.common import policy from ironic.common import utils as common_utils from ironic import objects METRICS = metrics_utils.get_metrics_logger(__name__) _DEFAULT_RETURN_FIELDS = ('uuid', 'address') def hide_fields_in_newer_versions(obj): # if requested version is < 1.18, hide internal_info field if not api_utils.allow_port_internal_info(): obj.internal_info = wsme.Unset # if requested version is < 1.19, hide local_link_connection and # pxe_enabled fields if not api_utils.allow_port_advanced_net_fields(): obj.pxe_enabled = wsme.Unset obj.local_link_connection = wsme.Unset # if requested version is < 1.24, hide portgroup_uuid field if not api_utils.allow_portgroups_subcontrollers(): obj.portgroup_uuid = wsme.Unset # if requested version is < 1.34, hide physical_network field. if not api_utils.allow_port_physical_network(): obj.physical_network = wsme.Unset class Port(base.APIBase): """API representation of a port. This class enforces type checking and value constraints, and converts between the internal object model and the API representation of a port. """ _node_uuid = None _portgroup_uuid = None def _get_node_uuid(self): return self._node_uuid def _set_node_uuid(self, value): if value and self._node_uuid != value: try: # FIXME(comstud): One should only allow UUID here, but # there seems to be a bug in that tests are passing an # ID. See bug #1301046 for more details. node = objects.Node.get(pecan.request.context, value) self._node_uuid = node.uuid # NOTE(lucasagomes): Create the node_id attribute on-the-fly # to satisfy the api -> rpc object # conversion. self.node_id = node.id except exception.NodeNotFound as e: # Change error code because 404 (NotFound) is inappropriate # response for a POST request to create a Port e.code = http_client.BAD_REQUEST # BadRequest raise elif value == wtypes.Unset: self._node_uuid = wtypes.Unset def _get_portgroup_uuid(self): return self._portgroup_uuid def _set_portgroup_uuid(self, value): if value and self._portgroup_uuid != value: if not api_utils.allow_portgroups_subcontrollers(): self._portgroup_uuid = wtypes.Unset return try: portgroup = objects.Portgroup.get(pecan.request.context, value) if portgroup.node_id != self.node_id: raise exception.BadRequest(_('Port can not be added to a ' 'portgroup belonging to a ' 'different node.')) self._portgroup_uuid = portgroup.uuid # NOTE(lucasagomes): Create the portgroup_id attribute # on-the-fly to satisfy the api -> # rpc object conversion. self.portgroup_id = portgroup.id except exception.PortgroupNotFound as e: # Change error code because 404 (NotFound) is inappropriate # response for a POST request to create a Port e.code = http_client.BAD_REQUEST # BadRequest raise e elif value == wtypes.Unset: self._portgroup_uuid = wtypes.Unset elif value is None and api_utils.allow_portgroups_subcontrollers(): # This is to output portgroup_uuid field if API version allows this self._portgroup_uuid = None uuid = types.uuid """Unique UUID for this port""" address = wsme.wsattr(types.macaddress, mandatory=True) """MAC Address for this port""" extra = {wtypes.text: types.jsontype} """This port's meta data""" internal_info = wsme.wsattr({wtypes.text: types.jsontype}, readonly=True) """This port's internal information maintained by ironic""" node_uuid = wsme.wsproperty(types.uuid, _get_node_uuid, _set_node_uuid, mandatory=True) """The UUID of the node this port belongs to""" portgroup_uuid = wsme.wsproperty(types.uuid, _get_portgroup_uuid, _set_portgroup_uuid, mandatory=False) """The UUID of the portgroup this port belongs to""" pxe_enabled = types.boolean """Indicates whether pxe is enabled or disabled on the node.""" local_link_connection = types.locallinkconnectiontype """The port binding profile for the port""" physical_network = wtypes.StringType(max_length=64) """The name of the physical network to which this port is connected.""" links = wsme.wsattr([link.Link], readonly=True) """A list containing a self link and associated port links""" def __init__(self, **kwargs): self.fields = [] fields = list(objects.Port.fields) # NOTE(lucasagomes): node_uuid is not part of objects.Port.fields # because it's an API-only attribute fields.append('node_uuid') # NOTE: portgroup_uuid is not part of objects.Port.fields # because it's an API-only attribute fields.append('portgroup_uuid') for field in fields: # Add fields we expose. if hasattr(self, field): self.fields.append(field) setattr(self, field, kwargs.get(field, wtypes.Unset)) # NOTE(lucasagomes): node_id is an attribute created on-the-fly # by _set_node_uuid(), it needs to be present in the fields so # that as_dict() will contain node_id field when converting it # before saving it in the database. self.fields.append('node_id') setattr(self, 'node_uuid', kwargs.get('node_id', wtypes.Unset)) # NOTE: portgroup_id is an attribute created on-the-fly # by _set_portgroup_uuid(), it needs to be present in the fields so # that as_dict() will contain portgroup_id field when converting it # before saving it in the database. self.fields.append('portgroup_id') setattr(self, 'portgroup_uuid', kwargs.get('portgroup_id', wtypes.Unset)) @staticmethod def _convert_with_links(port, url, fields=None): # NOTE(lucasagomes): Since we are able to return a specified set of # fields the "uuid" can be unset, so we need to save it in another # variable to use when building the links port_uuid = port.uuid if fields is not None: port.unset_fields_except(fields) # never expose the node_id attribute port.node_id = wtypes.Unset # never expose the portgroup_id attribute port.portgroup_id = wtypes.Unset port.links = [link.Link.make_link('self', url, 'ports', port_uuid), link.Link.make_link('bookmark', url, 'ports', port_uuid, bookmark=True) ] return port @classmethod def convert_with_links(cls, rpc_port, fields=None): port = Port(**rpc_port.as_dict()) if fields is not None: api_utils.check_for_invalid_fields(fields, port.as_dict()) hide_fields_in_newer_versions(port) return cls._convert_with_links(port, pecan.request.public_url, fields=fields) @classmethod def sample(cls, expand=True): sample = cls(uuid='27e3153e-d5bf-4b7e-b517-fb518e17f34c', address='fe:54:00:77:07:d9', extra={'foo': 'bar'}, internal_info={}, created_at=datetime.datetime.utcnow(), updated_at=datetime.datetime.utcnow(), pxe_enabled=True, local_link_connection={ 'switch_info': 'host', 'port_id': 'Gig0/1', 'switch_id': 'aa:bb:cc:dd:ee:ff'}, physical_network='physnet1') # NOTE(lucasagomes): node_uuid getter() method look at the # _node_uuid variable sample._node_uuid = '7ae81bb3-dec3-4289-8d6c-da80bd8001ae' sample._portgroup_uuid = '037d9a52-af89-4560-b5a3-a33283295ba2' fields = None if expand else _DEFAULT_RETURN_FIELDS return cls._convert_with_links(sample, 'http://localhost:6385', fields=fields) class PortPatchType(types.JsonPatchType): _api_base = Port @staticmethod def internal_attrs(): defaults = types.JsonPatchType.internal_attrs() return defaults + ['/internal_info'] class PortCollection(collection.Collection): """API representation of a collection of ports.""" ports = [Port] """A list containing ports objects""" def __init__(self, **kwargs): self._type = 'ports' @staticmethod def convert_with_links(rpc_ports, limit, url=None, fields=None, **kwargs): collection = PortCollection() collection.ports = [Port.convert_with_links(p, fields=fields) for p in rpc_ports] collection.next = collection.get_next(limit, url=url, **kwargs) return collection @classmethod def sample(cls): sample = cls() sample.ports = [Port.sample(expand=False)] return sample class PortsController(rest.RestController): """REST controller for Ports.""" _custom_actions = { 'detail': ['GET'], } invalid_sort_key_list = ['extra', 'internal_info', 'local_link_connection'] advanced_net_fields = ['pxe_enabled', 'local_link_connection'] def __init__(self, node_ident=None, portgroup_ident=None): super(PortsController, self).__init__() self.parent_node_ident = node_ident self.parent_portgroup_ident = portgroup_ident def _get_ports_collection(self, node_ident, address, portgroup_ident, marker, limit, sort_key, sort_dir, resource_url=None, fields=None): limit = api_utils.validate_limit(limit) sort_dir = api_utils.validate_sort_dir(sort_dir) marker_obj = None if marker: marker_obj = objects.Port.get_by_uuid(pecan.request.context, marker) if sort_key in self.invalid_sort_key_list: raise exception.InvalidParameterValue( _("The sort_key value %(key)s is an invalid field for " "sorting") % {'key': sort_key}) node_ident = self.parent_node_ident or node_ident portgroup_ident = self.parent_portgroup_ident or portgroup_ident if node_ident and portgroup_ident: raise exception.OperationNotPermitted() if portgroup_ident: # FIXME: Since all we need is the portgroup ID, we can # make this more efficient by only querying # for that column. This will get cleaned up # as we move to the object interface. portgroup = api_utils.get_rpc_portgroup(portgroup_ident) ports = objects.Port.list_by_portgroup_id(pecan.request.context, portgroup.id, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) elif node_ident: # FIXME(comstud): Since all we need is the node ID, we can # make this more efficient by only querying # for that column. This will get cleaned up # as we move to the object interface. node = api_utils.get_rpc_node(node_ident) ports = objects.Port.list_by_node_id(pecan.request.context, node.id, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) elif address: ports = self._get_ports_by_address(address) else: ports = objects.Port.list(pecan.request.context, limit, marker_obj, sort_key=sort_key, sort_dir=sort_dir) return PortCollection.convert_with_links(ports, limit, url=resource_url, fields=fields, sort_key=sort_key, sort_dir=sort_dir) def _get_ports_by_address(self, address): """Retrieve a port by its address. :param address: MAC address of a port, to get the port which has this MAC address. :returns: a list with the port, or an empty list if no port is found. """ try: port = objects.Port.get_by_address(pecan.request.context, address) return [port] except exception.PortNotFound: return [] def _check_allowed_port_fields(self, fields): """Check if fetching a particular field of a port is allowed. Check if the required version is being requested for fields that are only allowed to be fetched in a particular API version. :param fields: list or set of fields to check :raises: NotAcceptable if a field is not allowed """ if fields is None: return if (not api_utils.allow_port_advanced_net_fields() and set(fields).intersection(self.advanced_net_fields)): raise exception.NotAcceptable() if ('portgroup_uuid' in fields and not api_utils.allow_portgroups_subcontrollers()): raise exception.NotAcceptable() if ('physical_network' in fields and not api_utils.allow_port_physical_network()): raise exception.NotAcceptable() @METRICS.timer('PortsController.get_all') @expose.expose(PortCollection, types.uuid_or_name, types.uuid, types.macaddress, types.uuid, int, wtypes.text, wtypes.text, types.listtype, types.uuid_or_name) def get_all(self, node=None, node_uuid=None, address=None, marker=None, limit=None, sort_key='id', sort_dir='asc', fields=None, portgroup=None): """Retrieve a list of ports. Note that the 'node_uuid' interface is deprecated in favour of the 'node' interface :param node: UUID or name of a node, to get only ports for that node. :param node_uuid: UUID of a node, to get only ports for that node. :param address: MAC address of a port, to get the port which has this MAC address. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. This value cannot be larger than the value of max_limit in the [api] section of the ironic configuration, or only max_limit resources will be returned. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. :param fields: Optional, a list with a specified set of fields of the resource to be returned. :param portgroup: UUID or name of a portgroup, to get only ports for that portgroup. :raises: NotAcceptable, HTTPNotFound """ cdict = pecan.request.context.to_policy_values() policy.authorize('baremetal:port:get', cdict, cdict) api_utils.check_allow_specify_fields(fields) self._check_allowed_port_fields(fields) self._check_allowed_port_fields([sort_key]) if portgroup and not api_utils.allow_portgroups_subcontrollers(): raise exception.NotAcceptable() if fields is None: fields = _DEFAULT_RETURN_FIELDS if not node_uuid and node: # We're invoking this interface using positional notation, or # explicitly using 'node'. Try and determine which one. # Make sure only one interface, node or node_uuid is used if (not api_utils.allow_node_logical_names() and not uuidutils.is_uuid_like(node)): raise exception.NotAcceptable() return self._get_ports_collection(node_uuid or node, address, portgroup, marker, limit, sort_key, sort_dir, fields=fields) @METRICS.timer('PortsController.detail') @expose.expose(PortCollection, types.uuid_or_name, types.uuid, types.macaddress, types.uuid, int, wtypes.text, wtypes.text, types.uuid_or_name) def detail(self, node=None, node_uuid=None, address=None, marker=None, limit=None, sort_key='id', sort_dir='asc', portgroup=None): """Retrieve a list of ports with detail. Note that the 'node_uuid' interface is deprecated in favour of the 'node' interface :param node: UUID or name of a node, to get only ports for that node. :param node_uuid: UUID of a node, to get only ports for that node. :param address: MAC address of a port, to get the port which has this MAC address. :param portgroup: UUID or name of a portgroup, to get only ports for that portgroup. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. This value cannot be larger than the value of max_limit in the [api] section of the ironic configuration, or only max_limit resources will be returned. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: asc. :raises: NotAcceptable, HTTPNotFound """ cdict = pecan.request.context.to_policy_values() policy.authorize('baremetal:port:get', cdict, cdict) self._check_allowed_port_fields([sort_key]) if portgroup and not api_utils.allow_portgroups_subcontrollers(): raise exception.NotAcceptable() if not node_uuid and node: # We're invoking this interface using positional notation, or # explicitly using 'node'. Try and determine which one. # Make sure only one interface, node or node_uuid is used if (not api_utils.allow_node_logical_names() and not uuidutils.is_uuid_like(node)): raise exception.NotAcceptable() # NOTE(lucasagomes): /detail should only work against collections parent = pecan.request.path.split('/')[:-1][-1] if parent != "ports": raise exception.HTTPNotFound() resource_url = '/'.join(['ports', 'detail']) return self._get_ports_collection(node_uuid or node, address, portgroup, marker, limit, sort_key, sort_dir, resource_url) @METRICS.timer('PortsController.get_one') @expose.expose(Port, types.uuid, types.listtype) def get_one(self, port_uuid, fields=None): """Retrieve information about the given port. :param port_uuid: UUID of a port. :param fields: Optional, a list with a specified set of fields of the resource to be returned. :raises: NotAcceptable, HTTPNotFound """ cdict = pecan.request.context.to_policy_values() policy.authorize('baremetal:port:get', cdict, cdict) if self.parent_node_ident or self.parent_portgroup_ident: raise exception.OperationNotPermitted() api_utils.check_allow_specify_fields(fields) self._check_allowed_port_fields(fields) rpc_port = objects.Port.get_by_uuid(pecan.request.context, port_uuid) return Port.convert_with_links(rpc_port, fields=fields) @METRICS.timer('PortsController.post') @expose.expose(Port, body=Port, status_code=http_client.CREATED) def post(self, port): """Create a new port. :param port: a port within the request body. :raises: NotAcceptable, HTTPNotFound, Conflict """ context = pecan.request.context cdict = context.to_policy_values() policy.authorize('baremetal:port:create', cdict, cdict) if self.parent_node_ident or self.parent_portgroup_ident: raise exception.OperationNotPermitted() pdict = port.as_dict() self._check_allowed_port_fields(pdict) extra = pdict.get('extra') vif = extra.get('vif_port_id') if extra else None if vif: common_utils.warn_about_deprecated_extra_vif_port_id() if (pdict.get('portgroup_uuid') and (pdict.get('pxe_enabled') or vif)): rpc_pg = objects.Portgroup.get_by_uuid(context, pdict['portgroup_uuid']) if not rpc_pg.standalone_ports_supported: msg = _("Port group %s doesn't support standalone ports. " "This port cannot be created as a member of that " "port group because either 'extra/vif_port_id' " "was specified or 'pxe_enabled' was set to True.") raise exception.Conflict( msg % pdict['portgroup_uuid']) # NOTE(yuriyz): UUID is mandatory for notifications payload if not pdict.get('uuid'): pdict['uuid'] = uuidutils.generate_uuid() rpc_port = objects.Port(context, **pdict) rpc_node = objects.Node.get_by_id(context, rpc_port.node_id) notify_extra = {'node_uuid': port.node_uuid, 'portgroup_uuid': port.portgroup_uuid} notify.emit_start_notification(context, rpc_port, 'create', **notify_extra) with notify.handle_error_notification(context, rpc_port, 'create', **notify_extra): # TODO(mgoddard): In RPC API v1.41, port creation was moved to the # conductor service to facilitate validation of the physical # network field of ports in portgroups. Further consideration is # required determine how best to support rolling upgrades from a # release in which ports are created by the API service to one in # which they are created by the conductor service, while ensuring # that all required validation is performed. topic = pecan.request.rpcapi.get_topic_for(rpc_node) new_port = pecan.request.rpcapi.create_port(context, rpc_port, topic) notify.emit_end_notification(context, new_port, 'create', **notify_extra) # Set the HTTP Location Header pecan.response.location = link.build_url('ports', new_port.uuid) return Port.convert_with_links(new_port) @METRICS.timer('PortsController.patch') @wsme.validate(types.uuid, [PortPatchType]) @expose.expose(Port, types.uuid, body=[PortPatchType]) def patch(self, port_uuid, patch): """Update an existing port. :param port_uuid: UUID of a port. :param patch: a json PATCH document to apply to this port. :raises: NotAcceptable, HTTPNotFound """ context = pecan.request.context cdict = context.to_policy_values() policy.authorize('baremetal:port:update', cdict, cdict) if self.parent_node_ident or self.parent_portgroup_ident: raise exception.OperationNotPermitted() fields_to_check = set() for field in (self.advanced_net_fields + ['portgroup_uuid', 'physical_network']): field_path = '/%s' % field if (api_utils.get_patch_values(patch, field_path) or api_utils.is_path_removed(patch, field_path)): fields_to_check.add(field) self._check_allowed_port_fields(fields_to_check) rpc_port = objects.Port.get_by_uuid(context, port_uuid) try: port_dict = rpc_port.as_dict() # NOTE(lucasagomes): # 1) Remove node_id because it's an internal value and # not present in the API object # 2) Add node_uuid port_dict['node_uuid'] = port_dict.pop('node_id', None) # NOTE(vsaienko): # 1) Remove portgroup_id because it's an internal value and # not present in the API object # 2) Add portgroup_uuid port_dict['portgroup_uuid'] = port_dict.pop('portgroup_id', None) port = Port(**api_utils.apply_jsonpatch(port_dict, patch)) except api_utils.JSONPATCH_EXCEPTIONS as e: raise exception.PatchError(patch=patch, reason=e) if api_utils.is_path_removed(patch, '/portgroup_uuid'): rpc_port.portgroup_id = None # Update only the fields that have changed for field in objects.Port.fields: try: patch_val = getattr(port, field) except AttributeError: # Ignore fields that aren't exposed in the API continue if patch_val == wtypes.Unset: patch_val = None if rpc_port[field] != patch_val: rpc_port[field] = patch_val rpc_node = objects.Node.get_by_id(context, rpc_port.node_id) notify_extra = {'node_uuid': rpc_node.uuid, 'portgroup_uuid': port.portgroup_uuid} notify.emit_start_notification(context, rpc_port, 'update', **notify_extra) with notify.handle_error_notification(context, rpc_port, 'update', **notify_extra): topic = pecan.request.rpcapi.get_topic_for(rpc_node) new_port = pecan.request.rpcapi.update_port(context, rpc_port, topic) api_port = Port.convert_with_links(new_port) notify.emit_end_notification(context, new_port, 'update', **notify_extra) return api_port @METRICS.timer('PortsController.delete') @expose.expose(None, types.uuid, status_code=http_client.NO_CONTENT) def delete(self, port_uuid): """Delete a port. :param port_uuid: UUID of a port. :raises: OperationNotPermitted, HTTPNotFound """ context = pecan.request.context cdict = context.to_policy_values() policy.authorize('baremetal:port:delete', cdict, cdict) if self.parent_node_ident or self.parent_portgroup_ident: raise exception.OperationNotPermitted() rpc_port = objects.Port.get_by_uuid(context, port_uuid) rpc_node = objects.Node.get_by_id(context, rpc_port.node_id) portgroup_uuid = None if rpc_port.portgroup_id: portgroup = objects.Portgroup.get_by_id(context, rpc_port.portgroup_id) portgroup_uuid = portgroup.uuid notify_extra = {'node_uuid': rpc_node.uuid, 'portgroup_uuid': portgroup_uuid} notify.emit_start_notification(context, rpc_port, 'delete', **notify_extra) with notify.handle_error_notification(context, rpc_port, 'delete', **notify_extra): topic = pecan.request.rpcapi.get_topic_for(rpc_node) pecan.request.rpcapi.destroy_port(context, rpc_port, topic) notify.emit_end_notification(context, rpc_port, 'delete', **notify_extra)
{ "content_hash": "22a11a53d098d3432db4f06df42c68a2", "timestamp": "", "source": "github", "line_count": 672, "max_line_length": 79, "avg_line_length": 44.01636904761905, "alnum_prop": 0.5752053821968288, "repo_name": "SauloAislan/ironic", "id": "a0a8cc9d215954e9118233b538c25113f7938df2", "size": "30211", "binary": false, "copies": "1", "ref": "refs/heads/SauloAislan-WIP", "path": "ironic/api/controllers/v1/port.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Mako", "bytes": "349" }, { "name": "Python", "bytes": "5596702" }, { "name": "Shell", "bytes": "119832" } ], "symlink_target": "" }
package com.github.stocky37.util.tenacity.commands; import com.github.stocky37.util.core.Service; import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; public class ServiceCreateCommand<T> extends TenacityCommand<T> { private final Service<T, ?> delegate; private final T entity; public ServiceCreateCommand(TenacityPropertyKey key, Service<T, ?> delegate, T resource) { super(key); this.delegate = delegate; this.entity = resource; } @Override protected T run() throws Exception { return delegate.create(entity); } }
{ "content_hash": "2c5ee4cdd566058411e06f2768355974", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 91, "avg_line_length": 28.38095238095238, "alnum_prop": 0.7768456375838926, "repo_name": "stocky37/dropwizard-util", "id": "aa5ffd37fc2733de14eb4e1f7e57786131d1e35e", "size": "596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tenacity/src/main/java/com/github/stocky37/util/tenacity/commands/ServiceCreateCommand.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "68765" } ], "symlink_target": "" }