text
stringlengths
2
1.04M
meta
dict
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MasterPagesCountriesHomework { public partial class Nachalo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
{ "content_hash": "9cb89344bd1879bd5469451ccfd4bc4e", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 60, "avg_line_length": 19.470588235294116, "alnum_prop": 0.7009063444108762, "repo_name": "Spurch/ASP-.NET-WebForms", "id": "b6bdbe5a7e999387d67eff9aee08652bc3a08301", "size": "333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MasterPagesCountriesHomework/Nachalo.aspx.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "231697" }, { "name": "C#", "bytes": "433057" }, { "name": "CSS", "bytes": "5745" }, { "name": "HTML", "bytes": "35889" }, { "name": "JavaScript", "bytes": "1985651" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Immune_System { class Program { static void Main(string[] args) { var virus = new Dictionary<string, int>(); var healthInput = int.Parse(Console.ReadLine()); var health = healthInput; while (true) { var input = Console.ReadLine(); if (input == "end") { Console.WriteLine($"Final Health: {health}"); break; } var virusDefSeconds = 0; if (virus.ContainsKey(input)) { virusDefSeconds = (virus[input] * input.Length) / 3; } else { virus[input] = input.ToCharArray().Select(x => (int)x).Sum() / 3; virusDefSeconds = virus[input] * input.Length; } int virusSeconds = virusDefSeconds % 60; int virusMinutes = virusDefSeconds / 60; Console.WriteLine($"Virus {input}: {virus[input]} => {virusDefSeconds} seconds"); health -= virusDefSeconds; if (health <= 0) { Console.WriteLine("Immune System Defeated."); break; } else { Console.WriteLine($"{input} defeated in {virusMinutes}m {virusSeconds}s."); Console.WriteLine($"Remaining health: {health}"); } double newHealth = health * 0.2; health += (int)newHealth; if (health > healthInput) { health = healthInput; } } } } }
{ "content_hash": "8f93250e712fe3b8aa95f4d4032ea089", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 97, "avg_line_length": 30.93548387096774, "alnum_prop": 0.4416058394160584, "repo_name": "preslavc/SoftUni", "id": "73013697df53fab3912a02a4cc93fa2504438a38", "size": "1920", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Programming Fundamentals/More Exercises/Dictionaries and Lists/Immune System/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "623455" }, { "name": "Java", "bytes": "49221" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "039447e50a0108b0d43fadec2c7655e9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "4eadcd001efdc4b32fa2fc47f29f44d010b2546d", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Trimezia/Trimezia juncifolia/ Syn. Trimezia caeteana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* * Songs by Artist */ import React, { Component } from 'react' import { Link } from 'react-router' import Infinite from 'react-infinite' export default class SongsByArtist extends Component { renderArtistItems() { return Object.keys(this.props.artists).map( key => { return ( <Link to={'/songs/' + key} key={key}> <div className="border-bottom border-muted py2 mrn2 relative"> <div className="white h4" style={{marginRight: '140px'}}>{this.props.artists[key].label}</div> <span className="white absolute right-0 h2 mr3 px1" style={{top: '10px'}}> <span className="inline-block h6 bg-teal rounded mr2 relative" style={{padding: '3px 12px', top: '-3px'}}>{this.props.artists[key].songs.length + ' songs'}</span> › </span> </div> </Link> ) }) } render() { return ( <div style={{marginRight: '-15px'}}> <Infinite containerHeight={430} elementHeight={56} infiniteLoadBeginEdgeOffset={200} preloadBatchSize={Infinite.containerHeightScaleFactor(2)}>{this.renderArtistItems()}</Infinite> </div> ) } }
{ "content_hash": "1d4bfe2aa2c85dd934b362959a9edf2d", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 188, "avg_line_length": 35.03030303030303, "alnum_prop": 0.6133217993079585, "repo_name": "chexee/karaoke-night", "id": "3be275731d4cab516a0d0371ccda22da05a81d23", "size": "1158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/components/pages/SongsByArtist.react.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1526" }, { "name": "CSS", "bytes": "2279" }, { "name": "HTML", "bytes": "772" }, { "name": "JavaScript", "bytes": "26483" } ], "symlink_target": "" }
package bridge import ( "net" "testing" "github.com/docker/docker/pkg/iptables" "github.com/docker/libnetwork/netutils" ) const ( iptablesTestBridgeIP = "192.168.42.1" ) func TestProgramIPTable(t *testing.T) { // Create a test bridge with a basic bridge configuration (name + IPv4). defer netutils.SetupTestNetNS(t)() createTestBridge(getBasicTestConfig(), &bridgeInterface{}, t) // Store various iptables chain rules we care for. rules := []struct { rule iptRule descr string }{ {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-d", "127.1.2.3", "-i", "lo", "-o", "lo", "-j", "DROP"}}, "Test Loopback"}, {iptRule{table: iptables.Nat, chain: "POSTROUTING", preArgs: []string{"-t", "nat"}, args: []string{"-s", iptablesTestBridgeIP, "!", "-o", DefaultBridgeName, "-j", "MASQUERADE"}}, "NAT Test"}, {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", DefaultBridgeName, "!", "-o", DefaultBridgeName, "-j", "ACCEPT"}}, "Test ACCEPT NON_ICC OUTGOING"}, {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-o", DefaultBridgeName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}}, "Test ACCEPT INCOMING"}, {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", DefaultBridgeName, "-o", DefaultBridgeName, "-j", "ACCEPT"}}, "Test enable ICC"}, {iptRule{table: iptables.Filter, chain: "FORWARD", args: []string{"-i", DefaultBridgeName, "-o", DefaultBridgeName, "-j", "DROP"}}, "Test disable ICC"}, } // Assert the chain rules' insertion and removal. for _, c := range rules { assertIPTableChainProgramming(c.rule, c.descr, t) } } func TestSetupIPTables(t *testing.T) { // Create a test bridge with a basic bridge configuration (name + IPv4). defer netutils.SetupTestNetNS(t)() config := getBasicTestConfig() br := &bridgeInterface{} createTestBridge(config, br, t) // Modify iptables params in base configuration and apply them. config.EnableIPTables = true assertBridgeConfig(config, br, t) config.EnableIPMasquerade = true assertBridgeConfig(config, br, t) config.EnableICC = true assertBridgeConfig(config, br, t) config.EnableIPMasquerade = false assertBridgeConfig(config, br, t) } func getBasicTestConfig() *Configuration { config := &Configuration{ BridgeName: DefaultBridgeName, AddressIPv4: &net.IPNet{IP: net.ParseIP(iptablesTestBridgeIP), Mask: net.CIDRMask(16, 32)}} return config } func createTestBridge(config *Configuration, br *bridgeInterface, t *testing.T) { if err := setupDevice(config, br); err != nil { t.Fatalf("Failed to create the testing Bridge: %s", err.Error()) } if err := setupBridgeIPv4(config, br); err != nil { t.Fatalf("Failed to bring up the testing Bridge: %s", err.Error()) } } // Assert base function which pushes iptables chain rules on insertion and removal. func assertIPTableChainProgramming(rule iptRule, descr string, t *testing.T) { // Add if err := programChainRule(rule, descr, true); err != nil { t.Fatalf("Failed to program iptable rule %s: %s", descr, err.Error()) } if iptables.Exists(rule.table, rule.chain, rule.args...) == false { t.Fatalf("Failed to effectively program iptable rule: %s", descr) } // Remove if err := programChainRule(rule, descr, false); err != nil { t.Fatalf("Failed to remove iptable rule %s: %s", descr, err.Error()) } if iptables.Exists(rule.table, rule.chain, rule.args...) == true { t.Fatalf("Failed to effectively remove iptable rule: %s", descr) } } // Assert function which pushes chains based on bridge config parameters. func assertBridgeConfig(config *Configuration, br *bridgeInterface, t *testing.T) { // Attempt programming of ip tables. err := setupIPTables(config, br) if err != nil { t.Fatalf("%v", err) } }
{ "content_hash": "cf36c8eb2156ec7ec7c51e44e2b0ea33", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 193, "avg_line_length": 36.77669902912621, "alnum_prop": 0.6953537486800423, "repo_name": "mrjana/libnetwork", "id": "5f00b6fde4ec55cd008421403373311b47f17193", "size": "3788", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "drivers/bridge/setup_ip_tables_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "140829" }, { "name": "Makefile", "bytes": "2118" } ], "symlink_target": "" }
package com.excilys.ebi.spring.dbunit.test; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.dbunit.database.DatabaseConfig; import org.dbunit.dataset.IDataSet; import com.excilys.ebi.spring.dbunit.config.DBType; import com.excilys.ebi.spring.dbunit.config.DataSetFormat; import com.excilys.ebi.spring.dbunit.config.Constants.ConfigurationDefaults; @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface ExpectedDataSet { /** * alias for locations */ String[] value() default {}; /** * @return Dataset files locations */ String[] locations() default {}; /** * Columns to ignore. */ String[] columnsToIgnore() default {}; /** * {@link IDataSet} file format * * @return default {@link DataSetFormat#FLAT} */ DataSetFormat format() default DataSetFormat.FLAT; /** * database type * * @return default {@link DBType#HSQLDB} */ DBType dbType() default DBType.HSQLDB; /** * @return DataSource name in the Spring Context. If empty, expect one and * only one DataSource in the Spring Context. */ String dataSourceSpringName() default ""; /** * @see com.excilys.ebi.spring.dbunit.dataset.xml.flyweight.FlyWeightFlatXmlDataSetBuilder#setColumnSensing(boolean) * @return default {@link ConfigurationDefaults.DEFAULT_COLUMN_SENSING} */ boolean columnSensing() default ConfigurationDefaults.DEFAULT_COLUMN_SENSING; /** * @see com.excilys.ebi.spring.dbunit.dataset.xml.flyweight.FlyWeightFlatXmlDataSetBuilder#setMetaDataSet(IDataSet) * @return default empty */ String dtdLocation() default ""; /** * @see com.excilys.ebi.spring.dbunit.dataset.xml.flyweight.FlyWeightFlatXmlDataSetBuilder#setDtdMetadata(boolean) * @return default {@link ConfigurationDefaults.DEFAULT_DTD_METADATA} */ boolean dtdMetadata() default ConfigurationDefaults.DEFAULT_DTD_METADATA; /** * @see DatabaseConfig#FEATURE_CASE_SENSITIVE_TABLE_NAMES * @return default * {@link ConfigurationDefaults.DEFAULT_CASE_SENSITIVE_TABLE_NAMES} */ boolean caseSensitiveTableNames() default ConfigurationDefaults.DEFAULT_CASE_SENSITIVE_TABLE_NAMES; /** * @see DatabaseConfig#PROPERTY_ESCAPE_PATTERN * @return default {@link ConfigurationDefaults.DEFAULT_ESCAPE_PATTERN} */ String escapePattern() default ConfigurationDefaults.DEFAULT_ESCAPE_PATTERN; /** * @see DatabaseConfig#FEATURE_QUALIFIED_TABLE_NAMES * @return default * {@link ConfigurationDefaults.DEFAULT_QUALIFIED_TABLE_NAMES} */ boolean qualifiedTableNames() default ConfigurationDefaults.DEFAULT_QUALIFIED_TABLE_NAMES; /** * @see DatabaseConfig#PROPERTY_TABLE_TYPE * @return default {@link ConfigurationDefaults.DEFAULT_TABLE_TYPE} */ String[] tableType() default { "TABLE" }; /** * @return the schema */ String schema() default ""; }
{ "content_hash": "fd0f095c99521d19e38a48d4b711887b", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 117, "avg_line_length": 28.453703703703702, "alnum_prop": 0.7468272046859746, "repo_name": "excilys/spring-dbunit", "id": "92532f71e758e6b75acacd6164c8032046747f95", "size": "3715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-dbunit-test/src/main/java/com/excilys/ebi/spring/dbunit/test/ExpectedDataSet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "163948" } ], "symlink_target": "" }
"""Tests for tf.contrib.gan.python.features.random_tensor_pool.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.gan.python.features.python.random_tensor_pool_impl import tensor_pool from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class TensorPoolTest(test.TestCase): def test_pool_unknown_input_shape(self): """Checks that `input_value` can have unknown shape.""" input_value = array_ops.placeholder( dtype=dtypes.int32, shape=[None, None, 3]) output_value = tensor_pool(input_value, pool_size=10) with self.test_session(use_gpu=True) as session: for i in range(10): session.run(output_value, {input_value: [[[i] * 3]]}) session.run(output_value, {input_value: [[[i] * 3] * 2]}) session.run(output_value, {input_value: [[[i] * 3] * 5] * 2}) def test_pool_sequence(self): """Checks that values are pooled and returned maximally twice.""" input_value = array_ops.placeholder(dtype=dtypes.int32, shape=[]) output_value = tensor_pool(input_value, pool_size=10) with self.test_session(use_gpu=True) as session: outs = [] for i in range(50): out = session.run(output_value, {input_value: i}) outs.append(out) self.assertLessEqual(out, i) _, counts = np.unique(outs, return_counts=True) # Check that each value is returned maximally twice. self.assertTrue((counts <= 2).all()) def test_never_pool(self): """Checks that setting `pooling_probability` to zero works.""" input_value = array_ops.placeholder(dtype=dtypes.int32, shape=[]) output_value = tensor_pool( input_value, pool_size=10, pooling_probability=0.0) with self.test_session(use_gpu=True) as session: for i in range(50): out = session.run(output_value, {input_value: i}) self.assertEqual(out, i) def test_pooling_probability(self): """Checks that `pooling_probability` works.""" input_value = array_ops.placeholder(dtype=dtypes.int32, shape=[]) pool_size = 10 pooling_probability = 0.2 output_value = tensor_pool( input_value, pool_size=pool_size, pooling_probability=pooling_probability) with self.test_session(use_gpu=True) as session: not_pooled = 0 total = 1000 for i in range(total): out = session.run(output_value, {input_value: i}) if out == i: not_pooled += 1 self.assertAllClose( (not_pooled - pool_size) / (total - pool_size), 1 - pooling_probability, atol=0.03) def test_input_values_tuple(self): """Checks that `input_values` can be a tuple.""" input_values = (array_ops.placeholder(dtype=dtypes.int32, shape=[]), array_ops.placeholder(dtype=dtypes.int32, shape=[])) output_values = tensor_pool(input_values, pool_size=3) self.assertEqual(len(output_values), len(input_values)) with self.test_session(use_gpu=True) as session: for i in range(10): outs = session.run(output_values, { input_values[0]: i, input_values[1]: i + 1 }) self.assertEqual(len(outs), len(input_values)) self.assertEqual(outs[1] - outs[0], 1) if __name__ == '__main__': test.main()
{ "content_hash": "45e9bd7e02c6318f5343bbaf7227fdc2", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 93, "avg_line_length": 35.875, "alnum_prop": 0.6428571428571429, "repo_name": "eadgarchen/tensorflow", "id": "cef3a87ab34f9754099073eefcb3f1b1c97a3762", "size": "4133", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "tensorflow/contrib/gan/python/features/python/random_tensor_pool_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8913" }, { "name": "C", "bytes": "321171" }, { "name": "C++", "bytes": "35900386" }, { "name": "CMake", "bytes": "188687" }, { "name": "Go", "bytes": "1057580" }, { "name": "Java", "bytes": "541818" }, { "name": "Jupyter Notebook", "bytes": "1940884" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "44805" }, { "name": "Objective-C", "bytes": "12456" }, { "name": "Objective-C++", "bytes": "94716" }, { "name": "PHP", "bytes": "1429" }, { "name": "Perl", "bytes": "6179" }, { "name": "Perl 6", "bytes": "1357" }, { "name": "PureBasic", "bytes": "24932" }, { "name": "Python", "bytes": "31228552" }, { "name": "Ruby", "bytes": "547" }, { "name": "Shell", "bytes": "403773" } ], "symlink_target": "" }
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmsr/dsrwavvl.h" #include "dcmtk/dcmsr/dsrxmld.h" DSRWaveformReferenceValue::DSRWaveformReferenceValue() : DSRCompositeReferenceValue(), ChannelList() { } DSRWaveformReferenceValue::DSRWaveformReferenceValue(const OFString &sopClassUID, const OFString &sopInstanceUID, const OFBool check) : DSRCompositeReferenceValue(), ChannelList() { /* use the set method for checking purposes */ setReference(sopClassUID, sopInstanceUID, check); } DSRWaveformReferenceValue::DSRWaveformReferenceValue(const DSRWaveformReferenceValue &referenceValue) : DSRCompositeReferenceValue(referenceValue), ChannelList(referenceValue.ChannelList) { /* do not check since this would be unexpected to the user */ } DSRWaveformReferenceValue::~DSRWaveformReferenceValue() { } DSRWaveformReferenceValue &DSRWaveformReferenceValue::operator=(const DSRWaveformReferenceValue &referenceValue) { DSRCompositeReferenceValue::operator=(referenceValue); /* do not check since this would be unexpected to the user */ ChannelList = referenceValue.ChannelList; return *this; } void DSRWaveformReferenceValue::clear() { DSRCompositeReferenceValue::clear(); ChannelList.clear(); } OFBool DSRWaveformReferenceValue::isShort(const size_t flags) const { return ChannelList.isEmpty() || !(flags & DSRTypes::HF_renderFullData); } OFCondition DSRWaveformReferenceValue::print(STD_NAMESPACE ostream &stream, const size_t flags) const { const char *className = dcmFindNameOfUID(SOPClassUID.c_str()); stream << "("; if (className != NULL) stream << className; else stream << "\"" << SOPClassUID << "\""; stream << ","; if (flags & DSRTypes::PF_printSOPInstanceUID) stream << "\"" << SOPInstanceUID << "\""; if (!ChannelList.isEmpty()) { stream << ","; ChannelList.print(stream, flags); } stream << ")"; return EC_Normal; } OFCondition DSRWaveformReferenceValue::readXML(const DSRXMLDocument &doc, DSRXMLCursor cursor) { /* first read general composite reference information */ OFCondition result = DSRCompositeReferenceValue::readXML(doc, cursor); /* then read waveform related XML tags */ if (result.good()) { /* channel list (optional) */ cursor = doc.getNamedNode(cursor.getChild(), "channels"); if (cursor.valid()) { OFString tmpString; /* put element content to the channel list */ result = ChannelList.putString(doc.getStringFromNodeContent(cursor, tmpString).c_str()); } } return result; } OFCondition DSRWaveformReferenceValue::writeXML(STD_NAMESPACE ostream &stream, const size_t flags) const { OFCondition result = DSRCompositeReferenceValue::writeXML(stream, flags); if ((flags & DSRTypes::XF_writeEmptyTags) || !ChannelList.isEmpty()) { stream << "<channels>"; ChannelList.print(stream); stream << "</channels>" << OFendl; } return result; } OFCondition DSRWaveformReferenceValue::readItem(DcmItem &dataset) { /* read ReferencedSOPClassUID and ReferencedSOPInstanceUID */ OFCondition result = DSRCompositeReferenceValue::readItem(dataset); /* read ReferencedWaveformChannels (conditional) */ if (result.good()) ChannelList.read(dataset); return result; } OFCondition DSRWaveformReferenceValue::writeItem(DcmItem &dataset) const { /* write ReferencedSOPClassUID and ReferencedSOPInstanceUID */ OFCondition result = DSRCompositeReferenceValue::writeItem(dataset); /* write ReferencedWaveformChannels (conditional) */ if (result.good()) { if (!ChannelList.isEmpty()) result = ChannelList.write(dataset); } return result; } OFCondition DSRWaveformReferenceValue::renderHTML(STD_NAMESPACE ostream &docStream, STD_NAMESPACE ostream &annexStream, size_t &annexNumber, const size_t flags) const { /* render reference */ docStream << "<a href=\"" << HTML_HYPERLINK_PREFIX_FOR_CGI; docStream << "?waveform=" << SOPClassUID << "+" << SOPInstanceUID; if (!ChannelList.isEmpty()) { docStream << "&amp;channels="; ChannelList.print(docStream, 0 /*flags*/, '+', '+'); } docStream << "\">"; /* retrieve name of SOP class (if known) */ docStream << dcmFindNameOfUID(SOPClassUID.c_str(), "unknown waveform"); docStream << "</a>"; /* render (optional) channel list */ if (!isShort(flags)) { const char *lineBreak = (flags & DSRTypes::HF_renderSectionTitlesInline) ? " " : (flags & DSRTypes::HF_XHTML11Compatibility) ? "<br />" : "<br>"; if (flags & DSRTypes::HF_currentlyInsideAnnex) { docStream << OFendl << "<p>" << OFendl; /* render channel list (= print)*/ docStream << "<b>Referenced Waveform Channels:</b>" << lineBreak; ChannelList.print(docStream); docStream << "</p>"; } else { docStream << " "; DSRTypes::createHTMLAnnexEntry(docStream, annexStream, "for more details see", annexNumber, flags); annexStream << "<p>" << OFendl; /* render channel list (= print)*/ annexStream << "<b>Referenced Waveform Channels:</b>" << lineBreak; ChannelList.print(annexStream); annexStream << "</p>" << OFendl; } } return EC_Normal; } OFCondition DSRWaveformReferenceValue::getValue(DSRWaveformReferenceValue &referenceValue) const { referenceValue = *this; return EC_Normal; } OFCondition DSRWaveformReferenceValue::setValue(const DSRWaveformReferenceValue &referenceValue, const OFBool check) { OFCondition result = DSRCompositeReferenceValue::setValue(referenceValue, check); if (result.good()) ChannelList = referenceValue.ChannelList; return result; } OFBool DSRWaveformReferenceValue::appliesToChannel(const Uint16 multiplexGroupNumber, const Uint16 channelNumber) const { OFBool result = OFTrue; if (!ChannelList.isEmpty()) result = ChannelList.isElement(multiplexGroupNumber, channelNumber); return result; } OFCondition DSRWaveformReferenceValue::checkSOPClassUID(const OFString &sopClassUID) const { OFCondition result = DSRCompositeReferenceValue::checkSOPClassUID(sopClassUID); if (result.good()) { /* check for all valid/known SOP classes (according to DICOM PS 3.6-2011) */ if ((sopClassUID == UID_TwelveLeadECGWaveformStorage) || (sopClassUID == UID_GeneralECGWaveformStorage) || (sopClassUID == UID_AmbulatoryECGWaveformStorage) || (sopClassUID == UID_HemodynamicWaveformStorage) || (sopClassUID == UID_CardiacElectrophysiologyWaveformStorage) || (sopClassUID == UID_BasicVoiceAudioWaveformStorage) || (sopClassUID == UID_GeneralAudioWaveformStorage) || (sopClassUID == UID_ArterialPulseWaveformStorage) || (sopClassUID == UID_RespiratoryWaveformStorage)) { result = SR_EC_InvalidValue; } } return result; }
{ "content_hash": "78e43fd2a13f8598080ddf2dce2310f7", "timestamp": "", "source": "github", "line_count": 235, "max_line_length": 112, "avg_line_length": 33.09787234042553, "alnum_prop": 0.6266392388788892, "repo_name": "NCIP/annotation-and-image-markup", "id": "8d45d628f2d589c41e8269af06577e054d86bc4b", "size": "8167", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AIMToolkit_v4.1.0_rv44/source/dcmtk-3.6.1_20121102/dcmsr/libsrc/dsrwavvl.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "31363450" }, { "name": "C#", "bytes": "5152916" }, { "name": "C++", "bytes": "148605530" }, { "name": "CSS", "bytes": "85406" }, { "name": "Java", "bytes": "2039090" }, { "name": "Objective-C", "bytes": "381107" }, { "name": "Perl", "bytes": "502054" }, { "name": "Shell", "bytes": "11832" }, { "name": "Tcl", "bytes": "30867" } ], "symlink_target": "" }
import { strictEqual } from 'assert'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper'; import { TerminalProcessManager } from 'vs/workbench/contrib/terminal/browser/terminalProcessManager'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { ITestInstantiationService, TestTerminalProfileResolverService, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices'; import { IProductService } from 'vs/platform/product/common/productService'; import { IEnvironmentVariableService } from 'vs/workbench/contrib/terminal/common/environmentVariable'; import { EnvironmentVariableService } from 'vs/workbench/contrib/terminal/common/environmentVariableService'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { ITerminalChildProcess } from 'vs/platform/terminal/common/terminal'; import { ITerminalProfileResolverService } from 'vs/workbench/contrib/terminal/common/terminal'; import { ITerminalInstanceService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { Event } from 'vs/base/common/event'; import { TestProductService } from 'vs/workbench/test/common/workbenchTestServices'; class TestTerminalChildProcess implements ITerminalChildProcess { id: number = 0; get capabilities() { return []; } constructor( readonly shouldPersist: boolean ) { } updateProperty(property: any, value: any): Promise<void> { throw new Error('Method not implemented.'); } onProcessOverrideDimensions?: Event<any> | undefined; onProcessResolvedShellLaunchConfig?: Event<any> | undefined; onDidChangeHasChildProcesses?: Event<any> | undefined; onDidChangeProperty = Event.None; onProcessData = Event.None; onProcessExit = Event.None; onProcessReady = Event.None; onProcessTitleChanged = Event.None; onProcessShellTypeChanged = Event.None; async start(): Promise<undefined> { return undefined; } shutdown(immediate: boolean): void { } input(data: string): void { } resize(cols: number, rows: number): void { } acknowledgeDataEvent(charCount: number): void { } async setUnicodeVersion(version: '6' | '11'): Promise<void> { } async getInitialCwd(): Promise<string> { return ''; } async getCwd(): Promise<string> { return ''; } async getLatency(): Promise<number> { return 0; } async processBinary(data: string): Promise<void> { } refreshProperty(property: any): Promise<any> { return Promise.resolve(''); } } class TestTerminalInstanceService implements Partial<ITerminalInstanceService> { getBackend() { return { onPtyHostExit: Event.None, onPtyHostUnresponsive: Event.None, onPtyHostResponsive: Event.None, onPtyHostRestart: Event.None, onDidMoveWindowInstance: Event.None, onDidRequestDetach: Event.None, createProcess: ( shellLaunchConfig: any, cwd: string, cols: number, rows: number, unicodeVersion: '6' | '11', env: any, windowsEnableConpty: boolean, shouldPersist: boolean ) => new TestTerminalChildProcess(shouldPersist) } as any; } } suite('Workbench - TerminalProcessManager', () => { let disposables: DisposableStore; let instantiationService: ITestInstantiationService; let manager: TerminalProcessManager; setup(async () => { disposables = new DisposableStore(); instantiationService = workbenchInstantiationService(undefined, disposables); const configurationService = new TestConfigurationService(); await configurationService.setUserConfiguration('editor', { fontFamily: 'foo' }); await configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 'bar', enablePersistentSessions: true, shellIntegration: { enabled: false } } }); instantiationService.stub(IConfigurationService, configurationService); instantiationService.stub(IProductService, TestProductService); instantiationService.stub(IEnvironmentVariableService, instantiationService.createInstance(EnvironmentVariableService)); instantiationService.stub(ITerminalProfileResolverService, TestTerminalProfileResolverService); instantiationService.stub(ITerminalInstanceService, new TestTerminalInstanceService()); const configHelper = instantiationService.createInstance(TerminalConfigHelper); manager = instantiationService.createInstance(TerminalProcessManager, 1, configHelper, undefined, undefined); }); teardown(() => { disposables.dispose(); }); suite('process persistence', () => { suite('local', () => { test('regular terminal should persist', async () => { const p = await manager.createProcess({ }, 1, 1, false); strictEqual(p, undefined); strictEqual(manager.shouldPersist, true); }); test('task terminal should not persist', async () => { const p = await manager.createProcess({ isFeatureTerminal: true }, 1, 1, false); strictEqual(p, undefined); strictEqual(manager.shouldPersist, false); }); }); suite('remote', () => { const remoteCwd = URI.from({ scheme: Schemas.vscodeRemote, path: 'test/cwd' }); test('regular terminal should persist', async () => { const p = await manager.createProcess({ cwd: remoteCwd }, 1, 1, false); strictEqual(p, undefined); strictEqual(manager.shouldPersist, true); }); test('task terminal should not persist', async () => { const p = await manager.createProcess({ isFeatureTerminal: true, cwd: remoteCwd }, 1, 1, false); strictEqual(p, undefined); strictEqual(manager.shouldPersist, false); }); }); }); });
{ "content_hash": "cb6b4e1fff42d3ed7d896670fb05a746", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 159, "avg_line_length": 38.5, "alnum_prop": 0.7433766233766234, "repo_name": "microsoft/vscode", "id": "28f71ad6ebfe349c9c8e4c3d8eaa54ca7e86213c", "size": "6126", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "src/vs/workbench/contrib/terminal/test/browser/terminalProcessManager.test.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "19488" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "709" }, { "name": "C++", "bytes": "2745" }, { "name": "CSS", "bytes": "694473" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "Cuda", "bytes": "3634" }, { "name": "Dart", "bytes": "324" }, { "name": "Dockerfile", "bytes": "475" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "652" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "386747" }, { "name": "Hack", "bytes": "16" }, { "name": "Handlebars", "bytes": "1064" }, { "name": "Inno Setup", "bytes": "307296" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "956022" }, { "name": "Julia", "bytes": "940" }, { "name": "Jupyter Notebook", "bytes": "929" }, { "name": "Less", "bytes": "1029" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "2252" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "Objective-C++", "bytes": "1387" }, { "name": "PHP", "bytes": "998" }, { "name": "Perl", "bytes": "1922" }, { "name": "PowerShell", "bytes": "13597" }, { "name": "Pug", "bytes": "654" }, { "name": "Python", "bytes": "2171" }, { "name": "R", "bytes": "362" }, { "name": "Roff", "bytes": "351" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "301179" }, { "name": "SCSS", "bytes": "6732" }, { "name": "Scilab", "bytes": "54706" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "63596" }, { "name": "Swift", "bytes": "284" }, { "name": "TeX", "bytes": "1602" }, { "name": "TypeScript", "bytes": "43400033" }, { "name": "Visual Basic .NET", "bytes": "893" } ], "symlink_target": "" }
<?php namespace phpseclib\Crypt; use phpseclib\Math\BigInteger; /** * Pure-PHP PKCS#1 compliant implementation of RSA. * * @package RSA * @author Jim Wigginton <terrafrost@php.net> * @access public */ class RSA { /**#@+ * @access public * @see self::encrypt() * @see self::decrypt() */ /** * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding} * (OAEP) for encryption / decryption. * * Uses sha1 by default. * * @see self::setHash() * @see self::setMGFHash() */ const ENCRYPTION_OAEP = 1; /** * Use PKCS#1 padding. * * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards * compatibility with protocols (like SSH-1) written before OAEP's introduction. */ const ENCRYPTION_PKCS1 = 2; /** * Do not use any padding * * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc. */ const ENCRYPTION_NONE = 3; /**#@-*/ /**#@+ * @access public * @see self::sign() * @see self::verify() * @see self::setHash() */ /** * Use the Probabilistic Signature Scheme for signing * * Uses sha1 by default. * * @see self::setSaltLength() * @see self::setMGFHash() */ const SIGNATURE_PSS = 1; /** * Use the PKCS#1 scheme by default. * * Although self::SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards * compatibility with protocols (like SSH-2) written before PSS's introduction. */ const SIGNATURE_PKCS1 = 2; /**#@-*/ /**#@+ * @access private * @see \phpseclib\Crypt\RSA::createKey() */ /** * ASN1 Integer */ const ASN1_INTEGER = 2; /** * ASN1 Bit String */ const ASN1_BITSTRING = 3; /** * ASN1 Octet String */ const ASN1_OCTETSTRING = 4; /** * ASN1 Object Identifier */ const ASN1_OBJECT = 6; /** * ASN1 Sequence (with the constucted bit set) */ const ASN1_SEQUENCE = 48; /**#@-*/ /**#@+ * @access private * @see \phpseclib\Crypt\RSA::__construct() */ /** * To use the pure-PHP implementation */ const MODE_INTERNAL = 1; /** * To use the OpenSSL library * * (if enabled; otherwise, the internal implementation will be used) */ const MODE_OPENSSL = 2; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Crypt\RSA::createKey() * @see \phpseclib\Crypt\RSA::setPrivateKeyFormat() */ /** * PKCS#1 formatted private key * * Used by OpenSSH */ const PRIVATE_FORMAT_PKCS1 = 0; /** * PuTTY formatted private key */ const PRIVATE_FORMAT_PUTTY = 1; /** * XML formatted private key */ const PRIVATE_FORMAT_XML = 2; /** * PKCS#8 formatted private key */ const PRIVATE_FORMAT_PKCS8 = 8; /** * OpenSSH formatted private key */ const PRIVATE_FORMAT_OPENSSH = 9; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Crypt\RSA::createKey() * @see \phpseclib\Crypt\RSA::setPublicKeyFormat() */ /** * Raw public key * * An array containing two \phpseclib\Math\BigInteger objects. * * The exponent can be indexed with any of the following: * * 0, e, exponent, publicExponent * * The modulus can be indexed with any of the following: * * 1, n, modulo, modulus */ const PUBLIC_FORMAT_RAW = 3; /** * PKCS#1 formatted public key (raw) * * Used by File/X509.php * * Has the following header: * * -----BEGIN RSA PUBLIC KEY----- * * Analogous to ssh-keygen's pem format (as specified by -m) */ const PUBLIC_FORMAT_PKCS1 = 4; const PUBLIC_FORMAT_PKCS1_RAW = 4; /** * XML formatted public key */ const PUBLIC_FORMAT_XML = 5; /** * OpenSSH formatted public key * * Place in $HOME/.ssh/authorized_keys */ const PUBLIC_FORMAT_OPENSSH = 6; /** * PKCS#1 formatted public key (encapsulated) * * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set) * * Has the following header: * * -----BEGIN PUBLIC KEY----- * * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8 * is specific to private keys it's basically creating a DER-encoded wrapper * for keys. This just extends that same concept to public keys (much like ssh-keygen) */ const PUBLIC_FORMAT_PKCS8 = 7; /**#@-*/ /** * Precomputed Zero * * @var \phpseclib\Math\BigInteger * @access private */ var $zero; /** * Precomputed One * * @var \phpseclib\Math\BigInteger * @access private */ var $one; /** * Private Key Format * * @var int * @access private */ var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1; /** * Public Key Format * * @var int * @access public */ var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8; /** * Modulus (ie. n) * * @var \phpseclib\Math\BigInteger * @access private */ var $modulus; /** * Modulus length * * @var \phpseclib\Math\BigInteger * @access private */ var $k; /** * Exponent (ie. e or d) * * @var \phpseclib\Math\BigInteger * @access private */ var $exponent; /** * Primes for Chinese Remainder Theorem (ie. p and q) * * @var array * @access private */ var $primes; /** * Exponents for Chinese Remainder Theorem (ie. dP and dQ) * * @var array * @access private */ var $exponents; /** * Coefficients for Chinese Remainder Theorem (ie. qInv) * * @var array * @access private */ var $coefficients; /** * Hash name * * @var string * @access private */ var $hashName; /** * Hash function * * @var \phpseclib\Crypt\Hash * @access private */ var $hash; /** * Length of hash function output * * @var int * @access private */ var $hLen; /** * Length of salt * * @var int * @access private */ var $sLen; /** * Hash function for the Mask Generation Function * * @var \phpseclib\Crypt\Hash * @access private */ var $mgfHash; /** * Length of MGF hash function output * * @var int * @access private */ var $mgfHLen; /** * Encryption mode * * @var int * @access private */ var $encryptionMode = self::ENCRYPTION_OAEP; /** * Signature mode * * @var int * @access private */ var $signatureMode = self::SIGNATURE_PSS; /** * Public Exponent * * @var mixed * @access private */ var $publicExponent = false; /** * Password * * @var string * @access private */ var $password = false; /** * Components * * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions - * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't. * * @see self::_start_element_handler() * @var array * @access private */ var $components = array(); /** * Current String * * For use with parsing XML formatted keys. * * @see self::_character_handler() * @see self::_stop_element_handler() * @var mixed * @access private */ var $current; /** * OpenSSL configuration file name. * * Set to null to use system configuration file. * @see self::createKey() * @var mixed * @Access public */ var $configFile; /** * Public key comment field. * * @var string * @access private */ var $comment = 'phpseclib-generated-key'; /** * The constructor * * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason * \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late. * * @return \phpseclib\Crypt\RSA * @access public */ function __construct() { $this->configFile = dirname(__FILE__) . '/../openssl.cnf'; if (!defined('CRYPT_RSA_MODE')) { switch (true) { // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular, // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either. case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'): define('CRYPT_RSA_MODE', self::MODE_INTERNAL); break; case extension_loaded('openssl') && file_exists($this->configFile): // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work $versions = array(); // avoid generating errors (even with suppression) when phpinfo() is disabled (common in production systems) if (strpos(ini_get('disable_functions'), 'phpinfo') === false) { ob_start(); @phpinfo(); $content = ob_get_contents(); ob_end_clean(); preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches); if (!empty($matches[1])) { for ($i = 0; $i < count($matches[1]); $i++) { $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i]))); // Remove letter part in OpenSSL version if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) { $versions[$matches[1][$i]] = $fullVersion; } else { $versions[$matches[1][$i]] = $m[0]; } } } } // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+ switch (true) { case !isset($versions['Header']): case !isset($versions['Library']): case $versions['Header'] == $versions['Library']: case version_compare($versions['Header'], '1.0.0') >= 0 && version_compare($versions['Library'], '1.0.0') >= 0: define('CRYPT_RSA_MODE', self::MODE_OPENSSL); break; default: define('CRYPT_RSA_MODE', self::MODE_INTERNAL); define('MATH_BIGINTEGER_OPENSSL_DISABLE', true); } break; default: define('CRYPT_RSA_MODE', self::MODE_INTERNAL); } } $this->zero = new BigInteger(); $this->one = new BigInteger(1); $this->hash = new Hash('sha1'); $this->hLen = $this->hash->getLength(); $this->hashName = 'sha1'; $this->mgfHash = new Hash('sha1'); $this->mgfHLen = $this->mgfHash->getLength(); } /** * Create public / private key pair * * Returns an array with the following three elements: * - 'privatekey': The private key. * - 'publickey': The public key. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout). * Will need to be passed back to \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing. * * @access public * @param int $bits * @param int $timeout * @param array $p */ function createKey($bits = 1024, $timeout = false, $partial = array()) { if (!defined('CRYPT_RSA_EXPONENT')) { // http://en.wikipedia.org/wiki/65537_%28number%29 define('CRYPT_RSA_EXPONENT', '65537'); } // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if // CRYPT_RSA_MODE is set to self::MODE_INTERNAL. if CRYPT_RSA_MODE is set to self::MODE_OPENSSL then // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key // generation when there's a chance neither gmp nor OpenSSL are installed) if (!defined('CRYPT_RSA_SMALLEST_PRIME')) { define('CRYPT_RSA_SMALLEST_PRIME', 4096); } // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum if (CRYPT_RSA_MODE == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) { $config = array(); if (isset($this->configFile)) { $config['config'] = $this->configFile; } $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config); openssl_pkey_export($rsa, $privatekey, null, $config); $publickey = openssl_pkey_get_details($rsa); $publickey = $publickey['key']; $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, self::PRIVATE_FORMAT_PKCS1))); $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, self::PUBLIC_FORMAT_PKCS1))); // clear the buffer of error strings stemming from a minimalistic openssl.cnf while (openssl_error_string() !== false) { } return array( 'privatekey' => $privatekey, 'publickey' => $publickey, 'partialkey' => false ); } static $e; if (!isset($e)) { $e = new BigInteger(CRYPT_RSA_EXPONENT); } extract($this->_generateMinMax($bits)); $absoluteMin = $min; $temp = $bits >> 1; // divide by two to see how many bits P and Q would be if ($temp > CRYPT_RSA_SMALLEST_PRIME) { $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME); $temp = CRYPT_RSA_SMALLEST_PRIME; } else { $num_primes = 2; } extract($this->_generateMinMax($temp + $bits % $temp)); $finalMax = $max; extract($this->_generateMinMax($temp)); $generator = new BigInteger(); $n = $this->one->copy(); if (!empty($partial)) { extract(unserialize($partial)); } else { $exponents = $coefficients = $primes = array(); $lcm = array( 'top' => $this->one->copy(), 'bottom' => false ); } $start = time(); $i0 = count($primes) + 1; do { for ($i = $i0; $i <= $num_primes; $i++) { if ($timeout !== false) { $timeout-= time() - $start; $start = time(); if ($timeout <= 0) { return array( 'privatekey' => '', 'publickey' => '', 'partialkey' => serialize(array( 'primes' => $primes, 'coefficients' => $coefficients, 'lcm' => $lcm, 'exponents' => $exponents )) ); } } if ($i == $num_primes) { list($min, $temp) = $absoluteMin->divide($n); if (!$temp->equals($this->zero)) { $min = $min->add($this->one); // ie. ceil() } $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout); } else { $primes[$i] = $generator->randomPrime($min, $max, $timeout); } if ($primes[$i] === false) { // if we've reached the timeout if (count($primes) > 1) { $partialkey = ''; } else { array_pop($primes); $partialkey = serialize(array( 'primes' => $primes, 'coefficients' => $coefficients, 'lcm' => $lcm, 'exponents' => $exponents )); } return array( 'privatekey' => '', 'publickey' => '', 'partialkey' => $partialkey ); } // the first coefficient is calculated differently from the rest // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1]) if ($i > 2) { $coefficients[$i] = $n->modInverse($primes[$i]); } $n = $n->multiply($primes[$i]); $temp = $primes[$i]->subtract($this->one); // textbook RSA implementations use Euler's totient function instead of the least common multiple. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function $lcm['top'] = $lcm['top']->multiply($temp); $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp); $exponents[$i] = $e->modInverse($temp); } list($temp) = $lcm['top']->divide($lcm['bottom']); $gcd = $temp->gcd($e); $i0 = 1; } while (!$gcd->equals($this->one)); $d = $e->modInverse($temp); $coefficients[2] = $primes[2]->modInverse($primes[1]); // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>: // RSAPrivateKey ::= SEQUENCE { // version Version, // modulus INTEGER, -- n // publicExponent INTEGER, -- e // privateExponent INTEGER, -- d // prime1 INTEGER, -- p // prime2 INTEGER, -- q // exponent1 INTEGER, -- d mod (p-1) // exponent2 INTEGER, -- d mod (q-1) // coefficient INTEGER, -- (inverse of q) mod p // otherPrimeInfos OtherPrimeInfos OPTIONAL // } return array( 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients), 'publickey' => $this->_convertPublicKey($n, $e), 'partialkey' => false ); } /** * Convert a private key to the appropriate format. * * @access private * @see self::setPrivateKeyFormat() * @param string $RSAPrivateKey * @return string */ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients) { $signed = $this->privateKeyFormat != self::PRIVATE_FORMAT_XML; $num_primes = count($primes); $raw = array( 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi 'modulus' => $n->toBytes($signed), 'publicExponent' => $e->toBytes($signed), 'privateExponent' => $d->toBytes($signed), 'prime1' => $primes[1]->toBytes($signed), 'prime2' => $primes[2]->toBytes($signed), 'exponent1' => $exponents[1]->toBytes($signed), 'exponent2' => $exponents[2]->toBytes($signed), 'coefficient' => $coefficients[2]->toBytes($signed) ); // if the format in question does not support multi-prime rsa and multi-prime rsa was used, // call _convertPublicKey() instead. switch ($this->privateKeyFormat) { case self::PRIVATE_FORMAT_XML: if ($num_primes != 2) { return false; } return "<RSAKeyValue>\r\n" . ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" . ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" . ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" . ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" . ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" . ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" . ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" . ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" . '</RSAKeyValue>'; break; case self::PRIVATE_FORMAT_PUTTY: if ($num_primes != 2) { return false; } $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: "; $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none'; $key.= $encryption; $key.= "\r\nComment: " . $this->comment . "\r\n"; $public = pack( 'Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus'] ); $source = pack( 'Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption, strlen($this->comment), $this->comment, strlen($public), $public ); $public = base64_encode($public); $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n"; $key.= chunk_split($public, 64); $private = pack( 'Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient'] ); if (empty($this->password) && !is_string($this->password)) { $source.= pack('Na*', strlen($private), $private); $hashkey = 'putty-private-key-file-mac-key'; } else { $private.= Random::string(16 - (strlen($private) & 15)); $source.= pack('Na*', strlen($private), $private); $sequence = 0; $symkey = ''; while (strlen($symkey) < 32) { $temp = pack('Na*', $sequence++, $this->password); $symkey.= pack('H*', sha1($temp)); } $symkey = substr($symkey, 0, 32); $crypto = new AES(); $crypto->setKey($symkey); $crypto->disablePadding(); $private = $crypto->encrypt($private); $hashkey = 'putty-private-key-file-mac-key' . $this->password; } $private = base64_encode($private); $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n"; $key.= chunk_split($private, 64); $hash = new Hash('sha1'); $hash->setKey(pack('H*', sha1($hashkey))); $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n"; return $key; case self::PRIVATE_FORMAT_OPENSSH: if ($num_primes != 2) { return false; } $publicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']); $privateKey = pack( 'Na*Na*Na*Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['modulus']), $raw['modulus'], strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['coefficient']), $raw['coefficient'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'] ); $checkint = Random::string(4); $paddedKey = pack( 'a*Na*', $checkint . $checkint . $privateKey, strlen($this->comment), $this->comment ); $paddingLength = (7 * strlen($paddedKey)) % 8; for ($i = 1; $i <= $paddingLength; $i++) { $paddedKey.= chr($i); } $key = pack( 'Na*Na*Na*NNa*Na*', strlen('none'), 'none', strlen('none'), 'none', 0, '', 1, strlen($publicKey), $publicKey, strlen($paddedKey), $paddedKey ); $key = "openssh-key-v1\0$key"; return "-----BEGIN OPENSSH PRIVATE KEY-----\r\n" . chunk_split(base64_encode($key), 70) . "-----END OPENSSH PRIVATE KEY-----"; default: // eg. self::PRIVATE_FORMAT_PKCS1 $components = array(); foreach ($raw as $name => $value) { $components[$name] = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value); } $RSAPrivateKey = implode('', $components); if ($num_primes > 2) { $OtherPrimeInfos = ''; for ($i = 3; $i <= $num_primes; $i++) { // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo // // OtherPrimeInfo ::= SEQUENCE { // prime INTEGER, -- ri // exponent INTEGER, -- di // coefficient INTEGER -- ti // } $OtherPrimeInfo = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true)); $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true)); $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true)); $OtherPrimeInfos.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo); } $RSAPrivateKey.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos); } $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); if ($this->privateKeyFormat == self::PRIVATE_FORMAT_PKCS8) { $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $RSAPrivateKey = pack( 'Ca*a*Ca*a*', self::ASN1_INTEGER, "\01\00", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey ); $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); if (!empty($this->password) || is_string($this->password)) { $salt = Random::string(8); $iterationCount = 2048; $crypto = new DES(); $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey); $parameters = pack( 'Ca*a*Ca*N', self::ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt, self::ASN1_INTEGER, $this->_encodeLength(4), $iterationCount ); $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03"; $encryptionAlgorithm = pack( 'Ca*a*Ca*a*', self::ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC, self::ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters ); $RSAPrivateKey = pack( 'Ca*a*Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm, self::ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey ); $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END ENCRYPTED PRIVATE KEY-----'; } else { $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END PRIVATE KEY-----'; } return $RSAPrivateKey; } if (!empty($this->password) || is_string($this->password)) { $iv = Random::string(8); $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8); $des = new TripleDES(); $des->setKey($symkey); $des->setIV($iv); $iv = strtoupper(bin2hex($iv)); $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . "Proc-Type: 4,ENCRYPTED\r\n" . "DEK-Info: DES-EDE3-CBC,$iv\r\n" . "\r\n" . chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) . '-----END RSA PRIVATE KEY-----'; } else { $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END RSA PRIVATE KEY-----'; } return $RSAPrivateKey; } } /** * Convert a public key to the appropriate format * * @access private * @see self::setPublicKeyFormat() * @param string $RSAPrivateKey * @return string */ function _convertPublicKey($n, $e) { $signed = $this->publicKeyFormat != self::PUBLIC_FORMAT_XML; $modulus = $n->toBytes($signed); $publicExponent = $e->toBytes($signed); switch ($this->publicKeyFormat) { case self::PUBLIC_FORMAT_RAW: return array('e' => $e->copy(), 'n' => $n->copy()); case self::PUBLIC_FORMAT_XML: return "<RSAKeyValue>\r\n" . ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" . ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" . '</RSAKeyValue>'; break; case self::PUBLIC_FORMAT_OPENSSH: // from <http://tools.ietf.org/html/rfc4253#page-15>: // string "ssh-rsa" // mpint e // mpint n $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus); $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment; return $RSAPublicKey; default: // eg. self::PUBLIC_FORMAT_PKCS1_RAW or self::PUBLIC_FORMAT_PKCS1 // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>: // RSAPublicKey ::= SEQUENCE { // modulus INTEGER, -- n // publicExponent INTEGER -- e // } $components = array( 'modulus' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus), 'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent) ); $RSAPublicKey = pack( 'Ca*a*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent'] ); if ($this->publicKeyFormat == self::PUBLIC_FORMAT_PKCS1_RAW) { $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split(base64_encode($RSAPublicKey), 64) . '-----END RSA PUBLIC KEY-----'; } else { // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $RSAPublicKey = chr(0) . $RSAPublicKey; $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey; $RSAPublicKey = pack( 'Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey ); $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split(base64_encode($RSAPublicKey), 64) . '-----END PUBLIC KEY-----'; } return $RSAPublicKey; } } /** * Break a public or private key down into its constituant components * * @access private * @see self::_convertPublicKey() * @see self::_convertPrivateKey() * @param string|array $key * @param int $type * @return array|bool */ function _parseKey($key, $type) { if ($type != self::PUBLIC_FORMAT_RAW && !is_string($key)) { return false; } switch ($type) { case self::PUBLIC_FORMAT_RAW: if (!is_array($key)) { return false; } $components = array(); switch (true) { case isset($key['e']): $components['publicExponent'] = $key['e']->copy(); break; case isset($key['exponent']): $components['publicExponent'] = $key['exponent']->copy(); break; case isset($key['publicExponent']): $components['publicExponent'] = $key['publicExponent']->copy(); break; case isset($key[0]): $components['publicExponent'] = $key[0]->copy(); } switch (true) { case isset($key['n']): $components['modulus'] = $key['n']->copy(); break; case isset($key['modulo']): $components['modulus'] = $key['modulo']->copy(); break; case isset($key['modulus']): $components['modulus'] = $key['modulus']->copy(); break; case isset($key[1]): $components['modulus'] = $key[1]->copy(); } return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false; case self::PRIVATE_FORMAT_PKCS1: case self::PRIVATE_FORMAT_PKCS8: case self::PUBLIC_FORMAT_PKCS1: /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here: http://tools.ietf.org/html/rfc1421#section-4.6.1.1 http://tools.ietf.org/html/rfc1421#section-4.6.1.3 DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's own implementation. ie. the implementation *is* the standard and any bugs that may exist in that implementation are part of the standard, as well. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */ if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) { $iv = pack('H*', trim($matches[2])); $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8))); // remove the Proc-Type / DEK-Info sections as they're no longer needed $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key); $ciphertext = $this->_extractBER($key); if ($ciphertext === false) { $ciphertext = $key; } switch ($matches[1]) { case 'AES-256-CBC': $crypto = new AES(); break; case 'AES-128-CBC': $symkey = substr($symkey, 0, 16); $crypto = new AES(); break; case 'DES-EDE3-CFB': $crypto = new TripleDES(Base::MODE_CFB); break; case 'DES-EDE3-CBC': $symkey = substr($symkey, 0, 24); $crypto = new TripleDES(); break; case 'DES-CBC': $crypto = new DES(); break; default: return false; } $crypto->setKey($symkey); $crypto->setIV($iv); $decoded = $crypto->decrypt($ciphertext); } else { $decoded = $this->_extractBER($key); } if ($decoded !== false) { $key = $decoded; } $components = array(); if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($key) != strlen($key)) { return false; } $tag = ord($this->_string_shift($key)); /* intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 631 cons: SEQUENCE 4:d=1 hl=2 l= 1 prim: INTEGER :00 7:d=1 hl=2 l= 13 cons: SEQUENCE 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 20:d=2 hl=2 l= 0 prim: NULL 22:d=1 hl=4 l= 609 prim: OCTET STRING ie. PKCS8 keys*/ if ($tag == self::ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") { $this->_string_shift($key, 3); $tag = self::ASN1_SEQUENCE; } if ($tag == self::ASN1_SEQUENCE) { $temp = $this->_string_shift($key, $this->_decodeLength($key)); if (ord($this->_string_shift($temp)) != self::ASN1_OBJECT) { return false; } $length = $this->_decodeLength($temp); switch ($this->_string_shift($temp, $length)) { case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption break; case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC /* PBEParameter ::= SEQUENCE { salt OCTET STRING (SIZE(8)), iterationCount INTEGER } */ if (ord($this->_string_shift($temp)) != self::ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($temp) != strlen($temp)) { return false; } $this->_string_shift($temp); // assume it's an octet string $salt = $this->_string_shift($temp, $this->_decodeLength($temp)); if (ord($this->_string_shift($temp)) != self::ASN1_INTEGER) { return false; } $this->_decodeLength($temp); list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT)); $this->_string_shift($key); // assume it's an octet string $length = $this->_decodeLength($key); if (strlen($key) != $length) { return false; } $crypto = new DES(); $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); $key = $crypto->decrypt($key); if ($key === false) { return false; } return $this->_parseKey($key, self::PRIVATE_FORMAT_PKCS1); default: return false; } /* intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 290 cons: SEQUENCE 4:d=1 hl=2 l= 13 cons: SEQUENCE 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 17:d=2 hl=2 l= 0 prim: NULL 19:d=1 hl=4 l= 271 prim: BIT STRING */ $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of // unused bits in the final subsequent octet. The number shall be in the range zero to seven." // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2) if ($tag == self::ASN1_BITSTRING) { $this->_string_shift($key); } if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($key) != strlen($key)) { return false; } $tag = ord($this->_string_shift($key)); } if ($tag != self::ASN1_INTEGER) { return false; } $length = $this->_decodeLength($key); $temp = $this->_string_shift($key, $length); if (strlen($temp) != 1 || ord($temp) > 2) { $components['modulus'] = new BigInteger($temp, 256); $this->_string_shift($key); // skip over self::ASN1_INTEGER $length = $this->_decodeLength($key); $components[$type == self::PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256); return $components; } if (ord($this->_string_shift($key)) != self::ASN1_INTEGER) { return false; } $length = $this->_decodeLength($key); $components['modulus'] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['publicExponent'] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['primes'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256)); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256)); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($key, $length), 256)); if (!empty($key)) { if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } $this->_decodeLength($key); while (!empty($key)) { if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } $this->_decodeLength($key); $key = substr($key, 1); $length = $this->_decodeLength($key); $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['coefficients'][] = new BigInteger($this->_string_shift($key, $length), 256); } } return $components; case self::PUBLIC_FORMAT_OPENSSH: $parts = explode(' ', $key, 3); $key = isset($parts[1]) ? base64_decode($parts[1]) : false; if ($key === false) { return false; } $comment = isset($parts[2]) ? $parts[2] : false; $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa"; if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $publicExponent = new BigInteger($this->_string_shift($key, $length), -256); if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $modulus = new BigInteger($this->_string_shift($key, $length), -256); if ($cleanup && strlen($key)) { if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $realModulus = new BigInteger($this->_string_shift($key, $length), -256); return strlen($key) ? false : array( 'modulus' => $realModulus, 'publicExponent' => $modulus, 'comment' => $comment ); } else { return strlen($key) ? false : array( 'modulus' => $modulus, 'publicExponent' => $publicExponent, 'comment' => $comment ); } // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue // http://en.wikipedia.org/wiki/XML_Signature case self::PRIVATE_FORMAT_XML: case self::PUBLIC_FORMAT_XML: $this->components = array(); $xml = xml_parser_create('UTF-8'); xml_set_object($xml, $this); xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler'); xml_set_character_data_handler($xml, '_data_handler'); // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added if (!xml_parse($xml, '<xml>' . $key . '</xml>')) { xml_parser_free($xml); unset($xml); return false; } xml_parser_free($xml); unset($xml); return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false; // from PuTTY's SSHPUBK.C case self::PRIVATE_FORMAT_PUTTY: $components = array(); $key = preg_split('#\r\n|\r|\n#', $key); $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0])); if ($type != 'ssh-rsa') { return false; } $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1])); $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2])); $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3])); $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength)))); $public = substr($public, 11); extract(unpack('Nlength', $this->_string_shift($public, 4))); $components['publicExponent'] = new BigInteger($this->_string_shift($public, $length), -256); extract(unpack('Nlength', $this->_string_shift($public, 4))); $components['modulus'] = new BigInteger($this->_string_shift($public, $length), -256); $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4])); $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength)))); switch ($encryption) { case 'aes256-cbc': $symkey = ''; $sequence = 0; while (strlen($symkey) < 32) { $temp = pack('Na*', $sequence++, $this->password); $symkey.= pack('H*', sha1($temp)); } $symkey = substr($symkey, 0, 32); $crypto = new AES(); } if ($encryption != 'none') { $crypto->setKey($symkey); $crypto->disablePadding(); $private = $crypto->decrypt($private); if ($private === false) { return false; } } extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['privateExponent'] = new BigInteger($this->_string_shift($private, $length), -256); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['primes'] = array(1 => new BigInteger($this->_string_shift($private, $length), -256)); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['primes'][] = new BigInteger($this->_string_shift($private, $length), -256); $temp = $components['primes'][1]->subtract($this->one); $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp)); $temp = $components['primes'][2]->subtract($this->one); $components['exponents'][] = $components['publicExponent']->modInverse($temp); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($private, $length), -256)); return $components; case self::PRIVATE_FORMAT_OPENSSH: $components = array(); $decoded = $this->_extractBER($key); $magic = $this->_string_shift($decoded, 15); if ($magic !== "openssh-key-v1\0") { return false; } $options = $this->_string_shift($decoded, 24); // \0\0\0\4none = ciphername // \0\0\0\4none = kdfname // \0\0\0\0 = kdfoptions // \0\0\0\1 = numkeys if ($options != "\0\0\0\4none\0\0\0\4none\0\0\0\0\0\0\0\1") { return false; } extract(unpack('Nlength', $this->_string_shift($decoded, 4))); if (strlen($decoded) < $length) { return false; } $publicKey = $this->_string_shift($decoded, $length); extract(unpack('Nlength', $this->_string_shift($decoded, 4))); if (strlen($decoded) < $length) { return false; } $paddedKey = $this->_string_shift($decoded, $length); if ($this->_string_shift($publicKey, 11) !== "\0\0\0\7ssh-rsa") { return false; } $checkint1 = $this->_string_shift($paddedKey, 4); $checkint2 = $this->_string_shift($paddedKey, 4); if (strlen($checkint1) != 4 || $checkint1 !== $checkint2) { return false; } if ($this->_string_shift($paddedKey, 11) !== "\0\0\0\7ssh-rsa") { return false; } $values = array( &$components['modulus'], &$components['publicExponent'], &$components['privateExponent'], &$components['coefficients'][2], &$components['primes'][1], &$components['primes'][2] ); foreach ($values as &$value) { extract(unpack('Nlength', $this->_string_shift($paddedKey, 4))); if (strlen($paddedKey) < $length) { return false; } $value = new BigInteger($this->_string_shift($paddedKey, $length), -256); } extract(unpack('Nlength', $this->_string_shift($paddedKey, 4))); if (strlen($paddedKey) < $length) { return false; } $components['comment'] = $this->_string_shift($decoded, $length); $temp = $components['primes'][1]->subtract($this->one); $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp)); $temp = $components['primes'][2]->subtract($this->one); $components['exponents'][] = $components['publicExponent']->modInverse($temp); return $components; } return false; } /** * Returns the key size * * More specifically, this returns the size of the modulo in bits. * * @access public * @return int */ function getSize() { return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits()); } /** * Start Element Handler * * Called by xml_set_element_handler() * * @access private * @param resource $parser * @param string $name * @param array $attribs */ function _start_element_handler($parser, $name, $attribs) { //$name = strtoupper($name); switch ($name) { case 'MODULUS': $this->current = &$this->components['modulus']; break; case 'EXPONENT': $this->current = &$this->components['publicExponent']; break; case 'P': $this->current = &$this->components['primes'][1]; break; case 'Q': $this->current = &$this->components['primes'][2]; break; case 'DP': $this->current = &$this->components['exponents'][1]; break; case 'DQ': $this->current = &$this->components['exponents'][2]; break; case 'INVERSEQ': $this->current = &$this->components['coefficients'][2]; break; case 'D': $this->current = &$this->components['privateExponent']; } $this->current = ''; } /** * Stop Element Handler * * Called by xml_set_element_handler() * * @access private * @param resource $parser * @param string $name */ function _stop_element_handler($parser, $name) { if (isset($this->current)) { $this->current = new BigInteger(base64_decode($this->current), 256); unset($this->current); } } /** * Data Handler * * Called by xml_set_character_data_handler() * * @access private * @param resource $parser * @param string $data */ function _data_handler($parser, $data) { if (!isset($this->current) || is_object($this->current)) { return; } $this->current.= trim($data); } /** * Loads a public or private key * * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed) * * @access public * @param string|RSA|array $key * @param bool|int $type optional * @return bool */ function loadKey($key, $type = false) { if ($key instanceof RSA) { $this->privateKeyFormat = $key->privateKeyFormat; $this->publicKeyFormat = $key->publicKeyFormat; $this->k = $key->k; $this->hLen = $key->hLen; $this->sLen = $key->sLen; $this->mgfHLen = $key->mgfHLen; $this->encryptionMode = $key->encryptionMode; $this->signatureMode = $key->signatureMode; $this->password = $key->password; $this->configFile = $key->configFile; $this->comment = $key->comment; if (is_object($key->hash)) { $this->hash = new Hash($key->hash->getHash()); } if (is_object($key->mgfHash)) { $this->mgfHash = new Hash($key->mgfHash->getHash()); } if (is_object($key->modulus)) { $this->modulus = $key->modulus->copy(); } if (is_object($key->exponent)) { $this->exponent = $key->exponent->copy(); } if (is_object($key->publicExponent)) { $this->publicExponent = $key->publicExponent->copy(); } $this->primes = array(); $this->exponents = array(); $this->coefficients = array(); foreach ($this->primes as $prime) { $this->primes[] = $prime->copy(); } foreach ($this->exponents as $exponent) { $this->exponents[] = $exponent->copy(); } foreach ($this->coefficients as $coefficient) { $this->coefficients[] = $coefficient->copy(); } return true; } if ($type === false) { $types = array( self::PUBLIC_FORMAT_RAW, self::PRIVATE_FORMAT_PKCS1, self::PRIVATE_FORMAT_XML, self::PRIVATE_FORMAT_PUTTY, self::PUBLIC_FORMAT_OPENSSH, self::PRIVATE_FORMAT_OPENSSH ); foreach ($types as $type) { $components = $this->_parseKey($key, $type); if ($components !== false) { break; } } } else { $components = $this->_parseKey($key, $type); } if ($components === false) { $this->comment = null; $this->modulus = null; $this->k = null; $this->exponent = null; $this->primes = null; $this->exponents = null; $this->coefficients = null; $this->publicExponent = null; return false; } if (isset($components['comment']) && $components['comment'] !== false) { $this->comment = $components['comment']; } $this->modulus = $components['modulus']; $this->k = strlen($this->modulus->toBytes()); $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent']; if (isset($components['primes'])) { $this->primes = $components['primes']; $this->exponents = $components['exponents']; $this->coefficients = $components['coefficients']; $this->publicExponent = $components['publicExponent']; } else { $this->primes = array(); $this->exponents = array(); $this->coefficients = array(); $this->publicExponent = false; } switch ($type) { case self::PUBLIC_FORMAT_OPENSSH: case self::PUBLIC_FORMAT_RAW: $this->setPublicKey(); break; case self::PRIVATE_FORMAT_PKCS1: switch (true) { case strpos($key, '-BEGIN PUBLIC KEY-') !== false: case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false: $this->setPublicKey(); } } return true; } /** * Sets the password * * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false. * Or rather, pass in $password such that empty($password) && !is_string($password) is true. * * @see self::createKey() * @see self::loadKey() * @access public * @param string $password */ function setPassword($password = false) { $this->password = $password; } /** * Defines the public key * * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being * public. * * Do note that when a new key is loaded the index will be cleared. * * Returns true on success, false on failure * * @see self::getPublicKey() * @access public * @param string $key optional * @param int $type optional * @return bool */ function setPublicKey($key = false, $type = false) { // if a public key has already been loaded return false if (!empty($this->publicExponent)) { return false; } if ($key === false && !empty($this->modulus)) { $this->publicExponent = $this->exponent; return true; } if ($type === false) { $types = array( self::PUBLIC_FORMAT_RAW, self::PUBLIC_FORMAT_PKCS1, self::PUBLIC_FORMAT_XML, self::PUBLIC_FORMAT_OPENSSH ); foreach ($types as $type) { $components = $this->_parseKey($key, $type); if ($components !== false) { break; } } } else { $components = $this->_parseKey($key, $type); } if ($components === false) { return false; } if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) { $this->modulus = $components['modulus']; $this->exponent = $this->publicExponent = $components['publicExponent']; return true; } $this->publicExponent = $components['publicExponent']; return true; } /** * Defines the private key * * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force * phpseclib to treat the key as a private key. This function will do that. * * Do note that when a new key is loaded the index will be cleared. * * Returns true on success, false on failure * * @see self::getPublicKey() * @access public * @param string $key optional * @param int $type optional * @return bool */ function setPrivateKey($key = false, $type = false) { if ($key === false && !empty($this->publicExponent)) { $this->publicExponent = false; return true; } $rsa = new RSA(); if (!$rsa->loadKey($key, $type)) { return false; } $rsa->publicExponent = false; // don't overwrite the old key if the new key is invalid $this->loadKey($rsa); return true; } /** * Returns the public key * * The public key is only returned under two circumstances - if the private key had the public key embedded within it * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this * function won't return it since this library, for the most part, doesn't distinguish between public and private keys. * * @see self::getPublicKey() * @access public * @param string $key * @param int $type optional */ function getPublicKey($type = self::PUBLIC_FORMAT_PKCS8) { if (empty($this->modulus) || empty($this->publicExponent)) { return false; } $oldFormat = $this->publicKeyFormat; $this->publicKeyFormat = $type; $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent); $this->publicKeyFormat = $oldFormat; return $temp; } /** * Returns the public key's fingerprint * * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is * no public key currently loaded, false is returned. * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716) * * @access public * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned * for invalid values. * @return mixed */ function getPublicKeyFingerprint($algorithm = 'md5') { if (empty($this->modulus) || empty($this->publicExponent)) { return false; } $modulus = $this->modulus->toBytes(true); $publicExponent = $this->publicExponent->toBytes(true); $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus); switch ($algorithm) { case 'sha256': $hash = new Hash('sha256'); $base = base64_encode($hash->hash($RSAPublicKey)); return substr($base, 0, strlen($base) - 1); case 'md5': return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1); default: return false; } } /** * Returns the private key * * The private key is only returned if the currently loaded key contains the constituent prime numbers. * * @see self::getPublicKey() * @access public * @param string $key * @param int $type optional * @return mixed */ function getPrivateKey($type = self::PUBLIC_FORMAT_PKCS1) { if (empty($this->primes)) { return false; } $oldFormat = $this->privateKeyFormat; $this->privateKeyFormat = $type; $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients); $this->privateKeyFormat = $oldFormat; return $temp; } /** * Returns a minimalistic private key * * Returns the private key without the prime number constituants. Structurally identical to a public key that * hasn't been set as the public key * * @see self::getPrivateKey() * @access private * @param string $key * @param int $type optional */ function _getPrivatePublicKey($mode = self::PUBLIC_FORMAT_PKCS8) { if (empty($this->modulus) || empty($this->exponent)) { return false; } $oldFormat = $this->publicKeyFormat; $this->publicKeyFormat = $mode; $temp = $this->_convertPublicKey($this->modulus, $this->exponent); $this->publicKeyFormat = $oldFormat; return $temp; } /** * __toString() magic method * * @access public * @return string */ function __toString() { $key = $this->getPrivateKey($this->privateKeyFormat); if ($key !== false) { return $key; } $key = $this->_getPrivatePublicKey($this->publicKeyFormat); return $key !== false ? $key : ''; } /** * __clone() magic method * * @access public * @return Crypt_RSA */ function __clone() { $key = new RSA(); $key->loadKey($this); return $key; } /** * Generates the smallest and largest numbers requiring $bits bits * * @access private * @param int $bits * @return array */ function _generateMinMax($bits) { $bytes = $bits >> 3; $min = str_repeat(chr(0), $bytes); $max = str_repeat(chr(0xFF), $bytes); $msb = $bits & 7; if ($msb) { $min = chr(1 << ($msb - 1)) . $min; $max = chr((1 << $msb) - 1) . $max; } else { $min[0] = chr(0x80); } return array( 'min' => new BigInteger($min, 256), 'max' => new BigInteger($max, 256) ); } /** * DER-decode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private * @param string $string * @return int */ function _decodeLength(&$string) { $length = ord($this->_string_shift($string)); if ($length & 0x80) { // definite length, long form $length&= 0x7F; $temp = $this->_string_shift($string, $length); list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)); } return $length; } /** * DER-encode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private * @param int $length * @return string */ function _encodeLength($length) { if ($length <= 0x7F) { return chr($length); } $temp = ltrim(pack('N', $length), chr(0)); return pack('Ca*', 0x80 | strlen($temp), $temp); } /** * String Shift * * Inspired by array_shift * * @param string $string * @param int $index * @return string * @access private */ function _string_shift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } /** * Determines the private key format * * @see self::createKey() * @access public * @param int $format */ function setPrivateKeyFormat($format) { $this->privateKeyFormat = $format; } /** * Determines the public key format * * @see self::createKey() * @access public * @param int $format */ function setPublicKeyFormat($format) { $this->publicKeyFormat = $format; } /** * Determines which hashing function should be used * * Used with signature production / verification and (if the encryption mode is self::ENCRYPTION_OAEP) encryption and * decryption. If $hash isn't supported, sha1 is used. * * @access public * @param string $hash */ function setHash($hash) { // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. switch ($hash) { case 'md2': case 'md5': case 'sha1': case 'sha256': case 'sha384': case 'sha512': $this->hash = new Hash($hash); $this->hashName = $hash; break; default: $this->hash = new Hash('sha1'); $this->hashName = 'sha1'; } $this->hLen = $this->hash->getLength(); } /** * Determines which hashing function should be used for the mask generation function * * The mask generation function is used by self::ENCRYPTION_OAEP and self::SIGNATURE_PSS and although it's * best if Hash and MGFHash are set to the same thing this is not a requirement. * * @access public * @param string $hash */ function setMGFHash($hash) { // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. switch ($hash) { case 'md2': case 'md5': case 'sha1': case 'sha256': case 'sha384': case 'sha512': $this->mgfHash = new Hash($hash); break; default: $this->mgfHash = new Hash('sha1'); } $this->mgfHLen = $this->mgfHash->getLength(); } /** * Determines the salt length * * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}: * * Typical salt lengths in octets are hLen (the length of the output * of the hash function Hash) and 0. * * @access public * @param int $format */ function setSaltLength($sLen) { $this->sLen = $sLen; } /** * Integer-to-Octet-String primitive * * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}. * * @access private * @param \phpseclib\Math\BigInteger $x * @param int $xLen * @return string */ function _i2osp($x, $xLen) { $x = $x->toBytes(); if (strlen($x) > $xLen) { user_error('Integer too large'); return false; } return str_pad($x, $xLen, chr(0), STR_PAD_LEFT); } /** * Octet-String-to-Integer primitive * * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}. * * @access private * @param string $x * @return \phpseclib\Math\BigInteger */ function _os2ip($x) { return new BigInteger($x, 256); } /** * Exponentiate with or without Chinese Remainder Theorem * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}. * * @access private * @param \phpseclib\Math\BigInteger $x * @return \phpseclib\Math\BigInteger */ function _exponentiate($x) { switch (true) { case empty($this->primes): case $this->primes[1]->equals($this->zero): case empty($this->coefficients): case $this->coefficients[2]->equals($this->zero): case empty($this->exponents): case $this->exponents[1]->equals($this->zero): return $x->modPow($this->exponent, $this->modulus); } $num_primes = count($this->primes); if (defined('CRYPT_RSA_DISABLE_BLINDING')) { $m_i = array( 1 => $x->modPow($this->exponents[1], $this->primes[1]), 2 => $x->modPow($this->exponents[2], $this->primes[2]) ); $h = $m_i[1]->subtract($m_i[2]); $h = $h->multiply($this->coefficients[2]); list(, $h) = $h->divide($this->primes[1]); $m = $m_i[2]->add($h->multiply($this->primes[2])); $r = $this->primes[1]; for ($i = 3; $i <= $num_primes; $i++) { $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]); $r = $r->multiply($this->primes[$i - 1]); $h = $m_i->subtract($m); $h = $h->multiply($this->coefficients[$i]); list(, $h) = $h->divide($this->primes[$i]); $m = $m->add($r->multiply($h)); } } else { $smallest = $this->primes[1]; for ($i = 2; $i <= $num_primes; $i++) { if ($smallest->compare($this->primes[$i]) > 0) { $smallest = $this->primes[$i]; } } $one = new BigInteger(1); $r = $one->random($one, $smallest->subtract($one)); $m_i = array( 1 => $this->_blind($x, $r, 1), 2 => $this->_blind($x, $r, 2) ); $h = $m_i[1]->subtract($m_i[2]); $h = $h->multiply($this->coefficients[2]); list(, $h) = $h->divide($this->primes[1]); $m = $m_i[2]->add($h->multiply($this->primes[2])); $r = $this->primes[1]; for ($i = 3; $i <= $num_primes; $i++) { $m_i = $this->_blind($x, $r, $i); $r = $r->multiply($this->primes[$i - 1]); $h = $m_i->subtract($m); $h = $h->multiply($this->coefficients[$i]); list(, $h) = $h->divide($this->primes[$i]); $m = $m->add($r->multiply($h)); } } return $m; } /** * Performs RSA Blinding * * Protects against timing attacks by employing RSA Blinding. * Returns $x->modPow($this->exponents[$i], $this->primes[$i]) * * @access private * @param \phpseclib\Math\BigInteger $x * @param \phpseclib\Math\BigInteger $r * @param int $i * @return \phpseclib\Math\BigInteger */ function _blind($x, $r, $i) { $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i])); $x = $x->modPow($this->exponents[$i], $this->primes[$i]); $r = $r->modInverse($this->primes[$i]); $x = $x->multiply($r); list(, $x) = $x->divide($this->primes[$i]); return $x; } /** * Performs blinded RSA equality testing * * Protects against a particular type of timing attack described. * * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)} * * Thanks for the heads up singpolyma! * * @access private * @param string $x * @param string $y * @return bool */ function _equals($x, $y) { if (function_exists('hash_equals')) { return hash_equals($x, $y); } if (strlen($x) != strlen($y)) { return false; } $result = "\0"; $x^= $y; for ($i = 0; $i < strlen($x); $i++) { $result|= $x[$i]; } return $result === "\0"; } /** * RSAEP * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}. * * @access private * @param \phpseclib\Math\BigInteger $m * @return \phpseclib\Math\BigInteger */ function _rsaep($m) { if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { user_error('Message representative out of range'); return false; } return $this->_exponentiate($m); } /** * RSADP * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}. * * @access private * @param \phpseclib\Math\BigInteger $c * @return \phpseclib\Math\BigInteger */ function _rsadp($c) { if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) { user_error('Ciphertext representative out of range'); return false; } return $this->_exponentiate($c); } /** * RSASP1 * * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}. * * @access private * @param \phpseclib\Math\BigInteger $m * @return \phpseclib\Math\BigInteger */ function _rsasp1($m) { if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { user_error('Message representative out of range'); return false; } return $this->_exponentiate($m); } /** * RSAVP1 * * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}. * * @access private * @param \phpseclib\Math\BigInteger $s * @return \phpseclib\Math\BigInteger */ function _rsavp1($s) { if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) { user_error('Signature representative out of range'); return false; } return $this->_exponentiate($s); } /** * MGF1 * * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}. * * @access private * @param string $mgfSeed * @param int $mgfLen * @return string */ function _mgf1($mgfSeed, $maskLen) { // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output. $t = ''; $count = ceil($maskLen / $this->mgfHLen); for ($i = 0; $i < $count; $i++) { $c = pack('N', $i); $t.= $this->mgfHash->hash($mgfSeed . $c); } return substr($t, 0, $maskLen); } /** * RSAES-OAEP-ENCRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}. * * @access private * @param string $m * @param string $l * @return string */ function _rsaes_oaep_encrypt($m, $l = '') { $mLen = strlen($m); // Length checking // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. if ($mLen > $this->k - 2 * $this->hLen - 2) { user_error('Message too long'); return false; } // EME-OAEP encoding $lHash = $this->hash->hash($l); $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2); $db = $lHash . $ps . chr(1) . $m; $seed = Random::string($this->hLen); $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); $maskedDB = $db ^ $dbMask; $seedMask = $this->_mgf1($maskedDB, $this->hLen); $maskedSeed = $seed ^ $seedMask; $em = chr(0) . $maskedSeed . $maskedDB; // RSA encryption $m = $this->_os2ip($em); $c = $this->_rsaep($m); $c = $this->_i2osp($c, $this->k); // Output the ciphertext C return $c; } /** * RSAES-OAEP-DECRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2: * * Note. Care must be taken to ensure that an opponent cannot * distinguish the different error conditions in Step 3.g, whether by * error message or timing, or, more generally, learn partial * information about the encoded message EM. Otherwise an opponent may * be able to obtain useful information about the decryption of the * ciphertext C, leading to a chosen-ciphertext attack such as the one * observed by Manger [36]. * * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}: * * Both the encryption and the decryption operations of RSAES-OAEP take * the value of a label L as input. In this version of PKCS #1, L is * the empty string; other uses of the label are outside the scope of * this document. * * @access private * @param string $c * @param string $l * @return string */ function _rsaes_oaep_decrypt($c, $l = '') { // Length checking // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) { user_error('Decryption error'); return false; } // RSA decryption $c = $this->_os2ip($c); $m = $this->_rsadp($c); if ($m === false) { user_error('Decryption error'); return false; } $em = $this->_i2osp($m, $this->k); // EME-OAEP decoding $lHash = $this->hash->hash($l); $y = ord($em[0]); $maskedSeed = substr($em, 1, $this->hLen); $maskedDB = substr($em, $this->hLen + 1); $seedMask = $this->_mgf1($maskedDB, $this->hLen); $seed = $maskedSeed ^ $seedMask; $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); $db = $maskedDB ^ $dbMask; $lHash2 = substr($db, 0, $this->hLen); $m = substr($db, $this->hLen); $hashesMatch = $this->_equals($lHash, $lHash2); $leadingZeros = 1; $patternMatch = 0; $offset = 0; for ($i = 0; $i < strlen($m); $i++) { $patternMatch|= $leadingZeros & ($m[$i] === "\1"); $leadingZeros&= $m[$i] === "\0"; $offset+= $patternMatch ? 0 : 1; } // we do & instead of && to avoid https://en.wikipedia.org/wiki/Short-circuit_evaluation // to protect against timing attacks if (!$hashesMatch & !$patternMatch) { user_error('Decryption error'); return false; } // Output the message M return substr($m, $offset + 1); } /** * Raw Encryption / Decryption * * Doesn't use padding and is not recommended. * * @access private * @param string $m * @return string */ function _raw_encrypt($m) { $temp = $this->_os2ip($m); $temp = $this->_rsaep($temp); return $this->_i2osp($temp, $this->k); } /** * RSAES-PKCS1-V1_5-ENCRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}. * * @access private * @param string $m * @return string */ function _rsaes_pkcs1_v1_5_encrypt($m) { $mLen = strlen($m); // Length checking if ($mLen > $this->k - 11) { user_error('Message too long'); return false; } // EME-PKCS1-v1_5 encoding $psLen = $this->k - $mLen - 3; $ps = ''; while (strlen($ps) != $psLen) { $temp = Random::string($psLen - strlen($ps)); $temp = str_replace("\x00", '', $temp); $ps.= $temp; } $type = 2; // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) { $type = 1; // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF" $ps = str_repeat("\xFF", $psLen); } $em = chr(0) . chr($type) . $ps . chr(0) . $m; // RSA encryption $m = $this->_os2ip($em); $c = $this->_rsaep($m); $c = $this->_i2osp($c, $this->k); // Output the ciphertext C return $c; } /** * RSAES-PKCS1-V1_5-DECRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}. * * For compatibility purposes, this function departs slightly from the description given in RFC3447. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the * second byte is 2 or less. If it is, we'll accept the decrypted string as valid. * * As a consequence of this, a private key encrypted ciphertext produced with \phpseclib\Crypt\RSA may not decrypt * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but * not private key encrypted ciphertext's. * * @access private * @param string $c * @return string */ function _rsaes_pkcs1_v1_5_decrypt($c) { // Length checking if (strlen($c) != $this->k) { // or if k < 11 user_error('Decryption error'); return false; } // RSA decryption $c = $this->_os2ip($c); $m = $this->_rsadp($c); if ($m === false) { user_error('Decryption error'); return false; } $em = $this->_i2osp($m, $this->k); // EME-PKCS1-v1_5 decoding if (ord($em[0]) != 0 || ord($em[1]) > 2) { user_error('Decryption error'); return false; } $ps = substr($em, 2, strpos($em, chr(0), 2) - 2); $m = substr($em, strlen($ps) + 3); if (strlen($ps) < 8) { user_error('Decryption error'); return false; } // Output M return $m; } /** * EMSA-PSS-ENCODE * * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}. * * @access private * @param string $m * @param int $emBits */ function _emsa_pss_encode($m, $emBits) { // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8) $sLen = $this->sLen !== null ? $this->sLen : $this->hLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { user_error('Encoding error'); return false; } $salt = Random::string($sLen); $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; $h = $this->hash->hash($m2); $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2); $db = $ps . chr(1) . $salt; $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); $maskedDB = $db ^ $dbMask; $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0]; $em = $maskedDB . $h . chr(0xBC); return $em; } /** * EMSA-PSS-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}. * * @access private * @param string $m * @param string $em * @param int $emBits * @return string */ function _emsa_pss_verify($m, $em, $emBits) { // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. $emLen = ($emBits + 7) >> 3; // ie. ceil($emBits / 8); $sLen = $this->sLen !== null ? $this->sLen : $this->hLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { return false; } if ($em[strlen($em) - 1] != chr(0xBC)) { return false; } $maskedDB = substr($em, 0, -$this->hLen - 1); $h = substr($em, -$this->hLen - 1, $this->hLen); $temp = chr(0xFF << ($emBits & 7)); if ((~$maskedDB[0] & $temp) != $temp) { return false; } $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); $db = $maskedDB ^ $dbMask; $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0]; $temp = $emLen - $this->hLen - $sLen - 2; if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) { return false; } $salt = substr($db, $temp + 1); // should be $sLen long $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; $h2 = $this->hash->hash($m2); return $this->_equals($h, $h2); } /** * RSASSA-PSS-SIGN * * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}. * * @access private * @param string $m * @return string */ function _rsassa_pss_sign($m) { // EMSA-PSS encoding $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1); // RSA signature $m = $this->_os2ip($em); $s = $this->_rsasp1($m); $s = $this->_i2osp($s, $this->k); // Output the signature S return $s; } /** * RSASSA-PSS-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}. * * @access private * @param string $m * @param string $s * @return string */ function _rsassa_pss_verify($m, $s) { // Length checking if (strlen($s) != $this->k) { user_error('Invalid signature'); return false; } // RSA verification $modBits = strlen($this->modulus->toBits()); $s2 = $this->_os2ip($s); $m2 = $this->_rsavp1($s2); if ($m2 === false) { user_error('Invalid signature'); return false; } $em = $this->_i2osp($m2, $this->k); if ($em === false) { user_error('Invalid signature'); return false; } // EMSA-PSS verification return $this->_emsa_pss_verify($m, $em, $modBits - 1); } /** * EMSA-PKCS1-V1_5-ENCODE * * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}. * * @access private * @param string $m * @param int $emLen * @return string */ function _emsa_pkcs1_v1_5_encode($m, $emLen) { $h = $this->hash->hash($m); if ($h === false) { return false; } // see http://tools.ietf.org/html/rfc3447#page-43 switch ($this->hashName) { case 'md2': $t = pack('H*', '3020300c06082a864886f70d020205000410'); break; case 'md5': $t = pack('H*', '3020300c06082a864886f70d020505000410'); break; case 'sha1': $t = pack('H*', '3021300906052b0e03021a05000414'); break; case 'sha256': $t = pack('H*', '3031300d060960864801650304020105000420'); break; case 'sha384': $t = pack('H*', '3041300d060960864801650304020205000430'); break; case 'sha512': $t = pack('H*', '3051300d060960864801650304020305000440'); } $t.= $h; $tLen = strlen($t); if ($emLen < $tLen + 11) { user_error('Intended encoded message length too short'); return false; } $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3); $em = "\0\1$ps\0$t"; return $em; } /** * RSASSA-PKCS1-V1_5-SIGN * * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}. * * @access private * @param string $m * @return string */ function _rsassa_pkcs1_v1_5_sign($m) { // EMSA-PKCS1-v1_5 encoding $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); if ($em === false) { user_error('RSA modulus too short'); return false; } // RSA signature $m = $this->_os2ip($em); $s = $this->_rsasp1($m); $s = $this->_i2osp($s, $this->k); // Output the signature S return $s; } /** * RSASSA-PKCS1-V1_5-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}. * * @access private * @param string $m * @return string */ function _rsassa_pkcs1_v1_5_verify($m, $s) { // Length checking if (strlen($s) != $this->k) { user_error('Invalid signature'); return false; } // RSA verification $s = $this->_os2ip($s); $m2 = $this->_rsavp1($s); if ($m2 === false) { user_error('Invalid signature'); return false; } $em = $this->_i2osp($m2, $this->k); if ($em === false) { user_error('Invalid signature'); return false; } // EMSA-PKCS1-v1_5 encoding $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); if ($em2 === false) { user_error('RSA modulus too short'); return false; } // Compare return $this->_equals($em, $em2); } /** * Set Encryption Mode * * Valid values include self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1. * * @access public * @param int $mode */ function setEncryptionMode($mode) { $this->encryptionMode = $mode; } /** * Set Signature Mode * * Valid values include self::SIGNATURE_PSS and self::SIGNATURE_PKCS1 * * @access public * @param int $mode */ function setSignatureMode($mode) { $this->signatureMode = $mode; } /** * Set public key comment. * * @access public * @param string $comment */ function setComment($comment) { $this->comment = $comment; } /** * Get public key comment. * * @access public * @return string */ function getComment() { return $this->comment; } /** * Encryption * * Both self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1 both place limits on how long $plaintext can be. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will * be concatenated together. * * @see self::decrypt() * @access public * @param string $plaintext * @return string */ function encrypt($plaintext) { switch ($this->encryptionMode) { case self::ENCRYPTION_NONE: $plaintext = str_split($plaintext, $this->k); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_raw_encrypt($m); } return $ciphertext; case self::ENCRYPTION_PKCS1: $length = $this->k - 11; if ($length <= 0) { return false; } $plaintext = str_split($plaintext, $length); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m); } return $ciphertext; //case self::ENCRYPTION_OAEP: default: $length = $this->k - 2 * $this->hLen - 2; if ($length <= 0) { return false; } $plaintext = str_split($plaintext, $length); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_rsaes_oaep_encrypt($m); } return $ciphertext; } } /** * Decryption * * @see self::encrypt() * @access public * @param string $plaintext * @return string */ function decrypt($ciphertext) { if ($this->k <= 0) { return false; } $ciphertext = str_split($ciphertext, $this->k); $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT); $plaintext = ''; switch ($this->encryptionMode) { case self::ENCRYPTION_NONE: $decrypt = '_raw_encrypt'; break; case self::ENCRYPTION_PKCS1: $decrypt = '_rsaes_pkcs1_v1_5_decrypt'; break; //case self::ENCRYPTION_OAEP: default: $decrypt = '_rsaes_oaep_decrypt'; } foreach ($ciphertext as $c) { $temp = $this->$decrypt($c); if ($temp === false) { return false; } $plaintext.= $temp; } return $plaintext; } /** * Create a signature * * @see self::verify() * @access public * @param string $message * @return string */ function sign($message) { if (empty($this->modulus) || empty($this->exponent)) { return false; } switch ($this->signatureMode) { case self::SIGNATURE_PKCS1: return $this->_rsassa_pkcs1_v1_5_sign($message); //case self::SIGNATURE_PSS: default: return $this->_rsassa_pss_sign($message); } } /** * Verifies a signature * * @see self::sign() * @access public * @param string $message * @param string $signature * @return bool */ function verify($message, $signature) { if (empty($this->modulus) || empty($this->exponent)) { return false; } switch ($this->signatureMode) { case self::SIGNATURE_PKCS1: return $this->_rsassa_pkcs1_v1_5_verify($message, $signature); //case self::SIGNATURE_PSS: default: return $this->_rsassa_pss_verify($message, $signature); } } /** * Extract raw BER from Base64 encoding * * @access private * @param string $str * @return string */ function _extractBER($str) { /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them * above and beyond the ceritificate. * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line: * * Bag Attributes * localKeyID: 01 00 00 00 * subject=/O=organization/OU=org unit/CN=common name * issuer=/O=organization/CN=common name */ $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1); // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff $temp = preg_replace('#-+[^-]+-+#', '', $temp); // remove new lines $temp = str_replace(array("\r", "\n", ' '), '', $temp); $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; return $temp != false ? $temp : $str; } }
{ "content_hash": "7c5268f86bb0de0c0ca333ebdd3859c9", "timestamp": "", "source": "github", "line_count": 3156, "max_line_length": 175, "avg_line_length": 35.13339670468948, "alnum_prop": 0.4741569791037238, "repo_name": "phil-davis/core", "id": "3ece5170530f063279bca033dfefd4d2518e2eb1", "size": "112113", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "apps/files_external/3rdparty/phpseclib/phpseclib/phpseclib/Crypt/RSA.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "262" }, { "name": "Makefile", "bytes": "473" }, { "name": "Shell", "bytes": "8644" } ], "symlink_target": "" }
#import "DynamoDBBatchGetItemRequestMarshaller.h" #import "DynamoDBAttributeValue.h" #import "AmazonJSON.h" #import "AmazonSDKUtil.h" @implementation DynamoDBBatchGetItemRequestMarshaller +(AmazonServiceRequest *)createRequest:(DynamoDBBatchGetItemRequest *)batchGetItemRequest { DynamoDBRequest *request = [[DynamoDBRequest alloc] init]; [request setDelegate:[batchGetItemRequest delegate]]; [request setCredentials:[batchGetItemRequest credentials]]; [request setEndpoint:[batchGetItemRequest requestEndpoint]]; [request setRequestTag:[batchGetItemRequest requestTag]]; [request addValue:@"DynamoDB_20120810.BatchGetItem" forHeader:@"X-Amz-Target"]; [request addValue:@"application/x-amz-json-1.0" forHeader:@"Content-Type"]; NSMutableDictionary *json = [[[NSMutableDictionary alloc] init] autorelease]; if (batchGetItemRequest.requestItems != nil && [batchGetItemRequest.requestItems count] > 0) { NSMutableDictionary *requestItemsJson = [[[NSMutableDictionary alloc] init] autorelease]; [json setValue:requestItemsJson forKey:@"RequestItems"]; for (NSString *requestItemsListValue in batchGetItemRequest.requestItems) { NSMutableDictionary *requestItemsListValueJson = [[[NSMutableDictionary alloc] init] autorelease]; [requestItemsJson setValue:requestItemsListValueJson forKey:requestItemsListValue]; DynamoDBKeysAndAttributes *requestItemsListValueValue = [batchGetItemRequest.requestItems valueForKey:requestItemsListValue]; if (requestItemsListValueValue.keys != nil) { NSMutableArray *itemJson = [[[NSMutableArray alloc] init] autorelease]; [requestItemsListValueJson setValue:itemJson forKey:@"Keys"]; for (NSMutableDictionary *itemListValue in requestItemsListValueValue.keys) { NSMutableDictionary *keyJson = [NSMutableDictionary dictionary]; [itemJson addObject:keyJson]; for (NSString *key in [itemListValue allKeys]) { NSMutableDictionary *keysListValueJson = [[[NSMutableDictionary alloc] init] autorelease]; [keyJson setValue:keysListValueJson forKey:key]; DynamoDBAttributeValue *keysListValueValue = [itemListValue valueForKey:key]; if (keysListValueValue.s != nil) { [keysListValueJson setValue:keysListValueValue.s forKey:@"S"]; } if (keysListValueValue.n != nil) { [keysListValueJson setValue:keysListValueValue.n forKey:@"N"]; } if (keysListValueValue.b != nil) { [keysListValueJson setValue:[keysListValueValue.b base64EncodedString] forKey:@"B"]; } if (keysListValueValue != nil) { NSArray *sSList = keysListValueValue.sS; if (sSList != nil && [sSList count] > 0) { NSMutableArray *sSArray = [[[NSMutableArray alloc] init] autorelease]; [keysListValueJson setValue:sSArray forKey:@"SS"]; for (NSString *sSListValue in sSList) { if (sSListValue != nil) { [sSArray addObject:sSListValue]; } } } } if (keysListValueValue != nil) { NSArray *nSList = keysListValueValue.nS; if (nSList != nil && [nSList count] > 0) { NSMutableArray *nSArray = [[[NSMutableArray alloc] init] autorelease]; [keysListValueJson setValue:nSArray forKey:@"NS"]; for (NSString *nSListValue in nSList) { if (nSListValue != nil) { [nSArray addObject:nSListValue]; } } } } if (keysListValueValue != nil) { NSArray *bSList = keysListValueValue.bS; if (bSList != nil && [bSList count] > 0) { NSMutableArray *bSArray = [[[NSMutableArray alloc] init] autorelease]; [keysListValueJson setValue:bSArray forKey:@"BS"]; for (NSData *bSListValue in bSList) { if (bSListValue != nil) { [bSArray addObject:[bSListValue base64EncodedString]]; } } } } } } } if (requestItemsListValueValue != nil) { NSArray *attributesToGetList = requestItemsListValueValue.attributesToGet; if (attributesToGetList != nil && [attributesToGetList count] > 0) { NSMutableArray *attributesToGetArray = [[[NSMutableArray alloc] init] autorelease]; [requestItemsListValueJson setValue:attributesToGetArray forKey:@"AttributesToGet"]; for (NSString *attributesToGetListValue in attributesToGetList) { if (attributesToGetListValue != nil) { [attributesToGetArray addObject:attributesToGetListValue]; } } } } if (requestItemsListValueValue.consistentReadIsSet) { [requestItemsListValueJson setValue:(requestItemsListValueValue.consistentRead ? @"true":@"false") forKey:@"ConsistentRead"]; } } } if (batchGetItemRequest.returnConsumedCapacity != nil) { [json setValue:batchGetItemRequest.returnConsumedCapacity forKey:@"ReturnConsumedCapacity"]; } request.content = [AmazonJSON JSONRepresentation:json]; [request addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[[request.content dataUsingEncoding:NSUTF8StringEncoding] length]] forHeader:@"Content-Length"]; return [request autorelease]; } @end
{ "content_hash": "7ad4ef41a5fa5950542cd558b4c070e3", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 171, "avg_line_length": 51.6171875, "alnum_prop": 0.546541546844256, "repo_name": "wallisch/aws-sdk-ios-v1", "id": "f896b8779c0fbc89237f7f380d340c8f42bb8d42", "size": "7191", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Amazon.DynamoDB/Model/DynamoDBBatchGetItemRequestMarshaller.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "15339" }, { "name": "Objective-C", "bytes": "7696659" }, { "name": "Shell", "bytes": "3903" } ], "symlink_target": "" }
package org.apache.beam.runners.core.fn; import io.grpc.stub.StreamObserver; import java.util.concurrent.BlockingQueue; import org.apache.beam.model.fnexecution.v1.BeamFnApi; import org.apache.beam.model.fnexecution.v1.BeamFnControlGrpc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Fn API control service which adds incoming SDK harness connections to a pool. * * @deprecated Runners should depend on the beam-runners-java-fn-execution module for this * functionality. */ @Deprecated public class FnApiControlClientPoolService extends BeamFnControlGrpc.BeamFnControlImplBase { private static final Logger LOGGER = LoggerFactory.getLogger(FnApiControlClientPoolService.class); private final BlockingQueue<FnApiControlClient> clientPool; private FnApiControlClientPoolService(BlockingQueue<FnApiControlClient> clientPool) { this.clientPool = clientPool; } /** * Creates a new {@link FnApiControlClientPoolService} which will enqueue and vend new SDK harness * connections. */ public static FnApiControlClientPoolService offeringClientsToPool( BlockingQueue<FnApiControlClient> clientPool) { return new FnApiControlClientPoolService(clientPool); } /** * Called by gRPC for each incoming connection from an SDK harness, and enqueue an available SDK * harness client. * * <p>Note: currently does not distinguish what sort of SDK it is, so a separate instance is * required for each. */ @Override public StreamObserver<BeamFnApi.InstructionResponse> control( StreamObserver<BeamFnApi.InstructionRequest> requestObserver) { LOGGER.info("Beam Fn Control client connected."); FnApiControlClient newClient = FnApiControlClient.forRequestObserver(requestObserver); try { clientPool.put(newClient); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } return newClient.asResponseObserver(); } }
{ "content_hash": "72819b82b4e5f742ae3037814a7faa70", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 100, "avg_line_length": 35.392857142857146, "alnum_prop": 0.7679112008072654, "repo_name": "axbaretto/beam", "id": "21fc4f73fd0462d230108d5dcc376c84d3f1cf4b", "size": "2787", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "runners/core-java/src/main/java/org/apache/beam/runners/core/fn/FnApiControlClientPoolService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1598" }, { "name": "Batchfile", "bytes": "3220" }, { "name": "C", "bytes": "1339873" }, { "name": "C++", "bytes": "1132901" }, { "name": "CSS", "bytes": "124283" }, { "name": "Dockerfile", "bytes": "23950" }, { "name": "FreeMarker", "bytes": "7428" }, { "name": "Go", "bytes": "2795906" }, { "name": "Groovy", "bytes": "187109" }, { "name": "HTML", "bytes": "238575" }, { "name": "Java", "bytes": "39085315" }, { "name": "JavaScript", "bytes": "1221326" }, { "name": "Jupyter Notebook", "bytes": "7396" }, { "name": "Makefile", "bytes": "354938" }, { "name": "Python", "bytes": "51449019" }, { "name": "Roff", "bytes": "70716" }, { "name": "Ruby", "bytes": "4159" }, { "name": "Shell", "bytes": "351541" }, { "name": "TeX", "bytes": "70920" }, { "name": "Thrift", "bytes": "1118" } ], "symlink_target": "" }
<?php namespace Magento\CatalogSearch\Model\Search; use Magento\Search\Model\QueryFactory; /** * Search model for backend search */ class Catalog extends \Magento\Framework\Object { /** * Catalog search data * * @var \Magento\Search\Model\QueryFactory */ protected $queryFactory = null; /** * Magento string lib * * @var \Magento\Framework\Stdlib\String */ protected $string; /** * Adminhtml data * * @var \Magento\Backend\Helper\Data */ protected $_adminhtmlData = null; /** * @param \Magento\Backend\Helper\Data $adminhtmlData * @param \Magento\Framework\Stdlib\String $string * @param QueryFactory $queryFactory */ public function __construct( \Magento\Backend\Helper\Data $adminhtmlData, \Magento\Framework\Stdlib\String $string, QueryFactory $queryFactory ) { $this->_adminhtmlData = $adminhtmlData; $this->string = $string; $this->queryFactory = $queryFactory; } /** * Load search results * * @return $this */ public function load() { $result = []; if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) { $this->setResults($result); return $this; } $collection = $this->queryFactory->get() ->getSearchCollection() ->addAttributeToSelect('name') ->addAttributeToSelect('description') ->addBackendSearchFilter($this->getQuery()) ->setCurPage($this->getStart()) ->setPageSize($this->getLimit()) ->load(); foreach ($collection as $product) { $description = strip_tags($product->getDescription()); $result[] = [ 'id' => 'product/1/' . $product->getId(), 'type' => __('Product'), 'name' => $product->getName(), 'description' => $this->string->substr($description, 0, 30), 'url' => $this->_adminhtmlData->getUrl('catalog/product/edit', ['id' => $product->getId()]), ]; } $this->setResults($result); return $this; } }
{ "content_hash": "88692fa9fe183a4d92f2f09178b6f12f", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 108, "avg_line_length": 26.294117647058822, "alnum_prop": 0.5400447427293065, "repo_name": "webadvancedservicescom/magento", "id": "e47e289857ff917e6e24b6b1c22b212b13fa4889", "size": "2325", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/code/Magento/CatalogSearch/Model/Search/Catalog.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "16380" }, { "name": "CSS", "bytes": "2592299" }, { "name": "HTML", "bytes": "9192193" }, { "name": "JavaScript", "bytes": "2874762" }, { "name": "PHP", "bytes": "41399372" }, { "name": "Shell", "bytes": "3084" }, { "name": "VCL", "bytes": "3547" }, { "name": "XSLT", "bytes": "19817" } ], "symlink_target": "" }
<?php /** * Exception which thrown by PayPal API in case of processable error codes */ class Mage_Paypal_Model_Api_ProcessableException extends Mage_Core_Exception { /**#@+ * Error code returned by PayPal */ const API_INTERNAL_ERROR = 10001; const API_UNABLE_PROCESS_PAYMENT_ERROR_CODE = 10417; const API_MAX_PAYMENT_ATTEMPTS_EXCEEDED = 10416; const API_UNABLE_TRANSACTION_COMPLETE = 10486; const API_TRANSACTION_EXPIRED = 10411; const API_DO_EXPRESS_CHECKOUT_FAIL = 10422; const API_COUNTRY_FILTER_DECLINE = 10537; const API_MAXIMUM_AMOUNT_FILTER_DECLINE = 10538; const API_OTHER_FILTER_DECLINE = 10539; /**#@-*/ /** * Get error message which can be displayed to website user * * @return string */ public function getUserMessage() { switch ($this->getCode()) { case self::API_INTERNAL_ERROR: case self::API_UNABLE_PROCESS_PAYMENT_ERROR_CODE: $message = Mage::helper('paypal')->__("I'm sorry - but we were not able to process your payment. Please try another payment method or contact us so we can assist you."); break; case self::API_COUNTRY_FILTER_DECLINE: case self::API_MAXIMUM_AMOUNT_FILTER_DECLINE: case self::API_OTHER_FILTER_DECLINE: $message = Mage::helper('paypal')->__("I'm sorry - but we are not able to complete your transaction. Please contact us so we can assist you."); break; default: $message = $this->getMessage(); } return $message; } }
{ "content_hash": "3912a3f9f4916ada603c2903f8195a6b", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 185, "avg_line_length": 36.73913043478261, "alnum_prop": 0.5958579881656805, "repo_name": "portchris/NaturalRemedyCompany", "id": "4fdea9c2cc249ead9c5528935e627bccf2e04315", "size": "2625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/code/core/Mage/Paypal/Model/Api/ProcessableException.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "20009" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "2584823" }, { "name": "Dockerfile", "bytes": "828" }, { "name": "HTML", "bytes": "8762252" }, { "name": "JavaScript", "bytes": "2932806" }, { "name": "PHP", "bytes": "66466458" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Ruby", "bytes": "576" }, { "name": "Shell", "bytes": "40066" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>high-school-geometry: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.2 / high-school-geometry - 8.13.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> high-school-geometry <small> 8.13.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-20 04:58:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-20 04:58:01 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;palmskog@gmail.com&quot; homepage: &quot;https://github.com/coq-community/HighSchoolGeometry&quot; dev-repo: &quot;git+https://github.com/coq-community/HighSchoolGeometry.git&quot; bug-reports: &quot;https://github.com/coq-community/HighSchoolGeometry/issues&quot; license: &quot;LGPL-2.1-or-later&quot; synopsis: &quot;Geometry in Coq for French high school&quot; description: &quot;&quot;&quot; This Coq library is dedicated to high-shool geometry teaching. The axiomatisation for affine Euclidean space is in a non analytic setting. Includes a proof of Ptolemy&#39;s theorem.&quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] depends: [ &quot;coq&quot; {&gt;= &quot;8.12&quot; &amp; &lt; &quot;8.15~&quot;} ] tags: [ &quot;category:Mathematics/Geometry/General&quot; &quot;keyword:geometry&quot; &quot;keyword:teaching&quot; &quot;keyword:high school&quot; &quot;keyword:Ptolemy&#39;s theorem&quot; &quot;logpath:HighSchoolGeometry&quot; &quot;date:2021-08-06&quot; ] authors: [ &quot;Frédérique Guilhot&quot; &quot;Tuan-Minh Pham&quot; ] url { src: &quot;https://github.com/coq-community/HighSchoolGeometry/archive/v8.13.tar.gz&quot; checksum: &quot;sha512=47dba843c3541c628725224b6f9d353b5e5d224cd16ae52d6980a6aec9d698855477934609364dfaaa91271818f530d7af6d344c2ee7c38f8c0e0a3e226a655e&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-high-school-geometry.8.13.0 coq.8.7.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.2). The following dependencies couldn&#39;t be met: - coq-high-school-geometry -&gt; coq &gt;= 8.12 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-high-school-geometry.8.13.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "17195a53456f00820dddef696412b22f", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 159, "avg_line_length": 41.50574712643678, "alnum_prop": 0.554970922182221, "repo_name": "coq-bench/coq-bench.github.io", "id": "fcab04fd40aa8557c88c1b25afaa7b75c265456e", "size": "7249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.7.2/high-school-geometry/8.13.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
Some assorted CloudBot plugins
{ "content_hash": "3eb1a72aa3bc38d19b6466a64851d2c3", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 30, "avg_line_length": 31, "alnum_prop": 0.8709677419354839, "repo_name": "Aaron1011/CloudBotPlugins", "id": "804ea48405ed01cba86b9fa052208529146663d7", "size": "49", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2534" } ], "symlink_target": "" }
package Physics; // Just a simple data structure to represent a physics body public class Body { public final Rectangle occupiedArea; public boolean hasGravity = true; public Vector2D velocity = new Vector2D(0,0); // We're restricting ourselves to rectangles, but another option would be to // pass an interface of a generic shape to the constructor public Body(Rectangle rectangle) { this.occupiedArea = rectangle; } }
{ "content_hash": "3b15fd2f440b06df76faadf34714b904", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 80, "avg_line_length": 32.714285714285715, "alnum_prop": 0.7205240174672489, "repo_name": "Lavesson/java-physics", "id": "c6c2ec719db7284f8b051234df79a7e929b2b76f", "size": "458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/Physics/Body.java", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "381" }, { "name": "Java", "bytes": "53017" } ], "symlink_target": "" }
.class public final Landroid/hardware/hdmi/HdmiRecordSources$OwnSource; .super Landroid/hardware/hdmi/HdmiRecordSources$RecordSource; .source "HdmiRecordSources.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/hardware/hdmi/HdmiRecordSources; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x19 name = "OwnSource" .end annotation # static fields .field private static final EXTRA_DATA_SIZE:I # direct methods .method private constructor <init>()V .locals 2 .prologue .line 111 const/4 v0, 0x1 const/4 v1, 0x0 invoke-direct {p0, v0, v1}, Landroid/hardware/hdmi/HdmiRecordSources$RecordSource;-><init>(II)V .line 110 return-void .end method .method synthetic constructor <init>(Landroid/hardware/hdmi/HdmiRecordSources$OwnSource;)V .locals 0 .prologue invoke-direct {p0}, Landroid/hardware/hdmi/HdmiRecordSources$OwnSource;-><init>()V return-void .end method # virtual methods .method extraParamToByteArray([BI)I .locals 1 .param p1, "data" # [B .param p2, "index" # I .prologue .line 116 const/4 v0, 0x0 return v0 .end method
{ "content_hash": "831eec77733508574551ff8187782107", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 99, "avg_line_length": 20.896551724137932, "alnum_prop": 0.7178217821782178, "repo_name": "libnijunior/patchrom_bullhead", "id": "64c53bd7899f69db32f06c1afcf5b912f2866142", "size": "1212", "binary": false, "copies": "2", "ref": "refs/heads/mtc20k", "path": "framework.jar.out/smali/android/hardware/hdmi/HdmiRecordSources$OwnSource.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3334" }, { "name": "Groff", "bytes": "8687" }, { "name": "Makefile", "bytes": "2098" }, { "name": "Shell", "bytes": "26769" }, { "name": "Smali", "bytes": "172301453" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Sample for Data binding with AngularJS"> <meta name="author" content="Hoai Nam Vo"> <title>AngularJS - Binding</title> <link rel="shortcut icon" href="/public/favicon.png"> <!-- Style sheet --> <link rel="stylesheet" href="/public/components/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="/public/components/bootstrap/dist/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="style.css"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body ng-app="data-binding"> <!-- Header --> <header class="header"> <div class="container"> <div class="navbar-header"> <h2 class="navbar-brand"> <a href="/">AngularJS</a> </h2> </div> </div> </header> <!-- Content --> <section ng-controller="ManagementController"> <div class="container"> <!-- Title --> <h1>My favorite soloists</h1> <h4 class="description">AngularJS version</h4> <!-- Form --> <div class="form-management" ng-controller="FormController"> <form class="navbar-form"> <div class="form-group"> <input type="text" class="form-control" autocomplete="off" spellcheck="false" placeholder="Artist" ng-model="artist"> </div> <div class="form-group"> <input type="text" class="form-control" autocomplete="off" spellcheck="false" placeholder="Instrument" ng-model="instrument"> </div> <button type="button" class="btn btn-primary" ng-click="insertArtist()">Insert</button> </form> </div> <!-- Table --> <table class="table table-artist"> <thead> <tr> <th>Index</th> <th>Artist</th> <th>Instrument</th> <th></th> </tr> </thead> <tbody ng-controller="ListController"> <tr ng-repeat="artist in artists"> <td>{{$index + 1}}</td> <td>{{artist.name}}</td> <td>{{artist.instrument}}</td> <td> <button type="button" class="btn btn-danger" ng-click="removeArtist($index)"> <span class="glyphicon glyphicon-remove"></span> </button> </td> </tr> </tbody> </table> </div> </section> <!-- Scripts --> <script src="/public/components/angular/angular.min.js"></script> <script src="index.js"></script> </body> </html>
{ "content_hash": "c6b8a563d08cd5eb4546e06798bdd370", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 111, "avg_line_length": 41.69565217391305, "alnum_prop": 0.4363920750782065, "repo_name": "vhnam/sample-angular", "id": "85589ee0f7d14e0159931f80d69ba2f460817cef", "size": "3836", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "angular-binding/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3637" }, { "name": "HTML", "bytes": "16894" }, { "name": "JavaScript", "bytes": "161" } ], "symlink_target": "" }
title: Aneira Pugh gender: female submitted: false graduated: 2013 ---
{ "content_hash": "9885017e236d8b2f306cc80328c86918", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 18, "avg_line_length": 14.2, "alnum_prop": 0.7605633802816901, "repo_name": "johnathan99j/history-project", "id": "58a65ee8732ec2d5af49f358af058ec763d87f89", "size": "75", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_people/aneira_pugh.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "86536" }, { "name": "CoffeeScript", "bytes": "41479" }, { "name": "Dockerfile", "bytes": "974" }, { "name": "HTML", "bytes": "109321" }, { "name": "JavaScript", "bytes": "16577" }, { "name": "Python", "bytes": "1892" }, { "name": "Ruby", "bytes": "65568" }, { "name": "Shell", "bytes": "6659" } ], "symlink_target": "" }
{- | Module : Text.Tabl Description : Table layout engine that provides alignment and decoration Copyright : (c) 2016-2020 Daniel Lovasko License : BSD2 Maintainer : Daniel Lovasko <daniel.lovasko@gmail.com> Stability : stable Portability : portable Text.Tabl arranges multiple Text instances into a table layout while providing means of alignment, and visual decoration both horizontally and vertically. -} module Text.Tabl ( Alignment(..) , Decoration(..) , Environment(..) , tabl ) where import Data.List (transpose) import qualified Data.Text as T import Text.Tabl.Alignment import Text.Tabl.Ascii import Text.Tabl.Decoration import Text.Tabl.Environment import Text.Tabl.Latex import Text.Tabl.Util -- | Create a table layout based on the specified output environment, -- decorations and alignments. tabl :: Environment -- ^ output environment -> Decoration -- ^ horizontal decoration -> Decoration -- ^ vertical decoration -> [Alignment] -- ^ column alignments -> [[T.Text]] -- ^ table cell data -> T.Text -- ^ final layout tabl _ _ _ _ [] = T.empty tabl _ _ _ _ [[]] = T.empty tabl env hdecor vdecor aligns cells = render env hpres vpres ealigns ecells where -- Alternative to a type-class. render EnvAscii = ascii render EnvLatex = latex -- Compute the locations of horizontal and vertical decorations. hpres = presence (length cells + 1) tecells hdecor vpres = presence (length (head ecells) + 1) ecells vdecor -- Fill the rows with fewer columns with empty strings. ecells = map (extend columnCount T.empty) cells tecells = transpose ecells -- Assume alignment to the left for the columns without specification. ealigns = extend columnCount AlignLeft aligns -- Compute the final number of columns of the table. columnCount = maximum $ map length cells
{ "content_hash": "90160b28b400d0526604eedf641c77ea", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 75, "avg_line_length": 31.063492063492063, "alnum_prop": 0.6821665815022995, "repo_name": "lovasko/tabl", "id": "4e41b77a6f9cea5c675aed0a9c3c6a9fda322b6e", "size": "1957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Text/Tabl.hs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Haskell", "bytes": "14372" } ], "symlink_target": "" }
SYNONYM #### According to Index Fungorum #### Published in null #### Original name Coremium swantonii A.L. Sm., 1919 ### Remarks null
{ "content_hash": "433544b6222e8182ec582807929e2f20", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 33, "avg_line_length": 10.538461538461538, "alnum_prop": 0.6861313868613139, "repo_name": "mdoering/backbone", "id": "38096baab3bc7c900990669537521bf8b0858c80", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Eurotiomycetes/Eurotiales/Trichocomaceae/Paecilomyces/Paecilomyces farinosus/ Syn. Spicaria swantoni/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
In diesem Hands-On werden Sie das Projekt erstellen und die Hauptseite der App mit XAML aufbauen. _Hinweis: Wir verwenden einige Logos von externen Quellen, mit der freundlichen Unterstützung von_ http://www.alienvalley.com ## Ziele - Ein Visual Studio Projekt für die universelle Windows Plattform erstellen - Eine Entwicklerlizenz beantragen - Das App-Manifest einrichten - Die Hauptseite der App mit XAML erstellen - Die In-App-Navigation einrichten --- ## Übungen Dieses Hands-On besteht aus den folgenden Übungen:<br/> 1. <a href="#Exercise1">Erstellen und Einrichten des Projekts</a><br/> 2. <a href="#Exercise2">Erstellen der Hauptseite der App</a> <a name="Exercise1"></a> ### Übung 1: Erstellen und Einrichten des Projekts In dieser Übung werden Sie das Projekt in Visual Studio erstellen und die benötigten Dateien einbinden. #### Aufgabe 1 - App-Projekt in Visual Studio erstellen In diesem Schritt wird das Projekt in Visual Studio angelegt und der aktuellen Projektmappe hinzugefügt. 1. In Visual Studio machen Sie einen Rechtsklick auf die aktuell geöffnete Projektmappe **DotNETJumpStart**. 2. Dort wählen Sie **Hinzufügen/Neues Projekt** aus.<br/><br/> ![](_images/add-project.png?raw=true "Abbildung 1")<br/> 3. Im Dialog **Neues Projekt**: 1. Wählen Sie **Vorlagen/Visual C#/Windows/Universell**. 2. Wählen Sie **Leere App (Universelle Windows-App)**. 3. Nennen Sie das Projekt **ImageApp** und bestätigen mit **OK**.<br/><br/> ![](_images/create-project.png?raw=true "Abbildung 2")<br/> 4. Wählen Sie folgende Einstellungen für die Zielversion, in dem sich öffnenden Dialog:<br/><br/> ![](_images/version-select.png?raw=true "Abbildung 3")<br/> Falls auf dem System keine Entwicklerlizenz installiert ist, werden Sie nun mit einem Dialog aufgefordert, eine solche zu beantragen. Sollte das nicht der Fall sein, können Sie die nächste Aufgabe überspringen. #### Aufgabe 2: Abrufen einer Windows Entwickler Lizenz Wenn Sie zum ersten Mal eine App auf einem Gerät ausführen oder debuggen wollen, werden Sie aufgefordert, eine Entwicklerlizenz für diesen Computer oder dieses Gerät herunterzuladen. Diese ist zum Entwickeln und Testen kostenlos. **Falls Sie nicht nach einer Lizenz gefragt werden, können Sie diesen Schritt überspringen**. 1. Lesen Sie sich die Lizenzbedingungen durch und klicken Sie auf die Schaltfläche zum Akzeptieren der Bedingungen<br/><br/> ![](_images/license-1.png?raw=true "Abbildung 4")<br/> 2. Klicken Sie im Dialogfeld Benutzerkontensteuerung Control (UAC) auf Ja, um den Vorgang fortzusetzen. 3. Melden Sie sich mit Ihrem Microsoft-Konto an.<br/><br/> ![](_images/license-2.png?raw=true "Abbildung 5")<br/> 4. Nachdem Sie die Lizenz auf dem lokalen Computer installiert haben, wird auf diesem Computer erst dann wieder eine entsprechende Benutzeraufforderung eingeblendet, wenn die Lizenz abläuft.<br/><br/> ![](_images/license-3.png?raw=true "Abbildung 6")<br/> #### Aufgabe 3: Startprojekt festlegen Vor den nächsten Schritten muss das neue Projekt noch als **Startprojekt** festgelegt werden. 1. Machen Sie einen Rechtsklick auf das neue Projekt **ImageApp** im **Projektmappen-Explorer** und wählen **Als Startprojekt festlegen**. 2. Machen Sie einen Rechtsklick auf die Projektmappe **DotNETJumpStart** und öffnen den **Konfigurations-Manager**. 3. Dort wählen Sie bei der **ImageApp** die Optionen "**Erstellen**" und "**Bereitstellen**" aus.<br><br> ![](_images/config-manager.png?raw=true "Abbildung 7")<br/> 4. Wenn Sie nun das Debugging mit **F5** starten, so wird die App automatisch erstellt und gestartet. 5. Machen Sie sich nun mit der Projektstruktur vertraut. Folgende Dateien und Ordner sind im Projekt enthalten: - **Assets/**: Enthält App-Logos. - **App.xaml**: Die Hauptdatei der App, die für den Startvorgang verantwortlich ist. - **MainPage.xaml**: Die erste Seite der App, die automatisch bei App-Start aufgerufen wird. - **TemporaryKey.pfx**: Temporäres Entwicklerzertifikat - **Package.appxmanifest**: Die Manifestdatei, in der App-Einstellungen getroffen werden. - **project.json**: Projektdatei von Visual Studio #### Aufgabe 4: Mobile Extension hinzufügen Um auch gerätespezifische Funktionen von Smartphones verwenden zu können, muss noch ein sogenanntes "**Extension SDK**" hinzugefügt werden. Dieses benötigen wir in einem der späteren Hands-Ons. 1. Hierzu machen Sie einen Rechtsklick auf **Verweise** in der Projektmappe und wählen **Verweis hinzufügen** aus.<br><br> ![](_images/verweise.png?raw=true "Abbildung 8")<br/> 2. Im neu geöffneten Fenster wählen Sie links **Universal Windows/Erweiterungen** und selektieren eine auf Ihrem System vorhandene Version vom **Windows Mobile Extensions for the UWP**.<br><br> ![](_images/extensions.png?raw=true "Abbildung 9")<br/> 3. Bestätigen Sie mit **OK**. 4. Starten Sie das Debugging. Sollte eine Fehlermeldung angezeigt werden, öffnen Sie erneut die **Verweisübersicht** und wählen eine andere Version des SDKs aus. #### Aufgabe 5: Manifest einrichten In dieser Aufgabe werden Sie den App-Namen, Kachelgrafiken, sowie Berechtigungen für die App festlegen. Diese Einstellungen können im sogenannten **App-Manifest** getroffen werden. 1. Im **Projektmappen-Explorer** machen Sie einen Rechtsklick auf den Ordner **Assets** und wählen **Hinzufügen/Vorhandenes Element**. 2. Im Dialogfeld navigieren Sie in den Ordner **Dateien/Assets** vom aktuellen Hands-On und wählen alle Dateien aus. 3. Überschreiben Sie alle bereits vorhandenen Dateien. 4. Machen Sie im **Projektmappen-Explorer** einen Doppelklick auf das **Package.appxmanifest**, um das Manifest zu öffnen. 5. Ändern Sie den Anzeigenamen der App zu einem beliebigen Namen (hier **SnapIt**) und wechseln dann auf den Reiter **Visuelle Assets**.<br/><br/> ![](_images/manifest-1.png?raw=true "Abbildung 10")<br/> 6. Wählen Sie links den Bereich **Alle Bildanlagen (All Visual Assets)** aus. 7. Aktivieren Sie in den **Anzeigeeinstellungen (Display Settings) das Medium Tile. 8. Tragen Sie bei **Begrüßungsbildschirm (Splash Screen)** als Hintergrundfarbe "**white**" ein.<br/><br/> ![](_images/manifest-2.png?raw=true "Abbildung 11")<br/><br/> 9. Wechseln Sie nun auf den Reiter **Funktionen (Capabilities)** und stellen Sie sicher, dass die Funktion **Internet (Client)** ausgewählt ist.<br/><br/> ![](_images/manifest-3.png?raw=true "Abbildung 12")<br/> 10. Wählen Sie **Debugging starten** aus dem Menü **Debuggen** oder drücken Sie **F5**. 11. Die App sollte nun gestartet werden. Sie sollten bereits im Ladebildschirm das eingestellte Logo sehen. 12. Beenden Sie das Debugging und öffnen im Windows Startmenü **Alle Apps**. 13. Dort finden Sie bereits Ihre App mit dem eingestellten Namen.<br/><br/> ![](_images/windows-start-menu.png?raw=true "Abbildung 13")<br/> #### Aufgabe 6: Benötigte Dateien referenzieren Es wurden bereits einige Dateien für Sie vorbereitet, die häufig in App-Projekten benötigt werden. Auch werden einige Views vorgegeben, um im zeitlichen Rahmen der Veranstaltung zu bleiben. Die Dateien sollen in diesem Schritt in das Projekt eingebunden werden. 1. Erzeugen Sie einen neuen Ordner **Common** im aktuellen Projekt. Sie können das über einen Rechtsklick auf das Projekt im **Projektmappen-Explorer** tun, indem Sie dort **Hinzufügen/Neuer Ordner** wählen. 2. Fügen Sie daraufhin diesem Ordner die Dateien aus dem aktuellen Hands-On Unterordner **Dateien/Common** hinzu. Hierzu machen Sie einen Rechtsklick auf den neu erstellten Ordner Common und wählen **Hinzufügen/Vorhandenes Element**. 3. Wiederholen Sie die Schritte 1 und 2 für die Ordner **Views**, **Utils** und **ViewModels**. Mit diesen Schritten haben Sie die benötigten Dateien für die App eingebunden. Ihre Projektmappe sollte nun wie folgt aussehen:<br/><br/> ![](_images/solution-explorer-after-adding.png?raw=true "Abbildung 14")<br/> <a name="Exercise2"></a> ### Übung 2: Erstellen der Hauptseite der App In dieser Übung werden Sie die Hauptseite der App mit XAML erstellen. XAML ist eine von Microsoft entwickelte Beschreibungssprache für Oberflächen von Anwendungen, die auf XML basiert. #### Aufgabe 1 - Anpassen der Hauptseite Zunächst wird die bereits bestehende Hauptseite der App (**MainPage.xaml**) angepasst und eine App-Bar hinzugefügt. 1. Verschieben Sie die Datei "**MainPage.xaml**" per Drag-and-Drop in den Ordner **Views**. 2. Öffnen Sie die Datei **MainPage.xaml** mit einem Doppelklick im XAML-Designer. 3. Ersetzen Sie den alten Quellcode der Datei durch folgenden XAML-Code: ```XML <Page x:Class="ImageApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:ImageApp" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:vm="using:ImageApp.ViewModels" xmlns:common="using:ImageApp.Common" x:Name="mainPage"> <!-- TODO: add Page.DataContext here --> <!-- TODO: add Page.Resources here --> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="0,50,0,0"> <GridView IsItemClickEnabled="False" SelectionMode="None"> <GridView.ItemTemplate> <DataTemplate> <Grid Margin="12" Width="320" Height="320"> <Grid.RowDefinitions> <RowDefinition Height="70"/> <RowDefinition/> <RowDefinition Height="50"/> </Grid.RowDefinitions> <!-- TODO: add grid template here --> </Grid> </DataTemplate> </GridView.ItemTemplate> </GridView> <!-- TODO: add info label here --> </Grid> <Page.BottomAppBar> <CommandBar> <AppBarButton Icon="Camera" Label="Hinzufügen" /> <AppBarButton Icon="Refresh" Label="Aktualisieren" /> <CommandBar.SecondaryCommands> <AppBarButton Icon="Sort" Label="Nach Bewertung sortieren" /> <AppBarButton Icon="Sort" Label="Nach Datum sortieren" /> </CommandBar.SecondaryCommands> </CommandBar> </Page.BottomAppBar> </Page> ``` 4. Inspizieren Sie den XAML-Code und die daraus resultierenden Steuerelemente im Designer. 5. Starten Sie das Debugging und sehen sich das Ergebnis an. Das **GridView** wird nicht angezeigt, da es bisher keine Einträge enthält.<br/><br/> ![](_images/main-page.png?raw=true "Abbildung 15")<br/> #### Aufgabe 2 - In-App-Navigation hinzufügen In dieser Aufgabe wird die Navigation von der Hauptseite zur **"Post hinzufügen"**-Seite eingerichtet und die Schaltfläche zum Zurücknavigieren für alle Views aktiviert. 1. Selektieren Sie im XAML-Quellcode die **CommandBar** und machen einen Doppelklick in der Design-Vorschau auf den **Kamera-Button** in der App-Bar der Hauptseite. 2. Im neu hinzugefügten **AppBarButton_Click**-Handler fügen Sie den folgenden Code zur Navigation ein: ```C# this.Frame.Navigate(typeof(AddPostPage)); ``` 3. Starten Sie das Debugging und Testen die Navigation über den Hinzufügen-Button. Sie werden feststellen, dass Sie keine Möglichkeit haben, zur Hauptseite der App zurückzukehren. Die Schaltfläche zum Zurücknavigieren muss manuell aktiviert werden. Sie werden hierzu die Schaltfläche global für alle Views aktivieren: 1. Öffnen Sie die Codeansicht der App-Hauptdatei **App.xaml**, indem Sie auf die Datei **App.xaml** rechtsklicken und **Code anzeigen** wählen. 2. Fügen Sie dem using-Block am Anfang der Datei die folgenden Namespace-Verweise hinzu: ```C# using Windows.UI.Core; ``` 3. Zunächst aktivieren wir den **AppViewBackButton**. Ersetzen Sie hierzu die Methode **OnLaunched** durch folgende Implementierung: ```C# protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // App-Initialisierung nicht wiederholen, wenn das Fenster bereits Inhalte enthält. // Nur sicherstellen, dass das Fenster aktiv ist. if (rootFrame == null) { // Frame erstellen, der als Navigationskontext fungiert und zum Parameter der ersten Seite navigieren rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Zustand von zuvor angehaltener Anwendung laden } // Den Frame im aktuellen Fenster platzieren Window.Current.Content = rootFrame; // Register a handler for BackRequested events and set the // visibility of the Back button rootFrame.Navigated += OnNavigated; SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // Wenn der Navigationsstapel nicht wiederhergestellt wird, zur ersten Seite navigieren // und die neue Seite konfigurieren, indem die erforderlichen Informationen als Navigationsparameter // übergeben werden rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Sicherstellen, dass das aktuelle Fenster aktiv ist Window.Current.Activate(); } } ``` 3. Damit der **AppViewBackButton** auch global verwendet werden kann, fügen Sie der Datei noch folgende 2 Methoden hinzu: ```C# void OnNavigated(object sender, NavigationEventArgs e) { // Each time a navigation event occurs, update the Back button's visibility SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = ((Frame)sender).CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed; } void OnBackRequested(object sender, BackRequestedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame.CanGoBack) { e.Handled = true; rootFrame.GoBack(); } } ``` 5. Starten Sie die App und versuchen von der **Hinzufügen-Seite** zurück zu navigieren. Es sollte eine neue Schaltfläche angezeigt werden.<br/><br/> ![](_images/back-button-app.png?raw=true "Abbildung 16")<br/> Auf Smartphones wird vergleichsweise keine Zurück-Schaltfläche angezeigt, sondern die Hardware-Zurück-Taste auf dem Gerät aktiviert. ## Zusammenfassung Mit Beendung dieser Session haben Sie gelernt: - Eine Projekt für die universelle Windows Plattform zu erstellen - Eine Windows Entwickler Lizenz abzurufen - Das App-Manifest einzurichten - Eine XAML-View zu erstellen - Die In-App-Navigation zu verwenden
{ "content_hash": "c555c1995146b1f7ca0da8094f1e0bac", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 323, "avg_line_length": 53.14089347079038, "alnum_prop": 0.7085488877392654, "repo_name": "danielbeckmann/DotNETJumpStart", "id": "38790eaf471e1a0313958c67a43e801c2c47301f", "size": "15706", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "06. Universal Windows Platform/01. Projektsetup/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "872" }, { "name": "C#", "bytes": "1477126" }, { "name": "CSS", "bytes": "23162" }, { "name": "JavaScript", "bytes": "1861544" } ], "symlink_target": "" }
<div class="content" data-ng-repeat="branch in tree" data-ng-style="{backgroundColor:mtd.colorize(branch.letters)}"> <div ng-if="mtd.persona" class="content-name">{{branch.title}}</div> <content data-ng-if="branch.next && mtd.isSelected(branch.letters)" class="inner" next="branch.next" mtd="mtd"></content> </div>
{ "content_hash": "9cb3d93ce6de8dee11b818c36117df6f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 126, "avg_line_length": 41.875, "alnum_prop": 0.6776119402985075, "repo_name": "fondfrukt/Feeds", "id": "dc65e690b4e0f8b2efb8dbdd61543fb46c93ddde", "size": "335", "binary": false, "copies": "1", "ref": "refs/heads/glitch", "path": "partials/contents.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "38032" }, { "name": "HTML", "bytes": "30101" }, { "name": "JavaScript", "bytes": "490508" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/itemCameraPressed"/> <item android:drawable="@color/itemCameraNormal"/> </selector>
{ "content_hash": "4ed019a19557ec1aa98904e856c9d6c4", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 84, "avg_line_length": 52, "alnum_prop": 0.7307692307692307, "repo_name": "xiaoGuy/ImageSelectorLikeWeChat", "id": "7468664e7383ab4cb8c7f275bb338eab3cafc282", "size": "260", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/selector_item_camera.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "80260" } ], "symlink_target": "" }
package com.guidewire.tools.marathon.client trait Task { def id : String def host : String def ports: Seq[Int] } trait TaskKill { def appId: String def host : String def id : String def scale: Boolean } object Task { type Apply[TTask <: Task] = ( String , String , Seq[Int] ) => TTask def apply( id : String , host : String , ports: Seq[Int] ) (implicit version: api.Client) = validate(version.VersionSpecificTaskApply(id, host, ports)) def validate(task: Task): Task = task } import scala.collection.JavaConverters._ /** * WARNING: This should never be a companion object or it will not be exposed to the Java API * correctly. */ object Tasks { def create( id : String , host : String , ports: java.util.List[java.lang.Integer] ) = Task(id = id, host = host, ports = ports.asScala.map(_.toInt).toSeq)(implicitly[api.Client]) def create( id : String , host : String , ports : java.util.List[java.lang.Integer] , version: api.Client ) = Task(id = id, host = host, ports = ports.asScala.map(_.toInt).toSeq)(version) } object TaskKill { type Apply[TTaskKill <: TaskKill] = ( String , String , String , Boolean ) => TTaskKill def apply( appId: String , host : String , id : String = "*" , scale: Boolean = false ) (implicit version: api.Client) = validate(version.VersionSpecificTaskKillApply(appId, host, id, scale)) def validate(taskKill: TaskKill): TaskKill = taskKill } /** * WARNING: This should never be a companion object or it will not be exposed to the Java API * correctly. */ object TaskKills { def create( appId: String , host : String , id : String , scale: Boolean ) = TaskKill(appId = appId, host = host, id = id, scale = scale)(implicitly[api.Client]) def create( appId : String , host : String , id : String , scale : Boolean , version: api.Client ) = TaskKill(appId = appId, host = host, id = id, scale = scale)(version) def create( appId: String , host : String ) = TaskKill(appId = appId, host = host)(implicitly[api.Client]) def create( appId : String , host : String , version: api.Client ) = TaskKill(appId = appId, host = host)(version) def create( appId: String , host : String , id : String ) = TaskKill(appId = appId, host = host, id = id)(implicitly[api.Client]) def create( appId : String , host : String , id : String , version: api.Client ) = TaskKill(appId = appId, host = host, id = id)(version) }
{ "content_hash": "adb87b26928d97af9145c538017f822d", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 96, "avg_line_length": 20.914728682170544, "alnum_prop": 0.6015567086730912, "repo_name": "Guidewire/marathon-client", "id": "51acfa838a8c5f11db36faffb4ea28e725c26a3e", "size": "2698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/guidewire/tools/marathon/client/Tasks.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9107" }, { "name": "Scala", "bytes": "77967" } ], "symlink_target": "" }
<?php namespace AthenaPlus\SchooltripBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tab * * @ORM\Table() * @ORM\Entity(repositoryClass="AthenaPlus\SchooltripBundle\Entity\TabRepository") */ class Tab { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var \DateTime * * @ORM\Column(name="date", type="date", nullable=true) */ private $date; /** * @var array * * @ORM\Column(name="content", type="json_array", nullable=true) */ private $content; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set date * * @param \DateTime $date * @return Tab */ public function setDate($date) { $this->date = $date; return $this; } /** * Get date * * @return \DateTime */ public function getDate() { return $this->date; } /** * Set content * * @param array $content * @return Tab */ public function setContent($content) { $this->content = $content; return $this; } /** * Get content * * @return array */ public function getContent() { return $this->content; } /** * @ORM\ManyToOne(targetEntity="Journal", inversedBy="tabs") * @ORM\JoinColumn(name="journal_id", referencedColumnName="id") */ protected $journal; /** * Set journal * * @param Journal $journal */ public function setJournal(Journal $journal = null) { $this->journal = $journal; } /** * Get journal * * @return Journal */ public function getJournal() { return $this->journal; } }
{ "content_hash": "a51c53cf62cf1f2f20fde99ef773a083", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 82, "avg_line_length": 15.975206611570249, "alnum_prop": 0.5002586652871185, "repo_name": "PACKED-vzw/schooltrip", "id": "63dae9f191a2ff8abf51c5660990234f2581357d", "size": "1933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AthenaPlus/SchooltripBundle/Entity/Tab.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "195759" }, { "name": "HTML", "bytes": "245154" }, { "name": "JavaScript", "bytes": "252277" }, { "name": "PHP", "bytes": "217584" } ], "symlink_target": "" }
using Server; var builder = WebApplication.CreateBuilder(args); builder.Services.AddGrpc(o => { o.ResponseCompressionAlgorithm = "gzip"; }); var app = builder.Build(); app.MapGrpcService<GreeterService>(); app.Run();
{ "content_hash": "6644774ce50a56158d59adf0178f6ce2", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 49, "avg_line_length": 18.666666666666668, "alnum_prop": 0.7276785714285714, "repo_name": "grpc/grpc-dotnet", "id": "b658a3bc5d9b799ed31f5434a9cf39f8ba5b6b38", "size": "868", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/Compressor/Server/Program.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "747" }, { "name": "C#", "bytes": "3393867" }, { "name": "Dockerfile", "bytes": "860" }, { "name": "HTML", "bytes": "3311" }, { "name": "JavaScript", "bytes": "1906" }, { "name": "PowerShell", "bytes": "10078" }, { "name": "Shell", "bytes": "15913" } ], "symlink_target": "" }
class Error < ActiveRecord::Base include ActiveModel::Serializers::Xml end
{ "content_hash": "a501f999864fd978096c79944b5355b7", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 39, "avg_line_length": 25.666666666666668, "alnum_prop": 0.7922077922077922, "repo_name": "PredicSis/s3-server", "id": "97b76a6703c0e2c57513114980a46d1d31398233", "size": "292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/error.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "2399" }, { "name": "Ruby", "bytes": "64033" } ], "symlink_target": "" }
from django.conf.urls.defaults import * # that's how we define an item # possible model_names are defined in favourites_conf.py urlpatterns = patterns('', (r'^(?P<model_name>\w+)/(?P<item_pk>\d+)/', include('favourites.urls_items')), (r'^collection/(?P<collection_id>\d+)/', include('favourites.urls_collections')), ) urlpatterns += patterns('favourites.views', url(r'^$', 'collections_index', name='favourites.collections_index'), url(r'^permission_denied/$', 'permission_denied', name='favourites.permission_denied') )
{ "content_hash": "7ac99e22918339c74eae8fc814a036df", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 90, "avg_line_length": 41.38461538461539, "alnum_prop": 0.6914498141263941, "repo_name": "gregplaysguitar/glamkit", "id": "321cbe0b60ff6ae17e322b5d84a34095a43deb0a", "size": "538", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "glamkit/incubated/favourites/urls.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "25519" }, { "name": "Python", "bytes": "111853" } ], "symlink_target": "" }
<div> This is user dashboard </div>
{ "content_hash": "a3fb6ae8d13dcb32feef10335bffeaa3", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 26, "avg_line_length": 13, "alnum_prop": 0.6410256410256411, "repo_name": "at15/bform-web", "id": "7844bc964886361738b96952f426774ca871d219", "size": "39", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/user/user.dashboard.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1679" }, { "name": "HTML", "bytes": "2352" }, { "name": "JavaScript", "bytes": "1367" }, { "name": "TypeScript", "bytes": "3384" } ], "symlink_target": "" }
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='mxconsole/protobuf/__init__.py', package='', syntax='proto2', serialized_pb=_b('\n\x1emxconsole/protobuf/__init__.py') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) # @@protoc_insertion_point(module_scope)
{ "content_hash": "7c12444205306a8b5dc0e81acb959059", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 74, "avg_line_length": 25.62962962962963, "alnum_prop": 0.7557803468208093, "repo_name": "bravomikekilo/mxconsole", "id": "11ceec7b0d5fb99231d46e05455d72c54e0298c4", "size": "793", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mxconsole/protobuf/__init__/py_pb2.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "27900" }, { "name": "CSS", "bytes": "5107" }, { "name": "HTML", "bytes": "584168" }, { "name": "JavaScript", "bytes": "1734943" }, { "name": "Protocol Buffer", "bytes": "71639" }, { "name": "Python", "bytes": "981371" }, { "name": "Shell", "bytes": "1566" }, { "name": "TypeScript", "bytes": "786869" } ], "symlink_target": "" }
<?php class RowData { public $value; public $type; } class Login { public $client_id; public $userName; public $userPassword; } class ReportClientBusinessBills { public $report; function __construct() { } public function GetReportClientBusinessBills($web_login, $web_pass, $locations, $users, $start_date, $end_date, $client_id, $client_department) { if(file_exists('classes/TMSoapClient.php')) require_once('classes/TMSoapClient.php'); $TMServer = new TMSoapClient('ServerSite.wsdl', array( 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, 'trace' => true, 'exceptions' => true, 'connection_timeout'=>9999, 'features' => SOAP_SINGLE_ELEMENT_ARRAYS | SOAP_USE_XSI_ARRAY_TYPE, 'soap_version' => SOAP_1_2, 'classmap' => array('Login' => 'Login'), 'style' => SOAP_DOCUMENT, 'use' => SOAP_LITERAL ) ); $TMServer->__setTimeout(180); // Login $params = new Login; $params->client_id = $client_id; $params->userName = $web_login; $params->userPassword = $web_pass; $response = $TMServer->ClientLogin($params); $soap_params = array( 'locations' => $locations, // ints 'users' => $users, // ints 'start_date' => $start_date, 'end_date' => $end_date, 'client_id' => $client_id, 'client_department' => $client_department, 'report_title' => 'Raport Bilete Avion' ); //report header and first data $response = object2array($TMServer->ReportClientBusinessBills($soap_params)); $response = $response['ReportClientBusinessBillsResult']; $pages = explode('<ReportPage>',$TMServer->__getLastResponse()); list($pages[count($pages)-1],$discard) = explode('</ReportPage>',$pages[count($pages)-1]); unset($pages[0]); foreach($pages as &$page) { $page = str_replace('</ReportPage>','',$page); $page = '<ProcessClientBusinessBillsPage xmlns="http://www.dreamsoftware.ro/tm_version2"><page>'.$page.'</page></ProcessClientBusinessBillsPage>'; //var_dump(formatXmlString($page)); } //print_r($response); //report process pages for($i=1;$i<=count($pages);$i++) { $TMServer->xml = $pages[$i]; $TMServer->__setTimeout(180); $response_page = $TMServer-> ProcessClientBusinessBillsPage(); // echo '<!--',formatXmlString($TMServer->__getLastResponse()),'-->'; $processed_page = object2array($response_page); $response_page = $response_page->ProcessClientBusinessBillsPageResult; $processed_page = object2array($response_page); //var_dump($processed_page); $response['report_pages']['ReportPage'][$i-1] = $processed_page; unset($xml_doc); } $this->report = $response; //print_r($this->report); } } ?>
{ "content_hash": "dd9f9211a5cd4e9c74881717ef3a2af0", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 149, "avg_line_length": 29.701030927835053, "alnum_prop": 0.6056924678930927, "repo_name": "faneaatiku/appconsro", "id": "66bb893bce5c9413f4cbc7fbdd3261ba58faaf1f", "size": "2881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "protected/components/classes/ReportClientBusinessBills.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2613" }, { "name": "Batchfile", "bytes": "1337" }, { "name": "C++", "bytes": "36216" }, { "name": "CSS", "bytes": "2452357" }, { "name": "CoffeeScript", "bytes": "4704" }, { "name": "Go", "bytes": "13884" }, { "name": "HTML", "bytes": "3587703" }, { "name": "JavaScript", "bytes": "7082039" }, { "name": "Makefile", "bytes": "460" }, { "name": "PHP", "bytes": "24379816" }, { "name": "Python", "bytes": "11441" }, { "name": "Shell", "bytes": "2423" } ], "symlink_target": "" }
from __future__ import absolute_import, division, print_function import collections from contextlib import closing import errno import gzip import logging import os import re import socket import ssl import sys from tornado.escape import to_unicode from tornado import gen from tornado.httpclient import AsyncHTTPClient from tornado.httputil import HTTPHeaders, ResponseStartLine from tornado.ioloop import IOLoop from tornado.log import gen_log from tornado.concurrent import Future from tornado.netutil import Resolver, bind_sockets from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.test.httpclient_test import ChunkHandler, CountdownHandler, HelloWorldHandler, RedirectHandler from tornado.test import httpclient_test from tornado.testing import AsyncHTTPTestCase, AsyncHTTPSTestCase, AsyncTestCase, ExpectLog from tornado.test.util import skipOnTravis, skipIfNoIPv6, refusing_port, unittest, skipBefore35, exec_test from tornado.web import RequestHandler, Application, asynchronous, url, stream_request_body class SimpleHTTPClientCommonTestCase(httpclient_test.HTTPClientCommonTestCase): def get_http_client(self): client = SimpleAsyncHTTPClient(force_instance=True) self.assertTrue(isinstance(client, SimpleAsyncHTTPClient)) return client class TriggerHandler(RequestHandler): def initialize(self, queue, wake_callback): self.queue = queue self.wake_callback = wake_callback @asynchronous def get(self): logging.debug("queuing trigger") self.queue.append(self.finish) if self.get_argument("wake", "true") == "true": self.wake_callback() class HangHandler(RequestHandler): @asynchronous def get(self): pass class ContentLengthHandler(RequestHandler): def get(self): self.set_header("Content-Length", self.get_argument("value")) self.write("ok") class HeadHandler(RequestHandler): def head(self): self.set_header("Content-Length", "7") class OptionsHandler(RequestHandler): def options(self): self.set_header("Access-Control-Allow-Origin", "*") self.write("ok") class NoContentHandler(RequestHandler): def get(self): self.set_status(204) self.finish() class SeeOtherPostHandler(RequestHandler): def post(self): redirect_code = int(self.request.body) assert redirect_code in (302, 303), "unexpected body %r" % self.request.body self.set_header("Location", "/see_other_get") self.set_status(redirect_code) class SeeOtherGetHandler(RequestHandler): def get(self): if self.request.body: raise Exception("unexpected body %r" % self.request.body) self.write("ok") class HostEchoHandler(RequestHandler): def get(self): self.write(self.request.headers["Host"]) class NoContentLengthHandler(RequestHandler): @asynchronous def get(self): if self.request.version.startswith('HTTP/1'): # Emulate the old HTTP/1.0 behavior of returning a body with no # content-length. Tornado handles content-length at the framework # level so we have to go around it. stream = self.request.connection.detach() stream.write(b"HTTP/1.0 200 OK\r\n\r\n" b"hello") stream.close() else: self.finish('HTTP/1 required') class EchoPostHandler(RequestHandler): def post(self): self.write(self.request.body) @stream_request_body class RespondInPrepareHandler(RequestHandler): def prepare(self): self.set_status(403) self.finish("forbidden") class SimpleHTTPClientTestMixin(object): def get_app(self): # callable objects to finish pending /trigger requests self.triggers = collections.deque() return Application([ url("/trigger", TriggerHandler, dict(queue=self.triggers, wake_callback=self.stop)), url("/chunk", ChunkHandler), url("/countdown/([0-9]+)", CountdownHandler, name="countdown"), url("/hang", HangHandler), url("/hello", HelloWorldHandler), url("/content_length", ContentLengthHandler), url("/head", HeadHandler), url("/options", OptionsHandler), url("/no_content", NoContentHandler), url("/see_other_post", SeeOtherPostHandler), url("/see_other_get", SeeOtherGetHandler), url("/host_echo", HostEchoHandler), url("/no_content_length", NoContentLengthHandler), url("/echo_post", EchoPostHandler), url("/respond_in_prepare", RespondInPrepareHandler), url("/redirect", RedirectHandler), ], gzip=True) def test_singleton(self): # Class "constructor" reuses objects on the same IOLoop self.assertTrue(SimpleAsyncHTTPClient() is SimpleAsyncHTTPClient()) # unless force_instance is used self.assertTrue(SimpleAsyncHTTPClient() is not SimpleAsyncHTTPClient(force_instance=True)) # different IOLoops use different objects with closing(IOLoop()) as io_loop2: client1 = self.io_loop.run_sync(gen.coroutine(SimpleAsyncHTTPClient)) client2 = io_loop2.run_sync(gen.coroutine(SimpleAsyncHTTPClient)) self.assertTrue(client1 is not client2) def test_connection_limit(self): with closing(self.create_client(max_clients=2)) as client: self.assertEqual(client.max_clients, 2) seen = [] # Send 4 requests. Two can be sent immediately, while the others # will be queued for i in range(4): client.fetch(self.get_url("/trigger"), lambda response, i=i: (seen.append(i), self.stop())) self.wait(condition=lambda: len(self.triggers) == 2) self.assertEqual(len(client.queue), 2) # Finish the first two requests and let the next two through self.triggers.popleft()() self.triggers.popleft()() self.wait(condition=lambda: (len(self.triggers) == 2 and len(seen) == 2)) self.assertEqual(set(seen), set([0, 1])) self.assertEqual(len(client.queue), 0) # Finish all the pending requests self.triggers.popleft()() self.triggers.popleft()() self.wait(condition=lambda: len(seen) == 4) self.assertEqual(set(seen), set([0, 1, 2, 3])) self.assertEqual(len(self.triggers), 0) def test_redirect_connection_limit(self): # following redirects should not consume additional connections with closing(self.create_client(max_clients=1)) as client: client.fetch(self.get_url('/countdown/3'), self.stop, max_redirects=3) response = self.wait() response.rethrow() def test_gzip(self): # All the tests in this file should be using gzip, but this test # ensures that it is in fact getting compressed. # Setting Accept-Encoding manually bypasses the client's # decompression so we can see the raw data. response = self.fetch("/chunk", use_gzip=False, headers={"Accept-Encoding": "gzip"}) self.assertEqual(response.headers["Content-Encoding"], "gzip") self.assertNotEqual(response.body, b"asdfqwer") # Our test data gets bigger when gzipped. Oops. :) # Chunked encoding bypasses the MIN_LENGTH check. self.assertEqual(len(response.body), 34) f = gzip.GzipFile(mode="r", fileobj=response.buffer) self.assertEqual(f.read(), b"asdfqwer") def test_max_redirects(self): response = self.fetch("/countdown/5", max_redirects=3) self.assertEqual(302, response.code) # We requested 5, followed three redirects for 4, 3, 2, then the last # unfollowed redirect is to 1. self.assertTrue(response.request.url.endswith("/countdown/5")) self.assertTrue(response.effective_url.endswith("/countdown/2")) self.assertTrue(response.headers["Location"].endswith("/countdown/1")) def test_header_reuse(self): # Apps may reuse a headers object if they are only passing in constant # headers like user-agent. The header object should not be modified. headers = HTTPHeaders({'User-Agent': 'Foo'}) self.fetch("/hello", headers=headers) self.assertEqual(list(headers.get_all()), [('User-Agent', 'Foo')]) def test_see_other_redirect(self): for code in (302, 303): response = self.fetch("/see_other_post", method="POST", body="%d" % code) self.assertEqual(200, response.code) self.assertTrue(response.request.url.endswith("/see_other_post")) self.assertTrue(response.effective_url.endswith("/see_other_get")) # request is the original request, is a POST still self.assertEqual("POST", response.request.method) @skipOnTravis def test_connect_timeout(self): timeout = 0.1 timeout_min, timeout_max = 0.099, 1.0 class TimeoutResolver(Resolver): def resolve(self, *args, **kwargs): return Future() # never completes with closing(self.create_client(resolver=TimeoutResolver())) as client: client.fetch(self.get_url('/hello'), self.stop, connect_timeout=timeout) response = self.wait() self.assertEqual(response.code, 599) self.assertTrue(timeout_min < response.request_time < timeout_max, response.request_time) self.assertEqual(str(response.error), "HTTP 599: Timeout while connecting") @skipOnTravis def test_request_timeout(self): timeout = 0.1 timeout_min, timeout_max = 0.099, 0.15 if os.name == 'nt': timeout = 0.5 timeout_min, timeout_max = 0.4, 0.6 response = self.fetch('/trigger?wake=false', request_timeout=timeout) self.assertEqual(response.code, 599) self.assertTrue(timeout_min < response.request_time < timeout_max, response.request_time) self.assertEqual(str(response.error), "HTTP 599: Timeout during request") # trigger the hanging request to let it clean up after itself self.triggers.popleft()() @skipIfNoIPv6 def test_ipv6(self): [sock] = bind_sockets(None, '::1', family=socket.AF_INET6) port = sock.getsockname()[1] self.http_server.add_socket(sock) url = '%s://[::1]:%d/hello' % (self.get_protocol(), port) # ipv6 is currently enabled by default but can be disabled self.http_client.fetch(url, self.stop, allow_ipv6=False) response = self.wait() self.assertEqual(response.code, 599) self.http_client.fetch(url, self.stop) response = self.wait() self.assertEqual(response.body, b"Hello world!") def xtest_multiple_content_length_accepted(self): response = self.fetch("/content_length?value=2,2") self.assertEqual(response.body, b"ok") response = self.fetch("/content_length?value=2,%202,2") self.assertEqual(response.body, b"ok") response = self.fetch("/content_length?value=2,4") self.assertEqual(response.code, 599) response = self.fetch("/content_length?value=2,%202,3") self.assertEqual(response.code, 599) def test_head_request(self): response = self.fetch("/head", method="HEAD") self.assertEqual(response.code, 200) self.assertEqual(response.headers["content-length"], "7") self.assertFalse(response.body) def test_options_request(self): response = self.fetch("/options", method="OPTIONS") self.assertEqual(response.code, 200) self.assertEqual(response.headers["content-length"], "2") self.assertEqual(response.headers["access-control-allow-origin"], "*") self.assertEqual(response.body, b"ok") def test_no_content(self): response = self.fetch("/no_content") self.assertEqual(response.code, 204) # 204 status shouldn't have a content-length # # Tests with a content-length header are included below # in HTTP204NoContentTestCase. self.assertNotIn("Content-Length", response.headers) def test_host_header(self): host_re = re.compile(b"^127.0.0.1:[0-9]+$") response = self.fetch("/host_echo") self.assertTrue(host_re.match(response.body)) url = self.get_url("/host_echo").replace("http://", "http://me:secret@") self.http_client.fetch(url, self.stop) response = self.wait() self.assertTrue(host_re.match(response.body), response.body) def test_connection_refused(self): cleanup_func, port = refusing_port() self.addCleanup(cleanup_func) with ExpectLog(gen_log, ".*", required=False): self.http_client.fetch("http://127.0.0.1:%d/" % port, self.stop) response = self.wait() self.assertEqual(599, response.code) if sys.platform != 'cygwin': # cygwin returns EPERM instead of ECONNREFUSED here contains_errno = str(errno.ECONNREFUSED) in str(response.error) if not contains_errno and hasattr(errno, "WSAECONNREFUSED"): contains_errno = str(errno.WSAECONNREFUSED) in str(response.error) self.assertTrue(contains_errno, response.error) # This is usually "Connection refused". # On windows, strerror is broken and returns "Unknown error". expected_message = os.strerror(errno.ECONNREFUSED) self.assertTrue(expected_message in str(response.error), response.error) def test_queue_timeout(self): with closing(self.create_client(max_clients=1)) as client: client.fetch(self.get_url('/trigger'), self.stop, request_timeout=10) # Wait for the trigger request to block, not complete. self.wait() client.fetch(self.get_url('/hello'), self.stop, connect_timeout=0.1) response = self.wait() self.assertEqual(response.code, 599) self.assertTrue(response.request_time < 1, response.request_time) self.assertEqual(str(response.error), "HTTP 599: Timeout in request queue") self.triggers.popleft()() self.wait() def test_no_content_length(self): response = self.fetch("/no_content_length") if response.body == b"HTTP/1 required": self.skipTest("requires HTTP/1.x") else: self.assertEquals(b"hello", response.body) def sync_body_producer(self, write): write(b'1234') write(b'5678') @gen.coroutine def async_body_producer(self, write): yield write(b'1234') yield gen.Task(IOLoop.current().add_callback) yield write(b'5678') def test_sync_body_producer_chunked(self): response = self.fetch("/echo_post", method="POST", body_producer=self.sync_body_producer) response.rethrow() self.assertEqual(response.body, b"12345678") def test_sync_body_producer_content_length(self): response = self.fetch("/echo_post", method="POST", body_producer=self.sync_body_producer, headers={'Content-Length': '8'}) response.rethrow() self.assertEqual(response.body, b"12345678") def test_async_body_producer_chunked(self): response = self.fetch("/echo_post", method="POST", body_producer=self.async_body_producer) response.rethrow() self.assertEqual(response.body, b"12345678") def test_async_body_producer_content_length(self): response = self.fetch("/echo_post", method="POST", body_producer=self.async_body_producer, headers={'Content-Length': '8'}) response.rethrow() self.assertEqual(response.body, b"12345678") @skipBefore35 def test_native_body_producer_chunked(self): namespace = exec_test(globals(), locals(), """ async def body_producer(write): await write(b'1234') await gen.Task(IOLoop.current().add_callback) await write(b'5678') """) response = self.fetch("/echo_post", method="POST", body_producer=namespace["body_producer"]) response.rethrow() self.assertEqual(response.body, b"12345678") @skipBefore35 def test_native_body_producer_content_length(self): namespace = exec_test(globals(), locals(), """ async def body_producer(write): await write(b'1234') await gen.Task(IOLoop.current().add_callback) await write(b'5678') """) response = self.fetch("/echo_post", method="POST", body_producer=namespace["body_producer"], headers={'Content-Length': '8'}) response.rethrow() self.assertEqual(response.body, b"12345678") def test_100_continue(self): response = self.fetch("/echo_post", method="POST", body=b"1234", expect_100_continue=True) self.assertEqual(response.body, b"1234") def test_100_continue_early_response(self): def body_producer(write): raise Exception("should not be called") response = self.fetch("/respond_in_prepare", method="POST", body_producer=body_producer, expect_100_continue=True) self.assertEqual(response.code, 403) def test_streaming_follow_redirects(self): # When following redirects, header and streaming callbacks # should only be called for the final result. # TODO(bdarnell): this test belongs in httpclient_test instead of # simple_httpclient_test, but it fails with the version of libcurl # available on travis-ci. Move it when that has been upgraded # or we have a better framework to skip tests based on curl version. headers = [] chunks = [] self.fetch("/redirect?url=/hello", header_callback=headers.append, streaming_callback=chunks.append) chunks = list(map(to_unicode, chunks)) self.assertEqual(chunks, ['Hello world!']) # Make sure we only got one set of headers. num_start_lines = len([h for h in headers if h.startswith("HTTP/")]) self.assertEqual(num_start_lines, 1) class SimpleHTTPClientTestCase(SimpleHTTPClientTestMixin, AsyncHTTPTestCase): def setUp(self): super(SimpleHTTPClientTestCase, self).setUp() self.http_client = self.create_client() def create_client(self, **kwargs): return SimpleAsyncHTTPClient(force_instance=True, **kwargs) class SimpleHTTPSClientTestCase(SimpleHTTPClientTestMixin, AsyncHTTPSTestCase): def setUp(self): super(SimpleHTTPSClientTestCase, self).setUp() self.http_client = self.create_client() def create_client(self, **kwargs): return SimpleAsyncHTTPClient(force_instance=True, defaults=dict(validate_cert=False), **kwargs) def test_ssl_options(self): resp = self.fetch("/hello", ssl_options={}) self.assertEqual(resp.body, b"Hello world!") def test_ssl_context(self): resp = self.fetch("/hello", ssl_options=ssl.SSLContext(ssl.PROTOCOL_SSLv23)) self.assertEqual(resp.body, b"Hello world!") def test_ssl_options_handshake_fail(self): with ExpectLog(gen_log, "SSL Error|Uncaught exception", required=False): resp = self.fetch( "/hello", ssl_options=dict(cert_reqs=ssl.CERT_REQUIRED)) self.assertRaises(ssl.SSLError, resp.rethrow) def test_ssl_context_handshake_fail(self): with ExpectLog(gen_log, "SSL Error|Uncaught exception"): ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED resp = self.fetch("/hello", ssl_options=ctx) self.assertRaises(ssl.SSLError, resp.rethrow) def test_error_logging(self): # No stack traces are logged for SSL errors (in this case, # failure to validate the testing self-signed cert). # The SSLError is exposed through ssl.SSLError. with ExpectLog(gen_log, '.*') as expect_log: response = self.fetch("/", validate_cert=True) self.assertEqual(response.code, 599) self.assertIsInstance(response.error, ssl.SSLError) self.assertFalse(expect_log.logged_stack) class CreateAsyncHTTPClientTestCase(AsyncTestCase): def setUp(self): super(CreateAsyncHTTPClientTestCase, self).setUp() self.saved = AsyncHTTPClient._save_configuration() def tearDown(self): AsyncHTTPClient._restore_configuration(self.saved) super(CreateAsyncHTTPClientTestCase, self).tearDown() def test_max_clients(self): AsyncHTTPClient.configure(SimpleAsyncHTTPClient) with closing(AsyncHTTPClient(force_instance=True)) as client: self.assertEqual(client.max_clients, 10) with closing(AsyncHTTPClient( max_clients=11, force_instance=True)) as client: self.assertEqual(client.max_clients, 11) # Now configure max_clients statically and try overriding it # with each way max_clients can be passed AsyncHTTPClient.configure(SimpleAsyncHTTPClient, max_clients=12) with closing(AsyncHTTPClient(force_instance=True)) as client: self.assertEqual(client.max_clients, 12) with closing(AsyncHTTPClient( max_clients=13, force_instance=True)) as client: self.assertEqual(client.max_clients, 13) with closing(AsyncHTTPClient( max_clients=14, force_instance=True)) as client: self.assertEqual(client.max_clients, 14) class HTTP100ContinueTestCase(AsyncHTTPTestCase): def respond_100(self, request): self.http1 = request.version.startswith('HTTP/1.') if not self.http1: request.connection.write_headers(ResponseStartLine('', 200, 'OK'), HTTPHeaders()) request.connection.finish() return self.request = request self.request.connection.stream.write( b"HTTP/1.1 100 CONTINUE\r\n\r\n", self.respond_200) def respond_200(self): self.request.connection.stream.write( b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nA", self.request.connection.stream.close) def get_app(self): # Not a full Application, but works as an HTTPServer callback return self.respond_100 def test_100_continue(self): res = self.fetch('/') if not self.http1: self.skipTest("requires HTTP/1.x") self.assertEqual(res.body, b'A') class HTTP204NoContentTestCase(AsyncHTTPTestCase): def respond_204(self, request): self.http1 = request.version.startswith('HTTP/1.') if not self.http1: # Close the request cleanly in HTTP/2; it will be skipped anyway. request.connection.write_headers(ResponseStartLine('', 200, 'OK'), HTTPHeaders()) request.connection.finish() return # A 204 response never has a body, even if doesn't have a content-length # (which would otherwise mean read-until-close). We simulate here a # server that sends no content length and does not close the connection. # # Tests of a 204 response with no Content-Length header are included # in SimpleHTTPClientTestMixin. stream = request.connection.detach() stream.write(b"HTTP/1.1 204 No content\r\n") if request.arguments.get("error", [False])[-1]: stream.write(b"Content-Length: 5\r\n") else: stream.write(b"Content-Length: 0\r\n") stream.write(b"\r\n") stream.close() def get_app(self): return self.respond_204 def test_204_no_content(self): resp = self.fetch('/') if not self.http1: self.skipTest("requires HTTP/1.x") self.assertEqual(resp.code, 204) self.assertEqual(resp.body, b'') def test_204_invalid_content_length(self): # 204 status with non-zero content length is malformed with ExpectLog(gen_log, ".*Response with code 204 should not have body"): response = self.fetch("/?error=1") if not self.http1: self.skipTest("requires HTTP/1.x") if self.http_client.configured_class != SimpleAsyncHTTPClient: self.skipTest("curl client accepts invalid headers") self.assertEqual(response.code, 599) class HostnameMappingTestCase(AsyncHTTPTestCase): def setUp(self): super(HostnameMappingTestCase, self).setUp() self.http_client = SimpleAsyncHTTPClient( hostname_mapping={ 'www.example.com': '127.0.0.1', ('foo.example.com', 8000): ('127.0.0.1', self.get_http_port()), }) def get_app(self): return Application([url("/hello", HelloWorldHandler), ]) def test_hostname_mapping(self): self.http_client.fetch( 'http://www.example.com:%d/hello' % self.get_http_port(), self.stop) response = self.wait() response.rethrow() self.assertEqual(response.body, b'Hello world!') def test_port_mapping(self): self.http_client.fetch('http://foo.example.com:8000/hello', self.stop) response = self.wait() response.rethrow() self.assertEqual(response.body, b'Hello world!') class ResolveTimeoutTestCase(AsyncHTTPTestCase): def setUp(self): # Dummy Resolver subclass that never invokes its callback. class BadResolver(Resolver): def resolve(self, *args, **kwargs): pass super(ResolveTimeoutTestCase, self).setUp() self.http_client = SimpleAsyncHTTPClient( resolver=BadResolver()) def get_app(self): return Application([url("/hello", HelloWorldHandler), ]) def test_resolve_timeout(self): response = self.fetch('/hello', connect_timeout=0.1) self.assertEqual(response.code, 599) class MaxHeaderSizeTest(AsyncHTTPTestCase): def get_app(self): class SmallHeaders(RequestHandler): def get(self): self.set_header("X-Filler", "a" * 100) self.write("ok") class LargeHeaders(RequestHandler): def get(self): self.set_header("X-Filler", "a" * 1000) self.write("ok") return Application([('/small', SmallHeaders), ('/large', LargeHeaders)]) def get_http_client(self): return SimpleAsyncHTTPClient(max_header_size=1024) def test_small_headers(self): response = self.fetch('/small') response.rethrow() self.assertEqual(response.body, b'ok') def test_large_headers(self): with ExpectLog(gen_log, "Unsatisfiable read"): response = self.fetch('/large') self.assertEqual(response.code, 599) class MaxBodySizeTest(AsyncHTTPTestCase): def get_app(self): class SmallBody(RequestHandler): def get(self): self.write("a" * 1024 * 64) class LargeBody(RequestHandler): def get(self): self.write("a" * 1024 * 100) return Application([('/small', SmallBody), ('/large', LargeBody)]) def get_http_client(self): return SimpleAsyncHTTPClient(max_body_size=1024 * 64) def test_small_body(self): response = self.fetch('/small') response.rethrow() self.assertEqual(response.body, b'a' * 1024 * 64) def test_large_body(self): with ExpectLog(gen_log, "Malformed HTTP message from None: Content-Length too long"): response = self.fetch('/large') self.assertEqual(response.code, 599) class MaxBufferSizeTest(AsyncHTTPTestCase): def get_app(self): class LargeBody(RequestHandler): def get(self): self.write("a" * 1024 * 100) return Application([('/large', LargeBody)]) def get_http_client(self): # 100KB body with 64KB buffer return SimpleAsyncHTTPClient(max_body_size=1024 * 100, max_buffer_size=1024 * 64) def test_large_body(self): response = self.fetch('/large') response.rethrow() self.assertEqual(response.body, b'a' * 1024 * 100) class ChunkedWithContentLengthTest(AsyncHTTPTestCase): def get_app(self): class ChunkedWithContentLength(RequestHandler): def get(self): # Add an invalid Transfer-Encoding to the response self.set_header('Transfer-Encoding', 'chunked') self.write("Hello world") return Application([('/chunkwithcl', ChunkedWithContentLength)]) def get_http_client(self): return SimpleAsyncHTTPClient() def test_chunked_with_content_length(self): # Make sure the invalid headers are detected with ExpectLog(gen_log, ("Malformed HTTP message from None: Response " "with both Transfer-Encoding and Content-Length")): response = self.fetch('/chunkwithcl') self.assertEqual(response.code, 599)
{ "content_hash": "41517f088489f27fff722a737a973e7e", "timestamp": "", "source": "github", "line_count": 767, "max_line_length": 107, "avg_line_length": 39.555410691003914, "alnum_prop": 0.617027588252744, "repo_name": "legnaleurc/tornado", "id": "df41abd7b87766f68f8f5e6ad2965d6ac041d58d", "size": "30339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tornado/test/simple_httpclient_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1664" }, { "name": "HTML", "bytes": "25" }, { "name": "Python", "bytes": "1579708" }, { "name": "Ruby", "bytes": "1428" }, { "name": "Shell", "bytes": "4070" } ], "symlink_target": "" }
package uk.nhs.hdn.ckan.domain.strings; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import uk.nhs.hdn.common.serialisers.*; public abstract class AbstractSerialisableString extends AbstractValueSerialisableStringIsUnknown implements Serialisable { protected AbstractSerialisableString(@NonNls @NotNull final String value) { super(value); } @Override public final void serialise(@NotNull final Serialiser serialiser) throws CouldNotSerialiseException { try { serialiseValue(serialiser); } catch (CouldNotSerialiseValueException e) { throw new CouldNotSerialiseException(this, e); } } }
{ "content_hash": "6ff07fdcdc487a454931548d819f950a", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 121, "avg_line_length": 23.428571428571427, "alnum_prop": 0.7942073170731707, "repo_name": "health-and-care-developer-network/health-and-care-developer-network", "id": "788108704955c387e2c0e9b620ce7137397d8be4", "size": "1247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/ckan/ckan-domain/uk/nhs/hdn/ckan/domain/strings/AbstractSerialisableString.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "686149" }, { "name": "C++", "bytes": "4895" }, { "name": "Java", "bytes": "2479497" }, { "name": "JavaScript", "bytes": "1811558" }, { "name": "Objective-C", "bytes": "328" }, { "name": "PHP", "bytes": "89889" }, { "name": "Perl", "bytes": "155878" }, { "name": "Ragel in Ruby Host", "bytes": "12141" }, { "name": "Ruby", "bytes": "774" }, { "name": "Shell", "bytes": "236221" }, { "name": "XML", "bytes": "674124" } ], "symlink_target": "" }
using System; using Mono.Cecil.PE; namespace Mono.Cecil.Metadata { sealed class BlobHeap : Heap { public BlobHeap(Section section, uint start, uint size) : base(section, start, size) { } public byte[] Read(uint index) { if (index == 0 || index > Size - 1) return Empty<byte>.Array; var data = Section.Data; int position = (int)(index + Offset); int length = (int)Mixin.ReadCompressedUInt32(data, ref position); var buffer = new byte[length]; Buffer.BlockCopy(data, position, buffer, 0, length); return buffer; } } }
{ "content_hash": "cfaa24e09c65bf5224982a6fdbe37a4e", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 77, "avg_line_length": 21.558823529411764, "alnum_prop": 0.5061391541609823, "repo_name": "gameCreator2s/BorderExpansion", "id": "03833d134cf589239b93158d5295cc969ee3a471", "size": "1948", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "borderExpansionProj/Assets/Standard Assets/Mono.Cecil.20/MonoCecil/Mono.Cecil.Metadata/BlobHeap.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "4208436" }, { "name": "CSS", "bytes": "2229" }, { "name": "HLSL", "bytes": "14568" }, { "name": "HTML", "bytes": "17800" }, { "name": "JavaScript", "bytes": "1175" }, { "name": "Lua", "bytes": "31127" }, { "name": "ShaderLab", "bytes": "466562" }, { "name": "XSLT", "bytes": "22214" } ], "symlink_target": "" }
package org.springframework.boot.actuate.autoconfigure; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionOutcome; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration; import org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration; import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; import org.springframework.boot.autoconfigure.security.SecurityPrerequisite; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.security.config.annotation.web.WebSecurityConfigurer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity.IgnoredRequestConfigurer; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AnyRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.StringUtils; /** * {@link EnableAutoConfiguration Auto-configuration} for security of framework endpoints. * Many aspects of the behavior can be controller with {@link ManagementServerProperties} * via externalized application properties (or via an bean definition of that type to set * the defaults). * <p> * The framework {@link Endpoint}s (used to expose application information to operations) * include a {@link Endpoint#isSensitive() sensitive} configuration option which will be * used as a security hint by the filter created here. * * @author Dave Syer * @author Andy Wilkinson */ @Configuration @ConditionalOnWebApplication @ConditionalOnClass({ EnableWebSecurity.class }) @AutoConfigureAfter(SecurityAutoConfiguration.class) @AutoConfigureBefore(FallbackWebSecurityAutoConfiguration.class) @EnableConfigurationProperties public class ManagementWebSecurityAutoConfiguration { private static final String[] NO_PATHS = new String[0]; @Bean @ConditionalOnMissingBean({ IgnoredPathsWebSecurityConfigurerAdapter.class }) public IgnoredPathsWebSecurityConfigurerAdapter ignoredPathsWebSecurityConfigurerAdapter() { return new IgnoredPathsWebSecurityConfigurerAdapter(); } @Configuration protected static class ManagementSecurityPropertiesConfiguration implements SecurityPrerequisite { @Autowired(required = false) private SecurityProperties security; @Autowired(required = false) private ManagementServerProperties management; @PostConstruct public void init() { if (this.management != null && this.security != null) { this.security.getUser().getRole() .add(this.management.getSecurity().getRole()); } } } // Get the ignored paths in early @Order(SecurityProperties.IGNORED_ORDER + 1) private static class IgnoredPathsWebSecurityConfigurerAdapter implements WebSecurityConfigurer<WebSecurity> { @Autowired(required = false) private ErrorController errorController; @Autowired(required = false) private EndpointHandlerMapping endpointHandlerMapping; @Autowired private ManagementServerProperties management; @Autowired private SecurityProperties security; @Autowired(required = false) private ServerProperties server; @Override public void configure(WebSecurity builder) throws Exception { } @Override public void init(WebSecurity builder) throws Exception { IgnoredRequestConfigurer ignoring = builder.ignoring(); // The ignores are not cumulative, so to prevent overwriting the defaults we // add them back. List<String> ignored = SpringBootWebSecurityConfiguration .getIgnored(this.security); if (!this.management.getSecurity().isEnabled()) { ignored.addAll(Arrays .asList(EndpointPaths.ALL.getPaths(this.endpointHandlerMapping))); } if (ignored.contains("none")) { ignored.remove("none"); } if (this.errorController != null) { ignored.add(normalizePath(this.errorController.getErrorPath())); } if (this.server != null) { String[] paths = this.server.getPathsArray(ignored); ignoring.antMatchers(paths); } } private String normalizePath(String errorPath) { String result = StringUtils.cleanPath(errorPath); if (!result.startsWith("/")) { result = "/" + result; } return result; } } @Configuration @ConditionalOnMissingBean(WebSecurityConfiguration.class) @Conditional(WebSecurityEnablerCondition.class) @EnableWebSecurity protected static class WebSecurityEnabler extends AuthenticationManagerConfiguration { } /** * WebSecurityEnabler condition. */ static class WebSecurityEnablerCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String managementEnabled = context.getEnvironment() .getProperty("management.security.enabled", "true"); String basicEnabled = context.getEnvironment() .getProperty("security.basic.enabled", "true"); return new ConditionOutcome( "true".equalsIgnoreCase(managementEnabled) && !"true".equalsIgnoreCase(basicEnabled), "Management security enabled and basic disabled"); } } @Configuration @ConditionalOnMissingBean({ ManagementWebSecurityConfigurerAdapter.class }) @ConditionalOnProperty(prefix = "management.security", name = "enabled", matchIfMissing = true) @Order(ManagementServerProperties.BASIC_AUTH_ORDER) protected static class ManagementWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired private SecurityProperties security; @Autowired private ManagementServerProperties management; @Autowired(required = false) private ManagementContextResolver contextResolver; @Autowired(required = false) private ServerProperties server; @Autowired(required = false) private EndpointHandlerMapping endpointHandlerMapping; public void setEndpointHandlerMapping( EndpointHandlerMapping endpointHandlerMapping) { this.endpointHandlerMapping = endpointHandlerMapping; } protected final EndpointHandlerMapping getRequiredEndpointHandlerMapping() { if (this.endpointHandlerMapping == null) { ApplicationContext context = (this.contextResolver == null ? null : this.contextResolver.getApplicationContext()); if (context != null && context .getBeanNamesForType(EndpointHandlerMapping.class).length > 0) { this.endpointHandlerMapping = context .getBean(EndpointHandlerMapping.class); } if (this.endpointHandlerMapping == null) { this.endpointHandlerMapping = new EndpointHandlerMapping( Collections.<MvcEndpoint>emptySet()); } } return this.endpointHandlerMapping; } @Override protected void configure(HttpSecurity http) throws Exception { // secure endpoints RequestMatcher matcher = getRequestMatcher(); if (matcher != null) { // Always protect them if present if (this.security.isRequireSsl()) { http.requiresChannel().anyRequest().requiresSecure(); } AuthenticationEntryPoint entryPoint = entryPoint(); http.exceptionHandling().authenticationEntryPoint(entryPoint); // Match all the requests for actuator endpoints ... http.requestMatcher(matcher); // ... but permitAll() for the non-sensitive ones configurePermittedRequests(http.authorizeRequests()); http.httpBasic().authenticationEntryPoint(entryPoint); // No cookies for management endpoints by default http.csrf().disable(); http.sessionManagement().sessionCreationPolicy( this.management.getSecurity().getSessions()); SpringBootWebSecurityConfiguration.configureHeaders(http.headers(), this.security.getHeaders()); } } private RequestMatcher getRequestMatcher() { if (!this.management.getSecurity().isEnabled()) { return null; } String path = this.management.getContextPath(); if (StringUtils.hasText(path)) { AntPathRequestMatcher matcher = new AntPathRequestMatcher( this.server.getPath(path) + "/**"); return matcher; } // Match everything, including the sensitive and non-sensitive paths return new EndpointPathRequestMatcher(EndpointPaths.ALL); } private AuthenticationEntryPoint entryPoint() { BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint(); entryPoint.setRealmName(this.security.getBasic().getRealm()); return entryPoint; } private void configurePermittedRequests( ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests) { // Permit access to the non-sensitive endpoints requests.requestMatchers( new EndpointPathRequestMatcher(EndpointPaths.NON_SENSITIVE)) .permitAll(); // Restrict the rest to the configured role requests.anyRequest().hasRole(this.management.getSecurity().getRole()); } private final class EndpointPathRequestMatcher implements RequestMatcher { private final EndpointPaths endpointPaths; private RequestMatcher delegate; EndpointPathRequestMatcher(EndpointPaths endpointPaths) { this.endpointPaths = endpointPaths; } @Override public boolean matches(HttpServletRequest request) { if (this.delegate == null) { this.delegate = createDelegate(); } return this.delegate.matches(request); } private RequestMatcher createDelegate() { ServerProperties server = ManagementWebSecurityConfigurerAdapter.this.server; List<RequestMatcher> matchers = new ArrayList<RequestMatcher>(); EndpointHandlerMapping endpointHandlerMapping = ManagementWebSecurityConfigurerAdapter.this .getRequiredEndpointHandlerMapping(); for (String path : this.endpointPaths.getPaths(endpointHandlerMapping)) { matchers.add(new AntPathRequestMatcher(server.getPath(path))); } return (matchers.isEmpty() ? AnyRequestMatcher.INSTANCE : new OrRequestMatcher(matchers)); } } } private enum EndpointPaths { ALL, NON_SENSITIVE { @Override protected boolean isIncluded(MvcEndpoint endpoint) { return !endpoint.isSensitive(); } }; public String[] getPaths(EndpointHandlerMapping endpointHandlerMapping) { if (endpointHandlerMapping == null) { return NO_PATHS; } Set<? extends MvcEndpoint> endpoints = endpointHandlerMapping.getEndpoints(); Set<String> paths = new LinkedHashSet<String>(endpoints.size()); for (MvcEndpoint endpoint : endpoints) { if (isIncluded(endpoint)) { String path = endpointHandlerMapping.getPath(endpoint.getPath()); paths.add(path); if (!path.equals("")) { if (endpoint.isSensitive()) { // Ensure that nested paths are secured paths.add(path + "/**"); // Add Spring MVC-generated additional paths paths.add(path + ".*"); } } paths.add(path + "/"); } } return paths.toArray(new String[paths.size()]); } protected boolean isIncluded(MvcEndpoint endpoint) { return true; } } }
{ "content_hash": "4a0c54cc87af1f274752a986115725b5", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 107, "avg_line_length": 36.9291553133515, "alnum_prop": 0.7838117022061536, "repo_name": "Nephilim84/contestparser", "id": "8e2aefa12feb0e515bcc79a169f3e1b1050340ea", "size": "14173", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5774" }, { "name": "FreeMarker", "bytes": "2116" }, { "name": "Groovy", "bytes": "39500" }, { "name": "HTML", "bytes": "71561" }, { "name": "Java", "bytes": "7528219" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "Ruby", "bytes": "1305" }, { "name": "SQLPL", "bytes": "20085" }, { "name": "Shell", "bytes": "6296" }, { "name": "Smarty", "bytes": "3276" }, { "name": "XSLT", "bytes": "33894" } ], "symlink_target": "" }
package org.jfree.chart.renderer.xy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Line2D.Double; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.LinkedList; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.ParamChecks; import org.jfree.data.xy.NormalizedMatrixSeries; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; import org.jfree.util.ShapeUtilities; public class XYDifferenceRenderer extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { private static final long serialVersionUID = -8447915602375584857L; private transient Shape legendLine; private transient Paint negativePaint; private transient Paint positivePaint; private boolean roundXCoordinates; private boolean shapesVisible; public XYDifferenceRenderer() { this(Color.green, Color.red, false); } public XYDifferenceRenderer(Paint positivePaint, Paint negativePaint, boolean shapes) { ParamChecks.nullNotPermitted(positivePaint, "positivePaint"); ParamChecks.nullNotPermitted(negativePaint, "negativePaint"); this.positivePaint = positivePaint; this.negativePaint = negativePaint; this.shapesVisible = shapes; this.legendLine = new Double(-7.0d, 0.0d, 7.0d, 0.0d); this.roundXCoordinates = false; } public Paint getPositivePaint() { return this.positivePaint; } public void setPositivePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.positivePaint = paint; fireChangeEvent(); } public Paint getNegativePaint() { return this.negativePaint; } public void setNegativePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.negativePaint = paint; notifyListeners(new RendererChangeEvent(this)); } public boolean getShapesVisible() { return this.shapesVisible; } public void setShapesVisible(boolean flag) { this.shapesVisible = flag; fireChangeEvent(); } public Shape getLegendLine() { return this.legendLine; } public void setLegendLine(Shape line) { ParamChecks.nullNotPermitted(line, "line"); this.legendLine = line; fireChangeEvent(); } public boolean getRoundXCoordinates() { return this.roundXCoordinates; } public void setRoundXCoordinates(boolean round) { this.roundXCoordinates = round; fireChangeEvent(); } public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { XYItemRendererState state = super.initialise(g2, dataArea, plot, data, info); state.setProcessVisibleItemsOnly(false); return state; } public int getPassCount() { return 2; } public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (pass == 0) { drawItemPass0(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState); } else if (pass == 1) { drawItemPass1(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState); } } protected void drawItemPass0(Graphics2D x_graphics, Rectangle2D x_dataArea, PlotRenderingInfo x_info, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, XYDataset x_dataset, int x_series, int x_item, CrosshairState x_crosshairState) { if (x_series == 0 && x_item == 0) { boolean b_impliedZeroSubtrahend = 1 == x_dataset.getSeriesCount(); if (!isEitherSeriesDegenerate(x_dataset, b_impliedZeroSubtrahend)) { if (b_impliedZeroSubtrahend || !areSeriesDisjoint(x_dataset)) { int l_subtrahendItemCount; Double d; double l_slope; boolean b_positive; LinkedList l_minuendXs = new LinkedList(); LinkedList l_minuendYs = new LinkedList(); LinkedList l_subtrahendXs = new LinkedList(); LinkedList l_subtrahendYs = new LinkedList(); LinkedList l_polygonXs = new LinkedList(); LinkedList l_polygonYs = new LinkedList(); int l_minuendItem = 0; int l_minuendItemCount = x_dataset.getItemCount(0); Double l_minuendCurX = null; Double l_minuendNextX = null; Double l_minuendCurY = null; Double l_minuendNextY = null; double l_minuendMaxY = Double.NEGATIVE_INFINITY; double l_minuendMinY = Double.POSITIVE_INFINITY; int l_subtrahendItem = 0; Double d2 = null; Double d3 = null; Double d4 = null; Double d5 = null; double l_subtrahendMaxY = Double.NEGATIVE_INFINITY; double l_subtrahendMinY = Double.POSITIVE_INFINITY; if (b_impliedZeroSubtrahend) { l_subtrahendItem = 0; l_subtrahendItemCount = 2; d = new Double(x_dataset.getXValue(0, 0)); d = new Double(x_dataset.getXValue(0, l_minuendItemCount - 1)); d = new Double(0.0d); d = new Double(0.0d); l_subtrahendMaxY = 0.0d; l_subtrahendMinY = 0.0d; l_subtrahendXs.add(d); l_subtrahendYs.add(d); } else { l_subtrahendItemCount = x_dataset.getItemCount(1); } boolean b_minuendDone = false; boolean b_minuendAdvanced = true; boolean b_minuendAtIntersect = false; boolean b_minuendFastForward = false; boolean b_subtrahendDone = false; boolean b_subtrahendAdvanced = true; boolean b_subtrahendAtIntersect = false; boolean b_subtrahendFastForward = false; boolean b_colinear = false; double l_x1 = 0.0d; double l_y1 = 0.0d; double l_x2 = 0.0d; double l_y2 = 0.0d; double l_x3 = 0.0d; double l_y3 = 0.0d; double l_x4 = 0.0d; double l_y4 = 0.0d; boolean b_fastForwardDone = false; while (!b_fastForwardDone) { l_x1 = x_dataset.getXValue(0, l_minuendItem); l_y1 = x_dataset.getYValue(0, l_minuendItem); l_x2 = x_dataset.getXValue(0, l_minuendItem + 1); l_y2 = x_dataset.getYValue(0, l_minuendItem + 1); d = new Double(l_x1); d = new Double(l_y1); d = new Double(l_x2); d = new Double(l_y2); if (b_impliedZeroSubtrahend) { l_x3 = d2.doubleValue(); l_y3 = d4.doubleValue(); l_x4 = d3.doubleValue(); l_y4 = d5.doubleValue(); } else { l_x3 = x_dataset.getXValue(1, l_subtrahendItem); l_y3 = x_dataset.getYValue(1, l_subtrahendItem); l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1); l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1); d = new Double(l_x3); d = new Double(l_y3); d = new Double(l_x4); d = new Double(l_y4); } if (l_x2 <= l_x3) { l_minuendItem++; b_minuendFastForward = true; } else if (l_x4 <= l_x1) { l_subtrahendItem++; b_subtrahendFastForward = true; } else { if (l_x3 < l_x1 && l_x1 < l_x4) { l_slope = (l_y4 - l_y3) / (l_x4 - l_x3); d2 = d; d = new Double((l_slope * l_x1) + (l_y3 - (l_slope * l_x3))); l_subtrahendXs.add(d2); l_subtrahendYs.add(d); } if (l_x1 < l_x3 && l_x3 < l_x2) { l_slope = (l_y2 - l_y1) / (l_x2 - l_x1); l_minuendCurX = d2; d = new Double((l_slope * l_x3) + (l_y1 - (l_slope * l_x1))); l_minuendXs.add(l_minuendCurX); l_minuendYs.add(d); } l_minuendMaxY = l_minuendCurY.doubleValue(); l_minuendMinY = l_minuendCurY.doubleValue(); l_subtrahendMaxY = d4.doubleValue(); l_subtrahendMinY = d4.doubleValue(); b_fastForwardDone = true; } } while (!b_minuendDone && !b_subtrahendDone) { if (!(b_minuendDone || b_minuendFastForward || !b_minuendAdvanced)) { l_x1 = x_dataset.getXValue(0, l_minuendItem); l_y1 = x_dataset.getYValue(0, l_minuendItem); d = new Double(l_x1); d = new Double(l_y1); if (!b_minuendAtIntersect) { l_minuendXs.add(d); l_minuendYs.add(d); } l_minuendMaxY = Math.max(l_minuendMaxY, l_y1); l_minuendMinY = Math.min(l_minuendMinY, l_y1); l_x2 = x_dataset.getXValue(0, l_minuendItem + 1); l_y2 = x_dataset.getYValue(0, l_minuendItem + 1); d = new Double(l_x2); d = new Double(l_y2); } if (!(b_impliedZeroSubtrahend || b_subtrahendDone || b_subtrahendFastForward || !b_subtrahendAdvanced)) { l_x3 = x_dataset.getXValue(1, l_subtrahendItem); l_y3 = x_dataset.getYValue(1, l_subtrahendItem); d = new Double(l_x3); d = new Double(l_y3); if (!b_subtrahendAtIntersect) { l_subtrahendXs.add(d); l_subtrahendYs.add(d); } l_subtrahendMaxY = Math.max(l_subtrahendMaxY, l_y3); l_subtrahendMinY = Math.min(l_subtrahendMinY, l_y3); l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1); l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1); d = new Double(l_x4); d = new Double(l_y4); } b_minuendFastForward = false; b_subtrahendFastForward = false; Double l_intersectX = null; Double l_intersectY = null; boolean b_intersect = false; b_minuendAtIntersect = false; b_subtrahendAtIntersect = false; if (l_x2 != l_x4 || l_y2 != l_y4) { double l_denominator = ((l_y4 - l_y3) * (l_x2 - l_x1)) - ((l_x4 - l_x3) * (l_y2 - l_y1)); double l_deltaY = l_y1 - l_y3; double l_deltaX = l_x1 - l_x3; double l_numeratorA = ((l_x4 - l_x3) * l_deltaY) - ((l_y4 - l_y3) * l_deltaX); double l_numeratorB = ((l_x2 - l_x1) * l_deltaY) - ((l_y2 - l_y1) * l_deltaX); if (0.0d == l_numeratorA && 0.0d == l_numeratorB && 0.0d == l_denominator) { b_colinear = true; } else if (b_colinear) { Object obj; Double d6; l_minuendXs.clear(); l_minuendYs.clear(); l_subtrahendXs.clear(); l_subtrahendYs.clear(); l_polygonXs.clear(); l_polygonYs.clear(); b_colinear = false; boolean b_useMinuend = l_x3 <= l_x1 && l_x1 <= l_x4; if (b_useMinuend) { obj = l_minuendCurX; } else { d6 = d2; } l_polygonXs.add(obj); if (b_useMinuend) { obj = l_minuendCurY; } else { d6 = d4; } l_polygonYs.add(obj); } double l_slopeA = l_numeratorA / l_denominator; double l_slopeB = l_numeratorB / l_denominator; boolean b_vertical = l_x1 == l_x2 && l_x3 == l_x4 && l_x2 == l_x4; if ((0.0d < l_slopeA && l_slopeA <= NormalizedMatrixSeries.DEFAULT_SCALE_FACTOR && 0.0d < l_slopeB && l_slopeB <= NormalizedMatrixSeries.DEFAULT_SCALE_FACTOR) || b_vertical) { double l_xi; double l_yi; if (b_vertical) { b_colinear = false; l_xi = l_x2; l_yi = l_x4; } else { l_xi = l_x1 + ((l_x2 - l_x1) * l_slopeA); l_yi = l_y1 + ((l_y2 - l_y1) * l_slopeA); } d = new Double(l_xi); d = new Double(l_yi); b_intersect = true; b_minuendAtIntersect = l_xi == l_x2 && l_yi == l_y2; b_subtrahendAtIntersect = l_xi == l_x4 && l_yi == l_y4; l_minuendCurX = d; l_minuendCurY = d; d2 = d; d4 = d; } } else if (l_x1 == l_x3 && l_y1 == l_y3) { b_colinear = true; } else { d = new Double(l_x2); d = new Double(l_y2); b_intersect = true; b_minuendAtIntersect = true; b_subtrahendAtIntersect = true; } if (b_intersect) { l_polygonXs.addAll(l_minuendXs); l_polygonYs.addAll(l_minuendYs); l_polygonXs.add(l_intersectX); l_polygonYs.add(l_intersectY); Collections.reverse(l_subtrahendXs); Collections.reverse(l_subtrahendYs); l_polygonXs.addAll(l_subtrahendXs); l_polygonYs.addAll(l_subtrahendYs); b_positive = l_subtrahendMaxY <= l_minuendMaxY && l_subtrahendMinY <= l_minuendMinY; createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis, x_rangeAxis, b_positive, l_polygonXs, l_polygonYs); l_minuendXs.clear(); l_minuendYs.clear(); l_subtrahendXs.clear(); l_subtrahendYs.clear(); l_polygonXs.clear(); l_polygonYs.clear(); double l_y = l_intersectY.doubleValue(); l_minuendMaxY = l_y; l_subtrahendMaxY = l_y; l_minuendMinY = l_y; l_subtrahendMinY = l_y; l_polygonXs.add(l_intersectX); l_polygonYs.add(l_intersectY); } if (l_x2 <= l_x4) { l_minuendItem++; b_minuendAdvanced = true; } else { b_minuendAdvanced = false; } if (l_x4 <= l_x2) { l_subtrahendItem++; b_subtrahendAdvanced = true; } else { b_subtrahendAdvanced = false; } b_minuendDone = l_minuendItem == l_minuendItemCount + -1; b_subtrahendDone = l_subtrahendItem == l_subtrahendItemCount + -1; } if (b_minuendDone && l_x3 < l_x2 && l_x2 < l_x4) { l_slope = (l_y4 - l_y3) / (l_x4 - l_x3); d3 = l_minuendNextX; d = new Double((l_slope * l_x2) + (l_y3 - (l_slope * l_x3))); } if (b_subtrahendDone && l_x1 < l_x4 && l_x4 < l_x2) { l_slope = (l_y2 - l_y1) / (l_x2 - l_x1); l_minuendNextX = d3; d = new Double((l_slope * l_x4) + (l_y1 - (l_slope * l_x1))); } l_minuendMaxY = Math.max(l_minuendMaxY, l_minuendNextY.doubleValue()); l_subtrahendMaxY = Math.max(l_subtrahendMaxY, d5.doubleValue()); l_minuendMinY = Math.min(l_minuendMinY, l_minuendNextY.doubleValue()); l_subtrahendMinY = Math.min(l_subtrahendMinY, d5.doubleValue()); l_minuendXs.add(l_minuendNextX); l_minuendYs.add(l_minuendNextY); l_subtrahendXs.add(d3); l_subtrahendYs.add(d5); l_polygonXs.addAll(l_minuendXs); l_polygonYs.addAll(l_minuendYs); Collections.reverse(l_subtrahendXs); Collections.reverse(l_subtrahendYs); l_polygonXs.addAll(l_subtrahendXs); l_polygonYs.addAll(l_subtrahendYs); b_positive = l_subtrahendMaxY <= l_minuendMaxY && l_subtrahendMinY <= l_minuendMinY; createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis, x_rangeAxis, b_positive, l_polygonXs, l_polygonYs); } } } } protected void drawItemPass1(Graphics2D x_graphics, Rectangle2D x_dataArea, PlotRenderingInfo x_info, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, XYDataset x_dataset, int x_series, int x_item, CrosshairState x_crosshairState) { Shape l_entityArea = null; EntityCollection l_entities = null; if (x_info != null) { l_entities = x_info.getOwner().getEntityCollection(); } Paint l_seriesPaint = getItemPaint(x_series, x_item); Stroke l_seriesStroke = getItemStroke(x_series, x_item); x_graphics.setPaint(l_seriesPaint); x_graphics.setStroke(l_seriesStroke); PlotOrientation l_orientation = x_plot.getOrientation(); RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge(); RectangleEdge l_rangeAxisLocation = x_plot.getRangeAxisEdge(); double l_x0 = x_dataset.getXValue(x_series, x_item); double l_y0 = x_dataset.getYValue(x_series, x_item); double l_x1 = x_domainAxis.valueToJava2D(l_x0, x_dataArea, l_domainAxisLocation); double l_y1 = x_rangeAxis.valueToJava2D(l_y0, x_dataArea, l_rangeAxisLocation); if (getShapesVisible()) { Shape l_shape = getItemShape(x_series, x_item); if (l_orientation == PlotOrientation.HORIZONTAL) { l_shape = ShapeUtilities.createTranslatedShape(l_shape, l_y1, l_x1); } else { l_shape = ShapeUtilities.createTranslatedShape(l_shape, l_x1, l_y1); } if (l_shape.intersects(x_dataArea)) { x_graphics.setPaint(getItemPaint(x_series, x_item)); x_graphics.fill(l_shape); } l_entityArea = l_shape; } if (l_entities != null) { if (l_entityArea == null) { l_entityArea = new Rectangle2D.Double(l_x1 - DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS, l_y1 - DateAxis.DEFAULT_AUTO_RANGE_MINIMUM_SIZE_IN_MILLISECONDS, 4.0d, 4.0d); } String l_tip = null; XYToolTipGenerator l_tipGenerator = getToolTipGenerator(x_series, x_item); if (l_tipGenerator != null) { l_tip = l_tipGenerator.generateToolTip(x_dataset, x_series, x_item); } String l_url = null; XYURLGenerator l_urlGenerator = getURLGenerator(); if (l_urlGenerator != null) { l_url = l_urlGenerator.generateURL(x_dataset, x_series, x_item); } l_entities.add(new XYItemEntity(l_entityArea, x_dataset, x_series, x_item, l_tip, l_url)); } if (isItemLabelVisible(x_series, x_item)) { drawItemLabel(x_graphics, l_orientation, x_dataset, x_series, x_item, l_x1, l_y1, l_y1 < 0.0d); } updateCrosshairValues(x_crosshairState, l_x0, l_y0, x_plot.getDomainAxisIndex(x_domainAxis), x_plot.getRangeAxisIndex(x_rangeAxis), l_x1, l_y1, l_orientation); if (x_item != 0) { double l_x2 = x_domainAxis.valueToJava2D(x_dataset.getXValue(x_series, x_item - 1), x_dataArea, l_domainAxisLocation); double l_y2 = x_rangeAxis.valueToJava2D(x_dataset.getYValue(x_series, x_item - 1), x_dataArea, l_rangeAxisLocation); Line2D l_line = null; if (PlotOrientation.HORIZONTAL == l_orientation) { l_line = new Double(l_y1, l_x1, l_y2, l_x2); } else if (PlotOrientation.VERTICAL == l_orientation) { Double doubleR = new Double(l_x1, l_y1, l_x2, l_y2); } if (l_line != null && l_line.intersects(x_dataArea)) { x_graphics.setPaint(getItemPaint(x_series, x_item)); x_graphics.setStroke(getItemStroke(x_series, x_item)); x_graphics.draw(l_line); } } } private boolean isEitherSeriesDegenerate(XYDataset x_dataset, boolean x_impliedZeroSubtrahend) { boolean z = false; if (!x_impliedZeroSubtrahend) { if (x_dataset.getItemCount(0) < 2 || x_dataset.getItemCount(1) < 2) { z = true; } return z; } else if (x_dataset.getItemCount(0) < 2) { return true; } else { return false; } } private boolean areSeriesDisjoint(XYDataset x_dataset) { int l_minuendItemCount = x_dataset.getItemCount(0); double l_minuendFirst = x_dataset.getXValue(0, 0); double l_minuendLast = x_dataset.getXValue(0, l_minuendItemCount - 1); int l_subtrahendItemCount = x_dataset.getItemCount(1); double l_subtrahendFirst = x_dataset.getXValue(1, 0); double l_subtrahendLast = x_dataset.getXValue(1, l_subtrahendItemCount - 1); if (l_minuendLast < l_subtrahendFirst || l_subtrahendLast < l_minuendFirst) { return true; } return false; } private void createPolygon(Graphics2D x_graphics, Rectangle2D x_dataArea, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, boolean x_positive, LinkedList x_xValues, LinkedList x_yValues) { PlotOrientation l_orientation = x_plot.getOrientation(); RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge(); RectangleEdge l_rangeAxisLocation = x_plot.getRangeAxisEdge(); Object[] l_xValues = x_xValues.toArray(); Object[] l_yValues = x_yValues.toArray(); GeneralPath l_path = new GeneralPath(); double l_x; int i; if (PlotOrientation.VERTICAL == l_orientation) { l_x = x_domainAxis.valueToJava2D(((Double) l_xValues[0]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_path.moveTo((float) l_x, (float) x_rangeAxis.valueToJava2D(((Double) l_yValues[0]).doubleValue(), x_dataArea, l_rangeAxisLocation)); for (i = 1; i < l_xValues.length; i++) { l_x = x_domainAxis.valueToJava2D(((Double) l_xValues[i]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_path.lineTo((float) l_x, (float) x_rangeAxis.valueToJava2D(((Double) l_yValues[i]).doubleValue(), x_dataArea, l_rangeAxisLocation)); } l_path.closePath(); } else { l_x = x_domainAxis.valueToJava2D(((Double) l_xValues[0]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_path.moveTo((float) x_rangeAxis.valueToJava2D(((Double) l_yValues[0]).doubleValue(), x_dataArea, l_rangeAxisLocation), (float) l_x); for (i = 1; i < l_xValues.length; i++) { l_x = x_domainAxis.valueToJava2D(((Double) l_xValues[i]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_path.lineTo((float) x_rangeAxis.valueToJava2D(((Double) l_yValues[i]).doubleValue(), x_dataArea, l_rangeAxisLocation), (float) l_x); } l_path.closePath(); } if (l_path.intersects(x_dataArea)) { Paint positivePaint; if (x_positive) { positivePaint = getPositivePaint(); } else { positivePaint = getNegativePaint(); } x_graphics.setPaint(positivePaint); x_graphics.fill(l_path); } } public LegendItem getLegendItem(int datasetIndex, int series) { LegendItem result = null; XYPlot p = getPlot(); if (p != null) { XYDataset dataset = p.getDataset(datasetIndex); if (dataset != null && getItemVisible(series, 0)) { String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel(dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Paint paint = lookupSeriesPaint(series); result = new LegendItem(label, description, toolTipText, urlText, getLegendLine(), lookupSeriesStroke(series), paint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); } } return result; } public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYDifferenceRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYDifferenceRenderer that = (XYDifferenceRenderer) obj; if (!PaintUtilities.equal(this.positivePaint, that.positivePaint)) { return false; } if (!PaintUtilities.equal(this.negativePaint, that.negativePaint)) { return false; } if (this.shapesVisible != that.shapesVisible) { return false; } if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) { return false; } if (this.roundXCoordinates != that.roundXCoordinates) { return false; } return true; } public Object clone() throws CloneNotSupportedException { XYDifferenceRenderer clone = (XYDifferenceRenderer) super.clone(); clone.legendLine = ShapeUtilities.clone(this.legendLine); return clone; } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.positivePaint, stream); SerialUtilities.writePaint(this.negativePaint, stream); SerialUtilities.writeShape(this.legendLine, stream); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.positivePaint = SerialUtilities.readPaint(stream); this.negativePaint = SerialUtilities.readPaint(stream); this.legendLine = SerialUtilities.readShape(stream); } }
{ "content_hash": "92aec35c1fd0be48378d43213614791f", "timestamp": "", "source": "github", "line_count": 640, "max_line_length": 252, "avg_line_length": 49.7765625, "alnum_prop": 0.5020246727563801, "repo_name": "ivanshen/Who-Are-You-Really", "id": "3351b84005669f06b76ba06240d0b66e556bcf6e", "size": "31857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "org/jfree/chart/renderer/xy/XYDifferenceRenderer.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "4336252" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <title>Inclusion (ARX API Documentation)</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="Inclusion (ARX API Documentation)"; } //--> </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="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Inclusion.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/deidentifier/arx/criteria/ImplicitPrivacyCriterion.html" title="class in org.deidentifier.arx.criteria"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/deidentifier/arx/criteria/KAnonymity.html" title="class in org.deidentifier.arx.criteria"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/deidentifier/arx/criteria/Inclusion.html" target="_top">Frames</a></li> <li><a href="Inclusion.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.deidentifier.arx.criteria</div> <h2 title="Class Inclusion" class="title">Class Inclusion</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html" title="class in org.deidentifier.arx.criteria">org.deidentifier.arx.criteria.PrivacyCriterion</a></li> <li> <ul class="inheritance"> <li><a href="../../../../org/deidentifier/arx/criteria/ImplicitPrivacyCriterion.html" title="class in org.deidentifier.arx.criteria">org.deidentifier.arx.criteria.ImplicitPrivacyCriterion</a></li> <li> <ul class="inheritance"> <li><a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">org.deidentifier.arx.criteria.DPresence</a></li> <li> <ul class="inheritance"> <li>org.deidentifier.arx.criteria.Inclusion</li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable</dd> </dl> <hr> <br> <pre>public class <span class="strong">Inclusion</span> extends <a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">DPresence</a></pre> <div class="block">This is a special criterion that does not enforce any privacy guarantees but allows to define a data subset.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#org.deidentifier.arx.criteria.Inclusion">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../org/deidentifier/arx/criteria/Inclusion.html#Inclusion(org.deidentifier.arx.DataSubset)">Inclusion</a></strong>(<a href="../../../../org/deidentifier/arx/DataSubset.html" title="class in org.deidentifier.arx">DataSubset</a>&nbsp;subset)</code> <div class="block">Creates a new instance of the enclosure criterion.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../org/deidentifier/arx/criteria/Inclusion.html#getRequirements()">getRequirements</a></strong>()</code> <div class="block">Returns the criterion's requirements.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../org/deidentifier/arx/criteria/Inclusion.html#initialize(org.deidentifier.arx.framework.data.DataManager)">initialize</a></strong>(org.deidentifier.arx.framework.data.DataManager&nbsp;manager)</code> <div class="block">Override this to initialize the criterion.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/deidentifier/arx/criteria/Inclusion.html#isAnonymous(org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry)">isAnonymous</a></strong>(org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry&nbsp;entry)</code> <div class="block">Implement this, to enforce the criterion.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/deidentifier/arx/criteria/Inclusion.html#isLocalRecodingSupported()">isLocalRecodingSupported</a></strong>()</code> <div class="block">Returns whether the criterion supports local recoding.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/deidentifier/arx/criteria/Inclusion.html#toString()">toString</a></strong>()</code> <div class="block">Returns a string representation.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.deidentifier.arx.criteria.DPresence"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.deidentifier.arx.criteria.<a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">DPresence</a></h3> <code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html#clone()">clone</a>, <a href="../../../../org/deidentifier/arx/criteria/DPresence.html#getDMax()">getDMax</a>, <a href="../../../../org/deidentifier/arx/criteria/DPresence.html#getDMin()">getDMin</a>, <a href="../../../../org/deidentifier/arx/criteria/DPresence.html#getSubset()">getSubset</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.deidentifier.arx.criteria.PrivacyCriterion"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.deidentifier.arx.criteria.<a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html" title="class in org.deidentifier.arx.criteria">PrivacyCriterion</a></h3> <code><a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#getPopulationModel()">getPopulationModel</a>, <a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#getRiskThresholdJournalist()">getRiskThresholdJournalist</a>, <a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#getRiskThresholdMarketer()">getRiskThresholdMarketer</a>, <a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#getRiskThresholdProsecutor()">getRiskThresholdProsecutor</a>, <a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#isMonotonicWithGeneralization()">isMonotonicWithGeneralization</a>, <a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#isMonotonicWithSuppression()">isMonotonicWithSuppression</a>, <a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#isSampleBased()">isSampleBased</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Inclusion(org.deidentifier.arx.DataSubset)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Inclusion</h4> <pre>public&nbsp;Inclusion(<a href="../../../../org/deidentifier/arx/DataSubset.html" title="class in org.deidentifier.arx">DataSubset</a>&nbsp;subset)</pre> <div class="block">Creates a new instance of the enclosure criterion.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>subset</code> - Research subset</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getRequirements()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRequirements</h4> <pre>public&nbsp;int&nbsp;getRequirements()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#getRequirements()">PrivacyCriterion</a></code></strong></div> <div class="block">Returns the criterion's requirements.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html#getRequirements()">getRequirements</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">DPresence</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd></dd></dl> </li> </ul> <a name="initialize(org.deidentifier.arx.framework.data.DataManager)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>initialize</h4> <pre>public&nbsp;void&nbsp;initialize(org.deidentifier.arx.framework.data.DataManager&nbsp;manager)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#initialize(org.deidentifier.arx.framework.data.DataManager)">PrivacyCriterion</a></code></strong></div> <div class="block">Override this to initialize the criterion.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html#initialize(org.deidentifier.arx.framework.data.DataManager)">initialize</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">DPresence</a></code></dd> </dl> </li> </ul> <a name="isAnonymous(org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isAnonymous</h4> <pre>public&nbsp;boolean&nbsp;isAnonymous(org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry&nbsp;entry)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#isAnonymous(org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry)">PrivacyCriterion</a></code></strong></div> <div class="block">Implement this, to enforce the criterion.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html#isAnonymous(org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry)">isAnonymous</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">DPresence</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd></dd></dl> </li> </ul> <a name="isLocalRecodingSupported()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isLocalRecodingSupported</h4> <pre>public&nbsp;boolean&nbsp;isLocalRecodingSupported()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#isLocalRecodingSupported()">PrivacyCriterion</a></code></strong></div> <div class="block">Returns whether the criterion supports local recoding.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html#isLocalRecodingSupported()">isLocalRecodingSupported</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">DPresence</a></code></dd> <dt><span class="strong">Returns:</span></dt><dd></dd></dl> </li> </ul> <a name="toString()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/PrivacyCriterion.html#toString()">PrivacyCriterion</a></code></strong></div> <div class="block">Returns a string representation.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html#toString()">toString</a></code>&nbsp;in class&nbsp;<code><a href="../../../../org/deidentifier/arx/criteria/DPresence.html" title="class in org.deidentifier.arx.criteria">DPresence</a></code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Inclusion.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/deidentifier/arx/criteria/ImplicitPrivacyCriterion.html" title="class in org.deidentifier.arx.criteria"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/deidentifier/arx/criteria/KAnonymity.html" title="class in org.deidentifier.arx.criteria"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/deidentifier/arx/criteria/Inclusion.html" target="_top">Frames</a></li> <li><a href="Inclusion.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "df7fcb35a44aaff35d8f25234dfa3782", "timestamp": "", "source": "github", "line_count": 386, "max_line_length": 921, "avg_line_length": 47.0880829015544, "alnum_prop": 0.6636773767605634, "repo_name": "fstahnke/arx", "id": "b27647742264a88b562bde2de9abcfd895e5502d", "size": "18176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/api/org/deidentifier/arx/criteria/Inclusion.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "48618" }, { "name": "Java", "bytes": "5107323" } ], "symlink_target": "" }
#!/usr/bin/env python # from singa.model import * def load_data( workspace = None, backend = 'kvfile', nb_rbm = 0, # the number of layers for RBM and Autoencoder checkpoint_steps = 0, **pvalues ): # using mnist dataset data_dir = 'examples/mnist' path_train = data_dir + '/train_data.bin' path_test = data_dir + '/test_data.bin' if workspace == None: workspace = data_dir # checkpoint path to load checkpoint_list = None if checkpoint_steps > 0: workerid = 0 checkpoint_list = [] for i in range(nb_rbm-1, 0, -1): checkpoint_list.append('examples/rbm/rbm{0}/checkpoint/step{1}-worker{2}'.format(str(i),checkpoint_steps,workerid)) store = Store(path=path_train, backend=backend, **pvalues) data_train = Data(load='recordinput', phase='train', conf=store, checkpoint=checkpoint_list) store = Store(path=path_test, backend=backend, **pvalues) data_test = Data(load='recordinput', phase='test', conf=store) return data_train, data_test, workspace
{ "content_hash": "15d0acfb8482ae3821ab5af59478761f", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 121, "avg_line_length": 28.47222222222222, "alnum_prop": 0.6663414634146342, "repo_name": "jinyangturbo/incubator-singa", "id": "0f75393a4c5ce6b2a0599c2a9b6e75c368b76812", "size": "1957", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tool/python/examples/datasets/mnist.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "15155" }, { "name": "C++", "bytes": "2020411" }, { "name": "Cuda", "bytes": "29301" }, { "name": "M4", "bytes": "9075" }, { "name": "Makefile", "bytes": "12643" }, { "name": "Protocol Buffer", "bytes": "29456" }, { "name": "Python", "bytes": "87084" }, { "name": "Shell", "bytes": "21827" }, { "name": "VimL", "bytes": "1356" } ], "symlink_target": "" }
import config from '../config/config'; import factory from './factory'; export default factory(config.multiForum);
{ "content_hash": "c7a3cf437269ad2d3c5caa89e976f5ef", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 42, "avg_line_length": 29, "alnum_prop": 0.7586206896551724, "repo_name": "alexproca/democracy-os", "id": "cb646e3d6959b5704fb346c14b508be26abb25b7", "size": "116", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/url-builder/url-builder.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "116961" }, { "name": "HTML", "bytes": "56633" }, { "name": "JavaScript", "bytes": "371013" }, { "name": "Makefile", "bytes": "412" } ], "symlink_target": "" }
package {{application.rootpackage}}.app; import android.app.Activity; import android.os.Bundle; import butterknife.ButterKnife; import {{application.rootpackage}}.R; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ApplicationImpl.with(this).inject(this); ButterKnife.inject(this); } }
{ "content_hash": "8f7c1c95341864953ee5686110953015", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 56, "avg_line_length": 22.428571428571427, "alnum_prop": 0.7282377919320594, "repo_name": "KarlNosworthy/startr", "id": "95c7b3c2df8c251577cdde3262dd1d1d4c9e88d2", "size": "471", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/android/app/code/app/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2185" }, { "name": "Shell", "bytes": "2645" } ], "symlink_target": "" }
(function($,sr){ // debouncing function from John Hann // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ var debounce = function (func, threshold, execAsap) { var timeout; return function debounced () { var obj = this, args = arguments; function delayed () { if (!execAsap) func.apply(obj, args); timeout = null; }; if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 100); }; } // smartresize jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); }; })(jQuery,'smartresize');
{ "content_hash": "209fb23841048e88b4687d1743b300e9", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 101, "avg_line_length": 30.23076923076923, "alnum_prop": 0.5559796437659033, "repo_name": "sp90/review", "id": "d4e6578d02adaeb80784b7b9d22d34d5186b30e9", "size": "786", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/js/plugins/smartresize.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "105300" }, { "name": "JavaScript", "bytes": "575671" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.IO; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; using System.Linq; using Microsoft.Win32; using Common = ISIS.GME.Common; using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces; using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes; using ISIS.GME.Common.Interfaces; using System.Windows.Forms; using CyPhySignalBlocksAddOn; namespace CyPhySignalBlocksAddOn { [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyPhySignalBlocksAddOnAddon : IMgaComponentEx, IGMEVersionInfo, IMgaEventSink { private MgaAddOn addon; private bool componentEnabled = true; private bool firstTime = false; private LibraryInfo QudtLibraryInfo; private LibraryInfo PortLibraryInfo; private LibraryInfo MaterialLibraryInfo; private LibraryInfo CADResourceLibraryInfo; private LibraryInfo TestbenchesInfo; private string metaPath; private List<string> libraryPaths = new List<string>(); private GMEConsole GMEConsole { get; set; } private MgaProject project; private delegate void TimerLogicDelegate(); // test code private class LibraryInfo { public bool attachedLibrary = false; private string displayName; public string DisplayName { get { return displayName; } } private string mgaName; public string MgaName { get { return mgaName; } } private LibraryTimer timer; public void TimerGo() { timer.go(); } public LibraryInfo(string mga, string display, TimerLogicDelegate f, IMgaProject project) { mgaName = mga; displayName = display; timer = new LibraryTimer(mgaName, f, project); } } private class LibraryTimer { private string storeName; public string Name { get { return storeName; } } private bool setupTimer = false; private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); private TimerLogicDelegate callback; private IMgaProject project; public LibraryTimer(string name, TimerLogicDelegate f, IMgaProject project) { callback = f; storeName = name; this.project = project; } public void TimerEventProcessor(Object obj, EventArgs evtArgs) { if ((project.ProjectStatus & 8) == 0) // if not in transaction { timer.Stop(); callback(); } } public void go() { if (!setupTimer) { timer.Tick += new EventHandler(TimerEventProcessor); timer.Interval = 1; timer.Start(); setupTimer = true; } //else //{ //timer.Enabled = true; // restart the timer -- unused right now because library refresh is not useful //} } } public CyPhySignalBlocksAddOnAddon() { } // Event handlers for addons #region MgaEventSink members public void GlobalEvent(globalevent_enum @event) { if (@event == globalevent_enum.GLOBALEVENT_CLOSE_PROJECT) { Marshal.FinalReleaseComObject(addon); addon = null; } if (!componentEnabled) { return; } if (@event == globalevent_enum.GLOBALEVENT_OPEN_PROJECT) { if (Environment.Is64BitProcess) { MessageBox.Show("You're running GME (64 bit). Many CyPhyML components do not work with GME (64 bit). Please start GME instead."); } } if (@event == (globalevent_enum)11 /* GLOBALEVENT_OPEN_PROJECT_FINISHED */) { // Store all library path names that will be attached // Nothing will be attached for these projects based on http://escher.isis.vanderbilt.edu/JIRA/browse/META-1559 // Don't attach QUDT or PortLib to themselves libraryPaths.Add(Path.Combine(metaPath, QudtLibraryInfo.MgaName + ".mga")); libraryPaths.Add(Path.Combine(metaPath, PortLibraryInfo.MgaName + ".mga")); libraryPaths.Add(Path.Combine(metaPath, MaterialLibraryInfo.MgaName + ".mga")); libraryPaths.Add(Path.Combine(metaPath, CADResourceLibraryInfo.MgaName + ".mga")); libraryPaths.Add(Path.Combine(metaPath, TestbenchesInfo.MgaName + ".mga")); TriggerQudtRefreshIfNeeded(); } if (@event == globalevent_enum.GLOBALEVENT_COMMIT_TRANSACTION) { CollapseFoldersWithSameNames(); } if (@event == globalevent_enum.APPEVENT_XML_IMPORT_END) { // System.Diagnostics.Trace.WriteLine("XML import end event"); needFolderCollapse = true; CollapseFoldersWithSameNames(); } // System.Diagnostics.Trace.WriteLine(@event.ToString()); // TODO: Handle global events // MessageBox.Show(@event.ToString()); } private bool needFolderCollapse = false; private void CollapseFoldersWithSameNames() { if (needFolderCollapse == false) { return; } if (addon == null) { // this method can be called as a delegate after the timer expires // if the xml import fails addon will be null so we have nothing to // do in that case. // this prevents a null reference exception on addon.Project line below return; } if ((addon.Project.ProjectStatus & 8) != 0) { System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); timer.Tick += (sender, args) => { this.CollapseFoldersWithSameNames(); timer.Stop(); timer.Dispose(); }; timer.Interval = 1; timer.Start(); return; } addon.Project.BeginTransactionInNewTerr(); try { needFolderCollapse = false; GMEConsole.Info.WriteLine("Collapse duplicate folder names into one..."); this.CollapseFolders(this.project.RootFolder); this.CollapseLibraries(this.project.RootFolder); GMEConsole.Info.WriteLine("Removing empty duplicated folders..."); this.RemoveEmptyDuplicatedFolders(this.project.RootFolder); GMEConsole.Info.WriteLine("Done."); } catch (Exception e) { GMEConsole.Info.WriteLine("Exception occurred while collapsing folders: " + e.Message); addon.Project.AbortTransaction(); return; } addon.Project.CommitTransaction(); } private void CollapseLibraries(MgaFolder mgaFolder) { LibraryInfo[] infos = new LibraryInfo[] { this.QudtLibraryInfo, this.PortLibraryInfo, this.MaterialLibraryInfo, this.CADResourceLibraryInfo, this.TestbenchesInfo }; var libraries = mgaFolder .ChildFolders .Cast<MgaFolder>() .Where(x => string.IsNullOrEmpty(x.LibraryName) == false) .GroupBy(lib => infos.Where(inf => lib.Name.Contains(inf.DisplayName)).FirstOrDefault()) .ToList(); foreach (IGrouping<LibraryInfo, MgaFolder> group in libraries.Where(gr => gr.Key != null)) { var orderedLibraries = group.OrderBy(f => f.RelID); var library = orderedLibraries.First(); foreach (var dup in orderedLibraries.Skip(1)) { ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(dup, library, null); sw.UpdateSublibrary(); dup.DestroyObject(); } } } private void RemoveEmptyDuplicatedFolders(MgaFolder mgaFolder) { foreach (MgaFolder childFolder in mgaFolder.ChildFolders) { if (childFolder.IsLibOrLibObject() == false) { this.RemoveEmptyDuplicatedFolders(childFolder); } } var uniqueNames = mgaFolder .ChildFolders .Cast<MgaFolder>() .Where(x => x.IsLibOrLibObject() == false) .Select(x => x.Name) .Distinct() .ToList(); foreach (var uniqueFolderName in uniqueNames) { var firstObj = mgaFolder.ChildFolders.Cast<MgaFolder>().Where(x => x.IsLibOrLibObject() == false).Where(x => x.Name == uniqueFolderName).FirstOrDefault(); var foldersToDelete = mgaFolder.ChildFolders.Cast<MgaFolder>().Where(x => x.IsLibOrLibObject() == false).Where(x => x != firstObj).Where(x => x.Name == uniqueFolderName).Where(x => x.ChildObjects.Count == 0).ToList(); foldersToDelete.ForEach(x => x.DestroyObject()); } } private void CollapseFolders(MgaFolder mgaFolder) { Func<IMgaObject, Tuple<string, string>> nameAndKind = x => new Tuple<string, string>(x.Name, x.MetaBase.Name); var uniqueNames = mgaFolder .ChildFolders .Cast<MgaFolder>() .Where(x => x.IsLibOrLibObject() == false) .Where(x => x.MetaBase.Name != "RootFolder") .GroupBy(x => nameAndKind(x)) .ToList(); foreach (var group in uniqueNames.Where(x => x.Any())) { var firstObj = group.First(); var foldersToMove = group.Skip(1).SelectMany(x => x.ChildFolders.Cast<MgaFolder>()).Where(x => x.IsLibOrLibObject() == false); var fcosToMove = group.Skip(1).SelectMany(x => x.ChildFCOs.Cast<MgaFCO>()).Where(x => x.IsLibObject == false); //GMEConsole.Info.WriteLine(" -- {0}", firstObj.AbsPath); foreach (var item in foldersToMove) { if (item.IsLibOrLibObject()) { GMEConsole.Error.WriteLine(" - Lib object! {0}", item.AbsPath); continue; } var moved = firstObj.MoveFolderDisp(item); //GMEConsole.Info.WriteLine(" ----- {0} -> {1}", item.AbsPath, moved.AbsPath); } foreach (var item in fcosToMove) { if (item.IsLibObject) { GMEConsole.Error.WriteLine(" - Lib object! {0}", item.AbsPath); continue; } var moved = firstObj.MoveFCODisp(item); //GMEConsole.Info.WriteLine(" ----- {0} -> {1}", item.AbsPath, moved.AbsPath); } } foreach (MgaFolder childFolder in mgaFolder.ChildFolders) { if (childFolder.IsLibOrLibObject() == false) { this.CollapseFolders(childFolder); } } } // Look up the value of the META_PATH variable public string GetMetaPathValue() { const string keyName = "Software\\META"; RegistryKey metaKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32) .OpenSubKey(keyName, false); using (metaKey) { string metaPath = "C:\\Program Files (x86)\\META"; if (metaKey != null) { metaPath = (string)metaKey.GetValue("META_PATH", metaPath); } return metaPath; } } /// <summary> /// Called when an FCO or folder changes /// </summary> /// <param name="subject">the object the event(s) happened to</param> /// <param name="eventMask">objectevent_enum values ORed together</param> /// <param name="param">extra information provided for cetertain event types</param> public void ObjectEvent(MgaObject subject, uint eventMask, object param) { // TODO: Handle object events (OR eventMask with the members of objectevent_enum) // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(project); } TriggerQudtRefreshIfNeeded(); } private void TriggerQudtRefreshIfNeeded() { if (!firstTime) { // put the arguments into private variables where they can be reached by the timer code if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(project); } #if DEBUG GMEConsole.Info.WriteLine("CyPhySignalBlocksAddOn starting up..."); #endif //GMEConsole.Info.WriteLine(eventMask.ToString()); if (!componentEnabled) { GMEConsole.Info.WriteLine("CyPhySignalBlocksAddOn not enabled..."); return; } // First, check to see whether the libraries have already been loaded //CyPhy.RootFolder rootFolder = ISIS.GME.Common.Utils.CreateObject<CyPhyClasses.RootFolder>(rf as MgaObject); IMgaFolder rootFolder = project.RootFolder; IMgaFolders subFolders = rootFolder.ChildFolders; // META-1320: refactored some // Run this on any event, but only once (if not already loaded) if (!QudtLibraryInfo.attachedLibrary) //if (!attachedQudtLibrary) { QudtLibraryInfo.TimerGo(); } if (!PortLibraryInfo.attachedLibrary) //if (!attachedPortLibrary) { PortLibraryInfo.TimerGo(); // portLibTimer.go(); } if (!MaterialLibraryInfo.attachedLibrary) // if (!attachedMaterialLibrary) { MaterialLibraryInfo.TimerGo(); } if (!CADResourceLibraryInfo.attachedLibrary) { CADResourceLibraryInfo.TimerGo(); } if (!TestbenchesInfo.attachedLibrary) { TestbenchesInfo.TimerGo(); } firstTime = true; } } public void QudtTimerHandler() { AttachLibrary(QudtLibraryInfo); } public void PortLibTimerHandler() { AttachLibrary(PortLibraryInfo); } public void MaterialLibTimerHandler() { AttachLibrary(MaterialLibraryInfo); } public void CADResourceLibTimerHandler() { AttachLibrary(CADResourceLibraryInfo); } private readonly int PROJECT_STATUS_OPEN = 0x1; private void AttachLibrary(LibraryInfo libraryInfo) { string mgaPath = metaPath + "\\" + libraryInfo.MgaName + ".mga"; if (!libraryInfo.attachedLibrary && (project.ProjectStatus & PROJECT_STATUS_OPEN) == PROJECT_STATUS_OPEN) { if (!File.Exists(mgaPath)) { GMEConsole.Error.WriteLine("Path '" + mgaPath + "' does not exist. Cannot attach " + libraryInfo.MgaName); return; } project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_BEGIN); try { project.BeginTransaction(project.ActiveTerritory); IMgaFolder oldLibFolder = project.RootFolder.ChildFolders.Cast<IMgaFolder>() .Where(x => string.IsNullOrWhiteSpace(x.LibraryName) == false && (x.Name.Contains(libraryInfo.DisplayName) || x.Name.Contains(libraryInfo.DisplayName))).FirstOrDefault(); bool needAttach; if (oldLibFolder == null) { needAttach = true; if (libraryPaths.Contains(Path.GetFullPath(project.ProjectConnStr.Substring("MGA=".Length)))) { // Don't attach libraries to themselves needAttach = false; } } else { DateTime oldModTime; long loldModTime; if (long.TryParse(oldLibFolder.RegistryValue["modtime"], out loldModTime)) { oldModTime = DateTime.FromFileTimeUtc(loldModTime); } else { oldModTime = DateTime.MinValue; } needAttach = File.GetLastWriteTimeUtc(mgaPath).CompareTo(oldModTime) > 0; if (!needAttach) { GMEConsole.Info.WriteLine("Library is up-to-date: embedded library modified " + oldModTime.ToString() + ", " + libraryInfo.MgaName + " modified " + File.GetLastWriteTimeUtc(mgaPath).ToString()); } } if (needAttach) { MgaProject proj = (MgaProject) Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); int mgaVersion; string paradigmName; string paradigmVersion; object paradigmGuid; bool readOnly; proj.QueryProjectInfo("MGA=" + mgaPath, out mgaVersion, out paradigmName, out paradigmVersion, out paradigmGuid, out readOnly); Guid guidP1 = ConvertToGUID(paradigmGuid); Guid guidP2 = ConvertToGUID(project.RootMeta.GUID); bool guidsEqual = guidP1.Equals(guidP2); if (paradigmName != project.MetaName || !guidsEqual) { GMEConsole.Info.WriteLine("Skipping refresh of " + libraryInfo.DisplayName + " because it uses a different metamodel version than the current project."); throw new Exception(); } GMEConsole.Info.WriteLine("Attaching library " + mgaPath); RootFolder newLibFolder = Common.Classes.RootFolder.GetRootFolder(project).AttachLibrary("MGA=" + mgaPath); DateTime modtime = File.GetLastWriteTimeUtc(mgaPath); ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).RegistryValue["modtime"] = modtime.ToFileTimeUtc().ToString(); if (oldLibFolder != null) { ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(oldLibFolder, newLibFolder.Impl, null); sw.UpdateSublibrary(); oldLibFolder.DestroyObject(); } ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).LibraryName = libraryInfo.DisplayName; GMEConsole.Info.WriteLine((oldLibFolder == null ? "Attached " : "Refreshed ") + libraryInfo.MgaName + ".mga library."); } project.CommitTransaction(); } catch { project.AbortTransaction(); } finally { project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_END); } libraryInfo.attachedLibrary = true; } } private static Guid ConvertToGUID(object guidObj) { var array = (Array)guidObj; byte[] bytearray = new byte[16]; array.CopyTo(bytearray, 0); var guid = new Guid(bytearray); return guid; } #endregion #region IMgaComponentEx Members public void Initialize(MgaProject p) { // Creating addon p.CreateAddOn(this, out addon); // Setting event mask (see ComponentConfig.eventMask) unchecked { addon.EventMask = (uint)ComponentConfig.eventMask; } this.project = p; if (metaPath == null) { metaPath = Path.Combine(GetMetaPathValue(), "meta"); } if (!Directory.Exists(metaPath)) { throw new ApplicationException(metaPath + " doesn't exist"); } //qudtTimer = new LibraryTimer("QudtTimer", new TimerLogicDelegate(QudtTimerHandler), project); //portLibTimer = new LibraryTimer("PortLibTimer", new TimerLogicDelegate(PortLibTimerHandler), project); QudtLibraryInfo = new LibraryInfo("CyPhyMLQudt", "UnitLibrary QUDT", new TimerLogicDelegate(QudtTimerHandler), project); PortLibraryInfo = new LibraryInfo("CyPhy_PortLib", "PortLibrary CyPhy_PortLib", new TimerLogicDelegate(PortLibTimerHandler), project); MaterialLibraryInfo = new LibraryInfo("CyPhy_MaterialLib", "MaterialLibrary CyPhy_MaterialLib", new TimerLogicDelegate(MaterialLibTimerHandler), project); CADResourceLibraryInfo = new LibraryInfo("CyPhy_CADResourceLib", "CADResourceLibrary", new TimerLogicDelegate(CADResourceLibTimerHandler), project); TestbenchesInfo = new LibraryInfo("Testbenches", "TestBenchLibrary", new TimerLogicDelegate(() => AttachLibrary(TestbenchesInfo)), project); } public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); // Not called by addon } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion } public static class MgaObjectLibrary { public static bool IsLibOrLibObject(this IMgaObject o) { if (o is IMgaFolder) { return string.IsNullOrEmpty(((IMgaFolder)o).LibraryName) == false || o.IsLibObject; } else { return o.IsLibObject; } } public static bool IsLibOrLibObject(this MgaFolder o) { return IsLibOrLibObject(((IMgaObject)o)); } } }
{ "content_hash": "440fa524bbdb4faf19b43be861b3d6cd", "timestamp": "", "source": "github", "line_count": 740, "max_line_length": 233, "avg_line_length": 37.69054054054054, "alnum_prop": 0.5129970241296475, "repo_name": "pombredanne/metamorphosys-desktop", "id": "012ae5bc56360f46870a5edeac927864f782c68b", "size": "30674", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metamorphosys/META/src/CyPhySignalBlocksAddOn/CyPhySignalBlocksAddOn.cs", "mode": "33261", "license": "mit", "language": [ { "name": "Arduino", "bytes": "10683" }, { "name": "Assembly", "bytes": "117345" }, { "name": "Awk", "bytes": "3591" }, { "name": "Batchfile", "bytes": "228118" }, { "name": "BitBake", "bytes": "4526" }, { "name": "C", "bytes": "3613212" }, { "name": "C#", "bytes": "11617773" }, { "name": "C++", "bytes": "51448188" }, { "name": "CMake", "bytes": "3055" }, { "name": "CSS", "bytes": "109563" }, { "name": "Clojure", "bytes": "37831" }, { "name": "Eagle", "bytes": "3782687" }, { "name": "Emacs Lisp", "bytes": "8514" }, { "name": "GAP", "bytes": "49124" }, { "name": "Groff", "bytes": "2178" }, { "name": "Groovy", "bytes": "7686" }, { "name": "HTML", "bytes": "4025250" }, { "name": "Inno Setup", "bytes": "35715" }, { "name": "Java", "bytes": "489537" }, { "name": "JavaScript", "bytes": "167454" }, { "name": "Lua", "bytes": "1660" }, { "name": "Makefile", "bytes": "97209" }, { "name": "Mathematica", "bytes": "26" }, { "name": "Matlab", "bytes": "80874" }, { "name": "Max", "bytes": "78198" }, { "name": "Modelica", "bytes": "44541139" }, { "name": "Objective-C", "bytes": "34004" }, { "name": "Perl", "bytes": "19285" }, { "name": "PostScript", "bytes": "400254" }, { "name": "PowerShell", "bytes": "19749" }, { "name": "Processing", "bytes": "1477" }, { "name": "Prolog", "bytes": "3121" }, { "name": "Protocol Buffer", "bytes": "58995" }, { "name": "Python", "bytes": "5517835" }, { "name": "Ruby", "bytes": "4483" }, { "name": "Shell", "bytes": "956773" }, { "name": "Smarty", "bytes": "37892" }, { "name": "TeX", "bytes": "4183594" }, { "name": "Visual Basic", "bytes": "22546" }, { "name": "XSLT", "bytes": "332312" } ], "symlink_target": "" }
import Ember from 'ember'; import {purecloudEnvironmentTld} from '../utils/purecloud-environment'; export default Ember.Route.extend({ purecloud: Ember.inject.service(), analyticsService: Ember.inject.service(), init(){ let that = this; function receiveMessage(event) { if (event.origin !== "null" && event.origin !== window.location.origin) { //return; } if(typeof(event.data) === 'object'){ return; } let data = JSON.parse(event.data); if(data.action === 'anaytics'){ that.get("analyticsService").logExporerExecution(data.httpMethod, data.url); } } window.addEventListener("message", receiveMessage, false); }, model(){ let search = window.location.search; if(window.location.hash.indexOf("share")>0){ search = "?" + window.location.hash.substring(window.location.hash.indexOf("share")); }else if(window.location.hash.indexOf("filter")>0){ search = "?" + window.location.hash.substring(window.location.hash.indexOf("filter")); } let purecloudEnvironment = purecloudEnvironmentTld(); let swaggerUrl = `https://api.${purecloudEnvironment}/api/v2/docs/swagger`; swaggerUrl = `/swagger-schema/publicapi-v2-latest.json`; let swagger = `openApiUrl=${swaggerUrl}&host=api.${purecloudEnvironment}&shareUrl=${window.location.origin}` + encodeURIComponent('/developer-tools/#/api-explorer?'); if(search == null || search.length === 0){ search = "?"+swagger; }else{ search += "&" + swagger; } let openApiExplorerUrl = `https://developer.${purecloudEnvironment}/openapi-explorer/index.html`; if(purecloudEnvironment === 'ininsca.com'){ //need to special case here openApiExplorerUrl = `https://apps.${purecloudEnvironment}/openapi-explorer/`; } //openApiExplorerUrl = 'http://localhost:8081/'; return `${openApiExplorerUrl}${search}#token_type=bearer&access_token=` + this.get("purecloud").get("session").options.token; } });
{ "content_hash": "8cee33688c203655cf2ddd7a502906c9", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 174, "avg_line_length": 35.36507936507937, "alnum_prop": 0.5987432675044884, "repo_name": "jbfrederick/developer-tools", "id": "f3d505c56256f75752b68326452dbabbf89da35a", "size": "2228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/routes/api-explorer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "75980" }, { "name": "HTML", "bytes": "70439" }, { "name": "JavaScript", "bytes": "129331" } ], "symlink_target": "" }
let num = 103.941345 console.log(num) console.log(num.toFixed(2)) console.log(num.toExponential(5)) console.log(num.toPrecision(5)) console.log(Math.round(num)) console.log(Math.floor(num)) console.log(Math.ceil(num)) let min = 10 let max = 20 //Math.random return from 0-1 let randomNumber = Math.floor(Math.random() * (max - min + 1 )) + min let makeGuess = function(guess){ let min = 1 let max = 5 let randomNumber = Math.floor(Math.random() * (max - min + 1 )) + min return guess === randomNumber } console.log(randomNumber) // 10-20 console.log(makeGuess(5)) // 10-20
{ "content_hash": "37d862a7c7bfdbaeb169f1b06d1e9752", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 73, "avg_line_length": 22.884615384615383, "alnum_prop": 0.6789915966386555, "repo_name": "koitoer/mean", "id": "5af92ff8bdda4732a8d8d0e46bbbe07cfbd483ea", "size": "595", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javascript/basics/objects/object7-numbers.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "142" }, { "name": "HTML", "bytes": "112086" }, { "name": "JavaScript", "bytes": "1680046" } ], "symlink_target": "" }
<header> <nav class="navbar nav"> <div class="container-fluid"> <div class="title"><h1>ZA.LEYBA</h1></div> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="ptitle">ZA.LEYBA</div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav"> <li class="item"><a href="../index.php">about</a></li> <li class="item"><a href="../work/index.php">work</a></li> <li class="item"><a href="contact/index.php">contact</a></li> <li class="item"><a href="../gallery/index.php">gallery</a></li> <li class="item"> <a class="iglogo" href="https://www.instagram.com/mtvzach/"></a> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </header>
{ "content_hash": "590e1d8f4f2c13954ada4a42030afd7e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 136, "avg_line_length": 34.03030303030303, "alnum_prop": 0.6046304541406946, "repo_name": "zleyba/zaleyba", "id": "42473164d63b3c8fce2c133415b11b7ea1f321f5", "size": "1123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public_html/include-header.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "133" }, { "name": "CSS", "bytes": "12592" }, { "name": "JavaScript", "bytes": "37045" }, { "name": "PHP", "bytes": "25715" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Authors: * Dbrant * Eleassar * Franga2000 * HairyFotr * MuratTheTurkish * Pickle12 * P̲̳l̳eo * SHaran (WMF) --> <resources> <string name="app_name_prod">Wikipedija</string> <string name="app_name_beta">Wikipedija beta</string> <string name="app_name_alpha">Wikipedija alfa</string> <string name="wikimedia">Wikimedia</string> <string name="nav_item_back">Nazaj</string> <string name="page_tabs_back">Nazaj</string> <string name="nav_item_forward">Naprej</string> <string name="search_hint">Išči v Wikipediji</string> <string name="search_hint_voice_search">Iskanje z glasovnim vnosom</string> <string name="search_hint_search_languages">Poiščite jezik</string> <string name="filter_hint_filter_my_lists_and_articles">Filtriraj moje sezname</string> <string name="nav_item_suggested_edits">Urejanja</string> <string name="nav_item_more">Več</string> <string name="nav_item_search">Išči</string> <string name="error_network_error">Ni se mogoče povezati z internetom.</string> <string name="page_error_retry">Poskusi znova</string> <string name="card_offline_error_retry">Poskusi znova</string> <string name="storage_access_error_retry">Poskusi znova</string> <string name="article_load_error_retry">Poskusi znova</string> <string name="offline_load_error_retry">Poskusi znova</string> <string name="page_error_back_to_main">Pojdi nazaj</string> <string name="error_back">Pojdi nazaj</string> <string name="error_next">Naprej</string> <string name="menu_clear_all_history">Izbriši zgodovino</string> <string name="history_item_deleted">Članek %s izbrisan iz zgodovine</string> <string name="history_items_deleted">%d člankov izbrisanih iz zgodovine</string> <string name="history_item_delete_undo">Razveljavi</string> <string name="notification_archive_undo">Razveljavi</string> <string name="app_settings">Nastavitve aplikacije</string> <string name="search_tab_tooltip">Za neposredni vpis iskalnega izraza še enkrat tapnite ikono.</string> <string name="history_list_title">Zgodovina</string> <string name="image_content_description">Slika: %s</string> <string name="page_content_description">Stran: %s</string> <string name="wikimedia_commons">Wikimedijina zbirka</string> <string name="wikidata">Wikipodatki</string> <string name="dialog_title_clear_history">Izbriši zgodovino brskanja</string> <string name="dialog_message_clear_history">To bo izbrisalo vso zgodovino brskanja in zaprlo vse trenutno odprte zavihke. Ali to res želite storiti?</string> <string name="dialog_message_clear_history_yes">Da</string> <string name="dialog_message_clear_history_no">Ne</string> <string name="share_via">Deli z</string> <string name="image_share_via">Deli z</string> <string name="search_redirect_from">Preusmerjeno iz %s</string> <string name="page_edit_history_activity_title">Zgodovina redakcij: %s</string> <string name="page_edit_history_minor_edit">&lt;b&gt;m&lt;/b&gt; %s</string> <string name="page_edit_history_comment_placeholder">Prazen povzetek urejanja</string> <string name="page_edit_history_search_or_filter_edits_hint">Preišči ali filtriraj urejanja</string> <string name="page_edit_history_filter_by">Filtriraj po</string> <string name="page_edit_history_filter_by_all">Vseh urejanjih (%s)</string> <string name="page_edit_history_filter_by_user">Urejanjih uporabnikov (%s)</string> <string name="page_edit_history_filter_by_anon">Anonimnih urejanjih (%s)</string> <string name="page_edit_history_filter_by_bot">Urejanjih botov (%s)</string> <string name="page_edit_history_metrics_content_description">Metrike od %1$s do %2$s</string> <plurals name="page_edit_history_article_edits_since_year"> <item quantity="one">%1$d urejanje od %2$s </item> <item quantity="two">%1$d urejanji od %2$s </item> <item quantity="few">%1$d urejanja od %2$s </item> <item quantity="other">%1$d urejanj od %2$s</item> </plurals> <plurals name="edits_since_year_per_wiki"> <item quantity="one">%1$d urejanje od %2$s (%3$s)</item> <item quantity="two">%1$d urejanji od %2$s (%3$s)</item> <item quantity="few">%1$d urejanja od %2$s (%3$s)</item> <item quantity="other">%1$d urejanj od %2$s (%3$s)</item> </plurals> <string name="page_edit_history_empty_search_message">Za prikaz več urejanj poskusite spremeniti &lt;a href=\"#\"&gt;filtre&lt;/a&gt;</string> <string name="menu_page_show_tabs">Pokaži zavihke</string> <string name="menu_page_other_languages">Spremeni jezik</string> <string name="menu_page_find_in_page">Poišči na strani</string> <string name="menu_page_add_to_watchlist">Dodaj na spisek nadzorov</string> <string name="menu_page_watch">Opazuj</string> <string name="menu_page_unwatch">Odopazuj</string> <string name="menu_page_view_talk">Ogled pogovorne strani</string> <string name="menu_page_talk_page">Pogovorna stran</string> <string name="menu_page_view_edit_history">Ogled zgodovine urejanja</string> <string name="menu_page_edit_history">Zgodovina urejanja</string> <string name="menu_page_remove_from_watchlist">Odstrani s spiska nadzorov</string> <string name="menu_page_watched">Opazovano</string> <string name="edit_section_find_in_page">Poišči na strani</string> <string name="menu_page_font_and_theme">Pisava in tema</string> <string name="menu_page_add_to_list">Dodaj na bralni seznam</string> <string name="menu_page_add_to_default_list">Shrani</string> <string name="feed_card_add_to_list">Dodaj na bralni seznam</string> <string name="feed_card_add_to_default_list">Shrani</string> <string name="menu_page_share">Deli povezavo</string> <string name="menu_article_share">Deli članek</string> <string name="menu_page_article_share">Deli</string> <string name="menu_page_open_a_new_tab">Odpri na novem zavihku</string> <string name="menu_page_new_tab">Nov zavihek</string> <string name="menu_page_reading_lists">Bralni seznami</string> <string name="menu_page_recently_viewed">Nedavno pregledano</string> <string name="menu_page_archive">Arhiv</string> <string name="menu_long_press_open_page">Odpri</string> <string name="menu_long_press_open_in_new_tab">Odpri na novem zavihku</string> <string name="menu_long_press_copy_page">Kopiraj naslov povezave</string> <string name="menu_text_select_define">Opredeli</string> <string name="on_this_day_page_share">Deli</string> <string name="reading_list_page_share">Deli</string> <string name="menu_text_select_edit_here">Uredi tukaj</string> <string name="menu_edit_article">Uredi članek</string> <string name="last_updated_text">Zadnja posodobitev: %s</string> <string name="talk_page_link_text">Ogled pogovorne strani</string> <string name="edit_history_link_text">Ogled zgodovine urejanja</string> <string name="map_view_link_text">Prikaži na karti</string> <string name="other_languages_indication_text">Preberite v drugem jeziku</string> <string name="language_count_link_text">Na voljo v %d drugih jezikih</string> <string name="content_license_cc_by_sa">CC BY-SA 3.0</string> <string name="edit_save_action_license_logged_in">Z objavo izražate strinjanje s &lt;a href=\"%1$s\"&gt;Pogoji uporabe&lt;/a&gt; in svoje prispevke nepreklicno objavljate pod licenco &lt;a href=\"%2$s\"&gt;CC BY-SA 3.0&lt;/a&gt;.</string> <string name="edit_save_action_license_anon">Z objavo se strinjate s &lt;a href=\"%1$s\"&gt;Pogoji uporabe&lt;/a&gt; in svoje prispevke nepreklicno objavljate pod licenco &lt;a href=\"%2$s/\"&gt;CC BY-SA 3.0&lt;/a&gt;. Urejanja bodo pripisana IP-naslovu vaše naprave. Če se boste &lt;a href=\"https://#login\"&gt;prijavili&lt;/a&gt;, boste imeli več zasebnosti.</string> <string name="edit_anon_warning">Urejanja bodo pripisana IP-naslovu vaše naprave. Če se &lt;a href=\"https://#login\"&gt;prijavite&lt;/a&gt;, boste imeli več zasebnosti.</string> <string name="preference_title_language">Jeziki Wikipedije</string> <string name="langlinks_filter_hint">Iskanje</string> <string name="langlinks_empty">Ta stran ni na voljo v drugih jezikih.</string> <string name="langlinks_no_match">Najden ni bil noben jezik</string> <string name="langlinks_activity_title">Drugi jeziki</string> <string name="langlinks_your_wikipedia_languages">Wikipedija v vaših jezikih</string> <string name="menu_save_changes">Objavi spremembe</string> <string name="edit_saved_successfully">Sprememba objavljena!</string> <string name="dialog_message_edit_failed">Urejanje neuspešno!</string> <string name="dialog_message_edit_failed_retry">Poskusi znova</string> <string name="dialog_message_edit_failed_cancel">Prekliči</string> <string name="dialog_message_leaving_edit">Vaše spremembe še niso bile shranjene. Res želite zapustiti to stran?</string> <string name="dialog_message_leaving_edit_leave">Zapusti</string> <string name="dialog_message_leaving_edit_stay">Ostani</string> <string name="menu_show_toc">Kazalo vsebine</string> <string name="search_no_results_found">Ni najdenih zadetkov</string> <string name="search_reading_list_no_results">V »%s« ni najdenih zadetkov</string> <string name="search_reading_lists_no_results">V seznamih branja ni ničesar</string> <string name="search_history_no_results">V zgodovini ni bilo mogoče najti ničesar</string> <string name="edit_section_captcha_message">Za pomoč pri zaščiti pred smetjem vas prosimo, da vpišete spodaj prikazane besede</string> <string name="edit_section_captcha_request_an_account_message">Ali ne morete videti slike? &lt;a href=\"https://en.wikipedia.org/wiki/Wikipedia:Request_an_account\"&gt;Zahtevajte račun&lt;/a&gt;</string> <string name="edit_section_captcha_hint">Ponovite zgornje besede</string> <string name="title_captcha">Vnesite CAPTCHA</string> <string name="edit_section_captcha_reload">Tapnite CAPTCHA, da se znova naloži</string> <string name="nav_item_login">Prijava v Wikipedijo</string> <string name="login_username_hint">Uporabniško ime</string> <string name="login_password_hint">Geslo</string> <string name="account_creation_password_hint">Geslo</string> <string name="login_2fa_hint">Koda za dvofaktorsko avtentikacijo</string> <string name="login_2fa_other_workflow_error_msg">Potrebna je dvofaktorska avtentikacija! Vrnite se na glavno dejavnost in se prijavite s svojim žetonom 2FA, nato poskusite znova.</string> <string name="onboarding_card_login">Prijava</string> <string name="page_editing_login">Prijava</string> <string name="reading_lists_sync_login">Prijava</string> <string name="create_account_login">Prijava</string> <string name="menu_login">Prijava</string> <string name="login_activity_title">Prijava</string> <string name="login_in_progress_dialog_message">Prijavljanje ...</string> <string name="login_success_toast">Prijavljeni ste!</string> <string name="reset_password_title">Nastavite svoje geslo</string> <string name="reset_password_description">Prijavili ste se z začasnim geslom. Za dokončanje prijave tu nastavite novo geslo.</string> <string name="reset_password_hint">Novo geslo</string> <string name="reset_password_button">Shrani in prijavi me</string> <string name="preference_title_logout">Odjava</string> <string name="toast_logout_complete">Odjavljeni</string> <string name="logout_prompt">S tem se boste odjavili v vseh napravah, v katerih ste trenutno prijavili. Ali želite nadaljevati?</string> <string name="logout_dialog_cancel_button_text">Prekliči</string> <string name="logged_out_in_background_title">Odjavljeni</string> <string name="logged_out_in_background_dialog">Odjavili ste se iz Wikipedije. Ali se želite znova prijaviti?</string> <string name="logged_out_in_background_login">Prijava</string> <string name="logged_out_in_background_cancel">Prekliči</string> <string name="history_empty_title">Ni nedavno ogledanih člankov</string> <string name="history_empty_message">Tu lahko sledite, kaj ste prebrali.</string> <string name="history_offline_articles_toast">Nekateri članki v zgodovini brez povezave morda ne bodo vidni.</string> <string name="search_empty_message">Iščite in berite v prosti enciklopediji v svojem jeziku</string> <string name="search_empty_message_multilingual_upgrade">Iščite v Wikipediji v več jezikih</string> <string name="delete_selected_items">Izbrišite izbrane predmete</string> <string name="wp_stylized">&lt;big&gt;W&lt;/big&gt;IKIPEDIJ&lt;big&gt;A&lt;/big&gt;</string> <string name="create_account_username_hint">Uporabniško ime</string> <string name="login_dont_have_account">Še nimate uporabniškega računa?</string> <string name="login_join_wikipedia">Pridružite se Wikipediji</string> <string name="login_forgot_password">Ste pozabili geslo?</string> <string name="create_account_already_have">Že imate račun?</string> <string name="create_account_activity_title">Ustvarite račun</string> <string name="dialog_create_account_checking_progress">Preverjanje</string> <string name="create_account_email_hint">E-poštni naslov (izbirno)</string> <string name="create_account_password_repeat_hint">Ponovite geslo</string> <string name="create_account_password_is_username">Geslo ne sme biti enako uporabniškemu imenu</string> <string name="create_account_passwords_mismatch_error">Gesli se ne ujemata</string> <string name="create_account_email_error">Neveljaven e-poštni naslov</string> <string name="create_account_username_error">Neveljaven znak v uporabniškem imenu</string> <string name="create_account_password_error">Geslo mora vsebovati vsaj 8 znakov</string> <string name="create_account_generic_error">Računa ni bilo mogoče ustvariti</string> <string name="create_account_next">Naprej</string> <string name="email_recommendation_dialog_title">Ustvarim račun brez e-poštnega naslova?</string> <string name="email_recommendation_dialog_message">Čeprav e-poštni naslov ni obvezen, je &lt;b&gt;močno priporočljiv&lt;/b&gt;, saj je potreben za obnovo računa, če izgubite geslo.</string> <string name="email_recommendation_message">Priporočeno, saj se e-poštni naslov uporablja za obnovitev dostopa do računa.</string> <string name="email_recommendation_dialog_create_without_email_action">Nadaljuj brez e-poštnega naslova</string> <string name="email_recommendation_dialog_create_with_email_action">Dodajte e-poštni naslov</string> <string name="create_account_button">Ustvari račun</string> <string name="create_account_name_unavailable">Uporabniško ime »%s« ni na voljo. Prosimo, izberite drugo ime.</string> <string name="create_account_ip_block_message">Žal je ustvarjanje novih računov z vašega IP-naslova trenutno preprečeno.</string> <string name="create_account_ip_block_help_url">https://en.wikipedia.org/wiki/Help:I_have_been_blocked</string> <string name="create_account_ip_block_details">Podrobnosti</string> <string name="preferences_general_heading">Splošno</string> <string name="preferences_account_heading">Račun</string> <string name="wikipedia_app_faq">Pogosta vprašanja o aplikaciji Wikipedija</string> <string name="send_feedback">Sporočite svoje mnenje</string> <string name="create_account_account_created_toast">Račun ustvarjen!</string> <string name="preferences_heading_syncing">Sinhronizacija</string> <string name="preferences_heading_data_usage">Uporaba podatkov</string> <string name="preferences_heading_experimental">Preizkusno</string> <string name="preference_title_sync_reading_lists_from_account">Sinhronizacija bralnih seznamov</string> <string name="preference_title_download_reading_list_articles">Prenesi članke na bralnem seznamu</string> <string name="preference_summary_sync_reading_lists">Sinhroniziraj bralne sezname med različnimi napravami tako, da se shranijo v mojem računu v Wikipediji.</string> <string name="preference_summary_sync_reading_lists_from_account">Sinhroniziraj bralne sezname med različnimi napravami tako, da se shranijo v računu »%s« v Wikipediji.</string> <string name="preference_dialog_of_turning_off_reading_list_sync_title">Odstranim sinhronizirane bralne sezname iz »%s«?</string> <string name="preference_dialog_of_turning_off_reading_list_sync_text">S tem boste iz shranjevanja v oblaku v celoti izbrisali vse predhodno sinhronizirane bralne sezame. Odstranim z vašega računa »%s« vse sinhronizirane sezname?</string> <string name="preferences_privacy_settings_heading">Zasebnost</string> <string name="preference_title_eventlogging_opt_in">Pošiljaj poročila o uporabi</string> <string name="preference_summary_eventlogging_opt_in">Omogočite Wikimedii zbiranje podatkov o tem, kako uporabljate aplikacijo, da bo ta postala še boljša.</string> <string name="preference_title_auto_upload_crash_reports">Pošiljaj poročila o sesutjih</string> <string name="preference_summary_auto_upload_crash_reports">Omogočite aplikaciji samodejno pošiljanje poročil o sesutjih tretjemu ponudniku storitve, da bomo lahko pregledali dogodke ter hitreje in lažje odpravili hrošče.</string> <string name="editing_error_spamblacklist">Zaznane so bile povezave na blokirane domene (%s). Prosimo, odstranite jih in poskusite znova.</string> <string name="history_filter_list_hint">Filtriraj zgodovino</string> <string name="error_can_not_process_link">Te povezave ni mogoče prikazati</string> <string name="page_protected_autoconfirmed">Ta stran je delno zaščitena.</string> <string name="page_protected_sysop">Ta stran je zaščitena v celoti.</string> <string name="page_protected_other">Ta stran je zaščitena na naslednjih ravneh: %s</string> <string name="page_protected_can_not_edit">Vaš račun trenutno žal nima zadostnih pravic za urejanje te strani.</string> <string name="page_protected_can_not_edit_anon">Žal te strani trenutno ni mogoče urejati anonimno.</string> <string name="page_protected_can_not_edit_title">Stran je zaščitena</string> <string name="page_watchlist_overflow_menu_onboarding_tooltip_title">Dodaj na spisek nadzorov</string> <string name="page_watchlist_overflow_menu_onboarding_tooltip_text">Sledite spremembe člankov, ki vas zanimajo. Tapnite prelivni meni in izberite &lt;b&gt;Dodaj na spisek nadzorov&lt;/b&gt;, da si ogledate spremembe članka.</string> <string name="settings_item_preferences">Nastavitve</string> <string name="settings_activity_title">Nastavitve</string> <string name="about_description">O aplikaciji Wikipedija</string> <string name="privacy_policy_description">Pravilnik o zasebnosti</string> <string name="terms_of_use_description">Pogoji uporabe</string> <string name="about_wikipedia_url">https://sl.wikipedia.org/wiki/Wikipedija:O_Wikipediji</string> <string name="privacy_policy_url">https://foundation.wikimedia.org/wiki/Privacy_policy</string> <string name="offline_reading_and_data_url">https://www.mediawiki.org/wiki/Wikimedia_Apps/Android_FAQ#Offline_reading_and_data</string> <string name="android_app_faq_url">https://www.mediawiki.org/wiki/Wikimedia_Apps/Android_FAQ</string> <string name="terms_of_use_url">https://foundation.wikimedia.org/wiki/Terms_of_Use</string> <string name="android_app_request_an_account_url">https://en.wikipedia.org/wiki/Wikipedia:Request_an_account</string> <string name="cc_by_sa_3_url">https://creativecommons.org/licenses/by-sa/3.0/deed.sl</string> <string name="cc_0_url">https://creativecommons.org/publicdomain/zero/1.0/deed.sl</string> <string name="android_app_edit_help_url">https://m.mediawiki.org/wiki/Wikimedia_Apps/Suggested_edits</string> <string name="suggested_edits_image_tags_help_url">https://www.mediawiki.org/wiki/Wikimedia_Apps/Suggested_edits#Image_tags</string> <string name="about_libraries_heading">Uporabljene knjižnice</string> <string name="about_contributors_heading">Prispevajoči</string> <string name="about_contributors">&lt;a href=\"https://www.mediawiki.org/wiki/Wikimedia_Apps/Team/Android\"&gt;Stran ekipe&lt;/a&gt;</string> <string name="about_translators_heading">Prevajalci</string> <string name="about_translators_translatewiki">Aplikacijo so prevedli prostovoljci projekta &lt;a href=\"https://translatewiki.net\"&gt;translatewiki.net&lt;/a&gt;.</string> <string name="about_app_license_heading">Licenca</string> <string name="about_app_license">Izvorna koda je na voljo v repozitorijih &lt;a href=\"https://gerrit.wikimedia.org/r/#/admin/projects/apps/android/wikipedia\"&gt;Gerrit&lt;/a&gt; in &lt;a href=\"https://github.com/wikimedia/apps-android-wikipedia\"&gt;GitHub&lt;/a&gt; pod licenco &lt;a href=\"https://www.apache.org/licenses/LICENSE-2.0\"&gt;Apache 2.0 License&lt;/a&gt;. Če ni navedeno drugače, je vsebina na razpolago pod licenco &lt;a href=\"https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\"&gt;Creative Commons Pripis avtorja-Deljenje pod enakimi pogoji&lt;/a&gt;.</string> <string name="about_wmf">Izdelek &lt;a href=\"https://wikimediafoundation.org/\"&gt;Fundacije Wikimedia&lt;/a&gt;</string> <string name="about_activity_title">O projektu</string> <string name="edit_abandon_confirm">Stran je bila spremenjena. Ali jo res želite zapustiti, ne da bi shranili svoje spremembe?</string> <string name="edit_abandon_confirm_yes">Da</string> <string name="edit_abandon_confirm_no">Ne</string> <string name="user_blocked_from_editing_title">Blokiran</string> <string name="user_logged_in_blocked_from_editing">Urejanje tega vikija je za vaš račun preprečeno.</string> <string name="user_anon_blocked_from_editing">Urejanje je za vaš IP-naslov preprečeno.</string> <string name="edit_how_page_improved">Kako ste izboljšali stran?</string> <string name="edit_next">Naprej</string> <string name="edit_done">Objavi</string> <string name="edit_preview">Predogled</string> <string name="edit_undo">Razveljavi</string> <string name="edit_redo">Uveljavi</string> <string name="edit_rollback">Vrni</string> <plurals name="edit_diff_bytes"> <item quantity="one">%s zlog</item> <item quantity="two">%s zloga</item> <item quantity="few">%s zlogov</item> <item quantity="other">%s zlogov</item> </plurals> <string name="edit_zoom_in">Povečaj</string> <string name="edit_zoom_out">Pomanjšaj</string> <string name="edit_summary_tag_typo">Popravek tipkarske napake</string> <string name="edit_summary_tag_grammar">Popravek slovnice</string> <string name="edit_summary_tag_links">Dodane povezave</string> <string name="edit_summary_tag_other">Drugo</string> <string name="edit_summary_tag_other_hint">Drug način, s katerim ste izboljšali stran</string> <string name="edit_conflict_title">Navzkrižje urejanj</string> <string name="edit_conflict_message">Stran je že spremenil drug uporabnik, čigar urejanje je v navzkrižju z vašim urejanjem. Skopirajte svoja urejanja, pojdite nazaj in osvežite stran, nato pa poskusite znova.</string> <string name="edit_notices">Obvestilo o urejanju</string> <string name="edit_notices_please_read">Prosimo, preberite pred urejanjem</string> <string name="edit_notices_show_auto">Samodejno prikazuj obvestila o urejanju</string> <string name="edit_notices_tooltip">Za ogled obvestil o urejanju tega članka tapnite ta gumb.</string> <string name="find_next">Najdi naslednje</string> <string name="find_previous">Najdi prejšnje</string> <string name="find_first_occurence">To je prva pojavitev</string> <string name="find_last_occurence">To je zadnja pojavitev</string> <string name="article_opened_in_background_tab">Članek je odprt na zavihku v ozadju.</string> <string name="abusefilter_title_warn">To urejanje se zdi nekonstruktivno. Ali ga res želite objaviti?</string> <string name="abusefilter_title_disallow">Tega urejanja ne morete objaviti. Pojdite nazaj in ga spremenite.</string> <string name="abusefilter_text_warn">To urejanje je samodejni filter prepoznal kot morda nekonstruktivno. Vsebuje lahko eno ali več od naslednjega:&lt;br /&gt;&lt;br /&gt;– besedilo s samimi velikimi črkami;&lt;br /&gt;– izpraznitev članka ali smetje;&lt;br /&gt;– nepredmetne zunanje povezave ali slike;&lt;br /&gt;– ponavljajoči se znaki.</string> <string name="abusefilter_text_disallow">Samodejni filter je to urejanje zaznal kot morda nekonstruktivno ali morebitni vandalizem.&lt;br /&gt;&lt;br /&gt;Wikipedija je enciklopedija, zato spada vanjo samo nepristranska in pomembna vsebina.</string> <string name="page_similar_titles">Podobne strani</string> <string name="search_did_you_mean">Ali ste mislili \"%s\"?</string> <string name="search_recent_header">Zadnja iskanja</string> <string name="search_results_count_zero">Ni zadetkov</string> <plurals name="search_results_count"> <item quantity="one">1 zadetek</item> <item quantity="two">%d zadetka</item> <item quantity="few">%d zadetki</item> <item quantity="other">%d zadetkov</item> </plurals> <string name="button_clear_all_recent_searches">Počisti zadnja iskanja</string> <string name="clear_recent_searches_confirm">Ali res želite počistiti svojo zgodovino iskanja?</string> <string name="clear_recent_searches_confirm_yes">Da</string> <string name="clear_recent_searches_confirm_no">Ne</string> <string name="error_browser_not_found">Spletne strani ni mogoče odpreti (na voljo ni noben brskalnik).</string> <string name="table_infobox">Podatki na hitro</string> <string name="table_other">Več informacij</string> <string name="table_close">Zapri</string> <string name="widget_name_featured_page">Izbrana stran Wikipedije</string> <string name="widget_title_featured_page">Današnji izbrani članek:</string> <string name="widget_name_search">Iskanje v Wikipediji</string> <string name="wiktionary_no_definitions_found">Najdena ni bila nobena opredelitev.</string> <string name="alpha_update_notification_title">Nova alfa posodobitev</string> <string name="alpha_update_notification_text">Tapni za prenos</string> <string name="dialog_close_description">Zapri</string> <string name="preference_title_show_images">Prikazuj slike</string> <string name="preference_summary_show_images">Omogočite ali onemogočite nalaganje slik na straneh. Če je vaša internetna povezava počasna ali imate omejen prenos podatkov, to možnost odkljukajte.</string> <string name="preference_title_download_only_over_wifi">Prenašaj samo prek Wi-Fi-ja</string> <string name="dialog_title_download_only_over_wifi">Potrdim prenos z mobilnimi podatki?</string> <string name="dialog_text_download_only_over_wifi">V nastavitvah ste vklopili možnost »Prenašaj samo prek Wi-Fi-ja«. Ali želite omogočiti mobilni prenos podatkov samo za ta prenos?</string> <string name="dialog_title_download_only_over_wifi_allow">Dovoli</string> <string name="read_more_section">Preberi še kaj</string> <string name="about_article_section">O članku</string> <string name="menu_gallery_visit_image_page">Pojdi na stran s sliko</string> <string name="gallery_error_draw_failed">Slike ni mogoče narisati.</string> <string name="license_title">Licenca za %s</string> <string name="gallery_menu_share">Deli</string> <string name="gallery_share_error">Slike ni mogoče deliti: %s</string> <string name="gallery_save_progress">Prenašam datoteko ...</string> <string name="gallery_save_success">Datoteka shranjena.</string> <string name="gallery_error_video_failed">Videa ni mogoče predvajati.</string> <string name="gallery_save_image_write_permission_rationale">Za shranjevanje slik je potrebno dovoljenje za shranjevanje v vaši napravi.</string> <string name="gallery_edit_button_content_description">Uredi napis k sliki</string> <string name="gallery_add_image_caption_button">Dodaj napis k sliki</string> <string name="gallery_add_image_caption_in_language_button">Dodaj napis k sliki (%s)</string> <string name="err_cannot_save_file">Datoteke ni mogoče shraniti</string> <string name="expand_refs">Tapni za razširitev</string> <string name="cc_logo">Licenca Creative Commons</string> <string name="captcha_image">Slika CAPTCHA</string> <string name="gallery_fair_use_license">Poštena uporaba</string> <string name="gallery_uploader_unknown">Neznani naložnik</string> <string name="gallery_not_available_offline_snackbar">Prikaz galerije ni na voljo brez povezave.</string> <string name="gallery_not_available_offline_snackbar_dismiss">Opusti</string> <string name="menu_new_tab">Nov zavihek</string> <string name="menu_close_all_tabs">Zapri vse zavihke</string> <string name="close_all_tabs_confirm">Ali res želite zapreti vse zavihke?</string> <string name="close_all_tabs_confirm_yes">Da</string> <string name="close_all_tabs_confirm_no">Ne</string> <string name="button_close_tab">Zapri zavihek</string> <string name="unnamed_tab_closed">Zavihek zaprt.</string> <string name="tab_item_closed">%s: zaprto.</string> <string name="all_tab_items_closed">Vsi zavihki zaprti.</string> <string name="tool_tip_bookmark_icon_title">Dodaj na bralni seznam</string> <string name="tool_tip_bookmark_icon_text">Da shranite članek na bralni seznam, tapnite ikono za zaznamek.</string> <string name="page_view_in_browser">Prikaži stran v brskalniku</string> <string name="tool_tip_toc_title">Hitri dostop do vsebinskega kazala</string> <string name="tool_tip_toc_text">Zdaj lahko podrsate levo, da odprete vsebinsko kazalo, ali tapnete drsnik in ga povlečete, da hitro preidete na drug razdelek članka.</string> <string name="tool_tip_lang_button">Zdaj lahko Wikipedijo v aplikaciji berete in raziskujete v več jezikih</string> <string name="error_response_malformed">Odgovor strežnika ni bil ustrezno oblikovan.</string> <string name="error_unknown">Prišlo je do neznane napake.</string> <string name="format_error_server_message">Sporočilo: »%s«</string> <string name="address_copied">Naslov kopiran v odložišče.</string> <string name="text_copied">Besedilo kopirano v odložišče.</string> <string name="button_continue_to_article">Preberi članek</string> <string name="button_continue_to_talk_page">Odpri pogovorno stran</string> <string name="button_continue_to_disambiguation">Oglej si podobne strani</string> <string name="link_preview_disambiguation_description">Ta naslov se nanaša na več kot eno stran:</string> <string name="button_add_to_reading_list">Dodaj na bralni seznam</string> <string name="page_offline_notice_cannot_load_while_offline">Članka brez povezave ni mogoče naložiti.</string> <string name="page_offline_notice_add_to_reading_list">Namig: Dodajte članek na bralni seznam in se bo prenesel, ko boste spet povezani.</string> <string name="page_offline_notice_last_date">Berete nepovezano različico tega članka; čas shranitve: %s.</string> <string name="button_get_directions">Pridobite navodila za pot</string> <string name="error_no_maps_app">Najti ni mogoče nobene navigacijske aplikacije.</string> <string name="preference_title_customize_explore_feed">Vir Raziskovanje</string> <string name="preference_title_show_link_previews">Prikazuj predogled povezav</string> <string name="preference_summary_customize_explore_feed">Prilagodite vir Raziskovanje</string> <string name="preference_summary_show_link_previews">Ob tapkanju povezav prikaži hiter predogled člankov.</string> <string name="preference_title_collapse_tables">Strni preglednice</string> <string name="preference_summary_collapse_tables">Samodejno strni preglednice v člankih, kot so infopolja, sklici in opombe.</string> <string name="nav_item_donate">Prispevajte sredstva</string> <string name="error_voice_search_not_available">Prepoznava glasu žal ni na voljo.</string> <string name="location_service_disabled">Lokacijske storitve so onemogočene.</string> <string name="enable_location_service">Omogoči</string> <string name="location_permissions_enable_prompt">Omogočite lokacijska dovoljenja, da si ogledate kraje v svoji bližini.</string> <string name="location_permissions_enable_action">Vklopi</string> <string name="error_webview_updating">Orodje WebView sistema Android se trenutno posodablja. Poskusite znova čez nekaj trenutkov.</string> <plurals name="multi_items_selected"> <item quantity="one">%d izbrana</item> <item quantity="two">%d izbrani</item> <item quantity="few">%d izbrane</item> <item quantity="other">%d izbranih</item> </plurals> <string name="multi_select_items_selected">%d izbranih</string> <string name="error_message_generic">Prišlo je do napake</string> <string name="view_link_preview_error_button_dismiss">Opusti</string> <string name="error_page_does_not_exist">Ta stran ne obstaja</string> <string name="error_user_page_does_not_exist">Wikipedija nima &lt;a href=\"%1$s \"&gt;uporabniške strani&lt;/a&gt; s točno tem imenom. Na splošno bi to stran moral ustvariti in urejati &lt;b&gt;%2$s&lt;/b&gt;. Če ste v dvomih, preverite, ali »%3$s« obstaja.</string> <string name="view_wiki_error_message_offline">Ni povezave z internetom</string> <string name="view_wiki_error_message_timeout">Z Wikipedijo se ni mogoče povezati. Preverite omrežno povezavo ali poskusite znova pozneje.</string> <string name="reference_title">Sklic %s</string> <string name="reference_list_title">Sklici</string> <string name="theme_chooser_dialog_image_dimming_switch_label">Zatemnitev slike (pri temni temi)</string> <string name="preference_title_prefer_offline_content">Prednost daj nepreneseni vsebini</string> <string name="preference_summary_prefer_offline_content">Da prihranite pri porabi podatkov, lahko namesto stalnega nalaganja zadnje različice članka nalagate članke, ki so na voljo preneseni.</string> <string name="theme_chooser_dialog_match_system_theme_switch_label">Usklajeno s sistemsko temo</string> <string name="page_footer_license_text">Vsebina je na voljo pod licenco $1, razen če je navedeno drugače.</string> <string name="empty_tab_title">Nov zavihek</string> <string name="menu_save_all_tabs">Shrani vse zavihke</string> <string name="error_blocked_title">Vaše uporabniško ime ali IP-naslov je bil(o) blokiran(o).</string> <string name="error_blocked_by">Blokiranje je vzpostavil/a &lt;a href=\"%2$s\"&gt;%1$s&lt;/a&gt;</string> <string name="error_blocked_reason">Navedeni razlog: %s</string> <string name="error_blocked_start">Začetek blokiranja: %s</string> <string name="error_blocked_expiry">Pretek blokiranja: %s</string> <string name="error_blocked_id">ID blokade: %s</string> <string name="error_blocked_footer">Za pogovor o blokiranju se lahko obrnete na &lt;a href=\"%2$s\"&gt;%1$s&lt;/a&gt; ali drugega &lt;a href=\"https://sl.wikipedia.org/wiki/Wikipedija:Administratorji\"&gt;administratorja&lt;/a&gt;.</string> <string name="theme_chooser_menu_item_short_tooltip">Prilagodite svojo orodno vrstico</string> <string name="error_blocked_footer_no_blocker">Za pogovor o blokiranju se lahko obrnete na &lt;a href=\"https://sl.wikipedia.org/wiki/Wikipedija:Administratorji\"&gt;administratorja&lt;/a&gt;.</string> <string name="crash_report_activity_title">Napaka aplikacije</string> <string name="crash_report_relaunch_or_quit">Žal je prišlo do napake aplikacije Wikipedija, zato je bila prekinjena.\n\nŽelite začeti znova ali aplikacijo zapreti?</string> <string name="crash_report_relaunch">Začni znova</string> <string name="crash_report_quit">Zapri</string> <string name="article_menu_bar_save_button">Shrani</string> <string name="article_menu_bar_language_button">Jezik</string> <string name="article_menu_bar_search_button">Išči</string> <string name="article_menu_bar_theme_button">Tema</string> <string name="article_menu_bar_contents_button">Vsebina</string> <string name="article_header_edit_hint">Uredi ...</string> <string name="article_header_edit_description">Uredi opis članka</string> <string name="article_header_edit_lead_section">Uredi uvod</string> <string name="color_theme_select">Tema</string> <string name="color_theme_light">Svetla</string> <string name="color_theme_dark">Temna</string> <string name="color_theme_black">Črna</string> <string name="color_theme_sepia">Sepija</string> <string name="color_theme_test_title">Vzorčno besedilo</string> <string name="color_theme_test_text">Povlecite drsnik, da spremenite velikost besedila pri branju člankov. Za nastavitev velikosti besedila v vsej aplikaciji spremenite sistemsko velikost besedila.</string> <string name="preference_title_app_theme">Tema aplikacije</string> <string name="preference_summary_color_theme">Preklopi na uporabo temne teme</string> <string name="text_size_increase">Povečaj velikost besedila</string> <string name="text_size_decrease">Zmanjšaj velikost besedila</string> <string name="text_size_percent_default">%s (privzeto)</string> <string name="text_style_title">Pisava</string> <string name="theme_category_reading">Branje</string> <string name="theme_category_editing">Urejanje</string> <string name="reading_focus_mode">Način za branje</string> <string name="reading_focus_mode_detail">Ob pomikanju skrije možnosti urejanja in orodno vrstico na dnu</string> <string name="editing_syntax_highlight_label">Označevanje skladnje</string> <string name="editing_line_numbers_label">Prikaži številke vrstic</string> <string name="editing_monospace_font_label">Uporabi pisavo monospace</string> <string name="editing_typing_suggestions">Prikaži predloge za tipkanje</string> <string name="nav_item_saved">Shranjeno</string> <string name="reading_list_save_to">Shrani na bralni seznam</string> <string name="reading_list_move_to">Prestavi na bralni seznam</string> <string name="reading_list_create_new">Ustvari nov seznam</string> <string name="reading_list_title_exists">Bralni seznam »%s« že obstaja.</string> <string name="reading_list_article_added_to_named">%1$s dodano na %2$s.</string> <string name="reading_list_article_added_to_default_list">Članek %s je shranjen. Ali ga želite dodati na seznam?</string> <string name="reading_list_article_moved_to_named">Članek %1$s je prestavljen na %2$s.</string> <string name="reading_list_article_already_exists_message">Vse je v redu! Seznam %1$s že vsebuje članek %2$s.</string> <string name="reading_list_articles_already_exist_message">Vse je v redu! %s že vsebuje vse članke.</string> <string name="reading_list_added_view_button">Prikaži seznam</string> <string name="reading_list_add_to_list_button">Dodaj na seznam</string> <plurals name="format_reading_list_statistical_summary"> <item quantity="one">1 članek, %2$.2f MB</item> <item quantity="two">%1$d članka, %2$.2f MB</item> <item quantity="few">%1$d članki, %2$.2f MB</item> <item quantity="other">%1$d člankov, %2$.2f MB</item> </plurals> <plurals name="format_reading_list_statistical_detail"> <item quantity="one">Brez povezave je na voljo %1$d od 1 članka, %3$.2f MB</item> <item quantity="two">Brez povezave je na voljo %1$d od 2 člankov, %3$.2f MB</item> <item quantity="few">Brez povezave je na voljo %1$d od %2$d člankov, %3$.2f MB</item> <item quantity="other">Brez povezave je na voljo %1$d od %2$d člankov, %3$.2f MB</item> </plurals> <string name="format_reading_list_statistical_summary_singular">1 članek, %1$.2f MB</string> <string name="format_reading_list_statistical_summary_plural">%1$d čl., %2$.2f MB</string> <string name="format_reading_list_statistical_detail_singular">Brez povezave je na voljo %1$d od 1 članka, %2$.2f MB</string> <string name="format_reading_list_statistical_detail_plural">Brez povezave je na voljo %1$d od %2$d člankov, %3$.2f MB</string> <string name="reading_list_sort">Razvrsti</string> <string name="reading_list_sort_ellipsis">Razvrsti po ...</string> <string name="reading_list_sort_by_name">Razvrsti po naslovu</string> <string name="reading_list_sort_by_name_desc">Razvrsti po naslovu (obratno)</string> <string name="reading_list_sort_by_recent">Razvrsti po datumu dodajanja (najnovejše)</string> <string name="reading_list_sort_by_recent_desc">Razvrsti po datumu dodajanja (najstarejše)</string> <string name="reading_list_sort_by_created">Razvrsti po datumu ustvaritve (najnovejše)</string> <string name="reading_list_sort_by_created_desc">Razvrsti po datumu ustvaritve (najstarejše)</string> <string name="reading_list_menu_delete">Izbriši seznam</string> <string name="reading_list_menu_rename">Uredi naslov/opis</string> <string name="reading_list_action_menu_remove_from_offline">Odstrani preneseno</string> <string name="reading_list_action_menu_save_for_offline">Prenesi</string> <string name="reading_list_action_menu_remove_all_from_offline">Odstrani vse nepreneseno</string> <string name="reading_list_action_menu_save_all_for_offline">Prenesi vse</string> <string name="reading_list_action_menu_add_to_another_list">Dodaj na drug seznam</string> <string name="reading_list_action_menu_move_to_another_list">Prestavi na drug seznam</string> <string name="reading_list_name_sample">Moj bralni seznam</string> <string name="reading_list_name_hint">Naslov seznama</string> <string name="reading_list_description_hint">Opis (izbirno)</string> <string name="reading_list_item_deleted">Članek %s je odstranjen s seznama.</string> <string name="reading_list_item_deleted_from_list">%1$s odstranjen s seznama %2$s</string> <plurals name="reading_list_articles_deleted"> <item quantity="one">%d članek odstranjen s seznama</item> <item quantity="two">%d članka odstranjena s seznama</item> <item quantity="few">%d članki odstranjeni s seznama</item> <item quantity="other">%d člankov odstranjenih s seznama</item> </plurals> <plurals name="reading_list_articles_deleted_from_list"> <item quantity="one">%d članek odstranjen s seznama %s</item> <item quantity="two">%d članka odstranjena s seznama %s</item> <item quantity="few">%d članki odstranjeni s seznama %s</item> <item quantity="other">%d člankov odstranjenih s seznama %s</item> </plurals> <string name="reading_list_items_deleted">%d člankov odstranjenih s seznama</string> <string name="reading_lists_item_deleted">%s odstranjen s seznamov</string> <string name="reading_list_item_delete_undo">Razveljavi</string> <string name="reading_list_deleted">Seznam %s izbrisan</string> <string name="saved_list_empty_title">Nimate še prenesenih strani</string> <string name="reading_lists_empty_message">Dodajte članke na seznam za poznejše branje, tudi ko ste brez povezave.</string> <string name="reading_list_empty">Na tem seznamu nimate člankov.</string> <string name="reading_list_article_offline">Na voljo brez povezave</string> <string name="reading_list_article_make_offline">Članek naj bo na voljo brez povezave</string> <string name="reading_list_add_to_other_list">Dodaj na drug bralni seznam</string> <string name="reading_list_move_to_other_list">Prestavi na drug bralni seznam</string> <string name="reading_list_move_from_to_other_list">Prestavi s %s na drug bralni seznam</string> <string name="reading_list_remove_from_list">Odstrani s seznama %s</string> <string name="reading_list_remove_from_lists">Odstrani z bralnih seznamov</string> <string name="reading_list_select_item">Izberi</string> <string name="reading_list_confirm_remove_article_from_offline">Odstrani preneseno</string> <string name="reading_list_confirm_remove_article_from_offline_title">Članek je na več seznamih</string> <string name="reading_list_confirm_remove_article_from_offline_message">%s ne bo več na voljo preneseno za noben bralni seznam:</string> <string name="reading_lists_sync_reminder_title">Vklopim sinhronizacijo bralnih seznamov?</string> <string name="reading_lists_sync_reminder_text">Članke, shranjene v bralne sezname, lahko zdaj sinhronizirate z računom v Wikipediji. &lt;a href=\"https://www.mediawiki.org/wiki/Wikimedia_Apps/Android_FAQ#Synced_reading_lists\"&gt;Več o tem&lt;/a&gt;</string> <string name="reading_lists_login_reminder_text_with_link">Bralne sezname lahko zdaj sinhronizirate med napravami. Prijavite se v svoj račun v Wikipediji in omogočite shranjevanje seznamov. &lt;a href=\"https://www.mediawiki.org/wiki/Wikimedia_Apps/Android_FAQ#Synced_reading_lists\"&gt;Več o tem&lt;/a&gt;</string> <string name="reading_lists_sync_reminder_action">Omogoči sinhroniziranje</string> <string name="reading_list_login_reminder_title">Sinhroniziraj bralne sezname</string> <string name="reading_lists_login_reminder_text">Bralne sezname lahko zdaj sinhronizirate med napravami. Prijavite se v svoj račun v Wikipediji in omogočite shranjevanje seznamov.</string> <string name="reading_lists_login_button">Prijavite se / pridružite se Wikipediji</string> <string name="reading_lists_ignore_button">Ne zdaj</string> <string name="reading_lists_confirm_remote_delete_yes">Da</string> <string name="reading_lists_confirm_remote_delete_no">Ne</string> <string name="reading_list_article_save_in_progress">Članek se prenaša in bo po končanem prenosu na voljo brez povezave.</string> <string name="reading_list_articles_added_to_named">%1$d člankov dodanih na %2$s</string> <string name="reading_list_articles_moved_to_named">%1$d člankov prestavljenih na %2$s</string> <string name="reading_list_delete_confirm">Ali res želite izbrisati %s?</string> <string name="reading_list_preference_login_to_enable_sync_dialog_title">Za možnost sinhronizacije se prijavite</string> <string name="reading_list_preference_login_to_enable_sync_dialog_text">Za shranjevanje bralnih seznamov na svoj račun se prijavite.</string> <string name="reading_list_preference_login_to_enable_sync_dialog_cancel">Prekliči</string> <string name="reading_list_preference_login_to_enable_sync_dialog_login">Prijava</string> <string name="reading_list_turned_sync_off_dialog_title">Sinhronizacija bralnih seznamov izklopljena</string> <string name="reading_list_turned_sync_off_dialog_text">Sinhronizacija bralnih seznamov je v vašem računu izklopljena; prijavljene naprave se več ne posodabljajo. Sinhronizacijo bralnih seznamov lahko vklopite v Nastavitvah.</string> <string name="reading_list_turned_sync_off_dialog_ok">V redu</string> <string name="reading_list_turned_sync_off_dialog_settings">Nastavitve</string> <string name="reading_list_prompt_turned_sync_on_dialog_title">Vklopim sinhronizacijo bralnih seznamov?</string> <string name="reading_list_prompt_turned_sync_on_dialog_text">Članke, shranjene na bralnih seznamih, lahko zdaj sinhronizirate s svojimi računom v Wikipediji. &lt;a href=\"#faq\"&gt;Več o tem&lt;/a&gt;</string> <string name="reading_list_prompt_turned_sync_on_dialog_do_not_show">Tega ne prikaži več</string> <string name="reading_list_prompt_turned_sync_on_dialog_enable_syncing">Sinhroniziraj</string> <string name="reading_list_prompt_turned_sync_on_dialog_no_thanks">Ne, hvala</string> <string name="default_reading_list_name">Shranjeno</string> <string name="default_reading_list_description">Privzeti seznam za vaše shranjene članke</string> <string name="no_user_lists_title">Organiziraj članke v sezname</string> <string name="no_user_lists_msg">Ustvarite lahko sezname krajev, ki jih želite obiskati, priljubljenih tem in še marsičesa drugega</string> <string name="reading_list_saved_list_rename">%1$s (uporabnik ustvarjen)</string> <string name="split_reading_list_message">Bralni seznami so omejeni na %d člankov. Obstoječi seznami, ki presegajo to dolžino, so bili razdeljeni v več seznamov.</string> <string name="reading_list_move_article_limit_message">Prestavitev na ta seznam ni mogoča. Dosegli ste omejitev seznama »%1$s« na %2$d člankov.</string> <string name="reading_list_article_limit_message">Na ta seznam ni mogoče dodati. Dosegli ste omejitev seznama »%1$s« na %2$d člankov.</string> <string name="reading_lists_limit_message">Še enega seznama ni mogoče ustvariti. Dosegli ste omejitev 100 bralnih seznamov na račun.</string> <string name="reading_lists_menu_create_list">Ustvari nov seznam</string> <string name="reading_lists_menu_sort_by">Razvrsti po</string> <string name="reading_lists_refresh_sync_option">Osveži sinhronizacijo</string> <string name="reading_list_preference_login_or_signup_to_enable_sync_dialog_login">Prijava/registracija</string> <plurals name="reading_list_article_offline_message"> <item quantity="one">Članek bo zdaj na voljo brez povezave.</item> <item quantity="two">Članka bosta zdaj na voljo brez povezave.</item> <item quantity="few">Članki bodo zdaj na voljo brez povezave.</item> <item quantity="other">Članki bodo zdaj na voljo brez povezave.</item> </plurals> <plurals name="reading_list_article_not_offline_message"> <item quantity="one">Članek ne bo več na voljo brez povezave.</item> <item quantity="two">Članka ne bosta več na voljo brez povezave.</item> <item quantity="few">Članki ne bodo več na voljo brez povezave.</item> <item quantity="other">Članki ne bodo več na voljo brez povezave.</item> </plurals> <string name="reading_list_toast_last_sync">Bralni seznami sinhronizirani.</string> <string name="reading_list_menu_last_sync">Zadnja sinhronizacija: %s</string> <string name="reading_list_remove_list_dialog_ok_button_text">V redu</string> <string name="reading_list_delete_dialog_ok_button_text">V redu</string> <string name="reading_list_remove_from_list_dialog_cancel_button_text">Prekliči</string> <string name="reading_list_delete_dialog_cancel_button_text">Prekliči</string> <string name="reading_list_remove_from_offline_cancel_button_text">Prekliči</string> <string name="reading_list_download_using_mobile_data_cancel_button_text">Prekliči</string> <string name="reading_list_split_dialog_ok_button_text">V redu</string> <string name="reading_list_activity_title">Bralni seznam: %s</string> <string name="user_option_sync_label">Nastavitve</string> <string name="notification_reverted_title">Vrnjeno urejanje</string> <string name="notification_channel_title">Prenos člankov</string> <string name="notification_channel_description">Napredek prenosa</string> <string name="notification_syncing_pause_button">Premor</string> <string name="notification_syncing_resume_button">Nadaljuj</string> <string name="notification_syncing_cancel_button">Prekliči</string> <string name="notification_syncing_reading_list_channel_title">Sinhronizacija bralnih seznamov</string> <string name="notification_syncing_reading_list_channel_description">Napredek sinhronizacije bralnih seznamov</string> <string name="notification_many_unread">Imate %d neprebranih obvestil</string> <plurals name="notification_channel_name"> <item quantity="one">Prenašam članek</item> <item quantity="two">Prenašam članka</item> <item quantity="few">Prenašam članke</item> <item quantity="other">Prenašam članke</item> </plurals> <plurals name="notification_syncing_title"> <item quantity="one">Prenašam %1$d članek …</item> <item quantity="two">Prenašam %1$d članka …</item> <item quantity="few">Prenašam %1$d članke …</item> <item quantity="other">Prenašam %1$d članke …</item> </plurals> <plurals name="notification_syncing_description"> <item quantity="one">Preostal je še %1$d članek</item> <item quantity="two">Preostala sta še %1$d članka</item> <item quantity="few">Preostali so še %1$d članki</item> <item quantity="other">Preostalo je še %1$d člankov</item> </plurals> <plurals name="notification_syncing_reading_list_channel_name"> <item quantity="one">Sinhronizacija bralnega seznama</item> <item quantity="two">Sinhronizacija bralnih seznamov</item> <item quantity="few">Sinhronizacija bralnih seznamov</item> <item quantity="other">Sinhronizacija bralnih seznamov</item> </plurals> <plurals name="notification_syncing_reading_list_title"> <item quantity="one">Sinhroniziram %1$d seznam …</item> <item quantity="two">Sinhroniziram %1$d seznama …</item> <item quantity="few">Sinhroniziram %1$d sezname …</item> <item quantity="other">Sinhroniziram %1$d sezname …</item> </plurals> <plurals name="notification_syncing_reading_list_description"> <item quantity="one">Preostal je še %1$d seznam</item> <item quantity="two">Preostala sta še %1$d seznama</item> <item quantity="few">Preostali so še %1$d seznami</item> <item quantity="other">Preostalo je še %1$d seznamov</item> </plurals> <string name="notification_echo_channel_description">Obvestila v Wikipediji</string> <string name="notifications_activity_title">Obvestila</string> <string name="notifications_activity_title_archived">Obvestila (arhivirano)</string> <string name="notifications_search">Išči v obvestilih</string> <string name="notifications_view_unread">Ogled neprebranih</string> <string name="notifications_view_archived">Prikaži arhivirano</string> <string name="notifications_prefs">Nastavitve obveščanja</string> <string name="notifications_archive">Označi kot prebrano in arhiviraj</string> <plurals name="notification_archive_message"> <item quantity="one">Obvestilo arhivirano</item> <item quantity="two">Obvestili arhivirani</item> <item quantity="few">%d obvestila arhivirana</item> <item quantity="other">%d obvestila arhivirana</item> </plurals> <string name="notifications_poll_enable_title">Omogoči obveščanje</string> <string name="notifications_poll_enable_positive">Vključi</string> <string name="notifications_poll_enable_negative">Ne zdaj</string> <string name="notifications_empty_message">Prebrali ste vsa obvestila!</string> <string name="notifications_view_archived_button_text">Prikaži arhivirana obvestila</string> <string name="notification_preferences_title">Nastavitve obveščanja</string> <string name="notifications_mark_unread">Označi kot neprebrano</string> <string name="notifications_mark_all_as_read">Označi vse kot prebrano</string> <string name="notifications_direct_reply_action">Odgovor</string> <string name="notifications_direct_reply_progress">Objavljam odgovor na %s ...</string> <string name="notifications_direct_reply_success">Odgovor objavljen.</string> <string name="notifications_direct_reply_error">Odgovora ni bilo mogoče objaviti samodejno.</string> <string name="notifications_mark_all_as_read_message">%d označenih kot prebrana</string> <string name="notifications_mark_all_as_unread_message">%d označenih kot neprebrana</string> <plurals name="notifications_mark_as_read_plural"> <item quantity="one">1 označeno kot prebrano</item> <item quantity="two">%d označeni kot prebrani</item> <item quantity="few">%d označena kot prebrana</item> <item quantity="other">%d označenih kot prebrana</item> </plurals> <plurals name="notifications_mark_as_unread_plural"> <item quantity="one">1 označeno kot neprebrano</item> <item quantity="two">2 označeni kot neprebrani</item> <item quantity="few">%d označenih kot neprebrana</item> <item quantity="other">%d označenih kot neprebrana</item> </plurals> <string name="watchlist_title">Spisek nadzorov</string> <string name="preference_title_notification_poll">Preveri obvestila</string> <string name="preference_summary_notification_poll">Omogoči aplikaciji uporabo podatkov za preverjanje novih obvestil v ozadju.</string> <string name="preference_category_notification_types">Vrste obvestil v aplikaciji</string> <string name="preference_title_notification_system">Sistem</string> <string name="preference_summary_notification_system">Sistemska sporočila</string> <string name="preference_title_notification_milestone">Mejnik</string> <string name="preference_summary_notification_milestone">Doseženo določeno število urejanj</string> <string name="preference_title_notification_thanks">Zahvala</string> <string name="preference_summary_notification_thanks">Nekdo se vam zahvaljuje za urejanje</string> <string name="preference_title_notification_revert">Vrnitve</string> <string name="preference_summary_notification_revert">Eden od vaših prispevkov je bil razveljavljen</string> <string name="preference_title_notification_login_fail">Prijava</string> <string name="preference_summary_notification_login_fail">Vaša prijavljanja</string> <string name="preference_title_notification_mention">Omemba</string> <string name="preference_summary_notification_mention">Nekdo vas je omenil na eni od strani</string> <string name="preference_title_notification_user_talk">Pogovorna stran</string> <string name="preference_summary_notification_user_talk">Sporočila in odgovori s pogovornih strani</string> <string name="preference_title_notification_email_user">Prejeta e-pošta</string> <string name="preference_summary_notification_email_user">Nekdo iz vikija vam je poslal e-pošto</string> <string name="preference_title_notification_user_rights">Spremembe uporabniških pravic</string> <string name="preference_summary_notification_user_rights">Prejeto ob spremembi vaših uporabniških pravic</string> <string name="preference_title_notification_article_linked">Povezave na članke, ki ste jih ustvarili</string> <string name="preference_summary_notification_article_linked">Prejeto ob ustvaritvi nove povezave na stran, ki ste jo ustvarili</string> <string name="preference_category_push_notifications">Potisna obvestila</string> <string name="preference_title_customize_push_notifications">Prilagodi potisna obvestila</string> <string name="preference_category_display_settings">Nastavitve prikaza</string> <string name="preference_title_hide_read_notifications">Skrij prebrana obvestila</string> <string name="notifications_channel_group_wikipedia_notifications_title">Wikipedija</string> <string name="notifications_channel_group_wikipedia_notifications_description">Obvestila iz Wikipedije</string> <string name="notifications_channel_group_other_title">Drugo</string> <string name="notifications_channel_group_other_description">Druga obvestila iz aplikacije</string> <string name="notifications_filter_label">Filtriranje obvestil</string> <string name="notifications_filter_icon_content_description">Filtriraj obvestila</string> <string name="notifications_filter_update_app_languages">Posodobi jezike aplikacije</string> <string name="notifications_empty_search_message">Če želite videti več obvestil, poskusite odstraniti %s</string> <plurals name="notifications_number_of_filters"> <item quantity="one">%d filter</item> <item quantity="two">%d filtra</item> <item quantity="few">%d filtri</item> <item quantity="other">%d filtrov</item> </plurals> <string name="notifications_select_all_filters">Izberi vse filtre</string> <string name="notifications_tab_filter_all">Vse</string> <string name="notifications_tab_filter_mentions">Omembe</string> <string name="notifications_tab_filter_unread">(%s)</string> <string name="notifications_search_bar_hint">Preišči ali filtriraj obvestila</string> <string name="notifications_search_bar_filter_hint">Filter obvestil</string> <string name="notifications_menu_mark_as_read">Označi kot prebrano</string> <string name="notifications_menu_mark_as_unread">Označi kot neprebrano</string> <string name="notifications_swipe_action_read">Prebrano</string> <string name="notifications_swipe_action_unread">Neprebrano</string> <string name="notifications_menu_check_all">Označi vse predmete</string> <string name="notifications_menu_uncheck_all">Odznači vse predmete</string> <string name="notifications_wiki_filter_header">Filter vikijev</string> <string name="notifications_type_filter_header">Filter tipov</string> <string name="notifications_all_wikis_text">Vsi vikiji</string> <string name="notifications_all_types_text">Vse vrste</string> <string name="notifications_menu_user_talk_page">%s: pogovorna stran</string> <string name="notifications_offline_disable_message">Ta funkcija ni ma voljo brez internetne povezave.</string> <string name="view_because_you_read_card_title">Ker ste prebrali</string> <string name="view_random_card_title">Randomizator</string> <string name="view_random_article_card_title">Naključni članek</string> <string name="view_random_article_card_action">Več naključnih člankov</string> <string name="view_top_read_card_title">Najbolj brano</string> <string name="view_top_read_card_action">Več najbolj branega</string> <string name="view_top_read_card_pageviews_k_suffix">%d k</string> <string name="view_top_read_card_pageviews_m_suffix">%d M</string> <string name="view_next_random_article">Naloži še en naključni članek</string> <string name="view_main_page_card_title">Danes v Wikipediji</string> <string name="view_main_page_card_action">Ogled glavne strani</string> <string name="view_featured_image_card_title">Slika dneva</string> <string name="view_featured_image_card_download">Prenesi</string> <string name="view_featured_image_card_share">Deli</string> <string name="menu_feed_card_dismiss">Skrij kartico</string> <string name="menu_feed_card_dismissed">Kartica skrita.</string> <string name="menu_feed_card_edit_card_languages">Uredi jezike kartice</string> <string name="menu_feed_overflow_label">Več možnosti</string> <string name="feed_featured_image_share_subject">Izbrana slika iz Wikimedijine zbirke</string> <string name="feed">Raziskuj</string> <string name="home">Domov</string> <string name="view_static_card_icon_content_description">Ikona kartice</string> <string name="view_card_news_title">V novicah</string> <plurals name="view_continue_reading_card_subtitle"> <item quantity="one">včeraj</item> <item quantity="two">pred %d dnevoma</item> <item quantity="few">pred %d dnevi</item> <item quantity="other">pred %d dnevi</item> </plurals> <string name="view_continue_reading_card_subtitle_today">danes</string> <string name="view_continue_reading_card_subtitle_read_date">Brano: %s</string> <string name="view_announcement_card_negative_action">Ne, hvala</string> <string name="view_offline_card_text">Vsebine ni mogoče naložiti brez povezave.</string> <string name="view_featured_article_card_title">Izbrani članki</string> <string name="view_static_card_save_button_label">Shrani</string> <string name="feed_configure_activity_title">Prilagodi vir</string> <string name="feed_configure_menu_reset">Ponastavi na privzeto</string> <string name="feed_configure_menu_select_all">Prikaži vse</string> <string name="feed_configure_menu_deselect_all">Skrij vse</string> <string name="feed_configure_language_warning">Vse vrste kartic niso podprte v vseh jezikih Wikipedije. Izbrane jezike lahko urejate v nastavitvah.</string> <string name="feed_item_type_news">Članki o tekočih dogodkih</string> <string name="feed_item_type_on_this_day">Zgodovinski dogodki na današnji dan</string> <string name="feed_item_type_because_you_read">Predlogi glede na pred kratkim prebrani članek iz vaše zgodovine</string> <string name="feed_item_type_featured_article">Izbrani članek dneva v Wikipediji</string> <string name="feed_item_type_trending">Danes najbolj obiskani članki</string> <string name="feed_item_type_featured_image">Izbrana slika dneva iz Wikimedijine zbirke</string> <string name="feed_item_type_main_page">Glavna stran Wikipedije z izbrano vsebino dneva</string> <string name="feed_item_type_randomizer">Prikazuje naključne članke za branje</string> <string name="feed_item_type_suggested_edits">Predlogi za dodajanje vsebine v Wikipedijo</string> <string name="feed_empty_message">V vašem viru Raziskovanje ni ničesar</string> <string name="feed_configure_onboarding_action">Prilagodi</string> <string name="customize_lang_selection_dialog_ok_button_text">V redu</string> <string name="customize_lang_selection_dialog_cancel_button_text">Prekliči</string> <string name="feed_configure_onboarding_text">&lt;strong&gt;Prilagodite si svoj vir Raziskovanje&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Izberete lahko, kaj želite v viru videti, in določite tudi najljubše vrste vsebine.</string> <string name="feed_lang_selection_dialog_ok_button_text">V redu</string> <string name="feed_lang_selection_dialog_cancel_button_text">Prekliči</string> <string name="feed_accessibility_card_text">Dosegli ste dno vira.</string> <string name="feed_accessibility_card_load_more_button">Naloži več</string> <string name="top_read_activity_title">Najbolj brano: %s</string> <string name="tabs_activity_title">Zavihki</string> <string name="description_edit_text_hint">Opis članka</string> <string name="description_edit_article_description_label">Članek</string> <string name="description_edit_translate_article_description_label_per_language">Opis članka (%s)</string> <string name="description_edit_translate_article_description_hint_per_language">Opis članka (%s)</string> <string name="description_edit_add_caption_label">Opis slike</string> <string name="description_edit_add_caption_hint">Opis slike</string> <string name="description_edit_translate_caption_label_per_language">Napis k sliki (%s)</string> <string name="description_edit_translate_caption_hint_per_language">Napis k sliki (%s)</string> <string name="description_edit_save">Objavi</string> <string name="description_edit_read">Preberi</string> <string name="description_edit_add_description">Dodaj opis članka</string> <string name="description_edit_translate_description">Prevedi opis članka</string> <string name="description_edit_edit_description">Uredi opis članka</string> <string name="description_edit_add_image_caption">Dodaj napis k sliki</string> <string name="description_edit_edit_image_caption">Uredite napis k sliki</string> <string name="description_edit_translate_image_caption">Prevedi napis k sliki</string> <string name="description_edit_cancel_hint">Prekliči</string> <string name="description_edit_help_title">Informacije: opisi člankov</string> <string name="description_edit_help_about_wikidata">O projektu Wikidata</string> <string name="description_edit_help_wikidata_guide">Vodnik Wikipodatkov za pisanje opisov</string> <string name="wikidata_description_guide_url">https://www.wikidata.org/wiki/Help:Description#slovenščina</string> <string name="description_edit_anon_limit">Hvala za vaše nadaljnje zanimanje za urejanje opisov člankov! Za dodatna urejanja se prijavite v svoj račun v Wikipediji.</string> <string name="description_edit_license_notice">S spremembo opisa članka se strinjam s &lt;a href=\"%1$s\"&gt;Pogoji uporabe&lt;/a&gt; in nepreklicno objavo svojih prispevkov pod licenco &lt;a href=\"%2$s\"&gt;Creative Commons CC0&lt;/a&gt;.</string> <string name="description_edit_helper_text_lowercase_warning">običajno začnite z malo črko</string> <string name="description_edit_voice_input_description">Glasovni vnos</string> <string name="description_edit_learn_more">Več o opisih člankov</string> <string name="description_edit_image_caption_learn_more">Več o napisih k slikam</string> <string name="description_edit_description_learn_more_url">https://www.mediawiki.org/wiki/Wikimedia_Apps/Suggested_edits#Article_descriptions</string> <string name="description_edit_image_caption_learn_more_url">https://www.mediawiki.org/wiki/Wikimedia_Apps/Suggested_edits#Image_captions</string> <string name="description_too_short">Besedilo je prekratko.</string> <string name="description_ends_with_punctuation">Besedilo se ne sme končati z ločilom.</string> <string name="description_starts_with_article">Izogibajte se začenjanju s členi, kot je »ta« ali \"to\".</string> <string name="description_starts_with_uppercase">Začnite z malo črko, razen če je prva beseda lastno ime.</string> <string name="description_starts_with_lowercase">Izogibajte se začetku z malo začetnico.</string> <string name="description_is_in_different_language">Besedilo je v nepričakovanem jeziku. Jezik mora biti %s.</string> <string name="description_verification_notice">Preverite, ali je vaš opis v %1$s. Če je opis, ki ste ga napisali, v %2$s, lahko to obvestilo opustite.</string> <string name="description_edit_success_saved">Opis članka objavljen!</string> <string name="description_edit_success_saved_snackbar">Opis članka objavljen!</string> <string name="description_edit_success_saved_in_lang_snackbar">Opis članka objavljen (%s)</string> <string name="description_edit_success_saved_image_caption_snackbar">Napis k sliki objavljen!</string> <string name="description_edit_success_saved_image_caption_in_lang_snackbar">Napis k sliki objavljen! (%s)</string> <string name="description_edit_success_saved_image_tags_snackbar">Oznaka (oznake) slik objavljena (objavljene)!</string> <string name="description_edit_success_se_general_feed_link_snackbar">Vas je veselilo? Pomagajte nam dodati še več.</string> <string name="description_edit_success_encouragement">Wikipedijo ste pravkar izboljšali za vsakogar</string> <string name="description_edit_success_done">Končano</string> <string name="description_edit_success_did_you_know">Ali ste vedeli?</string> <string name="description_edit_success_article_edit_hint">V tej aplikaciji lahko članke tudi urejate. Poskusite naslednjič s klikom ikone ^1 popravljati tipkarske napake in kratke stavke.</string> <string name="description_edit_tutorial_title_descriptions">Opisi člankov</string> <string name="description_edit_tutorial_title_descriptions_summary">Povzetek članka, ki bralcem pomaga razumeti temo ob prvem pogledu</string> <string name="description_edit_tutorial_keep_it_short">Naj bo kratko</string> <string name="description_edit_tutorial_keep_it_short_instructions">Najboljše ena vrstica z dvema do dvanajstimi besedami</string> <string name="description_edit_tutorial_button_label_start_editing">Začetek urejanja</string> <string name="description_edit_tutorial_promise">Ob začetku obljubljam, da te funkcije ne bom zlorabil/a</string> <string name="customize_toolbar_title">Prilagodi orodno vrstico</string> <string name="customize_toolbar_shortcut_description_text">Prilagodite si orodno vrstico na dnu s 5 bližnjicami, ki so za vas najuporabnejše.</string> <string name="customize_toolbar_category_toolbar">Orodna vrstica</string> <string name="customize_toolbar_category_menu">Meni</string> <string name="customize_toolbar_drag_and_drop_placeholder">Povlecite in spustite svoje najljubše predmete sem 👋</string> <string name="customize_toolbar_reset_to_default_button">Ponastavi na privzeto</string> <string name="customize_toolbar_item_drag_handle_default_tooltip">Za prestavitev predmeta pridržite ikono za povlek</string> <string name="customize_toolbar_item_default_tooltip">Element pritisnite in povlecite, da ga prestavite.</string> <string name="suggested_edits_describe_articles">Opisovanje člankov</string> <string name="suggested_edits_caption_images">Dodajte napise k slikam</string> <string name="suggested_edits_tag_images">Označujte slike</string> <string name="suggested_edits_review_description">Pregled opisa članka</string> <string name="suggested_edits_add_description_button">Dodaj opis</string> <string name="suggested_edits_edit_description_button">Uredi opis</string> <string name="suggested_edits_add_translation_button">Dodaj prevod</string> <string name="suggested_edits_edit_translation_button">Uredi prevod</string> <string name="suggested_edits_add_caption_button">Dodaj napis</string> <string name="suggested_edits_edit_caption_button">Uredi napis</string> <string name="suggested_edits_review_image_caption">Pregled napisa k sliki</string> <string name="suggested_edits_my_contributions">Moji prispevki</string> <string name="suggested_edits_no_description">Ta datoteka nima opisa</string> <string name="suggested_edits_license_notice">S shranitvijo opisa se strinjam s &lt;a href=\"%1$s\"&gt;Pogoji uporabe&lt;/a&gt; in svoje prispevke nepreklicno objavljam pod licenco &lt;a href=\"%2$s\"&gt;Creative Commons CC0&lt;/a&gt;.</string> <string name="suggested_edits_image_caption_license_notice">S pripisom napisa k sliki izražam strinjanje s &lt;a href=\"%1$s\"&gt;Pogoji uporabe&lt;/a&gt; in nepreklicno objavljam svoj prispevek pod licenco &lt;a href=\"%2$s\"&gt;Creative Commons CC0&lt;/a&gt;.</string> <string name="suggested_edits_menu_info">Informacije</string> <string name="suggested_edits_task_add_description_title">Dodajanje opisov k člankom</string> <string name="suggested_edits_task_add_description_description">Prispevajte k člankom brez opisa</string> <string name="suggested_edits_task_image_caption_title">Dodajanje napisov k slikam</string> <string name="suggested_edits_task_image_caption_description">Dodajajte manjkajoče kratke napise k slikam</string> <string name="suggested_edits_task_translate_caption_title">Prevajanje napisov k slikam</string> <string name="suggested_edits_task_translate_caption_description">Prevajajte napise v druge jezike</string> <string name="suggested_edits_task_multilingual_title">Več nalog za večjezične urejevalce</string> <string name="suggested_edits_task_multilingual_description">Naloge za prevajanje so na voljo, če berete in pišete v več kot enem jeziku Wikipedije.</string> <string name="suggested_edits_task_image_caption_edit_disable_text">Zaklenjeno, dokler ne uredite %d napisov k slikam</string> <string name="suggested_edits_task_translate_description_edit_disable_text">Zaklenjeno, dokler ne uredite %d opisov člankov (preverjeno)</string> <string name="suggested_edits_task_multilingual_negative">Ni zame</string> <string name="suggested_edits_task_multilingual_positive">Dodaj jezike</string> <string name="suggested_edits_image_caption_summary_title_image">Slika</string> <string name="suggested_edits_image_caption_summary_title_artist">Umetnik/izdelovalec</string> <string name="suggested_edits_image_caption_summary_title_author">Avtor</string> <string name="suggested_edits_image_caption_summary_title_source">Vir</string> <string name="suggested_edits_image_caption_summary_title_license">Licenca</string> <string name="suggested_edits_image_caption_summary_title_date">Datum</string> <plurals name="suggested_edits_contribution_count"> <item quantity="one">1 prispevek</item> <item quantity="two">%d prispevka</item> <item quantity="few">%d prispevki</item> <item quantity="other">%d prispevkov</item> </plurals> <string name="suggested_edits_feed_card_title">Predlagana urejanja</string> <string name="suggested_edits_feed_card_add_description_button">Dodaj opis članka</string> <string name="suggested_edits_feed_card_add_translation_in_language_button">Dodaj opis članka (%s)</string> <string name="suggested_edits_tasks_onboarding_get_started">Začni</string> <string name="suggested_edits_image_preview_dialog_caption_in_language_title">Napis k sliki (%s)</string> <string name="suggested_edits_image_preview_dialog_image">Slika</string> <string name="suggested_edits_image_preview_dialog_file_commons">Datoteka iz Wikimedijine zbirke</string> <string name="suggested_edits_image_preview_dialog_artist">Umetnik/izdelovalec</string> <string name="suggested_edits_image_preview_dialog_tags">Oznake</string> <string name="suggested_edits_image_preview_dialog_date">Datum</string> <string name="suggested_edits_image_preview_dialog_source">Vir/fotograf</string> <string name="suggested_edits_image_preview_dialog_licensing">Licenca</string> <string name="suggested_edits_image_preview_dialog_more_info">Več o tem</string> <string name="suggested_edits_image_preview_dialog_file_page_link_text">Stran datoteke v Wikimedijini zbirki</string> <string name="suggested_edits_image_preview_dialog_file_page_wikipedia_link_text">Stran datoteke v Wikipediji</string> <string name="suggested_edits_article_cta_image_tags">Dodajte sliki oznake</string> <string name="suggested_edits_article_cta_image_caption">Dodaj napis k sliki</string> <string name="suggested_edits_article_cta_image_caption_in_language">Dodaj napis k sliki (%s)</string> <string name="suggested_edits_article_cta_snackbar_action">Prikaži</string> <string name="suggested_edits_feed_card_add_image_caption">Dodaj napis k sliki</string> <string name="suggested_edits_feed_card_translate_image_caption">Dodaj napis k sliki (%s)</string> <string name="suggested_edits_feed_card_add_image_tags">Dodajte sliki oznake</string> <string name="suggested_edits_snackbar_survey_text">Kako je potekalo urejanje? Prosimo, vzemite si trenutek in odgovorite na anketo o urejanju z aplikacijo.</string> <string name="suggested_edits_snackbar_survey_action_text">Opravi anketo</string> <string name="suggested_edits_task_action_text_add">Dodaj</string> <string name="suggested_edits_task_action_text_translate">Prevedi</string> <string name="suggested_edits_image_captions">Napisi k slikam</string> <string name="suggested_edits_image_tags">Označbe slik</string> <string name="suggested_edits_image_tags_publishing">Objavljam</string> <string name="suggested_edits_image_tags_published">Objavljeno</string> <string name="suggested_edits_image_tags_onboarding_title">Označevanje slik omogoča, da jih je lažje najti.</string> <string name="suggested_edits_image_tags_onboarding_text">Z dodajanjem oznak k slikam boste omogočili lažje iskanje slik v Zbirki, shrambi prosto licenciranih slik, ki jo Wikipedija uporablja za slike v člankih.</string> <string name="suggested_edits_image_tags_onboarding_note">K slikam bodo dodane samo oznake, ki jih boste izbrali.</string> <string name="suggested_edits_image_tags_task_detail">Dodajte oznake po meri, da bo sliko lažje najti.</string> <string name="suggested_edits_image_tags_choose">Dodajte ali izberite ustrezne oznake</string> <string name="suggested_edits_image_tags_published_list">Objavljene oznake</string> <string name="suggested_edits_image_tags_search">Iskanje oznak</string> <string name="suggested_edits_image_tags_select_title">Za to sliko niste izbrali nobene oznake</string> <string name="suggested_edits_image_tags_select_text">K slikam bodo dodane smao oznake, ki jih boste izbrali. Oznake, ki jih ne boste izbrali, bodo označene kot zavrnjene. Ali resnično želite vse oznake označiti kot zavrnjene?</string> <string name="suggested_edits_image_tags_add_tag">Dodaj oznako</string> <string name="suggested_edits_image_zoom_tooltip">Za povečanje sliko razprite s prsti.</string> <string name="suggested_edits_encouragement_message">%s, hvala za vaša urejanja. Tu boste našli več načinov za prispevanje k Wikipediji.</string> <string name="suggested_edits_onboarding_message">&lt;b&gt;Pozdravljeni, %s&lt;/b&gt;, tu lahko najdete nekaj hitrih in preprostih načinov za izboljšanje Wikipedije. Svoj prispevek boste opazili takoj, ko boste začeli. Uspešno urejanje!</string> <string name="suggested_edits_image_captions_task_detail">Opišite sliko, da bodo bralci lahko razumeli njen pomen in kontekst.</string> <string name="suggested_edits_add_descriptions_task_detail">Povzemite članek, da bodo bralci temo lahko razumeli že ob prvem pogledu.</string> <string name="suggested_edits_contributions_stat_tooltip">Skupno število vaših urejanj do zdaj.</string> <string name="suggested_edits_edit_streak_stat_tooltip">Število zaporednih dni, ko ste urejali. Če nekaj časa niste sodelovali, je prikazan datum vašega zadnjega prispevka.</string> <string name="suggested_edits_page_views_stat_tooltip">Skupno število ogledov predmetov, h katerim ste prispevali, v zadnjih 30 dneh.</string> <string name="suggested_edits_edit_quality_stat_tooltip">Glede na število vaših vrnjenih (razveljavljenih) urejanj. Vrnjena urejanja: %d.</string> <string name="suggested_edits_paused_message">Predlagana urejanja so prekinjena do %1$s. %2$s, žal so bili nekateri od vaših zadnjih prispevkov vrnjeni.</string> <string name="suggested_edits_disabled_message">Predlagana urejanja so onemogočena. %s, žal so bili številni od vaših nedavnih prispevkov vrnjeni.</string> <string name="suggested_edits_ip_blocked_message">Zdi se, da je urejanje z vašega IP-naslova (ali razpona IP-naslovov) trenutno preprečeno.</string> <string name="suggested_edits_gate_message">Oprostite, %s, za uporabo te možnosti morate narediti vsaj tri popravke neposredno v članku.</string> <string name="suggested_edits_editing_tips_link_text">Nasveti in triki za urejanje</string> <string name="suggested_edits_help_page_link_text">Stran za pomoč za predlagana urejanja</string> <string name="suggested_edits_edit_streak_label_text">Niz urejanj</string> <string name="suggested_edits_views_label_text">Ogledov</string> <string name="suggested_edits_quality_label_text">Kakovost urejanj</string> <string name="suggested_edits_quality_perfect_text">Popolno</string> <string name="suggested_edits_quality_excellent_text">Odlična</string> <string name="suggested_edits_quality_very_good_text">Zelo dobra</string> <string name="suggested_edits_quality_good_text">Dobra</string> <string name="suggested_edits_quality_okay_text">V redu</string> <string name="suggested_edits_quality_sufficient_text">Zadostna</string> <string name="suggested_edits_quality_poor_text">Podpovprečna</string> <string name="suggested_edits_quality_bad_text">Slaba</string> <string name="suggested_edits_label">Predlagana urejanja</string> <plurals name="suggested_edits_contribution"> <item quantity="one">Prispevek</item> <item quantity="two">Prispevki</item> <item quantity="few">Prispevki</item> <item quantity="other">Prispevki</item> </plurals> <plurals name="suggested_edits_edit_streak_detail_text"> <item quantity="one">%d dan</item> <item quantity="two">%d dneva</item> <item quantity="few">%d dnevi</item> <item quantity="other">%d dni</item> </plurals> <string name="suggested_edits_what_is_title">Kaj so predlagana urejanja?</string> <string name="suggested_edits_what_is_text">Predlagana urejanja so priložnost za majhne, toda pomembne prispevke k Wikipediji.</string> <string name="suggested_edits_learn_more">Več o tem</string> <string name="suggested_edits_paused_title">Prekinjeno</string> <string name="suggested_edits_disabled_title">Onemogočeno</string> <string name="suggested_edits_ip_blocked_title">IP blokiran</string> <string name="suggested_edits_last_edited">Zadnje urejanje</string> <string name="suggested_edits_last_edited_never">Nikoli</string> <string name="suggested_edits_task_new">novo</string> <string name="suggested_edits_cc0_notice">Z objavo izražate strinjanje s &lt;a href=\"%1$s\"&gt;pogoji uporabe&lt;/a&gt; in ta prispevek nepreklicno objavljate pod licenco &lt;a href=\"%2$s\"&gt;CC0&lt;/a&gt;.</string> <string name="suggested_edits_reactivation_notification_title">Predlagana urejanja</string> <string name="suggested_edits_reactivation_notification_stage_one">Hvala za urejanje Wikipedije! Zakaj ne bi nadaljevali, kjer ste končali?</string> <string name="suggested_edits_reactivation_notification_stage_two">Imate trenutek za nadaljnje izboljševanje Wikipedije? Oglejte si te predloge za urejanje.</string> <string name="suggested_edits_contributions_screen_title">Prispevki uporabnika/ce %s</string> <string name="suggested_edits_contribution_language_label">Jezik</string> <string name="suggested_edits_contribution_date_time_label">Datum/čas</string> <string name="suggested_edits_contribution_type_label">Vrsta prispevka</string> <string name="suggested_edits_contribution_image_label">Slika</string> <string name="suggested_edits_contribution_article_label">Članek</string> <string name="suggested_edits_contribution_views">%s ogledov</string> <plurals name="suggested_edits_contribution_seen_times"> <item quantity="one">Ogledano enkrat v preteklih 30 dnevih</item> <item quantity="two">Ogledano dvakrat v preteklih 30 dnevih</item> <item quantity="few">Ogledano %s-krat v preteklih 30 dnevih.</item> <item quantity="other">Ogledano %s-krat v preteklih 30 dnevih.</item> </plurals> <string name="suggested_edits_contribution_seen_text">%s ogledov v zadnjih 30 dneh.</string> <plurals name="suggested_edits_image_tag_contribution_label"> <item quantity="one">Dodali ste %d oznako</item> <item quantity="two">Dodali ste %d oznaki</item> <item quantity="few">Dodali ste %d oznake</item> <item quantity="other">Dodali ste %d oznak</item> </plurals> <string name="suggested_edits_contribution_type_title">%1$d urejanj: %2$s</string> <string name="suggested_edits_contribution_date_yesterday_text">Včeraj</string> <string name="suggested_edits_encourage_account_creation_title">Ste vedeli, da lahko Wikipedijo ureja vsakdo?</string> <string name="suggested_edits_encourage_account_creation_message">Predlagana urejanja so nov način urejanja Wikipedije v Androidu. Pomagal vam bo opraviti majhne, vendar pomembne prispevke k Wikipediji.\nNaš cilj je poenostaviti urejanje in ga napraviti vsakomur lažje dostopnega! Za začetek se prijavite ali pridružite Wikipediji.</string> <string name="suggested_edits_encourage_account_creation_login_button">Prijavite se / pridružite se Wikipediji</string> <string name="suggested_edits_contribution_type_image_tag">Oznaka slike</string> <string name="suggested_edits_contribution_current_revision_text">Vaše urejanje je trenutno prikazano v Wikipediji</string> <string name="suggested_card_more_edits">Več predlaganih urejanj</string> <plurals name="suggested_edits_tags_diff_count_text"> <item quantity="one">%1$s oznaka</item> <item quantity="two">%1$s oznaki</item> <item quantity="few">%1$s oznake</item> <item quantity="other">%1$s oznak</item> </plurals> <plurals name="suggested_edits_contribution_diff_count_text"> <item quantity="one">%1$s znak</item> <item quantity="two">%1$s znaka</item> <item quantity="few">%1$s znaki</item> <item quantity="other">%1$s znakov</item> </plurals> <plurals name="suggested_edits_removed_contribution_label"> <item quantity="one">Odstranili ste %d znak</item> <item quantity="two">Odstranili ste %d znaka</item> <item quantity="few">Odstranili ste %d znake</item> <item quantity="other">Odstranili ste %d znakov</item> </plurals> <plurals name="suggested_edits_added_contribution_label"> <item quantity="one">Dodali ste %d znak</item> <item quantity="two">Dodali ste %d znaka</item> <item quantity="few">Dodali ste %d znake</item> <item quantity="other">Dodali ste %d znakov</item> </plurals> <string name="file_page_activity_title">Stran datoteke</string> <string name="file_page_add_image_caption_button">Dodaj napis k sliki</string> <string name="file_page_add_image_tags_button">Dodaj sliki oznake</string> <string name="file_page_edit_button_content_description">Uredi %s</string> <string name="description_edit_revert_subtitle">Hvala za urejanje Wikipedije!</string> <string name="description_edit_revert_intro">Vemo, da ste se potrudili po najboljših močeh, vendar je eden od pregledovalcev imel pomisleke. Možni razlogi za vrnitev vašega urejanja so:</string> <string name="description_edit_revert_reason1">vaš prispevek ni bil v skladu z eno od &lt;a href=\"%1$s\"&gt;smernic&lt;/a&gt;.</string> <string name="description_edit_revert_reason2">vaš prispevek je bil videti kot eksperiment ali vandalizem.</string> <string name="description_edit_revert_history">Če želite, si lahko ogledate &lt;a href=\"%1$s\"&gt;zgodovino urejanj&lt;/a&gt;.</string> <string name="description_edit_login_cancel_button_text">Prekliči</string> <string name="offline_read_permission_rationale">Za bsrkanje brez povezave je potrebno dovoljenje za dostop do vaše naprave.</string> <string name="offline_read_final_rationale">Za uporabo Nepovezane knjižnice je potrebno dovoljenje za dostop do pomnilnika vaše naprave.</string> <string name="size_gb">%.2f GB</string> <string name="size_mb">%.2f MB</string> <string name="onboarding_skip">Preskoči</string> <string name="onboarding_continue">Nadaljuj</string> <string name="onboarding_get_started">Začni</string> <string name="onboarding_maybe_later">Morda pozneje</string> <string name="onboarding_explore_title">Novi načini raziskovanja</string> <string name="onboarding_explore_text">Vstopite v zajčjo luknjo Wikipedije z neprestanim posodabljanjem vira raziskovanja. &lt;br/&gt; &lt;b&gt;Prilagodite&lt;/b&gt; vir svojim zanimanjem – pa naj bodo to zgodovinski dogodki &lt;b&gt;Na današnji dan&lt;/b&gt; ali metanje kocke z možnostjo &lt;b&gt;Naključno&lt;/b&gt;.</string> <string name="onboarding_reading_list_sync_title">Bralni seznami s sinhronizacijo</string> <string name="onboarding_reading_list_sync_text_v2">Ustvarjate lahko bralne sezname člankov, ki jih želite prebrati pozneje, tudi če niste povezani v splet. &lt;br/&gt;Za sinhronizacijo bralnih seznamov se prijavite v svoj račun v Wikipediji. &lt;a href=\"#login\"&gt;Pridružite se Wikipediji&lt;/a&gt;</string> <string name="onboarding_analytics_title">Pošiljajte anonimne podatke</string> <string name="onboarding_analytics_offline_text">Pomagajte izboljševati aplikacijo s tem, da nam sporočate, kako jo uporabljate. Zbrani podatki so anonimni. &lt;a href=\"#privacy\"&gt;Več o tem&lt;/a&gt;</string> <string name="onboarding_analytics_switch_title">Pošiljaj podatke o uporabi</string> <string name="onboarding_got_it">Razumem</string> <string name="onboarding_multilingual_secondary_text">Na vaši napravi smo našli naslednje:</string> <string name="onboarding_multilingual_add_language_text">Dodajte ali uredite jezike</string> <string name="onboarding_welcome_title_v2">Prosta enciklopedija\n… v več kot 300 jezikih</string> <string name="app_shortcuts_random">Naključno</string> <string name="app_shortcuts_continue_reading">Nadaljuj branje</string> <string name="app_shortcuts_search">Iskanje</string> <string name="on_this_day_card_title">Na današnji dan</string> <string name="more_events_text">Več na ta dan</string> <string name="events_count_text">%1$s dogodkov v letih %2$s–%3$d</string> <string name="this_year">To leto</string> <string name="on_this_day_dialog_next_month">Naslednji mesec</string> <string name="on_this_day_dialog_previous_month">Prejšnji mesec</string> <string name="on_this_day_open_date_picker">Odpri izbiralnik datumov</string> <plurals name="diff_years"> <item quantity="one">Prejšnje leto</item> <item quantity="two">Pred dvema letoma</item> <item quantity="few">Pred %d leti</item> <item quantity="other">Pred %d leti</item> </plurals> <string name="on_this_day_end_of_scroll_message">Potovali ste skozi čas 🚀</string> <string name="on_this_day_back_to_future">Nazaj v prihodnost</string> <string name="languages_list_activity_title">Dodaj jezik</string> <string name="languages_list_suggested_text">Predlagani</string> <string name="languages_list_all_text">Vsi jeziki</string> <string name="wikipedia_languages_title">Jeziki Wikipedije</string> <string name="wikipedia_languages_your_languages_text">Vaš jezik</string> <string name="wikipedia_languages_add_language_text">Dodaj jezik</string> <string name="wikipedia_languages_remove_text">Odstrani jezik</string> <string name="wikipedia_languages_remove_action_mode_title">Odstrani jezik</string> <plurals name="wikipedia_languages_remove_dialog_title"> <item quantity="one">Odstranim izbrani jezik?</item> <item quantity="two">Odstranim izbrana jezika</item> <item quantity="few">Odstranim izbrane jezike</item> <item quantity="other">Odstranim izbrane jezike?</item> </plurals> <string name="wikipedia_languages_remove_dialog_content">V viru Raziskovanje in hitrih filtrih iskanja boste videli samo vsebino za preostale jezike Wikipedije.</string> <string name="wikipedia_languages_remove_warning_dialog_title">Ne morem odstraniti vseh jezikov</string> <string name="wikipedia_languages_remove_warning_dialog_content">Ohranite vsaj en jezik Wikipedije, v katerem lahko pregledujete in berete vsebino.</string> <string name="more_language_options">več</string> <string name="add_wikipedia_languages_text">Dodaj jezike Wikipedije</string> <string name="dialog_of_remove_chinese_variants_from_app_lang_title">Želite med jeziki aplikacije odstraniti različico kitajščine?</string> <string name="dialog_of_remove_chinese_variants_from_app_lang_text">Trenutno imate med jeziki aplikacije tradicionalno in poenostavljeno različico kitajščine. Želite jezikovne nastavitve posodobiti?</string> <string name="dialog_of_remove_chinese_variants_from_app_lang_edit">Uredi jezike</string> <string name="dialog_of_remove_chinese_variants_from_app_lang_no">Ne, hvala</string> <string name="remove_language_dialog_cancel_button_text">Prekliči</string> <string name="remove_language_dialog_ok_button_text">V redu</string> <string name="remove_all_language_warning_dialog_ok_button_text">V redu</string> <string name="protected_page_warning_dialog_ok_button_text">V redu</string> <string name="account_editing_blocked_dialog_ok_button_text">V redu</string> <string name="edit_conflict_dialog_ok_button_text">V redu</string> <string name="reverted_edit_dialog_ok_button_text">V redu</string> <string name="account_editing_blocked_dialog_cancel_button_text">Prekliči</string> <string name="edit_type_all">Vsi prispevki</string> <string name="content_description_for_page_indicator">Stran %1$d od %2$d</string> <string name="wikitext_bold">Krepko</string> <string name="wikitext_italic">Ležeče</string> <string name="wikitext_underline">Podčrtano</string> <string name="wikitext_strikethrough">Prečrtano</string> <string name="wikitext_sup">Nadpisano</string> <string name="wikitext_sub">Podpisano</string> <string name="wikitext_large">Veliko besedilo</string> <string name="wikitext_small">Majhno besedilo</string> <string name="wikitext_code">Koda</string> <string name="wikitext_link">Povezava</string> <string name="wikitext_heading_n">Podnaslov %d</string> <string name="wikitext_formatting">Oblikovanje</string> <string name="wikitext_headings">Podnaslovi</string> <string name="wikitext_insert_media">Vstavi predstavnost</string> <string name="wikitext_bulleted_list">Označen seznam</string> <string name="wikitext_numbered_list">Oštevilčen seznam</string> <string name="wikitext_template">Predloga</string> <string name="wikitext_reference">Sklic</string> <string name="wikitext_preview_link">Predogled povezave</string> <string name="insert_media_title">Vstavi predstavnost</string> <string name="insert_media_search_description">Izberite datoteko iz Wikimedijine zbirke</string> <string name="insert_media_search_hint">Poišči predstavnost</string> <string name="insert_media_settings">Nastavitve predstavnosti</string> <string name="insert_media_settings_uploaded_image">Naložena slika</string> <string name="insert_media_settings_caption">Napis</string> <string name="insert_media_settings_caption_description">Oznaka, ki je prikazana poleg predmeta za vse bralce</string> <string name="insert_media_settings_alternative_text">Alternativno besedilo</string> <string name="insert_media_settings_alternative_text_description">Besedilni opis za bralce, ki ne morejo videti slike</string> <string name="insert_media_advanced_settings">Napredne nastavitve</string> <string name="insert_media_advanced_settings_wrap_image">Ovij besedilo okoli slike</string> <string name="insert_media_advanced_settings_image_position">Položaj slike</string> <string name="insert_media_advanced_settings_image_position_right">Desno</string> <string name="insert_media_advanced_settings_image_position_left">Levo</string> <string name="insert_media_advanced_settings_image_position_center">Usredinjeno</string> <string name="insert_media_advanced_settings_image_position_none">Brez</string> <string name="insert_media_advanced_settings_image_type">Vrsta slike</string> <string name="insert_media_advanced_settings_image_type_thumbnail">Sličica</string> <string name="insert_media_advanced_settings_image_type_frameless">Brez okvirja</string> <string name="insert_media_advanced_settings_image_type_frame">Okvir</string> <string name="insert_media_advanced_settings_image_type_basic">Osnovna</string> <string name="insert_media_advanced_settings_image_type_tip">Nastavite lahko, kako se ta predstavnostni predmet prikaže na strani. Zaradi skladnosti z drugimi stranmi je v skoraj vseh primerih najustreznejša oblika sličice.</string> <string name="insert_media_advanced_settings_image_size">Velikost slike</string> <string name="insert_media_advanced_settings_image_size_default">Privzeto</string> <string name="insert_media_advanced_settings_image_size_custom">Po meri</string> <string name="insert_media_advanced_settings_image_size_custom_width">Širina</string> <string name="insert_media_advanced_settings_image_size_custom_height">Višina</string> <string name="insert_media_advanced_settings_image_size_custom_px">točk</string> <string name="insert_media_insert_button">Vstavi</string> <string name="main_drawer_help">Pomoč</string> <string name="main_drawer_login">Prijavite se / pridružite se Wikipediji</string> <string name="main_tooltip_text">Pozdravljeni, %s, ste vedeli, da lahko Wikipedijo ureja vsakdo?</string> <string name="main_tooltip_text_v2">Ste vedeli, da lahko Wikipedijo ureja vsakdo?</string> <string name="main_tooltip_action_button">Začnimo</string> <string name="main_tooltip_watchlist_title">Spisek nadzorov</string> <string name="main_tooltip_watchlist_text">Članke in strani, ki ste jih dodali na svoj spisek nadzorov, lahko spremljate v meniju Več pod &lt;b&gt;Spisek nadzorov&lt;/b&gt;.</string> <string name="custom_date_picker_dialog_ok_button_text">V redu</string> <string name="text_input_dialog_ok_button_text">V redu</string> <string name="text_input_dialog_cancel_button_text">Prekliči</string> <string name="custom_date_picker_dialog_cancel_button_text">Prekliči</string> <string name="talk_title">Pogovor</string> <string name="talk_user_title">Pogovor: %s</string> <string name="talk_new_topic">Nova tema</string> <string name="talk_new_topic_submitted">Tema objavljena.</string> <string name="talk_page_empty">Ta pogovorna stran je prazna.</string> <string name="talk_add_reply">Odgovori</string> <string name="talk_no_subject">(Brez predmeta)</string> <string name="talk_reply_subject">Tema</string> <string name="talk_reply_hint">Sestavite odgovor</string> <string name="talk_message_hint">Sestavi sporočilo</string> <string name="talk_message_empty">Sporočilo ne sme biti prazno.</string> <string name="talk_subject_empty">Predmet ne sme biti prazen.</string> <string name="talk_response_submitted">Odgovor objavljen.</string> <string name="talk_snackbar_undo">Razveljavi</string> <string name="talk_last_modified">&lt;b&gt;Zadnji/a spremenil/a %1$s&lt;/b&gt; uporabnik/ca %2$s</string> <string name="talk_snackbar_survey_text">Hvala za uporabo pogovornih strani. Ali ste nam pripravljeni izboljšati aplikacijo s sodelovanjem v anketi?</string> <string name="talk_snackbar_survey_action_text">Začnimo</string> <string name="talk_share_discussion_subject">Wikipedija – pogovor o temi pogovorne strani «%s«</string> <string name="talk_share_talk_page">Wikipedija – pogovori na pogovorni strani</string> <string name="talk_edit_disclaimer">To je pogovorna stran. Prosimo, upoštevajte smernice za pogovorne strani in komentarje pri urejanju vikibesedila podpišite s štirimi tildami: ~~~~.&lt;br&gt;&lt;br&gt;&lt;a href=\"https://sl.wikipedia.org/wiki/Wikipedija:Smernice za pogovorne strani\"&gt;Wikipedija:Smernice za pogovorne strani&lt;/a&gt;</string> <string name="talk_search_hint">Preišči obvestila</string> <string name="talk_search_topics_hint">Preišči teme</string> <string name="talk_search_find_in_talk_topics_hint">Poišči v temi pogovorne strani</string> <string name="talk_overflow_sort_by">Razvrsti po</string> <string name="talk_overflow_sort_date_published">Datum objave</string> <string name="talk_overflow_sort_date_updated">Datum posodobitve</string> <string name="talk_overflow_sort_topic_name">Naslov teme</string> <plurals name="talk_show_replies_count"> <item quantity="one">Prikaži odgovor</item> <item quantity="two">Prikaži odgovora</item> <item quantity="few">Prikaži odgovore (%d)</item> <item quantity="other">Prikaži odgovore (%d)</item> </plurals> <plurals name="talk_hide_replies_count"> <item quantity="one">Skrij odgovor</item> <item quantity="two">Skrij odgovora</item> <item quantity="few">Skrij odgovore (%d)</item> <item quantity="other">Skrij odgovore (%d)</item> </plurals> <string name="talk_thread_subscribed_to">Naročeni ste na »%s«</string> <string name="talk_thread_unsubscribed_from">Odjavljeni ste od »%s«</string> <string name="talk_list_item_overflow_subscribe">Naroči se</string> <string name="talk_list_item_overflow_subscribed">Naročeni</string> <string name="talk_list_item_overflow_mark_as_read">Označi kot prebrano</string> <string name="talk_list_item_overflow_mark_as_unread">Označi kot neprebrano</string> <string name="talk_list_item_overflow_share">Deli</string> <string name="talk_list_item_last_comment_date">Zadnji komentar: %s</string> <string name="talk_list_item_reply_icon_content_description">Skupno odgovorov</string> <string name="talk_list_item_user_icon_content_description">Simbol uporabnika</string> <string name="talk_list_item_swipe_mark_as_read">Prebrano</string> <string name="talk_list_item_swipe_mark_as_unread">Neprebrano</string> <string name="talk_login_to_subscribe_dialog_title">Za naročanje na teme se prijavite</string> <string name="talk_login_to_subscribe_dialog_content">Naročila na teme vam omogočajo prejemanje obvestil o novih komentarjih pri posameznih temah. Da se naročite na temo, si ustvarite račun ali se prijavite v svoj Wikimedia račun.</string> <string name="talk_archived_title">Arhiv pogovorne strani: %s</string> <string name="menu_option_share_talk_discussion">Deli pogovor</string> <string name="menu_option_share_talk_page">Deli pogovorno stran</string> <string name="menu_option_share_edit">Deli urejanje</string> <string name="menu_option_user_contributions">Prispevki uporabnika/ce %s</string> <string name="menu_option_edit_source">Uredi vir</string> <string name="menu_option_user_page">Uporabniška stran uporabnika/ce %s</string> <string name="menu_option_find_in_talk_page_topic">Poišči v temi pogovorne strani</string> <string name="menu_option_copy_link_to_clipboard">Kopiraj povezavo v odložišče</string> <string name="talk_menu_copy_text">Kopiraj besedilo</string> <string name="talk_menu_expand_threads">Razširi niti</string> <string name="talk_menu_collapse_threads">Strni niti</string> <string name="watchlist_details_watching_label">Spremljam</string> <string name="watchlist_details_watch_label">Opazuj</string> <string name="watchlist_details_next_edit">Naslednje urejanje</string> <string name="watchlist_details_prev_edit">Prejšnje urejanje</string> <string name="thank_label">Zahvala</string> <string name="view_user_page">Ogled uporabnikove strani</string> <string name="thank_dialog_title_text">Javno se zahvalite</string> <string name="thank_dialog_text">Zahvale so preprost način za izražanje priznanja za delo urejevalca v Wikipediji. Zahval ni mogoče razveljaviti in so javno razvidne.</string> <string name="thank_dialog_positive_button_text">Pošlji zahvalo</string> <string name="thank_dialog_negative_button_text">Prekliči</string> <string name="thank_success_message">Uporabniku/ci %s ste poslali zahvalo 👍</string> <string name="menu_option_view_user_profile">Ogled uporabnikove strani</string> <string name="menu_option_view_user_talk">Ogled pogovorne strani</string> <string name="menu_option_view_user_contributions">Ogled uporabnikovih prispevkov</string> <string name="revision_diff_compare">Primerjava redakcij</string> <string name="revision_diff_compare_title">Primerjava redakcij: %s</string> <string name="revision_diff_from">Od:</string> <string name="revision_diff_to">Do:</string> <string name="revision_diff_line_num">Vrstica %d</string> <string name="revision_diff_line_nums">Vrstice %d–%d</string> <string name="revision_diff_lines_from_to">Vrstice %1$d–%2$d</string> <string name="revision_diff_line_added">Vrstica dodana</string> <string name="revision_diff_line_removed">Vrstica odstranjena</string> <string name="revision_diff_paragraph_added">Dodani odstavek</string> <string name="revision_diff_paragraph_removed">Odstavek odstranjen</string> <string name="revision_undo_title">Razveljavi urejanje</string> <string name="revision_undo_message">To bo razveljavilo spremembe v tukaj prikazani(h) redakciji(ah).</string> <string name="revision_undo_reason">Za nadaljevanje navedite razlog za razveljavitev tega urejanja:</string> <string name="revision_undo_success">Redakcija je bila razveljavljena.</string> <string name="revision_rollback_dialog_title">Ali res želite vrniti urejanje?</string> <string name="revision_rollback_success">Urejanje vrnjeno.</string> <string name="revision_compare_button">Primerjaj</string> <string name="revision_compare_two_only">Izberete lahko samo dve redakciji.</string> <string name="watchlist_page_add_to_watchlist_snackbar">Na svoj spisek nadzorov ste dodali stran %1$s in njeno pogovorno stran; %2$s.</string> <string name="watchlist_page_add_to_watchlist_snackbar_action">Spremeni</string> <string name="watchlist_page_add_to_watchlist_snackbar_period_permanently">trajno</string> <string name="watchlist_page_add_to_watchlist_snackbar_period_for_one_week">za 1 teden</string> <string name="watchlist_page_add_to_watchlist_snackbar_period_for_one_month">za 1 mesec</string> <string name="watchlist_page_add_to_watchlist_snackbar_period_for_three_months">za 3 mesece</string> <string name="watchlist_page_add_to_watchlist_snackbar_period_for_six_months">za 6 mesecev</string> <string name="watchlist_page_removed_from_watchlist_snackbar">S svojega spiska nadzorov ste odstranili stran %s in njeno pogovorno stran.</string> <string name="watchlist_expiry_dialog_title">Izberite čas spremljanja na spisku nadzorov</string> <string name="watchlist_expiry_dialog_permanent">Trajno</string> <string name="watchlist_expiry_dialog_one_week">1 teden</string> <string name="watchlist_expiry_dialog_one_month">1 mesec</string> <string name="watchlist_expiry_dialog_three_months">3 mesece</string> <string name="watchlist_expiry_dialog_six_months">6 mesecev</string> <string name="watchlist_empty">Na spisku nadzorov nimate nobenega članka.</string> <string name="watchlist_filter_all">Vse</string> <string name="watchlist_filter_talk">Pogovor</string> <string name="watchlist_filter_pages">Strani</string> <string name="watchlist_filter_other">Drugo</string> <string name="watchlist_page_moved">Prestavljeno</string> <string name="watchlist_page_protected">Zaščiteno</string> <string name="watchlist_page_deleted">Izbrisano</string> <string name="preview_edit_title">Predogled urejanja</string> <string name="preview_edit_summarize_edit_title">Povzetek urejanja</string> <string name="preview_edit_summarize_edit_hint">Kako ste izboljšali to stran?</string> <string name="preview_edit_minor_edit">Manjše urejanje</string> <string name="preview_edit_watch_this_page">Opazuj stran</string> <string name="preview_edit_learn_more">Več o povzetkih urejanja</string> <string name="action_item_categories">Kategorije</string> <string name="page_no_categories">Ta stran še ni uvrščena v nobeno kategorijo.</string> <string name="category_tab_articles">Članki</string> <string name="category_tab_subcategories">Podkategorije</string> <string name="category_empty">V tej kategoriji ni najdenih člankov.</string> <string name="subcategory_empty">V tej kategoriji ni najdenih podkategorij.</string> <string name="search_namespaces">Imenski prostori</string> <string name="revision_initial_none">Brez (to je prva redakcija)</string> <string name="user_contrib_activity_title">Prispevki uporabnika/ce %s</string> <string name="archive_empty">Ni najdenih arhivskih strani.</string> <string name="user_contrib_filter_ns">Filtriraj po imenskem prostoru</string> <string name="user_contrib_filter_all">Vsi imenski prostori</string> <string name="user_contrib_filter_ns_header">Filter imenskega prostora</string> <string name="namespace_article">Članek</string> <string name="user_contrib_current">trenutno</string> <string name="media_playback_error">Napaka pri predvajanju predstavnosti.</string> <string name="user_contrib_menu_label">Prispevki</string> <string name="user_contrib_filter_activity_title">Filtriraj prispevke</string> <string name="shareable_reading_lists_import_dialog_title">Uvozi bralni seznam</string> <string name="shareable_reading_lists_import_dialog_content">Ali res želite uvoziti ta bralni seznam?</string> <string name="shareable_reading_lists_import_dialog_confirm">Uvozi</string> <string name="shareable_reading_lists_import_dialog_cancel">Prekliči</string> <string name="shareable_reading_lists_new_indicator">*novo*</string> <string name="shareable_reading_lists_new_install_dialog_title">Z vami je bil deljen bralni seznam.</string> <string name="shareable_reading_lists_new_install_dialog_content">Opazili smo, da je bil z vami deljen bralni seznam. Če si želite ogledati ta seznam v tej aplikaciji, se vrnite na prvotno sporočilo in znova tapnite povezavo, ki je bila deljena z vami.</string> <string name="shareable_reading_lists_new_install_dialog_got_it">Razumem</string> <string name="shareable_reading_lists_new_imported_list_title">Uvoženi seznam</string> <plurals name="shareable_reading_lists_import_dialog_content_articles"> <item quantity="one">%d članek</item> <item quantity="two">%d članka</item> <item quantity="few">%d članki</item> <item quantity="other">%d člankov</item> </plurals> <string name="reading_list_share_menu_label">Deli ...</string> <string name="reading_list_share_message">Živijo! S tabo želim deliti svoj bralni seznam »%s«:</string> <string name="reading_list_share_survey_title">Nam lahko pomagate izboljšati to funkcijo?</string> <string name="reading_list_share_survey_body">Deljenje in izvoz bralnih seznamov sta preizkusni funkciji in potrebujemo vaše povratne informacije, da ju izboljšamo ali odstranimo.</string> </resources>
{ "content_hash": "7d6715229aff317c5c731210a6d9f4cc", "timestamp": "", "source": "github", "line_count": 1354, "max_line_length": 642, "avg_line_length": 82.05096011816839, "alnum_prop": 0.7609926460660504, "repo_name": "wikimedia/apps-android-wikipedia", "id": "57e35c5906dc357761bbdde44ff8e6ab96f5af54", "size": "111940", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "app/src/main/res/values-sl/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "68009" }, { "name": "Jinja", "bytes": "533" }, { "name": "Kotlin", "bytes": "2849948" }, { "name": "Python", "bytes": "23673" }, { "name": "Shell", "bytes": "521" } ], "symlink_target": "" }
@interface ViewController : UIViewController @end
{ "content_hash": "a87c07317640ee4bf1cb116f002dd042", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 44, "avg_line_length": 10.6, "alnum_prop": 0.7924528301886793, "repo_name": "djfitz/RFSurvey", "id": "1f0c2a20575a53a1fb0ef635460d4f89d0d567cc", "size": "210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RFSurvey/ViewController.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "5320" } ], "symlink_target": "" }
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8"> <title>pause</title> <link href="../../../images/logo-icon.svg" rel="icon" type="image/svg"> <script>var pathToRoot = "../../../";</script> <script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script> <link href="../../../styles/style.css" rel="Stylesheet"> <link href="../../../styles/logo-styles.css" rel="Stylesheet"> <link href="../../../styles/jetbrains-mono.css" rel="Stylesheet"> <link href="../../../styles/main.css" rel="Stylesheet"> <script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script> <script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script> <script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script> <script type="text/javascript" src="../../../scripts/main.js" async="async"></script> </head> <body> <div id="container"> <div id="leftColumn"> <div id="logo"></div> <div id="paneSearch"></div> <div id="sideMenu"></div> </div> <div id="main"> <div id="leftToggler"><span class="icon-toggler"></span></div> <script type="text/javascript" src="../../../scripts/pages.js"></script> <script type="text/javascript" src="../../../scripts/main.js"></script> <div class="main-content" id="content" pageIds="org.hexworks.zircon.internal.application/LibgdxApplication/pause/#/PointingToDeclaration//-1188598541"> <div class="navigation-wrapper" id="navigation-wrapper"> <div class="breadcrumbs"><a href="../../index.html">zircon.jvm.libgdx</a>/<a href="../index.html">org.hexworks.zircon.internal.application</a>/<a href="index.html">LibgdxApplication</a>/<a href="pause.html">pause</a></div> <div class="pull-right d-flex"> <div id="searchBar"></div> </div> </div> <div class="cover "> <h1 class="cover"><span>pause</span></h1> </div> <div class="divergent-group" data-filterable-current=":zircon.jvm.libgdx:dokkaHtml/main" data-filterable-set=":zircon.jvm.libgdx:dokkaHtml/main"><div class="with-platform-tags"><span class="pull-right"></span></div> <div> <div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.jvm.libgdx:dokkaHtml/main"><div class="symbol monospace">open override fun <a href="pause.html">pause</a>()<span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div> </div> </div> <h2 class="">Sources</h2> <div class="table" data-togglable="Sources"><a data-name="%5Borg.hexworks.zircon.internal.application%2FLibgdxApplication%2Fpause%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-1188598541" anchor-label="https://github.com/Hexworks/zircon/tree/master/zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/application/LibgdxApplication.kt#L61" id="%5Borg.hexworks.zircon.internal.application%2FLibgdxApplication%2Fpause%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-1188598541" data-filterable-set=":zircon.jvm.libgdx:dokkaHtml/main"></a> <div class="table-row" data-filterable-current=":zircon.jvm.libgdx:dokkaHtml/main" data-filterable-set=":zircon.jvm.libgdx:dokkaHtml/main"> <div class="main-subrow keyValue "> <div class=""><span class="inline-flex"><a href="https://github.com/Hexworks/zircon/tree/master/zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/application/LibgdxApplication.kt#L61">(source)</a><span class="anchor-wrapper"><span class="anchor-icon" pointing-to="%5Borg.hexworks.zircon.internal.application%2FLibgdxApplication%2Fpause%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-1188598541"></span> <div class="copy-popup-wrapper "><span class="copy-popup-icon"></span><span>Link copied to clipboard</span></div> </span></span></div> <div></div> </div> </div> </div> </div> <div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div> </div> </div> </body> </html>
{ "content_hash": "560275d89d79df3af8f5134e59b7dd69", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 558, "avg_line_length": 77.14754098360656, "alnum_prop": 0.6519337016574586, "repo_name": "Hexworks/zircon", "id": "9a72f19b0845bc1f496e6c3c6472bca8c8a835fe", "size": "4707", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/2021.1.0-RELEASE-KOTLIN/zircon.jvm.libgdx/zircon.jvm.libgdx/org.hexworks.zircon.internal.application/-libgdx-application/pause.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "121457" }, { "name": "Kotlin", "bytes": "1792092" }, { "name": "Shell", "bytes": "152" } ], "symlink_target": "" }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Mike Krüger" email="mike@icsharpcode.net"/> // <version>$Revision: 3205 $</version> // </file> using System; using System.Collections.Generic; using System.Diagnostics; using WorldBankBBS.ICSharpCode.TextEditor.Src.Document.FoldingStrategy; using WorldBankBBS.ICSharpCode.TextEditor.Src.Document.HighlightingStrategy; using WorldBankBBS.ICSharpCode.TextEditor.Src.Document.LineManager; using WorldBankBBS.ICSharpCode.TextEditor.Src.Document.TextBufferStrategy; using WorldBankBBS.ICSharpCode.TextEditor.Src.Undo; namespace WorldBankBBS.ICSharpCode.TextEditor.Src.Document { /// <summary> /// Describes the caret marker /// </summary> public enum LineViewerStyle { /// <summary> /// No line viewer will be displayed /// </summary> None, /// <summary> /// The row in which the caret is will be marked /// </summary> FullRow } /// <summary> /// Describes the indent style /// </summary> public enum IndentStyle { /// <summary> /// No indentation occurs /// </summary> None, /// <summary> /// The indentation from the line above will be /// taken to indent the curent line /// </summary> Auto, /// <summary> /// Inteligent, context sensitive indentation will occur /// </summary> Smart } /// <summary> /// Describes the bracket highlighting style /// </summary> public enum BracketHighlightingStyle { /// <summary> /// Brackets won't be highlighted /// </summary> None, /// <summary> /// Brackets will be highlighted if the caret is on the bracket /// </summary> OnBracket, /// <summary> /// Brackets will be highlighted if the caret is after the bracket /// </summary> AfterBracket } /// <summary> /// Describes the selection mode of the text area /// </summary> public enum DocumentSelectionMode { /// <summary> /// The 'normal' selection mode. /// </summary> Normal, /// <summary> /// Selections will be added to the current selection or new /// ones will be created (multi-select mode) /// </summary> Additive } /// <summary> /// The default <see cref="IDocument"/> implementation. /// </summary> internal sealed class DefaultDocument : IDocument { bool readOnly = false; LineManager.LineManager lineTrackingStrategy; BookmarkManager.BookmarkManager bookmarkManager; ITextBufferStrategy textBufferStrategy; //IFormattingStrategy formattingStrategy; FoldingManager foldingManager; UndoStack undoStack = new UndoStack(); ITextEditorProperties textEditorProperties = new DefaultTextEditorProperties(); MarkerStrategy.MarkerStrategy markerStrategy; public LineManager.LineManager LineManager { get { return lineTrackingStrategy; } set { lineTrackingStrategy = value; } } public event EventHandler<LineLengthChangeEventArgs> LineLengthChanged { add { lineTrackingStrategy.LineLengthChanged += value; } remove { lineTrackingStrategy.LineLengthChanged -= value; } } public event EventHandler<LineCountChangeEventArgs> LineCountChanged { add { lineTrackingStrategy.LineCountChanged += value; } remove { lineTrackingStrategy.LineCountChanged -= value; } } public event EventHandler<LineEventArgs> LineDeleted { add { lineTrackingStrategy.LineDeleted += value; } remove { lineTrackingStrategy.LineDeleted -= value; } } public MarkerStrategy.MarkerStrategy MarkerStrategy { get { return markerStrategy; } set { markerStrategy = value; } } public ITextEditorProperties TextEditorProperties { get { return textEditorProperties; } set { textEditorProperties = value; } } public UndoStack UndoStack { get { return undoStack; } } public IList<LineSegment> LineSegmentCollection { get { return lineTrackingStrategy.LineSegmentCollection; } } public bool ReadOnly { get { return readOnly; } set { readOnly = value; } } public ITextBufferStrategy TextBufferStrategy { get { return textBufferStrategy; } set { textBufferStrategy = value; } } //public IFormattingStrategy FormattingStrategy { // get { // return formattingStrategy; // } // set { // formattingStrategy = value; // } //} public FoldingManager FoldingManager { get { return foldingManager; } set { foldingManager = value; } } public IHighlightingStrategy HighlightingStrategy { get { return lineTrackingStrategy.HighlightingStrategy; } set { lineTrackingStrategy.HighlightingStrategy = value; } } public int TextLength { get { return textBufferStrategy.Length; } } public BookmarkManager.BookmarkManager BookmarkManager { get { return bookmarkManager; } set { bookmarkManager = value; } } public string TextContent { get { return GetText(0, textBufferStrategy.Length); } set { Debug.Assert(textBufferStrategy != null); Debug.Assert(lineTrackingStrategy != null); OnDocumentAboutToBeChanged(new DocumentEventArgs(this, 0, 0, value)); textBufferStrategy.SetContent(value); lineTrackingStrategy.SetContent(value); undoStack.ClearAll(); OnDocumentChanged(new DocumentEventArgs(this, 0, 0, value)); OnTextContentChanged(EventArgs.Empty); } } public void Insert(int offset, string text) { if (readOnly) { return; } OnDocumentAboutToBeChanged(new DocumentEventArgs(this, offset, -1, text)); textBufferStrategy.Insert(offset, text); lineTrackingStrategy.Insert(offset, text); undoStack.Push(new UndoableInsert(this, offset, text)); OnDocumentChanged(new DocumentEventArgs(this, offset, -1, text)); } public void Remove(int offset, int length) { if (readOnly) { return; } OnDocumentAboutToBeChanged(new DocumentEventArgs(this, offset, length)); undoStack.Push(new UndoableDelete(this, offset, GetText(offset, length))); textBufferStrategy.Remove(offset, length); lineTrackingStrategy.Remove(offset, length); OnDocumentChanged(new DocumentEventArgs(this, offset, length)); } public void Replace(int offset, int length, string text) { if (readOnly) { return; } OnDocumentAboutToBeChanged(new DocumentEventArgs(this, offset, length, text)); undoStack.Push(new UndoableReplace(this, offset, GetText(offset, length), text)); textBufferStrategy.Replace(offset, length, text); lineTrackingStrategy.Replace(offset, length, text); OnDocumentChanged(new DocumentEventArgs(this, offset, length, text)); } public char GetCharAt(int offset) { return textBufferStrategy.GetCharAt(offset); } public string GetText(int offset, int length) { #if DEBUG if (length < 0) throw new ArgumentOutOfRangeException("length", length, "length < 0"); #endif return textBufferStrategy.GetText(offset, length); } public string GetText(ISegment segment) { return GetText(segment.Offset, segment.Length); } public int TotalNumberOfLines { get { return lineTrackingStrategy.TotalNumberOfLines; } } public int GetLineNumberForOffset(int offset) { return lineTrackingStrategy.GetLineNumberForOffset(offset); } public LineSegment GetLineSegmentForOffset(int offset) { return lineTrackingStrategy.GetLineSegmentForOffset(offset); } public LineSegment GetLineSegment(int line) { return lineTrackingStrategy.GetLineSegment(line); } public int GetFirstLogicalLine(int lineNumber) { return lineTrackingStrategy.GetFirstLogicalLine(lineNumber); } public int GetLastLogicalLine(int lineNumber) { return lineTrackingStrategy.GetLastLogicalLine(lineNumber); } public int GetVisibleLine(int lineNumber) { return lineTrackingStrategy.GetVisibleLine(lineNumber); } // public int GetVisibleColumn(int logicalLine, int logicalColumn) // { // return lineTrackingStrategy.GetVisibleColumn(logicalLine, logicalColumn); // } // public int GetNextVisibleLineAbove(int lineNumber, int lineCount) { return lineTrackingStrategy.GetNextVisibleLineAbove(lineNumber, lineCount); } public int GetNextVisibleLineBelow(int lineNumber, int lineCount) { return lineTrackingStrategy.GetNextVisibleLineBelow(lineNumber, lineCount); } public TextLocation OffsetToPosition(int offset) { int lineNr = GetLineNumberForOffset(offset); LineSegment line = GetLineSegment(lineNr); return new TextLocation(offset - line.Offset, lineNr); } public int PositionToOffset(TextLocation p) { if (p.Y >= this.TotalNumberOfLines) { return 0; } LineSegment line = GetLineSegment(p.Y); return Math.Min(this.TextLength, line.Offset + Math.Min(line.Length, p.X)); } public void UpdateSegmentListOnDocumentChange<T>(List<T> list, DocumentEventArgs e) where T : ISegment { int removedCharacters = e.Length > 0 ? e.Length : 0; int insertedCharacters = e.Text != null ? e.Text.Length : 0; for (int i = 0; i < list.Count; ++i) { ISegment s = list[i]; int segmentStart = s.Offset; int segmentEnd = s.Offset + s.Length; if (e.Offset <= segmentStart) { segmentStart -= removedCharacters; if (segmentStart < e.Offset) segmentStart = e.Offset; } if (e.Offset < segmentEnd) { segmentEnd -= removedCharacters; if (segmentEnd < e.Offset) segmentEnd = e.Offset; } Debug.Assert(segmentStart <= segmentEnd); if (segmentStart == segmentEnd) { list.RemoveAt(i); --i; continue; } if (e.Offset <= segmentStart) segmentStart += insertedCharacters; if (e.Offset < segmentEnd) segmentEnd += insertedCharacters; Debug.Assert(segmentStart < segmentEnd); s.Offset = segmentStart; s.Length = segmentEnd - segmentStart; } } void OnDocumentAboutToBeChanged(DocumentEventArgs e) { DocumentAboutToBeChanged?.Invoke(this, e); } void OnDocumentChanged(DocumentEventArgs e) { DocumentChanged?.Invoke(this, e); } public event DocumentEventHandler DocumentAboutToBeChanged; public event DocumentEventHandler DocumentChanged; // UPDATE STUFF List<TextAreaUpdate> updateQueue = new List<TextAreaUpdate>(); public List<TextAreaUpdate> UpdateQueue { get { return updateQueue; } } public void RequestUpdate(TextAreaUpdate update) { if (updateQueue.Count == 1 && updateQueue[0].TextAreaUpdateType == TextAreaUpdateType.WholeTextArea) { // if we're going to update the whole text area, we don't need to store detail updates return; } if (update.TextAreaUpdateType == TextAreaUpdateType.WholeTextArea) { // if we're going to update the whole text area, we don't need to store detail updates updateQueue.Clear(); } updateQueue.Add(update); } public void CommitUpdate() { UpdateCommited?.Invoke(this, EventArgs.Empty); } void OnTextContentChanged(EventArgs e) { TextContentChanged?.Invoke(this, e); } public event EventHandler UpdateCommited; public event EventHandler TextContentChanged; [Conditional("DEBUG")] internal static void ValidatePosition(IDocument document, TextLocation position) { document.GetLineSegment(position.Line); } } }
{ "content_hash": "cbcbbf2d58d2a6651ee1d0e68fa1f3a1", "timestamp": "", "source": "github", "line_count": 451, "max_line_length": 105, "avg_line_length": 25.747228381374722, "alnum_prop": 0.6873062349293834, "repo_name": "sharpninja/WorldBankBBS", "id": "2147a1c47a1fdc705cfeb52b9e245a003de395da", "size": "11615", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WorldBankBBS.ICSharpCode.TextEditor/Src/Document/DefaultDocument.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "28035" }, { "name": "ActionScript", "bytes": "26638" }, { "name": "C", "bytes": "76419" }, { "name": "C#", "bytes": "1911556" }, { "name": "CSS", "bytes": "15617" }, { "name": "HTML", "bytes": "81655" }, { "name": "JavaScript", "bytes": "2494755" }, { "name": "M4", "bytes": "15056" }, { "name": "Makefile", "bytes": "6041" }, { "name": "Python", "bytes": "26221" }, { "name": "Shell", "bytes": "10539" }, { "name": "Visual Basic", "bytes": "19769" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b04b732d1ecf1b4326c21f814e38c014", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "982b52d9c87b1df5338e658cbd860f7bc624f280", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Solanum/Solanum trachytrichium/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
include_recipe "rundeck::server_dependencies" include_recipe "rundeck::server_install" include_recipe "rundeck::apache"
{ "content_hash": "673a4e9f2c3d8a9048b9a62fe47f5db2", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 45, "avg_line_length": 40, "alnum_prop": 0.8083333333333333, "repo_name": "marthag8/rundeck", "id": "bcef6c45f46a4048ec8267b97bd6ff98cc5e20e0", "size": "120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "recipes/server.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "24792" }, { "name": "Ruby", "bytes": "31666" }, { "name": "Shell", "bytes": "769" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="7dp"></corners> <stroke android:width="0dp" android:color="@android:color/black" android:height="10dp" /> <solid android:color="@color/colorPrimary"/> </shape>
{ "content_hash": "67c304a25fb8eb756e7d181cf6c97f8f", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 70, "avg_line_length": 34.9, "alnum_prop": 0.6045845272206304, "repo_name": "cruzj6/MyHealthcareAssistant", "id": "724464b89d0f11fd62889c933615c824313a4488", "size": "349", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/rounded_back.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "208947" } ], "symlink_target": "" }
CFLAGS += ${EXTRA_CFLAGS} CXXFLAGS += ${EXTRA_CXXFLAGS} LDFLAGS += $(EXTRA_LDFLAGS) MACHINE ?= $(shell uname -m) ARFLAGS = rs ifneq ($(MAKECMDGOALS),dbg) OPT += -O2 -fno-omit-frame-pointer ifneq ($(MACHINE),ppc64) # ppc64 doesn't support -momit-leaf-frame-pointer OPT += -momit-leaf-frame-pointer endif else # intentionally left blank endif ifeq ($(MAKECMDGOALS),shared_lib) OPT += -DNDEBUG endif ifeq ($(MAKECMDGOALS),static_lib) OPT += -DNDEBUG endif #----------------------------------------------- include src.mk AM_DEFAULT_VERBOSITY = 0 AM_V_GEN = $(am__v_GEN_$(V)) am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_$(V)) am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) am__v_at_0 = @ am__v_at_1 = AM_V_CC = $(am__v_CC_$(V)) am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_$(V)) am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = AM_V_AR = $(am__v_AR_$(V)) am__v_AR_ = $(am__v_AR_$(AM_DEFAULT_VERBOSITY)) am__v_AR_0 = @echo " AR " $@; am__v_AR_1 = AM_LINK = $(AM_V_CCLD)$(CXX) $^ $(EXEC_LDFLAGS) -o $@ $(LDFLAGS) $(COVERAGEFLAGS) # detect what platform we're building on dummy := $(shell (export ROCKSDB_ROOT="$(CURDIR)"; "$(CURDIR)/build_tools/build_detect_platform" "$(CURDIR)/make_config.mk")) # this file is generated by the previous line to set build flags and sources include make_config.mk ifneq ($(PLATFORM), IOS) CFLAGS += -g CXXFLAGS += -g else # no debug info for IOS, that will make our library big OPT += -DNDEBUG endif ifneq ($(filter -DROCKSDB_LITE,$(OPT)),) # found CFLAGS += -fno-exceptions CXXFLAGS += -fno-exceptions endif # ASAN doesn't work well with jemalloc. If we're compiling with ASAN, we should use regular malloc. ifdef COMPILE_WITH_ASAN DISABLE_JEMALLOC=1 EXEC_LDFLAGS += -fsanitize=address PLATFORM_CCFLAGS += -fsanitize=address PLATFORM_CXXFLAGS += -fsanitize=address endif # TSAN doesn't work well with jemalloc. If we're compiling with TSAN, we should use regular malloc. ifdef COMPILE_WITH_TSAN DISABLE_JEMALLOC=1 EXEC_LDFLAGS += -fsanitize=thread -pie PLATFORM_CCFLAGS += -fsanitize=thread -fPIC -DROCKSDB_TSAN_RUN PLATFORM_CXXFLAGS += -fsanitize=thread -fPIC -DROCKSDB_TSAN_RUN endif ifndef DISABLE_JEMALLOC EXEC_LDFLAGS := $(JEMALLOC_LIB) $(EXEC_LDFLAGS) PLATFORM_CXXFLAGS += $(JEMALLOC_INCLUDE) -DHAVE_JEMALLOC PLATFORM_CCFLAGS += $(JEMALLOC_INCLUDE) -DHAVE_JEMALLOC endif export GTEST_THROW_ON_FAILURE=1 GTEST_HAS_EXCEPTIONS=1 GTEST_DIR = ./third-party/gtest-1.7.0/fused-src PLATFORM_CCFLAGS += -isystem $(GTEST_DIR) PLATFORM_CXXFLAGS += -isystem $(GTEST_DIR) # This (the first rule) must depend on "all". default: all #------------------------------------------------- # make install related stuff INSTALL_PATH ?= /usr/local uninstall: rm -rf $(INSTALL_PATH)/include/rocksdb \ $(INSTALL_PATH)/lib/$(LIBRARY) \ $(INSTALL_PATH)/lib/$(SHARED) install: install -d $(INSTALL_PATH)/lib for header_dir in `find "include/rocksdb" -type d`; do \ install -d $(INSTALL_PATH)/$$header_dir; \ done for header in `find "include/rocksdb" -type f -name *.h`; do \ install -C -m 644 $$header $(INSTALL_PATH)/$$header; \ done [ ! -e $(LIBRARY) ] || install -C -m 644 $(LIBRARY) $(INSTALL_PATH)/lib [ ! -e $(SHARED) ] || install -C -m 644 $(SHARED) $(INSTALL_PATH)/lib #------------------------------------------------- WARNING_FLAGS = -W -Wextra -Wall -Wsign-compare -Wshadow \ -Wno-unused-parameter ifndef DISABLE_WARNING_AS_ERROR WARNING_FLAGS += -Werror endif CFLAGS += $(WARNING_FLAGS) -I. -I./include $(PLATFORM_CCFLAGS) $(OPT) CXXFLAGS += $(WARNING_FLAGS) -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT) -Woverloaded-virtual -Wnon-virtual-dtor -Wno-missing-field-initializers LDFLAGS += $(PLATFORM_LDFLAGS) date := $(shell date +%F) git_sha := $(shell git describe HEAD 2>/dev/null) gen_build_version = \ printf '%s\n' \ '\#include "build_version.h"' \ 'const char* rocksdb_build_git_sha = \ "rocksdb_build_git_sha:$(git_sha)";' \ 'const char* rocksdb_build_git_date = \ "rocksdb_build_git_date:$(date)";' \ 'const char* rocksdb_build_compile_date = __DATE__;' # Record the version of the source that we are compiling. # We keep a record of the git revision in this file. It is then built # as a regular source file as part of the compilation process. # One can run "strings executable_filename | grep _build_" to find # the version of the source that we used to build the executable file. util/build_version.cc: $(AM_V_GEN)$(gen_build_version) > $@.tmp $(AM_V_at)if test -f $@; then \ cmp -s $@.tmp $@ && : || mv -f $@.tmp $@; else mv -f $@.tmp $@; fi LIBOBJECTS = $(LIB_SOURCES:.cc=.o) MOCKOBJECTS = $(MOCK_SOURCES:.cc=.o) GTEST = $(GTEST_DIR)/gtest/gtest-all.o TESTUTIL = ./util/testutil.o TESTHARNESS = ./util/testharness.o $(TESTUTIL) $(MOCKOBJECTS) $(GTEST) BENCHHARNESS = ./util/benchharness.o VALGRIND_ERROR = 2 VALGRIND_DIR = build_tools/VALGRIND_LOGS VALGRIND_VER := $(join $(VALGRIND_VER),valgrind) VALGRIND_OPTS = --error-exitcode=$(VALGRIND_ERROR) --leak-check=full TESTS = \ db_test \ db_iter_test \ block_hash_index_test \ autovector_test \ column_family_test \ table_properties_collector_test \ arena_test \ auto_roll_logger_test \ benchharness_test \ block_test \ bloom_test \ dynamic_bloom_test \ c_test \ cache_test \ coding_test \ corruption_test \ crc32c_test \ slice_transform_test \ dbformat_test \ env_test \ fault_injection_test \ filelock_test \ filename_test \ block_based_filter_block_test \ full_filter_block_test \ histogram_test \ log_test \ manual_compaction_test \ memenv_test \ mock_env_test \ merge_test \ merger_test \ redis_test \ reduce_levels_test \ plain_table_db_test \ comparator_db_test \ prefix_test \ skiplist_test \ stringappend_test \ ttl_test \ backupable_db_test \ document_db_test \ json_document_test \ spatial_db_test \ version_edit_test \ version_set_test \ compaction_picker_test \ version_builder_test \ file_indexer_test \ write_batch_test \ write_controller_test\ deletefile_test \ table_test \ thread_local_test \ geodb_test \ rate_limiter_test \ options_test \ event_logger_test \ cuckoo_table_builder_test \ cuckoo_table_reader_test \ cuckoo_table_db_test \ flush_job_test \ wal_manager_test \ listener_test \ compaction_job_test \ thread_list_test \ sst_dump_test \ compact_files_test SUBSET := $(shell echo $(TESTS) |sed s/^.*$(ROCKSDBTESTS_START)/$(ROCKSDBTESTS_START)/) TOOLS = \ sst_dump \ db_sanity_test \ db_stress \ ldb \ db_repl_stress \ options_test \ PROGRAMS = db_bench signal_test table_reader_bench log_and_apply_bench cache_bench perf_context_test memtablerep_bench $(TOOLS) # The library name is configurable since we are maintaining libraries of both # debug/release mode. ifeq ($(LIBNAME),) LIBNAME=librocksdb endif LIBRARY = ${LIBNAME}.a ROCKSDB_MAJOR = $(shell egrep "ROCKSDB_MAJOR.[0-9]" include/rocksdb/version.h | cut -d ' ' -f 3) ROCKSDB_MINOR = $(shell egrep "ROCKSDB_MINOR.[0-9]" include/rocksdb/version.h | cut -d ' ' -f 3) ROCKSDB_PATCH = $(shell egrep "ROCKSDB_PATCH.[0-9]" include/rocksdb/version.h | cut -d ' ' -f 3) default: all #----------------------------------------------- # Create platform independent shared libraries. #----------------------------------------------- ifneq ($(PLATFORM_SHARED_EXT),) ifneq ($(PLATFORM_SHARED_VERSIONED),true) SHARED1 = ${LIBNAME}.$(PLATFORM_SHARED_EXT) SHARED2 = $(SHARED1) SHARED3 = $(SHARED1) SHARED4 = $(SHARED1) SHARED = $(SHARED1) else SHARED_MAJOR = $(ROCKSDB_MAJOR) SHARED_MINOR = $(ROCKSDB_MINOR) SHARED_PATCH = $(ROCKSDB_PATCH) SHARED1 = ${LIBNAME}.$(PLATFORM_SHARED_EXT) SHARED2 = $(SHARED1).$(SHARED_MAJOR) SHARED3 = $(SHARED1).$(SHARED_MAJOR).$(SHARED_MINOR) SHARED4 = $(SHARED1).$(SHARED_MAJOR).$(SHARED_MINOR).$(SHARED_PATCH) SHARED = $(SHARED1) $(SHARED2) $(SHARED3) $(SHARED4) $(SHARED1): $(SHARED4) ln -fs $(SHARED4) $(SHARED1) $(SHARED2): $(SHARED4) ln -fs $(SHARED4) $(SHARED2) $(SHARED3): $(SHARED4) ln -fs $(SHARED4) $(SHARED3) endif $(SHARED4): $(CXX) $(PLATFORM_SHARED_LDFLAGS)$(SHARED2) $(CXXFLAGS) $(PLATFORM_SHARED_CFLAGS) $(LIB_SOURCES) $(LDFLAGS) -o $@ endif # PLATFORM_SHARED_EXT .PHONY: blackbox_crash_test check clean coverage crash_test ldb_tests package \ release tags valgrind_check whitebox_crash_test format static_lib shared_lib all \ dbg rocksdbjavastatic rocksdbjava install uninstall analyze all: $(LIBRARY) $(PROGRAMS) $(TESTS) static_lib: $(LIBRARY) shared_lib: $(SHARED) dbg: $(LIBRARY) $(PROGRAMS) $(TESTS) # creates static library and programs release: $(MAKE) clean OPT="-DNDEBUG -O2" $(MAKE) static_lib $(PROGRAMS) -j32 coverage: $(MAKE) clean COVERAGEFLAGS="-fprofile-arcs -ftest-coverage" LDFLAGS+="-lgcov" $(MAKE) all check -j32 (cd coverage; ./coverage_test.sh) # Delete intermediate files find . -type f -regex ".*\.\(\(gcda\)\|\(gcno\)\)" -exec rm {} \; check: $(TESTS) ldb for t in $(TESTS); do echo "***** Running $$t"; ./$$t || exit 1; done python tools/ldb_test.py check_some: $(SUBSET) ldb for t in $(SUBSET); do echo "***** Running $$t"; ./$$t || exit 1; done python tools/ldb_test.py ldb_tests: ldb python tools/ldb_test.py crash_test: whitebox_crash_test blackbox_crash_test blackbox_crash_test: db_stress python -u tools/db_crashtest.py whitebox_crash_test: db_stress python -u tools/db_crashtest2.py asan_check: $(MAKE) clean COMPILE_WITH_ASAN=1 $(MAKE) check -j32 $(MAKE) clean asan_crash_test: $(MAKE) clean COMPILE_WITH_ASAN=1 $(MAKE) crash_test $(MAKE) clean valgrind_check: all $(PROGRAMS) $(TESTS) mkdir -p $(VALGRIND_DIR) echo TESTS THAT HAVE VALGRIND ERRORS > $(VALGRIND_DIR)/valgrind_failed_tests; \ echo TIMES in seconds TAKEN BY TESTS ON VALGRIND > $(VALGRIND_DIR)/valgrind_tests_times; \ for t in $(filter-out skiplist_test,$(TESTS)); do \ stime=`date '+%s'`; \ $(VALGRIND_VER) $(VALGRIND_OPTS) ./$$t; \ if [ $$? -eq $(VALGRIND_ERROR) ] ; then \ echo $$t >> $(VALGRIND_DIR)/valgrind_failed_tests; \ fi; \ etime=`date '+%s'`; \ echo $$t $$((etime - stime)) >> $(VALGRIND_DIR)/valgrind_tests_times; \ done analyze: clean $(CLANG_SCAN_BUILD) --use-analyzer=$(CLANG_ANALYZER) \ --use-c++=$(CXX) --use-cc=$(CC) --status-bugs \ -o $(CURDIR)/scan_build_report \ $(MAKE) dbg unity.cc: rm -f $@ $@-t for source_file in $(LIB_SOURCES); do \ echo "#include <$$source_file>" >> $@-t; \ done echo 'int main(int argc, char** argv){ return 0; }' >> $@-t chmod a=r $@-t mv $@-t $@ unity: unity.o $(AM_LINK) clean: rm -f $(PROGRAMS) $(TESTS) $(LIBRARY) $(SHARED) make_config.mk unity.cc rm -rf ios-x86 ios-arm scan_build_report find . -name "*.[oda]" -exec rm {} \; find . -type f -regex ".*\.\(\(gcda\)\|\(gcno\)\)" -exec rm {} \; rm -rf bzip2* snappy* zlib* tags: ctags * -R cscope -b `find . -name '*.cc'` `find . -name '*.h'` format: build_tools/format-diff.sh package: bash build_tools/make_package.sh $(SHARED_MAJOR).$(SHARED_MINOR) # --------------------------------------------------------------------------- # Unit tests and tools # --------------------------------------------------------------------------- $(LIBRARY): $(LIBOBJECTS) $(AM_V_AR)rm -f $@ $(AM_V_at)$(AR) $(ARFLAGS) $@ $(LIBOBJECTS) db_bench: db/db_bench.o $(LIBOBJECTS) $(TESTUTIL) $(AM_LINK) cache_bench: util/cache_bench.o $(LIBOBJECTS) $(TESTUTIL) $(AM_LINK) memtablerep_bench: db/memtablerep_bench.o $(LIBOBJECTS) $(TESTUTIL) $(AM_LINK) block_hash_index_test: table/block_hash_index_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) db_stress: tools/db_stress.o $(LIBOBJECTS) $(TESTUTIL) $(AM_LINK) db_sanity_test: tools/db_sanity_test.o $(LIBOBJECTS) $(TESTUTIL) $(AM_LINK) db_repl_stress: tools/db_repl_stress.o $(LIBOBJECTS) $(TESTUTIL) $(AM_LINK) signal_test: util/signal_test.o $(LIBOBJECTS) $(AM_LINK) arena_test: util/arena_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) autovector_test: util/autovector_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) column_family_test: db/column_family_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) table_properties_collector_test: db/table_properties_collector_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) bloom_test: util/bloom_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) dynamic_bloom_test: util/dynamic_bloom_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) c_test: db/c_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) cache_test: util/cache_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) coding_test: util/coding_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) stringappend_test: utilities/merge_operators/string_append/stringappend_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) redis_test: utilities/redis/redis_lists_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) benchharness_test: util/benchharness_test.o $(LIBOBJECTS) $(TESTHARNESS) $(BENCHHARNESS) $(AM_LINK) histogram_test: util/histogram_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) thread_local_test: util/thread_local_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) corruption_test: db/corruption_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) crc32c_test: util/crc32c_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) slice_transform_test: util/slice_transform_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) db_test: db/db_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) db_iter_test: db/db_iter_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) log_write_bench: util/log_write_bench.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) -pg plain_table_db_test: db/plain_table_db_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) comparator_db_test: db/comparator_db_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) table_reader_bench: table/table_reader_bench.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) -pg log_and_apply_bench: db/log_and_apply_bench.o $(LIBOBJECTS) $(TESTHARNESS) $(BENCHHARNESS) $(AM_LINK) -pg perf_context_test: db/perf_context_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_V_CCLD)$(CXX) $^ $(EXEC_LDFLAGS) -o $@ $(LDFLAGS) prefix_test: db/prefix_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_V_CCLD)$(CXX) $^ $(EXEC_LDFLAGS) -o $@ $(LDFLAGS) backupable_db_test: utilities/backupable/backupable_db_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) document_db_test: utilities/document/document_db_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) json_document_test: utilities/document/json_document_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) spatial_db_test: utilities/spatialdb/spatial_db_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) ttl_test: utilities/ttl/ttl_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) write_batch_with_index_test: utilities/write_batch_with_index/write_batch_with_index_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) flush_job_test: db/flush_job_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) compaction_job_test: db/compaction_job_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) wal_manager_test: db/wal_manager_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) dbformat_test: db/dbformat_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) env_test: util/env_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) fault_injection_test: db/fault_injection_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) rate_limiter_test: util/rate_limiter_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) filename_test: db/filename_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) block_based_filter_block_test: table/block_based_filter_block_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) full_filter_block_test: table/full_filter_block_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) log_test: db/log_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) table_test: table/table_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) block_test: table/block_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) skiplist_test: db/skiplist_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) version_edit_test: db/version_edit_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) version_set_test: db/version_set_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) compaction_picker_test: db/compaction_picker_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) version_builder_test: db/version_builder_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) file_indexer_test: db/file_indexer_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) reduce_levels_test: tools/reduce_levels_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) write_batch_test: db/write_batch_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) write_controller_test: db/write_controller_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) merge_test: db/merge_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) merger_test: table/merger_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) deletefile_test: db/deletefile_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) geodb_test: utilities/geodb/geodb_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) cuckoo_table_builder_test: table/cuckoo_table_builder_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) cuckoo_table_reader_test: table/cuckoo_table_reader_test.o $(LIBOBJECTS) $(TESTHARNESS) $(BENCHHARNESS) $(AM_LINK) cuckoo_table_db_test: db/cuckoo_table_db_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) listener_test: db/listener_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) thread_list_test: util/thread_list_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) compactor_test: utilities/compaction/compactor_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) compact_files_test: db/compact_files_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) options_test: util/options_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) event_logger_test: util/event_logger_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) sst_dump_test: util/sst_dump_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) memenv_test : util/memenv_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) mock_env_test : util/mock_env_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) manual_compaction_test: util/manual_compaction_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) filelock_test: util/filelock_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) auto_roll_logger_test: util/auto_roll_logger_test.o $(LIBOBJECTS) $(TESTHARNESS) $(AM_LINK) sst_dump: tools/sst_dump.o $(LIBOBJECTS) $(AM_LINK) ldb: tools/ldb.o $(LIBOBJECTS) $(AM_LINK) # --------------------------------------------------------------------------- # Jni stuff # --------------------------------------------------------------------------- JNI_NATIVE_SOURCES = ./java/rocksjni/*.cc JAVA_INCLUDE = -I$(JAVA_HOME)/include/ -I$(JAVA_HOME)/include/linux ARCH := $(shell getconf LONG_BIT) ROCKSDBJNILIB = librocksdbjni-linux$(ARCH).so ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-linux$(ARCH).jar ROCKSDB_JAR_ALL = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH).jar ROCKSDB_JAVADOCS_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-javadoc.jar ROCKSDB_SOURCES_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-sources.jar ifeq ($(PLATFORM), OS_MACOSX) ROCKSDBJNILIB = librocksdbjni-osx.jnilib ROCKSDB_JAR = rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-osx.jar ifneq ("$(wildcard $(JAVA_HOME)/include/darwin)","") JAVA_INCLUDE = -I$(JAVA_HOME)/include -I $(JAVA_HOME)/include/darwin else JAVA_INCLUDE = -I/System/Library/Frameworks/JavaVM.framework/Headers/ endif endif libz.a: -rm -rf zlib-1.2.8 curl -O http://zlib.net/zlib-1.2.8.tar.gz tar xvzf zlib-1.2.8.tar.gz cd zlib-1.2.8 && CFLAGS='-fPIC' ./configure --static && make cp zlib-1.2.8/libz.a . libbz2.a: -rm -rf bzip2-1.0.6 curl -O http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz tar xvzf bzip2-1.0.6.tar.gz cd bzip2-1.0.6 && make CFLAGS='-fPIC -Wall -Winline -O2 -g -D_FILE_OFFSET_BITS=64' cp bzip2-1.0.6/libbz2.a . libsnappy.a: -rm -rf snappy-1.1.1 curl -O https://snappy.googlecode.com/files/snappy-1.1.1.tar.gz tar xvzf snappy-1.1.1.tar.gz cd snappy-1.1.1 && ./configure --with-pic --enable-static cd snappy-1.1.1 && make cp snappy-1.1.1/.libs/libsnappy.a . rocksdbjavastatic: libz.a libbz2.a libsnappy.a OPT="-fPIC -DNDEBUG -O2" $(MAKE) $(LIBRARY) -j cd java;$(MAKE) javalib; rm -f ./java/target/$(ROCKSDBJNILIB) $(CXX) $(CXXFLAGS) -I./java/. $(JAVA_INCLUDE) -shared -fPIC -o ./java/target/$(ROCKSDBJNILIB) $(JNI_NATIVE_SOURCES) $(LIBOBJECTS) $(COVERAGEFLAGS) libz.a libbz2.a libsnappy.a cd java/target;strip -S -x $(ROCKSDBJNILIB) cd java;jar -cf target/$(ROCKSDB_JAR) HISTORY*.md cd java/target;jar -uf $(ROCKSDB_JAR) $(ROCKSDBJNILIB) cd java/target/classes;jar -uf ../$(ROCKSDB_JAR) org/rocksdb/*.class org/rocksdb/util/*.class cd java/target/apidocs;jar -cf ../$(ROCKSDB_JAVADOCS_JAR) * cd java/src/main/java;jar -cf ../../../target/$(ROCKSDB_SOURCES_JAR) org rocksdbjavastaticrelease: rocksdbjavastatic cd java/crossbuild && vagrant destroy -f && vagrant up linux32 && vagrant halt linux32 && vagrant up linux64 && vagrant halt linux64 cd java;jar -cf target/$(ROCKSDB_JAR_ALL) HISTORY*.md cd java/target;jar -uf $(ROCKSDB_JAR_ALL) librocksdbjni-*.so librocksdbjni-*.jnilib cd java/target/classes;jar -uf ../$(ROCKSDB_JAR_ALL) org/rocksdb/*.class org/rocksdb/util/*.class rocksdbjavastaticpublish: rocksdbjavastaticrelease mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=java/rocksjni.pom -Dfile=java/target/rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-javadoc.jar -Dclassifier=javadoc mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=java/rocksjni.pom -Dfile=java/target/rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-sources.jar -Dclassifier=sources mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=java/rocksjni.pom -Dfile=java/target/rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-linux64.jar -Dclassifier=linux64 mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=java/rocksjni.pom -Dfile=java/target/rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-linux32.jar -Dclassifier=linux32 mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=java/rocksjni.pom -Dfile=java/target/rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH)-osx.jar -Dclassifier=osx mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=java/rocksjni.pom -Dfile=java/target/rocksdbjni-$(ROCKSDB_MAJOR).$(ROCKSDB_MINOR).$(ROCKSDB_PATCH).jar rocksdbjava: OPT="-fPIC -DNDEBUG -O2" $(MAKE) $(LIBRARY) -j32 cd java;$(MAKE) javalib; rm -f ./java/target/$(ROCKSDBJNILIB) $(CXX) $(CXXFLAGS) -I./java/. $(JAVA_INCLUDE) -shared -fPIC -o ./java/target/$(ROCKSDBJNILIB) $(JNI_NATIVE_SOURCES) $(LIBOBJECTS) $(JAVA_LDFLAGS) $(COVERAGEFLAGS) cd java;jar -cf target/$(ROCKSDB_JAR) HISTORY*.md cd java/target;jar -uf $(ROCKSDB_JAR) $(ROCKSDBJNILIB) cd java/target/classes;jar -uf ../$(ROCKSDB_JAR) org/rocksdb/*.class org/rocksdb/util/*.class jclean: cd java;$(MAKE) clean; jtest: cd java;$(MAKE) sample;$(MAKE) test; jdb_bench: cd java;$(MAKE) db_bench; commit-prereq: $(MAKE) clean && $(MAKE) all check; $(MAKE) clean && $(MAKE) rocksdbjava; $(MAKE) clean && USE_CLANG=1 $(MAKE) all; $(MAKE) clean && OPT=-DROCKSDB_LITE $(MAKE) release; # --------------------------------------------------------------------------- # Platform-specific compilation # --------------------------------------------------------------------------- ifeq ($(PLATFORM), IOS) # For iOS, create universal object files to be used on both the simulator and # a device. PLATFORMSROOT=/Applications/Xcode.app/Contents/Developer/Platforms SIMULATORROOT=$(PLATFORMSROOT)/iPhoneSimulator.platform/Developer DEVICEROOT=$(PLATFORMSROOT)/iPhoneOS.platform/Developer IOSVERSION=$(shell defaults read $(PLATFORMSROOT)/iPhoneOS.platform/version CFBundleShortVersionString) .cc.o: mkdir -p ios-x86/$(dir $@) $(CXX) $(CXXFLAGS) -isysroot $(SIMULATORROOT)/SDKs/iPhoneSimulator$(IOSVERSION).sdk -arch i686 -arch x86_64 -c $< -o ios-x86/$@ mkdir -p ios-arm/$(dir $@) xcrun -sdk iphoneos $(CXX) $(CXXFLAGS) -isysroot $(DEVICEROOT)/SDKs/iPhoneOS$(IOSVERSION).sdk -arch armv6 -arch armv7 -arch armv7s -arch arm64 -c $< -o ios-arm/$@ lipo ios-x86/$@ ios-arm/$@ -create -output $@ .c.o: mkdir -p ios-x86/$(dir $@) $(CC) $(CFLAGS) -isysroot $(SIMULATORROOT)/SDKs/iPhoneSimulator$(IOSVERSION).sdk -arch i686 -arch x86_64 -c $< -o ios-x86/$@ mkdir -p ios-arm/$(dir $@) xcrun -sdk iphoneos $(CC) $(CFLAGS) -isysroot $(DEVICEROOT)/SDKs/iPhoneOS$(IOSVERSION).sdk -arch armv6 -arch armv7 -arch armv7s -arch arm64 -c $< -o ios-arm/$@ lipo ios-x86/$@ ios-arm/$@ -create -output $@ else .cc.o: $(AM_V_CC)$(CXX) $(CXXFLAGS) -c $< -o $@ $(COVERAGEFLAGS) .c.o: $(AM_V_CC)$(CC) $(CFLAGS) -c $< -o $@ endif # --------------------------------------------------------------------------- # Source files dependencies detection # --------------------------------------------------------------------------- # Add proper dependency support so changing a .h file forces a .cc file to # rebuild. # The .d file indicates .cc file's dependencies on .h files. We generate such # dependency by g++'s -MM option, whose output is a make dependency rule. %.d: %.cc @$(CXX) $(CXXFLAGS) $(PLATFORM_SHARED_CFLAGS) \ -MM -MT'$@' -MT'$(<:.cc=.o)' "$<" -o '$@' all_sources = $(LIB_SOURCES) $(TEST_BENCH_SOURCES) $(MOCK_SOURCES) DEPFILES = $(all_sources:.cc=.d) depend: $(DEPFILES) # if the make goal is either "clean" or "format", we shouldn't # try to import the *.d files. # TODO(kailiu) The unfamiliarity of Make's conditions leads to the ugly # working solution. ifneq ($(MAKECMDGOALS),clean) ifneq ($(MAKECMDGOALS),format) ifneq ($(MAKECMDGOALS),jclean) ifneq ($(MAKECMDGOALS),jtest) ifneq ($(MAKECMDGOALS),package) ifneq ($(MAKECMDGOALS),analyze) -include $(DEPFILES) endif endif endif endif endif endif
{ "content_hash": "a56f0c551c1ef83f85287e266a8bb9c1", "timestamp": "", "source": "github", "line_count": 822, "max_line_length": 277, "avg_line_length": 32.367396593673966, "alnum_prop": 0.6718409381342554, "repo_name": "amyvmiwei/rocksdb", "id": "02b41864fe201fe59519a7d22e5a74644ea37c2e", "size": "26936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Makefile", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "71697" }, { "name": "C++", "bytes": "4442817" }, { "name": "Java", "bytes": "742469" }, { "name": "Makefile", "bytes": "50233" }, { "name": "Objective-C", "bytes": "2945" }, { "name": "PHP", "bytes": "11927" }, { "name": "Python", "bytes": "187746" }, { "name": "Ruby", "bytes": "662" }, { "name": "Shell", "bytes": "48313" } ], "symlink_target": "" }
<form class="form-horizontal" ng-submit="reviews.addReview(product.reviews)"> <product-review class="well live-preview" ng-show="!reviews.review.isEmpty()" review="reviews.review"> </product-review> <fieldset class="form-group"> <label>Your Review:</label> <textarea class="form-control" rows="5" ng-model="reviews.review.body"></textarea> </fieldset> <fieldset class="form-group"> <label>Stars:</label> <select ng-model="reviews.review.stars"> <option value="5">5 stars</option> <option value="4">4 stars</option> <option value="3">3 stars</option> <option value="2">2 stars</option> <option value="1">1 star</option> </select> </fieldset> <fieldset class="form-group"> <label>by:</label> <input type="email" placeholder="someone@example.com" ng-model="reviews.review.author"> </fieldset> <button type="submit" class="btn btn-primary pull-right">Submit</button> </form>
{ "content_hash": "e11a341575f01eb38bbf2524a5f07ea8", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 74, "avg_line_length": 32.7, "alnum_prop": 0.6452599388379205, "repo_name": "dvn123/SINF", "id": "6b97ac6c57ad63a53689c2a9d6f7f028c5625e91", "size": "981", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "product-review-form.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "334753" }, { "name": "HTML", "bytes": "1584388" }, { "name": "JavaScript", "bytes": "1859810" }, { "name": "PHP", "bytes": "51748" } ], "symlink_target": "" }
package AutoDiff.Compiled; public class ConstPower extends TapeElement { public int Base; public double Exponent; public void accept(ITapeVisitor visitor) throws Exception { visitor.visit(this); } }
{ "content_hash": "6afe7a54b8657900c87380285ae0c82e", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 63, "avg_line_length": 17.357142857142858, "alnum_prop": 0.6625514403292181, "repo_name": "andreaswitsch/cnlcsplib", "id": "7b92d8ab50576adf88f3efb36de81f4cbb881e70", "size": "317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/src/main/java/AutoDiff/Compiled/ConstPower.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1014" }, { "name": "C#", "bytes": "357371" }, { "name": "C++", "bytes": "409548" }, { "name": "CMake", "bytes": "13102" }, { "name": "Java", "bytes": "346092" } ], "symlink_target": "" }
SELECT [GUID] ,[ScheduleID] ,[TaskID] ,[ServerID] ,[Inserted] ,[LastUpdate] FROM [live].[ExecutionStatus] WITH(XLOCK) WHERE [LastUpdate] < @lastUpdate;
{ "content_hash": "7aba1ba85f084d7040f1783f863e7ca2", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 31, "avg_line_length": 16.272727272727273, "alnum_prop": 0.6089385474860335, "repo_name": "MindFlavor/YoctoScheduler-core", "id": "917966f636a31aa4c893881080b6938a76a55b41", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "YoctoScheduler.Core/Database/tsql/LiveExecutionStatus/GetAndLockAll.sql", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "158777" }, { "name": "PowerShell", "bytes": "3401" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e5667e4b17154b9a04f462ab2c9fd7f3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "e74683766ec9f40eaf167093e7f3d4517eef990f", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Bryophyta/Bryopsida/Hypnales/Amblystegiaceae/Hygrohypnum/Hygrohypnum eugyrium/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>InternalErrorException - com.ligadata.MetadataAPI.InternalErrorException</title> <meta name="description" content="InternalErrorException - com.ligadata.MetadataAPI.InternalErrorException" /> <meta name="keywords" content="InternalErrorException com.ligadata.MetadataAPI.InternalErrorException" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'com.ligadata.MetadataAPI.InternalErrorException'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="type"> <div id="definition"> <img src="../../../lib/class_big.png" /> <p id="owner"><a href="../../package.html" class="extype" name="com">com</a>.<a href="../package.html" class="extype" name="com.ligadata">ligadata</a>.<a href="package.html" class="extype" name="com.ligadata.MetadataAPI">MetadataAPI</a></p> <h1>InternalErrorException</h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">case class</span> </span> <span class="symbol"> <span class="name">InternalErrorException</span><span class="params">(<span name="e">e: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result"> extends <span class="extype" name="scala.Exception">Exception</span> with <span class="extype" name="scala.Product">Product</span> with <span class="extype" name="scala.Serializable">Serializable</span></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="scala.Product">Product</span>, <span class="extype" name="scala.Equals">Equals</span>, <span class="extype" name="java.lang.Exception">Exception</span>, <span class="extype" name="java.lang.Throwable">Throwable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="com.ligadata.MetadataAPI.InternalErrorException"><span>InternalErrorException</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="scala.Product"><span>Product</span></li><li class="in" name="scala.Equals"><span>Equals</span></li><li class="in" name="java.lang.Exception"><span>Exception</span></li><li class="in" name="java.lang.Throwable"><span>Throwable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="com.ligadata.MetadataAPI.InternalErrorException#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(e:String):com.ligadata.MetadataAPI.InternalErrorException"></a> <a id="&lt;init&gt;:InternalErrorException"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">InternalErrorException</span><span class="params">(<span name="e">e: <span class="extype" name="scala.Predef.String">String</span></span>)</span> </span> </h4> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:AnyRef):Boolean"></a> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:AnyRef):Boolean"></a> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="java.lang.Throwable#addSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="addSuppressed(x$1:Throwable):Unit"></a> <a id="addSuppressed(Throwable):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">addSuppressed</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="com.ligadata.MetadataAPI.InternalErrorException#e" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="e:String"></a> <a id="e:String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">e</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span> </span> </h4> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#fillInStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="fillInStackTrace():Throwable"></a> <a id="fillInStackTrace():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">fillInStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="java.lang.Throwable#getCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getCause():Throwable"></a> <a id="getCause():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getCause</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#getLocalizedMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getLocalizedMessage():String"></a> <a id="getLocalizedMessage():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getLocalizedMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getMessage():String"></a> <a id="getMessage():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getStackTrace():Array[StackTraceElement]"></a> <a id="getStackTrace():Array[StackTraceElement]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getSuppressed():Array[Throwable]"></a> <a id="getSuppressed():Array[Throwable]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getSuppressed</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.Throwable">Throwable</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#initCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="initCause(x$1:Throwable):Throwable"></a> <a id="initCause(Throwable):Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">initCause</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintWriter):Unit"></a> <a id="printStackTrace(PrintWriter):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintWriter">PrintWriter</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintStream):Unit"></a> <a id="printStackTrace(PrintStream):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintStream">PrintStream</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace():Unit"></a> <a id="printStackTrace():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#setStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="setStackTrace(x$1:Array[StackTraceElement]):Unit"></a> <a id="setStackTrace(Array[StackTraceElement]):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">setStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.Serializable"> <h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3> </div><div class="parent" name="scala.Product"> <h3>Inherited from <span class="extype" name="scala.Product">Product</span></h3> </div><div class="parent" name="scala.Equals"> <h3>Inherited from <span class="extype" name="scala.Equals">Equals</span></h3> </div><div class="parent" name="java.lang.Exception"> <h3>Inherited from <span class="extype" name="java.lang.Exception">Exception</span></h3> </div><div class="parent" name="java.lang.Throwable"> <h3>Inherited from <span class="extype" name="java.lang.Throwable">Throwable</span></h3> </div><div class="parent" name="java.io.Serializable"> <h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> <script defer="defer" type="text/javascript" id="jquery-js" src="../../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../../lib/template.js"></script> </body> </html>
{ "content_hash": "1ee789b2e5070f19d3ade26448b872bf", "timestamp": "", "source": "github", "line_count": 593, "max_line_length": 642, "avg_line_length": 55.78752107925801, "alnum_prop": 0.5998428148237712, "repo_name": "traytonwhite/Kamanja", "id": "7d4ba2f5a310e41a20d029af92e5cce9d4ff80a9", "size": "33094", "binary": false, "copies": "1", "ref": "refs/heads/Sprint8Features", "path": "trunk/Documentation/KamanjaAPIDocs/com/ligadata/MetadataAPI/InternalErrorException.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5303" }, { "name": "CSS", "bytes": "36426" }, { "name": "HTML", "bytes": "96105" }, { "name": "Java", "bytes": "174690" }, { "name": "JavaScript", "bytes": "22944" }, { "name": "Protocol Buffer", "bytes": "2060" }, { "name": "Python", "bytes": "3714" }, { "name": "Scala", "bytes": "4406455" }, { "name": "Shell", "bytes": "154334" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading.Tasks; using Azure.Core; using Azure.Core.TestFramework; using Azure.Identity; using Azure.Storage.Sas; using Azure.Storage.Test; using Moq; using NUnit.Framework; namespace Azure.Storage.Files.DataLake.Tests { public class PathClientTests : PathTestBase { public PathClientTests(bool async, DataLakeClientOptions.ServiceVersion serviceVersion) : base(async, serviceVersion, null /* RecordedTestMode.Record /* to re-record */) { } [RecordedTest] public async Task Ctor_Uri() { string fileSystemName = GetNewFileSystemName(); await using DisposingFileSystem test = await GetNewFileSystem(fileSystemName: fileSystemName); // Arrange string directoryName = GetNewDirectoryName(); await test.FileSystem.CreateDirectoryAsync(directoryName); SasQueryParameters sasQueryParameters = GetNewAccountSasCredentials(); Uri uri = new Uri($"{TestConfigHierarchicalNamespace.BlobServiceEndpoint}/{fileSystemName}/{directoryName}?{sasQueryParameters}"); DataLakePathClient pathClient = InstrumentClient(new DataLakePathClient(uri, GetOptions())); // Act await pathClient.GetPropertiesAsync(); // Assert Assert.AreEqual(fileSystemName, pathClient.FileSystemName); Assert.AreEqual(uri, pathClient.Uri); } [RecordedTest] public async Task Ctor_SharedKey() { string fileSystemName = GetNewFileSystemName(); await using DisposingFileSystem test = await GetNewFileSystem(fileSystemName: fileSystemName); // Arrange string directoryName = GetNewDirectoryName(); await test.FileSystem.CreateDirectoryAsync(directoryName); StorageSharedKeyCredential sharedKey = new StorageSharedKeyCredential( TestConfigHierarchicalNamespace.AccountName, TestConfigHierarchicalNamespace.AccountKey); Uri uri = new Uri($"{TestConfigHierarchicalNamespace.BlobServiceEndpoint}/{fileSystemName}/{directoryName}"); DataLakePathClient pathClient = InstrumentClient(new DataLakePathClient(uri, sharedKey, GetOptions())); // Act await pathClient.GetPropertiesAsync(); // Assert Assert.AreEqual(fileSystemName, pathClient.FileSystemName); Assert.AreEqual(uri, pathClient.Uri); } [RecordedTest] public async Task Ctor_TokenCredential() { string fileSystemName = GetNewFileSystemName(); await using DisposingFileSystem test = await GetNewFileSystem(fileSystemName: fileSystemName); // Arrange string directoryName = GetNewDirectoryName(); await test.FileSystem.CreateDirectoryAsync(directoryName); TokenCredential tokenCredential = GetOAuthCredential(TestConfigHierarchicalNamespace); Uri uri = new Uri($"{TestConfigHierarchicalNamespace.BlobServiceEndpoint}/{fileSystemName}/{directoryName}").ToHttps(); DataLakePathClient pathClient = InstrumentClient(new DataLakePathClient(uri, tokenCredential, GetOptions())); // Act await pathClient.GetPropertiesAsync(); // Assert Assert.AreEqual(fileSystemName, pathClient.FileSystemName); Assert.AreEqual(uri, pathClient.Uri); } [RecordedTest] public async Task Ctor_ConnectionString_RoundTrip() { // Arrange string fileSystemName = GetNewFileSystemName(); string path = GetNewDirectoryName(); await using DisposingFileSystem test = await GetNewFileSystem(fileSystemName: fileSystemName); DataLakeDirectoryClient directoryClient = InstrumentClient(test.FileSystem.GetDirectoryClient(path)); await directoryClient.CreateAsync(); // Act string connectionString = $"DefaultEndpointsProtocol=https;AccountName={TestConfigHierarchicalNamespace.AccountName};AccountKey={TestConfigHierarchicalNamespace.AccountKey};EndpointSuffix=core.windows.net"; DataLakePathClient connStringDirectory = InstrumentClient(new DataLakePathClient(connectionString, fileSystemName, path, GetOptions())); // Assert await connStringDirectory.GetPropertiesAsync(); await connStringDirectory.GetAccessControlAsync(); } [RecordedTest] public async Task Ctor_ConnectionString_GenerateSas() { // Arrange string fileSystemName = GetNewFileSystemName(); string path = GetNewDirectoryName(); await using DisposingFileSystem test = await GetNewFileSystem(fileSystemName: fileSystemName); DataLakeDirectoryClient directoryClient = InstrumentClient(test.FileSystem.GetDirectoryClient(path)); await directoryClient.CreateAsync(); // Act string connectionString = $"DefaultEndpointsProtocol=https;AccountName={TestConfigHierarchicalNamespace.AccountName};AccountKey={TestConfigHierarchicalNamespace.AccountKey};EndpointSuffix=core.windows.net"; DataLakePathClient connStringDirectory = InstrumentClient(new DataLakePathClient(connectionString, fileSystemName, path, GetOptions())); Uri sasUri = connStringDirectory.GenerateSasUri(DataLakeSasPermissions.All, Recording.UtcNow.AddDays(1)); DataLakePathClient sasPathClient = InstrumentClient(new DataLakePathClient(sasUri, GetOptions())); // Assert await sasPathClient.GetPropertiesAsync(); await sasPathClient.GetAccessControlAsync(); } [RecordedTest] public void Ctor_TokenCredential_Http() { // Arrange TokenCredential tokenCredential = GetOAuthCredential(TestConfigHierarchicalNamespace); Uri uri = new Uri(TestConfigHierarchicalNamespace.BlobServiceEndpoint).ToHttp(); // Act TestHelper.AssertExpectedException( () => new DataLakePathClient(uri, tokenCredential), new ArgumentException("Cannot use TokenCredential without HTTPS.")); TestHelper.AssertExpectedException( () => new DataLakePathClient(uri, tokenCredential, new DataLakeClientOptions()), new ArgumentException("Cannot use TokenCredential without HTTPS.")); } [RecordedTest] public async Task Ctor_FileSystemAndPath() { // Arrange await using DisposingFileSystem test = await GetNewFileSystem(); DataLakeFileClient fileClient = await test.FileSystem.CreateFileAsync(GetNewFileName()); // Act DataLakePathClient pathClient = new DataLakePathClient(test.FileSystem, fileClient.Path); // Assert await pathClient.GetPropertiesAsync(); await pathClient.GetAccessControlAsync(); } #region GenerateSasTests [RecordedTest] public void CanGenerateSas_ClientConstructors() { // Arrange var constants = new TestConstants(this); var blobEndpoint = new Uri("https://127.0.0.1/" + constants.Sas.Account); var blobSecondaryEndpoint = new Uri("https://127.0.0.1/" + constants.Sas.Account + "-secondary"); var storageConnectionString = new StorageConnectionString(constants.Sas.SharedKeyCredential, blobStorageUri: (blobEndpoint, blobSecondaryEndpoint)); string connectionString = storageConnectionString.ToString(true); // Act - DataLakePathClient(Uri blobContainerUri, BlobClientOptions options = default) DataLakePathClient blob3 = InstrumentClient(new DataLakePathClient( blobEndpoint, GetOptions())); Assert.IsFalse(blob3.CanGenerateSasUri); // Act - DataLakePathClient(Uri blobContainerUri, StorageSharedKeyCredential credential, BlobClientOptions options = default) DataLakePathClient blob4 = InstrumentClient(new DataLakePathClient( blobEndpoint, constants.Sas.SharedKeyCredential, GetOptions())); Assert.IsTrue(blob4.CanGenerateSasUri); // Act - DataLakePathClient(Uri blobContainerUri, TokenCredential credential, BlobClientOptions options = default) var tokenCredentials = new DefaultAzureCredential(); DataLakePathClient blob5 = InstrumentClient(new DataLakePathClient( blobEndpoint, tokenCredentials, GetOptions())); Assert.IsFalse(blob5.CanGenerateSasUri); } [RecordedTest] public void CanGenerateSas_Mockable() { // Act var pathClient = new Mock<DataLakePathClient>(); pathClient.Setup(x => x.CanGenerateSasUri).Returns(false); // Assert Assert.IsFalse(pathClient.Object.CanGenerateSasUri); // Act pathClient.Setup(x => x.CanGenerateSasUri).Returns(true); // Assert Assert.IsTrue(pathClient.Object.CanGenerateSasUri); } [RecordedTest] public void GenerateSas_RequiredParameters() { // Arrange var constants = new TestConstants(this); string fileSystemName = GetNewFileSystemName(); string path = GetNewFileName(); DataLakeSasPermissions permissions = DataLakeSasPermissions.Read; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); var blobEndpoint = new Uri("http://127.0.0.1/" + constants.Sas.Account + "/" + fileSystemName + "/" + path); DataLakePathClient pathClient = InstrumentClient(new DataLakePathClient( blobEndpoint, constants.Sas.SharedKeyCredential, GetOptions())); // Act Uri sasUri = pathClient.GenerateSasUri(permissions, expiresOn); // Assert DataLakeSasBuilder sasBuilder2 = new DataLakeSasBuilder(permissions, expiresOn) { FileSystemName = fileSystemName, Path = path }; DataLakeUriBuilder expectedUri = new DataLakeUriBuilder(blobEndpoint) { Sas = sasBuilder2.ToSasQueryParameters(constants.Sas.SharedKeyCredential) }; Assert.AreEqual(expectedUri.ToUri().ToString(), sasUri.ToString()); } [RecordedTest] public void GenerateSas_Builder() { var constants = new TestConstants(this); string fileSystemName = GetNewFileSystemName(); string path = GetNewFileName(); DataLakeSasPermissions permissions = DataLakeSasPermissions.Read; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); DateTimeOffset startsOn = Recording.UtcNow.AddHours(-1); var blobEndpoint = new Uri("http://127.0.0.1/" + constants.Sas.Account + "/" + fileSystemName + "/" + path); DataLakePathClient pathClient = InstrumentClient(new DataLakePathClient( blobEndpoint, constants.Sas.SharedKeyCredential, GetOptions())); DataLakeSasBuilder sasBuilder = new DataLakeSasBuilder(permissions, expiresOn) { FileSystemName = fileSystemName, Path = path, StartsOn = startsOn }; // Act Uri sasUri = pathClient.GenerateSasUri(sasBuilder); // Assert DataLakeUriBuilder expectedUri = new DataLakeUriBuilder(blobEndpoint); DataLakeSasBuilder sasBuilder2 = new DataLakeSasBuilder(permissions, expiresOn) { FileSystemName = fileSystemName, Path = path, StartsOn = startsOn }; expectedUri.Sas = sasBuilder2.ToSasQueryParameters(constants.Sas.SharedKeyCredential); Assert.AreEqual(expectedUri.ToUri().ToString(), sasUri.ToString()); } [RecordedTest] public void GenerateSas_BuilderWrongFileSystemName() { // Arrange var constants = new TestConstants(this); var blobEndpoint = new Uri("http://127.0.0.1/"); UriBuilder blobUriBuilder = new UriBuilder(blobEndpoint); string path = GetNewFileName(); DataLakeSasPermissions permissions = DataLakeSasPermissions.Read; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); blobUriBuilder.Path += constants.Sas.Account + "/" + GetNewFileSystemName() + "/" + path; DataLakePathClient pathClient = InstrumentClient(new DataLakePathClient( blobUriBuilder.Uri, constants.Sas.SharedKeyCredential, GetOptions())); DataLakeSasBuilder sasBuilder = new DataLakeSasBuilder(permissions, expiresOn) { FileSystemName = GetNewFileSystemName(), // different filesystem name Path = path, }; // Act try { pathClient.GenerateSasUri(sasBuilder); Assert.Fail("DataLakePathClient.GenerateSasUri should have failed with an ArgumentException."); } catch (InvalidOperationException) { //the correct exception came back } } [RecordedTest] public void GenerateSas_BuilderWrongPath() { // Arrange var constants = new TestConstants(this); var blobEndpoint = new Uri("http://127.0.0.1/"); UriBuilder blobUriBuilder = new UriBuilder(blobEndpoint); string fileSystemName = GetNewFileSystemName(); DataLakeSasPermissions permissions = DataLakeSasPermissions.Read; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); blobUriBuilder.Path += constants.Sas.Account + "/" + fileSystemName + "/" + GetNewFileName(); DataLakePathClient containerClient = InstrumentClient(new DataLakePathClient( blobUriBuilder.Uri, constants.Sas.SharedKeyCredential, GetOptions())); DataLakeSasBuilder sasBuilder = new DataLakeSasBuilder(permissions, expiresOn) { FileSystemName = fileSystemName, Path = GetNewFileName(), // different path }; // Act try { containerClient.GenerateSasUri(sasBuilder); Assert.Fail("DataLakePathClient.GenerateSasUri should have failed with an ArgumentException."); } catch (InvalidOperationException) { //the correct exception came back } } [RecordedTest] public void GenerateSas_BuilderIsDirectoryError() { var constants = new TestConstants(this); var blobEndpoint = new Uri("http://127.0.0.1/"); UriBuilder blobUriBuilder = new UriBuilder(blobEndpoint); string fileSystemName = GetNewFileSystemName(); string fileName = GetNewFileName(); DataLakeSasPermissions permissions = DataLakeSasPermissions.Read; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); blobUriBuilder.Path += constants.Sas.Account + "/" + fileSystemName + "/" + fileName; DataLakePathClient containerClient = InstrumentClient(new DataLakePathClient( blobUriBuilder.Uri, constants.Sas.SharedKeyCredential, GetOptions())); DataLakeSasBuilder sasBuilder = new DataLakeSasBuilder(permissions, expiresOn) { FileSystemName = fileSystemName, Path = fileName, IsDirectory = true, }; // Act try { containerClient.GenerateSasUri(sasBuilder); Assert.Fail("DataLakeFileClient.GenerateSasUri should have failed with an ArgumentException."); } catch (InvalidOperationException) { //the correct exception came back } } #endregion [RecordedTest] public void CanMockClientConstructors() { // One has to call .Object to trigger constructor. It's lazy. var mock = new Mock<DataLakePathClient>(TestConfigDefault.ConnectionString, "name", "name", new DataLakeClientOptions()).Object; mock = new Mock<DataLakePathClient>(TestConfigDefault.ConnectionString, "name", "name").Object; mock = new Mock<DataLakePathClient>(new Uri("https://test/test"), new DataLakeClientOptions()).Object; mock = new Mock<DataLakePathClient>(new Uri("https://test/test"), GetNewSharedKeyCredentials(), new DataLakeClientOptions()).Object; mock = new Mock<DataLakePathClient>(new Uri("https://test/test"), new AzureSasCredential("foo"), new DataLakeClientOptions()).Object; mock = new Mock<DataLakePathClient>(new Uri("https://test/test"), GetOAuthCredential(TestConfigHierarchicalNamespace), new DataLakeClientOptions()).Object; } } }
{ "content_hash": "b11707eeb1a515e56cce06d721dcb225", "timestamp": "", "source": "github", "line_count": 400, "max_line_length": 218, "avg_line_length": 44.2675, "alnum_prop": 0.633026486700175, "repo_name": "ayeletshpigelman/azure-sdk-for-net", "id": "7d07beddacf6586cb62e275618949be8516b4395", "size": "17709", "binary": false, "copies": "1", "ref": "refs/heads/ayshpige/InternalBranchForDebuging", "path": "sdk/storage/Azure.Storage.Files.DataLake/tests/PathClientTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "Batchfile", "bytes": "28895" }, { "name": "C#", "bytes": "45912328" }, { "name": "CSS", "bytes": "685" }, { "name": "HTML", "bytes": "45212" }, { "name": "JavaScript", "bytes": "7875" }, { "name": "PowerShell", "bytes": "24250" }, { "name": "Shell", "bytes": "1470" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
using LoginStateLacrosBrowserTest = InProcessBrowserTest; IN_PROC_BROWSER_TEST_F(LoginStateLacrosBrowserTest, GetSessionState) { auto* lacros_service = chromeos::LacrosService::Get(); if (!lacros_service->IsAvailable<crosapi::mojom::LoginState>()) { LOG(WARNING) << "Unsupported ash version."; return; } crosapi::mojom::GetSessionStateResultPtr result; crosapi::mojom::LoginStateAsyncWaiter async_waiter( lacros_service->GetRemote<crosapi::mojom::LoginState>().get()); async_waiter.GetSessionState(&result); ASSERT_FALSE(result->is_error_message()); EXPECT_EQ(result->get_session_state(), crosapi::mojom::SessionState::kInSession); }
{ "content_hash": "a0d29353c411dd3582d69c8ba6156f83", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 70, "avg_line_length": 37.72222222222222, "alnum_prop": 0.7319587628865979, "repo_name": "ric2b/Vivaldi-browser", "id": "55b7d59ad0dd09e341ec4b94e211e5e8131147e9", "size": "1135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chromium/chrome/browser/lacros/login_state_lacros_browsertest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#ifndef MODULES_PERCEPTION_OBSTACLE_LIDAR_SEGMENTATION_CNNSEG_CLUSTER2D_H_ #define MODULES_PERCEPTION_OBSTACLE_LIDAR_SEGMENTATION_CNNSEG_CLUSTER2D_H_ #include <vector> #include <algorithm> #include "caffe/caffe.hpp" #include "modules/common/log.h" #include "modules/perception/lib/pcl_util/pcl_types.h" #include "modules/perception/obstacle/base/object.h" #include "modules/perception/obstacle/common/disjoint_set.h" #include "modules/perception/obstacle/lidar/segmentation/cnnseg/util.h" namespace apollo { namespace perception { namespace cnnseg { struct Obstacle { std::vector<int> grids; apollo::perception::pcl_util::PointCloudPtr cloud; float score; float height; Obstacle() { grids.clear(); cloud.reset(new apollo::perception::pcl_util::PointCloud); score = 0.0; height = -5.0; } }; class Cluster2D { public: Cluster2D() {} ~Cluster2D() {} bool Init(int rows, int cols, float range) { rows_ = rows; cols_ = cols; grids_ = rows_ * cols_; range_ = range; scale_ = 0.5 * static_cast<float>(rows_) / range_; inv_res_x_ = 0.5 * static_cast<float>(cols_) / range_; inv_res_y_ = 0.5 * static_cast<float>(rows_) / range_; point2grid_.clear(); obstacles_.clear(); id_img_.assign(grids_, -1); pc_ptr_.reset(); valid_indices_in_pc_ = nullptr; return true; } void Cluster(const caffe::Blob<float>& category_pt_blob, const caffe::Blob<float>& instance_pt_blob, const apollo::perception::pcl_util::PointCloudPtr& pc_ptr, const apollo::perception::pcl_util::PointIndices& valid_indices, float objectness_thresh, bool use_all_grids_for_clustering) { const float* category_pt_data = category_pt_blob.cpu_data(); const float* instance_pt_x_data = instance_pt_blob.cpu_data(); const float* instance_pt_y_data = instance_pt_blob.cpu_data() + instance_pt_blob.offset(0, 1); pc_ptr_ = pc_ptr; std::vector<std::vector<Node>> nodes(rows_, std::vector<Node>(cols_, Node())); // map points into grids size_t tot_point_num = pc_ptr_->size(); valid_indices_in_pc_ = &(valid_indices.indices); CHECK_LE(valid_indices_in_pc_->size(), tot_point_num); point2grid_.assign(valid_indices_in_pc_->size(), -1); for (size_t i = 0; i < valid_indices_in_pc_->size(); ++i) { int point_id = valid_indices_in_pc_->at(i); CHECK_GE(point_id, 0); CHECK_LT(point_id, static_cast<int>(tot_point_num)); const auto& point = pc_ptr_->points[point_id]; // * the coordinates of x and y have been exchanged in feature generation // step, // so we swap them back here. int pos_x = F2I(point.y, range_, inv_res_x_); // col int pos_y = F2I(point.x, range_, inv_res_y_); // row if (IsValidRowCol(pos_y, pos_x)) { // get grid index and count point number for corresponding node point2grid_[i] = RowCol2Grid(pos_y, pos_x); nodes[pos_y][pos_x].point_num++; } } // construct graph with center offset prediction and objectness for (int row = 0; row < rows_; row++) { for (int col = 0; col < cols_; col++) { int grid = RowCol2Grid(row, col); Node* node = &nodes[row][col]; apollo::perception::DisjointSetMakeSet(node); node->is_object = (use_all_grids_for_clustering || nodes[row][col].point_num > 0) && (*(category_pt_data + grid) >= objectness_thresh); int center_row = std::round(row + instance_pt_x_data[grid] * scale_); int center_col = std::round(col + instance_pt_y_data[grid] * scale_); center_row = std::min(std::max(center_row, 0), rows_ - 1); center_col = std::min(std::max(center_col, 0), cols_ - 1); node->center_node = &nodes[center_row][center_col]; } } // traverse nodes for (int row = 0; row < rows_; row++) { for (int col = 0; col < cols_; col++) { Node* node = &nodes[row][col]; if (node->is_object && node->traversed == 0) { Traverse(node); } } } for (int row = 0; row < rows_; row++) { for (int col = 0; col < cols_; col++) { Node* node = &nodes[row][col]; if (!node->is_center) { continue; } for (int row2 = row - 1; row2 <= row + 1; row2++) { for (int col2 = col - 1; col2 <= col + 1; col2++) { if ((row2 == row || col2 == col) && IsValidRowCol(row2, col2)) { Node* node2 = &nodes[row2][col2]; if (node2->is_center) { apollo::perception::DisjointSetUnion(node, node2); } } } } } } int count_obstacles = 0; obstacles_.clear(); id_img_.assign(grids_, -1); for (int row = 0; row < rows_; row++) { for (int col = 0; col < cols_; col++) { Node* node = &nodes[row][col]; if (!node->is_object) { continue; } Node* root = apollo::perception::DisjointSetFind(node); if (root->obstacle_id < 0) { root->obstacle_id = count_obstacles++; CHECK_EQ(static_cast<int>(obstacles_.size()), count_obstacles - 1); obstacles_.push_back(Obstacle()); } int grid = RowCol2Grid(row, col); CHECK_GE(root->obstacle_id, 0); id_img_[grid] = root->obstacle_id; obstacles_[root->obstacle_id].grids.push_back(grid); } } CHECK_EQ(static_cast<int>(count_obstacles), obstacles_.size()); } void Filter(const caffe::Blob<float>& confidence_pt_blob, const caffe::Blob<float>& height_pt_blob) { const float* confidence_pt_data = confidence_pt_blob.cpu_data(); const float* height_pt_data = height_pt_blob.cpu_data(); for (size_t obstacle_id = 0; obstacle_id < obstacles_.size(); obstacle_id++) { Obstacle* obs = &obstacles_[obstacle_id]; CHECK_GT(obs->grids.size(), 0); double score = 0.0; double height = 0.0; for (int grid : obs->grids) { score += static_cast<double>(confidence_pt_data[grid]); height += static_cast<double>(height_pt_data[grid]); } obs->score = score / static_cast<double>(obs->grids.size()); obs->height = height / static_cast<double>(obs->grids.size()); obs->cloud.reset(new apollo::perception::pcl_util::PointCloud); } } void GetObjects(const float confidence_thresh, const float height_thresh, const int min_pts_num, std::vector<ObjectPtr>* objects) { CHECK(valid_indices_in_pc_ != nullptr); for (size_t i = 0; i < point2grid_.size(); ++i) { int grid = point2grid_[i]; if (grid < 0) { continue; } CHECK_GE(grid, 0); CHECK_LT(grid, grids_); int obstacle_id = id_img_[grid]; int point_id = valid_indices_in_pc_->at(i); CHECK_GE(point_id, 0); CHECK_LT(point_id, static_cast<int>(pc_ptr_->size())); if (obstacle_id >= 0 && obstacles_[obstacle_id].score >= confidence_thresh) { if (height_thresh < 0 || pc_ptr_->points[point_id].z <= obstacles_[obstacle_id].height + height_thresh) { obstacles_[obstacle_id].cloud->push_back(pc_ptr_->points[point_id]); } } } for (size_t obstacle_id = 0; obstacle_id < obstacles_.size(); obstacle_id++) { Obstacle* obs = &obstacles_[obstacle_id]; if (static_cast<int>(obs->cloud->size()) < min_pts_num) { continue; } apollo::perception::ObjectPtr out_obj(new apollo::perception::Object); out_obj->cloud = obs->cloud; out_obj->score = obs->score; objects->push_back(out_obj); } } private: struct Node { Node* center_node; Node* parent; char node_rank; char traversed; bool is_center; bool is_object; int point_num; int obstacle_id; Node() { center_node = nullptr; parent = nullptr; node_rank = 0; traversed = 0; is_center = false; is_object = false; point_num = 0; obstacle_id = -1; } }; inline bool IsValidRowCol(int row, int col) const { return IsValidRow(row) && IsValidCol(col); } inline bool IsValidRow(int row) const { return row >= 0 && row < rows_; } inline bool IsValidCol(int col) const { return col >= 0 && col < cols_; } inline int RowCol2Grid(int row, int col) const { return row * cols_ + col; } void Traverse(Node* x) { std::vector<Node*> p; p.clear(); while (x->traversed == 0) { p.push_back(x); x->traversed = 2; x = x->center_node; } if (x->traversed == 2) { for (int i = static_cast<int>(p.size()) - 1; i >= 0 && p[i] != x; i--) { p[i]->is_center = true; } x->is_center = true; } for (size_t i = 0; i < p.size(); i++) { Node* y = p[i]; y->traversed = 1; y->parent = x->parent; } } int rows_; int cols_; int grids_; float range_; float scale_; float inv_res_x_; float inv_res_y_; apollo::perception::pcl_util::PointCloudPtr pc_ptr_; const std::vector<int>* valid_indices_in_pc_ = nullptr; std::vector<int> point2grid_; std::vector<int> id_img_; std::vector<Obstacle> obstacles_; }; } // namespace cnnseg } // namespace perception } // namespace apollo #endif // MODULES_PERCEPTION_OBSTACLE_LIDAR_SEGMENTATION_CNNSEG_CLUSTER2D_H_
{ "content_hash": "93df42eaf2234e91d039996a69170cd7", "timestamp": "", "source": "github", "line_count": 304, "max_line_length": 79, "avg_line_length": 31.44407894736842, "alnum_prop": 0.567527984098755, "repo_name": "fy2462/apollo", "id": "d144fd99448463aa9317258f208b9867379eb7bd", "size": "10331", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/perception/obstacle/lidar/segmentation/cnnseg/cluster2d.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3386" }, { "name": "C++", "bytes": "4761775" }, { "name": "CMake", "bytes": "58901" }, { "name": "CSS", "bytes": "20492" }, { "name": "HTML", "bytes": "236" }, { "name": "JavaScript", "bytes": "147786" }, { "name": "Python", "bytes": "640744" }, { "name": "Shell", "bytes": "103381" }, { "name": "Smarty", "bytes": "54938" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef GLOBALBOOST_PRIMITIVES_BLOCK_H #define GLOBALBOOST_PRIMITIVES_BLOCK_H #include <primitives/transaction.h> #include <serialize.h> #include <uint256.h> /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. */ class CBlockHeader { public: // header int32_t nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; uint32_t nTime; uint32_t nBits; uint32_t nNonce; CBlockHeader() { SetNull(); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(this->nVersion); READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); } void SetNull() { nVersion = 0; hashPrevBlock.SetNull(); hashMerkleRoot.SetNull(); nTime = 0; nBits = 0; nNonce = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const; uint256 GetPoWHash() const; int64_t GetBlockTime() const { return (int64_t)nTime; } }; class CBlock : public CBlockHeader { public: // network and disk std::vector<CTransactionRef> vtx; // memory only mutable bool fChecked; CBlock() { SetNull(); } CBlock(const CBlockHeader &header) { SetNull(); *(static_cast<CBlockHeader*>(this)) = header; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(*static_cast<CBlockHeader*>(this)); READWRITE(vtx); } void SetNull() { CBlockHeader::SetNull(); vtx.clear(); fChecked = false; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrevBlock; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } std::string ToString() const; }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ struct CBlockLocator { std::vector<uint256> vHave; CBlockLocator() {} explicit CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { int nVersion = s.GetVersion(); if (!(s.GetType() & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); } void SetNull() { vHave.clear(); } bool IsNull() const { return vHave.empty(); } }; #endif // GLOBALBOOST_PRIMITIVES_BLOCK_H
{ "content_hash": "fb8ee3838e4a0322f6d2b5e51f52cdbb", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 83, "avg_line_length": 23.420382165605094, "alnum_prop": 0.6293173782975252, "repo_name": "GlobalBoost/GlobalBoost-Y", "id": "a6b6a5eeb30cc786a7b5baa5380d0e779fd6bb31", "size": "3677", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/primitives/block.h", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28453" }, { "name": "C", "bytes": "781289" }, { "name": "C++", "bytes": "6028829" }, { "name": "HTML", "bytes": "21860" }, { "name": "Java", "bytes": "30290" }, { "name": "M4", "bytes": "196776" }, { "name": "Makefile", "bytes": "110650" }, { "name": "Objective-C", "bytes": "3012" }, { "name": "Objective-C++", "bytes": "4202" }, { "name": "Python", "bytes": "1467860" }, { "name": "QMake", "bytes": "756" }, { "name": "Shell", "bytes": "78870" } ], "symlink_target": "" }
package org.igniterealtime.jbosh; import org.junit.Test; /** * BOSH XEP-0124 specification section 2 tests: Requirements. */ public class XEP0124Section02Test extends AbstractBOSHTest { @Test public void noop() { // No tests defined } }
{ "content_hash": "aec79dfb0b9775acc5083ffed3c81790", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 61, "avg_line_length": 15.588235294117647, "alnum_prop": 0.6867924528301886, "repo_name": "matthewmcnew/jbosh", "id": "dfdd11900fb96a289142d2b19bcafd4aec1948ec", "size": "858", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/igniterealtime/jbosh/XEP0124Section02Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "217" }, { "name": "Java", "bytes": "437125" } ], "symlink_target": "" }
package com.raycoarana.baindo.observables; import java.util.Observer; public abstract class AbstractProperty<T> extends Observable<T> { protected T mValue; public AbstractProperty() { } public AbstractProperty(T defaultValue) { mValue = defaultValue; } public T getValue() { return mValue; } public abstract void onValueChanged(T newValue); /** * Sets a new value for this property, preventing that the sender observer gets called * by the update event that will be fired. * * @param newValue new value for the property * @param sender observer to ignore when notifying changes */ public void setValue(T newValue, Observer sender) { mValue = newValue; this.onValueChanged(newValue); setChanged(); notifyObservers(sender); } /** * Sets a new value for this property. Caller of this method must not be an Observer of this * property (or you will suffer a infinite loop). If you want to change the value of this * property from an Observer, use setValue(T, Observer) * * @param newValue new value for the property * * @see AbstractProperty#setValue(Object, java.util.Observer) */ public void setValue(T newValue) { setValue(newValue, null); } }
{ "content_hash": "cf28f26cf7e7879bb5a43c2407b8b938", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 96, "avg_line_length": 26.176470588235293, "alnum_prop": 0.6569288389513108, "repo_name": "raycoarana/baindo", "id": "b9d945ad9b1af4d978a6c8b76f1a0d8aa803c189", "size": "1962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/java/com/raycoarana/baindo/observables/AbstractProperty.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "390051" } ], "symlink_target": "" }
# Disallow Synchronous Methods (no-sync) This rule was **deprecated** in ESLint v7.0.0. Please use the corresponding rule in [`eslint-plugin-node`](https://github.com/mysticatea/eslint-plugin-node). In Node.js, most I/O is done through asynchronous methods. However, there are often synchronous versions of the asynchronous methods. For example, `fs.exists()` and `fs.existsSync()`. In some contexts, using synchronous operations is okay (if, as with ESLint, you are writing a command line utility). However, in other contexts the use of synchronous operations is considered a bad practice that should be avoided. For example, if you are running a high-travel web server on Node.js, you should consider carefully if you want to allow any synchronous operations that could lock up the server. ## Rule Details This rule is aimed at preventing synchronous methods from being called in Node.js. It looks specifically for the method suffix "`Sync`" (as is the convention with Node.js operations). ## Options This rule has an optional object option `{ allowAtRootLevel: <boolean> }`, which determines whether synchronous methods should be allowed at the top level of a file, outside of any functions. This option defaults to `false`. Examples of **incorrect** code for this rule with the default `{ allowAtRootLevel: false }` option: ```js /*eslint no-sync: "error"*/ fs.existsSync(somePath); function foo() { var contents = fs.readFileSync(somePath).toString(); } ``` Examples of **correct** code for this rule with the default `{ allowAtRootLevel: false }` option: ```js /*eslint no-sync: "error"*/ obj.sync(); async(function() { // ... }); ``` Examples of **incorrect** code for this rule with the `{ allowAtRootLevel: true }` option ```js /*eslint no-sync: ["error", { allowAtRootLevel: true }]*/ function foo() { var contents = fs.readFileSync(somePath).toString(); } var bar = baz => fs.readFileSync(qux); ``` Examples of **correct** code for this rule with the `{ allowAtRootLevel: true }` option ```js /*eslint no-sync: ["error", { allowAtRootLevel: true }]*/ fs.readFileSync(somePath).toString(); ``` ## When Not To Use It If you want to allow synchronous operations in your script, do not enable this rule.
{ "content_hash": "c0914a81e7bafb58b99f47928db3524a", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 592, "avg_line_length": 36.75409836065574, "alnum_prop": 0.7323818019625334, "repo_name": "DavidAnson/eslint", "id": "949df6d36b429e1a038ee635ae5081b1dc9ce5df", "size": "2242", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "docs/rules/no-sync.md", "mode": "33188", "license": "mit", "language": [ { "name": "EJS", "bytes": "4074" }, { "name": "HTML", "bytes": "898" }, { "name": "JavaScript", "bytes": "11114823" } ], "symlink_target": "" }
module Ch05LogisticRegression.GradientAscent ( gradAscent , sigmoid , stocGradAscent0 , stocGradAscent0History , stocGradAscent1 ) where import qualified Data.Vector.Storable as VS import MLUtil -- cf logRegres.sigmoid sigmoid :: Double -> Double sigmoid x = 1.0 / (1.0 + exp (-x)) -- cf logRegres.gradAscent gradAscent :: Double -> Int -> Matrix -> Matrix -> Matrix gradAscent alpha maxCycles values labels = let m = rows values n = cols values alpha' = scalar alpha in foldr (\_ weights -> let h = cmap sigmoid (values <> weights) err = labels - h weightsDelta = alpha' * (tr' values <> err) in weights + weightsDelta) (ones (n, 1)) -- initial weights [0 .. maxCycles - 1] -- cf logRegres.stocGradAscent0 -- This function demonstrates why we need to build a consistent set of -- primitives for linear algebra... -- TODO: Eliminate all the unnecessary conversions to and from lists etc. stocGradAscent0 :: Double -> Matrix -> Matrix -> Matrix stocGradAscent0 alpha values labels = let m = rows values n = cols values rows' = toRows values -- Bad, bad, bad in col $ VS.toList (foldr -- VS.toList is bad, bad, bad (\i weights -> let r = rows' !! i -- Bad, bad, bad label = labels `atIndex` (i, 0) h = sigmoid $ sumElements (r * weights) err = label - h weightsDelta = scale (alpha * err) r in weights + weightsDelta) (VS.replicate n 1) -- initial weights [m - 1, m - 2 .. 0]) -- stocGradAscent0 modified to allow us to track history of weights stocGradAscent0History :: Double -> Int -> Matrix -> Matrix -> (Vector, [Vector]) stocGradAscent0History alpha n values labels = foldl -- TODO: Can we improve on this? (\p _ -> helper alpha p values labels) (VS.replicate (rows values) 1, []) [1 .. n] helper :: Double -> (Vector, [Vector]) -> Matrix -> Matrix -> (Vector, [Vector]) helper alpha p values labels = let m = rows values n = cols values rows' = toRows values -- Bad, bad, bad in foldl -- VS.toList is bad, bad, bad (\(weights, history) i -> let r = rows' !! i -- Bad, bad, bad label = labels `atIndex` (i, 0) h = sigmoid $ sumElements (r * weights) err = label - h weightsDelta = scale (alpha * err) r weights' = weights + weightsDelta in (weights', history ++ [weights'])) -- TODO: Tweak fold since concatenation is O(N) I think p [0 .. m - 1] stocGradAscent1 :: Double -> Matrix -> Matrix -> [ExtractIndices] -> Matrix stocGradAscent1 alpha values labels eis = let m = rows values n = cols values rows' = toRows values -- Bad, bad, bad labels' = map (\i -> labels `atIndex` (i, 0)) [0 .. m - 1] in col $ VS.toList -- VS.toList is bad, bad, bad (foldl (\w (j, ei) -> stocGradAscent1Helper rows' labels' j ei w) (VS.replicate n 1) (zip [0 ..] eis)) stocGradAscent1Helper :: [Vector] -> [R] -> Int -> ExtractIndices -> Vector -> Vector stocGradAscent1Helper rows'' labels'' j ei weights = let Just (_, rows') = extract ei (zip rows'' labels'') in foldl (\weights (i, (r, label)) -> let alpha = 4.0 / (1.0 + fromIntegral (j + i)) + 0.0001 h = sigmoid $ sumElements (r * weights) err = label - h weightsDelta = scale (alpha * err) r in weights + weightsDelta) weights (zip [0 ..] rows')
{ "content_hash": "8ac83c36214edae07618172c158ab34e", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 105, "avg_line_length": 37.58163265306123, "alnum_prop": 0.5691012761335867, "repo_name": "rcook/mlutil", "id": "211e7382f71775821d3f0ab60f1462284da2dc0c", "size": "3683", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ch05-logistic-regression/lib/Ch05LogisticRegression/GradientAscent.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3957" }, { "name": "Haskell", "bytes": "103422" }, { "name": "PowerShell", "bytes": "2660" }, { "name": "Shell", "bytes": "1668" } ], "symlink_target": "" }
package cz.muni.fi.xtovarn.heimdall.pipeline.handler; import cz.muni.fi.xtovarn.heimdall.dispatcher.Dispatcher; import cz.muni.fi.xtovarn.heimdall.dispatcher.Subscription; public class SubmitToDispatcher implements Handler { private final Dispatcher dispatcher; public SubmitToDispatcher(Dispatcher dispatcher) { this.dispatcher = dispatcher; } @Override public Object handle(Object o) { dispatcher.submit((Subscription) o); return null; } }
{ "content_hash": "62626fd00d90e7cbd2b2de24cb425092", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 59, "avg_line_length": 26.444444444444443, "alnum_prop": 0.7626050420168067, "repo_name": "ngmon/ngmon", "id": "4c5ca9ebdb8dbb095f4bdacb277975e3c3844586", "size": "476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/cz/muni/fi/xtovarn/heimdall/pipeline/handler/SubmitToDispatcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "9985" }, { "name": "Java", "bytes": "59210" }, { "name": "Python", "bytes": "1221" }, { "name": "Shell", "bytes": "1274" } ], "symlink_target": "" }
define([ "lib/three" ], function(THREE) { /** * @author arodic / https://github.com/arodic */ /*jshint sub:true*/ ( function () { 'use strict'; var shouldCreateAxis = function(axis) { return (!this || !Array.isArray(this.hideAxis) || this.hideAxis.indexOf(axis) === -1); }; var GizmoMaterial = function ( parameters ) { THREE.MeshBasicMaterial.call( this ); this.depthTest = false; this.depthWrite = false; this.side = THREE.FrontSide; this.transparent = true; this.setValues( parameters ); this.oldColor = this.color.clone(); this.oldOpacity = this.opacity; this.highlight = function( highlighted ) { if ( highlighted ) { this.color.copy(THREE.TransformGizmo.highlightColor); this.opacity = 1; } else { this.color.copy( this.oldColor ); this.opacity = this.oldOpacity; } }; }; GizmoMaterial.prototype = Object.create( THREE.MeshBasicMaterial.prototype ); GizmoMaterial.prototype.constructor = GizmoMaterial; var GizmoLineMaterial = function ( parameters ) { THREE.LineBasicMaterial.call( this ); this.depthTest = false; this.depthWrite = false; this.transparent = true; this.linewidth = 1; this.setValues( parameters ); this.oldColor = this.color.clone(); this.oldOpacity = this.opacity; this.highlight = function( highlighted ) { if ( highlighted ) { this.color.copy(THREE.TransformGizmo.highlightColor); this.opacity = 1; } else { this.color.copy( this.oldColor ); this.opacity = this.oldOpacity; } }; }; GizmoLineMaterial.prototype = Object.create( THREE.LineBasicMaterial.prototype ); GizmoLineMaterial.prototype.constructor = GizmoLineMaterial; var pickerMaterial = new GizmoMaterial( { visible: false, transparent: false } ); THREE.TransformGizmo = function () { var scope = this; var showPickers = false; //debug var showActivePlane = false; //debug this.init = function () { THREE.Object3D.call( this ); this.handles = new THREE.Object3D(); this.pickers = new THREE.Object3D(); this.planes = new THREE.Object3D(); this.add( this.handles ); this.add( this.pickers ); this.add( this.planes ); //// PLANES var planeGeometry = new THREE.PlaneBufferGeometry( 50, 50, 2, 2 ); var planeMaterial = new THREE.MeshBasicMaterial( { visible: false, side: THREE.DoubleSide } ); var planes = { "XY": new THREE.Mesh( planeGeometry, planeMaterial ), "YZ": new THREE.Mesh( planeGeometry, planeMaterial ), "XZ": new THREE.Mesh( planeGeometry, planeMaterial ), "XYZE": new THREE.Mesh( planeGeometry, planeMaterial ) }; this.activePlane = planes[ "XYZE" ]; planes[ "YZ" ].rotation.set( 0, Math.PI / 2, 0 ); planes[ "XZ" ].rotation.set( - Math.PI / 2, 0, 0 ); for ( var i in planes ) { planes[ i ].name = i; this.planes.add( planes[ i ] ); this.planes[ i ] = planes[ i ]; } //// HANDLES AND PICKERS var setupGizmos = function( gizmoMap, parent ) { for ( var name in gizmoMap ) { for ( i = gizmoMap[ name ].length; i --; ) { var object = gizmoMap[ name ][ i ][ 0 ]; var position = gizmoMap[ name ][ i ][ 1 ]; var rotation = gizmoMap[ name ][ i ][ 2 ]; object.name = name; if ( position ) object.position.set( position[ 0 ], position[ 1 ], position[ 2 ] ); if ( rotation ) object.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ] ); parent.add( object ); } } }; setupGizmos( this.handleGizmos, this.handles ); setupGizmos( this.pickerGizmos, this.pickers ); // reset Transformations this.traverse( function ( child ) { if ( child instanceof THREE.Mesh ) { child.updateMatrix(); var tempGeometry = child.geometry.clone(); tempGeometry.applyMatrix( child.matrix ); child.geometry = tempGeometry; child.position.set( 0, 0, 0 ); child.rotation.set( 0, 0, 0 ); child.scale.set( 1, 1, 1 ); } } ); }; this.highlight = function ( axis ) { this.traverse( function( child ) { if ( child.material && child.material.highlight ) { if ( child.name === axis ) { child.material.highlight( true ); } else { child.material.highlight( false ); } } } ); }; }; THREE.TransformGizmo.highlightColor = new THREE.Color("yellow"); THREE.TransformGizmo.prototype = Object.create( THREE.Object3D.prototype ); THREE.TransformGizmo.prototype.constructor = THREE.TransformGizmo; THREE.TransformGizmo.prototype.update = function ( rotation, eye ) { var vec1 = new THREE.Vector3( 0, 0, 0 ); var vec2 = new THREE.Vector3( 0, 1, 0 ); var lookAtMatrix = new THREE.Matrix4(); this.traverse( function( child ) { if ( child.name.search( "E" ) !== - 1 ) { child.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( eye, vec1, vec2 ) ); } else if ( child.name.search( "X" ) !== - 1 || child.name.search( "Y" ) !== - 1 || child.name.search( "Z" ) !== - 1 ) { child.quaternion.setFromEuler( rotation ); } } ); }; THREE.TransformGizmoTranslate = function (options) { THREE.TransformGizmo.call( this ); var arrowGeometry = new THREE.Geometry(); var mesh = new THREE.Mesh( new THREE.CylinderGeometry( 0, 0.05, 0.2, 12, 1, false ) ); mesh.position.y = 0.5; mesh.updateMatrix(); arrowGeometry.merge( mesh.geometry, mesh.matrix ); this.handleGizmos = {}; this.pickerGizmos = {}; if ( shouldCreateAxis.call(options.pos, "X") ) { var lineXGeometry = new THREE.BufferGeometry(); lineXGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) ); this.handleGizmos.X = [ [ new THREE.Mesh( arrowGeometry, new GizmoMaterial( { color: options.colors.x } ) ), [ 0.5, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ], [ new THREE.Line( lineXGeometry, new GizmoLineMaterial( { color: options.colors.x } ) ) ] ]; this.pickerGizmos.X = [ [ new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0, 1, 4, 1, false ), pickerMaterial ), [ 0.6, 0, 0 ], [ 0, 0, - Math.PI / 2 ] ] ]; } if ( shouldCreateAxis.call(options.pos, "Y") ) { var lineYGeometry = new THREE.BufferGeometry(); lineYGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); this.handleGizmos.Y = [ [ new THREE.Mesh( arrowGeometry, new GizmoMaterial( { color: options.colors.y } ) ), [ 0, 0.5, 0 ] ], [ new THREE.Line( lineYGeometry, new GizmoLineMaterial( { color: options.colors.y } ) ) ] ]; this.pickerGizmos.Y = [ [ new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0, 1, 4, 1, false ), pickerMaterial ), [ 0, 0.6, 0 ] ] ]; } if ( shouldCreateAxis.call(options.pos, "Z") ) { var lineZGeometry = new THREE.BufferGeometry(); lineZGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); this.handleGizmos.Z = [ [ new THREE.Mesh( arrowGeometry, new GizmoMaterial( { color: options.colors.z } ) ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ] ], [ new THREE.Line( lineZGeometry, new GizmoLineMaterial( { color: options.colors.z } ) ) ] ]; this.pickerGizmos.Z = [ [ new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0, 1, 4, 1, false ), pickerMaterial ), [ 0, 0, 0.6 ], [ Math.PI / 2, 0, 0 ] ] ]; } if ( shouldCreateAxis.call(options.pos, "S") ) { var lineSGeometry = new THREE.Geometry(); lineSGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, -1, 0 ) ); this.handleGizmos.S = [ [ new THREE.Mesh( arrowGeometry, new GizmoMaterial( { color: 0x000000 } ) ), [ 0, -0.5, 0 ], [ 0, 0, Math.PI ] ], [ new THREE.Line( lineSGeometry, new GizmoLineMaterial( { color: 0x000000 } ) ) ] ]; this.pickerGizmos.S = [ [ new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0, 1, 4, 1, false ), pickerMaterial ), [ 0, -0.6, 0 ] ] ]; } if ( shouldCreateAxis.call(options.pos, "XYZ") ) { this.handleGizmos.XYZ = [ [ new THREE.Mesh( new THREE.OctahedronGeometry( 0.1, 0 ), new GizmoMaterial( { color: 0xffffff, opacity: 0.25 } ) ), [ 0, 0, 0 ], [ 0, 0, 0 ] ] ]; this.pickerGizmos.XYZ = [ [ new THREE.Mesh( new THREE.OctahedronGeometry( 0.2, 0 ), pickerMaterial ) ] ]; } if ( shouldCreateAxis.call(options.pos, "XY") ) { this.handleGizmos.XY = [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.29, 0.29 ), new GizmoMaterial( { color: options.colors.y, opacity: 0.25 } ) ), [ 0.15, 0.15, 0 ] ] ]; this.pickerGizmos.XY = [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.4, 0.4 ), pickerMaterial ), [ 0.2, 0.2, 0 ] ] ]; } if ( shouldCreateAxis.call(options.pos, "YZ") ) { this.handleGizmos.YZ = [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.29, 0.29 ), new GizmoMaterial( { color: options.colors.z, opacity: 0.25 } ) ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ] ] ]; this.pickerGizmos.YZ = [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.4, 0.4 ), pickerMaterial ), [ 0, 0.2, 0.2 ], [ 0, Math.PI / 2, 0 ] ] ]; } if ( shouldCreateAxis.call(options.pos, "XZ") ) { this.handleGizmos.XZ = [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.29, 0.29 ), new GizmoMaterial( { color: options.colors.x, opacity: 0.25 } ) ), [ 0.15, 0, 0.15 ], [ -Math.PI / 2, 0, 0 ] ] ]; this.pickerGizmos.XZ = [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry( 0.4, 0.4 ), pickerMaterial ), [ 0.2, 0, 0.2 ], [ - Math.PI / 2, 0, 0 ] ] ]; } this.setActivePlane = function ( axis, eye ) { var tempMatrix = new THREE.Matrix4(); eye.applyMatrix4( tempMatrix.getInverse( tempMatrix.extractRotation( this.planes[ "XY" ].matrixWorld ) ) ); if ( axis === "X" ) { this.activePlane = this.planes[ "XY" ]; if ( Math.abs( eye.y ) > Math.abs( eye.z ) ) this.activePlane = this.planes[ "XZ" ]; } if ( axis === "Y" ) { this.activePlane = this.planes[ "XY" ]; if ( Math.abs( eye.x ) > Math.abs( eye.z ) ) this.activePlane = this.planes[ "YZ" ]; } if ( axis === "Z" ) { this.activePlane = this.planes[ "XZ" ]; if ( Math.abs( eye.x ) > Math.abs( eye.y ) ) this.activePlane = this.planes[ "YZ" ]; } if ( axis === "XYZ" ) this.activePlane = this.planes[ "XYZE" ]; if ( axis === "XY" ) this.activePlane = this.planes[ "XY" ]; if ( axis === "YZ" ) this.activePlane = this.planes[ "YZ" ]; if ( axis === "XZ" ) this.activePlane = this.planes[ "XZ" ]; }; this.init(); }; THREE.TransformGizmoTranslate.prototype = Object.create( THREE.TransformGizmo.prototype ); THREE.TransformGizmoTranslate.prototype.constructor = THREE.TransformGizmoTranslate; THREE.TransformGizmoRotate = function (options) { THREE.TransformGizmo.call( this ); var CircleGeometry = function ( radius, facing, arc ) { var geometry = new THREE.BufferGeometry(); var vertices = []; arc = arc ? arc : 1; for ( var i = 0; i <= 64 * arc; ++ i ) { if ( facing === 'x' ) vertices.push( 0, Math.cos( i / 32 * Math.PI ) * radius, Math.sin( i / 32 * Math.PI ) * radius ); if ( facing === 'y' ) vertices.push( Math.cos( i / 32 * Math.PI ) * radius, 0, Math.sin( i / 32 * Math.PI ) * radius ); if ( facing === 'z' ) vertices.push( Math.sin( i / 32 * Math.PI ) * radius, Math.cos( i / 32 * Math.PI ) * radius, 0 ); } geometry.addAttribute( 'position', new THREE.Float32Attribute( vertices, 3 ) ); return geometry; }; var CustomTorusGeometry = function( radius, facing ) { var geometry = new THREE.TorusGeometry(radius, (radius == 1.25 ? 0.01 : 0.05), 2, 50); var matrix = new THREE.Matrix4(); if ( facing == 'x' ) matrix.makeRotationY(Math.PI * -0.5); if ( facing == 'y' ) matrix.makeRotationX(Math.PI * 0.5); geometry.applyMatrix(matrix); return geometry; }; var GizmoRotateHandle = function( radius, facing, arc, color, useTorus) { if (useTorus === true) return new THREE.Mesh( new CustomTorusGeometry(radius, facing), new GizmoLineMaterial( { color: color } ) ); return new THREE.Line( new CircleGeometry(radius, facing, arc), new GizmoLineMaterial( { color: color } ) ); } var GizmoRotatePicker = function(radius, tube, radialSegments, tubularSegments, arc, color) { return new THREE.Mesh( new THREE.TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ), pickerMaterial ) } var useTorus = (options.rot && options.rot.useTorus === true); var arc = (useTorus ? Math.PI * 2 : undefined); this.handleGizmos = {}; this.pickerGizmos = {}; if ( shouldCreateAxis.call(options.rot, "X") ) { this.handleGizmos.X = [ [ new GizmoRotateHandle( 1, 'x', 0.5, options.colors.x, useTorus ) ] ]; this.pickerGizmos.X = [ [ new GizmoRotatePicker( 1, 0.12, 4, 12, arc, options.colors.x ), [ 0, 0, 0 ], [ 0, -Math.PI / 2, -Math.PI / 2 ] ] ]; } if ( shouldCreateAxis.call(options.rot, "Y") ) { this.handleGizmos.Y = [ [ new GizmoRotateHandle( 1, 'y', 0.5, options.colors.y, useTorus ) ] ]; this.pickerGizmos.Y = [ [ new GizmoRotatePicker( 1, 0.12, 4, 12, arc, options.colors.y ), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ] ] ]; } if ( shouldCreateAxis.call(options.rot, "Z") ) { this.handleGizmos.Z = [ [ new GizmoRotateHandle( 1, 'z', 0.5, options.colors.z, useTorus ) ] ]; this.pickerGizmos.Z = [ [ new GizmoRotatePicker( 1, 0.12, 4, 12, arc, options.colors.z ), [ 0, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ] ]; } if ( shouldCreateAxis.call(options.rot, "E") ) { this.handleGizmos.E = [ [ new GizmoRotateHandle( 1.25, 'z', 1, options.colors.e, useTorus ) ] ]; this.pickerGizmos.E = [ [ new GizmoRotatePicker( 1.25, 0.12, 2, 24, undefined, options.colors.e ) ] ]; } if (!useTorus) { this.handleGizmos.XYZE = [ [ new GizmoRotateHandle(1, 'z', 1, 0x787878 ) ] ]; this.pickerGizmos.XYZE = [ [ new THREE.Mesh( new THREE.Geometry() ) ] ]; } this.setActivePlane = function ( axis ) { if ( axis === "E" ) this.activePlane = this.planes[ "XYZE" ]; if ( axis === "X" ) this.activePlane = this.planes[ "YZ" ]; if ( axis === "Y" ) this.activePlane = this.planes[ "XZ" ]; if ( axis === "Z" ) this.activePlane = this.planes[ "XY" ]; }; this.update = function ( rotation, eye2 ) { THREE.TransformGizmo.prototype.update.apply( this, arguments ); var group = { handles: this[ "handles" ], pickers: this[ "pickers" ], }; var tempMatrix = new THREE.Matrix4(); var worldRotation = new THREE.Euler( 0, 0, 1 ); var tempQuaternion = new THREE.Quaternion(); var unitX = new THREE.Vector3( 1, 0, 0 ); var unitY = new THREE.Vector3( 0, 1, 0 ); var unitZ = new THREE.Vector3( 0, 0, 1 ); var quaternionX = new THREE.Quaternion(); var quaternionY = new THREE.Quaternion(); var quaternionZ = new THREE.Quaternion(); var eye = eye2.clone(); worldRotation.copy( this.planes[ "XY" ].rotation ); tempQuaternion.setFromEuler( worldRotation ); tempMatrix.makeRotationFromQuaternion( tempQuaternion ).getInverse( tempMatrix ); eye.applyMatrix4( tempMatrix ); this.traverse( function( child ) { tempQuaternion.setFromEuler( worldRotation ); if ( child.name === "X" ) { quaternionX.setFromAxisAngle( unitX, Math.atan2( - eye.y, eye.z ) ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionX ); child.quaternion.copy( tempQuaternion ); } if ( child.name === "Y" ) { quaternionY.setFromAxisAngle( unitY, Math.atan2( eye.x, eye.z ) ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionY ); child.quaternion.copy( tempQuaternion ); } if ( child.name === "Z" ) { quaternionZ.setFromAxisAngle( unitZ, Math.atan2( eye.y, eye.x ) ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionZ ); child.quaternion.copy( tempQuaternion ); } } ); }; this.init(); }; THREE.TransformGizmoRotate.prototype = Object.create( THREE.TransformGizmo.prototype ); THREE.TransformGizmoRotate.prototype.constructor = THREE.TransformGizmoRotate; THREE.TransformGizmoScale = function (options) { THREE.TransformGizmo.call( this ); var arrowGeometry = new THREE.Geometry(); var mesh = new THREE.Mesh( new THREE.BoxGeometry( 0.125, 0.125, 0.125 ) ); mesh.position.y = 0.5; mesh.updateMatrix(); arrowGeometry.merge( mesh.geometry, mesh.matrix ); var lineXGeometry = new THREE.BufferGeometry(); lineXGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) ); var lineYGeometry = new THREE.BufferGeometry(); lineYGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); var lineZGeometry = new THREE.BufferGeometry(); lineZGeometry.addAttribute( 'position', new THREE.Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); this.handleGizmos = {}; this.pickerGizmos = {}; if ( shouldCreateAxis.call(options.scale, "X") ) { this.handleGizmos.X = [ [ new THREE.Mesh( arrowGeometry, new GizmoMaterial( { color: options.colors.x } ) ), [ 0.5, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ], [ new THREE.Line( lineXGeometry, new GizmoLineMaterial( { color: options.colors.x } ) ) ] ]; this.pickerGizmos.X = [ [ new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0, 1, 4, 1, false ), pickerMaterial ), [ 0.6, 0, 0 ], [ 0, 0, -Math.PI / 2 ] ] ]; } if ( shouldCreateAxis.call(options.scale, "Y") ) { this.handleGizmos.Y = [ [ new THREE.Mesh( arrowGeometry, new GizmoMaterial( { color: options.colors.y } ) ), [ 0, 0.5, 0 ] ], [ new THREE.Line( lineYGeometry, new GizmoLineMaterial( { color: options.colors.y } ) ) ] ]; this.pickerGizmos.Y = [ [ new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0, 1, 4, 1, false ), pickerMaterial ), [ 0, 0.6, 0 ] ] ]; } if ( shouldCreateAxis.call(options.scale, "Z") ) { this.handleGizmos.Z = [ [ new THREE.Mesh( arrowGeometry, new GizmoMaterial( { color: options.colors.z } ) ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ] ], [ new THREE.Line( lineZGeometry, new GizmoLineMaterial( { color: options.colors.z } ) ) ] ]; this.pickerGizmos.Z = [ [ new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0, 1, 4, 1, false ), pickerMaterial ), [ 0, 0, 0.6 ], [ Math.PI / 2, 0, 0 ] ] ]; } if ( shouldCreateAxis.call(options.scale, "XYZ") ) { this.handleGizmos.XYZ = [ [ new THREE.Mesh( new THREE.BoxGeometry( 0.125, 0.125, 0.125 ), new GizmoMaterial( { color: 0xffffff, opacity: 0.25 } ) ) ] ]; this.pickerGizmos.XYZ = [ [ new THREE.Mesh( new THREE.BoxGeometry( 0.4, 0.4, 0.4 ), pickerMaterial ) ] ]; } this.setActivePlane = function ( axis, eye ) { var tempMatrix = new THREE.Matrix4(); eye.applyMatrix4( tempMatrix.getInverse( tempMatrix.extractRotation( this.planes[ "XY" ].matrixWorld ) ) ); if ( axis === "X" ) { this.activePlane = this.planes[ "XY" ]; if ( Math.abs( eye.y ) > Math.abs( eye.z ) ) this.activePlane = this.planes[ "XZ" ]; } if ( axis === "Y" ) { this.activePlane = this.planes[ "XY" ]; if ( Math.abs( eye.x ) > Math.abs( eye.z ) ) this.activePlane = this.planes[ "YZ" ]; } if ( axis === "Z" ) { this.activePlane = this.planes[ "XZ" ]; if ( Math.abs( eye.x ) > Math.abs( eye.y ) ) this.activePlane = this.planes[ "YZ" ]; } if ( axis === "XYZ" ) this.activePlane = this.planes[ "XYZE" ]; }; this.init(); }; THREE.TransformGizmoScale.prototype = Object.create( THREE.TransformGizmo.prototype ); THREE.TransformGizmoScale.prototype.constructor = THREE.TransformGizmoScale; THREE.TransformControls = function ( camera, domElement, options ) { // TODO: Make non-uniform scale and rotate play nice in hierarchies // TODO: ADD RXYZ contol THREE.Object3D.call( this ); domElement = ( domElement !== undefined ) ? domElement : document; this.camera = camera; // WebTundra: Support multiple camera changing, maybe submit this to Three.js repo? :P this.options = $.extend(true, { colors : {} }, options); // WebTundra: options to modify some functionalities and visuals this.options.colors.x = (this.options.colors.x ? this.options.colors.x : 0xf44336); this.options.colors.y = (this.options.colors.y ? this.options.colors.y : 0x4caf50); this.options.colors.z = (this.options.colors.z ? this.options.colors.z : 0x2196f3); this.options.colors.e = (this.options.colors.e ? this.options.colors.e : 0x795548); THREE.TransformGizmo.highlightColor = new THREE.Color(this.options.colors.highlight ? this.options.colors.highlight : "#FFC107"); this.object = undefined; this.visible = false; this.translationSnap = null; this.translationSnapOffset = null; this.rotationSnap = null; this.space = "world"; this.size = 1; this.axis = null; var scope = this; var _mode = "translate"; var _dragging = false; var _plane = "XY"; var _gizmo = { "translate": new THREE.TransformGizmoTranslate(this.options), "rotate": new THREE.TransformGizmoRotate(this.options), "scale": new THREE.TransformGizmoScale(this.options) }; for ( var type in _gizmo ) { var gizmoObj = _gizmo[ type ]; gizmoObj.visible = ( type === _mode ); this.add( gizmoObj ); } var _lastMouseEvent = ""; var changeEvent = { type: "change" }; var mouseDownEvent = { type: "mouseDown" }; var mouseUpEvent = { type: "mouseUp", mode: _mode }; var objectChangeEvent = { type: "objectChange" }; var ray = new THREE.Raycaster(); var pointerVector = new THREE.Vector3(); var point = new THREE.Vector3(); var offset = new THREE.Vector3(); var rotation = new THREE.Vector3(); var offsetRotation = new THREE.Vector3(); var scale = 1; var lookAtMatrix = new THREE.Matrix4(); var eye = new THREE.Vector3(); var tempMatrix = new THREE.Matrix4(); var tempVector = new THREE.Vector3(); var tempQuaternion = new THREE.Quaternion(); var unitX = new THREE.Vector3( 1, 0, 0 ); var unitY = new THREE.Vector3( 0, 1, 0 ); var unitZ = new THREE.Vector3( 0, 0, 1 ); var quaternionXYZ = new THREE.Quaternion(); var quaternionX = new THREE.Quaternion(); var quaternionY = new THREE.Quaternion(); var quaternionZ = new THREE.Quaternion(); var quaternionE = new THREE.Quaternion(); var oldPosition = new THREE.Vector3(); var oldScale = new THREE.Vector3(); var oldRotationMatrix = new THREE.Matrix4(); var parentRotationMatrix = new THREE.Matrix4(); var parentScale = new THREE.Vector3(); var worldPosition = new THREE.Vector3(); var worldRotation = new THREE.Euler(); var worldRotationMatrix = new THREE.Matrix4(); var camPosition = new THREE.Vector3(); var camRotation = new THREE.Euler(); domElement.addEventListener( "mousedown", onPointerDown, false ); domElement.addEventListener( "touchstart", onPointerDown, false ); domElement.addEventListener( "mousemove", onPointerHover, false ); domElement.addEventListener( "touchmove", onPointerHover, false ); domElement.addEventListener( "mousemove", onPointerMove, false ); domElement.addEventListener( "touchmove", onPointerMove, false ); domElement.addEventListener( "mouseup", onPointerUp, false ); domElement.addEventListener( "mouseout", onPointerUp, false ); domElement.addEventListener( "touchend", onPointerUp, false ); domElement.addEventListener( "touchcancel", onPointerUp, false ); domElement.addEventListener( "touchleave", onPointerUp, false ); this.dispose = function () { domElement.removeEventListener( "mousedown", onPointerDown ); domElement.removeEventListener( "touchstart", onPointerDown ); domElement.removeEventListener( "mousemove", onPointerHover ); domElement.removeEventListener( "touchmove", onPointerHover ); domElement.removeEventListener( "mousemove", onPointerMove ); domElement.removeEventListener( "touchmove", onPointerMove ); domElement.removeEventListener( "mouseup", onPointerUp ); domElement.removeEventListener( "mouseout", onPointerUp ); domElement.removeEventListener( "touchend", onPointerUp ); domElement.removeEventListener( "touchcancel", onPointerUp ); domElement.removeEventListener( "touchleave", onPointerUp ); }; this.attach = function ( object ) { this.object = object; this.visible = true; this.update(); }; this.detach = function () { this.object = undefined; this.visible = false; this.axis = null; }; this.getMode = function () { return _mode; }; // WebTundra: have two helpful methods to check if the TransformControls are attached to an object and to set another camera this.isAttached = function () { return (scope.object !== undefined); } this.setCamera = function ( camera ) { scope.camera = camera; scope.update(); } this.setMode = function ( mode ) { _mode = mode ? mode : _mode; if ( _mode === "scale" ) scope.space = "local"; for ( var type in _gizmo ) _gizmo[ type ].visible = ( type === _mode ); this.update(); scope.dispatchEvent( changeEvent ); }; this.setTranslationSnap = function ( translationSnap ) { scope.translationSnap = translationSnap; }; this.setRotationSnap = function ( rotationSnap ) { scope.rotationSnap = rotationSnap; }; this.setSize = function ( size ) { scope.size = size; this.update(); scope.dispatchEvent( changeEvent ); }; this.setSpace = function ( space ) { scope.space = space; this.update(); scope.dispatchEvent( changeEvent ); }; this.update = function () { if ( scope.object === undefined ) return; scope.object.updateMatrixWorld(); worldPosition.setFromMatrixPosition( scope.object.matrixWorld ); worldRotation.setFromRotationMatrix( tempMatrix.extractRotation( scope.object.matrixWorld ) ); scope.camera.updateMatrixWorld(); camPosition.setFromMatrixPosition( scope.camera.matrixWorld ); camRotation.setFromRotationMatrix( tempMatrix.extractRotation( scope.camera.matrixWorld ) ); scale = worldPosition.distanceTo( camPosition ) / 6 * scope.size; this.position.copy( worldPosition ); this.scale.set( scale, scale, scale ); eye.copy( camPosition ).sub( worldPosition ).normalize(); if ( scope.space === "local" ) { _gizmo[ _mode ].update( worldRotation, eye ); } else if ( scope.space === "world" ) { _gizmo[ _mode ].update( new THREE.Euler(), eye ); } _gizmo[ _mode ].highlight( scope.axis ); }; function onPointerHover( event ) { if ( scope.object === undefined || _dragging === true || ( event.button !== undefined && event.button !== 0 ) ) return; _lastMouseEvent = "hover"; var pointer = event.changedTouches ? event.changedTouches[ 0 ] : event; var intersect = intersectObjects( pointer, _gizmo[ _mode ].pickers.children ); var axis = null; if ( intersect ) { axis = intersect.object.name; event.preventDefault(); } if ( scope.axis !== axis ) { scope.axis = axis; scope.update(); scope.dispatchEvent( changeEvent ); } } function onPointerDown( event ) { if ( scope.object === undefined || _dragging === true || ( event.button !== undefined && event.button !== 0 ) ) return; _lastMouseEvent = "down"; var pointer = event.changedTouches ? event.changedTouches[ 0 ] : event; if ( pointer.button === 0 || pointer.button === undefined ) { var intersect = intersectObjects( pointer, _gizmo[ _mode ].pickers.children ); if ( intersect ) { event.preventDefault(); event.stopPropagation(); scope.dispatchEvent( mouseDownEvent ); scope.axis = intersect.object.name; scope.update(); eye.copy( camPosition ).sub( worldPosition ).normalize(); _gizmo[ _mode ].setActivePlane( scope.axis, eye ); var planeIntersect = intersectObjects( pointer, [ _gizmo[ _mode ].activePlane ] ); if ( planeIntersect ) { oldPosition.copy( scope.object.position ); oldScale.copy( scope.object.scale ); oldRotationMatrix.extractRotation( scope.object.matrix ); worldRotationMatrix.extractRotation( scope.object.matrixWorld ); parentRotationMatrix.extractRotation( scope.object.parent.matrixWorld ); parentScale.setFromMatrixScale( tempMatrix.getInverse( scope.object.parent.matrixWorld ) ); offset.copy( planeIntersect.point ); } } } _dragging = true; } function onPointerMove( event ) { if ( scope.object === undefined || scope.axis === null || _dragging === false || ( event.button !== undefined && event.button !== 0 ) ) return; _lastMouseEvent = "move"; var pointer = event.changedTouches ? event.changedTouches[ 0 ] : event; var planeIntersect = intersectObjects( pointer, [ _gizmo[ _mode ].activePlane ] ); if ( planeIntersect === false ) return; event.preventDefault(); event.stopPropagation(); point.copy( planeIntersect.point ); if ( _mode === "translate" ) { point.sub( offset ); point.multiply( parentScale ); if ( scope.space === "local" ) { point.applyMatrix4( tempMatrix.getInverse( worldRotationMatrix ) ); if ( scope.axis.search( "X" ) === - 1 ) point.x = 0; if ( scope.axis.search( "Y" ) === - 1 ) point.y = 0; if ( scope.axis.search( "Z" ) === - 1 ) point.z = 0; point.applyMatrix4( oldRotationMatrix ); scope.object.position.copy( oldPosition ); scope.object.position.add( point ); } if ( scope.space === "world" || scope.axis.search( "XYZ" ) !== - 1 ) { if ( scope.axis.search( "X" ) === - 1 ) point.x = 0; if ( scope.axis.search( "Y" ) === - 1 ) point.y = 0; if ( scope.axis.search( "Z" ) === - 1 ) point.z = 0; point.applyMatrix4( tempMatrix.getInverse( parentRotationMatrix ) ); scope.object.position.copy( oldPosition ); scope.object.position.add( point ); } if ( scope.translationSnap !== null ) { if ( scope.space === "local" ) { scope.object.position.applyMatrix4( tempMatrix.getInverse( worldRotationMatrix ) ); } if ( !scope.translationSnapOffset ) { scope.translationSnapOffset = oldPosition.clone(); if ( scope.space === "local" ) scope.translationSnapOffset.applyMatrix4( tempMatrix.getInverse( worldRotationMatrix ) ); scope.translationSnapOffset.x -= (Math.round( scope.object.position.x / scope.translationSnap ) * scope.translationSnap); scope.translationSnapOffset.y -= (Math.round( scope.object.position.y / scope.translationSnap ) * scope.translationSnap); scope.translationSnapOffset.z -= (Math.round( scope.object.position.z / scope.translationSnap ) * scope.translationSnap); } if ( scope.axis.search( "X" ) !== - 1 ) scope.object.position.x = ( Math.round( scope.object.position.x / scope.translationSnap ) * scope.translationSnap ) + scope.translationSnapOffset.x; if ( scope.axis.search( "Y" ) !== - 1 ) scope.object.position.y = ( Math.round( scope.object.position.y / scope.translationSnap ) * scope.translationSnap ) + scope.translationSnapOffset.y; if ( scope.axis.search( "Z" ) !== - 1 ) scope.object.position.z = ( Math.round( scope.object.position.z / scope.translationSnap ) * scope.translationSnap ) + scope.translationSnapOffset.z; if ( scope.space === "local" ) { scope.object.position.applyMatrix4( worldRotationMatrix ); } } } else if ( _mode === "scale" ) { point.sub( offset ); point.multiply( parentScale ); if ( scope.space === "local" ) { var shouldLockScale = ( scope.options.scale && scope.options.scale.lock === true ); // WebTundra modification if ( scope.axis === "XYZ" || shouldLockScale ) { scale = 1 + ( ( shouldLockScale ? ( point.x + point.y + point.z ) : point.y ) / Math.max( oldScale.x, oldScale.y, oldScale.z ) ); scope.object.scale.x = oldScale.x * scale; scope.object.scale.y = oldScale.y * scale; scope.object.scale.z = oldScale.z * scale; } else { point.applyMatrix4( tempMatrix.getInverse( worldRotationMatrix ) ); if ( scope.axis === "X" ) scope.object.scale.x = oldScale.x * ( 1 + point.x / oldScale.x ); if ( scope.axis === "Y" ) scope.object.scale.y = oldScale.y * ( 1 + point.y / oldScale.y ); if ( scope.axis === "Z" ) scope.object.scale.z = oldScale.z * ( 1 + point.z / oldScale.z ); } } } else if ( _mode === "rotate" ) { point.sub( worldPosition ); point.multiply( parentScale ); tempVector.copy( offset ).sub( worldPosition ); tempVector.multiply( parentScale ); if ( scope.axis === "E" ) { point.applyMatrix4( tempMatrix.getInverse( lookAtMatrix ) ); tempVector.applyMatrix4( tempMatrix.getInverse( lookAtMatrix ) ); rotation.set( Math.atan2( point.z, point.y ), Math.atan2( point.x, point.z ), Math.atan2( point.y, point.x ) ); offsetRotation.set( Math.atan2( tempVector.z, tempVector.y ), Math.atan2( tempVector.x, tempVector.z ), Math.atan2( tempVector.y, tempVector.x ) ); tempQuaternion.setFromRotationMatrix( tempMatrix.getInverse( parentRotationMatrix ) ); quaternionE.setFromAxisAngle( eye, rotation.z - offsetRotation.z ); quaternionXYZ.setFromRotationMatrix( worldRotationMatrix ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionE ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionXYZ ); scope.object.quaternion.copy( tempQuaternion ); } else if ( scope.axis === "XYZE" ) { quaternionE.setFromEuler( point.clone().cross( tempVector ).normalize() ); // rotation axis tempQuaternion.setFromRotationMatrix( tempMatrix.getInverse( parentRotationMatrix ) ); quaternionX.setFromAxisAngle( quaternionE, - point.clone().angleTo( tempVector ) ); quaternionXYZ.setFromRotationMatrix( worldRotationMatrix ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionX ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionXYZ ); scope.object.quaternion.copy( tempQuaternion ); } else if ( scope.space === "local" ) { point.applyMatrix4( tempMatrix.getInverse( worldRotationMatrix ) ); tempVector.applyMatrix4( tempMatrix.getInverse( worldRotationMatrix ) ); rotation.set( Math.atan2( point.z, point.y ), Math.atan2( point.x, point.z ), Math.atan2( point.y, point.x ) ); offsetRotation.set( Math.atan2( tempVector.z, tempVector.y ), Math.atan2( tempVector.x, tempVector.z ), Math.atan2( tempVector.y, tempVector.x ) ); quaternionXYZ.setFromRotationMatrix( oldRotationMatrix ); if ( scope.rotationSnap !== null ) { quaternionX.setFromAxisAngle( unitX, Math.round( ( rotation.x - offsetRotation.x ) / scope.rotationSnap ) * scope.rotationSnap ); quaternionY.setFromAxisAngle( unitY, Math.round( ( rotation.y - offsetRotation.y ) / scope.rotationSnap ) * scope.rotationSnap ); quaternionZ.setFromAxisAngle( unitZ, Math.round( ( rotation.z - offsetRotation.z ) / scope.rotationSnap ) * scope.rotationSnap ); } else { quaternionX.setFromAxisAngle( unitX, rotation.x - offsetRotation.x ); quaternionY.setFromAxisAngle( unitY, rotation.y - offsetRotation.y ); quaternionZ.setFromAxisAngle( unitZ, rotation.z - offsetRotation.z ); } if ( scope.axis === "X" ) quaternionXYZ.multiplyQuaternions( quaternionXYZ, quaternionX ); if ( scope.axis === "Y" ) quaternionXYZ.multiplyQuaternions( quaternionXYZ, quaternionY ); if ( scope.axis === "Z" ) quaternionXYZ.multiplyQuaternions( quaternionXYZ, quaternionZ ); scope.object.quaternion.copy( quaternionXYZ ); } else if ( scope.space === "world" ) { rotation.set( Math.atan2( point.z, point.y ), Math.atan2( point.x, point.z ), Math.atan2( point.y, point.x ) ); offsetRotation.set( Math.atan2( tempVector.z, tempVector.y ), Math.atan2( tempVector.x, tempVector.z ), Math.atan2( tempVector.y, tempVector.x ) ); tempQuaternion.setFromRotationMatrix( tempMatrix.getInverse( parentRotationMatrix ) ); if ( scope.rotationSnap !== null ) { quaternionX.setFromAxisAngle( unitX, Math.round( ( rotation.x - offsetRotation.x ) / scope.rotationSnap ) * scope.rotationSnap ); quaternionY.setFromAxisAngle( unitY, Math.round( ( rotation.y - offsetRotation.y ) / scope.rotationSnap ) * scope.rotationSnap ); quaternionZ.setFromAxisAngle( unitZ, Math.round( ( rotation.z - offsetRotation.z ) / scope.rotationSnap ) * scope.rotationSnap ); } else { quaternionX.setFromAxisAngle( unitX, rotation.x - offsetRotation.x ); quaternionY.setFromAxisAngle( unitY, rotation.y - offsetRotation.y ); quaternionZ.setFromAxisAngle( unitZ, rotation.z - offsetRotation.z ); } quaternionXYZ.setFromRotationMatrix( worldRotationMatrix ); if ( scope.axis === "X" ) tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionX ); if ( scope.axis === "Y" ) tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionY ); if ( scope.axis === "Z" ) tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionZ ); tempQuaternion.multiplyQuaternions( tempQuaternion, quaternionXYZ ); scope.object.quaternion.copy( tempQuaternion ); } } scope.update(); scope.dispatchEvent( changeEvent ); scope.dispatchEvent( objectChangeEvent ); } function onPointerUp( event ) { if ( event.button !== undefined && event.button !== 0 ) return; if ( _lastMouseEvent === "down" && scope.axis === "S" ) { if ( scope.object ) { scope.object.position.y = 0; scope.update(); } } _lastMouseEvent = "up"; if ( _dragging && ( scope.axis !== null ) ) { mouseUpEvent.mode = _mode; scope.dispatchEvent( mouseUpEvent ) } _dragging = false; scope.translationSnapOffset = null; onPointerHover( event ); } function intersectObjects( pointer, objects ) { if (window.Tundra && window.Tundra.renderer) { // WebTundra modification var result = Tundra.renderer.raycast({ x : pointer.clientX, y : pointer.clientY, targets : objects, recursive : true, ignoreECModel : true }); if (result && result.object) { // mimic ray.intersectObjects response object return { distance: result.distance, point: result.pos, face: result.face, faceIndex: -1, object: result.object }; } } var rect = domElement.getBoundingClientRect(); var x = ( pointer.clientX - rect.left ) / rect.width; var y = ( pointer.clientY - rect.top ) / rect.height; pointerVector.set( ( x * 2 ) - 1, - ( y * 2 ) + 1 ); ray.setFromCamera( pointerVector, camera ); var intersections = ray.intersectObjects( objects, true ); return intersections[ 0 ] ? intersections[ 0 ] : false; } }; THREE.TransformControls.prototype = Object.create( THREE.Object3D.prototype ); THREE.TransformControls.prototype.constructor = THREE.TransformControls; }() ); return THREE.TransformControls; });
{ "content_hash": "0b4c8294770f1bb021fb3999cfe7cfcb", "timestamp": "", "source": "github", "line_count": 1261, "max_line_length": 193, "avg_line_length": 30.915146708961142, "alnum_prop": 0.6455981941309256, "repo_name": "realXtend/WebTundra", "id": "43607f34d324a552acf011223e06bd243fb8cb85", "size": "38984", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/lib/three/three-TransformControls.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "3229" }, { "name": "HTML", "bytes": "5322" }, { "name": "JavaScript", "bytes": "3727155" } ], "symlink_target": "" }
define({ "addDistance": "Tambahkan Unit Panjang", "addArea": "Tambahkan Unit Area", "label": "Label", "abbr": "Singkatan", "conversion": "Konversi", "actions": "Tindakan", "areaUnits": "Unit Area", "distanceUnits": "Unit Panjang", "kilometers": "Kilometer", "miles": "Mil", "meters": "Meter", "feet": "Kaki", "yards": "Yard", "nauticalmiles": "Mil Laut", "squareKilometers": "Kilometer persegi", "squareMiles": "Mil persegi", "acres": "Acre", "hectares": "Hektare", "squareMeters": "Meter persegi", "squareFeet": "Kaki persegi", "squareYards": "Yard persegi", "distance": "Jarak", "area": "Area", "kilometersAbbreviation": "km", "milesAbbreviation": "mi", "metersAbbreviation": "m", "feetAbbreviation": "ft", "yardsAbbreviation": "yd", "nauticalmilesAbbreviation": "nm", "squareKilometersAbbreviation": "km persegi", "squareMilesAbbreviation": "mi persegi", "acresAbbreviation": "ac", "hectaresAbbreviation": "ha", "squareMetersAbbreviation": "m persegi", "squareFeetAbbreviation": "kaki persegi", "squareYardsAbbreviation": "yd persegi", "defineUnits": "Tetapkan unit pengukuran.", "operationalLayer": "Tambahkan gambar sebagai layer operasional peta." });
{ "content_hash": "4fc4024863fdecc739833ea120ba687c", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 72, "avg_line_length": 30.825, "alnum_prop": 0.6666666666666666, "repo_name": "cmccullough2/cmv-wab-widgets", "id": "6742cdc409c223ac11217385e70d06dfc9d7c3c2", "size": "1233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wab/2.3/widgets/Draw/setting/nls/id/strings.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1198579" }, { "name": "HTML", "bytes": "946692" }, { "name": "JavaScript", "bytes": "22190423" }, { "name": "Pascal", "bytes": "4207" }, { "name": "TypeScript", "bytes": "102918" } ], "symlink_target": "" }
package com.flextrade.jfixture.jodatime.customisation; import com.flextrade.jfixture.NoSpecimen; import com.flextrade.jfixture.SpecimenBuilder; import com.flextrade.jfixture.SpecimenContext; import org.joda.time.Duration; import org.joda.time.ReadableDuration; public class ReadableDurationRelay implements SpecimenBuilder { @Override public Object create(Object request, SpecimenContext context) { if (!request.equals(ReadableDuration.class)) return new NoSpecimen(); return context.resolve(Duration.class); } }
{ "content_hash": "d3a814e166d64bc79af4b7531574e1fe", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 67, "avg_line_length": 30.944444444444443, "alnum_prop": 0.7719928186714542, "repo_name": "FlexTradeUKLtd/jfixture", "id": "3375eb058435ef63af59facf0fe8412b3ff5e137", "size": "557", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jfixture-jodatime/src/main/java/com/flextrade/jfixture/jodatime/customisation/ReadableDurationRelay.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "441727" }, { "name": "Shell", "bytes": "121" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>metacoq: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.0 / metacoq - 1.0~alpha+8.8</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> metacoq <small> 1.0~alpha+8.8 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-30 06:17:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-30 06:17:26 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.0 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://metacoq.github.io/metacoq&quot; dev-repo: &quot;git+https://github.com/MetaCoq/metacoq.git#coq-8.8&quot; bug-reports: &quot;https://github.com/MetaCoq/metacoq/issues&quot; authors: [&quot;Abhishek Anand &lt;aa755@cs.cornell.edu&gt;&quot; &quot;Simon Boulier &lt;simon.boulier@inria.fr&gt;&quot; &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; &quot;Yannick Forster &lt;forster@ps.uni-saarland.de&gt;&quot; &quot;Fabian Kunze &lt;fkunze@fakusb.de&gt;&quot; &quot;Gregory Malecha &lt;gmalecha@gmail.com&gt;&quot; &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Nicolas Tabareau &lt;nicolas.tabareau@inria.fr&gt;&quot; &quot;Théo Winterhalter &lt;theo.winterhalter@inria.fr&gt;&quot; ] license: &quot;MIT&quot; depends: [ &quot;ocaml&quot; {&gt; &quot;4.02.3&quot;} &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} &quot;coq-metacoq-template&quot; {= version} &quot;coq-metacoq-checker&quot; {= version} &quot;coq-metacoq-pcuic&quot; {= version} &quot;coq-metacoq-safechecker&quot; {= version} &quot;coq-metacoq-erasure&quot; {= version} &quot;coq-metacoq-translations&quot; {= version} ] synopsis: &quot;A meta-programming framework for Coq&quot; description: &quot;&quot;&quot; MetaCoq is a meta-programming framework for Coq. The meta-package includes the template-coq library, unverified checker for Coq, PCUIC development including a verified translation from Coq to PCUIC, safe checker and erasure for PCUIC and example translations. See individual packages for more detailed descriptions. &quot;&quot;&quot; url { src: &quot;https://github.com/MetaCoq/metacoq/archive/1.0-alpha+8.8.tar.gz&quot; checksum: &quot;sha256=c2fe122ad30849e99c1e5c100af5490cef0e94246f8eb83f6df3f2ccf9edfc04&quot; }</pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-metacoq.1.0~alpha+8.8 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0). The following dependencies couldn&#39;t be met: - coq-metacoq -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq.1.0~alpha+8.8</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "a3b9f1a5ba9c390a66deb46c2a42a61c", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 157, "avg_line_length": 43.01685393258427, "alnum_prop": 0.5587044534412956, "repo_name": "coq-bench/coq-bench.github.io", "id": "ffa03b8affd87f218739e8b2944d1bd4307b4aa6", "size": "7660", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.10.0/metacoq/1.0~alpha+8.8.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System; using System.Net; using System.Net.Http; using System.Web.Http; using BlueYonder.DataAccess.Interfaces; using BlueYonder.Entities; using System.ServiceModel; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using BlueYonder.Companion.Entities; using BlueYonder.Companion.Entities.Mappers; using BlueYonder.DataAccess.Repositories; namespace BlueYonder.Companion.Controllers { public class ReservationsController : ApiController { public IReservationRepository Reservations { get; set; } public ITravelerRepository Travelers { get; set; } public ReservationsController() { Reservations = new ReservationRepository(); Travelers = new TravelerRepository(); } public HttpResponseMessage Get(int id) { var reservation = Reservations.GetSingle(id); // Handling the HTTP status codes if (reservation != null) return Request.CreateResponse<ReservationDTO> (HttpStatusCode.OK, reservation.ToReservationDTO()); else return Request.CreateResponse(HttpStatusCode.NotFound); } public HttpResponseMessage Get(string travelerId) { int.TryParse(travelerId, out int travelerIdAsInt); var traveler = Travelers.FindBy(t => t.TravelerId == travelerIdAsInt).FirstOrDefault(); if (traveler == null) return Request.CreateResponse(HttpStatusCode.NotFound); var reservations = Reservations.FindBy(r => r.TravelerId == traveler.TravelerId); var reservationsDto = from r in reservations.ToList() select r.ToReservationDTO(); return Request.CreateResponse(HttpStatusCode.OK, reservationsDto); } public HttpResponseMessage Post([FromBody]ReservationDTO reservation) { // be availabe on the database before you persist the reservation. note that these schdules // might already be persisted if several consequent calls were made. // saving the new order to the database Reservation newReservation = reservation.FromReservationDTO(); // newReservation.ConfirmationCode = confirmationCode; Reservations.Add(newReservation); Reservations.Save(); // creating the response, with three key features: // 1. the newly saved entity // 2. 201 Created status code // 3. Location header with the location of the new resource var response = Request.CreateResponse(HttpStatusCode.Created, newReservation); response.Headers.Location = new Uri(Request.RequestUri, newReservation.ReservationId.ToString()); return response; } public HttpResponseMessage Delete(int id) { var reservation = Reservations.GetSingle(id); // returning 404 if the entity doesn't exist if (reservation == null) return Request.CreateResponse(HttpStatusCode.NotFound); Reservations.Delete(reservation); Reservations.Save(); return Request.CreateResponse(HttpStatusCode.OK); } } }
{ "content_hash": "cb0fcff8e13c4b9c4c0f9a954766767d", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 109, "avg_line_length": 36.30769230769231, "alnum_prop": 0.6513317191283293, "repo_name": "MicrosoftLearning/20487-DevelopingWindowsAzureAndWebServices", "id": "4e6ed9c6ca587a8ab108665cbc16107191ecad47", "size": "3306", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Allfiles/20487C/Mod03/LabFiles/begin/BlueYonder.Companion/BlueYonder.Companion.Controllers/ReservationsController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "32247" }, { "name": "C#", "bytes": "8538296" }, { "name": "CSS", "bytes": "629086" }, { "name": "HTML", "bytes": "271909" }, { "name": "JavaScript", "bytes": "2979953" }, { "name": "PowerShell", "bytes": "78421" }, { "name": "Smalltalk", "bytes": "24" } ], "symlink_target": "" }
#include <stdint.h> /** * Gets the amount of space available */ uint64_t GetDiskSpace(const char *path, uint64_t *available, uint64_t *total, uint64_t *free); /** * format(type) that all the following error checking functions follow */ typedef bool (*diskErrFunc_t)(uint64_t); /** * Returns whether the error is likely a Pathing error */ bool isErrBadPath(uint64_t error); /** * Returns whether the error is likely a permissions error */ bool isErrDenied(uint64_t error); /** * Returns whether the error is likely an IO error */ bool isErrIO(uint64_t error);
{ "content_hash": "a303af29ec0687ba03ec1587d62612e6", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 94, "avg_line_length": 18.677419354838708, "alnum_prop": 0.7046632124352331, "repo_name": "Saevon/node-diskfree", "id": "908534b7832439c3cd487e5d2e17f89bc550b518", "size": "579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/disk.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1299" }, { "name": "C++", "bytes": "11400" }, { "name": "JavaScript", "bytes": "1254" }, { "name": "Makefile", "bytes": "1453" }, { "name": "Python", "bytes": "199" } ], "symlink_target": "" }
// Provides base class sap.ui.core.Control for all controls sap.ui.define(['jquery.sap.global', './CustomStyleClassSupport', './Element', './UIArea', /* cyclic: './RenderManager', */ './ResizeHandler', './BusyIndicatorUtils'], function(jQuery, CustomStyleClassSupport, Element, UIArea, ResizeHandler, BusyIndicatorUtils) { "use strict"; /** * Creates and initializes a new control with the given <code>sId</code> and settings. * * The set of allowed entries in the <code>mSettings</code> object depends on the concrete * subclass and is described there. See {@link sap.ui.core.Element} for a general description of this * argument. * * The settings supported by Control are: * <ul> * <li>Properties * <ul> * <li>{@link #getBusy busy} : boolean (default: false)</li> * <li>{@link #getBusyIndicatorDelay busyIndicatorDelay} : int (default: 1000)</li> * </ul> * </li> * </ul> * * @param {string} [sId] optional id for the new control; generated automatically if no non-empty id is given * Note: this can be omitted, no matter whether <code>mSettings</code> will be given or not! * @param {object} [mSettings] optional map/JSON-object with initial settings for the new control * @public * * @class Base Class for Controls. * @extends sap.ui.core.Element * @abstract * @author Martin Schaus, Daniel Brinkmann * @version 1.36.6 * @alias sap.ui.core.Control * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var Control = Element.extend("sap.ui.core.Control", /** @lends sap.ui.core.Control */ { metadata : { stereotype : "control", "abstract" : true, publicMethods: ["placeAt", "attachBrowserEvent", "detachBrowserEvent", "getControlsByFieldGroup", "triggerValidateFieldGroup", "checkFieldGroupIds"], library: "sap.ui.core", properties : { /** * Whether the control is currently in busy state. */ "busy" : {type: "boolean", defaultValue: false}, /** * The delay in milliseconds, after which the busy indicator will show up for this control. */ "busyIndicatorDelay" : {type: "int", defaultValue: 1000}, /** * Whether the control should be visible on the screen. If set to false, a placeholder is rendered instead of the real control */ "visible" : { type: "boolean", group : "Appearance", defaultValue: true }, /** * The IDs of a logical field group that this control belongs to. All fields in a logical field group should share the same <code>fieldGroupId</code>. * Once a logical field group is left, the validateFieldGroup event is raised. * * @see {sap.ui.core.Control.attachValidateFieldGroup} * @since 1.31 */ "fieldGroupIds" : { type: "string[]", defaultValue: [] } }, events : { /** * Event is fired if a logical field group defined by <code>fieldGroupIds</code> of a control was left or the user explicitly pressed a validation key combination. * Use this event to validate data of the controls belonging to a field group. * @see {sap.ui.core.Control.setFieldGroupId} */ validateFieldGroup : { enableEventBubbling:true, parameters : { /** * field group IDs of the logical field groups to validate */ fieldGroupIds : {type : "string[]"} } } } }, constructor : function(sId, mSettings) { // TODO initialization should happen in init // but many of the existing controls don't call super.init() // As a workaround I moved the initialization of bAllowTextSelection here // so that it doesn't overwrite settings in init() (e.g. ListBox) this.bAllowTextSelection = true; Element.apply(this,arguments); this.bOutput = this.getDomRef() != null; // whether this control has already produced output if (this._sapUiCoreLocalBusy_initBusyIndicator) { this._sapUiCoreLocalBusy_initBusyIndicator(); } }, renderer : null // Control has no renderer }); /** * Overrides {@link sap.ui.core.Element#clone Element.clone} to clone additional * internal state. * * The additionally cloned information contains: * <ul> * <li>browser event handlers attached with {@link #attachBrowserEvent} * <li>text selection behavior * <li>style classes added with {@link #addStyleClass} * </ul> * * @param {string} [sIdSuffix] a suffix to be appended to the cloned element id * @param {string[]} [aLocalIds] an array of local IDs within the cloned hierarchy (internally used) * @return {sap.ui.core.Element} reference to the newly created clone * @protected */ Control.prototype.clone = function() { var oClone = Element.prototype.clone.apply(this, arguments); if ( this.aBindParameters ) { for (var i = 0, l = this.aBindParameters.length; i < l; i++) { var aParams = this.aBindParameters[i]; oClone.attachBrowserEvent(aParams.sEventType, aParams.fnHandler, aParams.oListener !== this ? aParams.oListener : undefined); } } oClone.bAllowTextSelection = this.bAllowTextSelection; return oClone; }; // must appear after clone() method and metamodel definition CustomStyleClassSupport.apply(Control.prototype); /** * Checks whether the control is still active (part of the active DOM) * * @return {boolean} whether the control is still in the active DOM * @private */ Control.prototype.isActive = function() { return jQuery.sap.domById(this.sId) != null; }; /** * Triggers rerendering of this element and its children. * * As <code>sap.ui.core.Element</code> "bubbles up" the invalidate, changes to children * potentially result in rerendering of the whole sub tree. * * @param {object} oOrigin * @protected */ Control.prototype.invalidate = function(oOrigin) { var oUIArea; if ( this.bOutput && (oUIArea = this.getUIArea()) ) { // if this control has been rendered before (bOutput) // and if it is contained in an UIArea (!!oUIArea) // then control re-rendering can be used (see UIArea.rerender() for details) // // The check for bOutput is necessary as the control // re-rendering needs to identify the previous rendering results. // Otherwise it wouldn't be able to replace them. // // Note about destroy(): when this control is currently in the process of being // destroyed, registering it for an autonomous re-rendering doesn't make sense. // In most cases, invalidation of the parent also doesn't make sense, // but there might be composite controls that rely on being invalidated when // a child is destroyed, so we keep the invalidation propagation untouched. if ( !this._bIsBeingDestroyed ) { oUIArea.addInvalidatedControl(this); } } else { // else we bubble up the hierarchy var oParent = this.getParent(); if (oParent && ( this.bOutput /* && !this.getUIArea() */ || /* !this.bOutput && */ !(this.getVisible && this.getVisible() === false))) { // Note: the two comments in the condition above show additional conditions // that help to understand the logic. As they are always fulfilled, // they have been omitted for better performance. // // If this control has a parent but either // - has produced output before ('this.bOutput') but is not part of an UIArea (!this.getUIArea()) // - or if it didn't produce output (!this.bOutput') before and is/became visible // then invalidate the parent to request re-rendering // // The first commented condition is always true, otherwise the initial if condition // in this method would have been met. The second one must be true as well because of the // short evaluation logic of JavaScript. When bOutput is true the second half of the Or won't be processed. oParent.invalidate(this); } } }; /** * Tries to replace its DOM reference by re-rendering. * @protected */ Control.prototype.rerender = function() { UIArea.rerenderControl(this); }; /** * Defines whether the user can select text inside this control. * Defaults to <code>true</code> as long as this method has not been called. * * <b>Note:</b>This only works in IE and Safari; for Firefox the element's style must * be set to: * <pre> * -moz-user-select: none; * </pre> * in order to prevent text selection. * * @param {boolean} bAllow whether to allow text selection or not * @return {sap.ui.core.Control} Returns <code>this</code> to allow method chaining * @public */ Control.prototype.allowTextSelection = function(bAllow) { this.bAllowTextSelection = bAllow; return this; }; /** * The string given as "sStyleClass" will be added to the "class" attribute of this control's root HTML element. * * This method is intended to be used to mark controls as being of a special type for which * special styling can be provided using CSS selectors that reference this style class name. * * <pre> * Example: * myButton.addStyleClass("myRedTextButton"); // add a CSS class to one button instance * * ...and in CSS: * .myRedTextButton { * color: red; * } * </pre> * * This will add the CSS class "myRedTextButton" to the Button HTML and the CSS code above will then * make the text in this particular button red. * * Only characters allowed inside HTML attributes are allowed. * Quotes are not allowed and this method will ignore any strings containing quotes. * Strings containing spaces are interpreted as ONE custom style class (even though CSS selectors interpret them * as different classes) and can only removed later by calling removeStyleClass() with exactly the * same (space-containing) string as parameter. * Multiple calls with the same sStyleClass will have no different effect than calling once. * If sStyleClass is null, the call is ignored. * * @name sap.ui.core.Control.prototype.addStyleClass * @function * * @param {string} sStyleClass the CSS class name to be added * @return {sap.ui.core.Control} Returns <code>this</code> to allow method chaining * @public */ /** * Removes the given string from the list of custom style classes that have been set previously. * Regular style classes like "sapUiBtn" cannot be removed. * * @name sap.ui.core.Control.prototype.removeStyleClass * @function * * @param {string} sStyleClass the style to be removed * @return {sap.ui.core.Control} Returns <code>this</code> to allow method chaining * @public */ /** * The string given as "sStyleClass" will be be either added to or removed from the "class" attribute of this control's root HTML element, * depending on the value of "bAdd": if bAdd is true, sStyleClass will be added. * If bAdd is not given, sStyleClass will be removed if it is currently present and will be added if not present. * If sStyleClass is null, the call is ignored. * * See addStyleClass and removeStyleClass for further documentation. * * @name sap.ui.core.Control.prototype.toggleStyleClass * @function * * @param {string} sStyleClass the CSS class name to be added or removed * @param {boolean} bAdd whether sStyleClass should be added (or removed); when this parameter is not given, sStyleClass will be toggled (removed, if present, and added if not present) * @return {sap.ui.core.Control} Returns <code>this</code> to allow method chaining * @public */ /** * Returns true if the given style class string is valid and if this control has this style class set * via a previous call to addStyleClass(). * * @name sap.ui.core.Control.prototype.hasStyleClass * @function * * @param {string} sStyleClass the style to check for * @type boolean * @return whether the given style has been set before * @public */ /** * Allows binding handlers for any native browser event to the root HTML element of this Control. This internally handles * DOM element replacements caused by re-rendering. * * IMPORTANT: * This should be only used as FALLBACK when the Control events do not cover a specific use-case! Always try using * SAPUI5 control events, as e.g. accessibility-related functionality is then provided automatically. * E.g. when working with a sap.ui.commons.Button, always use the Button's "press" event, not the native "click" event, because * "press" is also guaranteed to be fired when certain keyboard activity is supposed to trigger the Button. * * In the event handler, "this" refers to the Control - not to the root DOM element like in jQuery. While the DOM element can * be used and modified, the general caveats for working with SAPUI5 control DOM elements apply. In particular the DOM element * may be destroyed and replaced by a new one at any time, so modifications that are required to have permanent effect may not * be done. E.g. use Control.addStyleClass() instead if the modification is of visual nature. * * Use detachBrowserEvent() to remove the event handler(s) again. * * @param {string} [sEventType] A string containing one or more JavaScript event types, such as "click" or "blur". * @param {function} [fnHandler] A function to execute each time the event is triggered. * @param {object} [oListener] The object, that wants to be notified, when the event occurs * @return {sap.ui.core.Control} Returns <code>this</code> to allow method chaining * @public */ Control.prototype.attachBrowserEvent = function(sEventType, fnHandler, oListener) { if (sEventType && (typeof (sEventType) === "string")) { // do nothing if the first parameter is empty or not a string if (fnHandler && typeof (fnHandler) === "function") { // also do nothing if the second parameter is not a function // store the parameters for bind() if (!this.aBindParameters) { this.aBindParameters = []; } oListener = oListener || this; // FWE jQuery.proxy can't be used as it breaks our contract when used with same function but different listeners var fnProxy = function() { fnHandler.apply(oListener, arguments); }; this.aBindParameters.push({ sEventType: sEventType, fnHandler: fnHandler, oListener: oListener, fnProxy : fnProxy }); if (!this._sapui_bInAfterRenderingPhase) { // if control is rendered, directly call bind() this.$().bind(sEventType, fnProxy); } } } return this; }; /** * Removes event handlers which have been previously attached using {@link #attachBrowserEvent}. * * Note: listeners are only removed, if the same combination of event type, callback function * and context object is given as in the call to <code>attachBrowserEvent</code>. * * @param {string} [sEventType] A string containing one or more JavaScript event types, such as "click" or "blur". * @param {function} [fnHandler] The function that is to be no longer executed. * @param {object} [oListener] The context object that was given in the call to attachBrowserEvent. * @public */ Control.prototype.detachBrowserEvent = function(sEventType, fnHandler, oListener) { if (sEventType && (typeof (sEventType) === "string")) { // do nothing if the first parameter is empty or not a string if (fnHandler && typeof (fnHandler) === "function") { // also do nothing if the second parameter is not a function var $ = this.$(),i,oParamSet; oListener = oListener || this; // remove the bind parameters from the stored array if (this.aBindParameters) { for (i = this.aBindParameters.length - 1; i >= 0; i--) { oParamSet = this.aBindParameters[i]; if ( oParamSet.sEventType === sEventType && oParamSet.fnHandler === fnHandler && oParamSet.oListener === oListener ) { this.aBindParameters.splice(i, 1); // if control is rendered, directly call unbind() $.unbind(sEventType, oParamSet.fnProxy); } } } } } return this; }; /** * Returns a renderer for this control instance. * * It is retrieved using the RenderManager as done during rendering. * * @return {object} a Renderer suitable for this Control instance. * @protected */ Control.prototype.getRenderer = function () { //TODO introduce caching? return sap.ui.core.RenderManager.getRenderer(this); }; /** * Puts <code>this</code> control into the specified container (<code>oRef</code>) at the given * position (<code>oPosition</code>). * * First it is checked whether <code>oRef</code> is a container element / control (has a * multiple aggregation with type <code>sap.ui.core.Control</code> and name 'content') or is an Id String * of such an container. * If this is not the case <code>oRef</code> can either be a Dom Reference or Id String of the UIArea * (if it does not yet exist implicitly a new UIArea is created), * * The <code>oPosition</code> can be one of the following: * * <ul> * <li>"first": The control is added as the first element to the container.</li> * <li>"last": The control is added as the last element to the container (default).</li> * <li>"only": All existing children of the container are removed (not destroyed!) and the control is added as new child.</li> * <li><i>index</i>: The control is added at the specified <i>index</i> to the container.</li> * </ul> * * @param {string|Element|sap.ui.core.Control} oRef container into which the control should be put * @param {string|int} oPosition Describes the position where the control should be put into the container * @return {sap.ui.core.Control} Returns <code>this</code> to allow method chaining * @public */ Control.prototype.placeAt = function(oRef, oPosition) { var oCore = sap.ui.getCore(); if (oCore.isInitialized()) { // core already initialized, do it now // 1st try to resolve the oRef as a Container control var oContainer = oRef; if (typeof oContainer === "string") { oContainer = oCore.byId(oRef); } // if no container control is found use the corresponding UIArea var bIsUIArea = false; if (!(oContainer instanceof Element)) { oContainer = oCore.createUIArea(oRef); bIsUIArea = true; } if (!oContainer) { return this; } if (!bIsUIArea) { var oContentAggInfo = oContainer.getMetadata().getAggregation("content"); var bContainerSupportsPlaceAt = true; if (oContentAggInfo) { if (!oContentAggInfo.multiple || oContentAggInfo.type != "sap.ui.core.Control") { bContainerSupportsPlaceAt = false; } } else if (!oContainer.addContent || !oContainer.insertContent || !oContainer.removeAllContent) { //Temporary workaround for sap.ui.commons.AbsoluteLayout to enable // placeAt even when no content aggregation is available. // TODO: Find a proper solution bContainerSupportsPlaceAt = false; } if (!bContainerSupportsPlaceAt) { jQuery.sap.log.warning("placeAt cannot be processed because container " + oContainer + " does not have an aggregation 'content'."); return this; } } if (typeof oPosition === "number") { oContainer.insertContent(this, oPosition); } else { oPosition = oPosition || "last"; //"last" is default switch (oPosition) { case "last": oContainer.addContent(this); break; case "first": oContainer.insertContent(this, 0); break; case "only": oContainer.removeAllContent(); oContainer.addContent(this); break; default: jQuery.sap.log.warning("Position " + oPosition + " is not supported for function placeAt."); } } } else { // core not yet initialized, defer execution var that = this; oCore.attachInitEvent(function () { that.placeAt(oRef, oPosition); }); } return this; }; /* * Event handling */ /** * Cancels user text selection if text selection is disabled for this control. * See the {@link #allowTextSelection} method. * @private */ Control.prototype.onselectstart = function (oBrowserEvent) { if (!this.bAllowTextSelection) { oBrowserEvent.preventDefault(); oBrowserEvent.stopPropagation(); } }; /* * Rendering */ /** * Function is called before the rendering of the control is started. * * Applications must not call this hook method directly, it is called by the framework. * * Subclasses of Control should override this hook to implement any necessary actions before the rendering. * * @function * @name sap.ui.core.Control.prototype.onBeforeRendering * @protected */ //sap.ui.core.Control.prototype.onBeforeRendering = function() {}; /** * Function is called when the rendering of the control is completed. * * Applications must not call this hook method directly, it is called by the framework. * * Subclasses of Control should override this hook to implement any necessary actions after the rendering. * * @function * @name sap.ui.core.Control.prototype.onAfterRendering * @protected */ //sap.ui.core.Control.prototype.onAfterRendering = function() {}; /** * Returns the DOMNode Id to be used for the "labelFor" attribute of the label. * * By default, this is the Id of the control itself. * * @return {string} Id to be used for the <code>labelFor</code> * @public */ Control.prototype.getIdForLabel = function () { return this.getId(); }; Control.prototype.destroy = function(bSuppressInvalidate) { // avoid rerendering this._bIsBeingDestroyed = true; //Cleanup Busy Indicator this._cleanupBusyIndicator(); ResizeHandler.deregisterAllForControl(this.getId()); // Controls can have their visible-property set to "false" in which case the Element's destroy method will# // fail to remove the placeholder content from the DOM. We have to remove it here in that case if (!this.getVisible()) { var oPlaceholder = document.getElementById(sap.ui.core.RenderManager.createInvisiblePlaceholderId(this)); if (oPlaceholder && oPlaceholder.parentNode) { oPlaceholder.parentNode.removeChild(oPlaceholder); } } Element.prototype.destroy.call(this, bSuppressInvalidate); }; (function() { var sPreventedEvents = "focusin focusout keydown keypress keyup mousedown touchstart mouseup touchend click", oBusyIndicatorDelegate = { onAfterRendering: function() { if (this.getBusy() && this.$() && !this._busyIndicatorDelayedCallId && !this.$("busyIndicator").length) { // Also use the BusyIndicatorDelay when a control is initialized // with "busy = true". If the delayed call was already initialized // skip any further call if the control was re-rendered while // the delay is running. var iDelay = this.getBusyIndicatorDelay(); // Only do it via timeout if there is a delay. Otherwise append the // BusyIndicator immediately if (iDelay) { this._busyIndicatorDelayedCallId = jQuery.sap.delayedCall(iDelay, this, fnAppendBusyIndicator); } else { fnAppendBusyIndicator.call(this); } } } }, fnAppendBusyIndicator = function() { var $this = this.$(this._sBusySection), aForbiddenTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"]; //If there is a pending delayed call to append the busy indicator, we can clear it now if (this._busyIndicatorDelayedCallId) { jQuery.sap.clearDelayedCall(this._busyIndicatorDelayedCallId); delete this._busyIndicatorDelayedCallId; } // if no busy section/control jquery instance could be retrieved -> the control is not part of the dom anymore // this might happen in certain scenarios when e.g. a dialog is closed faster than the busyIndicatorDelay if (!$this || $this.length === 0) { jQuery.sap.log.warning("BusyIndicator could not be rendered. The outer control instance is not valid anymore."); return; } //Check if DOM Element where the busy indicator is supposed to be placed can handle content var sTag = $this.get(0) && $this.get(0).tagName; if (sTag && jQuery.inArray(sTag.toLowerCase(), aForbiddenTags) >= 0) { jQuery.sap.log.warning("BusyIndicator cannot be placed in elements with tag '" + sTag + "'."); return; } //check if the control has static position, if this is the case we need to change it, //because we relay on relative/absolute/fixed positioning if ($this.css('position') == 'static') { this._busyStoredPosition = 'static'; $this.css('position', 'relative'); } //Append busy indicator to control DOM this._$BusyIndicator = BusyIndicatorUtils.addHTML($this, this.getId() + "-busyIndicator"); BusyIndicatorUtils.animateIE9.start(this._$BusyIndicator); fnHandleInteraction.apply(this, [true]); }, fnHandleInteraction = function(bBusy) { var $this = this.$(this._sBusySection); if (bBusy) { // all focusable elements must be processed for the "tabindex=-1" // attribute. The dropdownBox for example has got two focusable elements // (arrow and input field) and both shouldn't be focusable. Otherwise // the input field will still be focused on keypress (tab) because the // browser focuses the element var $TabRefs = $this.find(":sapTabbable"), that = this; this._busyTabIndices = []; // if only the control itself without any tabrefs was found // block the events as well this._busyTabIndices.push({ ref : $this, tabindex : $this.attr('tabindex') }); $this.attr('tabindex', -1); $this.bind(sPreventedEvents, fnPreserveEvents); $TabRefs.each(function(iIndex, oObject) { var $Ref = jQuery(oObject), iTabIndex = $Ref.attr('tabindex'); if (iTabIndex < 0) { return true; } that._busyTabIndices.push({ ref: $Ref, tabindex: iTabIndex }); $Ref.attr('tabindex', -1); $Ref.bind(sPreventedEvents, fnPreserveEvents); }); } else { if (this._busyTabIndices) { jQuery.each(this._busyTabIndices, function(iIndex, oObject) { if (oObject.tabindex) { // if there was no tabindex before it was added by the BusyIndicator // the previous value is "undefined". And this value can't be set // so the attribute remains at the DOM-ref. So if there was no tabindex // attribute before the whole attribute should be removed again. oObject.ref.attr('tabindex', oObject.tabindex); } else { oObject.ref.removeAttr('tabindex'); } oObject.ref.unbind(sPreventedEvents, fnPreserveEvents); }); } this._busyTabIndices = []; } }, fnPreserveEvents = function(oEvent) { jQuery.sap.log.debug("Local Busy Indicator Event Suppressed: " + oEvent.type); oEvent.preventDefault(); oEvent.stopImmediatePropagation(); }; /** * Set the controls busy state. * * @param {boolean} bBusy The new busy state to be set * @return {sap.ui.core.Control} <code>this</code> to allow method chaining * @public */ Control.prototype.setBusy = function (bBusy, sBusySection /* this is an internal parameter to apply partial local busy indicator for a specific section of the control */) { this._sBusySection = sBusySection; var $this = this.$(this._sBusySection); //If the new state is already set, we don't need to do anything if (bBusy == this.getProperty("busy")) { return this; } //No rerendering this.setProperty("busy", bBusy, /*bSuppressInvalidate*/ true); if (bBusy) { this.addDelegate(oBusyIndicatorDelegate, false, this); } else { this.removeDelegate(oBusyIndicatorDelegate); //If there is a pending delayed call we clear it if (this._busyIndicatorDelayedCallId) { jQuery.sap.clearDelayedCall(this._busyIndicatorDelayedCallId); delete this._busyIndicatorDelayedCallId; } } //If no domref exists stop here. if (!this.getDomRef()) { return this; } if (bBusy) { if (this.getBusyIndicatorDelay() <= 0) { fnAppendBusyIndicator.apply(this); } else { this._busyIndicatorDelayedCallId = jQuery.sap.delayedCall(this.getBusyIndicatorDelay(), this, fnAppendBusyIndicator); } } else { //Remove the busy indicator from the DOM this.$("busyIndicator").remove(); this.$().removeClass('sapUiLocalBusy'); //Unset the actual DOM Element´s 'aria-busy' this.$().removeAttr('aria-busy'); //Reset the position style to its original state if (this._busyStoredPosition) { $this.css('position', this._busyStoredPosition); delete this._busyStoredPosition; } fnHandleInteraction.apply(this, [false]); BusyIndicatorUtils.animateIE9.stop(this._$BusyIndicator); } return this; }; /** * Check if the control is currently in busy state * * @public * @deprecated Use getBusy instead * @return boolean */ Control.prototype.isBusy = function() { return this.getProperty("busy"); }; /** * Define the delay, after which the busy indicator will show up * * @public * @param {int} iDelay The delay in ms * @return {sap.ui.core.Control} <code>this</code> to allow method chaining */ Control.prototype.setBusyIndicatorDelay = function(iDelay) { this.setProperty("busyIndicatorDelay", iDelay, /*bSuppressInvalidate*/ true); return this; }; /** * Cleanup all timers which might have been created by the busy indicator * * @private */ Control.prototype._cleanupBusyIndicator = function() { if (this._busyIndicatorDelayedCallId) { jQuery.sap.clearDelayedCall(this._busyIndicatorDelayedCallId); delete this._busyIndicatorDelayedCallId; } BusyIndicatorUtils.animateIE9.stop(this._$BusyIndicator); }; /** * Returns a copy of the field group IDs array. Modification of the field group IDs * need to call {@link #setFieldGroupIds setFieldGroupIds} to apply the changes. * * @name sap.ui.core.Control.prototype.getFieldGroupIds * @function * * @return {string[]} copy of the field group IDs * @public */ /** * Returns a list of all child controls with a field group ID. * See {@link #checkFieldGroupIds checkFieldGroupIds} for a description of the * <code>vFieldGroupIds</code> parameter. * Associated controls are not taken into account. * * @param {string|string[]} [vFieldGroupIds] ID of the field group or an array of field group IDs to match * @return {sap.ui.core.Control[]} The list of controls with a field group ID * @public */ Control.prototype.getControlsByFieldGroupId = function(vFieldGroupIds) { return this.findAggregatedObjects(true, function(oElement) { if (oElement instanceof Control) { return oElement.checkFieldGroupIds(vFieldGroupIds); } return false; }); }; /** * Returns whether the control has a given field group. * If <code>vFieldGroupIds</code> is not given it checks whether at least one field group ID is given for this control. * If <code>vFieldGroupIds</code> is an empty array or empty string, true is returned if there is no field group ID set for this control. * If <code>vFieldGroupIds</code> is a string array or a string all expected field group IDs are checked and true is returned if all are contained for given for this control. * The comma delimiter can be used to seperate multiple field group IDs in one string. * * @param {string|string[]} [vFieldGroupIds] ID of the field group or an array of field group IDs to match * @return {boolean} true if a field group ID matches * @public */ Control.prototype.checkFieldGroupIds = function(vFieldGroupIds) { if (typeof vFieldGroupIds === "string") { if (vFieldGroupIds === "") { return this.checkFieldGroupIds([]); } return this.checkFieldGroupIds(vFieldGroupIds.split(",")); } var aFieldGroups = this._getFieldGroupIds(); if (jQuery.isArray(vFieldGroupIds)) { var iFound = 0; for (var i = 0; i < vFieldGroupIds.length; i++) { if (aFieldGroups.indexOf(vFieldGroupIds[i]) > -1) { iFound++; } } return iFound === vFieldGroupIds.length; } else if (!vFieldGroupIds && aFieldGroups.length > 0) { return true; } return false; }; /** * Triggers the validateFieldGroup event for this control. * Called by sap.ui.core.UIArea if a field group should be validated after is loses the focus or a validation key combibation was pressed. * The validation key is defined in the UI area <code>UIArea._oFieldGroupValidationKey</code> * * @see {sap.ui.core.Control.attachValidateFieldGroup} * * @public */ Control.prototype.triggerValidateFieldGroup = function(aFieldGroupIds) { this.fireValidateFieldGroup({ fieldGroupIds : aFieldGroupIds }); }; })(); return Control; });
{ "content_hash": "27d2b12250e1cc422728268c74bb649a", "timestamp": "", "source": "github", "line_count": 892, "max_line_length": 185, "avg_line_length": 36.860986547085204, "alnum_prop": 0.6858576642335766, "repo_name": "zaveryukha/openui5_demo", "id": "295d8483bf5d7857d281bee08568936f07ce8610", "size": "33066", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc_root/resources/sap_library/sap/ui/core/Control-dbg.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4638706" }, { "name": "HTML", "bytes": "77356" }, { "name": "JavaScript", "bytes": "32024699" }, { "name": "Nginx", "bytes": "1629" } ], "symlink_target": "" }
package com.github.chen0040.leetcode.day10.easy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by xschen on 5/8/2017. * * summary: * Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. * Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. * The order of output does not matter. * * link: https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ */ public class FindAllAnagrams { public class Solution { public List<Integer> findAnagrams(String s, String p) { if(p.length()==0) return new ArrayList<Integer>(); Map<Character, Integer> p_states = new HashMap<Character, Integer>(); for(int i = 0; i < p.length(); ++i) { char c = p.charAt(i); p_states.put(c, p_states.getOrDefault(c, 0) + 1); } List<Integer> result = new ArrayList<Integer>(); Map<Character, Integer> s_states = new HashMap<Character, Integer>(); char prev_c = '0'; for(int i=0; i < s.length(); ++i){ char c = s.charAt(i); s_states.put(c, s_states.getOrDefault(c, 0) + 1); if(i >= p.length()-1){ boolean anagram = true; for(Map.Entry<Character, Integer> entry : p_states.entrySet()){ char c2 = entry.getKey(); int count = entry.getValue(); if(!s_states.containsKey(c2)) { anagram = false; break; } if(s_states.get(c2).intValue() != count) { anagram = false; break; } } if(anagram){ result.add(i - p.length() + 1); } prev_c = s.charAt(i-p.length()+1); if(s_states.containsKey(prev_c) && s_states.get(prev_c) > 1){ s_states.put(prev_c, s_states.get(prev_c) - 1); } else { s_states.remove(prev_c); } } } return result; } private String getState(Map<Character, Integer> state){ StringBuilder sb = new StringBuilder(); for(Map.Entry<Character, Integer> entry : state.entrySet()) { sb.append(entry.getKey() + "" + entry.getValue()); } return sb.toString(); } } }
{ "content_hash": "e79796b4d3e7df6125b4cce2a5375dfd", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 124, "avg_line_length": 33.60526315789474, "alnum_prop": 0.5199686765857479, "repo_name": "chen0040/java-leetcode", "id": "a8ae88d9ceed8b8220f28b20a80f96cd7b6eab02", "size": "2554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/github/chen0040/leetcode/day10/easy/FindAllAnagrams.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "429846" }, { "name": "SQLPL", "bytes": "393" }, { "name": "Shell", "bytes": "541" } ], "symlink_target": "" }
<?php /* TwigBundle:Exception:exception.html.twig */ class __TwigTemplate_3bf68954aad30659e4e7eb8140b1e9684baf54d412b0662f9da1539b65d2208c extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<div class=\"sf-exceptionreset\"> <div class=\"block_exception\"> <div class=\"block_exception_detected clear_fix\"> <div class=\"illustration_exception\"> <img alt=\"Exception detected!\" src=\""; // line 6 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/images/exception_detected.png"), "html", null, true); echo "\"/> </div> <div class=\"text_exception\"> <div class=\"open_quote\"> <img alt=\"\" src=\""; // line 11 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/images/open_quote.gif"), "html", null, true); echo "\"/> </div> <h1> "; // line 15 echo $this->env->getExtension('code')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message"), "html", null, true))); echo " </h1> <div> <strong>"; // line 19 echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : $this->getContext($context, "status_code")), "html", null, true); echo "</strong> "; echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : $this->getContext($context, "status_text")), "html", null, true); echo " - "; echo $this->env->getExtension('code')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class")); echo " </div> "; // line 22 $context["previous_count"] = twig_length_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "allPrevious")); // line 23 echo " "; if ((isset($context["previous_count"]) ? $context["previous_count"] : $this->getContext($context, "previous_count"))) { // line 24 echo " <div class=\"linked\"><span><strong>"; echo twig_escape_filter($this->env, (isset($context["previous_count"]) ? $context["previous_count"] : $this->getContext($context, "previous_count")), "html", null, true); echo "</strong> linked Exception"; echo ((((isset($context["previous_count"]) ? $context["previous_count"] : $this->getContext($context, "previous_count")) > 1)) ? ("s") : ("")); echo ":</span> <ul> "; // line 26 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "allPrevious")); foreach ($context['_seq'] as $context["i"] => $context["previous"]) { // line 27 echo " <li> "; // line 28 echo $this->env->getExtension('code')->abbrClass($this->getAttribute((isset($context["previous"]) ? $context["previous"] : $this->getContext($context, "previous")), "class")); echo " <a href=\"#traces_link_"; echo twig_escape_filter($this->env, ((isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")) + 1), "html", null, true); echo "\" onclick=\"toggle('traces_"; echo twig_escape_filter($this->env, ((isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")) + 1), "html", null, true); echo "', 'traces'); switchIcons('icon_traces_"; echo twig_escape_filter($this->env, ((isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")) + 1), "html", null, true); echo "_open', 'icon_traces_"; echo twig_escape_filter($this->env, ((isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")) + 1), "html", null, true); echo "_close');\">&#187;</a> </li> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['i'], $context['previous'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 31 echo " </ul> </div> "; } // line 34 echo " <div class=\"close_quote\"> <img alt=\"\" src=\""; // line 36 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/images/close_quote.gif"), "html", null, true); echo "\"/> </div> </div> </div> </div> "; // line 43 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "toarray")); foreach ($context['_seq'] as $context["position"] => $context["e"]) { // line 44 echo " "; $this->env->loadTemplate("TwigBundle:Exception:traces.html.twig")->display(array("exception" => (isset($context["e"]) ? $context["e"] : $this->getContext($context, "e")), "position" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "count" => (isset($context["previous_count"]) ? $context["previous_count"] : $this->getContext($context, "previous_count")))); // line 45 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['position'], $context['e'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 46 echo " "; // line 47 if ((isset($context["logger"]) ? $context["logger"] : $this->getContext($context, "logger"))) { // line 48 echo " <div class=\"block\"> <div class=\"logs clear_fix\"> "; // line 50 ob_start(); // line 51 echo " <h2> Logs&nbsp; <a href=\"#\" onclick=\"toggle('logs'); switchIcons('icon_logs_open', 'icon_logs_close'); return false;\"> <img class=\"toggle\" id=\"icon_logs_open\" alt=\"+\" src=\""; // line 54 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/images/blue_picto_more.gif"), "html", null, true); echo "\" style=\"visibility: hidden\" /> <img class=\"toggle\" id=\"icon_logs_close\" alt=\"-\" src=\""; // line 55 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/images/blue_picto_less.gif"), "html", null, true); echo "\" style=\"visibility: visible; margin-left: -18px\" /> </a> </h2> "; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); // line 59 echo " "; // line 60 if ($this->getAttribute((isset($context["logger"]) ? $context["logger"] : $this->getContext($context, "logger")), "counterrors")) { // line 61 echo " <div class=\"error_count\"> <span> "; // line 63 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["logger"]) ? $context["logger"] : $this->getContext($context, "logger")), "counterrors"), "html", null, true); echo " error"; echo ((($this->getAttribute((isset($context["logger"]) ? $context["logger"] : $this->getContext($context, "logger")), "counterrors") > 1)) ? ("s") : ("")); echo " </span> </div> "; } // line 67 echo " </div> <div id=\"logs\"> "; // line 71 $this->env->loadTemplate("TwigBundle:Exception:logs.html.twig")->display(array("logs" => $this->getAttribute((isset($context["logger"]) ? $context["logger"] : $this->getContext($context, "logger")), "logs"))); // line 72 echo " </div> </div> "; } // line 76 echo " "; // line 77 if ((isset($context["currentContent"]) ? $context["currentContent"] : $this->getContext($context, "currentContent"))) { // line 78 echo " <div class=\"block\"> "; // line 79 ob_start(); // line 80 echo " <h2> Content of the Output&nbsp; <a href=\"#\" onclick=\"toggle('output_content'); switchIcons('icon_content_open', 'icon_content_close'); return false;\"> <img class=\"toggle\" id=\"icon_content_close\" alt=\"-\" src=\""; // line 83 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/images/blue_picto_less.gif"), "html", null, true); echo "\" style=\"visibility: hidden\" /> <img class=\"toggle\" id=\"icon_content_open\" alt=\"+\" src=\""; // line 84 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/images/blue_picto_more.gif"), "html", null, true); echo "\" style=\"visibility: visible; margin-left: -18px\" /> </a> </h2> "; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); // line 88 echo " <div id=\"output_content\" style=\"display: none\"> "; // line 90 echo twig_escape_filter($this->env, (isset($context["currentContent"]) ? $context["currentContent"] : $this->getContext($context, "currentContent")), "html", null, true); echo " </div> <div style=\"clear: both\"></div> </div> "; } // line 96 echo " </div> <script type=\"text/javascript\">//<![CDATA[ function toggle(id, clazz) { var el = document.getElementById(id), current = el.style.display, i; if (clazz) { var tags = document.getElementsByTagName('*'); for (i = tags.length - 1; i >= 0 ; i--) { if (tags[i].className === clazz) { tags[i].style.display = 'none'; } } } el.style.display = current === 'none' ? 'block' : 'none'; } function switchIcons(id1, id2) { var icon1, icon2, visibility1, visibility2; icon1 = document.getElementById(id1); icon2 = document.getElementById(id2); visibility1 = icon1.style.visibility; visibility2 = icon2.style.visibility; icon1.style.visibility = visibility2; icon2.style.visibility = visibility1; } //]]></script> "; } public function getTemplateName() { return "TwigBundle:Exception:exception.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 225 => 96, 216 => 90, 212 => 88, 205 => 84, 201 => 83, 196 => 80, 194 => 79, 191 => 78, 189 => 77, 186 => 76, 180 => 72, 178 => 71, 172 => 67, 163 => 63, 159 => 61, 157 => 60, 154 => 59, 147 => 55, 143 => 54, 138 => 51, 136 => 50, 132 => 48, 130 => 47, 127 => 46, 121 => 45, 118 => 44, 114 => 43, 104 => 36, 100 => 34, 95 => 31, 78 => 28, 75 => 27, 71 => 26, 63 => 24, 60 => 23, 58 => 22, 41 => 15, 34 => 11, 19 => 1, 94 => 39, 88 => 6, 81 => 40, 79 => 39, 59 => 22, 48 => 19, 39 => 8, 35 => 7, 31 => 6, 26 => 6, 21 => 1, 46 => 8, 43 => 7, 32 => 4, 29 => 3,); } }
{ "content_hash": "8c2a194bebde98135522db0227dfa709", "timestamp": "", "source": "github", "line_count": 276, "max_line_length": 636, "avg_line_length": 47.960144927536234, "alnum_prop": 0.4878748961244995, "repo_name": "adriancoca/Drool", "id": "b5ac106c2e472f23253648cb4d34fab0788ebe36", "size": "13237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/cache/dev/twig/3b/f6/8954aad30659e4e7eb8140b1e9684baf54d412b0662f9da1539b65d2208c.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "213611" }, { "name": "JavaScript", "bytes": "133444" }, { "name": "PHP", "bytes": "64519" } ], "symlink_target": "" }
package configs import ( "fmt" "os" "path/filepath" "strings" "github.com/hashicorp/hcl/v2" ) // LoadConfigDir reads the .tf and .tf.json files in the given directory // as config files (using LoadConfigFile) and then combines these files into // a single Module. // // If this method returns nil, that indicates that the given directory does not // exist at all or could not be opened for some reason. Callers may wish to // detect this case and ignore the returned diagnostics so that they can // produce a more context-aware error message in that case. // // If this method returns a non-nil module while error diagnostics are returned // then the module may be incomplete but can be used carefully for static // analysis. // // This file does not consider a directory with no files to be an error, and // will simply return an empty module in that case. Callers should first call // Parser.IsConfigDir if they wish to recognize that situation. // // .tf files are parsed using the HCL native syntax while .tf.json files are // parsed using the HCL JSON syntax. func (p *Parser) LoadConfigDir(path string) (*Module, hcl.Diagnostics) { primaryPaths, overridePaths, diags := p.dirFiles(path) if diags.HasErrors() { return nil, diags } primary, fDiags := p.loadFiles(primaryPaths, false) diags = append(diags, fDiags...) override, fDiags := p.loadFiles(overridePaths, true) diags = append(diags, fDiags...) mod, modDiags := NewModule(primary, override) diags = append(diags, modDiags...) mod.SourceDir = path return mod, diags } // ConfigDirFiles returns lists of the primary and override files configuration // files in the given directory. // // If the given directory does not exist or cannot be read, error diagnostics // are returned. If errors are returned, the resulting lists may be incomplete. func (p Parser) ConfigDirFiles(dir string) (primary, override []string, diags hcl.Diagnostics) { return p.dirFiles(dir) } // IsConfigDir determines whether the given path refers to a directory that // exists and contains at least one Terraform config file (with a .tf or // .tf.json extension.) func (p *Parser) IsConfigDir(path string) bool { primaryPaths, overridePaths, _ := p.dirFiles(path) return (len(primaryPaths) + len(overridePaths)) > 0 } func (p *Parser) loadFiles(paths []string, override bool) ([]*File, hcl.Diagnostics) { var files []*File var diags hcl.Diagnostics for _, path := range paths { var f *File var fDiags hcl.Diagnostics if override { f, fDiags = p.LoadConfigFileOverride(path) } else { f, fDiags = p.LoadConfigFile(path) } diags = append(diags, fDiags...) if f != nil { files = append(files, f) } } return files, diags } func (p *Parser) dirFiles(dir string) (primary, override []string, diags hcl.Diagnostics) { infos, err := p.fs.ReadDir(dir) if err != nil { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Failed to read module directory", Detail: fmt.Sprintf("Module directory %s does not exist or cannot be read.", dir), }) return } for _, info := range infos { if info.IsDir() { // We only care about files continue } name := info.Name() ext := fileExt(name) if ext == "" || IsIgnoredFile(name) { continue } baseName := name[:len(name)-len(ext)] // strip extension isOverride := baseName == "override" || strings.HasSuffix(baseName, "_override") fullPath := filepath.Join(dir, name) if isOverride { override = append(override, fullPath) } else { primary = append(primary, fullPath) } } return } // fileExt returns the Terraform configuration extension of the given // path, or a blank string if it is not a recognized extension. func fileExt(path string) string { if strings.HasSuffix(path, ".tf") { return ".tf" } else if strings.HasSuffix(path, ".tf.json") { return ".tf.json" } else { return "" } } // IsIgnoredFile returns true if the given filename (which must not have a // directory path ahead of it) should be ignored as e.g. an editor swap file. func IsIgnoredFile(name string) bool { return strings.HasPrefix(name, ".") || // Unix-like hidden files strings.HasSuffix(name, "~") || // vim strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#") // emacs } // IsEmptyDir returns true if the given filesystem path contains no Terraform // configuration files. // // Unlike the methods of the Parser type, this function always consults the // real filesystem, and thus it isn't appropriate to use when working with // configuration loaded from a plan file. func IsEmptyDir(path string) (bool, error) { if _, err := os.Stat(path); err != nil && os.IsNotExist(err) { return true, nil } p := NewParser(nil) fs, os, diags := p.dirFiles(path) if diags.HasErrors() { return false, diags } return len(fs) == 0 && len(os) == 0, nil }
{ "content_hash": "6704cede00c700c0ebf6100cf7513017", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 96, "avg_line_length": 29.834355828220858, "alnum_prop": 0.7028583179107547, "repo_name": "citrix/terraform-provider-netscaler", "id": "2923af93a00e4ff4330665f203785c7877deec8f", "size": "4863", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "vendor/github.com/hashicorp/terraform/configs/parser_config_dir.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "668722" }, { "name": "HCL", "bytes": "229" }, { "name": "Makefile", "bytes": "3956" }, { "name": "Shell", "bytes": "1269" } ], "symlink_target": "" }
/*! * FullCalendar v2.1.1 Print Stylesheet * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ /* * Include this stylesheet on your page to get a more printer-friendly calendar. * When including this stylesheet, use the media='print' attribute of the <link> tag. * Make sure to include this stylesheet IN ADDITION to the regular fullcalendar.css. */ .fc { max-width: 100% !important; } /* Global Event Restyling --------------------------------------------------------------------------------------------------*/ .fc-event { background: #FF6 !important; color: #000 !important; page-break-inside: avoid; /*-webkit-print-color-adjust: exact; print-color-adjust: exact;*/ } .fc-event .fc-resizer { display: none; } /* Table & Day-Row Restyling --------------------------------------------------------------------------------------------------*/ th, td, hr, thead, tbody, .fc-row { border-color: #ccc !important; background: #fff !important; } /* kill the overlaid, absolutely-positioned common components */ .fc-bg, .fc-highlight-skeleton, .fc-helper-skeleton { display: none; } /* don't force a min-height on rows (for DayGrid) */ .fc tbody .fc-row { height: auto !important; /* undo height that JS set in distributeHeight */ min-height: 0 !important; /* undo the min-height from each view's specific stylesheet */ } .fc tbody .fc-row .fc-content-skeleton { position: static; /* undo .fc-rigid */ padding-bottom: 0 !important; /* use a more border-friendly method for this... */ } .fc tbody .fc-row .fc-content-skeleton tbody tr:last-child td { /* only works in newer browsers */ padding-bottom: 1em; /* ...gives space within the skeleton. also ensures min height in a way */ } .fc tbody .fc-row .fc-content-skeleton table { /* provides a min-height for the row, but only effective for IE, which exaggerates this value, making it look more like 3em. for other browers, it will already be this tall */ height: 1em; } /* Undo month-view event limiting. Display all events and hide the "more" links --------------------------------------------------------------------------------------------------*/ .fc-more-cell, .fc-more { display: none !important; } .fc tr.fc-limited { display: table-row !important; } .fc td.fc-limited { display: table-cell !important; } .fc-popover { display: none; /* never display the "more.." popover in print mode */ } /* TimeGrid Restyling --------------------------------------------------------------------------------------------------*/ /* undo the min-height 100% trick used to fill the container's height */ .fc-time-grid { min-height: 0 !important; } /* don't display the side axis at all ("all-day" and time cells) */ .fc-agenda-view .fc-axis { display: none; } /* don't display the horizontal lines */ .fc-slats, .fc-time-grid hr { /* this hr is used when height is underused and needs to be filled */ display: none !important; /* important overrides inline declaration */ } /* let the container that holds the events be naturally positioned and create real height */ .fc-time-grid .fc-content-skeleton { position: static; } /* in case there are no events, we still want some height */ .fc-time-grid .fc-content-skeleton table { height: 4em; } /* kill the horizontal spacing made by the event container. event margins will be done below */ .fc-time-grid .fc-event-container { margin: 0 !important; } /* TimeGrid *Event* Restyling --------------------------------------------------------------------------------------------------*/ /* naturally position events, vertically stacking them */ .fc-time-grid .fc-event { position: static !important; margin: 3px 2px !important; } /* for events that continue to a future day, give the bottom border back */ .fc-time-grid .fc-event.fc-not-end { border-bottom-width: 1px !important; } /* indicate the event continues via "..." text */ .fc-time-grid .fc-event.fc-not-end:after { content: "..."; } /* for events that are continuations from previous days, give the top border back */ .fc-time-grid .fc-event.fc-not-start { border-top-width: 1px !important; } /* indicate the event is a continuation via "..." text */ .fc-time-grid .fc-event.fc-not-start:before { content: "..."; } /* time */ /* undo a previous declaration and let the time text span to a second line */ .fc-time-grid .fc-event .fc-time { white-space: normal !important; } /* hide the the time that is normally displayed... */ .fc-time-grid .fc-event .fc-time span { display: none; } /* ...replace it with a more verbose version (includes AM/PM) stored in an html attribute */ .fc-time-grid .fc-event .fc-time:after { content: attr(data-full); } /* Vertical Scroller & Containers --------------------------------------------------------------------------------------------------*/ /* kill the scrollbars and allow natural height */ .fc-scroller, .fc-day-grid-container, /* these divs might be assigned height, which we need to cleared */ .fc-time-grid-container { /* */ overflow: visible !important; height: auto !important; } /* kill the horizontal border/padding used to compensate for scrollbars */ .fc-row { border: 0 !important; margin: 0 !important; } /* Button Controls --------------------------------------------------------------------------------------------------*/ .fc-button-group, .fc button { display: none; /* don't display any button-related controls */ } .popover {background: #FF6 !important; color: #000 !important; display:inline !important; position:relative !important; }
{ "content_hash": "0f53e66f3ce3a6e414a285e4a380dad8", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 100, "avg_line_length": 26.63157894736842, "alnum_prop": 0.6090549766439094, "repo_name": "hafizyounis78/shift", "id": "cd80757b119a9a5faa3a308f2ddd2c672f592e7f", "size": "5566", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/global/plugins/fullcalendar/fullcalendar.print.css", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "290" }, { "name": "ApacheConf", "bytes": "869" }, { "name": "CSS", "bytes": "2154373" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "Go", "bytes": "7076" }, { "name": "HTML", "bytes": "4199724" }, { "name": "JavaScript", "bytes": "5828590" }, { "name": "PHP", "bytes": "8470739" }, { "name": "Python", "bytes": "5845" }, { "name": "Shell", "bytes": "444" } ], "symlink_target": "" }
namespace CohesionAndCoupling { using System; using System.Linq; public class RectangularParallelepiped { private double width, height, depth; public RectangularParallelepiped(double width, double height, double depth) { this.Width = width; this.Height = height; this.Depth = depth; } public double Width { get { return this.width; } set { if (value <= 0) { throw new ArgumentException("Width cannot be less or equal to zero!"); } this.width = value; } } public double Height { get { return this.height; } set { if (value <= 0) { throw new ArgumentException("Height cannot be less or equal to zero!"); } this.height = value; } } public double Depth { get { return this.depth; } set { if (value <= 0) { throw new ArgumentException("Depth cannot be less or equal to zero!"); } this.depth = value; } } public double CalcVolume() { double volume = this.Width * this.Height * this.Depth; return volume; } public double CalcDiagonalXYZ() { double distance = GeometryUtils.CalcDistance3D(0, 0, 0, this.Width, this.Height, this.Depth); return distance; } public double CalcDiagonalXY() { double distance = GeometryUtils.CalcDistance2D(0, 0, this.Width, this.Height); return distance; } public double CalcDiagonalXZ() { double distance = GeometryUtils.CalcDistance2D(0, 0, this.Width, this.Depth); return distance; } public double CalcDiagonalYZ() { double distance = GeometryUtils.CalcDistance2D(0, 0, this.Height, this.Depth); return distance; } } }
{ "content_hash": "342488fd23b0cfa6fc74299cd999b265", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 105, "avg_line_length": 25.303370786516854, "alnum_prop": 0.4746891651865009, "repo_name": "flextry/Telerik-Academy", "id": "40db914246b77ce80a9679d076b7e9ec07e0c4b7", "size": "2254", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Programming with C#/4. C# High-Quality Code/07. High-Quality Classes/02. Cohesion and Coupling/RectangularParallelepiped.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102569" }, { "name": "Batchfile", "bytes": "99" }, { "name": "C#", "bytes": "7915052" }, { "name": "C++", "bytes": "71174" }, { "name": "CSS", "bytes": "428966" }, { "name": "CoffeeScript", "bytes": "290" }, { "name": "HTML", "bytes": "499757" }, { "name": "JavaScript", "bytes": "2425283" }, { "name": "PHP", "bytes": "85835" }, { "name": "PLpgSQL", "bytes": "22997" }, { "name": "SQLPL", "bytes": "941" }, { "name": "Shell", "bytes": "37" }, { "name": "Smalltalk", "bytes": "1231" }, { "name": "TypeScript", "bytes": "11347" }, { "name": "XSLT", "bytes": "1129" } ], "symlink_target": "" }
<?php include("User.class.php"); include('repository.class.php'); include("controller.action.php"); include("controller.erreur.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>BDE In'tech Info</title> <LINK href="/bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src= "/lib/jquery.js"></script> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <script type="text/javascript" src="/bootstrap/js/bootstrap.js"></script> </head> <style type="text/css" media="screen"> #full{ background-color: #C0DEED; height:1100px; width:auto; margin:0; padding:0; } #footer{ background-image: url(/img/background_reverse.gif) repeat-y scroll left bottom; text-align:center; padding-top:200px; width:auto; } #header{ height:180px; background: url("/img/header.png") repeat-y scroll left top; text-align:center; margin-top:-30px; } #header h1{ padding-top:60px; font-family: "Myriad Pro", Helvetica, Arial, sans-serif; color:white; font-size:45px; } </style> <div id="fulll"> <div id="header"></div><!-- #header --> <?php include("bundle.php"); ?> </div> <!--div id="footer"><img src= "/img/background_reverse.gif"/></div--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-34677811-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </html>
{ "content_hash": "c258cdf4c452392597cd4c9e57cce705", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 117, "avg_line_length": 26.816901408450704, "alnum_prop": 0.6565126050420168, "repo_name": "Grandvizir/ITI--Club", "id": "ba0364a80113e5891a4d2f5428a121d371bd47f1", "size": "1904", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "59257" }, { "name": "PHP", "bytes": "554644" } ], "symlink_target": "" }
[Demo here.](http://vcolavin.com/birthday_problem) In short, it takes a surprisingly small group of people for it to be likely that two people will share a birthday. I got the math from this [Wolfram MathWorld post](http://mathworld.wolfram.com/BirthdayProblem.html). Except for [math.js](http://mathjs.org/) (used to prevent the answer from almost always being "Infinity" or "NaN"), this is [vanilla JavaScript](http://vanilla-js.com/).
{ "content_hash": "38e33541ead903bd55056bdfcbcf3e55", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 169, "avg_line_length": 63, "alnum_prop": 0.7551020408163265, "repo_name": "vcolavin/birthday_problem", "id": "2358b700988226b4f2776a8d52e52689271efcf5", "size": "543", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "697" }, { "name": "JavaScript", "bytes": "1909" } ], "symlink_target": "" }
<launch> <!-- urdf xml robot description loaded on the Parameter Server--> <param name="robot_description" command="$(find xacro)/xacro $(find labrob_description)/urdf/ocare_realworld.urdf.xacro" /> <!-- Load joint controller configurations from YAML file to parameter server --> <rosparam file="$(find ex_ocare_control)/config/controller_config.yaml" command="load"/> <!-- main robot hardware interface handler node --> <node name="ocare_hw_node" pkg="ex_ocare_control" type="ex_ocare_control_node" required="false" output="screen" /> <node name="hokuyo" pkg="hokuyo_node" type="hokuyo_node" required="true" output="screen" > <param name="frame_id" type="str" value="laser"/> <param name="port" type="string" value="/dev/hokuyo"/> <param name="min_ang" type="double" value="-2.08621382713"/> <param name="max_ang" type="double" value="2.09234976768"/> <param name="intensity" type="bool" value="false"/> </node> <node name="mpu6050" pkg="mpu6050_serial_to_imu" type="mpu6050_serial_to_imu_node" output="screen" > <param name="port" type="string" value="/dev/arduino"/> </node> <!-- load the controllers --> <node name="controller_spawner" pkg="controller_manager" type="spawner" respawn="false" output="screen" ns="/ocare" args="pose_fuzzy_controller joint_state_controller"/> <!--node name="joint_state_publisher" pkg="joint_state_publisher" type="joint_state_publisher" /--> <node name="robot_state_publisher" pkg="robot_state_publisher" type="state_publisher" > <!-- urdf xml robot description loaded on the Parameter Server--> <param name="robot_description" command="$(find xacro)/xacro $(find labrob_description)/urdf/ocare_realworld.urdf.xacro" /> <remap from="/joint_states" to="/ocare/joint_states" /> </node> <node name="ocare_stage_node" pkg="ex_ocare_control" type="diff_test_stage_node" output="screen" > </node> </launch>
{ "content_hash": "2a0ca40d276dde1575f6c53680c5fc99", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 126, "avg_line_length": 47.325, "alnum_prop": 0.7010036978341257, "repo_name": "a0919958057/ros_ocare_nav", "id": "238f8d16de1d19fe0680d5451bc8816f1658c49e", "size": "1893", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ex_ocare_control/launch/ocare_hw_node.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "608" }, { "name": "C++", "bytes": "124328" }, { "name": "CMake", "bytes": "35047" }, { "name": "Python", "bytes": "64301" } ], "symlink_target": "" }
require 'spec_helper' require 'pact/mock_service/request_decorator' require 'pact/consumer_contract/request' module Pact module MockService describe RequestDecorator do let(:options) { {} } let(:body) { {some: "bod"} } let(:headers) { {some: "header"} } let(:request_params) do { method: :get, query: "param=foo", headers: headers, path: "/", body: body } end let(:request) { Pact::Request::Expected.from_hash(request_params) } subject { RequestDecorator.new(request) } describe "#to_json" do let(:parsed_json) { JSON.parse subject.to_json, symbolize_names: true} it "renders the keys in a meaningful order" do expect(subject.to_json).to match(/method.*path.*query.*headers.*body/) end context "with a body specified as a Hash" do it "serialises the body as a Hash" do expect(parsed_json[:body]).to eq body end end context "with a body specified as a Hash containing a Pact::Term" do let(:body) { { some: Pact::Term.new(generate: 'apple', matcher: /a/) } } it "serialises the Pact::Term to Ruby specific JSON that is not compatible with pact-specification 1.0.0" do expect(subject.to_json).to include "Pact::Term" end end end describe "#as_json" do context "without options" do it "does not include the options key" do expect(subject.as_json.key?(:options)).to be false end end context "with options" do let(:request_params) do { method: :get, path: "/", options: options } end let(:options) { {:opts => 'blah'} } it "includes the options in the request hash" do expect(subject.as_json[:options]).to eq options end end end end end end
{ "content_hash": "2d22988becc8e51086f75b590dcb74af", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 118, "avg_line_length": 26.67105263157895, "alnum_prop": 0.549580661075481, "repo_name": "bethesque/pact-mock_service", "id": "786f8941d4d6543dd382b5e12e6ff7820a17e87f", "size": "2027", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/lib/pact/mock_service/request_decorator_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "456" }, { "name": "Ruby", "bytes": "210171" }, { "name": "Shell", "bytes": "888" } ], "symlink_target": "" }
<script> <a click={() => window.open("https://lively-kernel.org/lively4/swd21-particles/start.html")}>dev repository</a> </script> ## Literature - <edit://../shadama/examples/1-Fill.shadama>
{ "content_hash": "dede7fa5d8acca80e53239bb7f1909c3", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 113, "avg_line_length": 19.7, "alnum_prop": 0.6751269035532995, "repo_name": "LivelyKernel/lively4-core", "id": "8ccce2bdea726eea5fa1331ab91ece3deb70a89a", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "demos/swd21/particles/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "144422" }, { "name": "HTML", "bytes": "589346" }, { "name": "JavaScript", "bytes": "4554338" } ], "symlink_target": "" }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include "libforestdb/forestdb.h" #include "fdb_engine.h" #include "superblock.h" #include "staleblock.h" #include "btreeblock.h" #include "list.h" #include "fdb_internal.h" #include "version.h" #include "blockcache.h" #include "memleak.h" /* * << super block structure >> * * 0x00 [file version (magic number)]: 8 bytes * 0x08 [super block revision number]: 8 bytes * 0x10 [bitmap revision number]: 8 bytes * 0x18 [BID for next allocation]: 8 bytes * 0x20 [last header BID]: 8 bytes * 0x28 [last header revnum]: 8 bytes * 0x30 [min active header revnum]: 8 bytes * 0x38 [min active header BID]: 8 bytes * 0x40 [# initial free blocks in the bitmap]: 8 bytes * 0x48 [# free blocks in the bitmap]: 8 bytes * 0x50 [bitmap size]: 8 bytes * 0x58 [reserved bitmap size (0 if not exist)]: 8 bytes * 0x60 ... [bitmap doc offset]: 8 bytes each * [CRC32]: 4 bytes * ... * [block marker]: 1 byte */ /* * << basic mask >> * 0: 10000000 * 1: 01000000 * ... * 7: 00000001 */ static uint8_t bmp_basic_mask[8]; /* * << 2d mask >> * bmp_2d_mask[pos][len] * * 0,1: 10000000 * 0,2: 11000000 * 0,3: 11100000 * ... * 1,1: 01000000 * 1,2: 01100000 * ... * 3,1: 00010000 * 3,2: 00011000 * ... * 6,1: 00000010 * 6,2: 00000011 * 7,1: 00000001 */ static uint8_t bmp_2d_mask[8][9]; // x % 8 #define mod8(x) ((x) & 0x7) // x / 8 #define div8(x) ((x) >> 3) // rounding down (to the nearest 8) #define rd8(x) (((x) >> 3) << 3) struct bmp_idx_node { uint64_t id; struct avl_node avl; }; INLINE int _bmp_idx_cmp(struct avl_node *a, struct avl_node *b, void *aux) { struct bmp_idx_node *aa, *bb; aa = _get_entry(a, struct bmp_idx_node, avl); bb = _get_entry(b, struct bmp_idx_node, avl); #ifdef __BIT_CMP return _CMP_U64(aa->id, bb->id); #else if (aa->id < bb->id) { return -1; } else if (aa->id > bb->id) { return 1; } else { return 0; } #endif } Superblock::Superblock(FileMgr *_file, struct sb_config _sconfig) { _init(_file, _sconfig); } Superblock::~Superblock() { _free(); } void Superblock::_init(FileMgr *_file, struct sb_config sconfig) { file = _file; config = sconfig; revnum = 0; bmpRevnum = 0; bmpSize = 0; bmp = NULL; bmpRCount = 0; bmpWCount = 0; spin_init(&bmpLock); bmpPrevSize = 0; bmpPrev = NULL; bmpDocOffset = NULL; bmpDocs = NULL; numBmpDocs = 0; numInitFreeBlocks = 0; numFreeBlocks = 0; curAllocBid = BLK_NOT_FOUND; lastHdrBid = BLK_NOT_FOUND; minLiveHdrRevnum = 0; minLiveHdrBid = BLK_NOT_FOUND; lastHdrRevnum = 0; numAlloc = 0; rsvBmp = NULL; avl_init(&bmpIdx, NULL); spin_init(&lock); } fdb_status Superblock::init(ErrLogCallback * log_callback) { size_t i; bid_t sb_bid; fdb_status fs; // exit if superblock is already initialized. if (revnum) { return FDB_RESULT_SUCCESS; } // no data should be written in the file before initialization of superblock. if (file->getPos() > 0) { return FDB_RESULT_SB_INIT_FAIL; } // initialize staleData instance if not exist if (!file->getStaleData()) { file->setStaleData(new StaleDataManager(file)); } file->setVersion(ver_get_latest_magic()); // write initial superblocks for (i=0; i<config.num_sb; ++i) { // allocate sb_bid = file->alloc_FileMgr(log_callback); if (sb_bid != i) { // other data was written during sb_write .. error fs = FDB_RESULT_SB_RACE_CONDITION; fdb_log(log_callback, fs, "Other writer interfered during sb_write (number: %" _F64 ")", static_cast<uint64_t>(i)); return fs; } fs = writeSb(i, log_callback); if (fs != FDB_RESULT_SUCCESS) { return fs; } } return FDB_RESULT_SUCCESS; } fdb_status Superblock::readLatest(ErrLogCallback *log_callback) { size_t i, max_sb_no = config.num_sb; uint64_t max_revnum = 0; uint64_t revnum_limit = static_cast<uint64_t>(-1); fdb_status fs; std::vector<Superblock *> sb_arr; //Superblock **sb_arr = new Superblock*[config.num_sb]; // initialize staleData instance if not exist if (!file->getStaleData()) { file->setStaleData(new StaleDataManager(file)); } if (revnum) { // Superblock is already read previously. // This means that there are some problems with the current superblock // so that we have to read another candidate. // Note: 'sb->revnum' denotes the revnum of next superblock to be // written, so we need to subtract 1 from it to get the revnum of // the current superblock successfully read from the file. revnum_limit = revnum.load() - 1; _free(); } // read all superblocks for (i=0; i<config.num_sb; ++i) { sb_arr.push_back(new Superblock(file, config)); fs = sb_arr[i]->readGivenNum(i, log_callback); uint64_t cur_revnum = sb_arr[i]->getRevnum(); if (fs == FDB_RESULT_SUCCESS && cur_revnum >= max_revnum && cur_revnum < revnum_limit) { max_sb_no = i; max_revnum = cur_revnum; } } if (max_sb_no == config.num_sb) { // all superblocks are broken fs = FDB_RESULT_SB_READ_FAIL; for (i=0; i<config.num_sb; ++i) { delete sb_arr[i]; } // no readable superblock // (if not corrupted, it may be a normal old version file) return fs; } // re-read the target superblock readGivenNum(max_sb_no, log_callback); // set last commit position if (curAllocBid.load() != BLK_NOT_FOUND) { file->setLastCommit(curAllocBid.load() * file->getConfig()->getBlockSize()); } else { // otherwise, last_commit == file->pos // (already set by FileMgr::open() function) } revnum++; avl_init(&bmpIdx, NULL); // free temporary superblocks for (i=0; i<config.num_sb; ++i) { delete sb_arr[i]; } return FDB_RESULT_SUCCESS; } void Superblock::initBmpMask() { // preset masks to speed up bitmap set/clear operations size_t i, pos, len; for (i=0; i<8; ++i) { bmp_basic_mask[i] = (uint8_t)(0x1 << (7-i)); } for (pos=0; pos<8; ++pos) { for (len=0; len<9; ++len) { bmp_2d_mask[pos][len] = 0x0; if (len != 0 && pos+len <= 8) { for (i=0; i<len; ++i) { bmp_2d_mask[pos][len] |= bmp_basic_mask[pos+i]; } } } } } void Superblock::_free() { if (rsvBmp) { rsvBmp->status = SB_RSV_VOID; freeBmpIdx(&rsvBmp->bmpIdx); freeRsv(rsvBmp); free(rsvBmp); } freeBmpIdx(&bmpIdx); free(bmp); free(bmpPrev); free(bmpDocOffset); // note that each docio object doesn't need to be freed // as key/body fields point to static memory regions. free(bmpDocs); spin_destroy(&lock); bmp = NULL; bmpDocOffset = NULL; bmpDocs = NULL; } fdb_status Superblock::readGivenNum(size_t sb_no, ErrLogCallback *log_callback) { ssize_t r; int real_blocksize = file->getBlockSize(); int blocksize = file->getBlockSize() - BLK_MARKER_SIZE; size_t i, num_docs; uint8_t *buf = alca(uint8_t, real_blocksize); uint32_t crc_file, crc, _crc; uint64_t enc_u64, version, offset, dummy64; fdb_status fs; struct sb_rsv_bmp *rsv = NULL; memset(buf, 0x0, real_blocksize); offset = 0; // directly read a block bypassing block cache r = file->readBlock(buf, sb_no); if (r != real_blocksize) { char errno_msg[512]; file->getOps()->get_errno_str(file->getFopsHandle(), errno_msg, 512); fs = FDB_RESULT_SB_READ_FAIL; fdb_log(log_callback, fs, "Failed to read the superblock: " "file read failure (SB No.: %" _F64 "), %s", static_cast<uint64_t>(sb_no), errno_msg); return fs; } // block marker check if (buf[blocksize] != BLK_MARKER_SB) { fs = FDB_RESULT_SB_READ_FAIL; fdb_log(log_callback, fs, "Failed to read the superblock: " "incorrect block marker (marker: %x, SB No.: %" _F64 "). " "Note: this message might be a false alarm if upgrade is running.", buf[blocksize], static_cast<uint64_t>(sb_no)); return fs; } // magic number memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); version = _endian_decode(enc_u64); // version check if (!ver_superblock_support(version)) { fs = FDB_RESULT_SB_READ_FAIL; fdb_log(log_callback, fs, "Failed to read the superblock: " "not supported version (magic: %" _F64 ", SB No.: %" _F64 ")", version, static_cast<uint64_t>(sb_no)); return fs; } // revision number memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); revnum = _endian_decode(enc_u64); // bitmap's revision number memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); bmpRevnum = _endian_decode(enc_u64); // curAllocBid memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); curAllocBid = _endian_decode(enc_u64); // last header bid memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); lastHdrBid = _endian_decode(enc_u64); // last header rev number memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); lastHdrRevnum = _endian_decode(enc_u64); // minimum active header revnum memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); minLiveHdrRevnum = _endian_decode(enc_u64); // minimum active header BID memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); minLiveHdrBid = _endian_decode(enc_u64); // # initial free blocks memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); numInitFreeBlocks = _endian_decode(enc_u64); // # free blocks memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); numFreeBlocks = _endian_decode(enc_u64); // bitmap size uint64_t sb_bmp_size; memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); sb_bmp_size = _endian_decode(enc_u64); bmpSize = sb_bmp_size; // reserved bitmap size memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); dummy64 = _endian_decode(enc_u64); if (dummy64) { // reserved bitmap array exists rsv = (struct sb_rsv_bmp*)calloc(1, sizeof(struct sb_rsv_bmp)); rsv->bmp = NULL; rsv->bmpSize = dummy64; rsv->curAllocBid = BLK_NOT_FOUND; rsv->status = SB_RSV_INITIALIZING; } // temporarily set bitmap array to NULL // (it will be allocated by fetching function) bmp = NULL; numBmpDocs = num_docs = bmpSizeToNumDocs(sb_bmp_size); if (num_docs) { bmpDocOffset = (bid_t*)calloc(num_docs, sizeof(bid_t)); bmpDocs = (struct docio_object*) calloc(num_docs, sizeof(struct docio_object)); } // read doc offsets for (i=0; i<num_docs; ++i) { memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); bmpDocOffset[i] = _endian_decode(enc_u64); } // read reserved bmp docs if exist if (rsv) { rsv->numBmpDocs = num_docs = bmpSizeToNumDocs(rsv->bmpSize); if (rsv->numBmpDocs) { rsv->bmpDocOffset = (bid_t*)calloc(num_docs, sizeof(bid_t)); rsv->bmpDocs = (struct docio_object*) calloc(num_docs, sizeof(struct docio_object)); } // read doc offsets for (i=0; i<num_docs; ++i) { memcpy(&enc_u64, buf + offset, sizeof(enc_u64)); offset += sizeof(enc_u64); rsv->bmpDocOffset[i] = _endian_decode(enc_u64); } rsvBmp = rsv; } // CRC crc = get_checksum(buf, offset, file->getCrcMode()); memcpy(&_crc, buf + offset, sizeof(_crc)); crc_file = _endian_decode(_crc); if (crc != crc_file) { free(bmpDocOffset); free(bmpDocs); bmpDocOffset = NULL; bmpDocs = NULL; fs = FDB_RESULT_SB_READ_FAIL; fdb_log(log_callback, fs, "Failed to read the superblock: " "not supported version (magic: %" _F64 ", SB No.: %" _F64 ")", version, static_cast<uint64_t>(sb_no)); return fs; } return FDB_RESULT_SUCCESS; } void Superblock::beginBmpBarrier() { bmpRCount++; if (bmpWCount.load()) { // now bmp pointer & related variables are being changed. // decrease count and grab lock until the change is done. bmpRCount--; spin_lock(&bmpLock); // got control: means that change is done. // re-increase the count bmpRCount++; spin_unlock(&bmpLock); } } void Superblock::endBmpBarrier() { bmpRCount--; } void Superblock::beginBmpChange() { // grab lock and increase writer count // now new readers cannot increase the reader count // (note that there is always one bitmap writer at a time) spin_lock(&bmpLock); bmpWCount++; // wait until previous BMP readers terminate // (they are very short bitmap accessing routines so that // will not take long time). size_t spin = 0; while (bmpRCount.load()) { if (++spin > 64) { #ifdef HAVE_SCHED_H sched_yield(); #elif _MSC_VER SwitchToThread(); #endif } } // now 1) all previous readers terminated // 2) new readers will be blocked } void Superblock::endBmpChange() { bmpWCount--; spin_unlock(&bmpLock); // now resume all pending readers } bool Superblock::switchReservedBlocks() { size_t i; struct sb_rsv_bmp *rsv = rsvBmp; // reserved block should exist if (!rsv) { return false; } // should be in a normal status uint32_t cond = SB_RSV_READY; if (!rsv->status.compare_exchange_strong(cond, SB_RSV_VOID)) { return false; } // now status becomes 'VOID' so that rsvBmp is not available. // mark stale previous system docs if (bmpDocOffset) { for (i=0; i<numBmpDocs; ++i) { file->markStale(bmpDocOffset[i], _fdb_get_docsize(bmpDocs[i].length)); } free(bmpDocOffset); free(bmpDocs); bmpDocOffset = NULL; bmpDocs = NULL; } // should flush all dirty blocks in cache file->sync_FileMgr(false, NULL); // free current bitmap idx freeBmpIdx(&bmpIdx); // temporarily keep current bitmap beginBmpChange(); uint8_t *old_prev_bmp = NULL; if (bmpPrev) { old_prev_bmp = bmpPrev; } bmpPrev = bmp; bmpPrevSize = bmpSize.load(); // copy all pointers from rsv to sb bmpRevnum = rsv->bmpRevnum; bmpSize.store(rsv->bmpSize); bmp = rsv->bmp; bmpIdx = rsv->bmpIdx; bmpDocOffset = rsv->bmpDocOffset; bmpDocs = rsv->bmpDocs; numBmpDocs = rsv->numBmpDocs; numFreeBlocks = numInitFreeBlocks = rsv->numFreeBlocks; curAllocBid.store(rsv->curAllocBid); minLiveHdrRevnum = rsv->minLiveHdrRevnum; minLiveHdrBid = rsv->minLiveHdrBid; endBmpChange(); free(old_prev_bmp); free(rsvBmp); rsvBmp = NULL; return true; } bid_t Superblock::allocBlock() { uint64_t i, node_idx, node_off, bmp_idx_no, bmp_off; bid_t ret = BLK_NOT_FOUND; struct avl_node *a; struct bmp_idx_node *item, query; numAlloc++; sb_alloc_start_over: if (!bmpExists()) { // no bitmap return BLK_NOT_FOUND; } if (numFreeBlocks == 0) { bool switched = false; if (rsvBmp) { switched = switchReservedBlocks(); } if (switched) { goto sb_alloc_start_over; } else { curAllocBid = BLK_NOT_FOUND; return BLK_NOT_FOUND; } } ret = curAllocBid.load(); numFreeBlocks--; if (numFreeBlocks == 0) { bool switched = false; if (rsvBmp) { switched = switchReservedBlocks(); } if (!switched) { curAllocBid = BLK_NOT_FOUND; } return ret; } // find allocable block in the same bmp idx node node_idx = ret >> 8; node_off = (ret & 0xff)+1; do { for (i=node_off; i<256; ++i) { bmp_idx_no = div8(i) + (node_idx * 32); bmp_off = mod8(i); if ((bmp_idx_no * 8 + bmp_off) >= bmpSize.load()) { break; } if (bmp[bmp_idx_no] & bmp_basic_mask[bmp_off]) { curAllocBid.store(bmp_idx_no * 8 + bmp_off); return ret; } } // current bmp_node does not include any free block .. remove query.id = node_idx; a = avl_search(&bmpIdx, &query.avl, _bmp_idx_cmp); if (a) { item = _get_entry(a, struct bmp_idx_node, avl); avl_remove(&bmpIdx, a); free(item); } // get next allocable bmp_node a = avl_first(&bmpIdx); if (!a) { // no more free bmp_node numFreeBlocks = 0; bool switched = false; if (rsvBmp) { switched = switchReservedBlocks(); } if (!switched) { curAllocBid = BLK_NOT_FOUND; } break; } item = _get_entry(a, struct bmp_idx_node, avl); node_idx = item->id; node_off = 0; } while (true); return ret; } bool Superblock::isWritable(bid_t bid) { if (bid < config.num_sb) { // superblocks are always writable return true; } bool ret = false; bid_t last_commit = file->getLastCommit() / file->getBlockSize(); uint64_t lw_bmp_revnum = file->getLastWritableBmpRevnum(); beginBmpBarrier(); uint8_t *sb_bmp = bmp; if (bmpRevnum.load() == lw_bmp_revnum) { // Same bitmap revision number: there are 2 possible cases // // (1) normal case // writable blocks // <----> <---> // +-------------------------------------------+ // | xxxxxxxxx xxxxxxxxxx | (x: reused blocks) // +-------------------------------------------+ // ^ ^ // last_commit cur_alloc // // (2) when file size grows after block reusing // writable blocks // <-------> <---------> // +-------------------------------------------+---------+ // | xxxxxxxxx xxxxxxxxxx | | // +-------------------------------------------+---------+ // ^ ^ ^ // last_commit bmpSize cur_alloc if (bid < bmpSize.load()) { // BID is in the bitmap .. check if bitmap is set. if (isBmpSet(sb_bmp, bid) && bid < curAllocBid.load() && bid >= last_commit) { ret = true; } } else { // BID is out-of-range of the bitmap if (bid >= last_commit) { ret = true; } } } else { // Different bitmap revision number: there are also 2 possible cases // // (1) normal case // writable blocks writable blocks // <----> <---> // +-------------------------------------------+ // | xxxxxxxxx xxxxxxxxxx | // +-------------------------------------------+ // ^ ^ // cur_alloc last_commit // // (2) when file size grows after block reusing // writable blocks writable blocks // <----> <------> <-----------x---------> // +-------------------------------------------+---------+ // | xxxxxx xxxxxxxx | | // +-------------------------------------------+---------+ // ^ ^ ^ // last_commit bmpSize cur_alloc // the block is writable if // 1) BID >= last_commit OR // 2) BID < curAllocBid AND corresponding bitmap is set. if (bid >= last_commit) { // if prev_bmp exists, last commit position is still located on the // previous bitmap (since prev_bmp is released when a commit is invoked // in the new bitmap). // So in this case, we have to check both previous/current bitmaps. // // (1: previous bitmap (sb->bmpPrev), 2: current bitmap (sb->bmp)) // // writable blocks writable blocks // <--> <----> <--> <> <> <> // +-------------------------------------------+ // | 2222 1111 222222 2222 111111111 22 11| // +-------------------------------------------+ // ^ // last_commit if (bmpPrev) { if (bid < bmpPrevSize && isBmpSet(bmpPrev, bid)) { ret = true; } if (bid < bmpSize.load() && isBmpSet(sb_bmp, bid)) { ret = true; } if (bid >= bmpSize.load()) { // blocks newly allocated beyond the bitmap size: // always writable ret = true; } } else { // bmpPrev doesn't exist even though bmpRevnum is different // this happens on the first block reclaim only // so all blocks whose 'BID >= last_commit' are writable. ret = true; } } if (bid < bmpSize.load() && bid < curAllocBid.load() && isBmpSet(sb_bmp, bid)) { // 'curAllocBid' is always smaller than 'bmpSize' // except for the case 'curAllocBid == BLK_NOT_FOUND' ret = true; } } endBmpBarrier(); return ret; } fdb_status Superblock::writeSb(size_t sb_no, ErrLogCallback * log_callback) { ssize_t r; int real_blocksize = file->getBlockSize(); int blocksize = file->getBlockSize() - BLK_MARKER_SIZE; uint8_t *buf = alca(uint8_t, real_blocksize); uint32_t crc, _crc; uint64_t enc_u64; uint64_t num_docs; size_t i, offset; fdb_status fs; memset(buf, 0x0, real_blocksize); offset = 0; // magic number enc_u64 = _endian_encode(file->getVersion()); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // revision number uint64_t sb_revnum = revnum.load(); enc_u64 = _endian_encode(sb_revnum); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // bitmap's revision number enc_u64 = _endian_encode(bmpRevnum.load()); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // curAllocBid bid_t sb_cur_alloc_bid = curAllocBid.load(); enc_u64 = _endian_encode(sb_cur_alloc_bid); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // last header bid bid_t sb_last_hdr_bid = lastHdrBid.load(); enc_u64 = _endian_encode(sb_last_hdr_bid); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // last header rev number uint64_t sb_last_hdr_revnum = lastHdrRevnum.load(); enc_u64 = _endian_encode(sb_last_hdr_revnum); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // minimum active header revnum enc_u64 = _endian_encode(minLiveHdrRevnum); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // minimum active header BID enc_u64 = _endian_encode(minLiveHdrBid); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // # initial free blocks enc_u64 = _endian_encode(numInitFreeBlocks); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // # free blocks enc_u64 = _endian_encode(numFreeBlocks); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // bitmap size uint64_t sb_bmp_size = bmpSize.load(); enc_u64 = _endian_encode(sb_bmp_size); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); bool rsv_bmp_enabled = false; uint32_t cond = SB_RSV_READY; if (rsvBmp && rsvBmp->status.compare_exchange_strong(cond, SB_RSV_WRITING) ) { rsv_bmp_enabled = true; // status becomes 'WRITING' so that switching will be postponed. // note that 'rsvBmp' is not currently used yet so that // it won't block any other tasks except for switching. } // reserved bitmap size (0 if not exist) if (rsv_bmp_enabled) { enc_u64 = _endian_encode(rsvBmp->bmpSize); } else { enc_u64 = 0; } memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); // bitmap doc offsets num_docs = bmpSizeToNumDocs(sb_bmp_size); for (i=0; i<num_docs; ++i) { enc_u64 = _endian_encode(bmpDocOffset[i]); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); } // reserved bitmap doc offsets if (rsv_bmp_enabled) { num_docs = bmpSizeToNumDocs(rsvBmp->bmpSize); for (i=0; i<num_docs; ++i) { enc_u64 = _endian_encode(rsvBmp->bmpDocOffset[i]); memcpy(buf + offset, &enc_u64, sizeof(enc_u64)); offset += sizeof(enc_u64); } rsvBmp->status = SB_RSV_READY; } // CRC crc = get_checksum(buf, offset, file->getCrcMode()); _crc = _endian_encode(crc); memcpy(buf + offset, &_crc, sizeof(_crc)); // set block marker memset(buf + blocksize, BLK_MARKER_SB, BLK_MARKER_SIZE); // directly write a block bypassing block cache r = file->writeBlocks(buf, 1, sb_no); if (r != real_blocksize) { char errno_msg[512]; file->getOps()->get_errno_str(file->getFopsHandle(), errno_msg, 512); fs = FDB_RESULT_SB_RACE_CONDITION; fdb_log(log_callback, fs, "Failed to write the superblock (number: %" _F64 "), %s", static_cast<uint64_t>(sb_no), errno_msg); return fs; } // increase superblock's revision number revnum++; return FDB_RESULT_SUCCESS; } void Superblock::appendBmpDoc(FdbKvsHandle *handle) { // == write bitmap into system docs == // calculate # docs (1MB by default) // (1MB bitmap covers 32GB DB file) size_t i; uint64_t num_docs; char doc_key[64]; // mark stale if previous doc offset exists if (bmpDocOffset) { for (i=0; i<numBmpDocs; ++i) { file->markStale(bmpDocOffset[i], _fdb_get_docsize(bmpDocs[i].length)); } free(bmpDocOffset); free(bmpDocs); bmpDocOffset = NULL; bmpDocs = NULL; } uint64_t sb_bmp_size = bmpSize.load(); numBmpDocs = num_docs = bmpSizeToNumDocs(sb_bmp_size); if (num_docs) { bmpDocOffset = (bid_t*)calloc(num_docs, sizeof(bid_t)); bmpDocs = (struct docio_object*)calloc(num_docs, sizeof(struct docio_object)); } // bitmap doc offsets for (i=0; i<num_docs; ++i) { // append a system doc for bitmap chunk memset(&bmpDocs[i], 0x0, sizeof(struct docio_object)); sprintf(doc_key, "bitmap_%" _F64 "_%d", bmpRevnum.load(), (int)i); bmpDocs[i].key = (void*)doc_key; bmpDocs[i].meta = NULL; bmpDocs[i].body = bmp + (i * SB_MAX_BITMAP_DOC_SIZE); bmpDocs[i].length.keylen = (keylen_t)strlen(doc_key)+1; bmpDocs[i].length.metalen = 0; if (i == num_docs - 1) { // the last doc bmpDocs[i].length.bodylen = (sb_bmp_size / 8) % SB_MAX_BITMAP_DOC_SIZE; } else { // otherwise: 1MB bmpDocs[i].length.bodylen = SB_MAX_BITMAP_DOC_SIZE; } bmpDocs[i].seqnum = 0; bmpDocOffset[i] = handle->dhandle->appendSystemDoc_Docio(&bmpDocs[i]); } } void Superblock::appendRsvBmpDoc(FdbKvsHandle *handle) { size_t i; uint64_t num_docs; char doc_key[64]; struct sb_rsv_bmp *rsv = NULL; rsv = rsvBmp; if (!rsv || rsv->status.load() != SB_RSV_INITIALIZING) { return; } rsv->numBmpDocs = num_docs = bmpSizeToNumDocs(rsv->bmpSize); if (num_docs) { rsv->bmpDocOffset = (bid_t*)calloc(num_docs, sizeof(bid_t)); rsv->bmpDocs = (struct docio_object*) calloc(num_docs, sizeof(struct docio_object)); } // bitmap doc offsets for (i=0; i<num_docs; ++i) { // append a system doc for bitmap chunk memset(&rsv->bmpDocs[i], 0x0, sizeof(struct docio_object)); sprintf(doc_key, "bitmap_%" _F64 "_%d", rsv->bmpRevnum, (int)i); rsv->bmpDocs[i].key = (void*)doc_key; rsv->bmpDocs[i].meta = NULL; rsv->bmpDocs[i].body = rsv->bmp + (i * SB_MAX_BITMAP_DOC_SIZE); rsv->bmpDocs[i].length.keylen = (keylen_t)strlen(doc_key)+1; rsv->bmpDocs[i].length.metalen = 0; if (i == num_docs - 1) { // the last doc rsv->bmpDocs[i].length.bodylen = (rsv->bmpSize / 8) % SB_MAX_BITMAP_DOC_SIZE; } else { // otherwise: 1MB rsv->bmpDocs[i].length.bodylen = SB_MAX_BITMAP_DOC_SIZE; } rsv->bmpDocs[i].seqnum = 0; rsv->bmpDocOffset[i] = handle->dhandle->appendSystemDoc_Docio(&rsv->bmpDocs[i]); } // now 'rsvBmp' is available. rsv->status = SB_RSV_READY; } fdb_status Superblock::readBmpDoc(FdbKvsHandle *handle) { // == read bitmap from system docs == size_t i; uint64_t num_docs; int64_t r_offset; char doc_key[64]; struct sb_rsv_bmp *rsv = NULL; // skip if previous bitmap exists OR // there is no bitmap to be fetched (fast screening) if (bmp.load(std::memory_order_relaxed) || bmpSize.load() == 0) { return FDB_RESULT_SUCCESS; } spin_lock(&lock); // check once again if superblock is already initialized // while the thread was blocked by the lock. if (bmp.load(std::memory_order_relaxed)) { spin_unlock(&lock); return FDB_RESULT_SUCCESS; } uint64_t sb_bmp_size = bmpSize.load(); numBmpDocs = num_docs = bmpSizeToNumDocs(sb_bmp_size); if (!num_docs) { spin_unlock(&lock); return FDB_RESULT_SUCCESS; } free(bmp); bmp = (uint8_t*)calloc(1, (sb_bmp_size+7) / 8); for (i=0; i<num_docs; ++i) { memset(&bmpDocs[i], 0x0, sizeof(struct docio_object)); // pre-allocated buffer for key bmpDocs[i].key = (void*)doc_key; // directly point to the bitmap bmpDocs[i].body = bmp + (i * SB_MAX_BITMAP_DOC_SIZE); r_offset = handle->dhandle->readDoc_Docio(bmpDocOffset[i], &bmpDocs[i], true); if (r_offset <= 0) { // read fail free(bmp); bmp = NULL; spin_unlock(&lock); return r_offset < 0 ? (fdb_status) r_offset : FDB_RESULT_SB_READ_FAIL; } } constructBmpIdx(&bmpIdx, bmp, sb_bmp_size, curAllocBid.load()); rsv = rsvBmp; if (rsv && rsv->status.load() == SB_RSV_INITIALIZING) { // reserved bitmap exists rsv->numBmpDocs = num_docs = bmpSizeToNumDocs(rsv->bmpSize); if (!num_docs) { spin_unlock(&lock); return FDB_RESULT_SUCCESS; } rsv->bmp = (uint8_t*)calloc(1, (rsv->bmpSize+7) / 8); for (i=0; i<num_docs; ++i) { memset(&rsv->bmpDocs[i], 0x0, sizeof(struct docio_object)); // pre-allocated buffer for key rsv->bmpDocs[i].key = (void*)doc_key; // directly point to the (reserved) bitmap rsv->bmpDocs[i].body = rsv->bmp + (i * SB_MAX_BITMAP_DOC_SIZE); r_offset = handle->dhandle->readDoc_Docio(rsv->bmpDocOffset[i], &rsv->bmpDocs[i], true); if (r_offset <= 0) { // read fail free(rsv->bmp); free(bmp); rsv->bmp = bmp = NULL; spin_unlock(&lock); return r_offset < 0 ? (fdb_status) r_offset : FDB_RESULT_SB_READ_FAIL; } } constructBmpIdx(&rsv->bmpIdx, rsv->bmp, rsv->bmpSize, 0); rsv->status = SB_RSV_READY; } spin_unlock(&lock); return FDB_RESULT_SUCCESS; } bool Superblock::checkSyncPeriod() { if (numAlloc * file->getBlockSize() > SB_SYNC_PERIOD) { return true; } return false; } bool Superblock::updateHeader(FdbKvsHandle *handle) { bool ret = false; if ((lastHdrBid.load() != handle->last_hdr_bid) && (lastHdrRevnum.load() < handle->cur_header_revnum)) { lastHdrBid = handle->last_hdr_bid.load(); lastHdrRevnum.store(handle->cur_header_revnum.load()); uint64_t lw_revnum = handle->file->getLastWritableBmpRevnum(); if (lw_revnum == bmpRevnum.load() && bmpPrev) { free(bmpPrev); bmpPrev = NULL; } ret = true; } return ret; } fdb_status Superblock::syncCircular(FdbKvsHandle *handle) { uint64_t sb_revnum; fdb_status fs; sb_revnum = revnum.load(); fs = writeSb(sb_revnum % config.num_sb, &handle->log_callback); return fs; } // Do not call any public api that would sync db header to any uncommitted // header. sb_decision_t Superblock::checkBlockReuse(FdbKvsHandle *handle) { // start block reusing when // 1) if blocks are not reused yet in this file: // when file size becomes larger than the threshold // 2) otherwise: // when # free blocks decreases under the threshold uint64_t live_datasize; uint64_t filesize; uint64_t ratio; if (file->getFileStatus() != FILE_NORMAL) { // being compacted file does not allow block reusing return SBD_NONE; } uint64_t block_reusing_threshold = file->getConfig()->getBlockReusingThreshold(); if (block_reusing_threshold == 0 || block_reusing_threshold >= 100) { // circular block reusing is disabled return SBD_NONE; } filesize = file->getPos(); if (filesize < SB_MIN_BLOCK_REUSING_FILESIZE) { return SBD_NONE; } // at least # keeping headers should exist // since the last block reusing if (handle->cur_header_revnum <= minLiveHdrRevnum + file->getConfig()->getNumKeepingHeaders()) { return SBD_NONE; } live_datasize = FdbEngine::getInstance()->estimateSpaceUsedInternal(handle); if (filesize == 0 || live_datasize == 0 || live_datasize > filesize) { return SBD_NONE; } ratio = (filesize - live_datasize) * 100 / filesize; if (ratio > block_reusing_threshold) { if (!bmpExists()) { // block reusing has not been started yet return SBD_RECLAIM; } else { // stale blocks are already being reused before if (numFreeBlocks == 0) { if (rsvBmp) { // reserved bitmap exists return SBD_SWITCH; } else { // re-reclaim return SBD_RECLAIM; } } else if ( (numFreeBlocks * 100 < numInitFreeBlocks * SB_PRE_RECLAIM_RATIO)) { if ( numInitFreeBlocks * file->getConfig()->getBlockSize() > SB_MIN_BLOCK_REUSING_FILESIZE ) { return SBD_RESERVE; } } } } return SBD_NONE; } bool Superblock::reclaimReusableBlocks(FdbKvsHandle *handle) { size_t i; uint64_t num_blocks, bmp_size_byte; stale_header_info sheader; reusable_block_list blist; // should flush all dirty blocks in cache file->sync_FileMgr(false, &handle->log_callback); sheader = fdb_get_smallest_active_header(handle); if (sheader.bid == BLK_NOT_FOUND) { return false; } // get reusable block list blist = file->getStaleData()->getReusableBlocks(handle, sheader); // update superblock's bitmap uint8_t *new_bmp = NULL, *old_bmp = NULL; num_blocks = file->getPos() / file->getBlockSize(); // 8 bitmaps per byte bmp_size_byte = (num_blocks+7) / 8; fdb_assert(num_blocks >= SB_DEFAULT_NUM_SUPERBLOCKS, num_blocks, SB_DEFAULT_NUM_SUPERBLOCKS); new_bmp = (uint8_t*)calloc(1, bmp_size_byte); // free pre-existing bmp index freeBmpIdx(&bmpIdx); for (i=0; i<blist.n_blocks; ++i) { setBmp(new_bmp, blist.blocks[i].bid, blist.blocks[i].count); if (i==0 && curAllocBid.load() == BLK_NOT_FOUND) { curAllocBid.store(blist.blocks[i].bid); } numFreeBlocks += blist.blocks[i].count; // add info for supplementary bmp index addBmpIdx(&bmpIdx, blist.blocks[i].bid, blist.blocks[i].count); } free(blist.blocks); beginBmpChange(); old_bmp = bmp.load(std::memory_order_relaxed); bmp.store(new_bmp, std::memory_order_relaxed); bmpSize = num_blocks; minLiveHdrRevnum = sheader.revnum; minLiveHdrBid = sheader.bid; bmpRevnum++; numInitFreeBlocks = numFreeBlocks; endBmpChange(); free(old_bmp); return true; } bool Superblock::reserveNextReusableBlocks(FdbKvsHandle *handle) { size_t i; uint64_t num_blocks, bmp_size_byte; stale_header_info sheader; reusable_block_list blist; struct sb_rsv_bmp *rsv = NULL; if (rsvBmp) { // next bitmap already reclaimed return false; } sheader = fdb_get_smallest_active_header(handle); if (sheader.bid == BLK_NOT_FOUND) { return false; } // get reusable block list blist = file->getStaleData()->getReusableBlocks(handle, sheader); // calculate bitmap size num_blocks = file->getPos() / file->getBlockSize(); bmp_size_byte = (num_blocks+7) / 8; if (num_blocks) { rsv = (struct sb_rsv_bmp*)calloc(1, sizeof(struct sb_rsv_bmp)); rsv->bmp = (uint8_t*)calloc(1, bmp_size_byte); rsv->curAllocBid = BLK_NOT_FOUND; // the initial status is 'INITIALIZING' so that 'rsvBmp' is not // available until executing sb_rsv_append_doc(). rsv->status = SB_RSV_INITIALIZING; avl_init(&rsv->bmpIdx, NULL); rsv->bmpSize = num_blocks; for (i=0; i<blist.n_blocks; ++i) { setBmp(rsv->bmp, blist.blocks[i].bid, blist.blocks[i].count); if (i==0 && rsv->curAllocBid == BLK_NOT_FOUND) { rsv->curAllocBid = blist.blocks[i].bid; } rsv->numFreeBlocks += blist.blocks[i].count; addBmpIdx(&rsv->bmpIdx, blist.blocks[i].bid, blist.blocks[i].count); } free(blist.blocks); rsv->minLiveHdrRevnum = sheader.revnum; rsv->minLiveHdrBid = sheader.bid; rsv->bmpRevnum = bmpRevnum+1; rsvBmp = rsv; } return true; } void Superblock::returnReusableBlocks(FdbKvsHandle *handle) { uint64_t node_id; bid_t cur; struct sb_rsv_bmp *rsv; struct avl_node *a; struct bmp_idx_node *item, query; // re-insert all remaining bitmap into stale list uint64_t sb_bmp_size = bmpSize.load(); for (cur = curAllocBid.load(); cur < sb_bmp_size; ++cur) { if (isBmpSet(bmp, cur)) { file->addStaleBlock(cur, 1); } if ((cur % 256) == 0 && cur > 0) { // node ID changes // remove & free current bmp node node_id = cur / 256; query.id = node_id - 1; a = avl_search(&bmpIdx, &query.avl, _bmp_idx_cmp); if (a) { item = _get_entry(a, struct bmp_idx_node, avl); avl_remove(&bmpIdx, a); free(item); } // move to next bmp node do { a = avl_first(&bmpIdx); if (a) { item = _get_entry(a, struct bmp_idx_node, avl); if (item->id <= node_id) { avl_remove(&bmpIdx, a); free(item); continue; } cur = item->id * 256; break; } // no more reusable block cur = sb_bmp_size; break; } while (true); } } numFreeBlocks = 0; curAllocBid.store(BLK_NOT_FOUND); // do the same work for the reserved blocks if exist rsv = rsvBmp; uint32_t cond = SB_RSV_READY; if (rsv && rsv->status.compare_exchange_strong(cond, SB_RSV_VOID)) { for (cur = rsv->curAllocBid; cur < rsv->bmpSize; ++cur) { if (isBmpSet(rsv->bmp, cur)) { file->addStaleBlock(cur, 1); } if ((cur % 256) == 0 && cur > 0) { // node ID changes // remove & free current bmp node node_id = cur / 256; query.id = node_id - 1; a = avl_search(&rsv->bmpIdx, &query.avl, _bmp_idx_cmp); if (a) { item = _get_entry(a, struct bmp_idx_node, avl); avl_remove(&rsv->bmpIdx, a); free(item); } // move to next bmp node do { a = avl_first(&rsv->bmpIdx); if (a) { item = _get_entry(a, struct bmp_idx_node, avl); if (item->id <= node_id) { avl_remove(&rsv->bmpIdx, a); free(item); continue; } cur = item->id * 256; break; } // no more reusable block cur = rsv->bmpSize; break; } while (true); } } rsv->numFreeBlocks = 0; rsv->curAllocBid = BLK_NOT_FOUND; freeBmpIdx(&rsv->bmpIdx); freeRsv(rsv); free(rsv); rsvBmp = NULL; } // re-store into stale tree using next header's revnum filemgr_header_revnum_t revnum = handle->cur_header_revnum; file->getStaleData()->gatherRegions(handle, revnum + 1, BLK_NOT_FOUND, BLK_NOT_FOUND, 0, false ); } void Superblock::updateBmp(uint8_t *target_bmp, bid_t bid, uint64_t len, int mode) { // mode==0: bitmap clear // mode==1: bitmap set uint64_t front_pos, front_len, rear_pos, rear_len; uint64_t mid_pos, mid_len; // front_len rear_len // <-> <--> // 00000111 | 11111111 | 11110000 // ^ <------> mid // front_pos front_pos = bid; front_len = 8 - mod8(front_pos); if (front_len >= len) { front_len = len; rear_pos = rear_len = mid_pos = mid_len = 0; } else { rear_pos = rd8(bid + len); rear_len = mod8(bid + len); mid_pos = bid + front_len; mid_len = len - front_len - rear_len; } // front bitmaps if (front_len) { if (mode) { target_bmp[div8(front_pos)] |= bmp_2d_mask[mod8(front_pos)][front_len]; } else { target_bmp[div8(front_pos)] &= ~bmp_2d_mask[mod8(front_pos)][front_len]; } } // rear bitmaps if (rear_len) { if (mode) { target_bmp[div8(rear_pos)] |= bmp_2d_mask[mod8(rear_pos)][rear_len]; } else { target_bmp[div8(rear_pos)] &= ~bmp_2d_mask[mod8(rear_pos)][rear_len]; } } // mid bitmaps uint8_t mask = (mode)?(0xff):(0x0); if (mid_len == 8) { // 8 bitmaps (1 byte) target_bmp[div8(mid_pos)] = mask; } else if (mid_len < 64) { // 16 ~ 56 bitmaps (2 ~ 7 bytes) size_t i; for (i=0; i<mid_len; i+=8) { target_bmp[div8(mid_pos+i)] = mask; } } else { // larger than 64 bitmaps (8 bytes) memset(target_bmp + div8(mid_pos), mask, div8(mid_len)); } } void Superblock::setBmp(uint8_t *target_bmp, bid_t bid, uint64_t len) { updateBmp(target_bmp, bid, len, 1); } void Superblock::clearBmp(uint8_t *target_bmp, bid_t bid, uint64_t len) { updateBmp(target_bmp, bid, len, 0); } void Superblock::addBmpIdx(struct avl_tree *target_idx, bid_t bid, bid_t count) { bid_t cur, start_id, stop_id; struct avl_node *a; struct bmp_idx_node *item, query; // 256 blocks per node start_id = bid >> 8; stop_id = (bid+count-1) >> 8; for (cur=start_id; cur<=stop_id; ++cur) { query.id = cur; a = avl_search(target_idx, &query.avl, _bmp_idx_cmp); if (a) { // already exists .. do nothing } else { // create a node item = (struct bmp_idx_node*)calloc(1, sizeof(struct bmp_idx_node)); item->id = query.id; avl_insert(target_idx, &item->avl, _bmp_idx_cmp); } } } void Superblock::freeBmpIdx(struct avl_tree *target_idx) { // free all supplemental bmp idx nodes struct avl_node *a; struct bmp_idx_node *item; a = avl_first(target_idx); while (a) { item = _get_entry(a, struct bmp_idx_node, avl); a = avl_next(a); avl_remove(target_idx, &item->avl); free(item); } } void Superblock::constructBmpIdx(struct avl_tree *target_idx, uint8_t *src_bmp, uint64_t src_bmp_size, bid_t start_bid) { uint64_t i, node_idx; uint64_t *bmp64 = (uint64_t*)src_bmp; struct bmp_idx_node *item; if (start_bid == BLK_NOT_FOUND) { start_bid = 0; } // Since a single byte includes 8 bitmaps, an 8-byte integer contains 64 bitmaps. // By converting bitmap array to uint64_t array, we can quickly verify if a // 64-bitmap-group has at least one non-zero bit or not. for (i=start_bid/64; i<src_bmp_size/64; ++i) { // in this loop, 'i' denotes bitmap group number. node_idx = i/4; if (bmp64[i]) { item = (struct bmp_idx_node *)calloc(1, sizeof(struct bmp_idx_node)); item->id = node_idx; avl_insert(target_idx, &item->avl, _bmp_idx_cmp); // skip other bitmaps in the same bitmap index node // (1 bitmap index node == 4 bitmap groups == 256 bitmaps) i = (node_idx+1)*4; } } // If there are remaining bitmaps, check if they are non-zero or not one by one. if (src_bmp_size % 64) { uint8_t off; uint64_t idx, start; start = (src_bmp_size/64)*64; if (start < start_bid) { start = start_bid; } for (i=start; i<src_bmp_size; ++i) { // in this loop, 'i' denotes bitmap number (i.e., BID). idx = div8(i); off = mod8(i); if (src_bmp[idx] & bmp_basic_mask[off]) { node_idx = i >> 8; item = (struct bmp_idx_node *)calloc(1, sizeof(struct bmp_idx_node)); item->id = node_idx; avl_insert(target_idx, &item->avl, _bmp_idx_cmp); i = (node_idx+1)*256; } } } } size_t Superblock::bmpSizeToNumDocs(uint64_t bmp_size) { if (bmp_size) { // 8 bitmaps per byte uint64_t num_bits_per_doc = 8 * SB_MAX_BITMAP_DOC_SIZE; return (bmp_size + num_bits_per_doc - 1) / num_bits_per_doc; } else { return 0; } } bool Superblock::isBmpSet(uint8_t *bmp, bid_t bid) { return (bmp[div8(bid)] & bmp_basic_mask[mod8(bid)]); } void Superblock::freeRsv(struct sb_rsv_bmp *rsv) { free(rsv->bmp); free(rsv->bmpDocOffset); free(rsv->bmpDocs); }
{ "content_hash": "03001ce65a859d8d7e98996c44bba0fb", "timestamp": "", "source": "github", "line_count": 1682, "max_line_length": 86, "avg_line_length": 30.072532699167656, "alnum_prop": 0.5277569095725753, "repo_name": "hisundar/forestdb", "id": "ee2d61245cb455ee4b6db6f6e2cbe87695202583", "size": "50582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/superblock.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "8009" }, { "name": "C++", "bytes": "3118036" }, { "name": "CMake", "bytes": "51966" }, { "name": "Objective-C", "bytes": "3171" } ], "symlink_target": "" }
package pubclas; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.UUID; import android.util.Log; /** * 调用方法 * Map<String, String> params = new HashMap<String, String>(); uploadUtil.uploadFile( picPath,"image", requestURL,params); */ /** * * 上传工具类 * 支持上传文件和参数 */ public class UploadUtil { private static UploadUtil uploadUtil; private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 private static final String PREFIX = "--"; private static final String LINE_END = "\r\n"; private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型 private UploadUtil() { } /** * 单例模式获取上传工具类 * @return */ public static UploadUtil getInstance() { if (null == uploadUtil) { uploadUtil = new UploadUtil(); } return uploadUtil; } private static final String TAG = "UploadUtil"; private int readTimeOut = 10 * 1000; // 读取超时 private int connectTimeout = 10 * 1000; // 超时时间 /*** * 请求使用多长时间 */ private static int requestTime = 0; private static final String CHARSET = "utf-8"; // 设置编码 /*** * 上传成功 */ public static final int UPLOAD_SUCCESS_CODE = 1; /** * 文件不存在 */ public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2; /** * 服务器出错 */ public static final int UPLOAD_SERVER_ERROR_CODE = 3; protected static final int WHAT_TO_UPLOAD = 1; protected static final int WHAT_UPLOAD_DONE = 2; /** * android上传文件到服务器 * * @param filePath * 需要上传的文件sd卡的路径 * @param fileKey "Image" * @param RequestURL * 请求的URL */ public void uploadFile(String filePath, String fileKey, String RequestURL, Map<String, String> param) { Log.e("filePath",filePath); if (filePath == null) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); return; } try { File file = new File(filePath); uploadFile(file, fileKey, RequestURL, param); } catch (Exception e) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); e.printStackTrace(); return; } } /** * android上传文件到服务器 * * @param file * 需要上传的文件 * @param fileKey * 在网页上<input type=file name=xxx/> xxx就是这里的fileKey * @param RequestURL * 请求的URL */ public void uploadFile(final File file, final String fileKey, final String RequestURL, final Map<String, String> param) { if (file == null || (!file.exists())) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); return; } //Log.i(TAG, "请求的URL=" + RequestURL); //Log.i(TAG, "请求的fileName=" + file.getName()); //Log.i(TAG, "请求的fileKey=" + fileKey); new Thread(new Runnable() { //开启线程上传文件 @Override public void run() { toUploadFile(file, fileKey, RequestURL, param); } }).start(); } private void toUploadFile(File file, String fileKey, String RequestURL, Map<String, String> param) { String result = null; requestTime= 0; long requestTime = System.currentTimeMillis(); long responseTime = 0; try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(readTimeOut); conn.setConnectTimeout(connectTimeout); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 //conn.setRequestMethod("PUT"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = null; String params = ""; /*** * 以下是用于上传参数 */ if (param != null && param.size() > 0) { Iterator<String> it = param.keySet().iterator(); while (it.hasNext()) { sb = null; sb = new StringBuffer(); String key = it.next(); String value = param.get(key); sb.append(PREFIX).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END); sb.append(value).append(LINE_END); params = sb.toString(); Log.i(TAG, key+"="+params+"##"); dos.write(params.getBytes()); // dos.flush(); } } sb = null; params = null; sb = new StringBuffer(); /** * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append(PREFIX).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\"" + file.getName() + "\"" + LINE_END); //sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的 sb.append("Content-Type:image/jpg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的 sb.append(LINE_END); params = sb.toString(); sb = null; //Log.i(TAG, file.getName()+"=" + params+"##"); dos.write(params.getBytes()); /**上传文件*/ InputStream is = new FileInputStream(file); Log.e("onUploadProcessListener == null",(onUploadProcessListener == null) + ""); Log.e("file == null",(file == null)+""); onUploadProcessListener.initUpload((int)file.length()); byte[] bytes = new byte[1024]; int len = 0; int curLen = 0; while ((len = is.read(bytes)) != -1) { curLen += len; dos.write(bytes, 0, len); onUploadProcessListener.onUploadProcess(curLen); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); // // dos.write(tempOutputStream.toByteArray()); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); responseTime = System.currentTimeMillis(); this.requestTime = (int) ((responseTime-requestTime)/1000); Log.e(TAG, "response code:" + res); if (res == 200) { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); sendMessage(UPLOAD_SUCCESS_CODE, result); //sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:"+ result); return; } else { Log.e(TAG, "request error"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:code=" + res); return; } } catch (MalformedURLException e) { e.printStackTrace(); sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage()); e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage()); e.printStackTrace(); return; } } /** * 发送上传结果 * @param responseCode * @param responseMessage */ private void sendMessage(int responseCode,String responseMessage) { onUploadProcessListener.onUploadDone(responseCode, responseMessage); } /** * 下面是一个自定义的回调函数,用到回调上传文件是否完成 * * @author shimingzheng * */ public static interface OnUploadProcessListener { /** * 上传响应 * @param responseCode * @param message */ void onUploadDone(int responseCode, String message); /** * 上传中 * @param uploadSize */ void onUploadProcess(int uploadSize); /** * 准备上传 * @param fileSize */ void initUpload(int fileSize); } private OnUploadProcessListener onUploadProcessListener; public void setOnUploadProcessListener(OnUploadProcessListener onUploadProcessListener) { this.onUploadProcessListener = onUploadProcessListener; } public int getReadTimeOut() { return readTimeOut; } public void setReadTimeOut(int readTimeOut) { this.readTimeOut = readTimeOut; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } /** * 获取上传使用的时间 * @return */ public static int getRequestTime() { return requestTime; } public static interface uploadProcessListener{ } }
{ "content_hash": "745a168957ff25dd321d1de62e14f4b1", "timestamp": "", "source": "github", "line_count": 331, "max_line_length": 117, "avg_line_length": 27.459214501510573, "alnum_prop": 0.6305424139069205, "repo_name": "wisegps/baba_en", "id": "b5ccb23a3ee0a00ee1cebcb40c7c0873ac87dde4", "size": "9889", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pubclas/UploadUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1384069" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>Tiles Gateway</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta http-equiv="Content-Security-Policy" content="default-src *; style-src &apos;self&apos; &apos;unsafe-inline&apos;; script-src &apos;self&apos; &apos;unsafe-inline&apos; &apos;unsafe-eval&apos;"> <meta name="format-detection" content="telephone=no"> <meta name="msapplication-tap-highlight" content="no"> <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico"> <link rel="manifest" href="manifest.json"> <meta name="theme-color" content="#4e8ef7"> <!-- cordova.js required for cordova apps --> <script src="cordova.js"></script> <!-- un-comment this code to enable service worker <script> if ('serviceWorker' in navigator) { navigator.serviceWorker.register('service-worker.js') .then(() => console.log('service worker installed')) .catch(err => console.log('Error', err)); } </script>--> <link href="build/main.css" rel="stylesheet"> </head> <body> <!-- Ionic's root component and where the app will load --> <ion-app></ion-app> <!-- The polyfills js is generated during the build process --> <script src="build/polyfills.js"></script> <!-- The bundle js is generated during the build process --> <script src="build/main.js"></script> </body> </html>
{ "content_hash": "a9a8b909eaa35f2fb9981c4fa0083244", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 202, "avg_line_length": 35.285714285714285, "alnum_prop": 0.6700404858299596, "repo_name": "teseolab/rapIoT-gateway-app", "id": "c9fdd20329e1d9fad92c1da5ad27f2a57eec2522", "size": "1482", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3169" }, { "name": "HTML", "bytes": "10420" }, { "name": "JavaScript", "bytes": "2205" }, { "name": "TypeScript", "bytes": "129945" } ], "symlink_target": "" }
package org.libriami.tests.model; import junit.framework.TestCase; import org.libriami.model.Address; import org.libriami.model.Contact; import org.libriami.model.EmailAddress; import org.libriami.model.PhoneNumber; public class TestMergeContacts extends TestCase { public void testMergeContacts() throws Exception { Contact c1 = new Contact("Test", "Hans"); c1.getEmail().add(new EmailAddress("hans@test.org")); c1.getAddress().add(new Address("Some street 123\nfoo,bar,D-70123 Stuttgart")); Contact c2 = new Contact("Test", "Hans"); c2.getEmail().add(new EmailAddress("hans@test.org")); c2.getEmail().add(new EmailAddress("hans2@fooo.de")); c2.getPhone().add(new PhoneNumber("+49711545454")); c2.getAddress().add(new Address("Some street 123\nfoo,bar,D-70123 Stuttgart")); c2.getAddress().add(new Address("Some other street\n,D-70124 Stuttgart")); // ContactMerger.merge(c1, c2); c1.merge(c2); System.out.println(c1); } }
{ "content_hash": "abb7473171941f3a15f712721800b771", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 81, "avg_line_length": 30.12121212121212, "alnum_prop": 0.704225352112676, "repo_name": "walterDurin/libriami", "id": "ffabe615a4538da0bdc4779986c75a91c3967be8", "size": "1607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/libriami/tests/model/TestMergeContacts.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "137058" } ], "symlink_target": "" }
@interface PodsDummy_ProtonomeRoundedViews : NSObject @end @implementation PodsDummy_ProtonomeRoundedViews @end
{ "content_hash": "46221bb6546d72017ea294c8591381a5", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 53, "avg_line_length": 28, "alnum_prop": 0.8660714285714286, "repo_name": "dclelland/HOWL", "id": "596ba066fa08036725a1f43dbce3955097fb6b54", "size": "146", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pods/Target Support Files/ProtonomeRoundedViews/ProtonomeRoundedViews-dummy.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "180" }, { "name": "Ruby", "bytes": "1022" }, { "name": "Swift", "bytes": "62583" } ], "symlink_target": "" }
/** @Generated Interrupt Manager File @Company: Microchip Technology Inc. @File Name: interrupt_manager.c @Summary: This is the Interrupt Manager file generated using MPLAB® Code Configurator @Description: This header file provides implementations for global interrupt handling. For individual peripheral handlers please see the peripheral driver for all modules selected in the GUI. Generation Information : Product Revision : MPLAB® Code Configurator - v2.25.2 Device : PIC18F45K22 Driver Version : 1.02 The generated drivers are tested against the following: Compiler : XC8 v1.34 MPLAB : MPLAB X v2.35 or v3.00 */ /* Copyright (c) 2013 - 2015 released Microchip Technology Inc. All rights reserved. Microchip licenses to you the right to use, modify, copy and distribute Software only when embedded on a Microchip microcontroller or digital signal controller that is integrated into your product or third party product (pursuant to the sublicense terms in the accompanying license agreement). You should refer to the license agreement accompanying this Software for additional information regarding your rights and obligations. SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. */ #include "interrupt_manager.h" #include "mcc.h" void INTERRUPT_Initialize(void) { // Disable Interrupt Priority Vectors (16CXXX Compatibility Mode) RCONbits.IPEN = 0; // Clear peripheral interrupt priority bits (default reset value) // RCI IPR3bits.RC2IP = 0; // TXI IPR3bits.TX2IP = 0; // RCI IPR1bits.RC1IP = 0; // TXI IPR1bits.TX1IP = 0; } void interrupt INTERRUPT_InterruptManager(void) { // interrupt handler if (PIE3bits.RC2IE == 1 && PIR3bits.RC2IF == 1) { EUSART2_Receive_ISR(); } else if (PIE3bits.TX2IE == 1 && PIR3bits.TX2IF == 1) { EUSART2_Transmit_ISR(); } else if (PIE1bits.RC1IE == 1 && PIR1bits.RC1IF == 1) { EUSART1_Receive_ISR(); } else if (PIE1bits.TX1IE == 1 && PIR1bits.TX1IF == 1) { EUSART1_Transmit_ISR(); } else { //Unhandled Interrupt } } /** End of File */
{ "content_hash": "8ac1adcd9dd2004475e9c6c2d386f8e6", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 82, "avg_line_length": 35.32941176470588, "alnum_prop": 0.6913086913086913, "repo_name": "uazipsev/EV15", "id": "a20df60a951b865885ea18c7516f715fdcca25a1", "size": "3003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Charger_Control.X/mcc_generated_files/interrupt_manager.c", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "7926" }, { "name": "Assembly", "bytes": "210550" }, { "name": "C", "bytes": "1189591" }, { "name": "C#", "bytes": "79493" }, { "name": "C++", "bytes": "27479" }, { "name": "Csound Score", "bytes": "1872" }, { "name": "Eagle", "bytes": "163778510" }, { "name": "Makefile", "bytes": "469928" }, { "name": "Objective-C", "bytes": "2646" }, { "name": "PAWN", "bytes": "67388" }, { "name": "PHP", "bytes": "423" }, { "name": "PLSQL", "bytes": "5219632" }, { "name": "Processing", "bytes": "68698" }, { "name": "Python", "bytes": "4742" }, { "name": "Shell", "bytes": "21862" } ], "symlink_target": "" }
#include "version.h" #include "export.h" #include "tools/editor/editor_settings.h" #include "tools/editor/editor_import_export.h" #include "tools/editor/editor_node.h" #include "io/zip_io.h" #include "io/marshalls.h" #include "globals.h" #include "os/file_access.h" #include "os/os.h" #include "platform/android/logo.h" static const char* android_perms[]={ "ACCESS_CHECKIN_PROPERTIES", "ACCESS_COARSE_LOCATION", "ACCESS_FINE_LOCATION", "ACCESS_LOCATION_EXTRA_COMMANDS", "ACCESS_MOCK_LOCATION", "ACCESS_NETWORK_STATE", "ACCESS_SURFACE_FLINGER", "ACCESS_WIFI_STATE", "ACCOUNT_MANAGER", "ADD_VOICEMAIL", "AUTHENTICATE_ACCOUNTS", "BATTERY_STATS", "BIND_ACCESSIBILITY_SERVICE", "BIND_APPWIDGET", "BIND_DEVICE_ADMIN", "BIND_INPUT_METHOD", "BIND_NFC_SERVICE", "BIND_NOTIFICATION_LISTENER_SERVICE", "BIND_PRINT_SERVICE", "BIND_REMOTEVIEWS", "BIND_TEXT_SERVICE", "BIND_VPN_SERVICE", "BIND_WALLPAPER", "BLUETOOTH", "BLUETOOTH_ADMIN", "BLUETOOTH_PRIVILEGED", "BRICK", "BROADCAST_PACKAGE_REMOVED", "BROADCAST_SMS", "BROADCAST_STICKY", "BROADCAST_WAP_PUSH", "CALL_PHONE", "CALL_PRIVILEGED", "CAMERA", "CAPTURE_AUDIO_OUTPUT", "CAPTURE_SECURE_VIDEO_OUTPUT", "CAPTURE_VIDEO_OUTPUT", "CHANGE_COMPONENT_ENABLED_STATE", "CHANGE_CONFIGURATION", "CHANGE_NETWORK_STATE", "CHANGE_WIFI_MULTICAST_STATE", "CHANGE_WIFI_STATE", "CLEAR_APP_CACHE", "CLEAR_APP_USER_DATA", "CONTROL_LOCATION_UPDATES", "DELETE_CACHE_FILES", "DELETE_PACKAGES", "DEVICE_POWER", "DIAGNOSTIC", "DISABLE_KEYGUARD", "DUMP", "EXPAND_STATUS_BAR", "FACTORY_TEST", "FLASHLIGHT", "FORCE_BACK", "GET_ACCOUNTS", "GET_PACKAGE_SIZE", "GET_TASKS", "GET_TOP_ACTIVITY_INFO", "GLOBAL_SEARCH", "HARDWARE_TEST", "INJECT_EVENTS", "INSTALL_LOCATION_PROVIDER", "INSTALL_PACKAGES", "INSTALL_SHORTCUT", "INTERNAL_SYSTEM_WINDOW", "INTERNET", "KILL_BACKGROUND_PROCESSES", "LOCATION_HARDWARE", "MANAGE_ACCOUNTS", "MANAGE_APP_TOKENS", "MANAGE_DOCUMENTS", "MASTER_CLEAR", "MEDIA_CONTENT_CONTROL", "MODIFY_AUDIO_SETTINGS", "MODIFY_PHONE_STATE", "MOUNT_FORMAT_FILESYSTEMS", "MOUNT_UNMOUNT_FILESYSTEMS", "NFC", "PERSISTENT_ACTIVITY", "PROCESS_OUTGOING_CALLS", "READ_CALENDAR", "READ_CALL_LOG", "READ_CONTACTS", "READ_EXTERNAL_STORAGE", "READ_FRAME_BUFFER", "READ_HISTORY_BOOKMARKS", "READ_INPUT_STATE", "READ_LOGS", "READ_PHONE_STATE", "READ_PROFILE", "READ_SMS", "READ_SOCIAL_STREAM", "READ_SYNC_SETTINGS", "READ_SYNC_STATS", "READ_USER_DICTIONARY", "REBOOT", "RECEIVE_BOOT_COMPLETED", "RECEIVE_MMS", "RECEIVE_SMS", "RECEIVE_WAP_PUSH", "RECORD_AUDIO", "REORDER_TASKS", "RESTART_PACKAGES", "SEND_RESPOND_VIA_MESSAGE", "SEND_SMS", "SET_ACTIVITY_WATCHER", "SET_ALARM", "SET_ALWAYS_FINISH", "SET_ANIMATION_SCALE", "SET_DEBUG_APP", "SET_ORIENTATION", "SET_POINTER_SPEED", "SET_PREFERRED_APPLICATIONS", "SET_PROCESS_LIMIT", "SET_TIME", "SET_TIME_ZONE", "SET_WALLPAPER", "SET_WALLPAPER_HINTS", "SIGNAL_PERSISTENT_PROCESSES", "STATUS_BAR", "SUBSCRIBED_FEEDS_READ", "SUBSCRIBED_FEEDS_WRITE", "SYSTEM_ALERT_WINDOW", "TRANSMIT_IR", "UNINSTALL_SHORTCUT", "UPDATE_DEVICE_STATS", "USE_CREDENTIALS", "USE_SIP", "VIBRATE", "WAKE_LOCK", "WRITE_APN_SETTINGS", "WRITE_CALENDAR", "WRITE_CALL_LOG", "WRITE_CONTACTS", "WRITE_EXTERNAL_STORAGE", "WRITE_GSERVICES", "WRITE_HISTORY_BOOKMARKS", "WRITE_PROFILE", "WRITE_SECURE_SETTINGS", "WRITE_SETTINGS", "WRITE_SMS", "WRITE_SOCIAL_STREAM", "WRITE_SYNC_SETTINGS", "WRITE_USER_DICTIONARY", NULL}; class EditorExportPlatformAndroid : public EditorExportPlatform { OBJ_TYPE( EditorExportPlatformAndroid,EditorExportPlatform ); enum { MAX_USER_PERMISSIONS=20, SCREEN_SMALL=0, SCREEN_NORMAL=1, SCREEN_LARGE=2, SCREEN_XLARGE=3, SCREEN_MAX=4 }; String custom_release_package; String custom_debug_package; int version_code; String version_name; String package; String name; String icon; String cmdline; bool _signed; bool apk_expansion; bool remove_prev; bool use_32_fb; bool immersive; bool export_arm; bool export_x86; String apk_expansion_salt; String apk_expansion_pkey; int orientation; String release_keystore; String release_password; String release_username; struct APKExportData { zipFile apk; EditorProgress *ep; }; struct Device { String id; String name; String description; }; Vector<Device> devices; bool devices_changed; Mutex *device_lock; Thread *device_thread; Ref<ImageTexture> logo; Set<String> perms; String user_perms[MAX_USER_PERMISSIONS]; bool screen_support[SCREEN_MAX]; volatile bool quit_request; static void _device_poll_thread(void *ud); String get_package_name(); String get_project_name() const; void _fix_manifest(Vector<uint8_t>& p_manifest, bool p_give_internet); void _fix_resources(Vector<uint8_t>& p_manifest); static Error save_apk_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total); protected: bool _set(const StringName& p_name, const Variant& p_value); bool _get(const StringName& p_name,Variant &r_ret) const; void _get_property_list( List<PropertyInfo> *p_list) const; public: virtual String get_name() const { return "Android"; } virtual ImageCompression get_image_compression() const { return IMAGE_COMPRESSION_ETC1; } virtual Ref<Texture> get_logo() const { return logo; } virtual bool poll_devices(); virtual int get_device_count() const; virtual String get_device_name(int p_device) const; virtual String get_device_info(int p_device) const; virtual Error run(int p_device,int p_flags=0); virtual bool requieres_password(bool p_debug) const { return !p_debug; } virtual String get_binary_extension() const { return "apk"; } virtual Error export_project(const String& p_path, bool p_debug, int p_flags=0); virtual bool can_export(String *r_error=NULL) const; EditorExportPlatformAndroid(); ~EditorExportPlatformAndroid(); }; bool EditorExportPlatformAndroid::_set(const StringName& p_name, const Variant& p_value) { String n=p_name; if (n=="one_click_deploy/clear_previous_install") remove_prev=p_value; else if (n=="custom_package/debug") custom_debug_package=p_value; else if (n=="custom_package/release") custom_release_package=p_value; else if (n=="version/code") version_code=p_value; else if (n=="version/name") version_name=p_value; else if (n=="command_line/extra_args") cmdline=p_value; else if (n=="package/unique_name") package=p_value; else if (n=="package/name") name=p_value; else if (n=="package/icon") icon=p_value; else if (n=="package/signed") _signed=p_value; else if (n=="architecture/arm") export_arm=p_value; else if (n=="architecture/x86") export_x86=p_value; else if (n=="screen/use_32_bits_view") use_32_fb=p_value; else if (n=="screen/immersive_mode") immersive=p_value; else if (n=="screen/orientation") orientation=p_value; else if (n=="screen/support_small") screen_support[SCREEN_SMALL]=p_value; else if (n=="screen/support_normal") screen_support[SCREEN_NORMAL]=p_value; else if (n=="screen/support_large") screen_support[SCREEN_LARGE]=p_value; else if (n=="screen/support_xlarge") screen_support[SCREEN_XLARGE]=p_value; else if (n=="keystore/release") release_keystore=p_value; else if (n=="keystore/release_user") release_username=p_value; else if (n=="keystore/release_password") release_password=p_value; else if (n=="apk_expansion/enable") apk_expansion=p_value; else if (n=="apk_expansion/SALT") apk_expansion_salt=p_value; else if (n=="apk_expansion/public_key") apk_expansion_pkey=p_value; else if (n.begins_with("permissions/")) { String what = n.get_slicec('/',1).to_upper(); bool state = p_value; if (state) perms.insert(what); else perms.erase(what); } else if (n.begins_with("user_permissions/")) { int which = n.get_slicec('/',1).to_int(); ERR_FAIL_INDEX_V(which,MAX_USER_PERMISSIONS,false); user_perms[which]=p_value; } else return false; return true; } bool EditorExportPlatformAndroid::_get(const StringName& p_name,Variant &r_ret) const{ String n=p_name; if (n=="one_click_deploy/clear_previous_install") r_ret=remove_prev; else if (n=="custom_package/debug") r_ret=custom_debug_package; else if (n=="custom_package/release") r_ret=custom_release_package; else if (n=="version/code") r_ret=version_code; else if (n=="version/name") r_ret=version_name; else if (n=="command_line/extra_args") r_ret=cmdline; else if (n=="package/unique_name") r_ret=package; else if (n=="package/name") r_ret=name; else if (n=="package/icon") r_ret=icon; else if (n=="package/signed") r_ret=_signed; else if (n=="architecture/arm") r_ret=export_arm; else if (n=="architecture/x86") r_ret=export_x86; else if (n=="screen/use_32_bits_view") r_ret=use_32_fb; else if (n=="screen/immersive_mode") r_ret=immersive; else if (n=="screen/orientation") r_ret=orientation; else if (n=="screen/support_small") r_ret=screen_support[SCREEN_SMALL]; else if (n=="screen/support_normal") r_ret=screen_support[SCREEN_NORMAL]; else if (n=="screen/support_large") r_ret=screen_support[SCREEN_LARGE]; else if (n=="screen/support_xlarge") r_ret=screen_support[SCREEN_XLARGE]; else if (n=="keystore/release") r_ret=release_keystore; else if (n=="keystore/release_user") r_ret=release_username; else if (n=="keystore/release_password") r_ret=release_password; else if (n=="apk_expansion/enable") r_ret=apk_expansion; else if (n=="apk_expansion/SALT") r_ret=apk_expansion_salt; else if (n=="apk_expansion/public_key") r_ret=apk_expansion_pkey; else if (n.begins_with("permissions/")) { String what = n.get_slicec('/',1).to_upper(); r_ret = perms.has(what); } else if (n.begins_with("user_permissions/")) { int which = n.get_slicec('/',1).to_int(); ERR_FAIL_INDEX_V(which,MAX_USER_PERMISSIONS,false); r_ret=user_perms[which]; } else return false; return true; } void EditorExportPlatformAndroid::_get_property_list( List<PropertyInfo> *p_list) const{ p_list->push_back( PropertyInfo( Variant::BOOL, "one_click_deploy/clear_previous_install")); p_list->push_back( PropertyInfo( Variant::STRING, "custom_package/debug", PROPERTY_HINT_GLOBAL_FILE,"apk")); p_list->push_back( PropertyInfo( Variant::STRING, "custom_package/release", PROPERTY_HINT_GLOBAL_FILE,"apk")); p_list->push_back( PropertyInfo( Variant::STRING, "command_line/extra_args")); p_list->push_back( PropertyInfo( Variant::INT, "version/code", PROPERTY_HINT_RANGE,"1,65535,1")); p_list->push_back( PropertyInfo( Variant::STRING, "version/name") ); p_list->push_back( PropertyInfo( Variant::STRING, "package/unique_name") ); p_list->push_back( PropertyInfo( Variant::STRING, "package/name") ); p_list->push_back( PropertyInfo( Variant::STRING, "package/icon",PROPERTY_HINT_FILE,"png") ); p_list->push_back( PropertyInfo( Variant::BOOL, "package/signed") ); p_list->push_back( PropertyInfo( Variant::BOOL, "architecture/arm") ); p_list->push_back( PropertyInfo( Variant::BOOL, "architecture/x86") ); p_list->push_back( PropertyInfo( Variant::BOOL, "screen/use_32_bits_view") ); p_list->push_back( PropertyInfo( Variant::BOOL, "screen/immersive_mode") ); p_list->push_back( PropertyInfo( Variant::INT, "screen/orientation",PROPERTY_HINT_ENUM,"Landscape,Portrait") ); p_list->push_back( PropertyInfo( Variant::BOOL, "screen/support_small") ); p_list->push_back( PropertyInfo( Variant::BOOL, "screen/support_normal") ); p_list->push_back( PropertyInfo( Variant::BOOL, "screen/support_large") ); p_list->push_back( PropertyInfo( Variant::BOOL, "screen/support_xlarge") ); p_list->push_back( PropertyInfo( Variant::STRING, "keystore/release",PROPERTY_HINT_GLOBAL_FILE,"keystore") ); p_list->push_back( PropertyInfo( Variant::STRING, "keystore/release_user" ) ); p_list->push_back( PropertyInfo( Variant::STRING, "keystore/release_password" ) ); p_list->push_back( PropertyInfo( Variant::BOOL, "apk_expansion/enable" ) ); p_list->push_back( PropertyInfo( Variant::STRING, "apk_expansion/SALT" ) ); p_list->push_back( PropertyInfo( Variant::STRING, "apk_expansion/public_key",PROPERTY_HINT_MULTILINE_TEXT ) ); const char **perms = android_perms; while(*perms) { p_list->push_back( PropertyInfo( Variant::BOOL, "permissions/"+String(*perms).to_lower())); perms++; } for(int i=0;i<MAX_USER_PERMISSIONS;i++) { p_list->push_back( PropertyInfo( Variant::STRING, "user_permissions/"+itos(i))); } //p_list->push_back( PropertyInfo( Variant::INT, "resources/pack_mode", PROPERTY_HINT_ENUM,"Copy,Single Exec.,Pack (.pck),Bundles (Optical)")); } static String _parse_string(const uint8_t *p_bytes,bool p_utf8) { uint32_t offset=0; uint32_t len = decode_uint16(&p_bytes[offset]); if (p_utf8) { //don't know how to read extended utf8, this will have to be for now len>>=8; } offset+=2; //printf("len %i, unicode: %i\n",len,int(p_utf8)); if (p_utf8) { Vector<uint8_t> str8; str8.resize(len+1); for(int i=0;i<len;i++) { str8[i]=p_bytes[offset+i]; } str8[len]=0; String str; str.parse_utf8((const char*)str8.ptr()); return str; } else { String str; for(int i=0;i<len;i++) { CharType c = decode_uint16(&p_bytes[offset+i*2]); if (c==0) break; str += String::chr(c); } return str; } } void EditorExportPlatformAndroid::_fix_resources(Vector<uint8_t>& p_manifest) { const int UTF8_FLAG = 0x00000100; print_line("*******************GORRRGLE***********************"); uint32_t header = decode_uint32(&p_manifest[0]); uint32_t filesize = decode_uint32(&p_manifest[4]); uint32_t string_block_len = decode_uint32(&p_manifest[16]); uint32_t string_count = decode_uint32(&p_manifest[20]); uint32_t string_flags = decode_uint32(&p_manifest[28]); const uint32_t string_table_begins = 40; Vector<String> string_table; printf("stirng block len: %i\n",string_block_len); printf("stirng count: %i\n",string_count); printf("flags: %x\n",string_flags); for(int i=0;i<string_count;i++) { uint32_t offset = decode_uint32(&p_manifest[string_table_begins+i*4]); offset+=string_table_begins+string_count*4; String str = _parse_string(&p_manifest[offset],string_flags&UTF8_FLAG); if (str.begins_with("godot-project-name")) { if (str=="godot-project-name") { //project name str = get_project_name(); } else { String lang = str.substr(str.find_last("-")+1,str.length()).replace("-","_"); String prop = "application/name_"+lang; if (Globals::get_singleton()->has(prop)) { str = Globals::get_singleton()->get(prop); } else { str = get_project_name(); } } } string_table.push_back(str); } //write a new string table, but use 16 bits Vector<uint8_t> ret; ret.resize(string_table_begins+string_table.size()*4); for(int i=0;i<string_table_begins;i++) { ret[i]=p_manifest[i]; } int ofs=0; for(int i=0;i<string_table.size();i++) { encode_uint32(ofs,&ret[string_table_begins+i*4]); ofs+=string_table[i].length()*2+2+2; } ret.resize(ret.size()+ofs); uint8_t *chars=&ret[ret.size()-ofs]; for(int i=0;i<string_table.size();i++) { String s = string_table[i]; encode_uint16(s.length(),chars); chars+=2; for(int j=0;j<s.length();j++) { encode_uint16(s[j],chars); chars+=2; } encode_uint16(0,chars); chars+=2; } //pad while(ret.size()%4) ret.push_back(0); //change flags to not use utf8 encode_uint32(string_flags&~0x100,&ret[28]); //change length encode_uint32(ret.size()-12,&ret[16]); //append the rest... int rest_from = 12+string_block_len; int rest_to = ret.size(); int rest_len = (p_manifest.size() - rest_from); ret.resize(ret.size() + (p_manifest.size() - rest_from) ); for(int i=0;i<rest_len;i++) { ret[rest_to+i]=p_manifest[rest_from+i]; } //finally update the size encode_uint32(ret.size(),&ret[4]); p_manifest=ret; printf("end\n"); } String EditorExportPlatformAndroid::get_project_name() const { String aname; if (this->name!="") { aname=this->name; } else { aname = Globals::get_singleton()->get("application/name"); } if (aname=="") { aname=_MKSTR(VERSION_NAME); } return aname; } void EditorExportPlatformAndroid::_fix_manifest(Vector<uint8_t>& p_manifest,bool p_give_internet) { const int CHUNK_AXML_FILE = 0x00080003; const int CHUNK_RESOURCEIDS = 0x00080180; const int CHUNK_STRINGS = 0x001C0001; const int CHUNK_XML_END_NAMESPACE = 0x00100101; const int CHUNK_XML_END_TAG = 0x00100103; const int CHUNK_XML_START_NAMESPACE = 0x00100100; const int CHUNK_XML_START_TAG = 0x00100102; const int CHUNK_XML_TEXT = 0x00100104; const int UTF8_FLAG = 0x00000100; Vector<String> string_table; uint32_t ofs=0; uint32_t header = decode_uint32(&p_manifest[ofs]); uint32_t filesize = decode_uint32(&p_manifest[ofs+4]); ofs+=8; // print_line("FILESIZE: "+itos(filesize)+" ACTUAL: "+itos(p_manifest.size())); uint32_t string_count; uint32_t styles_count; uint32_t string_flags; uint32_t string_data_offset; uint32_t styles_offset; uint32_t string_table_begins; uint32_t string_table_ends; Vector<uint8_t> stable_extra; while(ofs < p_manifest.size()) { uint32_t chunk = decode_uint32(&p_manifest[ofs]); uint32_t size = decode_uint32(&p_manifest[ofs+4]); switch(chunk) { case CHUNK_STRINGS: { int iofs=ofs+8; string_count=decode_uint32(&p_manifest[iofs]); styles_count=decode_uint32(&p_manifest[iofs+4]); uint32_t string_flags=decode_uint32(&p_manifest[iofs+8]); string_data_offset=decode_uint32(&p_manifest[iofs+12]); styles_offset=decode_uint32(&p_manifest[iofs+16]); /* printf("string count: %i\n",string_count); printf("flags: %i\n",string_flags); printf("sdata ofs: %i\n",string_data_offset); printf("styles ofs: %i\n",styles_offset); */ uint32_t st_offset=iofs+20; string_table.resize(string_count); uint32_t string_end=0; string_table_begins=st_offset; for(int i=0;i<string_count;i++) { uint32_t string_at = decode_uint32(&p_manifest[st_offset+i*4]); string_at+=st_offset+string_count*4; ERR_EXPLAIN("Unimplemented, can't read utf8 string table."); ERR_FAIL_COND(string_flags&UTF8_FLAG); if (string_flags&UTF8_FLAG) { } else { uint32_t len = decode_uint16(&p_manifest[string_at]); Vector<CharType> ucstring; ucstring.resize(len+1); for(int j=0;j<len;j++) { uint16_t c=decode_uint16(&p_manifest[string_at+2+2*j]); ucstring[j]=c; } string_end=MAX(string_at+2+2*len,string_end); ucstring[len]=0; string_table[i]=ucstring.ptr(); } // print_line("String "+itos(i)+": "+string_table[i]); } for(int i=string_end;i<(ofs+size);i++) { stable_extra.push_back(p_manifest[i]); } // printf("stable extra: %i\n",int(stable_extra.size())); string_table_ends=ofs+size; // print_line("STABLE SIZE: "+itos(size)+" ACTUAL: "+itos(string_table_ends)); } break; case CHUNK_XML_START_TAG: { int iofs=ofs+8; uint32_t line=decode_uint32(&p_manifest[iofs]); uint32_t nspace=decode_uint32(&p_manifest[iofs+8]); uint32_t name=decode_uint32(&p_manifest[iofs+12]); uint32_t check=decode_uint32(&p_manifest[iofs+16]); String tname=string_table[name]; // printf("NSPACE: %i\n",nspace); //printf("NAME: %i (%s)\n",name,tname.utf8().get_data()); //printf("CHECK: %x\n",check); uint32_t attrcount=decode_uint32(&p_manifest[iofs+20]); iofs+=28; //printf("ATTRCOUNT: %x\n",attrcount); for(int i=0;i<attrcount;i++) { uint32_t attr_nspace=decode_uint32(&p_manifest[iofs]); uint32_t attr_name=decode_uint32(&p_manifest[iofs+4]); uint32_t attr_value=decode_uint32(&p_manifest[iofs+8]); uint32_t attr_flags=decode_uint32(&p_manifest[iofs+12]); uint32_t attr_resid=decode_uint32(&p_manifest[iofs+16]); String value; if (attr_value!=0xFFFFFFFF) value=string_table[attr_value]; else value="Res #"+itos(attr_resid); String attrname = string_table[attr_name]; String nspace; if (attr_nspace!=0xFFFFFFFF) nspace=string_table[attr_nspace]; else nspace=""; printf("ATTR %i NSPACE: %i\n",i,attr_nspace); printf("ATTR %i NAME: %i (%s)\n",i,attr_name,attrname.utf8().get_data()); printf("ATTR %i VALUE: %i (%s)\n",i,attr_value,value.utf8().get_data()); printf("ATTR %i FLAGS: %x\n",i,attr_flags); printf("ATTR %i RESID: %x\n",i,attr_resid); //replace project information if (tname=="manifest" && attrname=="package") { print_line("FOUND PACKAGE"); string_table[attr_value]=get_package_name(); } //print_line("tname: "+tname); //print_line("nspace: "+nspace); //print_line("attrname: "+attrname); if (tname=="manifest" && /*nspace=="android" &&*/ attrname=="versionCode") { print_line("FOUND versioncode"); encode_uint32(version_code,&p_manifest[iofs+16]); } if (tname=="manifest" && /*nspace=="android" &&*/ attrname=="versionName") { print_line("FOUND versionname"); if (attr_value==0xFFFFFFFF) { WARN_PRINT("Version name in a resource, should be plaintext") } else string_table[attr_value]=version_name; } if (tname=="activity" && /*nspace=="android" &&*/ attrname=="screenOrientation") { encode_uint32(orientation==0?0:1,&p_manifest[iofs+16]); /* print_line("FOUND screen orientation"); if (attr_value==0xFFFFFFFF) { WARN_PRINT("Version name in a resource, should be plaintext") } else { string_table[attr_value]=(orientation==0?"landscape":"portrait"); }*/ } if (tname=="application" && /*nspace=="android" &&*/ attrname=="label") { print_line("FOUND application"); if (attr_value==0xFFFFFFFF) { WARN_PRINT("Application name in a resource, should be plaintext (but you can ignore this).") } else { String aname = get_project_name(); string_table[attr_value]=aname; } } if (tname=="activity" && /*nspace=="android" &&*/ attrname=="label") { print_line("FOUND activity name"); if (attr_value==0xFFFFFFFF) { WARN_PRINT("Activity name in a resource, should be plaintext (but you can ignore this)") } else { String aname; if (this->name!="") { aname=this->name; } else { aname = Globals::get_singleton()->get("application/name"); } if (aname=="") { aname=_MKSTR(VERSION_NAME); } print_line("APP NAME IS..."+aname); string_table[attr_value]=aname; } } if (tname=="uses-permission" && /*nspace=="android" &&*/ attrname=="name") { if (value.begins_with("godot.custom")) { int which = value.get_slice(".",2).to_int(); if (which>=0 && which<MAX_USER_PERMISSIONS && user_perms[which].strip_edges()!="") { string_table[attr_value]=user_perms[which].strip_edges(); } } else if (value.begins_with("godot.")) { String perm = value.get_slice(".",1); print_line("PERM: "+perm+" HAS: "+itos(perms.has(perm))); if (perms.has(perm) || (p_give_internet && perm=="INTERNET")) { string_table[attr_value]="android.permission."+perm; } } } if (tname=="supports-screens" ) { if (attr_value==0xFFFFFFFF) { WARN_PRINT("Screen res name in a resource, should be plaintext") } else if (attrname=="smallScreens") { encode_uint32(screen_support[SCREEN_SMALL]?0xFFFFFFFF:0,&p_manifest[iofs+16]); } else if (attrname=="mediumScreens") { encode_uint32(screen_support[SCREEN_NORMAL]?0xFFFFFFFF:0,&p_manifest[iofs+16]); } else if (attrname=="largeScreens") { encode_uint32(screen_support[SCREEN_LARGE]?0xFFFFFFFF:0,&p_manifest[iofs+16]); } else if (attrname=="xlargeScreens") { encode_uint32(screen_support[SCREEN_XLARGE]?0xFFFFFFFF:0,&p_manifest[iofs+16]); } } iofs+=20; } } break; } printf("chunk %x: size: %d\n",chunk,size); ofs+=size; } printf("end\n"); //create new andriodmanifest binary Vector<uint8_t> ret; ret.resize(string_table_begins+string_table.size()*4); for(int i=0;i<string_table_begins;i++) { ret[i]=p_manifest[i]; } ofs=0; for(int i=0;i<string_table.size();i++) { encode_uint32(ofs,&ret[string_table_begins+i*4]); ofs+=string_table[i].length()*2+2+2; print_line("ofs: "+itos(i)+": "+itos(ofs)); } ret.resize(ret.size()+ofs); uint8_t *chars=&ret[ret.size()-ofs]; for(int i=0;i<string_table.size();i++) { String s = string_table[i]; print_line("savint string :"+s); encode_uint16(s.length(),chars); chars+=2; for(int j=0;j<s.length();j++) { //include zero? encode_uint16(s[j],chars); chars+=2; } encode_uint16(0,chars); chars+=2; } ret.resize(ret.size()+stable_extra.size()); while(ret.size()%4) ret.push_back(0); for(int i=0;i<stable_extra.size();i++) { chars[i]=stable_extra[i]; } uint32_t new_stable_end=ret.size(); uint32_t extra = (p_manifest.size()-string_table_ends); ret.resize(new_stable_end + extra); for(int i=0;i<extra;i++) ret[new_stable_end+i]=p_manifest[string_table_ends+i]; while(ret.size()%4) ret.push_back(0); encode_uint32(ret.size(),&ret[4]); //update new file size encode_uint32(new_stable_end-8,&ret[12]); //update new string table size print_line("file size: "+itos(ret.size())); p_manifest=ret; #if 0 uint32_t header[9]; for(int i=0;i<9;i++) { header[i]=decode_uint32(&p_manifest[i*4]); } print_line("STO: "+itos(header[3])); uint32_t st_offset=9*4; //ERR_FAIL_COND(header[3]!=0x24) uint32_t string_count=header[4]; string_table.resize(string_count); for(int i=0;i<string_count;i++) { uint32_t string_at = decode_uint32(&p_manifest[st_offset+i*4]); string_at+=st_offset+string_count*4; uint32_t len = decode_uint16(&p_manifest[string_at]); Vector<CharType> ucstring; ucstring.resize(len+1); for(int j=0;j<len;j++) { uint16_t c=decode_uint16(&p_manifest[string_at+2+2*j]); ucstring[j]=c; } ucstring[len]=0; string_table[i]=ucstring.ptr(); } #endif } Error EditorExportPlatformAndroid::save_apk_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total) { APKExportData *ed=(APKExportData*)p_userdata; String dst_path=p_path; dst_path=dst_path.replace_first("res://","assets/"); zipOpenNewFileInZip(ed->apk, dst_path.utf8().get_data(), NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION); zipWriteInFileInZip(ed->apk,p_data.ptr(),p_data.size()); zipCloseFileInZip(ed->apk); ed->ep->step("File: "+p_path,3+p_file*100/p_total); return OK; } Error EditorExportPlatformAndroid::export_project(const String& p_path, bool p_debug, int p_flags) { String src_apk; EditorProgress ep("export","Exporting for Android",104); if (p_debug) src_apk=custom_debug_package; else src_apk=custom_release_package; if (src_apk=="") { String err; if (p_debug) { src_apk=find_export_template("android_debug.apk", &err); } else { src_apk=find_export_template("android_release.apk", &err); } if (src_apk=="") { EditorNode::add_io_error(err); return ERR_FILE_NOT_FOUND; } } FileAccess *src_f=NULL; zlib_filefunc_def io = zipio_create_io_from_file(&src_f); ep.step("Creating APK",0); unzFile pkg = unzOpen2(src_apk.utf8().get_data(), &io); if (!pkg) { EditorNode::add_io_error("Could not find template APK to export:\n"+src_apk); return ERR_FILE_NOT_FOUND; } ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN); int ret = unzGoToFirstFile(pkg); zlib_filefunc_def io2=io; FileAccess *dst_f=NULL; io2.opaque=&dst_f; zipFile apk=zipOpen2(p_path.utf8().get_data(),APPEND_STATUS_CREATE,NULL,&io2); while(ret==UNZ_OK) { //get filename unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0); bool skip=false; String file=fname; Vector<uint8_t> data; data.resize(info.uncompressed_size); //read unzOpenCurrentFile(pkg); unzReadCurrentFile(pkg,data.ptr(),data.size()); unzCloseCurrentFile(pkg); //write if (file=="AndroidManifest.xml") { _fix_manifest(data,p_flags&(EXPORT_DUMB_CLIENT|EXPORT_REMOTE_DEBUG)); } if (file=="resources.arsc") { _fix_resources(data); } if (file=="res/drawable/icon.png") { bool found=false; if (this->icon!="" && this->icon.ends_with(".png")) { FileAccess *f = FileAccess::open(this->icon,FileAccess::READ); if (f) { data.resize(f->get_len()); f->get_buffer(data.ptr(),data.size()); memdelete(f); found=true; } } if (!found) { String appicon = Globals::get_singleton()->get("application/icon"); if (appicon!="" && appicon.ends_with(".png")) { FileAccess*f = FileAccess::open(appicon,FileAccess::READ); if (f) { data.resize(f->get_len()); f->get_buffer(data.ptr(),data.size()); memdelete(f); } } } } if (file=="lib/x86/libgodot_android.so" && !export_x86) { skip=true; } if (file=="lib/armeabi/libgodot_android.so" && !export_arm) { skip=true; } if (file.begins_with("META-INF") && _signed) { skip=true; } print_line("ADDING: "+file); if (!skip) { zipOpenNewFileInZip(apk, file.utf8().get_data(), NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION); zipWriteInFileInZip(apk,data.ptr(),data.size()); zipCloseFileInZip(apk); } ret = unzGoToNextFile(pkg); } ep.step("Adding Files..",1); Error err=OK; Vector<String> cl = cmdline.strip_edges().split(" "); for(int i=0;i<cl.size();i++) { if (cl[i].strip_edges().length()==0) { cl.remove(i); i--; } } gen_export_flags(cl,p_flags); if (p_flags&EXPORT_DUMB_CLIENT) { /*String host = EditorSettings::get_singleton()->get("file_server/host"); int port = EditorSettings::get_singleton()->get("file_server/post"); String passwd = EditorSettings::get_singleton()->get("file_server/password"); cl.push_back("-rfs"); cl.push_back(host+":"+itos(port)); if (passwd!="") { cl.push_back("-rfs_pass"); cl.push_back(passwd); }*/ } else { //all files if (apk_expansion) { String apkfname="main."+itos(version_code)+"."+get_package_name()+".obb"; String fullpath=p_path.get_base_dir().plus_file(apkfname); FileAccess *pf = FileAccess::open(fullpath,FileAccess::WRITE); if (!pf) { EditorNode::add_io_error("Could not write expansion package file: "+apkfname); return OK; } err = save_pack(pf); memdelete(pf); cl.push_back("-use_apk_expansion"); cl.push_back("-apk_expansion_md5"); cl.push_back(FileAccess::get_md5(fullpath)); cl.push_back("-apk_expansion_key"); cl.push_back(apk_expansion_pkey.strip_edges()); } else { APKExportData ed; ed.ep=&ep; ed.apk=apk; err = export_project_files(save_apk_file,&ed,false); } } if (use_32_fb) cl.push_back("-use_depth_32"); if (immersive) cl.push_back("-use_immersive"); if (cl.size()) { //add comandline Vector<uint8_t> clf; clf.resize(4); encode_uint32(cl.size(),&clf[0]); for(int i=0;i<cl.size();i++) { CharString txt = cl[i].utf8(); int base = clf.size(); clf.resize(base+4+txt.length()); encode_uint32(txt.length(),&clf[base]); copymem(&clf[base+4],txt.ptr(),txt.length()); print_line(itos(i)+" param: "+cl[i]); } zipOpenNewFileInZip(apk, "assets/_cl_", NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION); zipWriteInFileInZip(apk,clf.ptr(),clf.size()); zipCloseFileInZip(apk); } zipClose(apk,NULL); unzClose(pkg); if (err) { return err; } if (_signed) { String jarsigner=EditorSettings::get_singleton()->get("android/jarsigner"); if (!FileAccess::exists(jarsigner)) { EditorNode::add_io_error("'jarsigner' could not be found.\nPlease supply a path in the editor settings.\nResulting apk is unsigned."); return OK; } String keystore; String password; String user; if (p_debug) { keystore=EditorSettings::get_singleton()->get("android/debug_keystore"); password=EditorSettings::get_singleton()->get("android/debug_keystore_pass"); user=EditorSettings::get_singleton()->get("android/debug_keystore_user"); ep.step("Signing Debug APK..",103); } else { keystore=release_keystore; password=release_password; user=release_username; ep.step("Signing Release APK..",103); } if (!FileAccess::exists(keystore)) { EditorNode::add_io_error("Could not find keystore, unable to export."); return ERR_FILE_CANT_OPEN; } List<String> args; args.push_back("-digestalg"); args.push_back("SHA1"); args.push_back("-sigalg"); args.push_back("MD5withRSA"); String tsa_url=EditorSettings::get_singleton()->get("android/timestamping_authority_url"); if (tsa_url != "") { args.push_back("-tsa"); args.push_back(tsa_url); } args.push_back("-verbose"); args.push_back("-keystore"); args.push_back(keystore); args.push_back("-storepass"); args.push_back(password); args.push_back(p_path); args.push_back(user); int retval; int err = OS::get_singleton()->execute(jarsigner,args,true,NULL,NULL,&retval); if (retval) { EditorNode::add_io_error("'jarsigner' returned with error #"+itos(retval)); return ERR_CANT_CREATE; } ep.step("Verifying APK..",104); args.clear(); args.push_back("-verify"); args.push_back(p_path); args.push_back("-verbose"); err = OS::get_singleton()->execute(jarsigner,args,true,NULL,NULL,&retval); if (retval) { EditorNode::add_io_error("'jarsigner' verificaiton of APK failed. Make sure to use jarsigner from Java 6."); return ERR_CANT_CREATE; } } return OK; } bool EditorExportPlatformAndroid::poll_devices() { bool dc=devices_changed; devices_changed=false; return dc; } int EditorExportPlatformAndroid::get_device_count() const { device_lock->lock(); int dc=devices.size(); device_lock->unlock(); return dc; } String EditorExportPlatformAndroid::get_device_name(int p_device) const { ERR_FAIL_INDEX_V(p_device,devices.size(),""); device_lock->lock(); String s=devices[p_device].name; device_lock->unlock(); return s; } String EditorExportPlatformAndroid::get_device_info(int p_device) const { ERR_FAIL_INDEX_V(p_device,devices.size(),""); device_lock->lock(); String s=devices[p_device].description; device_lock->unlock(); return s; } void EditorExportPlatformAndroid::_device_poll_thread(void *ud) { EditorExportPlatformAndroid *ea=(EditorExportPlatformAndroid *)ud; while(!ea->quit_request) { String adb=EditorSettings::get_singleton()->get("android/adb"); if (!FileAccess::exists(adb)) { OS::get_singleton()->delay_usec(3000000); continue; //adb not configured } String devices; List<String> args; args.push_back("devices"); int ec; Error err = OS::get_singleton()->execute(adb,args,true,NULL,&devices,&ec); Vector<String> ds = devices.split("\n"); Vector<String> ldevices; for(int i=1;i<ds.size();i++) { String d = ds[i]; int dpos = d.find("device"); if (dpos==-1) continue; d=d.substr(0,dpos).strip_edges(); // print_line("found devuce: "+d); ldevices.push_back(d); } ea->device_lock->lock(); bool different=false; if (devices.size()!=ldevices.size()) { different=true; } else { for(int i=0;i<ea->devices.size();i++) { if (ea->devices[i].id!=ldevices[i]) { different=true; break; } } } if (different) { Vector<Device> ndevices; for(int i=0;i<ldevices.size();i++) { Device d; d.id=ldevices[i]; for(int j=0;j<ea->devices.size();j++) { if (ea->devices[j].id==ldevices[i]) { d.description=ea->devices[j].description; d.name=ea->devices[j].name; } } if (d.description=="") { //in the oven, request! args.clear(); args.push_back("-s"); args.push_back(d.id); args.push_back("shell"); args.push_back("cat"); args.push_back("/system/build.prop"); int ec; String dp; Error err = OS::get_singleton()->execute(adb,args,true,NULL,&dp,&ec); print_line("RV: "+itos(ec)); Vector<String> props = dp.split("\n"); String vendor; String device; d.description+"Device ID: "+d.id+"\n"; for(int j=0;j<props.size();j++) { String p = props[j]; if (p.begins_with("ro.product.model=")) { device=p.get_slice("=",1).strip_edges(); } else if (p.begins_with("ro.product.brand=")) { vendor=p.get_slice("=",1).strip_edges().capitalize(); } else if (p.begins_with("ro.build.display.id=")) { d.description+="Build: "+p.get_slice("=",1).strip_edges()+"\n"; } else if (p.begins_with("ro.build.version.release=")) { d.description+="Release: "+p.get_slice("=",1).strip_edges()+"\n"; } else if (p.begins_with("ro.product.cpu.abi=")) { d.description+="CPU: "+p.get_slice("=",1).strip_edges()+"\n"; } else if (p.begins_with("ro.product.manufacturer=")) { d.description+="Manufacturer: "+p.get_slice("=",1).strip_edges()+"\n"; } else if (p.begins_with("ro.board.platform=")) { d.description+="Chipset: "+p.get_slice("=",1).strip_edges()+"\n"; } else if (p.begins_with("ro.opengles.version=")) { uint32_t opengl = p.get_slice("=",1).to_int(); d.description+="OpenGL: "+itos(opengl>>16)+"."+itos((opengl>>8)&0xFF)+"."+itos((opengl)&0xFF)+"\n"; } } d.name=vendor+" "+device; // print_line("name: "+d.name); // print_line("description: "+d.description); } ndevices.push_back(d); } ea->devices=ndevices; ea->devices_changed=true; } ea->device_lock->unlock(); OS::get_singleton()->delay_usec(3000000); } if (EditorSettings::get_singleton()->get("android/shutdown_adb_on_exit")) { String adb=EditorSettings::get_singleton()->get("android/adb"); if (!FileAccess::exists(adb)) { return; //adb not configured } List<String> args; args.push_back("kill-server"); OS::get_singleton()->execute(adb,args,true); }; } Error EditorExportPlatformAndroid::run(int p_device, int p_flags) { ERR_FAIL_INDEX_V(p_device,devices.size(),ERR_INVALID_PARAMETER); device_lock->lock(); EditorProgress ep("run","Running on "+devices[p_device].name,3); String adb=EditorSettings::get_singleton()->get("android/adb"); if (adb=="") { EditorNode::add_io_error("ADB executable not configured in settings, can't run."); device_lock->unlock(); return ERR_UNCONFIGURED; } //export_temp ep.step("Exporting APK",0); bool use_adb_over_usb = bool(EDITOR_DEF("android/use_remote_debug_over_adb",true)); if (use_adb_over_usb) { p_flags|=EXPORT_REMOTE_DEBUG_LOCALHOST; } String export_to=EditorSettings::get_singleton()->get_settings_path()+"/tmp/tmpexport.apk"; Error err = export_project(export_to,true,p_flags); if (err) { device_lock->unlock(); return err; } List<String> args; int rv; if (remove_prev) { ep.step("Uninstalling..",1); print_line("Uninstalling previous version: "+devices[p_device].name); args.push_back("-s"); args.push_back(devices[p_device].id); args.push_back("uninstall"); args.push_back(get_package_name()); err = OS::get_singleton()->execute(adb,args,true,NULL,NULL,&rv); #if 0 if (err || rv!=0) { EditorNode::add_io_error("Could not install to device."); device_lock->unlock(); return ERR_CANT_CREATE; } #endif } print_line("Installing into device (please wait..): "+devices[p_device].name); ep.step("Installing to Device (please wait..)..",2); args.clear(); args.push_back("-s"); args.push_back(devices[p_device].id); args.push_back("install"); args.push_back("-r"); args.push_back(export_to); err = OS::get_singleton()->execute(adb,args,true,NULL,NULL,&rv); if (err || rv!=0) { EditorNode::add_io_error("Could not install to device."); device_lock->unlock(); return ERR_CANT_CREATE; } if (use_adb_over_usb) { args.clear(); args.push_back("reverse"); args.push_back("--remove-all"); err = OS::get_singleton()->execute(adb,args,true,NULL,NULL,&rv); int port = Globals::get_singleton()->get("debug/debug_port"); args.clear(); args.push_back("reverse"); args.push_back("tcp:"+itos(port)); args.push_back("tcp:"+itos(port)); err = OS::get_singleton()->execute(adb,args,true,NULL,NULL,&rv); print_line("Reverse result: "+itos(rv)); int fs_port = EditorSettings::get_singleton()->get("file_server/port"); args.clear(); args.push_back("reverse"); args.push_back("tcp:"+itos(fs_port)); args.push_back("tcp:"+itos(fs_port)); err = OS::get_singleton()->execute(adb,args,true,NULL,NULL,&rv); print_line("Reverse result2: "+itos(rv)); } ep.step("Running on Device..",3); args.clear(); args.push_back("-s"); args.push_back(devices[p_device].id); args.push_back("shell"); args.push_back("am"); args.push_back("start"); args.push_back("-a"); args.push_back("android.intent.action.MAIN"); args.push_back("-n"); args.push_back(get_package_name()+"/org.godotengine.godot.Godot"); err = OS::get_singleton()->execute(adb,args,true,NULL,NULL,&rv); if (err || rv!=0) { EditorNode::add_io_error("Could not execute ondevice."); device_lock->unlock(); return ERR_CANT_CREATE; } device_lock->unlock(); return OK; } String EditorExportPlatformAndroid::get_package_name() { String pname = package; String basename = Globals::get_singleton()->get("application/name"); basename=basename.to_lower(); String name; bool first=true; for(int i=0;i<basename.length();i++) { CharType c = basename[i]; if (c>='0' && c<='9' && first) { continue; } if ((c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9')) { name+=String::chr(c); first=false; } } if (name=="") name="noname"; pname=pname.replace("$genname",name); return pname; } EditorExportPlatformAndroid::EditorExportPlatformAndroid() { version_code=1; version_name="1.0"; package="org.godotengine.$genname"; name=""; _signed=true; apk_expansion=false; device_lock = Mutex::create(); quit_request=false; orientation=0; remove_prev=true; use_32_fb=true; immersive=true; export_arm=true; export_x86=false; device_thread=Thread::create(_device_poll_thread,this); devices_changed=true; Image img( _android_logo ); logo = Ref<ImageTexture>( memnew( ImageTexture )); logo->create_from_image(img); for(int i=0;i<4;i++) screen_support[i]=true; } bool EditorExportPlatformAndroid::can_export(String *r_error) const { bool valid=true; String adb=EditorSettings::get_singleton()->get("android/adb"); String err; if (!FileAccess::exists(adb)) { valid=false; err+="ADB executable not configured in editor settings.\n"; } String js = EditorSettings::get_singleton()->get("android/jarsigner"); if (!FileAccess::exists(js)) { valid=false; err+="OpenJDK 6 jarsigner not configured in editor settings.\n"; } String dk = EditorSettings::get_singleton()->get("android/debug_keystore"); if (!FileAccess::exists(dk)) { valid=false; err+="Debug Keystore not configured in editor settings.\n"; } if (!exists_export_template("android_debug.apk") || !exists_export_template("android_release.apk")) { valid=false; err+="No export templates found.\nDownload and install export templates.\n"; } if (custom_debug_package!="" && !FileAccess::exists(custom_debug_package)) { valid=false; err+="Custom debug package not found.\n"; } if (custom_release_package!="" && !FileAccess::exists(custom_release_package)) { valid=false; err+="Custom release package not found.\n"; } if (apk_expansion) { //if (apk_expansion_salt=="") { // valid=false; // err+="Invalid SALT for apk expansion.\n"; //} if (apk_expansion_pkey=="") { valid=false; err+="Invalid public key for apk expansion.\n"; } } if (r_error) *r_error=err; return valid; } EditorExportPlatformAndroid::~EditorExportPlatformAndroid() { quit_request=true; Thread::wait_to_finish(device_thread); memdelete(device_lock); memdelete(device_thread); } void register_android_exporter() { String exe_ext=OS::get_singleton()->get_name()=="Windows"?"exe":""; EDITOR_DEF("android/adb",""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING,"android/adb",PROPERTY_HINT_GLOBAL_FILE,exe_ext)); EDITOR_DEF("android/jarsigner",""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING,"android/jarsigner",PROPERTY_HINT_GLOBAL_FILE,exe_ext)); EDITOR_DEF("android/debug_keystore",""); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING,"android/debug_keystore",PROPERTY_HINT_GLOBAL_FILE,"keystore")); EDITOR_DEF("android/debug_keystore_user","androiddebugkey"); EDITOR_DEF("android/debug_keystore_pass","android"); //EDITOR_DEF("android/release_keystore",""); //EDITOR_DEF("android/release_username",""); //EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING,"android/release_keystore",PROPERTY_HINT_GLOBAL_FILE,"*.keystore")); EDITOR_DEF("android/timestamping_authority_url",""); EDITOR_DEF("android/use_remote_debug_over_adb",false); EDITOR_DEF("android/shutdown_adb_on_exit",true); Ref<EditorExportPlatformAndroid> exporter = Ref<EditorExportPlatformAndroid>( memnew(EditorExportPlatformAndroid) ); EditorImportExport::get_singleton()->add_export_platform(exporter); }
{ "content_hash": "877a9c004f486ad93e8c0033b22abb58", "timestamp": "", "source": "github", "line_count": 1782, "max_line_length": 151, "avg_line_length": 25.496071829405164, "alnum_prop": 0.6577893207729893, "repo_name": "OpenSocialGames/godot", "id": "60f4e61c68d8bab6ed0cbaee16acb088fa65beb4", "size": "45434", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "platform/android/export/export.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "6955" }, { "name": "Assembly", "bytes": "372477" }, { "name": "Batchfile", "bytes": "2356" }, { "name": "C", "bytes": "25772308" }, { "name": "C++", "bytes": "12155113" }, { "name": "DIGITAL Command Language", "bytes": "95419" }, { "name": "GAP", "bytes": "3659" }, { "name": "GDScript", "bytes": "83943" }, { "name": "GLSL", "bytes": "57049" }, { "name": "HTML", "bytes": "9365" }, { "name": "Java", "bytes": "439345" }, { "name": "JavaScript", "bytes": "5802" }, { "name": "Matlab", "bytes": "2076" }, { "name": "Objective-C", "bytes": "43300" }, { "name": "Objective-C++", "bytes": "143724" }, { "name": "PHP", "bytes": "1095905" }, { "name": "Perl", "bytes": "1939071" }, { "name": "Python", "bytes": "128381" }, { "name": "Shell", "bytes": "1054" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "3710" } ], "symlink_target": "" }
package com.cs350.iyy; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
{ "content_hash": "64e7c54a9aba931cfacefb0392fce9c5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 93, "avg_line_length": 26.46153846153846, "alnum_prop": 0.7441860465116279, "repo_name": "wjw0926/IYY", "id": "7c36f073f4faa676d41d7efd5af292ab2f11e9dd", "size": "344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/androidTest/java/com/cs350/iyy/ApplicationTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "49459" }, { "name": "PHP", "bytes": "1963" } ], "symlink_target": "" }
[![NeuralTalk Day walk with Voice](http://img.youtube.com/vi/l8PVcKT6PtQ/0.jpg)](http://www.youtube.com/watch?v=l8PVcKT6PtQ) ### NeuralTalk Night Walk With Voice [![NeuralTalk Night Walk With Voice](http://img.youtube.com/vi/-696q1Sg48Q/0.jpg)](http://www.youtube.com/watch?v=-696q1Sg48Q) [`openFrameworks`][1], addon for IP Cameras using [Neuralktalk2][2] for automatic captioning. This is using the [`ofxIpVideoGrabber`][3] addon's example code. We've just modified it to read captions from neuraltalk2 and display it. If you haven't seen this [video][4] already, go check it out. It demenonstrates how deep learning can be used for automatic captioning based on what the webcam sees. What we've done here is, instead of using a webcam attached directly to the computer, we're feeding neuraltalk2 with feeds from an IP camera. In addition to that we've added text to speech so it reads what the camera sees as well. Useful for a blind person interested in hearing what the camera sees. This is a hack my friend and I worked on after seeing the original video demo of what neuraltalk2 can do. We also modified neuraltalk2's `eval.lua`[5] script and so it's possible to read the image feed from the IP camera. # Dependencies 1. Neuraltalk2 [2] 2. Our modified version of `eval.lua` [5] 3. `sudo apt-get install libttspico0 libttspico-utils libttspico-data` 4. Ubuntu 5. `voice.sh`[6] # Contributors [linuxkay](https://github.com/linuxkay) [1]: http://openframeworks.cc/ [2]: https://github.com/karpathy/neuraltalk2 [3]: https://github.com/bakercp/ofxIpVideoGrabber [3]: https://vimeo.com/146492001 [4]: https://github.com/karpathy/neuraltalk2/blob/master/eval.lua [5]: https://github.com/eyedol/ofxIPNeuraltalk2/blob/master/dependencies/eval.lua [6]: https://github.com/eyedol/ofxIPNeuraltalk2/blob/master/dependencies/voice.sh
{ "content_hash": "03d046de3b8c41fd62f250eed4bef0af", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 300, "avg_line_length": 52.542857142857144, "alnum_prop": 0.7656334964654704, "repo_name": "eyedol/ofxIPNeuraltalk2", "id": "75892cdd2cc26b342baa09db5913e7938482d32d", "size": "1895", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "13135" }, { "name": "Makefile", "bytes": "394" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-algebra-tactics: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.6 / mathcomp-algebra-tactics - 1.0.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-algebra-tactics <small> 1.0.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-21 00:31:44 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-21 00:31:44 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.6 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;sakaguchi@coins.tsukuba.ac.jp&quot; homepage: &quot;https://github.com/math-comp/algebra-tactics&quot; dev-repo: &quot;git+https://github.com/math-comp/algebra-tactics.git&quot; bug-reports: &quot;https://github.com/math-comp/algebra-tactics/issues&quot; license: &quot;CECILL-B&quot; synopsis: &quot;Ring and field tactics for Mathematical Components&quot; description: &quot;&quot;&quot; This library provides `ring` and `field` tactics for Mathematical Components, that work with any `comRingType` and `fieldType` instances, respectively. Their instance resolution is done through canonical structure inference. Therefore, they work with abstract rings and do not require `Add Ring` and `Add Field` commands. Another key feature of this library is that they automatically push down ring morphisms and additive functions to leaves of ring/field expressions before normalization to the Horner form.&quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot; ] install: [make &quot;install&quot;] depends: [ &quot;coq&quot; {(&gt;= &quot;8.13&quot; &amp; &lt; &quot;8.17~&quot;)} &quot;coq-mathcomp-ssreflect&quot; {(&gt;= &quot;1.12&quot; &amp; &lt; &quot;1.16~&quot;)} &quot;coq-mathcomp-algebra&quot; &quot;coq-mathcomp-zify&quot; {(&gt;= &quot;1.1.0&quot;)} &quot;coq-elpi&quot; {(&gt;= &quot;1.10.1&quot;)} ] tags: [ &quot;logpath:mathcomp.algebra_tactics&quot; ] authors: [ &quot;Kazuhiko Sakaguchi&quot; ] url { src: &quot;https://github.com/math-comp/algebra-tactics/archive/refs/tags/1.0.0.tar.gz&quot; checksum: &quot;sha256=fa46588280364b64167398c1bdf4e0b20ca21c30f30213be5d12ea14c5242aad&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-algebra-tactics.1.0.0 coq.8.6</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.6). The following dependencies couldn&#39;t be met: - coq-mathcomp-algebra-tactics -&gt; coq-elpi &gt;= 1.10.1 -&gt; ocaml &gt;= 4.07 base of this switch (use `--unlock-base&#39; to force) - coq-mathcomp-algebra-tactics -&gt; coq-elpi &gt;= 1.10.1 -&gt; elpi &gt;= 1.13.5 -&gt; ocaml &gt;= 4.04.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-algebra-tactics.1.0.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "2b99ae60f905e4ac7e585dee8b7d1026", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 159, "avg_line_length": 43.651685393258425, "alnum_prop": 0.5625482625482625, "repo_name": "coq-bench/coq-bench.github.io", "id": "a18a82cf6b6832c9212a25cc41a960708733d95e", "size": "7795", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.6/mathcomp-algebra-tactics/1.0.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php require_once 'Media/Process/Generic.php'; require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/mocks/Media/Process/Adapter/GenericMock.php'; class Media_Process_GenericTest extends PHPUnit_Framework_TestCase { protected $_files; protected $_data; protected function setUp() { $this->_files = dirname(dirname(dirname(dirname(__FILE__)))) . '/data'; $this->_data = dirname(dirname(dirname(dirname(dirname(__FILE__))))) .'/data'; } public function testConstruct() { $result = new Media_Process_Generic(array( 'source' => "{$this->_files}/image_jpg.jpg", 'adapter' => new Media_Process_Adapter_GenericMock(null) )); $this->assertInternalType('object', $result); $result = new Media_Process_Generic(array( 'source' => fopen("{$this->_files}/image_jpg.jpg", 'rb'), 'adapter' => new Media_Process_Adapter_GenericMock(null) )); $this->assertInternalType('object', $result); $result = new Media_Process_Generic(array( 'source' => "{$this->_files}/image_jpg.jpg", 'adapter' => new Media_Process_Adapter_GenericMock('test') )); $this->assertInternalType('object', $result); $result = new Media_Process_Generic(array( 'adapter' => new Media_Process_Adapter_GenericMock('test') )); $this->assertInternalType('object', $result); } public function testConstructFailWithNoArgs() { $this->setExpectedException('InvalidArgumentException'); new Media_Process_Generic(array()); } public function testConstructFailWithSourceButNoAdapter() { $this->setExpectedException('InvalidArgumentException'); new Media_Process_Generic(array('source' => "{$this->_files}/image_jpg.jpg")); } public function testConstructFailWithStringAdapterButNoSource() { $this->setExpectedException('InvalidArgumentException'); new Media_Process_Generic(array('adapter' => 'Dummy')); } public function testName() { $result = new Media_Process_Generic(array( 'source' => "{$this->_files}/image_jpg.jpg", 'adapter' => new Media_Process_Adapter_GenericMock(null) )); $this->assertEquals($result->name(), 'generic'); } public function testStoreHonorsOverwrite() { $target = tempnam(sys_get_temp_dir(), 'mm_'); touch($target); $media = new Media_Process_Generic(array( 'source' => fopen('php://temp', 'rb'), 'adapter' => new Media_Process_Adapter_GenericMock(null) )); $result = $media->store($target); $this->assertFalse($result); $result = $media->store($target, array('overwrite' => true)); $this->assertFileExists($result); unlink($target); $result = $media->store($target); $this->assertFileExists($result); unlink($target); } public function testPassthru() { $result = new Media_Process_Generic(array( 'source' => "{$this->_files}/image_jpg.jpg", 'adapter' => new Media_Process_Adapter_GenericMock(null) )); $this->assertEquals($result->passthru('depth', 8), true); } } ?>
{ "content_hash": "06c3b3d6baa173292885da9f500f2321", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 107, "avg_line_length": 30.46315789473684, "alnum_prop": 0.6821008984105045, "repo_name": "djstearns/blabfeed-beta2", "id": "45374095f572cb135c9806af1ba5c5acc6f14a60", "size": "3286", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "plugins/media/libs/mm/tests/unit/Media/Process/GenericTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "47686" }, { "name": "JavaScript", "bytes": "6401213" }, { "name": "Logos", "bytes": "7766" }, { "name": "PHP", "bytes": "3756608" }, { "name": "Ruby", "bytes": "4505" } ], "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. #} Dear {{user_object.display_name}}, A new release of {{project.name}} is available now! Release Notes from project owner {{project_owner.display_name}} : {{remarks}} Please check out the release @ <{{base_url}}{{folder_object.url()}}> --- Sent from {{domain}} because you indicated interest in <{{ base_url }} > To unsubscribe from further messages, please visit <{{ base_url }}/auth/subscriptions/>
{ "content_hash": "dd5129e327cf980fc2e028933d575bc8", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 87, "avg_line_length": 37.26470588235294, "alnum_prop": 0.7032359905288083, "repo_name": "apache/allura", "id": "9466b5aa7bf31f963d5731df3a0bed10ae1af68c", "size": "1267", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ForgeFiles/forgefiles/templates/mail.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6142" }, { "name": "CSS", "bytes": "181457" }, { "name": "Dockerfile", "bytes": "4748" }, { "name": "HTML", "bytes": "867332" }, { "name": "JavaScript", "bytes": "1191836" }, { "name": "Makefile", "bytes": "6248" }, { "name": "Python", "bytes": "4499987" }, { "name": "RAML", "bytes": "27600" }, { "name": "Roff", "bytes": "41" }, { "name": "Ruby", "bytes": "1280" }, { "name": "SCSS", "bytes": "27742" }, { "name": "Shell", "bytes": "131207" }, { "name": "XSLT", "bytes": "3357" } ], "symlink_target": "" }
import {StructureViewModelNode} from "./structure-view-model-node"; import {StructureViewModelDependency} from "./structure-view-model-dependency"; export class StructureViewModel { root: StructureViewModelNode = null; dependencies: Array<StructureViewModelDependency> = []; feedbacks: Array<StructureViewModelDependency> = []; }
{ "content_hash": "fd6cda241688011a5caf2f7b9d7d0384", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 79, "avg_line_length": 38.22222222222222, "alnum_prop": 0.7732558139534884, "repo_name": "rfruesmer/module-structure", "id": "23fd0c3e6fb25cf8196069ce88f8c216cb1f8be5", "size": "344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/structure-view-model/structure-view-model.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "329" }, { "name": "HTML", "bytes": "218" }, { "name": "JavaScript", "bytes": "78472" }, { "name": "TypeScript", "bytes": "112075" } ], "symlink_target": "" }
// Creates an MPMoviePlayer and starts playing the sample movie. // // Uses MPMoviePlayer because iOS does not have an AVPlayerView, so using // the AV framework on iOS adds unrelated code to get an AVPlayer to show // up on the screen. #import <UIKit/UIKit.h> @interface ViewController : UIViewController - (void)incrementCounter; @end extern ViewController* g_view_controller;
{ "content_hash": "1a523eda0daffc37fd18dfb18bcd5d44", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 73, "avg_line_length": 27.357142857142858, "alnum_prop": 0.7702349869451697, "repo_name": "justsomeguy-google-com/UniversalDashTransmuxer", "id": "a674af181a746997cca61593463bccd95e5795f9", "size": "961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/battery_test/iOS/ViewController.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11913" }, { "name": "C++", "bytes": "338662" }, { "name": "Objective-C", "bytes": "14642" }, { "name": "Objective-C++", "bytes": "46717" }, { "name": "Python", "bytes": "6239" } ], "symlink_target": "" }