text
stringlengths
2
1.04M
meta
dict
package ch.jalu.injector.handlers.dependency; import ch.jalu.injector.context.ObjectIdentifier; import ch.jalu.injector.context.ResolutionContext; import ch.jalu.injector.exceptions.InjectorException; import ch.jalu.injector.handlers.instantiation.Resolution; import ch.jalu.injector.samples.Duration; import ch.jalu.injector.samples.Size; import org.junit.jupiter.api.Test; import java.lang.annotation.Annotation; import static ch.jalu.injector.InjectorTestHelper.newDurationAnnotation; import static ch.jalu.injector.InjectorTestHelper.newSizeAnnotation; import static ch.jalu.injector.InjectorTestHelper.unwrapFromSimpleResolution; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test for {@link SavedAnnotationsHandler}. */ class SavedAnnotationsHandlerTest { private SavedAnnotationsHandler savedAnnotationsHandler = new SavedAnnotationsHandler(); @Test void shouldReturnRegisteredValue() { // given Object object = "value for @Duration"; savedAnnotationsHandler.onAnnotation(Duration.class, object); Annotation[] annotations = { newSizeAnnotation("value"), newDurationAnnotation() }; ResolutionContext context = new ResolutionContext( null, new ObjectIdentifier(null, null, annotations)); // when // Injector param not needed -> null Resolution<?> instantiation = savedAnnotationsHandler.resolve(context); // then assertThat(unwrapFromSimpleResolution(instantiation), equalTo(object)); } @Test void shouldReturnNullForUnregisteredAnnotation() { // given Annotation[] annotations = { newSizeAnnotation("value"), newDurationAnnotation() }; ResolutionContext context = new ResolutionContext( null, new ObjectIdentifier(null, null, annotations)); // register some object under another annotation for the heck of it savedAnnotationsHandler.onAnnotation(Test.class, new Object()); // when Resolution<?> result = savedAnnotationsHandler.resolve(context); // then assertThat(result, nullValue()); } @Test void shouldThrowForSecondAnnotationRegistration() { // given savedAnnotationsHandler.onAnnotation(Size.class, 12); // when / then assertThrows(InjectorException.class, () -> savedAnnotationsHandler.onAnnotation(Size.class, -8)); } @Test void shouldThrowForNullValueAssociatedToAnnotation() { // given / when / then assertThrows(InjectorException.class, () -> savedAnnotationsHandler.onAnnotation(Duration.class, null)); } }
{ "content_hash": "273ec8f02cb41837b1feb87a199c44d2", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 92, "avg_line_length": 35.18518518518518, "alnum_prop": 0.7136842105263158, "repo_name": "ljacqu/DependencyInjector", "id": "9eb459b23d4a78527b7f631f5195f39e07980e68", "size": "2850", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "injector/src/test/java/ch/jalu/injector/handlers/dependency/SavedAnnotationsHandlerTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "313344" } ], "symlink_target": "" }
using System; using System.Linq; using System.Reflection; namespace Zirpl.FluentReflection.Queries { internal sealed class ScopeCriteria : MemberInfoCriteriaBase { private readonly Type _reflectedType; internal bool Instance { get; set; } internal bool Static { get; set; } internal bool DeclaredOnThisType { get; set; } internal bool DeclaredOnBaseTypes { get; set; } // TODO: implement including hiddenBySignature members, and exclude them otherwise internal ScopeCriteria(Type type) { _reflectedType = type; } protected override MemberInfo[] RunGetMatches(MemberInfo[] memberInfos) { return memberInfos.Where(IsMatch).ToArray(); } protected internal override bool ShouldRun { get { // we can skip checks if // 1) neither Type scope was chosen (in which case the default will be used) // 2) BOTH were chosen, but no depth // - STATIC vs INSTANCE is completely handled by the binding flags var canSkip = (!DeclaredOnThisType && !DeclaredOnBaseTypes) || (DeclaredOnThisType && DeclaredOnBaseTypes); return !canSkip; } } private bool IsMatch(MemberInfo memberInfo) { if (memberInfo is MethodBase) { var method = (MethodBase)memberInfo; if (!IsDeclaredTypeMatch(method)) return false; } else if (memberInfo is EventInfo) { var eventInfo = (EventInfo)memberInfo; var addMethod = eventInfo.GetAddMethod(true); var removeMethod = eventInfo.GetRemoveMethod(true); if (!IsDeclaredTypeMatch(addMethod) && !IsDeclaredTypeMatch(removeMethod)) return false; } else if (memberInfo is FieldInfo) { var field = (FieldInfo)memberInfo; if (!IsDeclaredTypeMatch(field)) return false; } else if (memberInfo is PropertyInfo) { var propertyinfo = (PropertyInfo)memberInfo; var getMethod = propertyinfo.GetGetMethod(true); var setMethod = propertyinfo.GetSetMethod(true); if (!IsDeclaredTypeMatch(getMethod) && !IsDeclaredTypeMatch(setMethod)) return false; } else if (memberInfo is Type) { // nested types var type = (Type)memberInfo; if (!IsDeclaredTypeMatch(memberInfo)) return false; } else { throw new Exception("Unexpected MemberInfo type: " + memberInfo.GetType().ToString()); } return true; } private bool IsDeclaredTypeMatch(MemberInfo memberInfo) { // no need for this check, since getting here means we need to check if (memberInfo.DeclaringType.Equals(_reflectedType) && !DeclaredOnThisType) return false; if (!memberInfo.DeclaringType.Equals(_reflectedType) && !DeclaredOnBaseTypes) return false; // if neither was chosen, then evaluate to true return true; } } }
{ "content_hash": "662828da4651ea636536f17df1e346e6", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 104, "avg_line_length": 38.31818181818182, "alnum_prop": 0.5667259786476868, "repo_name": "zirplsoftware/ZFluentReflection", "id": "20c37650f5f3341b6ce93eb532d0ebc0e1222e0a", "size": "3374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Zirpl.FluentReflection/Queries/Implementation/Criteria/ScopeCriteria.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "342639" } ], "symlink_target": "" }
%https://code.google.com/p/edulinq/source/browse/src/Edulinq.Tests/SkipTest.cs function test_suite = testLinqSkipWhile initTestSuite; %% function testEmptySource l = linq([]); f = @() l.skipWhile(@(x) x > 3); assertExceptionThrown(f,'linq:skip:InputValue') function testPredicateFailingFirstElement l = linq(1:10); result = l.skipWhile(@(x) x > 1); assertEqual(result.toArray,[1:10]); source = {'zero' 'one' 'two' 'three' 'four' 'five'}; result = l.place(source).skipWhile(@(x) length(x) < 4); assertEqual(result.toList,source); function testPredicateWithIndexFailingFirstElement l = linq(1:10); result = l.skipWhile(@(x,index) x > 1 + index); assertEqual(result.toArray,[1:10]); source = {'zero' 'one' 'two' 'three' 'four' 'five'}; result = l.place(source).skipWhile(@(x,index) index + length(x) < 4); assertEqual(result.toList,source); function testPredicateMatchingSomeElements l = linq(1:10); result = l.skipWhile(@(x) x < 5); assertEqual(result.toArray,[5:10]); source = {'zero' 'one' 'two' 'three' 'four' 'five'}; result = l.place(source).skipWhile(@(x) length(x) < 5); assertEqual(result.toList,source(4:end)); function testPredicateWithIndexMatchingSomeElements l = linq([0, 1, 1, 2, 3, 5, 8, 13, 21]); result = l.skipWhile(@(x,index) x <= index); assertEqual(result.toArray,[8, 13, 21]); source = {'zero' 'one' 'two' 'three' 'four' 'five'}; result = l.place(source).skipWhile(@(x,index) length(x) > index-1); assertEqual(result.toList,source(5:end)); function testPredicateMatchingAllElements l = linq(1:10); result = l.skipWhile(@(x) x < 10); assertEqual(result.toArray,[]); source = {'zero' 'one' 'two' 'three' 'four' 'five'}; result = l.place(source).skipWhile(@(x) length(x) < 50); assertEqual(result.toList,{}); function testPredicateWithIndexMatchingAllElements l = linq([0, 1, 1, 2, 3, 5, 8, 13, 21]); result = l.skipWhile(@(x,index) x <= index+100); assertEqual(result.toArray,[]); source = {'zero' 'one' 'two' 'three' 'four' 'five'}; result = l.place(source).skipWhile(@(x,index) length(x) > index-100); assertEqual(result.toList,{});
{ "content_hash": "64b12500cc7940c7bfe51d28ad4ea7a6", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 78, "avg_line_length": 31.815384615384616, "alnum_prop": 0.6876208897485493, "repo_name": "brian-lau/MatlabQuery", "id": "0226eade8febfc9ea966cdaf8ad78e525d16d2e0", "size": "2068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Testing/testLinqSkipWhile.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Matlab", "bytes": "72551" } ], "symlink_target": "" }
package org.gradle.test.performance.mediummonolithicjavaproject.p491; import org.junit.Test; import static org.junit.Assert.*; public class Test9823 { Production9823 objectUnderTest = new Production9823(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
{ "content_hash": "2a69c0471e93e83bedea0b3f2a027d0d", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 69, "avg_line_length": 26.72151898734177, "alnum_prop": 0.6447181430601611, "repo_name": "oehme/analysing-gradle-performance", "id": "675cf503a0f69df12bfec8ca72de882a11ae30b4", "size": "2111", "binary": false, "copies": "1", "ref": "refs/heads/before", "path": "my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p491/Test9823.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "40770723" } ], "symlink_target": "" }
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #ifndef MOAISTREAMWRITER_H #define MOAISTREAMWRITER_H #include <moaicore/MOAIStream.h> //================================================================// // MOAIStreamWriter //================================================================// /** @name MOAIStreamWriter @text MOAIStreamWriter may be attached to another stream for the purpose of encoding and/or compressing bytes written to that stream using a given algorithm (such as base64 or 'deflate'). */ class MOAIStreamWriter : public virtual MOAIStream { private: MOAILuaSharedPtr < MOAIStream > mStream; USStreamWriter* mWriter; //----------------------------------------------------------------// static int _close ( lua_State* L ); static int _openBase64 ( lua_State* L ); static int _openDeflate ( lua_State* L ); public: DECL_LUA_FACTORY ( MOAIStreamWriter ) //----------------------------------------------------------------// void Close (); MOAIStreamWriter (); ~MOAIStreamWriter (); bool Open ( MOAIStream* stream, USStreamWriter* writer ); void RegisterLuaClass ( MOAILuaState& state ); void RegisterLuaFuncs ( MOAILuaState& state ); }; #endif
{ "content_hash": "57b7d8dfb9367d7b9f6b3518a9ac6213", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 69, "avg_line_length": 30.452380952380953, "alnum_prop": 0.5543393275996873, "repo_name": "jjimenezg93/ai-state_machines", "id": "67db4c317d143be1d1c0599290ea3bbb94197c81", "size": "1279", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "moai/src/moaicore/MOAIStreamWriter.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2248" }, { "name": "C", "bytes": "129853" }, { "name": "C++", "bytes": "3183245" }, { "name": "Lua", "bytes": "42754" }, { "name": "Objective-C", "bytes": "62841" }, { "name": "Objective-C++", "bytes": "167701" }, { "name": "Shell", "bytes": "1271" } ], "symlink_target": "" }
package temptable import ( "context" "testing" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/store/mockstore" "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/mock" "github.com/stretchr/testify/require" ) func createTestSuite(t *testing.T) (sessionctx.Context, *temporaryTableDDL) { store, err := mockstore.NewMockStore() require.NoError(t, err) sctx := mock.NewContext() sctx.Store = store ddl := GetTemporaryTableDDL(sctx).(*temporaryTableDDL) t.Cleanup(func() { require.NoError(t, store.Close()) }) return sctx, ddl } func TestAddLocalTemporaryTable(t *testing.T) { sctx, ddl := createTestSuite(t) sessVars := sctx.GetSessionVars() db1 := newMockSchema("db1") db2 := newMockSchema("db2") tbl1 := newMockTable("t1") tbl2 := newMockTable("t2") require.Nil(t, sessVars.LocalTemporaryTables) require.Nil(t, sessVars.TemporaryTableData) // insert t1 err := ddl.CreateLocalTemporaryTable(db1, tbl1) require.NoError(t, err) require.NotNil(t, sessVars.LocalTemporaryTables) require.NotNil(t, sessVars.TemporaryTableData) require.Equal(t, int64(1), tbl1.ID) got, exists := sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1")) require.True(t, exists) require.Equal(t, got.Meta(), tbl1) // insert t2 with data err = ddl.CreateLocalTemporaryTable(db1, tbl2) require.NoError(t, err) require.Equal(t, int64(2), tbl2.ID) got, exists = sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t2")) require.True(t, exists) require.Equal(t, got.Meta(), tbl2) // should success to set a key for a table k := tablecodec.EncodeRowKeyWithHandle(tbl1.ID, kv.IntHandle(1)) err = sessVars.TemporaryTableData.SetTableKey(tbl1.ID, k, []byte("v1")) require.NoError(t, err) val, err := sessVars.TemporaryTableData.Get(context.Background(), k) require.NoError(t, err) require.Equal(t, []byte("v1"), val) // insert dup table tbl1x := newMockTable("t1") err = ddl.CreateLocalTemporaryTable(db1, tbl1x) require.True(t, infoschema.ErrTableExists.Equal(err)) got, exists = sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1")) require.True(t, exists) require.Equal(t, got.Meta(), tbl1) // insert should be success for same table name in different db err = ddl.CreateLocalTemporaryTable(db2, tbl1x) require.NoError(t, err) got, exists = sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db2"), model.NewCIStr("t1")) require.Equal(t, int64(4), got.Meta().ID) require.True(t, exists) require.Equal(t, got.Meta(), tbl1x) // tbl1 still exist got, exists = sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1")) require.True(t, exists) require.Equal(t, got.Meta(), tbl1) } func TestRemoveLocalTemporaryTable(t *testing.T) { sctx, ddl := createTestSuite(t) sessVars := sctx.GetSessionVars() db1 := newMockSchema("db1") // remove when empty err := ddl.DropLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1")) require.True(t, infoschema.ErrTableNotExists.Equal(err)) // add one table tbl1 := newMockTable("t1") err = ddl.CreateLocalTemporaryTable(db1, tbl1) require.NoError(t, err) require.Equal(t, int64(1), tbl1.ID) k := tablecodec.EncodeRowKeyWithHandle(1, kv.IntHandle(1)) err = sessVars.TemporaryTableData.SetTableKey(tbl1.ID, k, []byte("v1")) require.NoError(t, err) // remove failed when table not found err = ddl.DropLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t2")) require.True(t, infoschema.ErrTableNotExists.Equal(err)) // remove failed when table not found (same table name in different db) err = ddl.DropLocalTemporaryTable(model.NewCIStr("db2"), model.NewCIStr("t1")) require.True(t, infoschema.ErrTableNotExists.Equal(err)) // check failed remove should have no effects got, exists := sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByID(tbl1.ID) require.True(t, exists) require.Equal(t, got.Meta(), tbl1) val, err := sessVars.TemporaryTableData.Get(context.Background(), k) require.NoError(t, err) require.Equal(t, []byte("v1"), val) // remove success err = ddl.DropLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1")) require.NoError(t, err) got, exists = sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1")) require.Nil(t, got) require.False(t, exists) val, err = sessVars.TemporaryTableData.Get(context.Background(), k) require.NoError(t, err) require.Equal(t, []byte{}, val) } func TestTruncateLocalTemporaryTable(t *testing.T) { sctx, ddl := createTestSuite(t) sessVars := sctx.GetSessionVars() db1 := newMockSchema("db1") // truncate when empty err := ddl.TruncateLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1")) require.True(t, infoschema.ErrTableNotExists.Equal(err)) require.Nil(t, sessVars.LocalTemporaryTables) require.Nil(t, sessVars.TemporaryTableData) // add one table tbl1 := newMockTable("t1") err = ddl.CreateLocalTemporaryTable(db1, tbl1) require.Equal(t, int64(1), tbl1.ID) require.NoError(t, err) k := tablecodec.EncodeRowKeyWithHandle(1, kv.IntHandle(1)) err = sessVars.TemporaryTableData.SetTableKey(1, k, []byte("v1")) require.NoError(t, err) // truncate failed for table not exist err = ddl.TruncateLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t2")) require.True(t, infoschema.ErrTableNotExists.Equal(err)) err = ddl.TruncateLocalTemporaryTable(model.NewCIStr("db2"), model.NewCIStr("t1")) require.True(t, infoschema.ErrTableNotExists.Equal(err)) // check failed should have no effects got, exists := sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1")) require.True(t, exists) require.Equal(t, got.Meta(), tbl1) val, err := sessVars.TemporaryTableData.Get(context.Background(), k) require.NoError(t, err) require.Equal(t, []byte("v1"), val) // insert a new tbl tbl2 := newMockTable("t2") err = ddl.CreateLocalTemporaryTable(db1, tbl2) require.Equal(t, int64(2), tbl2.ID) require.NoError(t, err) k2 := tablecodec.EncodeRowKeyWithHandle(2, kv.IntHandle(1)) err = sessVars.TemporaryTableData.SetTableKey(2, k2, []byte("v2")) require.NoError(t, err) // truncate success err = ddl.TruncateLocalTemporaryTable(model.NewCIStr("db1"), model.NewCIStr("t1")) require.NoError(t, err) got, exists = sessVars.LocalTemporaryTables.(*infoschema.SessionTables).TableByName(model.NewCIStr("db1"), model.NewCIStr("t1")) require.True(t, exists) require.NotEqual(t, got.Meta(), tbl1) require.Equal(t, int64(3), got.Meta().ID) val, err = sessVars.TemporaryTableData.Get(context.Background(), k) require.NoError(t, err) require.Equal(t, []byte{}, val) // truncate just effect its own data val, err = sessVars.TemporaryTableData.Get(context.Background(), k2) require.NoError(t, err) require.Equal(t, []byte("v2"), val) } func newMockTable(tblName string) *model.TableInfo { c1 := &model.ColumnInfo{ID: 1, Name: model.NewCIStr("c1"), State: model.StatePublic, Offset: 0, FieldType: *types.NewFieldType(mysql.TypeLonglong)} c2 := &model.ColumnInfo{ID: 2, Name: model.NewCIStr("c2"), State: model.StatePublic, Offset: 1, FieldType: *types.NewFieldType(mysql.TypeVarchar)} tblInfo := &model.TableInfo{Name: model.NewCIStr(tblName), Columns: []*model.ColumnInfo{c1, c2}, PKIsHandle: true} return tblInfo } func newMockSchema(schemaName string) *model.DBInfo { return &model.DBInfo{ID: 10, Name: model.NewCIStr(schemaName), State: model.StatePublic} }
{ "content_hash": "112550737cb7e0923114a06f4cf1a52c", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 148, "avg_line_length": 37.320754716981135, "alnum_prop": 0.7408998988877654, "repo_name": "pingcap/tidb", "id": "fbca5f6bcdc71b7bb12668b9804b637610d461c0", "size": "8503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "table/temptable/ddl_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1854" }, { "name": "Go", "bytes": "34056451" }, { "name": "HTML", "bytes": "420" }, { "name": "Java", "bytes": "3694" }, { "name": "JavaScript", "bytes": "900" }, { "name": "Jsonnet", "bytes": "15129" }, { "name": "Makefile", "bytes": "22240" }, { "name": "Ragel", "bytes": "3678" }, { "name": "Shell", "bytes": "439400" }, { "name": "Starlark", "bytes": "574240" }, { "name": "TypeScript", "bytes": "61875" }, { "name": "Yacc", "bytes": "353301" } ], "symlink_target": "" }
namespace Google.Cloud.Monitoring.V3.Snippets { // [START monitoring_v3_generated_MetricService_ListTimeSeries_sync] using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Cloud.Monitoring.V3; using System; public sealed partial class GeneratedMetricServiceClientSnippets { /// <summary>Snippet for ListTimeSeries</summary> /// <remarks> /// This snippet has been automatically generated and should be regarded as a code template only. /// It will require modifications to work: /// - It may require correct/in-range values for request initialization. /// - It may require specifying regional endpoints when creating the service client as shown in /// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint. /// </remarks> public void ListTimeSeriesRequestObject() { // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ListTimeSeriesRequest request = new ListTimeSeriesRequest { Filter = "", Interval = new TimeInterval(), Aggregation = new Aggregation(), OrderBy = "", View = ListTimeSeriesRequest.Types.TimeSeriesView.Full, ProjectName = ProjectName.FromProject("[PROJECT]"), SecondaryAggregation = new Aggregation(), }; // Make the request PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response = metricServiceClient.ListTimeSeries(request); // Iterate over all response items, lazily performing RPCs as required foreach (TimeSeries item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTimeSeriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TimeSeries item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TimeSeries> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TimeSeries item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END monitoring_v3_generated_MetricService_ListTimeSeries_sync] }
{ "content_hash": "4e8c8bddda668dfb12bcbae4da682cf0", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 120, "avg_line_length": 44.88732394366197, "alnum_prop": 0.6011923438970819, "repo_name": "googleapis/google-cloud-dotnet", "id": "7dc4da332c7142f2c37e89a761f12b143c90fc09", "size": "3809", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.GeneratedSnippets/MetricServiceClient.ListTimeSeriesRequestObjectSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "319820004" }, { "name": "Dockerfile", "bytes": "3415" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65881" } ], "symlink_target": "" }
import sys if sys.version_info[0] == 2: import Queue as queue else: import queue import contextlib import collections import logging from . import _utils, events logger = logging.getLogger(__name__) class Room(object): def __init__(self, id, client): self.id = id self._logger = logger.getChild('Room') self._client = client name = _utils.LazyFrom('scrape_info') description = _utils.LazyFrom('scrape_info') message_count = _utils.LazyFrom('scrape_info') user_count = _utils.LazyFrom('scrape_info') parent_site_name = _utils.LazyFrom('scrape_info') owners = _utils.LazyFrom('scrape_info') tags = _utils.LazyFrom('scrape_info') def scrape_info(self): data = self._client._br.get_room_info(self.id) self.name = data['name'] self.description = data['description'] self.message_count = data['message_count'] self.user_count = data['user_count'] self.parent_site_name = data['parent_site_name'] self.owners = [ self._client.get_user(user_id, name=user_name) for user_id, user_name in zip(data['owner_user_ids'], data['owner_user_names']) ] self.tags = data['tags'] @property def text_description(self): if self.description is not None: return _utils.html_to_text(self.description) def join(self): return self._client._join_room(self.id) def leave(self): return self._client._leave_room(self.id) def send_message(self, text, length_check=True): """ Sends a message (queued, to avoid getting throttled) @ivar text: The message to send @type text: L{str} """ if len(text) > 500 and length_check: self._logger.info("Could not send message because it was longer than 500 characters.") return if len(text) == 0: self._logger.info("Could not send message because it was empty.") return self._client._request_queue.put(('send', self.id, text)) self._logger.info("Queued message %r for room_id #%r.", text, self.id) self._logger.info("Queue length: %d.", self._client._request_queue.qsize()) def watch(self, event_callback): return self.watch_polling(event_callback, 3) def watch_polling(self, event_callback, interval): def on_activity(activity): for event in self._events_from_activity(activity, self.id): event_callback(event, self._client) return self._client._br.watch_room_http(self.id, on_activity, interval) def watch_socket(self, event_callback): def on_activity(activity): for event in self._events_from_activity(activity, self.id): event_callback(event, self._client) return self._client._br.watch_room_socket(self.id, on_activity) def _events_from_activity(self, activity, room_id): """ Returns a list of Events associated with a particular room, given an activity message from the server. """ room_activity = activity.get('r%s' % (room_id,), {}) room_events_data = room_activity.get('e', []) for room_event_data in room_events_data: if room_event_data: event = events.make(room_event_data, self._client) self._client._recently_gotten_objects.appendleft(event) yield event def new_events(self, types=events.Event): return FilteredEventIterator(self, types) def new_messages(self): return MessageIterator(self) def get_pingable_user_ids(self): return self._client._br.get_pingable_user_ids_in_room(self.id) def get_pingable_user_names(self): return self._client._br.get_pingable_user_names_in_room(self.id) def get_current_user_ids(self): return self._client._br.get_current_user_ids_in_room(self.id) def get_current_user_names(self): return self._client._br.get_current_user_names_in_room(self.id) class FilteredEventIterator(object): def __init__(self, room, types): self.types = types self._queue = queue.Queue() room.join() self._watcher = room.watch(self._on_event) def __enter__(self): return self def __exit__(self, exc_type, exc_value, tracback): self._watcher.close() def __iter__(self): while True: yield self._queue.get() def _on_event(self, event, client): if isinstance(event, self.types): self._queue.put(event) class MessageIterator(object): def __init__(self, room): self._event_iter = FilteredEventIterator(room, events.MessagePosted) def __enter__(self): return self def __exit__(self, exc_type, exc_value, tracback): self._event_iter._watcher.close() def __iter__(self): for event in self._event_iter: yield event.message def _on_event(self, event, client): return self._event_iter._on_event(event)
{ "content_hash": "578c6599ce65e0e0e5d0ca08cf334e80", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 98, "avg_line_length": 32.0251572327044, "alnum_prop": 0.6105655930871956, "repo_name": "ByteCommander/ChatExchange6", "id": "b88d5f8cc64163fe7a4cde2f09000e83e88daca6", "size": "5092", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "chatexchange/rooms.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "886" }, { "name": "Python", "bytes": "82364" }, { "name": "Shell", "bytes": "911" } ], "symlink_target": "" }
/*! * Copyright (c) 2015 by Contributors * \file image_det_aug_default.cc * \brief Default augmenter. */ #include <mxnet/base.h> #include <utility> #include <string> #include <algorithm> #include <vector> #include <cmath> #include "./image_augmenter.h" #include "../common/utils.h" namespace mxnet { namespace io { using mxnet::Tuple; namespace image_det_aug_default_enum { enum ImageDetAugDefaultCropEmitMode {kCenter, kOverlap}; enum ImageDetAugDefaultResizeMode {kForce, kShrink, kFit}; } /*! \brief image detection augmentation parameters*/ struct DefaultImageDetAugmentParam : public dmlc::Parameter<DefaultImageDetAugmentParam> { /*! \brief resize shorter edge to size before applying other augmentations */ int resize; /*! \brief probability we do random cropping, use prob <= 0 to disable */ float rand_crop_prob; /*! \brief min crop scales */ Tuple<float> min_crop_scales; /*! \brief max crop scales */ Tuple<float> max_crop_scales; /*! \brief min crop aspect ratios */ Tuple<float> min_crop_aspect_ratios; /*! \brief max crop aspect ratios */ Tuple<float> max_crop_aspect_ratios; /*! \brief min IOUs between ground-truths and crop boxes */ Tuple<float> min_crop_overlaps; /*! \brief max IOUs between ground-truths and crop boxes */ Tuple<float> max_crop_overlaps; /*! \brief min itersection/gt_area between ground-truths and crop boxes */ Tuple<float> min_crop_sample_coverages; /*! \brief max itersection/gt_area between ground-truths and crop boxes */ Tuple<float> max_crop_sample_coverages; /*! \brief min itersection/crop_area between ground-truths and crop boxes */ Tuple<float> min_crop_object_coverages; /*! \brief max itersection/crop_area between ground-truths and crop boxes */ Tuple<float> max_crop_object_coverages; /*! \brief number of crop samplers, skip random crop if <= 0 */ int num_crop_sampler; /*! \beief 0-emit ground-truth if center out of crop area * 1-emit if overlap < emit_overlap_thresh */ int crop_emit_mode; /*! \brief ground-truth emition threshold specific for crop_emit_mode == 1 */ float emit_overlap_thresh; /*! \brief maximum trials for cropping, skip cropping if fails exceed this number */ Tuple<int> max_crop_trials; /*! \brief random padding prob */ float rand_pad_prob; /*!< \brief maximum padding scale */ float max_pad_scale; /*! \brief max random in H channel */ int max_random_hue; /*! \brief random H prob */ float random_hue_prob; /*! \brief max random in S channel */ int max_random_saturation; /*! \brief random saturation prob */ float random_saturation_prob; /*! \brief max random in L channel */ int max_random_illumination; /*! \brief random illumination change prob */ float random_illumination_prob; /*! \brief max random contrast */ float max_random_contrast; /*! \brief random contrast prob */ float random_contrast_prob; /*! \brief random mirror prob */ float rand_mirror_prob; /*! \brief filled color while padding */ int fill_value; /*! \brief interpolation method 0-NN 1-bilinear 2-cubic 3-area 4-lanczos4 9-auto 10-rand */ int inter_method; /*! \brief shape of the image data */ mxnet::TShape data_shape; /*! \brief resize mode, 0-force * 1-Shrink to data_shape, preserve ratio, * 2-fit to data_shape, preserve ratio */ int resize_mode; // declare parameters DMLC_DECLARE_PARAMETER(DefaultImageDetAugmentParam) { DMLC_DECLARE_FIELD(resize).set_default(-1) .describe("Augmentation Param: scale shorter edge to size " "before applying other augmentations, -1 to disable."); DMLC_DECLARE_FIELD(rand_crop_prob).set_default(0.0f) .describe("Augmentation Param: Probability of random cropping, <= 0 to disable"); DMLC_DECLARE_FIELD(min_crop_scales).set_default(Tuple<float>({0.0f})) .describe("Augmentation Param: Min crop scales."); DMLC_DECLARE_FIELD(max_crop_scales).set_default(Tuple<float>({1.0f})) .describe("Augmentation Param: Max crop scales."); DMLC_DECLARE_FIELD(min_crop_aspect_ratios).set_default(Tuple<float>({1.0f})) .describe("Augmentation Param: Min crop aspect ratios."); DMLC_DECLARE_FIELD(max_crop_aspect_ratios).set_default(Tuple<float>({1.0f})) .describe("Augmentation Param: Max crop aspect ratios."); DMLC_DECLARE_FIELD(min_crop_overlaps).set_default(Tuple<float>({0.0f})) .describe("Augmentation Param: Minimum crop IOU between crop_box and ground-truths."); DMLC_DECLARE_FIELD(max_crop_overlaps).set_default(Tuple<float>({1.0f})) .describe("Augmentation Param: Maximum crop IOU between crop_box and ground-truth."); DMLC_DECLARE_FIELD(min_crop_sample_coverages).set_default(Tuple<float>({0.0f})) .describe("Augmentation Param: Minimum ratio of intersect/crop_area " "between crop box and ground-truths."); DMLC_DECLARE_FIELD(max_crop_sample_coverages).set_default(Tuple<float>({1.0f})) .describe("Augmentation Param: Maximum ratio of intersect/crop_area " "between crop box and ground-truths."); DMLC_DECLARE_FIELD(min_crop_object_coverages).set_default(Tuple<float>({0.0f})) .describe("Augmentation Param: Minimum ratio of intersect/gt_area " "between crop box and ground-truths."); DMLC_DECLARE_FIELD(max_crop_object_coverages).set_default(Tuple<float>({1.0f})) .describe("Augmentation Param: Maximum ratio of intersect/gt_area " "between crop box and ground-truths."); DMLC_DECLARE_FIELD(num_crop_sampler).set_default(1) .describe("Augmentation Param: Number of crop samplers."); DMLC_DECLARE_FIELD(crop_emit_mode) .add_enum("center", image_det_aug_default_enum::kCenter) .add_enum("overlap", image_det_aug_default_enum::kOverlap) .set_default(image_det_aug_default_enum::kCenter) .describe("Augmentation Param: Emition mode for invalid ground-truths after crop. " "center: emit if centroid of object is out of crop region; " "overlap: emit if overlap is less than emit_overlap_thresh. "); DMLC_DECLARE_FIELD(emit_overlap_thresh).set_default(0.3f) .describe("Augmentation Param: Emit overlap thresh for emit mode overlap only."); DMLC_DECLARE_FIELD(max_crop_trials).set_default(Tuple<int>({25})) .describe("Augmentation Param: Skip cropping if fail crop trail count " "exceeds this number."); DMLC_DECLARE_FIELD(rand_pad_prob).set_default(0.0f) .describe("Augmentation Param: Probability for random padding."); DMLC_DECLARE_FIELD(max_pad_scale).set_default(1.0f) .describe("Augmentation Param: Maximum padding scale."); DMLC_DECLARE_FIELD(max_random_hue).set_default(0) .describe("Augmentation Param: Maximum random value of H channel in HSL color space."); DMLC_DECLARE_FIELD(random_hue_prob).set_default(0.0f) .describe("Augmentation Param: Probability to apply random hue."); DMLC_DECLARE_FIELD(max_random_saturation).set_default(0) .describe("Augmentation Param: Maximum random value of S channel in HSL color space."); DMLC_DECLARE_FIELD(random_saturation_prob).set_default(0.0f) .describe("Augmentation Param: Probability to apply random saturation."); DMLC_DECLARE_FIELD(max_random_illumination).set_default(0) .describe("Augmentation Param: Maximum random value of L channel in HSL color space."); DMLC_DECLARE_FIELD(random_illumination_prob).set_default(0.0f) .describe("Augmentation Param: Probability to apply random illumination."); DMLC_DECLARE_FIELD(max_random_contrast).set_default(0) .describe("Augmentation Param: Maximum random value of delta contrast."); DMLC_DECLARE_FIELD(random_contrast_prob).set_default(0.0f) .describe("Augmentation Param: Probability to apply random contrast."); DMLC_DECLARE_FIELD(rand_mirror_prob).set_default(0.0f) .describe("Augmentation Param: Probability to apply horizontal flip aka. mirror."); DMLC_DECLARE_FIELD(fill_value).set_default(127) .describe("Augmentation Param: Filled color value while padding."); DMLC_DECLARE_FIELD(inter_method).set_default(1) .describe("Augmentation Param: 0-NN 1-bilinear 2-cubic 3-area 4-lanczos4 9-auto 10-rand."); DMLC_DECLARE_FIELD(data_shape) .set_expect_ndim(3).enforce_nonzero() .describe("Dataset Param: Shape of each instance generated by the DataIter."); DMLC_DECLARE_FIELD(resize_mode) .add_enum("force", image_det_aug_default_enum::kForce) .add_enum("shrink", image_det_aug_default_enum::kShrink) .add_enum("fit", image_det_aug_default_enum::kFit) .set_default(image_det_aug_default_enum::kForce) .describe("Augmentation Param: How image data fit in data_shape. " "force: force reshape to data_shape regardless of aspect ratio; " "shrink: ensure each side fit in data_shape, preserve aspect ratio; " "fit: fit image to data_shape, preserve ratio, will upscale if applicable."); } }; DMLC_REGISTER_PARAMETER(DefaultImageDetAugmentParam); std::vector<dmlc::ParamFieldInfo> ListDefaultDetAugParams() { return DefaultImageDetAugmentParam::__FIELDS__(); } #if MXNET_USE_OPENCV #include "./opencv_compatibility.h" using Rect = cv::Rect_<float>; #ifdef _MSC_VER #define M_PI CV_PI #endif /*! \brief helper class for better detection label handling */ class ImageDetLabel { public: /*! \brief Helper struct to store the coordinates and id for each object */ struct ImageDetObject { float id; float left; float top; float right; float bottom; std::vector<float> extra; // store extra info other than id and coordinates /*! \brief Return converted Rect object */ Rect ToRect() const { return Rect(left, top, right - left, bottom - top); } /*! \brief Return projected coordinates according to new region */ ImageDetObject Project(Rect box) const { ImageDetObject ret = *this; ret.left = std::max(0.f, (ret.left - box.x) / box.width); ret.top = std::max(0.f, (ret.top - box.y) / box.height); ret.right = std::min(1.f, (ret.right - box.x) / box.width); ret.bottom = std::min(1.f, (ret.bottom - box.y) / box.height); return ret; } /*! \brief Return Horizontally fliped coordinates */ ImageDetObject HorizontalFlip() const { ImageDetObject ret = *this; ret.left = 1.f - this->right; ret.right = 1.f - this->left; return ret; } }; // struct ImageDetObject /*! \brief constructor from raw array of detection labels */ explicit ImageDetLabel(const std::vector<float> &raw_label) { FromArray(raw_label); } /*! \brief construct from raw array with following format * header_width, object_width, (extra_headers...), * [id, xmin, ymin, xmax, ymax, (extra_object_info)] x N */ void FromArray(const std::vector<float> &raw_label) { int label_width = static_cast<int>(raw_label.size()); CHECK_GE(label_width, 7); // at least 2(header) + 5(1 object) int header_width = static_cast<int>(raw_label[0]); CHECK_GE(header_width, 2); object_width_ = static_cast<int>(raw_label[1]); CHECK_GE(object_width_, 5); // id, x1, y1, x2, y2... header_.assign(raw_label.begin(), raw_label.begin() + header_width); int num = (label_width - header_width) / object_width_; CHECK_EQ((label_width - header_width) % object_width_, 0); objects_.reserve(num); for (int i = header_width; i < label_width; i += object_width_) { ImageDetObject obj; auto it = raw_label.cbegin() + i; obj.id = *(it++); obj.left = *(it++); obj.top = *(it++); obj.right = *(it++); obj.bottom = *(it++); obj.extra.assign(it, it - 5 + object_width_); if (obj.right > obj.left && obj.bottom > obj.top) { objects_.push_back(obj); } } } /*! \brief Convert back to raw array */ std::vector<float> ToArray() const { std::vector<float> out(header_); out.reserve(out.size() + objects_.size() * object_width_); for (auto& obj : objects_) { out.push_back(obj.id); out.push_back(obj.left); out.push_back(obj.top); out.push_back(obj.right); out.push_back(obj.bottom); out.insert(out.end(), obj.extra.begin(), obj.extra.end()); } return out; } /*! \brief Intersection over Union between two rects */ static float RectIOU(Rect a, Rect b) { float intersect = (a & b).area(); if (intersect <= 0.f) return 0.f; return intersect / (a.area() + b.area() - intersect); } /*! \brief try crop image with given crop_box * return false if fail to meet any of the constraints * convert all objects if success */ bool TryCrop(const Rect crop_box, const float min_crop_overlap, const float max_crop_overlap, const float min_crop_sample_coverage, const float max_crop_sample_coverage, const float min_crop_object_coverage, const float max_crop_object_coverage, const int crop_emit_mode, const float emit_overlap_thresh) { if (objects_.size() < 1) { return true; // no object, raise error or just skip? } // check if crop_box valid bool valid = false; if (min_crop_overlap > 0.f || max_crop_overlap < 1.f || min_crop_sample_coverage > 0.f || max_crop_sample_coverage < 1.f || min_crop_object_coverage > 0.f || max_crop_object_coverage < 1.f) { for (auto& obj : objects_) { Rect gt_box = obj.ToRect(); if (min_crop_overlap > 0.f || max_crop_overlap < 1.f) { float ovp = RectIOU(crop_box, gt_box); if (ovp < min_crop_overlap || ovp > max_crop_overlap) { continue; } } if (min_crop_sample_coverage > 0.f || max_crop_sample_coverage < 1.f) { float c = (crop_box & gt_box).area() / crop_box.area(); if (c < min_crop_sample_coverage || c > max_crop_sample_coverage) { continue; } } if (min_crop_object_coverage > 0.f || max_crop_object_coverage < 1.f) { float c = (crop_box & gt_box).area() / gt_box.area(); if (c < min_crop_object_coverage || c > max_crop_object_coverage) { continue; } } valid = true; break; } } else { valid = true; } if (!valid) return false; // transform ground-truth labels std::vector<ImageDetObject> new_objects; for (auto& object : objects_) { if (image_det_aug_default_enum::kCenter == crop_emit_mode) { float center_x = (object.left + object.right) * 0.5f; float center_y = (object.top + object.bottom) * 0.5f; if (!crop_box.contains(cv::Point2f(center_x, center_y))) { continue; } new_objects.push_back(object.Project(crop_box)); } else if (image_det_aug_default_enum::kOverlap == crop_emit_mode) { Rect gt_box = object.ToRect(); float overlap = (crop_box & gt_box).area() / gt_box.area(); if (overlap > emit_overlap_thresh) { new_objects.push_back(object.Project(crop_box)); } } } if (new_objects.size() < 1) return false; objects_ = new_objects; // replace the old objects return true; } /*! \brief try pad image with given pad_box * convert all objects afterwards */ bool TryPad(const Rect pad_box) { // update all objects inplace for (auto& object : objects_) { object = object.Project(pad_box); } return true; } /*! \brief flip image and object coordinates horizontally */ bool TryMirror() { // flip all objects horizontally for (auto& object : objects_) { object = object.HorizontalFlip(); } return true; } private: /*! \brief width for each object information, 5 at least */ int object_width_; /*! \brief vector to store original header info */ std::vector<float> header_; /*! \brief storing objects in more convenient formats */ std::vector<ImageDetObject> objects_; }; // class ImageDetLabel /*! \brief helper class to do image augmentation */ class DefaultImageDetAugmenter : public ImageAugmenter { public: // contructor DefaultImageDetAugmenter() = default; void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override { std::vector<std::pair<std::string, std::string> > kwargs_left; kwargs_left = param_.InitAllowUnknown(kwargs); CHECK((param_.inter_method >= 0 && param_.inter_method <= 4) || (param_.inter_method >= 9 && param_.inter_method <= 10)) << "invalid inter_method: valid value 0,1,2,3,9,10"; // validate crop parameters ValidateCropParameters(&param_.min_crop_scales, param_.num_crop_sampler); ValidateCropParameters(&param_.max_crop_scales, param_.num_crop_sampler); ValidateCropParameters(&param_.min_crop_aspect_ratios, param_.num_crop_sampler); ValidateCropParameters(&param_.max_crop_aspect_ratios, param_.num_crop_sampler); ValidateCropParameters(&param_.min_crop_overlaps, param_.num_crop_sampler); ValidateCropParameters(&param_.max_crop_overlaps, param_.num_crop_sampler); ValidateCropParameters(&param_.min_crop_sample_coverages, param_.num_crop_sampler); ValidateCropParameters(&param_.max_crop_sample_coverages, param_.num_crop_sampler); ValidateCropParameters(&param_.min_crop_object_coverages, param_.num_crop_sampler); ValidateCropParameters(&param_.max_crop_object_coverages, param_.num_crop_sampler); ValidateCropParameters(&param_.max_crop_trials, param_.num_crop_sampler); for (int i = 0; i < param_.num_crop_sampler; ++i) { CHECK_GE(param_.min_crop_scales[i], 0.0f); CHECK_LE(param_.max_crop_scales[i], 1.0f); CHECK_GT(param_.max_crop_scales[i], param_.min_crop_scales[i]); CHECK_GE(param_.min_crop_aspect_ratios[i], 0.0f); CHECK_GE(param_.max_crop_aspect_ratios[i], param_.min_crop_aspect_ratios[i]); CHECK_GE(param_.max_crop_overlaps[i], param_.min_crop_overlaps[i]); CHECK_GE(param_.max_crop_sample_coverages[i], param_.min_crop_sample_coverages[i]); CHECK_GE(param_.max_crop_object_coverages[i], param_.min_crop_object_coverages[i]); } CHECK_GE(param_.emit_overlap_thresh, 0.0f); } /*! * \brief get interpolation method with given inter_method, 0-CV_INTER_NN 1-CV_INTER_LINEAR 2-CV_INTER_CUBIC * \ 3-CV_INTER_AREA 4-CV_INTER_LANCZOS4 9-AUTO(cubic for enlarge, area for shrink, bilinear for others) 10-RAND */ int GetInterMethod(int inter_method, int old_width, int old_height, int new_width, int new_height, common::RANDOM_ENGINE *prnd) { if (inter_method == 9) { if (new_width > old_width && new_height > old_height) { return 2; // CV_INTER_CUBIC for enlarge } else if (new_width <old_width && new_height < old_height) { return 3; // CV_INTER_AREA for shrink } else { return 1; // CV_INTER_LINEAR for others } } else if (inter_method == 10) { std::uniform_int_distribution<size_t> rand_uniform_int(0, 4); return rand_uniform_int(*prnd); } else { return inter_method; } } /*! \brief Check number of crop samplers and given parameters */ template<typename DType> void ValidateCropParameters(mxnet::Tuple<DType> *param, const int num_sampler) { if (num_sampler == 1) { CHECK_EQ(param->ndim(), 1); } else if (num_sampler > 1) { if (param->ndim() == 1) { std::vector<DType> vec(num_sampler, (*param)[0]); param->assign(vec.begin(), vec.end()); } else { CHECK_EQ(param->ndim(), num_sampler) << "# of parameters/crop_samplers mismatch "; } } } /*! \brief Generate crop box region given cropping parameters */ Rect GenerateCropBox(const float min_crop_scale, const float max_crop_scale, const float min_crop_aspect_ratio, const float max_crop_aspect_ratio, common::RANDOM_ENGINE *prnd, const float img_aspect_ratio) { float new_scale = std::uniform_real_distribution<float>( min_crop_scale, max_crop_scale)(*prnd) + 1e-12f; float min_ratio = std::max<float>(min_crop_aspect_ratio / img_aspect_ratio, new_scale * new_scale); float max_ratio = std::min<float>(max_crop_aspect_ratio / img_aspect_ratio, 1. / (new_scale * new_scale)); float new_ratio = std::sqrt(std::uniform_real_distribution<float>( min_ratio, max_ratio)(*prnd)); float new_width = std::min(1.f, new_scale * new_ratio); float new_height = std::min(1.f, new_scale / new_ratio); float x0 = std::uniform_real_distribution<float>(0.f, 1 - new_width)(*prnd); float y0 = std::uniform_real_distribution<float>(0.f, 1 - new_height)(*prnd); return Rect(x0, y0, new_width, new_height); } /*! \brief Generate padding box region given padding parameters */ Rect GeneratePadBox(const float max_pad_scale, common::RANDOM_ENGINE *prnd, const float threshold = 1.05f) { float new_scale = std::uniform_real_distribution<float>( 1.f, max_pad_scale)(*prnd); if (new_scale < threshold) return Rect(0, 0, 0, 0); auto rand_uniform = std::uniform_real_distribution<float>(0.f, new_scale - 1); float x0 = rand_uniform(*prnd); float y0 = rand_uniform(*prnd); return Rect(-x0, -y0, new_scale, new_scale); } cv::Mat Process(const cv::Mat &src, std::vector<float> *label, common::RANDOM_ENGINE *prnd) override { using mshadow::index_t; cv::Mat res; if (param_.resize != -1) { int new_height, new_width; if (src.rows > src.cols) { new_height = param_.resize*src.rows/src.cols; new_width = param_.resize; } else { new_height = param_.resize; new_width = param_.resize*src.cols/src.rows; } int interpolation_method = GetInterMethod(param_.inter_method, src.cols, src.rows, new_width, new_height, prnd); cv::resize(src, res, cv::Size(new_width, new_height), 0, 0, interpolation_method); } else { res = src; } // build a helper class for processing labels ImageDetLabel det_label(*label); // random engine std::uniform_real_distribution<float> rand_uniform(0, 1); // color space augmentation if (param_.random_hue_prob > 0.f || param_.random_saturation_prob > 0.f || param_.random_illumination_prob > 0.f || param_.random_contrast_prob > 0.f) { std::uniform_real_distribution<float> uniform_range(-1.f, 1.f); int h = uniform_range(*prnd) * param_.max_random_hue; int s = uniform_range(*prnd) * param_.max_random_saturation; int l = uniform_range(*prnd) * param_.max_random_illumination; float c = uniform_range(*prnd) * param_.max_random_contrast; h = rand_uniform(*prnd) < param_.random_hue_prob ? h : 0; s = rand_uniform(*prnd) < param_.random_saturation_prob ? s : 0; l = rand_uniform(*prnd) < param_.random_illumination_prob ? l : 0; c = rand_uniform(*prnd) < param_.random_contrast_prob ? c : 0; if (h != 0 || s != 0 || l != 0) { int temp[3] = {h, l, s}; int limit[3] = {180, 255, 255}; cv::cvtColor(res, res, CV_BGR2HLS); for (int i = 0; i < res.rows; ++i) { for (int j = 0; j < res.cols; ++j) { for (int k = 0; k < 3; ++k) { int v = res.at<cv::Vec3b>(i, j)[k]; v += temp[k]; v = std::max(0, std::min(limit[k], v)); res.at<cv::Vec3b>(i, j)[k] = v; } } } cv::cvtColor(res, res, CV_HLS2BGR); } if (std::fabs(c) > 1e-3) { cv::Mat tmp = res; tmp.convertTo(res, -1, c + 1.f, 0); } } // random mirror logic if (param_.rand_mirror_prob > 0 && rand_uniform(*prnd) < param_.rand_mirror_prob) { if (det_label.TryMirror()) { // flip image cv::flip(res, temp_, 1); res = temp_; } } // random padding logic if (param_.rand_pad_prob > 0 && param_.max_pad_scale > 1.f) { if (rand_uniform(*prnd) < param_.rand_pad_prob) { Rect pad_box = GeneratePadBox(param_.max_pad_scale, prnd); if (pad_box.area() > 0) { if (det_label.TryPad(pad_box)) { // pad image temp_ = res; int left = static_cast<int>(-pad_box.x * res.cols); int top = static_cast<int>(-pad_box.y * res.rows); int right = static_cast<int>((pad_box.width + pad_box.x - 1) * res.cols); int bot = static_cast<int>((pad_box.height + pad_box.y - 1) * res.rows); cv::copyMakeBorder(temp_, res, top, bot, left, right, cv::BORDER_ISOLATED, cv::Scalar(param_.fill_value, param_.fill_value, param_.fill_value)); } } } } // random crop logic if (param_.rand_crop_prob > 0 && param_.num_crop_sampler > 0) { if (rand_uniform(*prnd) < param_.rand_crop_prob) { // random crop sampling logic: randomly pick a sampler, return if success // continue to next sampler if failed(exceed max_trial) // return original sample if every sampler has failed std::vector<int> indices(param_.num_crop_sampler); for (int i = 0; i < param_.num_crop_sampler; ++i) { indices[i] = i; } std::shuffle(indices.begin(), indices.end(), *prnd); int num_processed = 0; for (auto idx : indices) { if (num_processed > 0) break; for (int t = 0; t < param_.max_crop_trials[idx]; ++t) { Rect crop_box = GenerateCropBox(param_.min_crop_scales[idx], param_.max_crop_scales[idx], param_.min_crop_aspect_ratios[idx], param_.max_crop_aspect_ratios[idx], prnd, static_cast<float>(res.cols) / res.rows); if (det_label.TryCrop(crop_box, param_.min_crop_overlaps[idx], param_.max_crop_overlaps[idx], param_.min_crop_sample_coverages[idx], param_.max_crop_sample_coverages[idx], param_.min_crop_object_coverages[idx], param_.max_crop_object_coverages[idx], param_.crop_emit_mode, param_.emit_overlap_thresh)) { ++num_processed; // crop image int left = static_cast<int>(crop_box.x * res.cols); int top = static_cast<int>(crop_box.y * res.rows); int width = static_cast<int>(crop_box.width * res.cols); int height = static_cast<int>(crop_box.height * res.rows); res = res(cv::Rect(left, top, width, height)); break; } } } } } if (image_det_aug_default_enum::kForce == param_.resize_mode) { // force resize to specified data_shape, regardless of aspect ratio int new_height = param_.data_shape[1]; int new_width = param_.data_shape[2]; int interpolation_method = GetInterMethod(param_.inter_method, res.cols, res.rows, new_width, new_height, prnd); cv::resize(res, res, cv::Size(new_width, new_height), 0, 0, interpolation_method); } else if (image_det_aug_default_enum::kShrink == param_.resize_mode) { // try to keep original size, shrink if too large float h = param_.data_shape[1]; float w = param_.data_shape[2]; if (res.rows > h || res.cols > w) { float ratio = std::min(h / res.rows, w / res.cols); int new_height = ratio * res.rows; int new_width = ratio * res.cols; int interpolation_method = GetInterMethod(param_.inter_method, res.cols, res.rows, new_width, new_height, prnd); cv::resize(res, res, cv::Size(new_width, new_height), 0, 0, interpolation_method); } } else if (image_det_aug_default_enum::kFit == param_.resize_mode) { float h = param_.data_shape[1]; float w = param_.data_shape[2]; float ratio = std::min(h / res.rows, w / res.cols); int new_height = ratio * res.rows; int new_width = ratio * res.cols; int interpolation_method = GetInterMethod(param_.inter_method, res.cols, res.rows, new_width, new_height, prnd); cv::resize(res, res, cv::Size(new_width, new_height), 0, 0, interpolation_method); } *label = det_label.ToArray(); // put back processed labels return res; } private: // temporal space cv::Mat temp_; // parameters DefaultImageDetAugmentParam param_; }; MXNET_REGISTER_IMAGE_AUGMENTER(det_aug_default) .describe("default detection augmenter") .set_body([]() { return new DefaultImageDetAugmenter(); }); #endif // MXNET_USE_OPENCV } // namespace io } // namespace mxnet
{ "content_hash": "3cf0305a5b99abebd2ccd618ca531865", "timestamp": "", "source": "github", "line_count": 670, "max_line_length": 114, "avg_line_length": 43.14328358208955, "alnum_prop": 0.6291773334255863, "repo_name": "leezu/mxnet", "id": "6b3109fbce197aa5e60cebfff1a1bae99a66e564", "size": "29713", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/io/image_det_aug_default.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1731" }, { "name": "Batchfile", "bytes": "13130" }, { "name": "C", "bytes": "233623" }, { "name": "C++", "bytes": "9758652" }, { "name": "CMake", "bytes": "164032" }, { "name": "Clojure", "bytes": "622640" }, { "name": "Cuda", "bytes": "1292731" }, { "name": "Dockerfile", "bytes": "101147" }, { "name": "Groovy", "bytes": "168211" }, { "name": "HTML", "bytes": "40268" }, { "name": "Java", "bytes": "205196" }, { "name": "Julia", "bytes": "445413" }, { "name": "Jupyter Notebook", "bytes": "3660357" }, { "name": "MATLAB", "bytes": "34903" }, { "name": "Makefile", "bytes": "149220" }, { "name": "Perl", "bytes": "1558421" }, { "name": "PowerShell", "bytes": "9244" }, { "name": "Python", "bytes": "9866322" }, { "name": "R", "bytes": "357982" }, { "name": "Raku", "bytes": "9012" }, { "name": "SWIG", "bytes": "161870" }, { "name": "Scala", "bytes": "1304635" }, { "name": "Shell", "bytes": "458535" }, { "name": "Smalltalk", "bytes": "3497" } ], "symlink_target": "" }
const { env: ENV } = process; export const CWD = process.cwd(); export const PORT = parseInt(ENV.PORT, 10) || 4000; export const NODE_ENV = ENV.NODE_ENV || 'development'; export const LUX_CONSOLE = ENV.LUX_CONSOLE || false;
{ "content_hash": "10f14236e51886e1e08aa9e1a124edaa", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 54, "avg_line_length": 37.5, "alnum_prop": 0.6933333333333334, "repo_name": "kureuil/lux", "id": "449a64043e0543e76541e708f30c681bbb3595ef", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/constants.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "214242" } ], "symlink_target": "" }
SYNONYM #### According to Index Fungorum #### Published in null #### Original name Erioderma physcoides Vain. ### Remarks null
{ "content_hash": "e3beb8ba932960c150c9b355e82b1e9e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 26, "avg_line_length": 10, "alnum_prop": 0.7076923076923077, "repo_name": "mdoering/backbone", "id": "efeb49c058d4a7b51cd0f3eeb1be52d90d1ea2a5", "size": "180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Pannariaceae/Erioderma/Erioderma physcioides/ Syn. Erioderma physcoides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@class ViewController; @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property UIViewController * navigationViewController; @end
{ "content_hash": "d7ffdfa59c826640e698ff8471bfd982", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 60, "avg_line_length": 27.857142857142858, "alnum_prop": 0.8153846153846154, "repo_name": "cobaltians/CodeDArmor", "id": "7f68278db7143fdebf6d98846d7165045cd27b61", "size": "368", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "iOS/CodeDArmor/AppDelegate.h", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "39398" }, { "name": "Java", "bytes": "12260" }, { "name": "JavaScript", "bytes": "255073" }, { "name": "Objective-C", "bytes": "13735" } ], "symlink_target": "" }
package com.krishagni.catissueplus.core.biospecimen.domain; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.hibernate.envers.AuditTable; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.annotation.Qualifier; import com.krishagni.catissueplus.core.administrative.domain.Site; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenErrorCode; import com.krishagni.catissueplus.core.biospecimen.domain.factory.VisitErrorCode; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; import com.krishagni.catissueplus.core.common.events.DependentEntityDetail; import com.krishagni.catissueplus.core.common.service.LabelGenerator; import com.krishagni.catissueplus.core.common.util.Status; import com.krishagni.catissueplus.core.common.util.Utility; @Configurable @Audited @AuditTable(value="CAT_SPECIMEN_COLL_GROUP_AUD") public class Visit { private static final String ENTITY_NAME = "visit"; public static final String VISIT_STATUS_PENDING = "Pending"; public static final String VISIT_STATUS_COMPLETED = "Complete"; private Long id; private String name; private Date visitDate; private String clinicalDiagnosis; private String clinicalStatus; private String activityStatus; private Site site; private String status; private String comments; private String surgicalPathologyNumber; private String sprName; private CollectionProtocolEvent cpEvent; private Set<Specimen> specimens = new HashSet<Specimen>(); private CollectionProtocolRegistration registration; private String defNameTmpl; @Autowired @Qualifier("visitNameGenerator") private LabelGenerator labelGenerator; public static String getEntityName() { return ENTITY_NAME; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getVisitDate() { return visitDate; } public void setVisitDate(Date visitDate) { this.visitDate = visitDate; } public String getClinicalDiagnosis() { return clinicalDiagnosis; } public void setClinicalDiagnosis(String clinicalDiagnosis) { this.clinicalDiagnosis = clinicalDiagnosis; } public String getClinicalStatus() { return clinicalStatus; } public void setClinicalStatus(String clinicalStatus) { this.clinicalStatus = clinicalStatus; } public String getActivityStatus() { return activityStatus; } public void setActivityStatus(String activityStatus) { if (StringUtils.isBlank(activityStatus)) { activityStatus = Status.ACTIVITY_STATUS_ACTIVE.getStatus(); } this.activityStatus = activityStatus; } public Site getSite() { return site; } public void setSite(Site site) { this.site = site; } public String getStatus() { return status; } public void setStatus(String status) { if (this.status != null && this.status.equals(status)) { return; } if (StringUtils.isBlank(status)) { throw OpenSpecimenException.userError(VisitErrorCode.INVALID_STATUS); } if (this.status != null && VISIT_STATUS_PENDING.equals(status)) { for (Specimen specimen : specimens) { specimen.setPending(); } } this.status = status; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getSurgicalPathologyNumber() { return surgicalPathologyNumber; } public void setSurgicalPathologyNumber(String surgicalPathologyNumber) { this.surgicalPathologyNumber = surgicalPathologyNumber; } public String getSprName() { return sprName; } public void setSprName(String sprName) { this.sprName = sprName; } public CollectionProtocolEvent getCpEvent() { return cpEvent; } public void setCpEvent(CollectionProtocolEvent cpEvent) { this.cpEvent = cpEvent; } @NotAudited public Set<Specimen> getSpecimens() { return specimens; } public void setSpecimens(Set<Specimen> specimens) { this.specimens = specimens; } public Set<Specimen> getTopLevelSpecimens() { Set<Specimen> result = new HashSet<Specimen>(); if (specimens == null) { return specimens; } for (Specimen specimen : specimens) { if (specimen.getParentSpecimen() == null) { result.add(specimen); } } return result; } public CollectionProtocolRegistration getRegistration() { return registration; } public void setRegistration(CollectionProtocolRegistration registration) { this.registration = registration; } public String getDefNameTmpl() { return defNameTmpl; } public void setDefNameTmpl(String defNameTmpl) { this.defNameTmpl = defNameTmpl; } public void setActive() { this.setActivityStatus(Status.ACTIVITY_STATUS_ACTIVE.getStatus()); } public boolean isActive() { return Status.ACTIVITY_STATUS_ACTIVE.getStatus().equals(this.activityStatus); } public boolean isCompleted() { return Visit.VISIT_STATUS_COMPLETED.equals(this.status); } public List<DependentEntityDetail> getDependentEntities() { return DependentEntityDetail.singletonList(Specimen.getEntityName(), getActiveSpecimens()); } public void updateActivityStatus(String activityStatus) { if (this.activityStatus != null && this.activityStatus.equals(activityStatus)) { return; } if (Status.ACTIVITY_STATUS_DISABLED.getStatus().equals(activityStatus)) { delete(); } } public void delete() { ensureNoActiveChildObjects(); for (Specimen specimen : getSpecimens()) { specimen.disable(false); } setName(Utility.getDisabledValue(getName())); setActivityStatus(Status.ACTIVITY_STATUS_DISABLED.getStatus()); } public void update(Visit visit) { updateActivityStatus(visit.getActivityStatus()); if (!isActive()) { return; } setClinicalDiagnosis(visit.getClinicalDiagnosis()); setClinicalStatus(visit.getClinicalStatus()); setCpEvent(visit.getCpEvent()); setRegistration(visit.getRegistration()); setSite(visit.getSite()); setStatus(visit.getStatus()); setComments(visit.getComments()); setName(visit.getName()); setSurgicalPathologyNumber(visit.getSurgicalPathologyNumber()); setVisitDate(visit.getVisitDate()); } public void updateSprName(String sprName) { setSprName(sprName); } public void addSpecimen(Specimen specimen) { specimens.add(specimen); } public CollectionProtocol getCollectionProtocol() { return registration.getCollectionProtocol(); } public void setNameIfEmpty() { if (StringUtils.isNotBlank(name)) { return; } setName(labelGenerator.generateLabel(defNameTmpl, this)); } private void ensureNoActiveChildObjects() { for (Specimen specimen : getSpecimens()) { if (specimen.isActiveOrClosed() && specimen.isCollected()) { throw OpenSpecimenException.userError(SpecimenErrorCode.REF_ENTITY_FOUND); } } } private int getActiveSpecimens() { int count = 0; for (Specimen specimen : getSpecimens()) { if (specimen.isActiveOrClosed() && specimen.isCollected()) { ++count; } } return count; } }
{ "content_hash": "d22e5641ca58001820b0ed8866507227", "timestamp": "", "source": "github", "line_count": 320, "max_line_length": 94, "avg_line_length": 23.053125, "alnum_prop": 0.7493561068184899, "repo_name": "asamgir/openspecimen", "id": "390164597e9fb150542e558d4012afd15e6d811d", "size": "7378", "binary": false, "copies": "1", "ref": "refs/heads/OS_v20_Travis_Setup", "path": "WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/domain/Visit.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "88783" }, { "name": "Groff", "bytes": "3349" }, { "name": "HTML", "bytes": "466628" }, { "name": "Java", "bytes": "2201900" }, { "name": "JavaScript", "bytes": "838615" } ], "symlink_target": "" }
<?php namespace app\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\Author; /** * AuthorSearch represents the model behind the search form about `app\models\Author`. */ class AuthorSearch extends Author { /** * @inheritdoc */ public function rules() { return [ [['author_id'], 'integer'], [['first_name', 'last_name', 'birth'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Author::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'author_id' => $this->author_id, 'birth' => $this->birth, ]); $query->andFilterWhere(['like', 'first_name', $this->first_name]) ->andFilterWhere(['like', 'last_name', $this->last_name]); return $dataProvider; } }
{ "content_hash": "6a60cc081fbd1254a66349907486d548", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 106, "avg_line_length": 22.760563380281692, "alnum_prop": 0.5464108910891089, "repo_name": "hehbhehb/basic", "id": "2fd9571945f719f2ae803a48b854961df5dd730c", "size": "1616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/AuthorSearch.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "260" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "85018" } ], "symlink_target": "" }
/* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015 by Delphix. All rights reserved. * Copyright (c) 2013 Steven Hartland. All rights reserved. */ #include <sys/zfs_context.h> #include <sys/dsl_userhold.h> #include <sys/dsl_dataset.h> #include <sys/dsl_destroy.h> #include <sys/dsl_synctask.h> #include <sys/dmu_tx.h> #include <sys/zfs_onexit.h> #include <sys/dsl_pool.h> #include <sys/dsl_dir.h> #include <sys/zfs_ioctl.h> #include <sys/zap.h> typedef struct dsl_dataset_user_hold_arg { nvlist_t *dduha_holds; nvlist_t *dduha_chkholds; nvlist_t *dduha_errlist; minor_t dduha_minor; } dsl_dataset_user_hold_arg_t; /* * If you add new checks here, you may need to add additional checks to the * "temporary" case in snapshot_check() in dmu_objset.c. */ int dsl_dataset_user_hold_check_one(dsl_dataset_t *ds, const char *htag, boolean_t temphold, dmu_tx_t *tx) { dsl_pool_t *dp = dmu_tx_pool(tx); objset_t *mos = dp->dp_meta_objset; int error = 0; ASSERT(dsl_pool_config_held(dp)); if (strlen(htag) > MAXNAMELEN) return (SET_ERROR(E2BIG)); /* Tempholds have a more restricted length */ if (temphold && strlen(htag) + MAX_TAG_PREFIX_LEN >= MAXNAMELEN) return (SET_ERROR(E2BIG)); /* tags must be unique (if ds already exists) */ if (ds != NULL && dsl_dataset_phys(ds)->ds_userrefs_obj != 0) { uint64_t value; error = zap_lookup(mos, dsl_dataset_phys(ds)->ds_userrefs_obj, htag, 8, 1, &value); if (error == 0) error = SET_ERROR(EEXIST); else if (error == ENOENT) error = 0; } return (error); } static int dsl_dataset_user_hold_check(void *arg, dmu_tx_t *tx) { dsl_dataset_user_hold_arg_t *dduha = arg; dsl_pool_t *dp = dmu_tx_pool(tx); if (spa_version(dp->dp_spa) < SPA_VERSION_USERREFS) return (SET_ERROR(ENOTSUP)); if (!dmu_tx_is_syncing(tx)) return (0); for (nvpair_t *pair = nvlist_next_nvpair(dduha->dduha_holds, NULL); pair != NULL; pair = nvlist_next_nvpair(dduha->dduha_holds, pair)) { dsl_dataset_t *ds; int error = 0; char *htag, *name; /* must be a snapshot */ name = nvpair_name(pair); if (strchr(name, '@') == NULL) error = SET_ERROR(EINVAL); if (error == 0) error = nvpair_value_string(pair, &htag); if (error == 0) error = dsl_dataset_hold(dp, name, FTAG, &ds); if (error == 0) { error = dsl_dataset_user_hold_check_one(ds, htag, dduha->dduha_minor != 0, tx); dsl_dataset_rele(ds, FTAG); } if (error == 0) { fnvlist_add_string(dduha->dduha_chkholds, name, htag); } else { /* * We register ENOENT errors so they can be correctly * reported if needed, such as when all holds fail. */ fnvlist_add_int32(dduha->dduha_errlist, name, error); if (error != ENOENT) return (error); } } return (0); } static void dsl_dataset_user_hold_sync_one_impl(nvlist_t *tmpholds, dsl_dataset_t *ds, const char *htag, minor_t minor, uint64_t now, dmu_tx_t *tx) { dsl_pool_t *dp = ds->ds_dir->dd_pool; objset_t *mos = dp->dp_meta_objset; uint64_t zapobj; ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock)); if (dsl_dataset_phys(ds)->ds_userrefs_obj == 0) { /* * This is the first user hold for this dataset. Create * the userrefs zap object. */ dmu_buf_will_dirty(ds->ds_dbuf, tx); zapobj = dsl_dataset_phys(ds)->ds_userrefs_obj = zap_create(mos, DMU_OT_USERREFS, DMU_OT_NONE, 0, tx); } else { zapobj = dsl_dataset_phys(ds)->ds_userrefs_obj; } ds->ds_userrefs++; VERIFY0(zap_add(mos, zapobj, htag, 8, 1, &now, tx)); if (minor != 0) { char name[MAXNAMELEN]; nvlist_t *tags; VERIFY0(dsl_pool_user_hold(dp, ds->ds_object, htag, now, tx)); (void) snprintf(name, sizeof (name), "%llx", (u_longlong_t)ds->ds_object); if (nvlist_lookup_nvlist(tmpholds, name, &tags) != 0) { tags = fnvlist_alloc(); fnvlist_add_boolean(tags, htag); fnvlist_add_nvlist(tmpholds, name, tags); fnvlist_free(tags); } else { fnvlist_add_boolean(tags, htag); } } spa_history_log_internal_ds(ds, "hold", tx, "tag=%s temp=%d refs=%llu", htag, minor != 0, ds->ds_userrefs); } typedef struct zfs_hold_cleanup_arg { char zhca_spaname[ZFS_MAX_DATASET_NAME_LEN]; uint64_t zhca_spa_load_guid; nvlist_t *zhca_holds; } zfs_hold_cleanup_arg_t; static void dsl_dataset_user_release_onexit(void *arg) { zfs_hold_cleanup_arg_t *ca = arg; spa_t *spa; int error; error = spa_open(ca->zhca_spaname, &spa, FTAG); if (error != 0) { zfs_dbgmsg("couldn't release holds on pool=%s " "because pool is no longer loaded", ca->zhca_spaname); return; } if (spa_load_guid(spa) != ca->zhca_spa_load_guid) { zfs_dbgmsg("couldn't release holds on pool=%s " "because pool is no longer loaded (guid doesn't match)", ca->zhca_spaname); spa_close(spa, FTAG); return; } (void) dsl_dataset_user_release_tmp(spa_get_dsl(spa), ca->zhca_holds); fnvlist_free(ca->zhca_holds); kmem_free(ca, sizeof (zfs_hold_cleanup_arg_t)); spa_close(spa, FTAG); } static void dsl_onexit_hold_cleanup(spa_t *spa, nvlist_t *holds, minor_t minor) { zfs_hold_cleanup_arg_t *ca; if (minor == 0 || nvlist_empty(holds)) { fnvlist_free(holds); return; } ASSERT(spa != NULL); ca = kmem_alloc(sizeof (*ca), KM_SLEEP); (void) strlcpy(ca->zhca_spaname, spa_name(spa), sizeof (ca->zhca_spaname)); ca->zhca_spa_load_guid = spa_load_guid(spa); ca->zhca_holds = holds; VERIFY0(zfs_onexit_add_cb(minor, dsl_dataset_user_release_onexit, ca, NULL)); } void dsl_dataset_user_hold_sync_one(dsl_dataset_t *ds, const char *htag, minor_t minor, uint64_t now, dmu_tx_t *tx) { nvlist_t *tmpholds; if (minor != 0) tmpholds = fnvlist_alloc(); else tmpholds = NULL; dsl_dataset_user_hold_sync_one_impl(tmpholds, ds, htag, minor, now, tx); dsl_onexit_hold_cleanup(dsl_dataset_get_spa(ds), tmpholds, minor); } static void dsl_dataset_user_hold_sync(void *arg, dmu_tx_t *tx) { dsl_dataset_user_hold_arg_t *dduha = arg; dsl_pool_t *dp = dmu_tx_pool(tx); nvlist_t *tmpholds; uint64_t now = gethrestime_sec(); if (dduha->dduha_minor != 0) tmpholds = fnvlist_alloc(); else tmpholds = NULL; for (nvpair_t *pair = nvlist_next_nvpair(dduha->dduha_chkholds, NULL); pair != NULL; pair = nvlist_next_nvpair(dduha->dduha_chkholds, pair)) { dsl_dataset_t *ds; VERIFY0(dsl_dataset_hold(dp, nvpair_name(pair), FTAG, &ds)); dsl_dataset_user_hold_sync_one_impl(tmpholds, ds, fnvpair_value_string(pair), dduha->dduha_minor, now, tx); dsl_dataset_rele(ds, FTAG); } dsl_onexit_hold_cleanup(dp->dp_spa, tmpholds, dduha->dduha_minor); } /* * The full semantics of this function are described in the comment above * lzc_hold(). * * To summarize: * holds is nvl of snapname -> holdname * errlist will be filled in with snapname -> error * * The snaphosts must all be in the same pool. * * Holds for snapshots that don't exist will be skipped. * * If none of the snapshots for requested holds exist then ENOENT will be * returned. * * If cleanup_minor is not 0, the holds will be temporary, which will be cleaned * up when the process exits. * * On success all the holds, for snapshots that existed, will be created and 0 * will be returned. * * On failure no holds will be created, the errlist will be filled in, * and an errno will returned. * * In all cases the errlist will contain entries for holds where the snapshot * didn't exist. */ int dsl_dataset_user_hold(nvlist_t *holds, minor_t cleanup_minor, nvlist_t *errlist) { dsl_dataset_user_hold_arg_t dduha; nvpair_t *pair; int ret; pair = nvlist_next_nvpair(holds, NULL); if (pair == NULL) return (0); dduha.dduha_holds = holds; dduha.dduha_chkholds = fnvlist_alloc(); dduha.dduha_errlist = errlist; dduha.dduha_minor = cleanup_minor; ret = dsl_sync_task(nvpair_name(pair), dsl_dataset_user_hold_check, dsl_dataset_user_hold_sync, &dduha, fnvlist_num_pairs(holds), ZFS_SPACE_CHECK_RESERVED); fnvlist_free(dduha.dduha_chkholds); return (ret); } typedef int (dsl_holdfunc_t)(dsl_pool_t *dp, const char *name, void *tag, dsl_dataset_t **dsp); typedef struct dsl_dataset_user_release_arg { dsl_holdfunc_t *ddura_holdfunc; nvlist_t *ddura_holds; nvlist_t *ddura_todelete; nvlist_t *ddura_errlist; nvlist_t *ddura_chkholds; } dsl_dataset_user_release_arg_t; /* Place a dataset hold on the snapshot identified by passed dsobj string */ static int dsl_dataset_hold_obj_string(dsl_pool_t *dp, const char *dsobj, void *tag, dsl_dataset_t **dsp) { return (dsl_dataset_hold_obj(dp, strtonum(dsobj, NULL), tag, dsp)); } static int dsl_dataset_user_release_check_one(dsl_dataset_user_release_arg_t *ddura, dsl_dataset_t *ds, nvlist_t *holds, const char *snapname) { uint64_t zapobj; nvlist_t *holds_found; objset_t *mos; int numholds; if (!ds->ds_is_snapshot) return (SET_ERROR(EINVAL)); if (nvlist_empty(holds)) return (0); numholds = 0; mos = ds->ds_dir->dd_pool->dp_meta_objset; zapobj = dsl_dataset_phys(ds)->ds_userrefs_obj; holds_found = fnvlist_alloc(); for (nvpair_t *pair = nvlist_next_nvpair(holds, NULL); pair != NULL; pair = nvlist_next_nvpair(holds, pair)) { uint64_t tmp; int error; const char *holdname = nvpair_name(pair); if (zapobj != 0) error = zap_lookup(mos, zapobj, holdname, 8, 1, &tmp); else error = SET_ERROR(ENOENT); /* * Non-existent holds are put on the errlist, but don't * cause an overall failure. */ if (error == ENOENT) { if (ddura->ddura_errlist != NULL) { char *errtag = kmem_asprintf("%s#%s", snapname, holdname); fnvlist_add_int32(ddura->ddura_errlist, errtag, ENOENT); strfree(errtag); } continue; } if (error != 0) { fnvlist_free(holds_found); return (error); } fnvlist_add_boolean(holds_found, holdname); numholds++; } if (DS_IS_DEFER_DESTROY(ds) && dsl_dataset_phys(ds)->ds_num_children == 1 && ds->ds_userrefs == numholds) { /* we need to destroy the snapshot as well */ if (dsl_dataset_long_held(ds)) { fnvlist_free(holds_found); return (SET_ERROR(EBUSY)); } fnvlist_add_boolean(ddura->ddura_todelete, snapname); } if (numholds != 0) { fnvlist_add_nvlist(ddura->ddura_chkholds, snapname, holds_found); } fnvlist_free(holds_found); return (0); } static int dsl_dataset_user_release_check(void *arg, dmu_tx_t *tx) { dsl_dataset_user_release_arg_t *ddura; dsl_holdfunc_t *holdfunc; dsl_pool_t *dp; if (!dmu_tx_is_syncing(tx)) return (0); dp = dmu_tx_pool(tx); ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock)); ddura = arg; holdfunc = ddura->ddura_holdfunc; for (nvpair_t *pair = nvlist_next_nvpair(ddura->ddura_holds, NULL); pair != NULL; pair = nvlist_next_nvpair(ddura->ddura_holds, pair)) { int error; dsl_dataset_t *ds; nvlist_t *holds; const char *snapname = nvpair_name(pair); error = nvpair_value_nvlist(pair, &holds); if (error != 0) error = (SET_ERROR(EINVAL)); else error = holdfunc(dp, snapname, FTAG, &ds); if (error == 0) { error = dsl_dataset_user_release_check_one(ddura, ds, holds, snapname); dsl_dataset_rele(ds, FTAG); } if (error != 0) { if (ddura->ddura_errlist != NULL) { fnvlist_add_int32(ddura->ddura_errlist, snapname, error); } /* * Non-existent snapshots are put on the errlist, * but don't cause an overall failure. */ if (error != ENOENT) return (error); } } return (0); } static void dsl_dataset_user_release_sync_one(dsl_dataset_t *ds, nvlist_t *holds, dmu_tx_t *tx) { dsl_pool_t *dp = ds->ds_dir->dd_pool; objset_t *mos = dp->dp_meta_objset; for (nvpair_t *pair = nvlist_next_nvpair(holds, NULL); pair != NULL; pair = nvlist_next_nvpair(holds, pair)) { int error; const char *holdname = nvpair_name(pair); /* Remove temporary hold if one exists. */ error = dsl_pool_user_release(dp, ds->ds_object, holdname, tx); VERIFY(error == 0 || error == ENOENT); VERIFY0(zap_remove(mos, dsl_dataset_phys(ds)->ds_userrefs_obj, holdname, tx)); ds->ds_userrefs--; spa_history_log_internal_ds(ds, "release", tx, "tag=%s refs=%lld", holdname, (longlong_t)ds->ds_userrefs); } } static void dsl_dataset_user_release_sync(void *arg, dmu_tx_t *tx) { dsl_dataset_user_release_arg_t *ddura = arg; dsl_holdfunc_t *holdfunc = ddura->ddura_holdfunc; dsl_pool_t *dp = dmu_tx_pool(tx); ASSERT(RRW_WRITE_HELD(&dp->dp_config_rwlock)); for (nvpair_t *pair = nvlist_next_nvpair(ddura->ddura_chkholds, NULL); pair != NULL; pair = nvlist_next_nvpair(ddura->ddura_chkholds, pair)) { dsl_dataset_t *ds; const char *name = nvpair_name(pair); VERIFY0(holdfunc(dp, name, FTAG, &ds)); dsl_dataset_user_release_sync_one(ds, fnvpair_value_nvlist(pair), tx); if (nvlist_exists(ddura->ddura_todelete, name)) { ASSERT(ds->ds_userrefs == 0 && dsl_dataset_phys(ds)->ds_num_children == 1 && DS_IS_DEFER_DESTROY(ds)); dsl_destroy_snapshot_sync_impl(ds, B_FALSE, tx); } dsl_dataset_rele(ds, FTAG); } } /* * The full semantics of this function are described in the comment above * lzc_release(). * * To summarize: * Releases holds specified in the nvl holds. * * holds is nvl of snapname -> { holdname, ... } * errlist will be filled in with snapname -> error * * If tmpdp is not NULL the names for holds should be the dsobj's of snapshots, * otherwise they should be the names of shapshots. * * As a release may cause snapshots to be destroyed this trys to ensure they * aren't mounted. * * The release of non-existent holds are skipped. * * At least one hold must have been released for the this function to succeed * and return 0. */ static int dsl_dataset_user_release_impl(nvlist_t *holds, nvlist_t *errlist, dsl_pool_t *tmpdp) { dsl_dataset_user_release_arg_t ddura; nvpair_t *pair; char *pool; int error; pair = nvlist_next_nvpair(holds, NULL); if (pair == NULL) return (0); /* * The release may cause snapshots to be destroyed; make sure they * are not mounted. */ if (tmpdp != NULL) { /* Temporary holds are specified by dsobj string. */ ddura.ddura_holdfunc = dsl_dataset_hold_obj_string; pool = spa_name(tmpdp->dp_spa); #ifdef _KERNEL for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL; pair = nvlist_next_nvpair(holds, pair)) { dsl_dataset_t *ds; dsl_pool_config_enter(tmpdp, FTAG); error = dsl_dataset_hold_obj_string(tmpdp, nvpair_name(pair), FTAG, &ds); if (error == 0) { char name[ZFS_MAX_DATASET_NAME_LEN]; dsl_dataset_name(ds, name); dsl_pool_config_exit(tmpdp, FTAG); dsl_dataset_rele(ds, FTAG); #if !defined(__zfsd__) (void) zfs_unmount_snap(name); #endif } else { dsl_pool_config_exit(tmpdp, FTAG); } } #endif } else { /* Non-temporary holds are specified by name. */ ddura.ddura_holdfunc = dsl_dataset_hold; pool = nvpair_name(pair); #ifdef _KERNEL for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL; pair = nvlist_next_nvpair(holds, pair)) { #if !defined(__zfsd__) (void) zfs_unmount_snap(nvpair_name(pair)); #endif } #endif } ddura.ddura_holds = holds; ddura.ddura_errlist = errlist; ddura.ddura_todelete = fnvlist_alloc(); ddura.ddura_chkholds = fnvlist_alloc(); error = dsl_sync_task(pool, dsl_dataset_user_release_check, dsl_dataset_user_release_sync, &ddura, 0, ZFS_SPACE_CHECK_NONE); fnvlist_free(ddura.ddura_todelete); fnvlist_free(ddura.ddura_chkholds); return (error); } /* * holds is nvl of snapname -> { holdname, ... } * errlist will be filled in with snapname -> error */ int dsl_dataset_user_release(nvlist_t *holds, nvlist_t *errlist) { return (dsl_dataset_user_release_impl(holds, errlist, NULL)); } /* * holds is nvl of snapdsobj -> { holdname, ... } */ void dsl_dataset_user_release_tmp(struct dsl_pool *dp, nvlist_t *holds) { ASSERT(dp != NULL); (void) dsl_dataset_user_release_impl(holds, NULL, dp); } int dsl_dataset_get_holds(const char *dsname, nvlist_t *nvl) { dsl_pool_t *dp; dsl_dataset_t *ds; int err; err = dsl_pool_hold(dsname, FTAG, &dp); if (err != 0) return (err); err = dsl_dataset_hold(dp, dsname, FTAG, &ds); if (err != 0) { dsl_pool_rele(dp, FTAG); return (err); } if (dsl_dataset_phys(ds)->ds_userrefs_obj != 0) { zap_attribute_t *za; zap_cursor_t zc; za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP); for (zap_cursor_init(&zc, ds->ds_dir->dd_pool->dp_meta_objset, dsl_dataset_phys(ds)->ds_userrefs_obj); zap_cursor_retrieve(&zc, za) == 0; zap_cursor_advance(&zc)) { fnvlist_add_uint64(nvl, za->za_name, za->za_first_integer); } zap_cursor_fini(&zc); kmem_free(za, sizeof (zap_attribute_t)); } dsl_dataset_rele(ds, FTAG); dsl_pool_rele(dp, FTAG); return (0); }
{ "content_hash": "89b07830c5b51bca53b2244fb0137c1f", "timestamp": "", "source": "github", "line_count": 651, "max_line_length": 80, "avg_line_length": 25.887864823348693, "alnum_prop": 0.6559069601851303, "repo_name": "jpeach/zfsd", "id": "0e72d47fb2781b0e5f54bc79ca6157c156fdc8bb", "size": "17672", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/fs/zfs/dsl_userhold.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13053" }, { "name": "C", "bytes": "8836219" }, { "name": "C++", "bytes": "561684" }, { "name": "CSS", "bytes": "8089" }, { "name": "HTML", "bytes": "238770" }, { "name": "Lua", "bytes": "334753" }, { "name": "M4", "bytes": "6915" }, { "name": "Makefile", "bytes": "79330" }, { "name": "Objective-C", "bytes": "3158" }, { "name": "Perl", "bytes": "509" }, { "name": "Roff", "bytes": "2339" }, { "name": "Shell", "bytes": "9861" } ], "symlink_target": "" }
package graphqlObj import "github.com/graphql-go/graphql" // ConsolInput object for GraphQL integration var ConsolInput = graphql.NewInputObject( graphql.InputObjectConfig{ Name: "Consol", Fields: graphql.InputObjectConfigFieldMap{ "Masterbill": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "ContainerMode": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "PaymentMethod": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "PortOfDischarge": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "PortOfLoading": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "ShipmentType": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "TransportMode": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "VesselName": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "VoyageFlightNo": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "EstimatedTimeOfDeparture": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "EstimatedTimeOfArrival": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "Carrier": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "ContainerNumber": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "ContainerType": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "DeliveryMode": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, "Seal": &graphql.InputObjectFieldConfig{ Type: graphql.String, }, }, }, ) // Consol object for GraphQL integration var Consol = graphql.NewObject( graphql.ObjectConfig{ Name: "Consol", Fields: graphql.Fields{ "Masterbill": &graphql.Field{ Type: graphql.String, }, "ContainerMode": &graphql.Field{ Type: graphql.String, }, "PaymentMethod": &graphql.Field{ Type: graphql.String, }, "PortOfDischarge": &graphql.Field{ Type: graphql.String, }, "PortOfLoading": &graphql.Field{ Type: graphql.String, }, "ShipmentType": &graphql.Field{ Type: graphql.String, }, "TransportMode": &graphql.Field{ Type: graphql.String, }, "VesselName": &graphql.Field{ Type: graphql.String, }, "VoyageFlightNo": &graphql.Field{ Type: graphql.String, }, "EstimatedTimeOfDeparture": &graphql.Field{ Type: graphql.String, }, "EstimatedTimeOfArrival": &graphql.Field{ Type: graphql.String, }, "Carrier": &graphql.Field{ Type: graphql.String, }, "ContainerNumber": &graphql.Field{ Type: graphql.String, }, "ContainerType": &graphql.Field{ Type: graphql.String, }, "DeliveryMode": &graphql.Field{ Type: graphql.String, }, "Seal": &graphql.Field{ Type: graphql.String, }, }, }, )
{ "content_hash": "c838561989942dac55b5ff2f2d2c53ba", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 63, "avg_line_length": 24.39316239316239, "alnum_prop": 0.6723896285914506, "repo_name": "blockfreight/go-bftx", "id": "3c6dfd7c7658b3f878b9b5bc52b63b9ca219af6d", "size": "2854", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "api/graphqlObj/consol.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1209" }, { "name": "Go", "bytes": "159527" }, { "name": "Shell", "bytes": "2565" } ], "symlink_target": "" }
include ../../Makefile.common LDFLAGS := -L.. -lgraph -L../../matrix -lFMatrix -lcblas -L../../libsafs -lsafs -lrt -lz $(LDFLAGS) CXXFLAGS = -I.. -I../../libsafs -I../../matrix -g -std=c++0x SOURCE := $(wildcard *.c) $(wildcard *.cpp) OBJS := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SOURCE))) DEPS := $(patsubst %.o,%.d,$(OBJS)) UNITTEST = test-bitmap test-partitioner test-vertex_index test-sparse_matrix all: $(UNITTEST) test-bitmap: test-bitmap.o ../libgraph.a $(CXX) -o test-bitmap test-bitmap.o $(LDFLAGS) test-sparse_matrix: test-sparse_matrix.o ../libgraph.a $(CXX) -o test-sparse_matrix test-sparse_matrix.o $(LDFLAGS) test-partitioner: test-partitioner.o ../libgraph.a $(CXX) -o test-partitioner test-partitioner.o $(LDFLAGS) test-vertex_index: test-vertex_index.o ../libgraph.a $(CXX) -o test-vertex_index test-vertex_index.o $(LDFLAGS) test: ./test-bitmap ./test-partitioner ./test-sparse_matrix ./test-vertex_index clean: rm -f *.o rm -f *.d rm -f *~ rm -f $(UNITTEST) -include $(DEPS)
{ "content_hash": "2c7d84e19a2284a967cf61e482c570e0", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 99, "avg_line_length": 26.94736842105263, "alnum_prop": 0.6572265625, "repo_name": "flashxio/FlashX", "id": "02868bb2caf974083e91d09eddc057324b3b9d9a", "size": "1720", "binary": false, "copies": "2", "ref": "refs/heads/release", "path": "flash-graph/unit-test/Makefile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3649" }, { "name": "C++", "bytes": "3702274" }, { "name": "CMake", "bytes": "9623" }, { "name": "Makefile", "bytes": "31838" }, { "name": "Perl", "bytes": "16384" }, { "name": "Python", "bytes": "1099" }, { "name": "R", "bytes": "3751" }, { "name": "Shell", "bytes": "12078" } ], "symlink_target": "" }
<?php namespace Wambo\Core\Storage; interface StorageInterface { public function read() : array; public function write(array $data); }
{ "content_hash": "b62b7eca26b2e186075d0a76899463de", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 39, "avg_line_length": 13.272727272727273, "alnum_prop": 0.7123287671232876, "repo_name": "wambo-co/module-core", "id": "5e92acc15dceacde359f0293fa68706be2521f82", "size": "146", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Wambo/Core/Storage/StorageInterface.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "19342" } ], "symlink_target": "" }
package act.asm; /** * A {@link MethodVisitor} that generates methods in bytecode form. Each visit * method of this class appends the bytecode corresponding to the visited * instruction to a byte vector, in the order these methods are called. * * @author Eric Bruneton * @author Eugene Kuleshov */ class MethodWriter extends MethodVisitor { /** * Pseudo access flag used to denote constructors. */ static final int ACC_CONSTRUCTOR = 0x80000; /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is zero. */ static final int SAME_FRAME = 0; // to 63 (0-3f) /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is 1 */ static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; // to 127 (40-7f) /** * Reserved for future use */ static final int RESERVED = 128; /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is 1. Offset is bigger then 63; */ static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; // f7 /** * Frame where current locals are the same as the locals in the previous * frame, except that the k last locals are absent. The value of k is given * by the formula 251-frame_type. */ static final int CHOP_FRAME = 248; // to 250 (f8-fA) /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is zero. Offset is bigger then 63; */ static final int SAME_FRAME_EXTENDED = 251; // fb /** * Frame where current locals are the same as the locals in the previous * frame, except that k additional locals are defined. The value of k is * given by the formula frame_type-251. */ static final int APPEND_FRAME = 252; // to 254 // fc-fe /** * Full frame */ static final int FULL_FRAME = 255; // ff /** * Indicates that the stack map frames must be recomputed from scratch. In * this case the maximum stack size and number of local variables is also * recomputed from scratch. * * @see #compute */ private static final int FRAMES = 0; /** * Indicates that the maximum stack size and number of local variables must * be automatically computed. * * @see #compute */ private static final int MAXS = 1; /** * Indicates that nothing must be automatically computed. * * @see #compute */ private static final int NOTHING = 2; /** * The class writer to which this method must be added. */ final ClassWriter cw; /** * Access flags of this method. */ private int access; /** * The index of the constant pool item that contains the className of this * method. */ private final int name; /** * The index of the constant pool item that contains the descriptor of this * method. */ private final int desc; /** * The descriptor of this method. */ private final String descriptor; /** * The signature of this method. */ String signature; /** * If not zero, indicates that the code of this method must be copied from * the ClassReader associated to this writer in <code>cw.cr</code>. More * precisely, this field gives the index of the first byte to copied from * <code>cw.cr.b</code>. */ int classReaderOffset; /** * If not zero, indicates that the code of this method must be copied from * the ClassReader associated to this writer in <code>cw.cr</code>. More * precisely, this field gives the number of bytes to copied from * <code>cw.cr.b</code>. */ int classReaderLength; /** * Number of exceptions that can be thrown by this method. */ int exceptionCount; /** * The exceptions that can be thrown by this method. More precisely, this * array contains the indexes of the constant pool items that contain the * internal names of these exception classes. */ int[] exceptions; /** * The annotation default attribute of this method. May be <tt>null</tt>. */ private ByteVector annd; /** * The runtime visible annotations of this method. May be <tt>null</tt>. */ private AnnotationWriter anns; /** * The runtime invisible annotations of this method. May be <tt>null</tt>. */ private AnnotationWriter ianns; /** * The runtime visible type annotations of this method. May be <tt>null</tt> * . */ private AnnotationWriter tanns; /** * The runtime invisible type annotations of this method. May be * <tt>null</tt>. */ private AnnotationWriter itanns; /** * The runtime visible parameter annotations of this method. May be * <tt>null</tt>. */ private AnnotationWriter[] panns; /** * The runtime invisible parameter annotations of this method. May be * <tt>null</tt>. */ private AnnotationWriter[] ipanns; /** * The number of synthetic parameters of this method. */ private int synthetics; /** * The non standard attributes of the method. */ private Attribute attrs; /** * The bytecode of this method. */ private ByteVector code = new ByteVector(); /** * Maximum stack size of this method. */ private int maxStack; /** * Maximum number of local variables for this method. */ private int maxLocals; /** * Number of local variables in the current stack map frame. */ private int currentLocals; /** * Number of stack map frames in the StackMapTable attribute. */ private int frameCount; /** * The StackMapTable attribute. */ private ByteVector stackMap; /** * The offset of the last frame that was written in the StackMapTable * attribute. */ private int previousFrameOffset; /** * The last frame that was written in the StackMapTable attribute. * * @see #frame */ private int[] previousFrame; /** * The current stack map frame. The first element contains the offset of the * instruction to which the frame corresponds, the second element is the * number of locals and the third one is the number of stack elements. The * local variables start at index 3 and are followed by the operand stack * values. In summary frame[0] = offset, frame[1] = nLocal, frame[2] = * nStack, frame[3] = nLocal. All types are encoded as integers, with the * same format as the one used in {@link Label}, but limited to BASE types. */ private int[] frame; /** * Number of elements in the exception handler list. */ private int handlerCount; /** * The first element in the exception handler list. */ private Handler firstHandler; /** * The last element in the exception handler list. */ private Handler lastHandler; /** * Number of entries in the MethodParameters attribute. */ private int methodParametersCount; /** * The MethodParameters attribute. */ private ByteVector methodParameters; /** * Number of entries in the LocalVariableTable attribute. */ private int localVarCount; /** * The LocalVariableTable attribute. */ private ByteVector localVar; /** * Number of entries in the LocalVariableTypeTable attribute. */ private int localVarTypeCount; /** * The LocalVariableTypeTable attribute. */ private ByteVector localVarType; /** * Number of entries in the LineNumberTable attribute. */ private int lineNumberCount; /** * The LineNumberTable attribute. */ private ByteVector lineNumber; /** * The start offset of the last visited instruction. */ private int lastCodeOffset; /** * The runtime visible type annotations of the code. May be <tt>null</tt>. */ private AnnotationWriter ctanns; /** * The runtime invisible type annotations of the code. May be <tt>null</tt>. */ private AnnotationWriter ictanns; /** * The non standard attributes of the method's code. */ private Attribute cattrs; /** * Indicates if some jump instructions are too small and need to be resized. */ private boolean resize; /** * The number of subroutines in this method. */ private int subroutines; // ------------------------------------------------------------------------ /* * Fields for the control flow graph analysis algorithm (used to compute the * maximum stack size). A control flow graph contains one node per "basic * block", and one edge per "jump" from one basic block to another. Each * node (i.e., each basic block) is represented by the Label object that * corresponds to the first instruction of this basic block. Each node also * stores the list of its successors in the graph, as a linked list of Edge * objects. */ /** * Indicates what must be automatically computed. * * @see #FRAMES * @see #MAXS * @see #NOTHING */ private final int compute; /** * A list of labels. This list is the list of basic blocks in the method, * i.e. a list of Label objects linked to each other by their * {@link Label#successor} field, in the order they are visited by * {@link MethodVisitor#visitLabel}, and starting with the first basic * block. */ private Label labels; /** * The previous basic block. */ private Label previousBlock; /** * The current basic block. */ private Label currentBlock; /** * The (relative) stack size after the last visited instruction. This size * is relative to the beginning of the current basic block, i.e., the true * stack size after the last visited instruction is equal to the * {@link Label#inputStackTop beginStackSize} of the current basic block * plus <tt>stackSize</tt>. */ private int stackSize; /** * The (relative) maximum stack size after the last visited instruction. * This size is relative to the beginning of the current basic block, i.e., * the true maximum stack size after the last visited instruction is equal * to the {@link Label#inputStackTop beginStackSize} of the current basic * block plus <tt>stackSize</tt>. */ private int maxStackSize; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ /** * Constructs a new {@link MethodWriter}. * * @param cw * the class writer in which the method must be added. * @param access * the method's access flags (see {@link Opcodes}). * @param name * the method's className. * @param desc * the method's descriptor (see {@link Type}). * @param signature * the method's signature. May be <tt>null</tt>. * @param exceptions * the internal names of the method's exceptions. May be * <tt>null</tt>. * @param computeMaxs * <tt>true</tt> if the maximum stack size and number of local * variables must be automatically computed. * @param computeFrames * <tt>true</tt> if the stack map tables must be recomputed from * scratch. */ MethodWriter(final ClassWriter cw, final int access, final String name, final String desc, final String signature, final String[] exceptions, final boolean computeMaxs, final boolean computeFrames) { super(Opcodes.ASM5); if (cw.firstMethod == null) { cw.firstMethod = this; } else { cw.lastMethod.mv = this; } cw.lastMethod = this; this.cw = cw; this.access = access; if ("<init>".equals(name)) { this.access |= ACC_CONSTRUCTOR; } this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); this.descriptor = desc; if (ClassReader.SIGNATURES) { this.signature = signature; } if (exceptions != null && exceptions.length > 0) { exceptionCount = exceptions.length; this.exceptions = new int[exceptionCount]; for (int i = 0; i < exceptionCount; ++i) { this.exceptions[i] = cw.newClass(exceptions[i]); } } this.compute = computeFrames ? FRAMES : (computeMaxs ? MAXS : NOTHING); if (computeMaxs || computeFrames) { // updates maxLocals int size = Type.getArgumentsAndReturnSizes(descriptor) >> 2; if ((access & Opcodes.ACC_STATIC) != 0) { --size; } maxLocals = size; currentLocals = size; // creates and visits the label for the first basic block labels = new Label(); labels.status |= Label.PUSHED; visitLabel(labels); } } // ------------------------------------------------------------------------ // Implementation of the MethodVisitor abstract class // ------------------------------------------------------------------------ @Override public void visitParameter(String name, int access) { if (methodParameters == null) { methodParameters = new ByteVector(); } ++methodParametersCount; methodParameters.putShort((name == null) ? 0 : cw.newUTF8(name)) .putShort(access); } @Override public AnnotationVisitor visitAnnotationDefault() { if (!ClassReader.ANNOTATIONS) { return null; } annd = new ByteVector(); return new AnnotationWriter(cw, false, annd, null, 0); } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2); if (visible) { aw.next = anns; anns = aw; } else { aw.next = ianns; ianns = aw; } return aw; } @Override public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write target_type and target_info AnnotationWriter.putTarget(typeRef, typePath, bv); // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = tanns; tanns = aw; } else { aw.next = itanns; itanns = aw; } return aw; } @Override public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); if ("Ljava/lang/Synthetic;".equals(desc)) { // workaround for a bug in javac with synthetic parameters // see ClassReader.readParameterAnnotations synthetics = Math.max(synthetics, parameter + 1); return new AnnotationWriter(cw, false, bv, null, 0); } // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2); if (visible) { if (panns == null) { panns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; } aw.next = panns[parameter]; panns[parameter] = aw; } else { if (ipanns == null) { ipanns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; } aw.next = ipanns[parameter]; ipanns[parameter] = aw; } return aw; } @Override public void visitAttribute(final Attribute attr) { if (attr.isCodeAttribute()) { attr.next = cattrs; cattrs = attr; } else { attr.next = attrs; attrs = attr; } } @Override public void visitCode() { } @Override public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { if (!ClassReader.FRAMES || compute == FRAMES) { return; } if (type == Opcodes.F_NEW) { if (previousFrame == null) { visitImplicitFirstFrame(); } currentLocals = nLocal; int frameIndex = startFrame(code.length, nLocal, nStack); for (int i = 0; i < nLocal; ++i) { if (local[i] instanceof String) { frame[frameIndex++] = Frame.OBJECT | cw.addType((String) local[i]); } else if (local[i] instanceof Integer) { frame[frameIndex++] = ((Integer) local[i]).intValue(); } else { frame[frameIndex++] = Frame.UNINITIALIZED | cw.addUninitializedType("", ((Label) local[i]).position); } } for (int i = 0; i < nStack; ++i) { if (stack[i] instanceof String) { frame[frameIndex++] = Frame.OBJECT | cw.addType((String) stack[i]); } else if (stack[i] instanceof Integer) { frame[frameIndex++] = ((Integer) stack[i]).intValue(); } else { frame[frameIndex++] = Frame.UNINITIALIZED | cw.addUninitializedType("", ((Label) stack[i]).position); } } endFrame(); } else { int delta; if (stackMap == null) { stackMap = new ByteVector(); delta = code.length; } else { delta = code.length - previousFrameOffset - 1; if (delta < 0) { if (type == Opcodes.F_SAME) { return; } else { throw new IllegalStateException(); } } } switch (type) { case Opcodes.F_FULL: currentLocals = nLocal; stackMap.putByte(FULL_FRAME).putShort(delta).putShort(nLocal); for (int i = 0; i < nLocal; ++i) { writeFrameType(local[i]); } stackMap.putShort(nStack); for (int i = 0; i < nStack; ++i) { writeFrameType(stack[i]); } break; case Opcodes.F_APPEND: currentLocals += nLocal; stackMap.putByte(SAME_FRAME_EXTENDED + nLocal).putShort(delta); for (int i = 0; i < nLocal; ++i) { writeFrameType(local[i]); } break; case Opcodes.F_CHOP: currentLocals -= nLocal; stackMap.putByte(SAME_FRAME_EXTENDED - nLocal).putShort(delta); break; case Opcodes.F_SAME: if (delta < 64) { stackMap.putByte(delta); } else { stackMap.putByte(SAME_FRAME_EXTENDED).putShort(delta); } break; case Opcodes.F_SAME1: if (delta < 64) { stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME + delta); } else { stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) .putShort(delta); } writeFrameType(stack[0]); break; } previousFrameOffset = code.length; ++frameCount; } maxStack = Math.max(maxStack, nStack); maxLocals = Math.max(maxLocals, currentLocals); } @Override public void visitInsn(final int opcode) { lastCodeOffset = code.length; // adds the instruction to the bytecode of the method code.putByte(opcode); // update currentBlock // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, null, null); } else { // updates current and max stack sizes int size = stackSize + Frame.SIZE[opcode]; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } // if opcode == ATHROW or xRETURN, ends current block (no successor) if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) { noSuccessor(); } } } @Override public void visitIntInsn(final int opcode, final int operand) { lastCodeOffset = code.length; // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, operand, null, null); } else if (opcode != Opcodes.NEWARRAY) { // updates current and max stack sizes only for NEWARRAY // (stack size variation = 0 for BIPUSH or SIPUSH) int size = stackSize + 1; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method if (opcode == Opcodes.SIPUSH) { code.put12(opcode, operand); } else { // BIPUSH or NEWARRAY code.put11(opcode, operand); } } @Override public void visitVarInsn(final int opcode, final int var) { lastCodeOffset = code.length; // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, var, null, null); } else { // updates current and max stack sizes if (opcode == Opcodes.RET) { // no stack change, but end of current block (no successor) currentBlock.status |= Label.RET; // save 'stackSize' here for future use // (see {@link #findSubroutineSuccessors}) currentBlock.inputStackTop = stackSize; noSuccessor(); } else { // xLOAD or xSTORE int size = stackSize + Frame.SIZE[opcode]; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } } if (compute != NOTHING) { // updates max locals int n; if (opcode == Opcodes.LLOAD || opcode == Opcodes.DLOAD || opcode == Opcodes.LSTORE || opcode == Opcodes.DSTORE) { n = var + 2; } else { n = var + 1; } if (n > maxLocals) { maxLocals = n; } } // adds the instruction to the bytecode of the method if (var < 4 && opcode != Opcodes.RET) { int opt; if (opcode < Opcodes.ISTORE) { /* ILOAD_0 */ opt = 26 + ((opcode - Opcodes.ILOAD) << 2) + var; } else { /* ISTORE_0 */ opt = 59 + ((opcode - Opcodes.ISTORE) << 2) + var; } code.putByte(opt); } else if (var >= 256) { code.putByte(196 /* WIDE */).put12(opcode, var); } else { code.put11(opcode, var); } if (opcode >= Opcodes.ISTORE && compute == FRAMES && handlerCount > 0) { visitLabel(new Label()); } } @Override public void visitTypeInsn(final int opcode, final String type) { lastCodeOffset = code.length; Item i = cw.newClassItem(type); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, code.length, cw, i); } else if (opcode == Opcodes.NEW) { // updates current and max stack sizes only if opcode == NEW // (no stack change for ANEWARRAY, CHECKCAST, INSTANCEOF) int size = stackSize + 1; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method code.put12(opcode, i.index); } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { lastCodeOffset = code.length; Item i = cw.newFieldItem(owner, name, desc); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, cw, i); } else { int size; // computes the stack size variation char c = desc.charAt(0); switch (opcode) { case Opcodes.GETSTATIC: size = stackSize + (c == 'D' || c == 'J' ? 2 : 1); break; case Opcodes.PUTSTATIC: size = stackSize + (c == 'D' || c == 'J' ? -2 : -1); break; case Opcodes.GETFIELD: size = stackSize + (c == 'D' || c == 'J' ? 1 : 0); break; // case Constants.PUTFIELD: default: size = stackSize + (c == 'D' || c == 'J' ? -3 : -2); break; } // updates current and max stack sizes if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method code.put12(opcode, i.index); } @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean itf) { lastCodeOffset = code.length; Item i = cw.newMethodItem(owner, name, desc, itf); int argSize = i.intVal; // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, cw, i); } else { /* * computes the stack size variation. In order not to recompute * several times this variation for the same Item, we use the * intVal field of this item to store this variation, once it * has been computed. More precisely this intVal field stores * the sizes of the arguments and of the return value * corresponding to desc. */ if (argSize == 0) { // the above sizes have not been computed yet, // so we compute them... argSize = Type.getArgumentsAndReturnSizes(desc); // ... and we save them in order // not to recompute them in the future i.intVal = argSize; } int size; if (opcode == Opcodes.INVOKESTATIC) { size = stackSize - (argSize >> 2) + (argSize & 0x03) + 1; } else { size = stackSize - (argSize >> 2) + (argSize & 0x03); } // updates current and max stack sizes if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method if (opcode == Opcodes.INVOKEINTERFACE) { if (argSize == 0) { argSize = Type.getArgumentsAndReturnSizes(desc); i.intVal = argSize; } code.put12(Opcodes.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0); } else { code.put12(opcode, i.index); } } @Override public void visitInvokeDynamicInsn(final String name, final String desc, final Handle bsm, final Object... bsmArgs) { lastCodeOffset = code.length; Item i = cw.newInvokeDynamicItem(name, desc, bsm, bsmArgs); int argSize = i.intVal; // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.INVOKEDYNAMIC, 0, cw, i); } else { /* * computes the stack size variation. In order not to recompute * several times this variation for the same Item, we use the * intVal field of this item to store this variation, once it * has been computed. More precisely this intVal field stores * the sizes of the arguments and of the return value * corresponding to desc. */ if (argSize == 0) { // the above sizes have not been computed yet, // so we compute them... argSize = Type.getArgumentsAndReturnSizes(desc); // ... and we save them in order // not to recompute them in the future i.intVal = argSize; } int size = stackSize - (argSize >> 2) + (argSize & 0x03) + 1; // updates current and max stack sizes if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method code.put12(Opcodes.INVOKEDYNAMIC, i.index); code.putShort(0); } @Override public void visitJumpInsn(final int opcode, final Label label) { lastCodeOffset = code.length; Label nextInsn = null; // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, 0, null, null); // 'label' is the target of a jump instruction label.getFirst().status |= Label.TARGET; // adds 'label' as a successor of this basic block addSuccessor(Edge.NORMAL, label); if (opcode != Opcodes.GOTO) { // creates a Label for the next basic block nextInsn = new Label(); } } else { if (opcode == Opcodes.JSR) { if ((label.status & Label.SUBROUTINE) == 0) { label.status |= Label.SUBROUTINE; ++subroutines; } currentBlock.status |= Label.JSR; addSuccessor(stackSize + 1, label); // creates a Label for the next basic block nextInsn = new Label(); /* * note that, by construction in this method, a JSR block * has at least two successors in the control flow graph: * the first one leads the next instruction after the JSR, * while the second one leads to the JSR target. */ } else { // updates current stack size (max stack size unchanged // because stack size variation always negative in this // case) stackSize += Frame.SIZE[opcode]; addSuccessor(stackSize, label); } } } // adds the instruction to the bytecode of the method if ((label.status & Label.RESOLVED) != 0 && label.position - code.length < Short.MIN_VALUE) { /* * case of a backward jump with an offset < -32768. In this case we * automatically replace GOTO with GOTO_W, JSR with JSR_W and IFxxx * <l> with IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is the * "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) and where <l'> * designates the instruction just after the GOTO_W. */ if (opcode == Opcodes.GOTO) { code.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { code.putByte(201); // JSR_W } else { // if the IF instruction is transformed into IFNOT GOTO_W the // next instruction becomes the target of the IFNOT instruction if (nextInsn != null) { nextInsn.status |= Label.TARGET; } code.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); code.putShort(8); // jump offset code.putByte(200); // GOTO_W } label.put(this, code, code.length - 1, true); } else { /* * case of a backward jump with an offset >= -32768, or of a forward * jump with, of course, an unknown offset. In these cases we store * the offset in 2 bytes (which will be increased in * resizeInstructions, if needed). */ code.putByte(opcode); label.put(this, code, code.length - 1, false); } if (currentBlock != null) { if (nextInsn != null) { // if the jump instruction is not a GOTO, the next instruction // is also a successor of this instruction. Calling visitLabel // adds the label of this next instruction as a successor of the // current block, and starts a new basic block visitLabel(nextInsn); } if (opcode == Opcodes.GOTO) { noSuccessor(); } } } @Override public void visitLabel(final Label label) { // resolves previous forward references to label, if any resize |= label.resolve(this, code.length, code.data); // updates currentBlock if ((label.status & Label.DEBUG) != 0) { return; } if (compute == FRAMES) { if (currentBlock != null) { if (label.position == currentBlock.position) { // successive labels, do not start a new basic block currentBlock.status |= (label.status & Label.TARGET); label.frame = currentBlock.frame; return; } // ends current block (with one new successor) addSuccessor(Edge.NORMAL, label); } // begins a new current block currentBlock = label; if (label.frame == null) { label.frame = new Frame(); label.frame.owner = label; } // updates the basic block list if (previousBlock != null) { if (label.position == previousBlock.position) { previousBlock.status |= (label.status & Label.TARGET); label.frame = previousBlock.frame; currentBlock = previousBlock; return; } previousBlock.successor = label; } previousBlock = label; } else if (compute == MAXS) { if (currentBlock != null) { // ends current block (with one new successor) currentBlock.outputStackMax = maxStackSize; addSuccessor(stackSize, label); } // begins a new current block currentBlock = label; // resets the relative current and max stack sizes stackSize = 0; maxStackSize = 0; // updates the basic block list if (previousBlock != null) { previousBlock.successor = label; } previousBlock = label; } } @Override public void visitLdcInsn(final Object cst) { lastCodeOffset = code.length; Item i = cw.newConstItem(cst); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.LDC, 0, cw, i); } else { int size; // computes the stack size variation if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) { size = stackSize + 2; } else { size = stackSize + 1; } // updates current and max stack sizes if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method int index = i.index; if (i.type == ClassWriter.LONG || i.type == ClassWriter.DOUBLE) { code.put12(20 /* LDC2_W */, index); } else if (index >= 256) { code.put12(19 /* LDC_W */, index); } else { code.put11(Opcodes.LDC, index); } } @Override public void visitIincInsn(final int var, final int increment) { lastCodeOffset = code.length; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.IINC, var, null, null); } } if (compute != NOTHING) { // updates max locals int n = var + 1; if (n > maxLocals) { maxLocals = n; } } // adds the instruction to the bytecode of the method if ((var > 255) || (increment > 127) || (increment < -128)) { code.putByte(196 /* WIDE */).put12(Opcodes.IINC, var) .putShort(increment); } else { code.putByte(Opcodes.IINC).put11(var, increment); } } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) { lastCodeOffset = code.length; // adds the instruction to the bytecode of the method int source = code.length; code.putByte(Opcodes.TABLESWITCH); code.putByteArray(null, 0, (4 - code.length % 4) % 4); dflt.put(this, code, source, true); code.putInt(min).putInt(max); for (int i = 0; i < labels.length; ++i) { labels[i].put(this, code, source, true); } // updates currentBlock visitSwitchInsn(dflt, labels); } @Override public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { lastCodeOffset = code.length; // adds the instruction to the bytecode of the method int source = code.length; code.putByte(Opcodes.LOOKUPSWITCH); code.putByteArray(null, 0, (4 - code.length % 4) % 4); dflt.put(this, code, source, true); code.putInt(labels.length); for (int i = 0; i < labels.length; ++i) { code.putInt(keys[i]); labels[i].put(this, code, source, true); } // updates currentBlock visitSwitchInsn(dflt, labels); } private void visitSwitchInsn(final Label dflt, final Label[] labels) { // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null); // adds current block successors addSuccessor(Edge.NORMAL, dflt); dflt.getFirst().status |= Label.TARGET; for (int i = 0; i < labels.length; ++i) { addSuccessor(Edge.NORMAL, labels[i]); labels[i].getFirst().status |= Label.TARGET; } } else { // updates current stack size (max stack size unchanged) --stackSize; // adds current block successors addSuccessor(stackSize, dflt); for (int i = 0; i < labels.length; ++i) { addSuccessor(stackSize, labels[i]); } } // ends current block noSuccessor(); } } @Override public void visitMultiANewArrayInsn(final String desc, final int dims) { lastCodeOffset = code.length; Item i = cw.newClassItem(desc); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(Opcodes.MULTIANEWARRAY, dims, cw, i); } else { // updates current stack size (max stack size unchanged because // stack size variation always negative or null) stackSize += 1 - dims; } } // adds the instruction to the bytecode of the method code.put12(Opcodes.MULTIANEWARRAY, i.index).putByte(dims); } @Override public AnnotationVisitor visitInsnAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write target_type and target_info typeRef = (typeRef & 0xFF0000FF) | (lastCodeOffset << 8); AnnotationWriter.putTarget(typeRef, typePath, bv); // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = ctanns; ctanns = aw; } else { aw.next = ictanns; ictanns = aw; } return aw; } @Override public void visitTryCatchBlock(final Label start, final Label end, final Label handler, final String type) { ++handlerCount; Handler h = new Handler(); h.start = start; h.end = end; h.handler = handler; h.desc = type; h.type = type != null ? cw.newClass(type) : 0; if (lastHandler == null) { firstHandler = h; } else { lastHandler.next = h; } lastHandler = h; } @Override public AnnotationVisitor visitTryCatchAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write target_type and target_info AnnotationWriter.putTarget(typeRef, typePath, bv); // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = ctanns; ctanns = aw; } else { aw.next = ictanns; ictanns = aw; } return aw; } @Override public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { if (signature != null) { if (localVarType == null) { localVarType = new ByteVector(); } ++localVarTypeCount; localVarType.putShort(start.position) .putShort(end.position - start.position) .putShort(cw.newUTF8(name)).putShort(cw.newUTF8(signature)) .putShort(index); } if (localVar == null) { localVar = new ByteVector(); } ++localVarCount; localVar.putShort(start.position) .putShort(end.position - start.position) .putShort(cw.newUTF8(name)).putShort(cw.newUTF8(desc)) .putShort(index); if (compute != NOTHING) { // updates max locals char c = desc.charAt(0); int n = index + (c == 'J' || c == 'D' ? 2 : 1); if (n > maxLocals) { maxLocals = n; } } } @Override public AnnotationVisitor visitLocalVariableAnnotation(int typeRef, TypePath typePath, Label[] start, Label[] end, int[] index, String desc, boolean visible) { if (!ClassReader.ANNOTATIONS) { return null; } ByteVector bv = new ByteVector(); // write target_type and target_info bv.putByte(typeRef >>> 24).putShort(start.length); for (int i = 0; i < start.length; ++i) { bv.putShort(start[i].position) .putShort(end[i].position - start[i].position) .putShort(index[i]); } if (typePath == null) { bv.putByte(0); } else { int length = typePath.b[typePath.offset] * 2 + 1; bv.putByteArray(typePath.b, typePath.offset, length); } // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, bv.length - 2); if (visible) { aw.next = ctanns; ctanns = aw; } else { aw.next = ictanns; ictanns = aw; } return aw; } @Override public void visitLineNumber(final int line, final Label start) { if (lineNumber == null) { lineNumber = new ByteVector(); } ++lineNumberCount; lineNumber.putShort(start.position); lineNumber.putShort(line); AsmContext.line(line); } @Override public void visitMaxs(final int maxStack, final int maxLocals) { if (resize) { // replaces the temporary jump opcodes introduced by Label.resolve. if (ClassReader.RESIZE) { resizeInstructions(); } else { throw new RuntimeException("Method code too large!"); } } if (ClassReader.FRAMES && compute == FRAMES) { // completes the control flow graph with exception handler blocks Handler handler = firstHandler; while (handler != null) { Label l = handler.start.getFirst(); Label h = handler.handler.getFirst(); Label e = handler.end.getFirst(); // computes the kind of the edges to 'h' String t = handler.desc == null ? "java/lang/Throwable" : handler.desc; int kind = Frame.OBJECT | cw.addType(t); // h is an exception handler h.status |= Label.TARGET; // adds 'h' as a successor of labels between 'start' and 'end' while (l != e) { // creates an edge to 'h' Edge b = new Edge(); b.info = kind; b.successor = h; // adds it to the successors of 'l' b.next = l.successors; l.successors = b; // goes to the next label l = l.successor; } handler = handler.next; } // creates and visits the first (implicit) frame Frame f = labels.frame; Type[] args = Type.getArgumentTypes(descriptor); f.initInputFrame(cw, access, args, this.maxLocals); visitFrame(f); /* * fix point algorithm: mark the first basic block as 'changed' * (i.e. put it in the 'changed' list) and, while there are changed * basic blocks, choose one, mark it as unchanged, and update its * successors (which can be changed in the process). */ int max = 0; Label changed = labels; while (changed != null) { // removes a basic block from the list of changed basic blocks Label l = changed; changed = changed.next; l.next = null; f = l.frame; // a reachable jump target must be stored in the stack map if ((l.status & Label.TARGET) != 0) { l.status |= Label.STORE; } // all visited labels are reachable, by definition l.status |= Label.REACHABLE; // updates the (absolute) maximum stack size int blockMax = f.inputStack.length + l.outputStackMax; if (blockMax > max) { max = blockMax; } // updates the successors of the current basic block Edge e = l.successors; while (e != null) { Label n = e.successor.getFirst(); boolean change = f.merge(cw, n.frame, e.info); if (change && n.next == null) { // if n has changed and is not already in the 'changed' // list, adds it to this list n.next = changed; changed = n; } e = e.next; } } // visits all the frames that must be stored in the stack map Label l = labels; while (l != null) { f = l.frame; if ((l.status & Label.STORE) != 0) { visitFrame(f); } if ((l.status & Label.REACHABLE) == 0) { // finds start and end of dead basic block Label k = l.successor; int start = l.position; int end = (k == null ? code.length : k.position) - 1; // if non empty basic block if (end >= start) { max = Math.max(max, 1); // replaces instructions with NOP ... NOP ATHROW for (int i = start; i < end; ++i) { code.data[i] = Opcodes.NOP; } code.data[end] = (byte) Opcodes.ATHROW; // emits a frame for this unreachable block int frameIndex = startFrame(start, 0, 1); frame[frameIndex] = Frame.OBJECT | cw.addType("java/lang/Throwable"); endFrame(); // removes the start-end range from the exception // handlers firstHandler = Handler.remove(firstHandler, l, k); } } l = l.successor; } handler = firstHandler; handlerCount = 0; while (handler != null) { handlerCount += 1; handler = handler.next; } this.maxStack = max; } else if (compute == MAXS) { // completes the control flow graph with exception handler blocks Handler handler = firstHandler; while (handler != null) { Label l = handler.start; Label h = handler.handler; Label e = handler.end; // adds 'h' as a successor of labels between 'start' and 'end' while (l != e) { // creates an edge to 'h' Edge b = new Edge(); b.info = Edge.EXCEPTION; b.successor = h; // adds it to the successors of 'l' if ((l.status & Label.JSR) == 0) { b.next = l.successors; l.successors = b; } else { // if l is a JSR block, adds b after the first two edges // to preserve the hypothesis about JSR block successors // order (see {@link #visitJumpInsn}) b.next = l.successors.next.next; l.successors.next.next = b; } // goes to the next label l = l.successor; } handler = handler.next; } if (subroutines > 0) { // completes the control flow graph with the RET successors /* * first step: finds the subroutines. This step determines, for * each basic block, to which subroutine(s) it belongs. */ // finds the basic blocks that belong to the "main" subroutine int id = 0; labels.visitSubroutine(null, 1, subroutines); // finds the basic blocks that belong to the real subroutines Label l = labels; while (l != null) { if ((l.status & Label.JSR) != 0) { // the subroutine is defined by l's TARGET, not by l Label subroutine = l.successors.next.successor; // if this subroutine has not been visited yet... if ((subroutine.status & Label.VISITED) == 0) { // ...assigns it a new id and finds its basic blocks id += 1; subroutine.visitSubroutine(null, (id / 32L) << 32 | (1L << (id % 32)), subroutines); } } l = l.successor; } // second step: finds the successors of RET blocks l = labels; while (l != null) { if ((l.status & Label.JSR) != 0) { Label L = labels; while (L != null) { L.status &= ~Label.VISITED2; L = L.successor; } // the subroutine is defined by l's TARGET, not by l Label subroutine = l.successors.next.successor; subroutine.visitSubroutine(l, 0, subroutines); } l = l.successor; } } /* * control flow analysis algorithm: while the block stack is not * empty, pop a block from this stack, update the max stack size, * compute the true (non relative) begin stack size of the * successors of this block, and push these successors onto the * stack (unless they have already been pushed onto the stack). * Note: by hypothesis, the {@link Label#inputStackTop} of the * blocks in the block stack are the true (non relative) beginning * stack sizes of these blocks. */ int max = 0; Label stack = labels; while (stack != null) { // pops a block from the stack Label l = stack; stack = stack.next; // computes the true (non relative) max stack size of this block int start = l.inputStackTop; int blockMax = start + l.outputStackMax; // updates the global max stack size if (blockMax > max) { max = blockMax; } // analyzes the successors of the block Edge b = l.successors; if ((l.status & Label.JSR) != 0) { // ignores the first edge of JSR blocks (virtual successor) b = b.next; } while (b != null) { l = b.successor; // if this successor has not already been pushed... if ((l.status & Label.PUSHED) == 0) { // computes its true beginning stack size... l.inputStackTop = b.info == Edge.EXCEPTION ? 1 : start + b.info; // ...and pushes it onto the stack l.status |= Label.PUSHED; l.next = stack; stack = l; } b = b.next; } } this.maxStack = Math.max(maxStack, max); } else { this.maxStack = maxStack; this.maxLocals = maxLocals; } } @Override public void visitEnd() { } // ------------------------------------------------------------------------ // Utility methods: control flow analysis algorithm // ------------------------------------------------------------------------ /** * Adds a successor to the {@link #currentBlock currentBlock} block. * * @param info * information about the control flow edge to be added. * @param successor * the successor block to be added to the current block. */ private void addSuccessor(final int info, final Label successor) { // creates and initializes an Edge object... Edge b = new Edge(); b.info = info; b.successor = successor; // ...and adds it to the successor list of the currentBlock block b.next = currentBlock.successors; currentBlock.successors = b; } /** * Ends the current basic block. This method must be used in the case where * the current basic block does not have any successor. */ private void noSuccessor() { if (compute == FRAMES) { Label l = new Label(); l.frame = new Frame(); l.frame.owner = l; l.resolve(this, code.length, code.data); previousBlock.successor = l; previousBlock = l; } else { currentBlock.outputStackMax = maxStackSize; } currentBlock = null; } // ------------------------------------------------------------------------ // Utility methods: stack map frames // ------------------------------------------------------------------------ /** * Visits a frame that has been computed from scratch. * * @param f * the frame that must be visited. */ private void visitFrame(final Frame f) { int i, t; int nTop = 0; int nLocal = 0; int nStack = 0; int[] locals = f.inputLocals; int[] stacks = f.inputStack; // computes the number of locals (ignores TOP types that are just after // a LONG or a DOUBLE, and all trailing TOP types) for (i = 0; i < locals.length; ++i) { t = locals[i]; if (t == Frame.TOP) { ++nTop; } else { nLocal += nTop + 1; nTop = 0; } if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } // computes the stack size (ignores TOP types that are just after // a LONG or a DOUBLE) for (i = 0; i < stacks.length; ++i) { t = stacks[i]; ++nStack; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } // visits the frame and its content int frameIndex = startFrame(f.owner.position, nLocal, nStack); for (i = 0; nLocal > 0; ++i, --nLocal) { t = locals[i]; frame[frameIndex++] = t; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } for (i = 0; i < stacks.length; ++i) { t = stacks[i]; frame[frameIndex++] = t; if (t == Frame.LONG || t == Frame.DOUBLE) { ++i; } } endFrame(); } /** * Visit the implicit first frame of this method. */ private void visitImplicitFirstFrame() { // There can be at most descriptor.length() + 1 locals int frameIndex = startFrame(0, descriptor.length() + 1, 0); if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & ACC_CONSTRUCTOR) == 0) { frame[frameIndex++] = Frame.OBJECT | cw.addType(cw.thisName); } else { frame[frameIndex++] = 6; // Opcodes.UNINITIALIZED_THIS; } } int i = 1; loop: while (true) { int j = i; switch (descriptor.charAt(i++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': frame[frameIndex++] = 1; // Opcodes.INTEGER; break; case 'F': frame[frameIndex++] = 2; // Opcodes.FLOAT; break; case 'J': frame[frameIndex++] = 4; // Opcodes.LONG; break; case 'D': frame[frameIndex++] = 3; // Opcodes.DOUBLE; break; case '[': while (descriptor.charAt(i) == '[') { ++i; } if (descriptor.charAt(i) == 'L') { ++i; while (descriptor.charAt(i) != ';') { ++i; } } frame[frameIndex++] = Frame.OBJECT | cw.addType(descriptor.substring(j, ++i)); break; case 'L': while (descriptor.charAt(i) != ';') { ++i; } frame[frameIndex++] = Frame.OBJECT | cw.addType(descriptor.substring(j + 1, i++)); break; default: break loop; } } frame[1] = frameIndex - 3; endFrame(); } /** * Starts the visit of a stack map frame. * * @param offset * the offset of the instruction to which the frame corresponds. * @param nLocal * the number of local variables in the frame. * @param nStack * the number of stack elements in the frame. * @return the index of the next element to be written in this frame. */ private int startFrame(final int offset, final int nLocal, final int nStack) { int n = 3 + nLocal + nStack; if (frame == null || frame.length < n) { frame = new int[n]; } frame[0] = offset; frame[1] = nLocal; frame[2] = nStack; return 3; } /** * Checks if the visit of the current frame {@link #frame} is finished, and * if yes, write it in the StackMapTable attribute. */ private void endFrame() { if (previousFrame != null) { // do not write the first frame if (stackMap == null) { stackMap = new ByteVector(); } writeFrame(); ++frameCount; } previousFrame = frame; frame = null; } /** * Compress and writes the current frame {@link #frame} in the StackMapTable * attribute. */ private void writeFrame() { int clocalsSize = frame[1]; int cstackSize = frame[2]; if ((cw.version & 0xFFFF) < Opcodes.V1_6) { stackMap.putShort(frame[0]).putShort(clocalsSize); writeFrameTypes(3, 3 + clocalsSize); stackMap.putShort(cstackSize); writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize); return; } int localsSize = previousFrame[1]; int type = FULL_FRAME; int k = 0; int delta; if (frameCount == 0) { delta = frame[0]; } else { delta = frame[0] - previousFrame[0] - 1; } if (cstackSize == 0) { k = clocalsSize - localsSize; switch (k) { case -3: case -2: case -1: type = CHOP_FRAME; localsSize = clocalsSize; break; case 0: type = delta < 64 ? SAME_FRAME : SAME_FRAME_EXTENDED; break; case 1: case 2: case 3: type = APPEND_FRAME; break; } } else if (clocalsSize == localsSize && cstackSize == 1) { type = delta < 63 ? SAME_LOCALS_1_STACK_ITEM_FRAME : SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED; } if (type != FULL_FRAME) { // verify if locals are the same int l = 3; for (int j = 0; j < localsSize; j++) { if (frame[l] != previousFrame[l]) { type = FULL_FRAME; break; } l++; } } switch (type) { case SAME_FRAME: stackMap.putByte(delta); break; case SAME_LOCALS_1_STACK_ITEM_FRAME: stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME + delta); writeFrameTypes(3 + clocalsSize, 4 + clocalsSize); break; case SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED: stackMap.putByte(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED).putShort( delta); writeFrameTypes(3 + clocalsSize, 4 + clocalsSize); break; case SAME_FRAME_EXTENDED: stackMap.putByte(SAME_FRAME_EXTENDED).putShort(delta); break; case CHOP_FRAME: stackMap.putByte(SAME_FRAME_EXTENDED + k).putShort(delta); break; case APPEND_FRAME: stackMap.putByte(SAME_FRAME_EXTENDED + k).putShort(delta); writeFrameTypes(3 + localsSize, 3 + clocalsSize); break; // case FULL_FRAME: default: stackMap.putByte(FULL_FRAME).putShort(delta).putShort(clocalsSize); writeFrameTypes(3, 3 + clocalsSize); stackMap.putShort(cstackSize); writeFrameTypes(3 + clocalsSize, 3 + clocalsSize + cstackSize); } } /** * Writes some types of the current frame {@link #frame} into the * StackMapTableAttribute. This method converts types from the format used * in {@link Label} to the format used in StackMapTable attributes. In * particular, it converts type table indexes to constant pool indexes. * * @param start * index of the first type in {@link #frame} to write. * @param end * index of last type in {@link #frame} to write (exclusive). */ private void writeFrameTypes(final int start, final int end) { for (int i = start; i < end; ++i) { int t = frame[i]; int d = t & Frame.DIM; if (d == 0) { int v = t & Frame.BASE_VALUE; switch (t & Frame.BASE_KIND) { case Frame.OBJECT: stackMap.putByte(7).putShort( cw.newClass(cw.typeTable[v].strVal1)); break; case Frame.UNINITIALIZED: stackMap.putByte(8).putShort(cw.typeTable[v].intVal); break; default: stackMap.putByte(v); } } else { StringBuilder sb = new StringBuilder(); d >>= 28; while (d-- > 0) { sb.append('['); } if ((t & Frame.BASE_KIND) == Frame.OBJECT) { sb.append('L'); sb.append(cw.typeTable[t & Frame.BASE_VALUE].strVal1); sb.append(';'); } else { switch (t & 0xF) { case 1: sb.append('I'); break; case 2: sb.append('F'); break; case 3: sb.append('D'); break; case 9: sb.append('Z'); break; case 10: sb.append('B'); break; case 11: sb.append('C'); break; case 12: sb.append('S'); break; default: sb.append('J'); } } stackMap.putByte(7).putShort(cw.newClass(sb.toString())); } } } private void writeFrameType(final Object type) { if (type instanceof String) { stackMap.putByte(7).putShort(cw.newClass((String) type)); } else if (type instanceof Integer) { stackMap.putByte(((Integer) type).intValue()); } else { stackMap.putByte(8).putShort(((Label) type).position); } } // ------------------------------------------------------------------------ // Utility methods: dump bytecode array // ------------------------------------------------------------------------ /** * Returns the size of the bytecode of this method. * * @return the size of the bytecode of this method. */ final int getSize() { if (classReaderOffset != 0) { return 6 + classReaderLength; } int size = 8; if (code.length > 0) { if (code.length > 65536) { throw new RuntimeException("Method code too large!"); } cw.newUTF8("Code"); size += 18 + code.length + 8 * handlerCount; if (localVar != null) { cw.newUTF8("LocalVariableTable"); size += 8 + localVar.length; } if (localVarType != null) { cw.newUTF8("LocalVariableTypeTable"); size += 8 + localVarType.length; } if (lineNumber != null) { cw.newUTF8("LineNumberTable"); size += 8 + lineNumber.length; } if (stackMap != null) { boolean zip = (cw.version & 0xFFFF) >= Opcodes.V1_6; cw.newUTF8(zip ? "StackMapTable" : "StackMap"); size += 8 + stackMap.length; } if (ClassReader.ANNOTATIONS && ctanns != null) { cw.newUTF8("RuntimeVisibleTypeAnnotations"); size += 8 + ctanns.getSize(); } if (ClassReader.ANNOTATIONS && ictanns != null) { cw.newUTF8("RuntimeInvisibleTypeAnnotations"); size += 8 + ictanns.getSize(); } if (cattrs != null) { size += cattrs.getSize(cw, code.data, code.length, maxStack, maxLocals); } } if (exceptionCount > 0) { cw.newUTF8("Exceptions"); size += 8 + 2 * exceptionCount; } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { if ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0) { cw.newUTF8("Synthetic"); size += 6; } } if ((access & Opcodes.ACC_DEPRECATED) != 0) { cw.newUTF8("Deprecated"); size += 6; } if (ClassReader.SIGNATURES && signature != null) { cw.newUTF8("Signature"); cw.newUTF8(signature); size += 8; } if (methodParameters != null) { cw.newUTF8("MethodParameters"); size += 7 + methodParameters.length; } if (ClassReader.ANNOTATIONS && annd != null) { cw.newUTF8("AnnotationDefault"); size += 6 + annd.length; } if (ClassReader.ANNOTATIONS && anns != null) { cw.newUTF8("RuntimeVisibleAnnotations"); size += 8 + anns.getSize(); } if (ClassReader.ANNOTATIONS && ianns != null) { cw.newUTF8("RuntimeInvisibleAnnotations"); size += 8 + ianns.getSize(); } if (ClassReader.ANNOTATIONS && tanns != null) { cw.newUTF8("RuntimeVisibleTypeAnnotations"); size += 8 + tanns.getSize(); } if (ClassReader.ANNOTATIONS && itanns != null) { cw.newUTF8("RuntimeInvisibleTypeAnnotations"); size += 8 + itanns.getSize(); } if (ClassReader.ANNOTATIONS && panns != null) { cw.newUTF8("RuntimeVisibleParameterAnnotations"); size += 7 + 2 * (panns.length - synthetics); for (int i = panns.length - 1; i >= synthetics; --i) { size += panns[i] == null ? 0 : panns[i].getSize(); } } if (ClassReader.ANNOTATIONS && ipanns != null) { cw.newUTF8("RuntimeInvisibleParameterAnnotations"); size += 7 + 2 * (ipanns.length - synthetics); for (int i = ipanns.length - 1; i >= synthetics; --i) { size += ipanns[i] == null ? 0 : ipanns[i].getSize(); } } if (attrs != null) { size += attrs.getSize(cw, null, 0, -1, -1); } return size; } /** * Puts the bytecode of this method in the given byte vector. * * @param out * the byte vector into which the bytecode of this method must be * copied. */ final void put(final ByteVector out) { final int FACTOR = ClassWriter.TO_ACC_SYNTHETIC; int mask = ACC_CONSTRUCTOR | Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / FACTOR); out.putShort(access & ~mask).putShort(name).putShort(desc); if (classReaderOffset != 0) { out.putByteArray(cw.cr.b, classReaderOffset, classReaderLength); return; } int attributeCount = 0; if (code.length > 0) { ++attributeCount; } if (exceptionCount > 0) { ++attributeCount; } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { if ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0) { ++attributeCount; } } if ((access & Opcodes.ACC_DEPRECATED) != 0) { ++attributeCount; } if (ClassReader.SIGNATURES && signature != null) { ++attributeCount; } if (methodParameters != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && annd != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && anns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ianns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && tanns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && itanns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && panns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ipanns != null) { ++attributeCount; } if (attrs != null) { attributeCount += attrs.getCount(); } out.putShort(attributeCount); if (code.length > 0) { int size = 12 + code.length + 8 * handlerCount; if (localVar != null) { size += 8 + localVar.length; } if (localVarType != null) { size += 8 + localVarType.length; } if (lineNumber != null) { size += 8 + lineNumber.length; } if (stackMap != null) { size += 8 + stackMap.length; } if (ClassReader.ANNOTATIONS && ctanns != null) { size += 8 + ctanns.getSize(); } if (ClassReader.ANNOTATIONS && ictanns != null) { size += 8 + ictanns.getSize(); } if (cattrs != null) { size += cattrs.getSize(cw, code.data, code.length, maxStack, maxLocals); } out.putShort(cw.newUTF8("Code")).putInt(size); out.putShort(maxStack).putShort(maxLocals); out.putInt(code.length).putByteArray(code.data, 0, code.length); out.putShort(handlerCount); if (handlerCount > 0) { Handler h = firstHandler; while (h != null) { out.putShort(h.start.position).putShort(h.end.position) .putShort(h.handler.position).putShort(h.type); h = h.next; } } attributeCount = 0; if (localVar != null) { ++attributeCount; } if (localVarType != null) { ++attributeCount; } if (lineNumber != null) { ++attributeCount; } if (stackMap != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ctanns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ictanns != null) { ++attributeCount; } if (cattrs != null) { attributeCount += cattrs.getCount(); } out.putShort(attributeCount); if (localVar != null) { out.putShort(cw.newUTF8("LocalVariableTable")); out.putInt(localVar.length + 2).putShort(localVarCount); out.putByteArray(localVar.data, 0, localVar.length); } if (localVarType != null) { out.putShort(cw.newUTF8("LocalVariableTypeTable")); out.putInt(localVarType.length + 2).putShort(localVarTypeCount); out.putByteArray(localVarType.data, 0, localVarType.length); } if (lineNumber != null) { out.putShort(cw.newUTF8("LineNumberTable")); out.putInt(lineNumber.length + 2).putShort(lineNumberCount); out.putByteArray(lineNumber.data, 0, lineNumber.length); } if (stackMap != null) { boolean zip = (cw.version & 0xFFFF) >= Opcodes.V1_6; out.putShort(cw.newUTF8(zip ? "StackMapTable" : "StackMap")); out.putInt(stackMap.length + 2).putShort(frameCount); out.putByteArray(stackMap.data, 0, stackMap.length); } if (ClassReader.ANNOTATIONS && ctanns != null) { out.putShort(cw.newUTF8("RuntimeVisibleTypeAnnotations")); ctanns.put(out); } if (ClassReader.ANNOTATIONS && ictanns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleTypeAnnotations")); ictanns.put(out); } if (cattrs != null) { cattrs.put(cw, code.data, code.length, maxLocals, maxStack, out); } } if (exceptionCount > 0) { out.putShort(cw.newUTF8("Exceptions")).putInt( 2 * exceptionCount + 2); out.putShort(exceptionCount); for (int i = 0; i < exceptionCount; ++i) { out.putShort(exceptions[i]); } } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { if ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0) { out.putShort(cw.newUTF8("Synthetic")).putInt(0); } } if ((access & Opcodes.ACC_DEPRECATED) != 0) { out.putShort(cw.newUTF8("Deprecated")).putInt(0); } if (ClassReader.SIGNATURES && signature != null) { out.putShort(cw.newUTF8("Signature")).putInt(2) .putShort(cw.newUTF8(signature)); } if (methodParameters != null) { out.putShort(cw.newUTF8("MethodParameters")); out.putInt(methodParameters.length + 1).putByte( methodParametersCount); out.putByteArray(methodParameters.data, 0, methodParameters.length); } if (ClassReader.ANNOTATIONS && annd != null) { out.putShort(cw.newUTF8("AnnotationDefault")); out.putInt(annd.length); out.putByteArray(annd.data, 0, annd.length); } if (ClassReader.ANNOTATIONS && anns != null) { out.putShort(cw.newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ClassReader.ANNOTATIONS && ianns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (ClassReader.ANNOTATIONS && tanns != null) { out.putShort(cw.newUTF8("RuntimeVisibleTypeAnnotations")); tanns.put(out); } if (ClassReader.ANNOTATIONS && itanns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleTypeAnnotations")); itanns.put(out); } if (ClassReader.ANNOTATIONS && panns != null) { out.putShort(cw.newUTF8("RuntimeVisibleParameterAnnotations")); AnnotationWriter.put(panns, synthetics, out); } if (ClassReader.ANNOTATIONS && ipanns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleParameterAnnotations")); AnnotationWriter.put(ipanns, synthetics, out); } if (attrs != null) { attrs.put(cw, null, 0, -1, -1, out); } } // ------------------------------------------------------------------------ // Utility methods: instruction resizing (used to handle GOTO_W and JSR_W) // ------------------------------------------------------------------------ /** * Resizes and replaces the temporary instructions inserted by * {@link Label#resolve} for wide forward jumps, while keeping jump offsets * and instruction addresses consistent. This may require to resize other * existing instructions, or even to introduce new instructions: for * example, increasing the size of an instruction by 2 at the middle of a * method can increases the offset of an IFEQ instruction from 32766 to * 32768, in which case IFEQ 32766 must be replaced with IFNEQ 8 GOTO_W * 32765. This, in turn, may require to increase the size of another jump * instruction, and so on... All these operations are handled automatically * by this method. * <p> * <i>This method must be called after all the method that is being built * has been visited</i>. In particular, the {@link Label Label} objects used * to construct the method are no longer valid after this method has been * called. */ private void resizeInstructions() { byte[] b = code.data; // bytecode of the method int u, v, label; // indexes in b int i, j; // loop indexes /* * 1st step: As explained above, resizing an instruction may require to * resize another one, which may require to resize yet another one, and * so on. The first step of the algorithm consists in finding all the * instructions that need to be resized, without modifying the code. * This is done by the following "fix point" algorithm: * * Parse the code to find the jump instructions whose offset will need * more than 2 bytes to be stored (the future offset is computed from * the current offset and from the number of bytes that will be inserted * or removed between the srccode and target instructions). For each such * instruction, adds an entry in (a copy of) the indexes and sizes * arrays (if this has not already been done in a previous iteration!). * * If at least one entry has been added during the previous step, go * back to the beginning, otherwise stop. * * In fact the real algorithm is complicated by the fact that the size * of TABLESWITCH and LOOKUPSWITCH instructions depends on their * position in the bytecode (because of padding). In order to ensure the * convergence of the algorithm, the number of bytes to be added or * removed from these instructions is over estimated during the previous * loop, and computed exactly only after the loop is finished (this * requires another pass to parse the bytecode of the method). */ int[] allIndexes = new int[0]; // copy of indexes int[] allSizes = new int[0]; // copy of sizes boolean[] resize; // instructions to be resized int newOffset; // future offset of a jump instruction resize = new boolean[code.length]; // 3 = loop again, 2 = loop ended, 1 = last pass, 0 = done int state = 3; do { if (state == 3) { state = 2; } u = 0; while (u < b.length) { int opcode = b[u] & 0xFF; // opcode of current instruction int insert = 0; // bytes to be added after this instruction switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // converts temporary opcodes 202 to 217, 218 and // 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (newOffset < Short.MIN_VALUE || newOffset > Short.MAX_VALUE) { if (!resize[u]) { if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { // two additional bytes will be required to // replace this GOTO or JSR instruction with // a GOTO_W or a JSR_W insert = 2; } else { // five additional bytes will be required to // replace this IFxxx <l> instruction with // IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx // is the "opposite" opcode of IFxxx (i.e., // IFNE for IFEQ) and where <l'> designates // the instruction just after the GOTO_W. insert = 5; } resize[u] = true; } } u += 3; break; case ClassWriter.LABELW_INSN: u += 5; break; case ClassWriter.TABL_INSN: if (state == 1) { // true number of bytes to be added (or removed) // from this instruction = (future number of padding // bytes - current number of padding byte) - // previously over estimated variation = // = ((3 - newOffset%4) - (3 - u%4)) - u%4 // = (-newOffset%4 + u%4) - u%4 // = -(newOffset & 3) newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // over estimation of the number of bytes to be // added to this instruction = 3 - current number // of padding bytes = 3 - (3 - u%4) = u%4 = u & 3 insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 4 * (readInt(b, u + 8) - readInt(b, u + 4) + 1) + 12; break; case ClassWriter.LOOK_INSN: if (state == 1) { // like TABL_INSN newOffset = getNewOffset(allIndexes, allSizes, 0, u); insert = -(newOffset & 3); } else if (!resize[u]) { // like TABL_INSN insert = u & 3; resize[u] = true; } // skips instruction u = u + 4 - (u & 3); u += 8 * readInt(b, u + 4) + 8; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case ClassWriter.MANA_INSN: default: u += 4; break; } if (insert != 0) { // adds a new (u, insert) entry in the allIndexes and // allSizes arrays int[] newIndexes = new int[allIndexes.length + 1]; int[] newSizes = new int[allSizes.length + 1]; System.arraycopy(allIndexes, 0, newIndexes, 0, allIndexes.length); System.arraycopy(allSizes, 0, newSizes, 0, allSizes.length); newIndexes[allIndexes.length] = u; newSizes[allSizes.length] = insert; allIndexes = newIndexes; allSizes = newSizes; if (insert > 0) { state = 3; } } } if (state < 3) { --state; } } while (state != 0); // 2nd step: // copies the bytecode of the method into a new bytevector, updates the // offsets, and inserts (or removes) bytes as requested. ByteVector newCode = new ByteVector(code.length); u = 0; while (u < code.length) { int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: newCode.putByte(opcode); u += 1; break; case ClassWriter.LABEL_INSN: if (opcode > 201) { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; label = u + readUnsignedShort(b, u + 1); } else { label = u + readShort(b, u + 1); } newOffset = getNewOffset(allIndexes, allSizes, u, label); if (resize[u]) { // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // <l> with IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where <l'> designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO) { newCode.putByte(200); // GOTO_W } else if (opcode == Opcodes.JSR) { newCode.putByte(201); // JSR_W } else { newCode.putByte(opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1); newCode.putShort(8); // jump offset newCode.putByte(200); // GOTO_W // newOffset now computed from start of GOTO_W newOffset -= 3; } newCode.putInt(newOffset); } else { newCode.putByte(opcode); newCode.putShort(newOffset); } u += 3; break; case ClassWriter.LABELW_INSN: label = u + readInt(b, u + 1); newOffset = getNewOffset(allIndexes, allSizes, u, label); newCode.putByte(opcode); newCode.putInt(newOffset); u += 5; break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.TABLESWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); j = readInt(b, u) - j + 1; u += 4; newCode.putInt(readInt(b, u - 4)); for (; j > 0; --j) { label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes v = u; u = u + 4 - (v & 3); // reads and copies instruction newCode.putByte(Opcodes.LOOKUPSWITCH); newCode.putByteArray(null, 0, (4 - newCode.length % 4) % 4); label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); j = readInt(b, u); u += 4; newCode.putInt(j); for (; j > 0; --j) { newCode.putInt(readInt(b, u)); u += 4; label = v + readInt(b, u); u += 4; newOffset = getNewOffset(allIndexes, allSizes, v, label); newCode.putInt(newOffset); } break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { newCode.putByteArray(b, u, 6); u += 6; } else { newCode.putByteArray(b, u, 4); u += 4; } break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: newCode.putByteArray(b, u, 2); u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: newCode.putByteArray(b, u, 3); u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: newCode.putByteArray(b, u, 5); u += 5; break; // case MANA_INSN: default: newCode.putByteArray(b, u, 4); u += 4; break; } } // updates the stack map frame labels if (compute == FRAMES) { Label l = labels; while (l != null) { /* * Detects the labels that are just after an IF instruction that * has been resized with the IFNOT GOTO_W pattern. These labels * are now the target of a jump instruction (the IFNOT * instruction). Note that we need the original label position * here. getNewOffset must therefore never have been called for * this label. */ u = l.position - 3; if (u >= 0 && resize[u]) { l.status |= Label.TARGET; } getNewOffset(allIndexes, allSizes, l); l = l.successor; } // Update the offsets in the uninitialized types for (i = 0; i < cw.typeTable.length; ++i) { Item item = cw.typeTable[i]; if (item != null && item.type == ClassWriter.TYPE_UNINIT) { item.intVal = getNewOffset(allIndexes, allSizes, 0, item.intVal); } } // The stack map frames are not serialized yet, so we don't need // to update them. They will be serialized in visitMaxs. } else if (frameCount > 0) { /* * Resizing an existing stack map frame table is really hard. Not * only the table must be parsed to update the offets, but new * frames may be needed for jump instructions that were inserted by * this method. And updating the offsets or inserting frames can * change the format of the following frames, in case of packed * frames. In practice the whole table must be recomputed. For this * the frames are marked as potentially invalid. This will cause the * whole class to be reread and rewritten with the COMPUTE_FRAMES * option (see the ClassWriter.toByteArray method). This is not very * efficient but is much easier and requires much less code than any * other method I can think of. */ cw.invalidFrames = true; } // updates the exception handler block labels Handler h = firstHandler; while (h != null) { getNewOffset(allIndexes, allSizes, h.start); getNewOffset(allIndexes, allSizes, h.end); getNewOffset(allIndexes, allSizes, h.handler); h = h.next; } // updates the instructions addresses in the // local var and line number tables for (i = 0; i < 2; ++i) { ByteVector bv = i == 0 ? localVar : localVarType; if (bv != null) { b = bv.data; u = 0; while (u < bv.length) { label = readUnsignedShort(b, u); newOffset = getNewOffset(allIndexes, allSizes, 0, label); writeShort(b, u, newOffset); label += readUnsignedShort(b, u + 2); newOffset = getNewOffset(allIndexes, allSizes, 0, label) - newOffset; writeShort(b, u + 2, newOffset); u += 10; } } } if (lineNumber != null) { b = lineNumber.data; u = 0; while (u < lineNumber.length) { writeShort( b, u, getNewOffset(allIndexes, allSizes, 0, readUnsignedShort(b, u))); u += 4; } } // updates the labels of the other attributes Attribute attr = cattrs; while (attr != null) { Label[] labels = attr.getLabels(); if (labels != null) { for (i = labels.length - 1; i >= 0; --i) { getNewOffset(allIndexes, allSizes, labels[i]); } } attr = attr.next; } // replaces old bytecodes with new ones code = newCode; } /** * Reads an unsigned short value in the given byte array. * * @param b * a byte array. * @param index * the start index of the value to be read. * @return the read value. */ static int readUnsignedShort(final byte[] b, final int index) { return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF); } /** * Reads a signed short value in the given byte array. * * @param b * a byte array. * @param index * the start index of the value to be read. * @return the read value. */ static short readShort(final byte[] b, final int index) { return (short) (((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF)); } /** * Reads a signed int value in the given byte array. * * @param b * a byte array. * @param index * the start index of the value to be read. * @return the read value. */ static int readInt(final byte[] b, final int index) { return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16) | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF); } /** * Writes a short value in the given byte array. * * @param b * a byte array. * @param index * where the first byte of the short value must be written. * @param s * the value to be written in the given byte array. */ static void writeShort(final byte[] b, final int index, final int s) { b[index] = (byte) (s >>> 8); b[index + 1] = (byte) s; } /** * Computes the future value of a bytecode offset. * <p> * Note: it is possible to have several entries for the same instruction in * the <tt>indexes</tt> and <tt>sizes</tt>: two entries (index=a,size=b) and * (index=a,size=b') are equivalent to a single entry (index=a,size=b+b'). * * @param indexes * current positions of the instructions to be resized. Each * instruction must be designated by the index of its <i>last</i> * byte, plus one (or, in other words, by the index of the * <i>first</i> byte of the <i>next</i> instruction). * @param sizes * the number of bytes to be <i>added</i> to the above * instructions. More precisely, for each i < <tt>len</tt>, * <tt>sizes</tt>[i] bytes will be added at the end of the * instruction designated by <tt>indexes</tt>[i] or, if * <tt>sizes</tt>[i] is negative, the <i>last</i> | * <tt>sizes[i]</tt>| bytes of the instruction will be removed * (the instruction size <i>must not</i> become negative or * null). * @param begin * index of the first byte of the srccode instruction. * @param end * index of the first byte of the target instruction. * @return the future value of the given bytecode offset. */ static int getNewOffset(final int[] indexes, final int[] sizes, final int begin, final int end) { int offset = end - begin; for (int i = 0; i < indexes.length; ++i) { if (begin < indexes[i] && indexes[i] <= end) { // forward jump offset += sizes[i]; } else if (end < indexes[i] && indexes[i] <= begin) { // backward jump offset -= sizes[i]; } } return offset; } /** * Updates the offset of the given label. * * @param indexes * current positions of the instructions to be resized. Each * instruction must be designated by the index of its <i>last</i> * byte, plus one (or, in other words, by the index of the * <i>first</i> byte of the <i>next</i> instruction). * @param sizes * the number of bytes to be <i>added</i> to the above * instructions. More precisely, for each i < <tt>len</tt>, * <tt>sizes</tt>[i] bytes will be added at the end of the * instruction designated by <tt>indexes</tt>[i] or, if * <tt>sizes</tt>[i] is negative, the <i>last</i> | * <tt>sizes[i]</tt>| bytes of the instruction will be removed * (the instruction size <i>must not</i> become negative or * null). * @param label * the label whose offset must be updated. */ static void getNewOffset(final int[] indexes, final int[] sizes, final Label label) { if ((label.status & Label.RESIZED) == 0) { label.position = getNewOffset(indexes, sizes, 0, label.position); label.status |= Label.RESIZED; } } }
{ "content_hash": "2add13ceb370c3f4689d74310c031c0b", "timestamp": "", "source": "github", "line_count": 2887, "max_line_length": 117, "avg_line_length": 38.60027710426048, "alnum_prop": 0.47726558924613466, "repo_name": "actframework/act-asm", "id": "dfb0976d1d020496ee889663ee9c75850bc385ad", "size": "113099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/act/asm/MethodWriter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "23669" }, { "name": "Java", "bytes": "1626453" } ], "symlink_target": "" }
License ============ Copyright (c) 2010 Audrey Roy, Daniel Greenfeld, and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{ "content_hash": "dde00c3883938c7fa73afba380af7b19", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 66, "avg_line_length": 44.48, "alnum_prop": 0.7967625899280576, "repo_name": "cartwheelweb/packaginator", "id": "08da8aa9e01470c008578e8c37db0078a41713f9", "size": "1112", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/license.rst", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24198" }, { "name": "JavaScript", "bytes": "245128" }, { "name": "Perl", "bytes": "470" }, { "name": "Python", "bytes": "433671" } ], "symlink_target": "" }
namespace CloudOnce.Internal.Providers { using Internal; using UnityEngine; /// <summary> /// For testing cloud save in the editor /// </summary> public class TestProviderStorageWrapper : ICloudStorageProvider { private readonly CloudOnceEvents cloudOnceEvents; private bool isSynchronizing; public TestProviderStorageWrapper(CloudOnceEvents events) { cloudOnceEvents = events; } /// <summary> /// Saves all cloud variables, to both disk and cloud. /// If <see cref="Cloud.CloudSaveEnabled"/> is <c>false</c>, it will only save to disk. /// Skips saving if no variables have been changed. /// </summary> public void Save() { DataManager.SaveToDisk(); if (!TestProvider.Instance.CloudSaveInitialized || !Cloud.CloudSaveEnabled) { #if CLOUDONCE_DEBUG Debug.LogWarning(!TestProvider.Instance.CloudSaveInitialized ? "Cloud Save has not been initialized, skipping upload and only saving to disk." : "Cloud Save is currently disabled, skipping upload and only saving to disk."); #endif cloudOnceEvents.RaiseOnCloudSaveComplete(false); return; } #if CLOUDONCE_DEBUG Debug.Log("Simulating cloud save."); #endif cloudOnceEvents.RaiseOnCloudSaveComplete(true); } /// <summary> /// Loads any available cloud data (if signed in and cloud saving is enabled). /// </summary> public void Load() { if (!TestProvider.Instance.CloudSaveInitialized || !Cloud.CloudSaveEnabled) { #if CLOUDONCE_DEBUG Debug.LogWarning(!TestProvider.Instance.CloudSaveInitialized ? "Cloud Save has not been initialized, aborting cloud load." : "Cloud Save is currently disabled, aborting cloud load."); #endif cloudOnceEvents.RaiseOnCloudLoadComplete(false); return; } if (Cloud.IsSignedIn) { #if CLOUDONCE_DEBUG Debug.Log("Simulating cloud load."); #endif var changedKeys = DataManager.GetRandomKeysFromGameData(); if (changedKeys.Length > 0) { #if CLOUDONCE_DEBUG Debug.Log("Simulating new cloud values (randomized)."); #endif cloudOnceEvents.RaiseOnNewCloudValues(changedKeys); } cloudOnceEvents.RaiseOnCloudLoadComplete(true); } else { Debug.LogWarning("Attempted to load cloud data, but the local user is not signed in." + " Will try to re-initialize."); Cloud.Initialize(); cloudOnceEvents.RaiseOnCloudLoadComplete(false); } } /// <summary> /// Calls <see cref="Load"/> and then <see cref="Save"/> as soon as the Cloud load is complete. /// </summary> public void Synchronize() { if (isSynchronizing) { return; } isSynchronizing = true; Cloud.OnCloudLoadComplete += OnCloudLoadComplete; Load(); } /// <summary> /// Resets a Cloud variable to the default value. /// </summary> /// <param name="key">The unique identifier for the Cloud variable you want to reset.</param> /// <returns>Whether or not the variable was successfully reset.</returns> public bool ResetVariable(string key) { return DataManager.ResetCloudPref(key); } /// <summary> /// Deletes a specific Cloud variable from the Cloud. /// </summary> /// <param name="key">The unique identifier for the CloudPref you want to delete.</param> /// <returns> /// <c>true</c> if the CloudPref is found and deleted, <c>false</c> if the specified <paramref name="key"/> doesn't exist. /// </returns> public bool DeleteVariable(string key) { return DataManager.DeleteCloudPref(key); } /// <summary> /// Deletes all variables that exists in the cloud save, but have not been declared in the local data. /// Can be useful during development when variable names change, but use with caution. /// </summary> /// <returns>An array with the keys for the variables that was cleared.</returns> public string[] ClearUnusedVariables() { return DataManager.ClearStowawayVariablesFromGameData(); } /// <summary> /// WARNING! Deletes all cloud variables both locally and in the cloud (if logged into a cloud save service)! /// Should only be used during development, not in production builds. /// </summary> public void DeleteAll() { DataManager.DeleteAllCloudVariables(); } private void OnCloudLoadComplete(bool arg0) { Cloud.OnCloudLoadComplete -= OnCloudLoadComplete; Save(); isSynchronizing = false; } } } #endif
{ "content_hash": "e477a3fb8952bdd69992ae017cf6db61", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 130, "avg_line_length": 35.891891891891895, "alnum_prop": 0.5736069277108434, "repo_name": "Trollpants/CloudOnce", "id": "b20aaeb7967c6aeaa4d5714e2055322c13911cba", "size": "5630", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "source/PluginDev/Assets/Extensions/CloudOnce/Providers/TestProvider/TestProviderStorageWrapper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1897650" }, { "name": "Java", "bytes": "759" }, { "name": "Objective-C", "bytes": "1801" }, { "name": "Objective-C++", "bytes": "9650" } ], "symlink_target": "" }
namespace Java.Util.Concurrent { using System; public interface ICompletionService<T> { IFuture<T> Poll(); IFuture<T> Poll(TimeSpan timeout); IFuture<T> Submit(ICallable<T> task); IFuture<T> Submit(IRunnable task, T result); IFuture<T> Take(); } }
{ "content_hash": "8aaa850be561f8300c31f622e01e4331", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 52, "avg_line_length": 23.53846153846154, "alnum_prop": 0.6045751633986928, "repo_name": "Elders/Servo.NET", "id": "de64b88f1a9ac647a9abdf9bd5368a3bc1f0eb4f", "size": "308", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Java.Util.Concurrent/ICompletionService.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2489" }, { "name": "C#", "bytes": "916097" }, { "name": "Smalltalk", "bytes": "66982" } ], "symlink_target": "" }
package ru.nivanov.model; /** * Created by Nikolay Ivanov on 03.10.2017. */ public class Vacancy { private final String name; private final String url; private final String author; private final String authorUrl; private final long createDate; /** * Constructor. * @param name .. * @param url .. * @param author .. * @param createDate .. */ public Vacancy(String name, String url, String author, String authorUrl, long createDate) { this.name = name; this.url = url; this.author = author; this.authorUrl = authorUrl; this.createDate = createDate; } /** * Creation date getter. * @return .. */ public long getCreateDate() { return createDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Vacancy vacancy = (Vacancy) o; return getName().equals(vacancy.getName()) && getUrl().equals(vacancy.getUrl()) && getAuthor().equals( vacancy.getAuthor()) && getAuthorUrl().equals(vacancy.getAuthorUrl()); } /** * Name getter. * @return .. */ public String getName() { return name; } /** * Url getter. * @return .. */ public String getUrl() { return url; } /** * Author getter. * @return .. */ public String getAuthor() { return author; } /** * Author url getter. * @return .. */ public String getAuthorUrl() { return authorUrl; } @Override public int hashCode() { final int constant = 31; int result = getName().hashCode(); result = constant * result + getUrl().hashCode(); result = constant * result + getAuthor().hashCode(); result = constant * result + getAuthorUrl().hashCode(); return result; } }
{ "content_hash": "25d2cb61764a502bbb4e7ed7954bfbee", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 110, "avg_line_length": 21.45263157894737, "alnum_prop": 0.5333660451422964, "repo_name": "Piterski72/Java-a-to-z", "id": "59ff57e4a72f7965e9221bba4e2980fbd5da9d7b", "size": "2038", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_008/TestTask008/src/main/java/ru/nivanov/model/Vacancy.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "161" }, { "name": "HTML", "bytes": "16965" }, { "name": "Java", "bytes": "709698" }, { "name": "JavaScript", "bytes": "20318" }, { "name": "XSLT", "bytes": "591" } ], "symlink_target": "" }
This is a template to build desktop chatbot application. Inspired from https://github.com/AndreiD/make_yourself_a_bot ## Electron Basics: A basic Electron application needs just these files: - `package.json` - Points to the app's main file and lists its details and dependencies. - `main.js` - Starts the app and creates a browser window to render HTML. This is the app's **main process**. - `index.html` - A web page to render. This is the app's **renderer process**. You can learn more about each of these components within the [Quick Start Guide](http://electron.atom.io/docs/latest/tutorial/quick-start). ## To Use To clone and run this repository you'll need [Git](https://git-scm.com) and [Node.js](https://nodejs.org/en/download/) (which comes with [npm](http://npmjs.com)) installed on your computer. From your command line: Learn more about Electron and its API in the [documentation](http://electron.atom.io/docs/latest). ```bash # Clone this repository git clone https://github.com/thayumaanavan/electron-chatbot-template # Go into the repository cd electron-chatbot-template # Install dependencies and run the app npm install && npm start ``` #### License [Apache 2.0](LICENSE.md)
{ "content_hash": "b0ac783cf983f8d3a77981c73193869d", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 213, "avg_line_length": 41.48275862068966, "alnum_prop": 0.7481296758104738, "repo_name": "thayumaanavan/electron-chatbot-template", "id": "2bb8065f9735da96569b18ad8c3253f07c05e374", "size": "1232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5215" }, { "name": "HTML", "bytes": "1406" }, { "name": "JavaScript", "bytes": "10385" } ], "symlink_target": "" }
package org.springframework.security.web.server.header; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch * @since 5.0 */ public class XXssProtectionServerHttpHeadersWriterTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); HttpHeaders headers = this.exchange.getResponse().getHeaders(); XXssProtectionServerHttpHeadersWriter writer = new XXssProtectionServerHttpHeadersWriter(); @Test void setHeaderValueNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setHeaderValue(null)) .withMessage("headerValue cannot be null"); } @Test public void writeHeadersWhenNoHeadersThenWriteHeaders() { this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0"); } @Test public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() { String headerValue = "value"; this.headers.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, headerValue); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly(headerValue); } @Test void writeHeadersWhenDisabledThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.DISABLED); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0"); } @Test void writeHeadersWhenEnabledThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1"); } @Test void writeHeadersWhenEnabledModeBlockThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED_MODE_BLOCK); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)) .containsOnly("1 ; mode=block"); } }
{ "content_hash": "a9695b8696726d2ec3c2812a4dc6a34a", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 113, "avg_line_length": 37.608108108108105, "alnum_prop": 0.8167445203018325, "repo_name": "spring-projects/spring-security", "id": "a8e8624b78b90d5e1975a43b3f61965443de52c9", "size": "3404", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "web/src/test/java/org/springframework/security/web/server/header/XXssProtectionServerHttpHeadersWriterTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "16776" }, { "name": "Groovy", "bytes": "43860" }, { "name": "HTML", "bytes": "80" }, { "name": "Java", "bytes": "15778038" }, { "name": "JavaScript", "bytes": "10" }, { "name": "Kotlin", "bytes": "845348" }, { "name": "PLSQL", "bytes": "3180" }, { "name": "Python", "bytes": "129" }, { "name": "Ruby", "bytes": "7008" }, { "name": "Shell", "bytes": "811" }, { "name": "XSLT", "bytes": "2369" } ], "symlink_target": "" }
using DotNetNuke.Web.Api; using Satrabel.OpenContent.Components.Datasource; #endregion namespace Satrabel.OpenContent.Components { public class StructRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) { mapRouteManager.MapHttpRoute("OpenContent", "default", "{controller}/{action}", new[] { "Satrabel.OpenContent.Components", "Satrabel.OpenContent.Components.JpList", "Satrabel.OpenContent.Components.Rss" }); DataSourceManager.RegisterDataSources(); } } }
{ "content_hash": "d66dac88a2ccc0dd0e5d912f47a931ae", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 218, "avg_line_length": 31.11111111111111, "alnum_prop": 0.7196428571428571, "repo_name": "janjonas/OpenContent", "id": "f78bcb2c4583f39c00e111b1ebafbb61b8fde314", "size": "668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Components/OpenContentRouteMapper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "50468" }, { "name": "Batchfile", "bytes": "2012" }, { "name": "C#", "bytes": "623469" }, { "name": "CSS", "bytes": "129157" }, { "name": "GCC Machine Description", "bytes": "482" }, { "name": "HTML", "bytes": "74910" }, { "name": "JavaScript", "bytes": "7915133" }, { "name": "PowerShell", "bytes": "6772" }, { "name": "Ruby", "bytes": "1845" }, { "name": "Shell", "bytes": "1462" } ], "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="@drawable/delete_3_an" /> <item android:state_pressed="false" android:drawable="@drawable/delete_3"></item> </selector>
{ "content_hash": "bd536e3a3c1c827d3984431b007b4536", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 85, "avg_line_length": 48.5, "alnum_prop": 0.711340206185567, "repo_name": "bingo1118/Bees", "id": "2531e8f92351cec8d1e9914e4e9cca3cb25099f4", "size": "291", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/drawable/delete_defence_image_selector3.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1393954" } ], "symlink_target": "" }
package cat.ppicas.cleanarch.owm; import java.util.ArrayList; import java.util.List; import cat.ppicas.cleanarch.model.City; import cat.ppicas.cleanarch.model.CurrentWeatherPreview; import cat.ppicas.cleanarch.owm.model.OWMCurrentWeather; import cat.ppicas.cleanarch.owm.model.OWMCurrentWeatherList; import cat.ppicas.cleanarch.repository.CityRepository; public class OWMCityRepository implements CityRepository { private final OWMService mService; public OWMCityRepository(OWMService service) { mService = service; } @Override public City getCity(String cityId) { OWMCurrentWeather cw = mService.getCurrentWeatherByCityId(cityId); return createCityFromCityWeather(cw); } @Override public List<City> findCity(String name) { List<City> cities = new ArrayList<City>(); OWMCurrentWeatherList citiesWeather = mService.getCurrentWeatherByCityName(name); for (OWMCurrentWeather cw : citiesWeather.getList()) { cities.add(createCityFromCityWeather(cw)); } return cities; } private City createCityFromCityWeather(OWMCurrentWeather cw) { CurrentWeatherPreview weatherPreview = new CurrentWeatherPreview( cw.getCityId(), cw.getMain().getTemp()); City city = new City(cw.getCityId(), cw.getCityName(), cw.getSystem().getCountry(), weatherPreview); return city; } }
{ "content_hash": "8d83ce6a07e2b3536b51eea73521c596", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 89, "avg_line_length": 32, "alnum_prop": 0.7118055555555556, "repo_name": "ppicas/android-clean-architecture-mvp", "id": "1fb6abe42abe0453418e5888d29a926da81cf564", "size": "2059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/cat/ppicas/cleanarch/owm/OWMCityRepository.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "117368" } ], "symlink_target": "" }
/* * @author max */ package com.intellij.ui; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.util.text.StringUtil; import java.util.ArrayList; public class SearchTextFieldWithStoredHistory extends SearchTextField { private final String myPropertyName; public SearchTextFieldWithStoredHistory(final String propertyName) { myPropertyName = propertyName; reset(); } @Override public void addCurrentTextToHistory() { super.addCurrentTextToHistory(); PropertiesComponent.getInstance().setValue(myPropertyName, StringUtil.join(getHistory(), "\n")); } public void reset() { final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); final String history = propertiesComponent.getValue(myPropertyName); if (history != null) { final String[] items = history.split("\n"); ArrayList<String> result = new ArrayList<>(); for (String item : items) { if (item != null && item.length() > 0) { result.add(item); } } setHistory(result); } setSelectedItem(""); } }
{ "content_hash": "21ff01333cab6ba8b6c39d8271f5849c", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 100, "avg_line_length": 26.595238095238095, "alnum_prop": 0.6956132497761862, "repo_name": "consulo/consulo", "id": "65f4d11cc7f5a35f9d461b52db26dab8ad3a8c1d", "size": "1717", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/base/platform-api/src/main/java/com/intellij/ui/SearchTextFieldWithStoredHistory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "299" }, { "name": "C", "bytes": "52718" }, { "name": "C++", "bytes": "72795" }, { "name": "CMake", "bytes": "854" }, { "name": "CSS", "bytes": "64655" }, { "name": "Groovy", "bytes": "36006" }, { "name": "HTML", "bytes": "173780" }, { "name": "Java", "bytes": "64026758" }, { "name": "Lex", "bytes": "5909" }, { "name": "Objective-C", "bytes": "23787" }, { "name": "Python", "bytes": "3276" }, { "name": "SCSS", "bytes": "9782" }, { "name": "Shell", "bytes": "5689" }, { "name": "Thrift", "bytes": "1216" }, { "name": "XSLT", "bytes": "49230" } ], "symlink_target": "" }
using content::DomOperationNotificationDetails; using content::RenderViewHost; namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace PPAPITestMessageHandler::PPAPITestMessageHandler() { } TestMessageHandler::MessageResponse PPAPITestMessageHandler::HandleMessage( const std::string& json) { std::string trimmed; TrimString(json, "\"", &trimmed); if (trimmed == "...") { return CONTINUE; } else { message_ = trimmed; return DONE; } } void PPAPITestMessageHandler::Reset() { TestMessageHandler::Reset(); message_.clear(); } PPAPITestBase::InfoBarObserver::InfoBarObserver() { registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, content::NotificationService::AllSources()); } PPAPITestBase::InfoBarObserver::~InfoBarObserver() { EXPECT_EQ(0u, expected_infobars_.size()) << "Missing an expected infobar"; } void PPAPITestBase::InfoBarObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { ASSERT_EQ(chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, type); InfoBarDelegate* info_bar_delegate = content::Details<InfoBarAddedDetails>(details).ptr(); ConfirmInfoBarDelegate* confirm_info_bar_delegate = info_bar_delegate->AsConfirmInfoBarDelegate(); ASSERT_TRUE(confirm_info_bar_delegate); ASSERT_FALSE(expected_infobars_.empty()) << "Unexpected infobar"; if (expected_infobars_.front()) confirm_info_bar_delegate->Accept(); else confirm_info_bar_delegate->Cancel(); expected_infobars_.pop_front(); // TODO(bauerb): We should close the infobar. } void PPAPITestBase::InfoBarObserver::ExpectInfoBarAndAccept( bool should_accept) { expected_infobars_.push_back(should_accept); } PPAPITestBase::PPAPITestBase() { } void PPAPITestBase::SetUpCommandLine(CommandLine* command_line) { // Do not use mesa if real GPU is required. if (!command_line->HasSwitch(switches::kUseGpuInTests)) { #if !defined(OS_MACOSX) CHECK(test_launcher_utils::OverrideGLImplementation( command_line, gfx::kGLImplementationOSMesaName)) << "kUseGL must not be set by test framework code!"; #endif } // The test sends us the result via a cookie. command_line->AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. command_line->AppendSwitch(switches::kEnablePepperTesting); // Smooth scrolling confuses the scrollbar test. command_line->AppendSwitch(switches::kDisableSmoothScrolling); // Enable threading since we test that feature. command_line->AppendSwitch(switches::kEnablePepperThreading); } void PPAPITestBase::SetUpOnMainThread() { // Always allow access to the PPAPI broker. browser()->profile()->GetHostContentSettingsMap()->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PPAPI_BROKER, CONTENT_SETTING_ALLOW); } GURL PPAPITestBase::GetTestFileUrl(const std::string& test_case) { FilePath test_path; EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &test_path)); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL test_url = net::FilePathToFileURL(test_path); GURL::Replacements replacements; std::string query = BuildQuery("", test_case); replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); return test_url.ReplaceComponents(replacements); } void PPAPITestBase::RunTest(const std::string& test_case) { GURL url = GetTestFileUrl(test_case); RunTestURL(url); } void PPAPITestBase::RunTestAndReload(const std::string& test_case) { GURL url = GetTestFileUrl(test_case); RunTestURL(url); // If that passed, we simply run the test again, which navigates again. RunTestURL(url); } void PPAPITestBase::RunTestViaHTTP(const std::string& test_case) { FilePath document_root; ASSERT_TRUE(ui_test_utils::GetRelativeBuildDirectory(&document_root)); RunHTTPTestServer(document_root, test_case, ""); } void PPAPITestBase::RunTestWithSSLServer(const std::string& test_case) { FilePath document_root; ASSERT_TRUE(ui_test_utils::GetRelativeBuildDirectory(&document_root)); net::TestServer test_server(net::TestServer::TYPE_HTTPS, net::BaseTestServer::SSLOptions(), document_root); ASSERT_TRUE(test_server.Start()); uint16_t port = test_server.host_port_pair().port(); RunHTTPTestServer(document_root, test_case, StringPrintf("ssl_server_port=%d", port)); } void PPAPITestBase::RunTestWithWebSocketServer(const std::string& test_case) { net::TestServer server(net::TestServer::TYPE_WS, net::TestServer::kLocalhost, net::GetWebSocketTestDataDirectory()); ASSERT_TRUE(server.Start()); uint16_t port = server.host_port_pair().port(); FilePath http_document_root; ASSERT_TRUE(ui_test_utils::GetRelativeBuildDirectory(&http_document_root)); RunHTTPTestServer(http_document_root, test_case, StringPrintf("websocket_port=%d", port)); } void PPAPITestBase::RunTestIfAudioOutputAvailable( const std::string& test_case) { RunTest(test_case); } void PPAPITestBase::RunTestViaHTTPIfAudioOutputAvailable( const std::string& test_case) { RunTestViaHTTP(test_case); } std::string PPAPITestBase::StripPrefixes(const std::string& test_name) { const char* const prefixes[] = { "FAILS_", "FLAKY_", "DISABLED_", "SLOW_" }; for (size_t i = 0; i < sizeof(prefixes)/sizeof(prefixes[0]); ++i) if (test_name.find(prefixes[i]) == 0) return test_name.substr(strlen(prefixes[i])); return test_name; } void PPAPITestBase::RunTestURL(const GURL& test_url) { // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sends messages using the DOM automation controller. The // value of "..." means it's still working and we should continue to wait, // any other value indicates completion (in this case it will start with // "PASS" or "FAIL"). This keeps us from timing out on waits for long tests. PPAPITestMessageHandler handler; JavascriptTestObserver observer( browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost(), &handler); ui_test_utils::NavigateToURL(browser(), test_url); ASSERT_TRUE(observer.Run()) << handler.error_message(); EXPECT_STREQ("PASS", handler.message().c_str()); } void PPAPITestBase::RunHTTPTestServer( const FilePath& document_root, const std::string& test_case, const std::string& extra_params) { net::TestServer test_server(net::TestServer::TYPE_HTTP, net::TestServer::kLocalhost, document_root); ASSERT_TRUE(test_server.Start()); std::string query = BuildQuery("files/test_case.html?", test_case); if (!extra_params.empty()) query = StringPrintf("%s&%s", query.c_str(), extra_params.c_str()); GURL url = test_server.GetURL(query); RunTestURL(url); } PPAPITest::PPAPITest() { } void PPAPITest::SetUpCommandLine(CommandLine* command_line) { PPAPITestBase::SetUpCommandLine(command_line); // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; EXPECT_TRUE(PathService::Get(base::DIR_MODULE, &plugin_dir)); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); command_line->AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); command_line->AppendSwitchASCII(switches::kAllowNaClSocketAPI, "127.0.0.1"); } std::string PPAPITest::BuildQuery(const std::string& base, const std::string& test_case){ return StringPrintf("%stestcase=%s", base.c_str(), test_case.c_str()); } OutOfProcessPPAPITest::OutOfProcessPPAPITest() { } void OutOfProcessPPAPITest::SetUpCommandLine(CommandLine* command_line) { PPAPITest::SetUpCommandLine(command_line); // Run PPAPI out-of-process to exercise proxy implementations. command_line->AppendSwitch(switches::kPpapiOutOfProcess); } void PPAPINaClTest::SetUpCommandLine(CommandLine* command_line) { PPAPITestBase::SetUpCommandLine(command_line); FilePath plugin_lib; EXPECT_TRUE(PathService::Get(chrome::FILE_NACL_PLUGIN, &plugin_lib)); EXPECT_TRUE(file_util::PathExists(plugin_lib)); // Enable running NaCl outside of the store. command_line->AppendSwitch(switches::kEnableNaCl); command_line->AppendSwitchASCII(switches::kAllowNaClSocketAPI, "127.0.0.1"); } // Append the correct mode and testcase string std::string PPAPINaClNewlibTest::BuildQuery(const std::string& base, const std::string& test_case) { return StringPrintf("%smode=nacl_newlib&testcase=%s", base.c_str(), test_case.c_str()); } // Append the correct mode and testcase string std::string PPAPINaClGLibcTest::BuildQuery(const std::string& base, const std::string& test_case) { return StringPrintf("%smode=nacl_glibc&testcase=%s", base.c_str(), test_case.c_str()); } void PPAPINaClTestDisallowedSockets::SetUpCommandLine( CommandLine* command_line) { PPAPITestBase::SetUpCommandLine(command_line); FilePath plugin_lib; EXPECT_TRUE(PathService::Get(chrome::FILE_NACL_PLUGIN, &plugin_lib)); EXPECT_TRUE(file_util::PathExists(plugin_lib)); // Enable running NaCl outside of the store. command_line->AppendSwitch(switches::kEnableNaCl); } // Append the correct mode and testcase string std::string PPAPINaClTestDisallowedSockets::BuildQuery( const std::string& base, const std::string& test_case) { return StringPrintf("%smode=nacl_newlib&testcase=%s", base.c_str(), test_case.c_str()); } void PPAPIBrokerInfoBarTest::SetUpOnMainThread() { // The default content setting for the PPAPI broker is ASK. We purposefully // don't call PPAPITestBase::SetUpOnMainThread() to keep it that way. }
{ "content_hash": "dbce4bb357d4e4cb89d14e2b462fe523", "timestamp": "", "source": "github", "line_count": 302, "max_line_length": 80, "avg_line_length": 35.51324503311258, "alnum_prop": 0.7068531468531468, "repo_name": "leighpauls/k2cro4", "id": "5da65af23cb562124c7a2e47b8508c7dabc4cc1e", "size": "12502", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/test/ppapi/ppapi_test.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
/* * pix1.c * * The pixN.c {N = 1,2,3,4} files are sorted by the type of operation. * The primary functions in these files are: * * pix1.c: constructors, destructors and field accessors * pix2.c: pixel poking of image, pad and border pixels * pix3.c: masking and logical ops, counting, mirrored tiling * pix4.c: histograms, fg/bg estimation, rectangle extraction * * * This file has the basic constructors, destructors and field accessors * * Pix memory management (allows custom allocator and deallocator) * static void *pix_malloc() * static void pix_free() * void setPixMemoryManager() * * Pix creation * PIX *pixCreate() * PIX *pixCreateNoInit() * PIX *pixCreateTemplate() * PIX *pixCreateTemplateNoInit() * PIX *pixCreateHeader() * PIX *pixClone() * * Pix destruction * void pixDestroy() * static void pixFree() * * Pix copy * PIX *pixCopy() * l_int32 pixResizeImageData() * l_int32 pixCopyColormap() * l_int32 pixSizesEqual() * l_int32 pixTransferAllData() * * Pix accessors * l_int32 pixGetWidth() * l_int32 pixSetWidth() * l_int32 pixGetHeight() * l_int32 pixSetHeight() * l_int32 pixGetDepth() * l_int32 pixSetDepth() * l_int32 pixGetDimensions() * l_int32 pixSetDimensions() * l_int32 pixCopyDimensions() * l_int32 pixGetWpl() * l_int32 pixSetWpl() * l_int32 pixGetRefcount() * l_int32 pixChangeRefcount() * l_uint32 pixGetXRes() * l_int32 pixSetXRes() * l_uint32 pixGetYRes() * l_int32 pixSetYRes() * l_int32 pixGetResolution() * l_int32 pixSetResolution() * l_int32 pixCopyResolution() * l_int32 pixScaleResolution() * l_int32 pixGetInputFormat() * l_int32 pixSetInputFormat() * l_int32 pixCopyInputFormat() * char *pixGetText() * l_int32 pixSetText() * l_int32 pixAddText() * l_int32 pixCopyText() * PIXCMAP *pixGetColormap() * l_int32 pixSetColormap() * l_int32 pixDestroyColormap() * l_uint32 *pixGetData() * l_int32 pixSetData() * l_uint32 *pixExtractData() * l_int32 pixFreeData() * * Pix line ptrs * void **pixGetLinePtrs() * * Pix debug * l_int32 pixPrintStreamInfo() * * * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * Important notes on direct management of pix image data * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * * Custom allocator and deallocator * -------------------------------- * * At the lowest level, you can specify the function that does the * allocation and deallocation of the data field in the pix. * By default, this is malloc and free. However, by calling * setPixMemoryManager(), custom functions can be substituted. * When using this, keep two things in mind: * * (1) Call setPixMemoryManager() before any pix have been allocated * (2) Destroy all pix as usual, in order to prevent leaks. * * In pixalloc.c, we provide an example custom allocator and deallocator. * To use it, you must call pmsCreate() before any pix have been allocated * and pmsDestroy() at the end after all pix have been destroyed. * * * Direct manipulation of the pix data field * ----------------------------------------- * * Memory management of the (image) data field in the pix is * handled differently from that in the colormap or text fields. * For colormap and text, the functions pixSetColormap() and * pixSetText() remove the existing heap data and insert the * new data. For the image data, pixSetData() just reassigns the * data field; any existing data will be lost if there isn't * another handle for it. * * Why is pixSetData() limited in this way? Because the image * data can be very large, we need flexible ways to handle it, * particularly when you want to re-use the data in a different * context without making a copy. Here are some different * things you might want to do: * * (1) Use pixCopy(pixd, pixs) where pixd is not the same size * as pixs. This will remove the data in pixd, allocate a * new data field in pixd, and copy the data from pixs, leaving * pixs unchanged. * * (2) Use pixTransferAllData(pixd, &pixs, ...) to transfer the * data from pixs to pixd without making a copy of it. If * pixs is not cloned, this will do the transfer and destroy pixs. * But if the refcount of pixs is greater than 1, it just copies * the data and decrements the ref count. * * (3) Use pixExtractData() to extract the image data from the pix * without copying if possible. This could be used, for example, * to convert from a pix to some other data structure with minimal * heap allocation. After the data is extracated, the pixels can * be munged and used in another context. However, the danger * here is that the pix might have a refcount > 1, in which case * a copy of the data must be made and the input pix left unchanged. * If there are no clones, the image data can be extracted without * a copy, and the data ptr in the pix must be nulled before * destroying it because the pix will no longer 'own' the data. * * We have provided accessors and functions here that should be * sufficient so that you can do anything you want without * explicitly referencing any of the pix member fields. * * However, to avoid memory smashes and leaks when doing special operations * on the pix data field, look carefully at the behavior of the image * data accessors and keep in mind that when you invoke pixDestroy(), * the pix considers itself the owner of all its heap data. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "allheaders.h" static void pixFree(PIX *pix); /*-------------------------------------------------------------------------* * Pix Memory Management * * * * These functions give you the freedom to specify at compile or run * * time the allocator and deallocator to be used for pix. It has no * * effect on memory management for other data structs, which are * * controlled by the #defines in environ.h. Likewise, the #defines * * in environ.h have no effect on the pix memory management. * * The default functions are malloc and free. Use setPixMemoryManager() * * to specify other functions to use. * *-------------------------------------------------------------------------*/ struct PixMemoryManager { void *(*allocator)(size_t); void (*deallocator)(void *); }; static struct PixMemoryManager pix_mem_manager = { &malloc, &free }; static void * pix_malloc(size_t size) { #ifndef COMPILER_MSVC return (*pix_mem_manager.allocator)(size); #else /* COMPILER_MSVC */ /* Under MSVC++, pix_mem_manager is initialized after a call * to pix_malloc. Just ignore the custom allocator feature. */ return malloc(size); #endif /* COMPILER_MSVC */ } static void pix_free(void *ptr) { #ifndef COMPILER_MSVC (*pix_mem_manager.deallocator)(ptr); return; #else /* COMPILER_MSVC */ /* Under MSVC++, pix_mem_manager is initialized after a call * to pix_malloc. Just ignore the custom allocator feature. */ free(ptr); return; #endif /* COMPILER_MSVC */ } /*! * setPixMemoryManager() * * Input: allocator (<optional>; use null to skip) * deallocator (<optional>; use null to skip) * Return: void * * Notes: * (1) Use this to change the alloc and/or dealloc functions; * e.g., setPixMemoryManager(my_malloc, my_free). */ #ifndef COMPILER_MSVC void setPixMemoryManager(void *(allocator(size_t)), void (deallocator(void *))) { if (allocator) pix_mem_manager.allocator = allocator; if (deallocator) pix_mem_manager.deallocator = deallocator; return; } #else /* COMPILER_MSVC */ /* MSVC++ wants type (*fun)(types...) syntax */ void setPixMemoryManager(void *((*allocator)(size_t)), void ((*deallocator)(void *))) { if (allocator) pix_mem_manager.allocator = allocator; if (deallocator) pix_mem_manager.deallocator = deallocator; return; } #endif /* COMPILER_MSVC */ /*--------------------------------------------------------------------* * Pix Creation * *--------------------------------------------------------------------*/ /*! * pixCreate() * * Input: width, height, depth * Return: pixd (with data allocated and initialized to 0), * or null on error */ PIX * pixCreate(l_int32 width, l_int32 height, l_int32 depth) { PIX *pixd; PROCNAME("pixCreate"); if ((pixd = pixCreateNoInit(width, height, depth)) == NULL) return (PIX *)ERROR_PTR("pixd not made", procName, NULL); memset(pixd->data, 0, 4 * pixd->wpl * pixd->h); return pixd; } /*! * pixCreateNoInit() * * Input: width, height, depth * Return: pixd (with data allocated but not initialized), * or null on error * * Notes: * (1) Must set pad bits to avoid reading unitialized data, because * some optimized routines (e.g., pixConnComp()) read from pad bits. */ PIX * pixCreateNoInit(l_int32 width, l_int32 height, l_int32 depth) { l_int32 wpl; PIX *pixd; l_uint32 *data; PROCNAME("pixCreateNoInit"); pixd = pixCreateHeader(width, height, depth); if (!pixd) return NULL; wpl = pixGetWpl(pixd); if ((data = (l_uint32 *)pix_malloc(4 * wpl * height)) == NULL) return (PIX *)ERROR_PTR("pix_malloc fail for data", procName, NULL); pixSetData(pixd, data); pixSetPadBits(pixd, 0); return pixd; } /*! * pixCreateTemplate() * * Input: pixs * Return: pixd, or null on error * * Notes: * (1) Makes a Pix of the same size as the input Pix, with the * data array allocated and initialized to 0. * (2) Copies the other fields, including colormap if it exists. */ PIX * pixCreateTemplate(PIX *pixs) { PIX *pixd; PROCNAME("pixCreateTemplate"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if ((pixd = pixCreateTemplateNoInit(pixs)) == NULL) return (PIX *)ERROR_PTR("pixd not made", procName, NULL); memset(pixd->data, 0, 4 * pixd->wpl * pixd->h); return pixd; } /*! * pixCreateTemplateNoInit() * * Input: pixs * Return: pixd, or null on error * * Notes: * (1) Makes a Pix of the same size as the input Pix, with * the data array allocated but not initialized to 0. * (2) Copies the other fields, including colormap if it exists. */ PIX * pixCreateTemplateNoInit(PIX *pixs) { l_int32 w, h, d; PIX *pixd; PROCNAME("pixCreateTemplateNoInit"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); pixGetDimensions(pixs, &w, &h, &d); if ((pixd = pixCreateNoInit(w, h, d)) == NULL) return (PIX *)ERROR_PTR("pixd not made", procName, NULL); pixCopyResolution(pixd, pixs); pixCopyColormap(pixd, pixs); pixCopyText(pixd, pixs); pixCopyInputFormat(pixd, pixs); return pixd; } /*! * pixCreateHeader() * * Input: width, height, depth * Return: pixd (with no data allocated), or null on error */ PIX * pixCreateHeader(l_int32 width, l_int32 height, l_int32 depth) { l_int32 wpl; PIX *pixd; PROCNAME("pixCreateHeader"); if ((depth != 1) && (depth != 2) && (depth != 4) && (depth != 8) && (depth != 16) && (depth != 24) && (depth != 32)) return (PIX *)ERROR_PTR("depth must be {1, 2, 4, 8, 16, 24, 32}", procName, NULL); if (width <= 0) return (PIX *)ERROR_PTR("width must be > 0", procName, NULL); if (height <= 0) return (PIX *)ERROR_PTR("height must be > 0", procName, NULL); if ((pixd = (PIX *)CALLOC(1, sizeof(PIX))) == NULL) return (PIX *)ERROR_PTR("CALLOC fail for pixd", procName, NULL); pixSetWidth(pixd, width); pixSetHeight(pixd, height); pixSetDepth(pixd, depth); wpl = (width * depth + 31) / 32; pixSetWpl(pixd, wpl); pixd->refcount = 1; pixd->informat = IFF_UNKNOWN; return pixd; } /*! * pixClone() * * Input: pix * Return: same pix (ptr), or null on error * * Notes: * (1) A "clone" is simply a handle (ptr) to an existing pix. * It is implemented because (a) images can be large and * hence expensive to copy, and (b) extra handles to a data * structure need to be made with a simple policy to avoid * both double frees and memory leaks. Pix are reference * counted. The side effect of pixClone() is an increase * by 1 in the ref count. * (2) The protocol to be used is: * (a) Whenever you want a new handle to an existing image, * call pixClone(), which just bumps a ref count. * (b) Always call pixDestroy() on all handles. This * decrements the ref count, nulls the handle, and * only destroys the pix when pixDestroy() has been * called on all handles. */ PIX * pixClone(PIX *pixs) { PROCNAME("pixClone"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); pixChangeRefcount(pixs, 1); return pixs; } /*--------------------------------------------------------------------* * Pix Destruction * *--------------------------------------------------------------------*/ /*! * pixDestroy() * * Input: &pix <will be nulled> * Return: void * * Notes: * (1) Decrements the ref count and, if 0, destroys the pix. * (2) Always nulls the input ptr. */ void pixDestroy(PIX **ppix) { PIX *pix; PROCNAME("pixDestroy"); if (!ppix) { L_WARNING("ptr address is null!", procName); return; } if ((pix = *ppix) == NULL) return; pixFree(pix); *ppix = NULL; return; } /*! * pixFree() * * Input: pix * Return: void * * Notes: * (1) Decrements the ref count and, if 0, destroys the pix. */ static void pixFree(PIX *pix) { l_uint32 *data; char *text; if (!pix) return; pixChangeRefcount(pix, -1); if (pixGetRefcount(pix) <= 0) { if ((data = pixGetData(pix)) != NULL) pix_free(data); if ((text = pixGetText(pix)) != NULL) FREE(text); pixDestroyColormap(pix); FREE(pix); } return; } /*-------------------------------------------------------------------------* * Pix Copy * *-------------------------------------------------------------------------*/ /*! * pixCopy() * * Input: pixd (<optional>; can be null, or equal to pixs, * or different from pixs) * pixs * Return: pixd, or null on error * * Notes: * (1) There are three cases: * (a) pixd == null (makes a new pix; refcount = 1) * (b) pixd == pixs (no-op) * (c) pixd != pixs (data copy; no change in refcount) * If the refcount of pixd > 1, case (c) will side-effect * these handles. * (2) The general pattern of use is: * pixd = pixCopy(pixd, pixs); * This will work for all three cases. * For clarity when the case is known, you can use: * (a) pixd = pixCopy(NULL, pixs); * (c) pixCopy(pixd, pixs); * (3) For case (c), we check if pixs and pixd are the same * size (w,h,d). If so, the data is copied directly. * Otherwise, the data is reallocated to the correct size * and the copy proceeds. The refcount of pixd is unchanged. * (4) This operation, like all others that may involve a pre-existing * pixd, will side-effect any existing clones of pixd. */ PIX * pixCopy(PIX *pixd, /* can be null */ PIX *pixs) { l_int32 bytes; l_uint32 *datas, *datad; PROCNAME("pixCopy"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if (pixs == pixd) return pixd; /* Total bytes in image data */ bytes = 4 * pixGetWpl(pixs) * pixGetHeight(pixs); /* If we're making a new pix ... */ if (!pixd) { if ((pixd = pixCreateTemplate(pixs)) == NULL) return (PIX *)ERROR_PTR("pixd not made", procName, NULL); datas = pixGetData(pixs); datad = pixGetData(pixd); memcpy((char *)datad, (char *)datas, bytes); return pixd; } /* Reallocate image data if sizes are different */ if (pixResizeImageData(pixd, pixs) == 1) return (PIX *)ERROR_PTR("reallocation of data failed", procName, NULL); /* Copy non-image data fields */ pixCopyColormap(pixd, pixs); pixCopyResolution(pixd, pixs); pixCopyInputFormat(pixd, pixs); pixCopyText(pixd, pixs); /* Copy image data */ datas = pixGetData(pixs); datad = pixGetData(pixd); memcpy((char*)datad, (char*)datas, bytes); return pixd; } /*! * pixResizeImageData() * * Input: pixd (gets new uninitialized buffer for image data) * pixs (determines the size of the buffer; not changed) * Return: 0 if OK, 1 on error * * Notes: * (1) This removes any existing image data from pixd and * allocates an uninitialized buffer that will hold the * amount of image data that is in pixs. */ l_int32 pixResizeImageData(PIX *pixd, PIX *pixs) { l_int32 w, h, d, wpl, bytes; l_uint32 *data; PROCNAME("pixResizeImageData"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pixd) return ERROR_INT("pixd not defined", procName, 1); if (pixSizesEqual(pixs, pixd)) /* nothing to do */ return 0; pixGetDimensions(pixs, &w, &h, &d); wpl = pixGetWpl(pixs); pixSetWidth(pixd, w); pixSetHeight(pixd, h); pixSetDepth(pixd, d); pixSetWpl(pixd, wpl); bytes = 4 * wpl * h; pixFreeData(pixd); /* free any existing image data */ if ((data = (l_uint32 *)pix_malloc(bytes)) == NULL) return ERROR_INT("pix_malloc fail for data", procName, 1); pixSetData(pixd, data); return 0; } /*! * pixCopyColormap() * * Input: src and dest Pix * Return: 0 if OK, 1 on error * * Notes: * (1) This always destroys any colormap in pixd (except if * the operation is a no-op. */ l_int32 pixCopyColormap(PIX *pixd, PIX *pixs) { PIXCMAP *cmaps, *cmapd; PROCNAME("pixCopyColormap"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pixd) return ERROR_INT("pixd not defined", procName, 1); if (pixs == pixd) return 0; /* no-op */ pixDestroyColormap(pixd); if ((cmaps = pixGetColormap(pixs)) == NULL) /* not an error */ return 0; if ((cmapd = pixcmapCopy(cmaps)) == NULL) return ERROR_INT("cmapd not made", procName, 1); pixSetColormap(pixd, cmapd); return 0; } /*! * pixSizesEqual() * * Input: two pix * Return: 1 if the two pix have same {h, w, d}; 0 otherwise. */ l_int32 pixSizesEqual(PIX *pix1, PIX *pix2) { PROCNAME("pixSizesEqual"); if (!pix1 || !pix2) return ERROR_INT("pix1 and pix2 not both defined", procName, 0); if (pix1 == pix2) return 1; if ((pixGetWidth(pix1) != pixGetWidth(pix2)) || (pixGetHeight(pix1) != pixGetHeight(pix2)) || (pixGetDepth(pix1) != pixGetDepth(pix2))) return 0; else return 1; } /*! * pixTransferAllData() * * Input: pixd (must be different from pixs) * &pixs (will be nulled if refcount goes to 0) * copytext (1 to copy the text field; 0 to skip) * copyformat (1 to copy the informat field; 0 to skip) * Return: 0 if OK, 1 on error * * Notes: * (1) This does a complete data transfer from pixs to pixd, * followed by the destruction of pixs (refcount permitting). * (2) If the refcount of pixs is 1, pixs is destroyed. Otherwise, * the data in pixs is copied (rather than transferred) to pixd. * (3) This operation, like all others with a pre-existing pixd, * will side-effect any existing clones of pixd. The pixd * refcount does not change. * (4) When might you use this? Suppose you have an in-place Pix * function (returning void) with the typical signature: * void function-inplace(PIX *pix, ...) * where "..." are non-pointer input parameters, and suppose * further that you sometimes want to return an arbitrary Pix * in place of the input Pix. There are two ways you can do this: * (a) The straightforward way is to change the function * signature to take the address of the Pix ptr: * void function-inplace(PIX **ppix, ...) { * PIX *pixt = function-makenew(*ppix); * pixDestroy(ppix); * *ppix = pixt; * return; * } * Here, the input and returned pix are different, as viewed * by the calling function, and the inplace function is * expected to destroy the input pix to avoid a memory leak. * (b) Keep the signature the same and use pixTransferAllData() * to return the new Pix in the input Pix struct: * void function-inplace(PIX *pix, ...) { * PIX *pixt = function-makenew(pix); * pixTransferAllData(pix, &pixt, 0, 0); * // pixDestroy() is called on pixt * return; * } * Here, the input and returned pix are the same, as viewed * by the calling function, and the inplace function must * never destroy the input pix, because the calling function * maintains an unchanged handle to it. */ l_int32 pixTransferAllData(PIX *pixd, PIX **ppixs, l_int32 copytext, l_int32 copyformat) { l_int32 nbytes; PIX *pixs; PROCNAME("pixTransferAllData"); if (!ppixs) return ERROR_INT("&pixs not defined", procName, 1); if ((pixs = *ppixs) == NULL) return ERROR_INT("pixs not defined", procName, 1); if (!pixd) return ERROR_INT("pixd not defined", procName, 1); if (pixs == pixd) /* no-op */ return ERROR_INT("pixd == pixs", procName, 1); if (pixGetRefcount(pixs) == 1) { /* transfer the data, cmap, text */ pixFreeData(pixd); /* dealloc any existing data */ pixSetData(pixd, pixGetData(pixs)); /* transfer new data from pixs */ pixs->data = NULL; /* pixs no longer owns data */ pixSetColormap(pixd, pixGetColormap(pixs)); /* frees old; sets new */ pixs->colormap = NULL; /* pixs no longer owns colormap */ if (copytext) { pixSetText(pixd, pixGetText(pixs)); pixSetText(pixs, NULL); } } else { /* preserve pixs by making a copy of the data, cmap, text */ pixResizeImageData(pixd, pixs); nbytes = 4 * pixGetWpl(pixs) * pixGetHeight(pixs); memcpy((char *)pixGetData(pixd), (char *)pixGetData(pixs), nbytes); pixCopyColormap(pixd, pixs); if (copytext) pixCopyText(pixd, pixs); } pixCopyResolution(pixd, pixs); pixCopyDimensions(pixd, pixs); if (copyformat) pixCopyInputFormat(pixd, pixs); /* This will destroy pixs if data was transferred; * otherwise, it just decrements its refcount. */ pixDestroy(ppixs); return 0; } /*--------------------------------------------------------------------* * Accessors * *--------------------------------------------------------------------*/ l_int32 pixGetWidth(PIX *pix) { PROCNAME("pixGetWidth"); if (!pix) return ERROR_INT("pix not defined", procName, UNDEF); return pix->w; } l_int32 pixSetWidth(PIX *pix, l_int32 width) { PROCNAME("pixSetWidth"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (width < 0) { pix->w = 0; return ERROR_INT("width must be >= 0", procName, 1); } pix->w = width; return 0; } l_int32 pixGetHeight(PIX *pix) { PROCNAME("pixGetHeight"); if (!pix) return ERROR_INT("pix not defined", procName, UNDEF); return pix->h; } l_int32 pixSetHeight(PIX *pix, l_int32 height) { PROCNAME("pixSetHeight"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (height < 0) { pix->h = 0; return ERROR_INT("h must be >= 0", procName, 1); } pix->h = height; return 0; } l_int32 pixGetDepth(PIX *pix) { PROCNAME("pixGetDepth"); if (!pix) return ERROR_INT("pix not defined", procName, UNDEF); return pix->d; } l_int32 pixSetDepth(PIX *pix, l_int32 depth) { PROCNAME("pixSetDepth"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (depth < 1) return ERROR_INT("d must be >= 1", procName, 1); pix->d = depth; return 0; } /*! * pixGetDimensions() * * Input: pix * &w, &h, &d (<optional return>; each can be null) * Return: 0 if OK, 1 on error */ l_int32 pixGetDimensions(PIX *pix, l_int32 *pw, l_int32 *ph, l_int32 *pd) { PROCNAME("pixGetDimensions"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (pw) *pw = pix->w; if (ph) *ph = pix->h; if (pd) *pd = pix->d; return 0; } /*! * pixSetDimensions() * * Input: pix * w, h, d (use 0 to skip the setting for any of these) * Return: 0 if OK, 1 on error */ l_int32 pixSetDimensions(PIX *pix, l_int32 w, l_int32 h, l_int32 d) { PROCNAME("pixSetDimensions"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (w > 0) pixSetWidth(pix, w); if (h > 0) pixSetHeight(pix, h); if (d > 0) pixSetDepth(pix, d); return 0; } /*! * pixCopyDimensions() * * Input: pixd * pixd * Return: 0 if OK, 1 on error */ l_int32 pixCopyDimensions(PIX *pixd, PIX *pixs) { PROCNAME("pixCopyDimensions"); if (!pixd) return ERROR_INT("pixd not defined", procName, 1); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (pixs == pixd) return 0; /* no-op */ pixSetWidth(pixd, pixGetWidth(pixs)); pixSetHeight(pixd, pixGetHeight(pixs)); pixSetDepth(pixd, pixGetDepth(pixs)); pixSetWpl(pixd, pixGetWpl(pixs)); return 0; } l_int32 pixGetWpl(PIX *pix) { PROCNAME("pixGetWpl"); if (!pix) return ERROR_INT("pix not defined", procName, UNDEF); return pix->wpl; } l_int32 pixSetWpl(PIX *pix, l_int32 wpl) { PROCNAME("pixSetWpl"); if (!pix) return ERROR_INT("pix not defined", procName, 1); pix->wpl = wpl; return 0; } l_int32 pixGetRefcount(PIX *pix) { PROCNAME("pixGetRefcount"); if (!pix) return ERROR_INT("pix not defined", procName, UNDEF); return pix->refcount; } l_int32 pixChangeRefcount(PIX *pix, l_int32 delta) { PROCNAME("pixChangeRefcount"); if (!pix) return ERROR_INT("pix not defined", procName, 1); pix->refcount += delta; return 0; } l_uint32 pixGetXRes(PIX *pix) { PROCNAME("pixGetXRes"); if (!pix) return ERROR_INT("pix not defined", procName, 0); return pix->xres; } l_int32 pixSetXRes(PIX *pix, l_uint32 res) { PROCNAME("pixSetXRes"); if (!pix) return ERROR_INT("pix not defined", procName, 1); pix->xres = res; return 0; } l_uint32 pixGetYRes(PIX *pix) { PROCNAME("pixGetYRes"); if (!pix) return ERROR_INT("pix not defined", procName, 0); return pix->yres; } l_int32 pixSetYRes(PIX *pix, l_uint32 res) { PROCNAME("pixSetYRes"); if (!pix) return ERROR_INT("pix not defined", procName, 1); pix->yres = res; return 0; } /*! * pixGetResolution() * * Input: pix * &xres, &yres (<optional return>; each can be null) * Return: 0 if OK, 1 on error */ l_int32 pixGetResolution(PIX *pix, l_uint32 *pxres, l_uint32 *pyres) { PROCNAME("pixGetResolution"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (pxres) *pxres = pix->xres; if (pyres) *pyres = pix->yres; return 0; } /*! * pixSetResolution() * * Input: pix * xres, yres (use 0 to skip the setting for either of these) * Return: 0 if OK, 1 on error */ l_int32 pixSetResolution(PIX *pix, l_uint32 xres, l_uint32 yres) { PROCNAME("pixSetResolution"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (xres > 0) pix->xres = xres; if (yres > 0) pix->yres = yres; return 0; } l_int32 pixCopyResolution(PIX *pixd, PIX *pixs) { PROCNAME("pixCopyResolution"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pixd) return ERROR_INT("pixd not defined", procName, 1); if (pixs == pixd) return 0; /* no-op */ pixSetXRes(pixd, pixGetXRes(pixs)); pixSetYRes(pixd, pixGetYRes(pixs)); return 0; } l_int32 pixScaleResolution(PIX *pix, l_float32 xscale, l_float32 yscale) { PROCNAME("pixScaleResolution"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (pix->xres != 0 && pix->yres != 0) { pix->xres = (l_uint32)(xscale * (l_float32)(pix->xres) + 0.5); pix->yres = (l_uint32)(yscale * (l_float32)(pix->yres) + 0.5); } return 0; } l_int32 pixGetInputFormat(PIX *pix) { PROCNAME("pixGetInputFormat"); if (!pix) return ERROR_INT("pix not defined", procName, UNDEF); return pix->informat; } l_int32 pixSetInputFormat(PIX *pix, l_int32 informat) { PROCNAME("pixSetInputFormat"); if (!pix) return ERROR_INT("pix not defined", procName, 1); pix->informat = informat; return 0; } l_int32 pixCopyInputFormat(PIX *pixd, PIX *pixs) { PROCNAME("pixCopyInputFormat"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pixd) return ERROR_INT("pixd not defined", procName, 1); if (pixs == pixd) return 0; /* no-op */ pixSetInputFormat(pixd, pixGetInputFormat(pixs)); return 0; } /*! * pixGetText() * * Input: pix * Return: ptr to existing text string * * Notes: * (1) The text string belongs to the pix. The caller must * NOT free it! */ char * pixGetText(PIX *pix) { PROCNAME("pixGetText"); if (!pix) return (char *)ERROR_PTR("pix not defined", procName, NULL); return pix->text; } /*! * pixSetText() * * Input: pix * textstring (can be null) * Return: 0 if OK, 1 on error * * Notes: * (1) This removes any existing textstring and puts a copy of * the input textstring there. */ l_int32 pixSetText(PIX *pix, const char *textstring) { PROCNAME("pixSetText"); if (!pix) return ERROR_INT("pix not defined", procName, 1); stringReplace(&pix->text, textstring); return 0; } /*! * pixAddText() * * Input: pix * textstring * Return: 0 if OK, 1 on error * * Notes: * (1) This adds the new textstring to any existing text. * (2) Either or both the existing text and the new text * string can be null. */ l_int32 pixAddText(PIX *pix, const char *textstring) { char *newstring; PROCNAME("pixAddText"); if (!pix) return ERROR_INT("pix not defined", procName, 1); newstring = stringJoin(pixGetText(pix), textstring); stringReplace(&pix->text, newstring); FREE(newstring); return 0; } l_int32 pixCopyText(PIX *pixd, PIX *pixs) { PROCNAME("pixCopyText"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pixd) return ERROR_INT("pixd not defined", procName, 1); if (pixs == pixd) return 0; /* no-op */ pixSetText(pixd, pixGetText(pixs)); return 0; } PIXCMAP * pixGetColormap(PIX *pix) { PROCNAME("pixGetColormap"); if (!pix) return (PIXCMAP *)ERROR_PTR("pix not defined", procName, NULL); return pix->colormap; } /*! * pixSetColormap() * * Input: pix * colormap (to be assigned) * Return: 0 if OK, 1 on error. * * Notes: * (1) Unlike with the pix data field, pixSetColormap() destroys * any existing colormap before assigning the new one. * Because colormaps are not ref counted, it is important that * the new colormap does not belong to any other pix. */ l_int32 pixSetColormap(PIX *pix, PIXCMAP *colormap) { PROCNAME("pixSetColormap"); if (!pix) return ERROR_INT("pix not defined", procName, 1); pixDestroyColormap(pix); pix->colormap = colormap; return 0; } /*! * pixDestroyColormap() * * Input: pix * Return: 0 if OK, 1 on error */ l_int32 pixDestroyColormap(PIX *pix) { PIXCMAP *cmap; PROCNAME("pixDestroyColormap"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if ((cmap = pix->colormap) != NULL) { pixcmapDestroy(&cmap); pix->colormap = NULL; } return 0; } /*! * pixGetData() * * Notes: * (1) This gives a new handle for the data. The data is still * owned by the pix, so do not call FREE() on it. */ l_uint32 * pixGetData(PIX *pix) { PROCNAME("pixGetData"); if (!pix) return (l_uint32 *)ERROR_PTR("pix not defined", procName, NULL); return pix->data; } /*! * pixSetData() * * Notes: * (1) This does not free any existing data. To free existing * data, use pixFreeData() before pixSetData(). */ l_int32 pixSetData(PIX *pix, l_uint32 *data) { PROCNAME("pixSetData"); if (!pix) return ERROR_INT("pix not defined", procName, 1); pix->data = data; return 0; } /*! * pixExtractData() * * Notes: * (1) This extracts the pix image data for use in another context. * The caller still needs to use pixDestroy() on the input pix. * (2) If refcount == 1, the data is extracted and the * pix->data ptr is set to NULL. * (3) If refcount > 1, this simply returns a copy of the data, * using the pix allocator, and leaving the input pix unchanged. */ l_uint32 * pixExtractData(PIX *pixs) { l_int32 count, bytes; l_uint32 *data, *datas; PROCNAME("pixExtractData"); if (!pixs) return (l_uint32 *)ERROR_PTR("pixs not defined", procName, NULL); count = pixGetRefcount(pixs); if (count == 1) { /* extract */ data = pixGetData(pixs); pixSetData(pixs, NULL); } else { /* refcount > 1; copy */ bytes = 4 * pixGetWpl(pixs) * pixGetHeight(pixs); datas = pixGetData(pixs); if ((data = (l_uint32 *)pix_malloc(bytes)) == NULL) return (l_uint32 *)ERROR_PTR("data not made", procName, NULL); memcpy((char *)data, (char *)datas, bytes); } return data; } /*! * pixFreeData() * * Notes: * (1) This frees the data and sets the pix data ptr to null. * It should be used before pixSetData() in the situation where * you want to free any existing data before doing * a subsequent assignment with pixSetData(). */ l_int32 pixFreeData(PIX *pix) { l_uint32 *data; PROCNAME("pixFreeData"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if ((data = pixGetData(pix)) != NULL) { pix_free(data); pix->data = NULL; } return 0; } /*--------------------------------------------------------------------* * Pix line ptrs * *--------------------------------------------------------------------*/ /*! * pixGetLinePtrs() * * Input: pix * &size (<optional return> array size, which is the pix height) * Return: array of line ptrs, or null on error * * Notes: * (1) This is intended to be used for fast random pixel access. * For example, for an 8 bpp image, * val = GET_DATA_BYTE(lines8[i], j); * is equivalent to, but much faster than, * pixGetPixel(pix, j, i, &val); * (2) How much faster? For 1 bpp, it's from 6 to 10x faster. * For 8 bpp, it's an amazing 30x faster. So if you are * doing random access over a substantial part of the image, * use this line ptr array. * (3) When random access is used in conjunction with a stack, * queue or heap, the overall computation time depends on * the operations performed on each struct that is popped * or pushed, and whether we are using a priority queue (O(logn)) * or a queue or stack (O(1)). For example, for maze search, * the overall ratio of time for line ptrs vs. pixGet/Set* is * Maze type Type Time ratio * binary queue 0.4 * gray heap (priority queue) 0.6 * (4) Because this returns a void** and the accessors take void*, * the compiler cannot check the pointer types. It is * strongly recommended that you adopt a naming scheme for * the returned ptr arrays that indicates the pixel depth. * (This follows the original intent of Simonyi's "Hungarian" * application notation, where naming is used proactively * to make errors visibly obvious.) By doing this, you can * tell by inspection if the correct accessor is used. * For example, for an 8 bpp pixg: * void **lineg8 = pixGetLinePtrs(pixg, NULL); * val = GET_DATA_BYTE(lineg8[i], j); // fast access; BYTE, 8 * ... * FREE(lineg8); // don't forget this * (5) These are convenient for accessing bytes sequentially in an * 8 bpp grayscale image. People who write image processing code * on 8 bpp images are accustomed to grabbing pixels directly out * of the raster array. Note that for little endians, you first * need to reverse the byte order in each 32-bit word. * Here's a typical usage pattern: * pixEndianByteSwap(pix); // always safe; no-op on big-endians * l_uint8 **lineptrs = (l_uint8 **)pixGetLinePtrs(pix); * pixGetDimensions(pix, &w, &h, NULL); * for (i = 0; i < h; i++) { * l_uint8 *line = lineptrs[i]; * for (j = 0; j < w; j++) { * val = line[j]; * ... * } * } * pixEndianByteSwap(pix); // restore big-endian order * FREE(lineptrs); * This can be done even more simply as follows: * l_uint8 **lineptrs = pixSetupByteProcessing(pix, &w, &h); * for (i = 0; i < h; i++) { * l_uint8 *line = lineptrs[i]; * for (j = 0; j < w; j++) { * val = line[j]; * ... * } * } * pixCleanupByteProcessing(pix, lineptrs); */ void ** pixGetLinePtrs(PIX *pix, l_int32 *psize) { l_int32 i, h, wpl; l_uint32 *data; void **lines; PROCNAME("pixGetLinePtrs"); if (!pix) return (void **)ERROR_PTR("pix not defined", procName, NULL); h = pixGetHeight(pix); if ((lines = (void **)CALLOC(h, sizeof(void *))) == NULL) return (void **)ERROR_PTR("lines not made", procName, NULL); wpl = pixGetWpl(pix); data = pixGetData(pix); for (i = 0; i < h; i++) lines[i] = (void *)(data + i * wpl); return lines; } /*--------------------------------------------------------------------* * Print output for debugging * *--------------------------------------------------------------------*/ extern const char *ImageFileFormatExtensions[]; /*! * pixPrintStreamInfo() * * Input: fp (file stream) * pix * text (<optional> identifying string; can be null) * Return: 0 if OK, 1 on error */ l_int32 pixPrintStreamInfo(FILE *fp, PIX *pix, const char *text) { l_int32 informat; PIXCMAP *cmap; PROCNAME("pixPrintStreamInfo"); if (!fp) return ERROR_INT("fp not defined", procName, 1); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (text) fprintf(fp, " Pix Info for %s:\n", text); fprintf(fp, " width = %d, height = %d, depth = %d\n", pixGetWidth(pix), pixGetHeight(pix), pixGetDepth(pix)); fprintf(fp, " wpl = %d, data = %p, refcount = %d\n", pixGetWpl(pix), pixGetData(pix), pixGetRefcount(pix)); if ((cmap = pixGetColormap(pix)) != NULL) pixcmapWriteStream(fp, cmap); else fprintf(fp, " no colormap\n"); informat = pixGetInputFormat(pix); fprintf(fp, " input format: %d (%s)\n", informat, ImageFileFormatExtensions[informat]); return 0; }
{ "content_hash": "b68c48935cc44c9a67f806a3fe2d5449", "timestamp": "", "source": "github", "line_count": 1578, "max_line_length": 79, "avg_line_length": 27.637515842839036, "alnum_prop": 0.5455379253416491, "repo_name": "dreamsxin/ultimatepp", "id": "33a72f4facd4f352965cafafedb573535a586c75", "size": "44535", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bazaar/PixRaster/lib/pix1.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "8477" }, { "name": "C", "bytes": "47921993" }, { "name": "C++", "bytes": "28354499" }, { "name": "CSS", "bytes": "659" }, { "name": "JavaScript", "bytes": "7006" }, { "name": "Objective-C", "bytes": "178854" }, { "name": "Perl", "bytes": "65041" }, { "name": "Python", "bytes": "38142" }, { "name": "Shell", "bytes": "91097" }, { "name": "Smalltalk", "bytes": "101" }, { "name": "Turing", "bytes": "661569" } ], "symlink_target": "" }
{:forge_host=>"forge-aio01-petest.puppetlabs.com", :is_puppetserver=>true, :is_jvm_puppet=>true, "service-wait"=>true, "service-prefix"=>"service ", "service-num-retries"=>1500, "puppetservice"=>"puppetserver", "puppetserver-package"=>"puppetserver", "use-service"=>true, "master-start-curl-retries"=>60, "puppetserver-confdir"=>"/etc/puppetlabs/puppetserver/conf.d", "puppetserver-config"=> "/etc/puppetlabs/puppetserver/conf.d/puppetserver.conf", :puppet_build_version=>"94965c9d0dbd5157d53e5333af33f36f0f475db6"}
{ "content_hash": "cfa1b8e36fc7e9d9ad10fe637d3371a0", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 67, "avg_line_length": 37.857142857142854, "alnum_prop": 0.7396226415094339, "repo_name": "puppetlabs/puppetserver", "id": "a98c7e2adb1388073b47775ceaaaf07eb8b25746", "size": "530", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "acceptance/config/beaker/options.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "1072269" }, { "name": "Dockerfile", "bytes": "6219" }, { "name": "Emacs Lisp", "bytes": "65" }, { "name": "HTML", "bytes": "345" }, { "name": "Java", "bytes": "7817" }, { "name": "Makefile", "bytes": "9443" }, { "name": "Pascal", "bytes": "396" }, { "name": "Puppet", "bytes": "853" }, { "name": "Ruby", "bytes": "263699" }, { "name": "Shell", "bytes": "46555" } ], "symlink_target": "" }
/* resource.h */ /* Copyright (c) 2012 by Jason Cheung <yujiecheung@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Jason Cheung nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __RESOURCE_H__ #define __RESOURCE_H__ #define IDB_VIRTUAL_BOARD 201 #define IDB_SEGMENT 202 #define IDB_LED_ON 203 #endif /* __RESOURCE_H__ */
{ "content_hash": "dc73c8cb73007acf8a7c00f519a0c004", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 83, "avg_line_length": 49.77777777777778, "alnum_prop": 0.7449776785714286, "repo_name": "yujiecheung/mvp", "id": "4301ff6767939cb91a2acc015e5832efa8a52a07", "size": "1792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mVirtualBoard/resource.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "390325" }, { "name": "C++", "bytes": "20648" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace Remoting { using RemoteId = Int32; using RemoteObject = MarshalByRefObject; public abstract class RemotingServer { public abstract void Start(); public abstract void Stop(); public abstract void AddObject(string name, RemoteObject value); public abstract void RemoveObject(string name); } }
{ "content_hash": "aa80b5d4f29907fde802ec555acc731e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 72, "avg_line_length": 23.79310344827586, "alnum_prop": 0.7478260869565218, "repo_name": "jbatonnet/shared", "id": "0e20f2ee3691d828d8f4b72cb0401d5f7ec4211d", "size": "692", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Remoting/RemotingServer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "319085" } ], "symlink_target": "" }
<?php function showRequests(){ include "mysql-cred.php"; $link = mysqli_connect( $servername, $username, $password, $database); if (mysqli_connect_errno()) { die("Connection failed: " . mysqli_connect_error); } $sql = "SELECT * from request"; $result = mysqli_query($link, $sql); $check = "<table>"; if ($result){ while($row = mysqli_fetch_row( $result )) { $check .= "<tr>"; $check .= "<td>" . $row[0] ; $check .= "<td>" . $row[1] ; $check .= "<td>" . $row[2] ; $check .= "<td>" . $row[3] ; $check .= "</tr>"; } } $check .= "</table>"; return $check; } function countRequests(){ include "mysql-cred.php"; $link = mysqli_connect( $servername, $username, $password, $database); if (mysqli_connect_errno()) { die("Connection failed: " . mysqli_connect_error); } $sql = "SELECT COUNT(*) as count, COUNT(DISTINCT requestIP) as countIP from request"; $result = mysqli_query($link, $sql); $check = ""; if ($result){ while($row = mysqli_fetch_row( $result )) { $check .= $row[0] . " requests from " . $row[1] . " distinct addresses"; } } return $check; }
{ "content_hash": "3b25a987816c30cfe8c14906580e2a38", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 89, "avg_line_length": 28.404761904761905, "alnum_prop": 0.5431684828164292, "repo_name": "owen-kellie-smith/chart", "id": "dff52d934c0f557950ddfe78419b53d390be1616", "size": "1193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "showRequests.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "85769" } ], "symlink_target": "" }
import { Text } from 'react-native' import React from 'react' import { Button, LeftButton, RightButton } from '../src' // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer' it('renders correctly => Button::label', () => { const tree = renderer.create( <Button label={'Button'} /> ) }) it('renders correctly => Button::children', () => { const tree = renderer.create( <Button> <Text>Button</Text> </Button> ) }) it('renders correctly => LeftButton', () => { const tree = renderer.create( <LeftButton label={'Back'} /> ) }) it('renders correctly => RightButton', () => { const tree = renderer.create( <RightButton label={'Forward'} /> ) })
{ "content_hash": "5b70204d5d24baf097049f87faea02d9", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 59, "avg_line_length": 22.90625, "alnum_prop": 0.6289222373806276, "repo_name": "thondery/kenote-react-native-design", "id": "b8babf7b2155fd94682bacf6718980ce09ffba93", "size": "733", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "__tests__/button.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "14968" } ], "symlink_target": "" }
<?php /** * A TestListener that integrates with XHProf. * * Here is an example XML configuration for activating this listener: * * <code> * <listeners> * <listener class="PHPUnit_Util_Log_XHProf" file="PHPUnit/Util/Log/XHProf.php"> * <arguments> * <array> * <element key="xhprofLibFile"> * <string>/var/www/xhprof_lib/utils/xhprof_lib.php</string> * </element> * <element key="xhprofRunsFile"> * <string>/var/www/xhprof_lib/utils/xhprof_runs.php</string> * </element> * <element key="xhprofWeb"> * <string>http://localhost/xhprof_html/index.php</string> * </element> * <element key="appNamespace"> * <string>Doctrine2</string> * </element> * <element key="xhprofFlags"> * <string>XHPROF_FLAGS_CPU,XHPROF_FLAGS_MEMORY</string> * </element> * </array> * </arguments> * </listener> * </listeners> * </code> * * @package PHPUnit * @subpackage Util_Log * @author Benjamin Eberlei <kontakt@beberlei.de> * @author Sebastian Bergmann <sebastian@phpunit.de> * @copyright 2002-2011 Sebastian Bergmann <sebastian@phpunit.de> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version Release: 3.5.13 * @link http://www.phpunit.de/ * @since Class available since Release 3.5.0 */ class PHPUnit_Util_Log_XHProf implements PHPUnit_Framework_TestListener { /** * @var array */ protected $runs = array(); /** * @var array */ protected $options = array(); /** * @var integer */ protected $suites = 0; /** * Constructor. * * @param array $options */ public function __construct(array $options = array()) { if (!extension_loaded('xhprof')) { throw new RuntimeException( 'The XHProf extension is required for this listener to work.' ); } if (!isset($options['appNamespace'])) { throw new InvalidArgumentException( 'The "appNamespace" option is not set.' ); } if (!isset($options['xhprofLibFile']) || !file_exists($options['xhprofLibFile'])) { throw new InvalidArgumentException( 'The "xhprofLibFile" option is not set or the configured file does not exist' ); } if (!isset($options['xhprofRunsFile']) || !file_exists($options['xhprofRunsFile'])) { throw new InvalidArgumentException( 'The "xhprofRunsFile" option is not set or the configured file does not exist' ); } require_once $options['xhprofLibFile']; require_once $options['xhprofRunsFile']; $this->options = $options; } /** * An error occurred. * * @param PHPUnit_Framework_Test $test * @param Exception $e * @param float $time */ public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { } /** * A failure occurred. * * @param PHPUnit_Framework_Test $test * @param PHPUnit_Framework_AssertionFailedError $e * @param float $time */ public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { } /** * Incomplete test. * * @param PHPUnit_Framework_Test $test * @param Exception $e * @param float $time */ public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) { } /** * Skipped test. * * @param PHPUnit_Framework_Test $test * @param Exception $e * @param float $time */ public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { } /** * A test started. * * @param PHPUnit_Framework_Test $test */ public function startTest(PHPUnit_Framework_Test $test) { if (!isset($this->options['xhprofFlags'])) { $flags = XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY; } else { $flags = 0; foreach (explode(',', $this->options['xhprofFlags']) as $flag) { $flags += constant($flag); } } xhprof_enable($flags); } /** * A test ended. * * @param PHPUnit_Framework_Test $test * @param float $time */ public function endTest(PHPUnit_Framework_Test $test, $time) { $data = xhprof_disable(); $runs = new XHProfRuns_Default; $run = $runs->save_run($data, $this->options['appNamespace']); $this->runs[] = $this->options['xhprofWeb'] . '?run=' . $run . '&source=' . $this->options['appNamespace']; } /** * A test suite started. * * @param PHPUnit_Framework_TestSuite $suite */ public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { $this->suites++; } /** * A test suite ended. * * @param PHPUnit_Framework_TestSuite $suite */ public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { $this->suites--; if ($this->suites == 0) { print "\n\nXHProf runs: " . count($this->runs) . "\n"; foreach ($this->runs as $run) { print ' * ' . $run . "\n"; } print "\n"; } } }
{ "content_hash": "8f6826f21c11393beab12c88de2bb4da", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 110, "avg_line_length": 26.90909090909091, "alnum_prop": 0.5385846372688478, "repo_name": "mgrauer/midas3score", "id": "42d8a1459352660688381a041853781e17e25bff", "size": "7670", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tests/library/PHPUnit/PHPUnit/Util/Log/XHProf.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "198666" }, { "name": "C", "bytes": "1028" }, { "name": "C++", "bytes": "31222" }, { "name": "Java", "bytes": "34890" }, { "name": "JavaScript", "bytes": "664866" }, { "name": "PHP", "bytes": "29033551" }, { "name": "Python", "bytes": "16812" }, { "name": "Shell", "bytes": "3319" } ], "symlink_target": "" }
namespace System.Management { public enum TextFormat { Mof = 0 } }
{ "content_hash": "ca4bb0d7fbdc6fbda3c606d85809d96c", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 27, "avg_line_length": 9.125, "alnum_prop": 0.6712328767123288, "repo_name": "jjenki11/blaze-chem-rendering", "id": "f06de29a8fa3c3768a241334373786f0430ecb48", "size": "1310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "qca_designer/lib/ml-pnet-0.8.1/mcs-sources/class/System.Management/System.Management/TextFormat.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "2476" } ], "symlink_target": "" }
/** Beispiel HTTP PUT */ #include "mbed.h" #include "HTTPClient.h" #include "data/HTTPText.h" #include "EthernetInterface.h" EthernetInterface eth; // HTTPClient Hilfsklasse HTTPClient http; // I/O Buffer char str[512]; DigitalOut myled(LED1); int main() { printf("HTTP Client - PUT\n"); eth.init(); eth.connect(); while(1) { myled = 1; // Daten zum senden aufbereiten HTTPText outText("Das sind Daten fuer den Server"); // Hilfsklasse um die Response vom Server zu formatieren HTTPText inText(str, 512); int ret = http.put("http://httpbin.org/put", outText, &inText); // lokale Variante mit CGI-Script auf IoT USB Stick. Wenn nicht Funktioniert: iot-stick durch IP-Adresse ersetzen // int ret = http.put("http://iot-stick/rest/cgi-bin/rest?test.txt", outText, &inText); if (!ret) { printf("Executed PUT successfully - read %d characters\n", strlen(str)); printf("Result: %s\n", str); } else { printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); } myled = 0; wait(10); } //eth.disconnect(); }
{ "content_hash": "84db8f7ff75cfb0f5eff58ab9953458e", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 121, "avg_line_length": 26.918367346938776, "alnum_prop": 0.5489006823351024, "repo_name": "mc-b/IoTKitV2", "id": "6da08b90c19808cf99fe4d3191c432d0538e68fc", "size": "1319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "http/HTTP_PUT/src/main.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "70975" }, { "name": "C++", "bytes": "667421" }, { "name": "CSS", "bytes": "7594" }, { "name": "Dockerfile", "bytes": "178" }, { "name": "HTML", "bytes": "9096" }, { "name": "JavaScript", "bytes": "647" }, { "name": "Ruby", "bytes": "3589" }, { "name": "Shell", "bytes": "2073" } ], "symlink_target": "" }
package org.knowm.xchange.examples.btcchina.fix; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.knowm.xchange.btcchina.service.fix.BTCChinaApplication; import org.knowm.xchange.btcchina.service.fix.fix44.BTCChinaMessageFactory; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.marketdata.Ticker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.ConfigError; import quickfix.DoNotSend; import quickfix.FileLogFactory; import quickfix.FileStoreFactory; import quickfix.Initiator; import quickfix.LogFactory; import quickfix.MessageFactory; import quickfix.MessageStoreFactory; import quickfix.SessionID; import quickfix.SessionNotFound; import quickfix.SessionSettings; import quickfix.SocketInitiator; public class BTCChinaClient { private static final Logger log = LoggerFactory.getLogger(BTCChinaClient.class); public static void main(String args[]) throws ConfigError, DoNotSend, IOException, SessionNotFound, InterruptedException { final String accessKey = args[0]; final String secretKey = args[1]; BTCChinaApplication app = new BTCChinaApplication() { @Override public void onLogon(quickfix.SessionID sessionId) { super.onLogon(sessionId); this.requestSnapshot(CurrencyPair.BTC_CNY, sessionId); this.requestSnapshotAndUpdates(CurrencyPair.BTC_CNY, sessionId); } @Override protected void onTicker(Ticker ticker, SessionID id) { log.info("ticker: {}", ticker); } @Override protected void onAccountInfo(String accReqId, AccountInfo accountInfo, SessionID id) { log.info("accReqId: {}, accountInfo: {}", accReqId, accountInfo); } }; InputStream inputStream = BTCChinaClient.class.getResourceAsStream("client.cfg"); SessionSettings settings = new SessionSettings(inputStream); MessageStoreFactory storeFactory = new FileStoreFactory(settings); LogFactory logFactory = new FileLogFactory(settings); MessageFactory messageFactory = new BTCChinaMessageFactory(); Initiator initiator = new SocketInitiator(app, storeFactory, settings, logFactory, messageFactory); initiator.start(); while (!initiator.isLoggedOn()) { TimeUnit.SECONDS.sleep(1); } log.info("logged on."); SessionID sessionId = initiator.getSessions().get(0); // account info request: U1000 app.requestAccountInfo(accessKey, secretKey, UUID.randomUUID().toString(), sessionId); log.info("account info request sent."); TimeUnit.SECONDS.sleep(30); log.info("exiting..."); } }
{ "content_hash": "0a939ed480808b083e2e4157bf8ae507", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 124, "avg_line_length": 33.18292682926829, "alnum_prop": 0.75303197353914, "repo_name": "gaborkolozsy/XChange", "id": "3ecf26ee3f83be3b25ae55290f30973a4281e5fc", "size": "2721", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "xchange-examples/src/main/java/org/knowm/xchange/examples/btcchina/fix/BTCChinaClient.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "5533267" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-us" xml:lang="en-us"> <!-- 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. --> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta name="copyright" content="(C) Copyright 2005" /> <meta name="DC.rights.owner" content="(C) Copyright 2005" /> <meta content="public" name="security" /> <meta content="index,follow" name="Robots" /> <meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' /> <meta content="task" name="DC.Type" /> <meta name="DC.Title" content="Turning on the trace facility" /> <meta scheme="URI" name="DC.Relation" content="tadmintracefacility.html" /> <meta content="XHTML" name="DC.Format" /> <meta content="tadminadv804410" name="DC.Identifier" /> <meta content="en-us" name="DC.Language" /> <link href="commonltr.css" type="text/css" rel="stylesheet" /> <title>Turning on the trace facility</title> </head> <body id="tadminadv804410"><a name="tadminadv804410"><!-- --></a> <h1 class="topictitle1">Turning on the trace facility</h1> <div> <ol> <li class="stepexpand"><span>Turn on tracing for all sessions by specifying the following property:</span> <pre>derby.drda.traceAll=true </pre> Alternatively, while the Network Server is running, you can use the following command to turn on the trace facility:<pre>java org.apache.derby.drda.NetworkServerControl trace on [-s &lt;<em>connection number</em>&gt;] [-h &lt;<em>hostname</em>&gt;][-p &lt;<em>portnumber</em>&gt;] </pre> If you specify a &lt;<em>connection number</em>&gt;, tracing will be turned on only for that connection.</li> <li class="stepexpand"><span>Set the location of the tracing files by specifying the following property:</span> <pre>derby.drda.traceDirectory=&lt;<em>directory for tracing files</em>&gt;</pre> Alternatively, while the Network Server is running, enter the following command to set the trace directory:<pre>java org.apache.derby.drda.NetworkServerControl traceDirectory &lt;<em>directory for tracing files</em>&gt; [-h &lt;<em>hostname</em>&gt;] [-p &lt;<em>portnumber</em>&gt;] </pre> <p>You need to specify only the directory where the tracing files will reside. The names of the tracing files are determined by the system. If you do not set a trace directory, the tracing files will be placed in derby.system.home.</p> <div class="p"> The Network Server will attempt to create the trace directory (and any parent directories) if they do not exist. This will require that the Java security policy for <samp class="codeph">derbynet.jar</samp> permits verification of the existence of the named trace directory and all necessary parent directories. For each directory created, the policy must allow <pre> permission java.io.FilePermission "&lt;<em>directory</em>&gt;", "read,write"; </pre> and for the trace directory itself, the policy must allow <pre> permission java.io.FilePermission "&lt;<em>tracedirectory</em>&gt;${/}-", "write"; </pre> </div> <p> See <a href="tadminnetservcustom.html#tadminnetservcustom">Customizing the Network Server's security policy</a> for information about customizing the Network Server's security policy. </p> </li> </ol> </div> <div> <div class="familylinks"> <div class="parentlink"><strong>Parent topic:</strong> <a href="tadmintracefacility.html" title="">Controlling tracing by using the trace facility</a></div> </div> </div> </body> </html>
{ "content_hash": "f85587c01e0b660cff8705a2f1218aa4", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 261, "avg_line_length": 45.11764705882353, "alnum_prop": 0.7094741416775315, "repo_name": "mminella/jsr-352-ri-tck", "id": "af590291f1696824f75becf7c33aa5bb63faacc6", "size": "4602", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "JSR352.BinaryDependencies/shipped/derby/docs/html/adminguide/tadminadv804410.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1743336" }, { "name": "Perl", "bytes": "80042" }, { "name": "Racket", "bytes": "180" }, { "name": "Ruby", "bytes": "1444" }, { "name": "Shell", "bytes": "45633" } ], "symlink_target": "" }
class CreatePatients < ActiveRecord::Migration def change create_table :patients, id: :uuid, default: 'gen_random_uuid()',force:true do |t| t.string :name t.string :gender t.date :date_of_birth t.string :phone t.string :email t.string :next_of_kin t.string :next_of_kin_contact t.timestamps null: false end end end
{ "content_hash": "70a81d9bb8e27b86ef24dfc56e990bb4", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 89, "avg_line_length": 29.066666666666666, "alnum_prop": 0.5458715596330275, "repo_name": "Nanzala/PMHRS", "id": "595ede237f82c9d978faf0f1f6423c2452ea9447", "size": "436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20151115213650_create_patients.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "337618" }, { "name": "CoffeeScript", "bytes": "2321" }, { "name": "HTML", "bytes": "53450" }, { "name": "JavaScript", "bytes": "683" }, { "name": "Ruby", "bytes": "74751" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- --> <resources> <dimen name="key_height">50dip</dimen> <!-- <dimen name="candidate_font_height">30sp</dimen> <dimen name="candidate_vertical_padding">18sp</dimen> --> <dimen name="candidate_font_height">20sp</dimen> <dimen name="candidate_vertical_padding">13sp</dimen> <dimen name="popup_char_height">40sp</dimen> <dimen name="popup_gloss_height">16sp</dimen> </resources>
{ "content_hash": "f24456d06e6e045e1b88598a2705eb60", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 57, "avg_line_length": 28.5, "alnum_prop": 0.6469298245614035, "repo_name": "divec/literatim", "id": "0558edbf7bb4020a7dee87f599d884e312300620", "size": "1082", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/values/dimens.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "100559" } ], "symlink_target": "" }
import {OnDestroy} from "@angular/core"; import {Subscription} from "rxjs"; export class BaseComponent implements OnDestroy { protected subscriptions: Subscription[] = []; constructor() { // ensure 'ngOnDestroy' is called anyway, independently of the child class implementation; based on // https://stackoverflow.com/questions/54979862/ensure-super-ondestroy-in-derived-component#56303624 and // https://stacksandfoundations.wordpress.com/2016/06/24/using-class-inheritance-to-hook-to-angular2-component-lifecycle/ const ngOnDestroyRef = this.ngOnDestroy; this.ngOnDestroy = () => { ngOnDestroyRef.call(this); this.unsubscribeAll(); }; } ngOnDestroy(): void { this.unsubscribeAll(); } protected unsubscribeAll(): void { if (this.subscriptions) { this.subscriptions.forEach(subscription => subscription.unsubscribe()); this.subscriptions.length = 0; } } }
{ "content_hash": "edc21b5141076bc5c6e1057d8774b452", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 129, "avg_line_length": 31.59375, "alnum_prop": 0.6547972304648862, "repo_name": "privet56/ng2Goodies", "id": "77b0aea09c487716b46607dd5f3b65abeb5a2006", "size": "1011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cheatsheets/ng/base-component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5829" }, { "name": "C", "bytes": "135411" }, { "name": "C#", "bytes": "63828" }, { "name": "C++", "bytes": "1125905" }, { "name": "CSS", "bytes": "207170" }, { "name": "Clarion", "bytes": "3810" }, { "name": "HTML", "bytes": "62610" }, { "name": "Java", "bytes": "5136" }, { "name": "JavaScript", "bytes": "459951" }, { "name": "Objective-C", "bytes": "24680" }, { "name": "Objective-C++", "bytes": "8477" }, { "name": "Perl", "bytes": "45398" }, { "name": "PowerShell", "bytes": "509" }, { "name": "Python", "bytes": "16469" }, { "name": "Raku", "bytes": "457" }, { "name": "Ruby", "bytes": "1860" }, { "name": "SCSS", "bytes": "109147" }, { "name": "Shell", "bytes": "3776" }, { "name": "TypeScript", "bytes": "59366" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2017-2018 The LitecoinZ developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_AMOUNT_H #define BITCOIN_AMOUNT_H #include "serialize.h" #include <stdlib.h> #include <string> typedef int64_t CAmount; static const CAmount COIN = 100000000; static const CAmount CENT = 1000000; extern const std::string CURRENCY_UNIT; /** No amount larger than this (in satoshi) is valid. * * Note that this constant is *not* the total money supply, which in LitecoinZ * currently happens to be less than 84,000,000 LTZ for various reasons, but * rather a sanity check. As this sanity check is used by consensus-critical * validation code, the exact value of the MAX_MONEY constant is consensus * critical; in unusual circumstances like a(nother) overflow bug that allowed * for the creation of coins out of thin air modification could lead to a fork. * */ static const CAmount MAX_MONEY = 84000000 * COIN; inline bool MoneyRange(const CAmount& nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Type-safe wrapper class for fee rates * (how much to pay based on transaction size) */ class CFeeRate { private: CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes public: CFeeRate() : nSatoshisPerK(0) { } explicit CFeeRate(const CAmount& _nSatoshisPerK): nSatoshisPerK(_nSatoshisPerK) { } CFeeRate(const CAmount& nFeePaid, size_t nSize); CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; } CAmount GetFee(size_t size) const; // unit returned is satoshis CAmount GetFeePerK() const { return GetFee(1000); } // satoshis-per-1000-bytes friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; } friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; } friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; } friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; } friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; } std::string ToString() const; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(nSatoshisPerK); } }; #endif // BITCOIN_AMOUNT_H
{ "content_hash": "830253272724cb2af7e5c85c63e55cbe", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 111, "avg_line_length": 40.50769230769231, "alnum_prop": 0.7299658184580327, "repo_name": "litecoinz-project/litecoinz", "id": "8dbc11c97f90e41bc753a9cc445d679c4f016319", "size": "2633", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/amount.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28453" }, { "name": "C", "bytes": "730195" }, { "name": "C++", "bytes": "6761814" }, { "name": "HTML", "bytes": "20970" }, { "name": "Java", "bytes": "30291" }, { "name": "M4", "bytes": "226422" }, { "name": "Makefile", "bytes": "154159" }, { "name": "Objective-C", "bytes": "6536" }, { "name": "Objective-C++", "bytes": "7240" }, { "name": "Python", "bytes": "906305" }, { "name": "Shell", "bytes": "103060" } ], "symlink_target": "" }
function createDonutCharts() { $("<style type='text/css' id='dynamic' />").appendTo("head"); $("div[chart-type*=donut]").each(function () { var d = $(this); var id = $(this).attr('id'); var max = $(this).data('chart-max'); if ($(this).data('chart-text')) { var text = $(this).data('chart-text'); } else { var text = ""; } if ($(this).data('chart-caption')) { var caption = $(this).data('chart-caption'); } else { var caption = ""; } if ($(this).data('chart-initial-rotate')) { var rotate = $(this).data('chart-initial-rotate'); } else { var rotate = 0; } var segments = $(this).data('chart-segments'); for (var i = 0; i < Object.keys(segments).length; i++) { var s = segments[i]; var start = ((s[0] / max) * 360) + rotate; var deg = ((s[1] / max) * 360); if (s[1] >= (max / 2)) { d.append('<div class="large donut-bite" data-segment-index="' + i + '"> '); } else { d.append('<div class="donut-bite" data-segment-index="' + i + '"> '); } var style = $("#dynamic").text() + "#" + id + " .donut-bite[data-segment-index=\"" + i + "\"]{-moz-transform:rotate(" + start + "deg);-ms-transform:rotate(" + start + "deg);-webkit-transform:rotate(" + start + "deg);-o-transform:rotate(" + start + "deg);transform:rotate(" + start + "deg);}#" + id + " .donut-bite[data-segment-index=\"" + i + "\"]:BEFORE{-moz-transform:rotate(" + deg + "deg);-ms-transform:rotate(" + deg + "deg);-webkit-transform:rotate(" + deg + "deg);-o-transform:rotate(" + deg + "deg);transform:rotate(" + deg + "deg); background-color: " + s[2] + ";}#" + id + " .donut-bite[data-segment-index=\"" + i + "\"]:BEFORE{ background-color: " + s[2] + ";}#" + id + " .donut-bite[data-segment-index=\"" + i + "\"].large:AFTER{ background-color: " + s[2] + ";}"; $("#dynamic").text(style); } d.children().first().before("<div class='donut-hole'><span class='donut-filling'>" + text + "</span></div>"); d.append("<div class='donut-caption-wrapper'><span class='donut-caption'>" + caption + "</span></div>"); }); } $(document).ready(function () { createDonutCharts(); });
{ "content_hash": "f68f829f5417a84e6a2e89b97c1094c4", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 788, "avg_line_length": 54, "alnum_prop": 0.49957912457912457, "repo_name": "madcore-ai/containers", "id": "28ee735600d6d9822980ea2b65848b2904a474ab", "size": "2376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pdfkit/js/donut-chart.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20441" }, { "name": "HTML", "bytes": "17144" }, { "name": "JavaScript", "bytes": "2376" }, { "name": "Python", "bytes": "65771" }, { "name": "Shell", "bytes": "1756" } ], "symlink_target": "" }
<stix:STIX_Package xmlns:cyboxCommon="http://cybox.mitre.org/common-2" xmlns:cybox="http://cybox.mitre.org/cybox-2" xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2" xmlns:example="http://example.com" xmlns:incident="http://stix.mitre.org/Incident-1" xmlns:ttp="http://stix.mitre.org/TTP-1" xmlns:ta="http://stix.mitre.org/ThreatActor-1" xmlns:stixCommon="http://stix.mitre.org/common-1" xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1" xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1" xmlns:stix="http://stix.mitre.org/stix-1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xal="urn:oasis:names:tc:ciq:xal:3" xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3" xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3" xsi:schemaLocation=" http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd http://stix.mitre.org/TTP-1 http://stix.mitre.org/XMLSchema/ttp/1.1.1/ttp.xsd http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-efb46caa-ded3-4b7a-9a77-0fd2004ed9ff" version="1.1.1" timestamp="2013-10-15T12:29:00+00:00"> <stix:TTPs> <stix:TTP id="example:ttp-eeec868a-72cf-4bae-8755-4869327ab483" timestamp="2014-12-22T16:28:22.115000+00:00" xsi:type='ttp:TTPType'> <ttp:Behavior> <ttp:Attack_Patterns> <ttp:Attack_Pattern capec_id="CAPEC-66"> <ttp:Title>SQL Injection</ttp:Title> </ttp:Attack_Pattern> </ttp:Attack_Patterns> </ttp:Behavior> </stix:TTP> </stix:TTPs> <stix:Incidents> <stix:Incident id="example:incident-9876947b-a5c9-4b0e-8f87-103d3e9604ed" timestamp="2014-05-18T15:34:56+00:00" xsi:type='incident:IncidentType'> <incident:Title> Hacker Cold z3ro of the Palestine Elite Force hacker group recently claimed to have breached the Cologne, Germany-based telecom provider NetCologne, and published user information on Pastebin. Above the data dump, the hacker wrote, "Hacked by C0ld z3ro &amp; LulzSecRoot from Palestine Elite Force / Long Live Palestine," along with what appears to be basic information on the SQL injection vulnerability leveraged to breach the site. The data published on Pastebin includes 15 user names, encrypted passwords, e-mail addresses, registration dates and display names. </incident:Title> <incident:External_ID source="VERIS">68D73719-7364-4090-BB03-4BCE378F6DD2</incident:External_ID> <incident:Time> <incident:Initial_Compromise precision="month">2013-09-01T00:00:00</incident:Initial_Compromise> </incident:Time> <incident:Reporter> <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'> <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"> <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"> <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">whbaker</xnl:NameLine> </xpil:PartyName> </ExtSch:Specification> </stixCommon:Identity> </incident:Reporter> <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'> <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"> <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"> <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">NetCologne</xnl:NameLine> </xpil:PartyName> <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"> <xpil:Address> <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3"> <xal:NameElement>DE</xal:NameElement> </xal:Country> </xpil:Address> </xpil:Addresses> </ExtSch:Specification> </incident:Victim> <incident:Affected_Assets> <incident:Affected_Asset> <incident:Type>Web application</incident:Type> <incident:Nature_Of_Security_Effect> <incident:Property_Affected> <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property> <incident:Description_Of_Effect>Credentials: 15; Notes:data dumped on pastebin</incident:Description_Of_Effect> </incident:Property_Affected> <incident:Property_Affected> <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property> <incident:Description_Of_Effect>Modify data,Repurpose,Defacement; Notes:defacement</incident:Description_Of_Effect> </incident:Property_Affected> <incident:Property_Affected> <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Availability</incident:Property> <incident:Type_Of_Availability_Loss xsi:type="stixVocabs:AvailabilityLossTypeVocab-1.1.1">Loss</incident:Type_Of_Availability_Loss> </incident:Property_Affected> </incident:Nature_Of_Security_Effect> </incident:Affected_Asset> </incident:Affected_Assets> <incident:Impact_Assessment> <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification> </incident:Impact_Assessment> <incident:Leveraged_TTPs> <incident:Leveraged_TTP> <stixCommon:TTP idref="example:ttp-eeec868a-72cf-4bae-8755-4869327ab483" xsi:type='ttp:TTPType'/> </incident:Leveraged_TTP> </incident:Leveraged_TTPs> <incident:Attributed_Threat_Actors> <incident:Threat_Actor> <stixCommon:Threat_Actor idref="example:threatactor-dd97f83d-82bb-4fc9-96ba-36e3933822e8" xsi:type='ta:ThreatActorType'/> </incident:Threat_Actor> </incident:Attributed_Threat_Actors> <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise> <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Agent Disclosure</incident:Discovery_Method> <incident:Information_Source> <stixCommon:Identity> <stixCommon:Name>vcdb</stixCommon:Name> </stixCommon:Identity> <stixCommon:Tools> <cyboxCommon:Tool> <cyboxCommon:Name>veris2stix</cyboxCommon:Name> <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor> <cyboxCommon:Version>0.1</cyboxCommon:Version> </cyboxCommon:Tool> <cyboxCommon:Tool> <cyboxCommon:Name>VERIS schema</cyboxCommon:Name> <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor> <cyboxCommon:Version>1.3.0</cyboxCommon:Version> </cyboxCommon:Tool> </stixCommon:Tools> <stixCommon:References> <stixCommon:Reference>http://www.esecurityplanet.com/hackers/palestine-elite-force-hackers-hit-german-isp-netcologne.html</stixCommon:Reference> </stixCommon:References> </incident:Information_Source> </stix:Incident> </stix:Incidents> <stix:Threat_Actors> <stix:Threat_Actor id="example:threatactor-dd97f83d-82bb-4fc9-96ba-36e3933822e8" timestamp="2014-12-22T16:28:22.115000+00:00" xsi:type='ta:ThreatActorType'> <ta:Description>Notes: RedHack</ta:Description> <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'> <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"> <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"> <xpil:Address> <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3"> <xal:NameElement>PS</xal:NameElement> </xal:Country> </xpil:Address> </xpil:Addresses> </ExtSch:Specification> </ta:Identity> <ta:Type timestamp="2014-12-22T16:28:22.115000+00:00"> <stixCommon:Value xsi:type="stixVocabs:ThreatActorTypeVocab-1.0">Hacktivist</stixCommon:Value> </ta:Type> <ta:Motivation timestamp="2014-12-22T16:28:22.115000+00:00"> <stixCommon:Value xsi:type="stixVocabs:MotivationVocab-1.1">Ego</stixCommon:Value> </ta:Motivation> <ta:Observed_TTPs> <ta:Observed_TTP> <stixCommon:TTP idref="example:ttp-eeec868a-72cf-4bae-8755-4869327ab483" xsi:type='ttp:TTPType'/> </ta:Observed_TTP> </ta:Observed_TTPs> </stix:Threat_Actor> </stix:Threat_Actors> </stix:STIX_Package>
{ "content_hash": "613c1e0171885d6a1dd281d762d2372d", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 616, "avg_line_length": 65.85161290322581, "alnum_prop": 0.6562163221318703, "repo_name": "rpiazza/veris-to-stix", "id": "28af2e06aae9f2318f950e66647f68e13952eddb", "size": "10207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "results/68D73719-7364-4090-BB03-4BCE378F6DD2.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "48356" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct bad_weekday</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../date_time/doxy.html#header.boost.date_time.gregorian.greg_weekday_hpp" title="Header &lt;boost/date_time/gregorian/greg_weekday.hpp&gt;"> <link rel="prev" href="../../load_idp98620960.html" title="Function template load"> <link rel="next" href="greg_weekday.html" title="Class greg_weekday"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../../load_idp98620960.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../date_time/doxy.html#header.boost.date_time.gregorian.greg_weekday_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="greg_weekday.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.gregorian.bad_weekday"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct bad_weekday</span></h2> <p>boost::gregorian::bad_weekday &#8212; Exception that flags that a weekday number is incorrect. </p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../date_time/doxy.html#header.boost.date_time.gregorian.greg_weekday_hpp" title="Header &lt;boost/date_time/gregorian/greg_weekday.hpp&gt;">boost/date_time/gregorian/greg_weekday.hpp</a>&gt; </span> <span class="keyword">struct</span> <a class="link" href="bad_weekday.html" title="Struct bad_weekday">bad_weekday</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">out_of_range</span> <span class="special">{</span> <span class="comment">// <a class="link" href="bad_weekday.html#boost.gregorian.bad_weekdayconstruct-copy-destruct">construct/copy/destruct</a></span> <a class="link" href="bad_weekday.html#idp110252304-bb"><span class="identifier">bad_weekday</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp202433792"></a><h2>Description</h2> <div class="refsect2"> <a name="idp202434208"></a><h3> <a name="boost.gregorian.bad_weekdayconstruct-copy-destruct"></a><code class="computeroutput">bad_weekday</code> public construct/copy/destruct</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><a name="idp110252304-bb"></a><span class="identifier">bad_weekday</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li></ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2001-2005 CrystalClear Software, Inc<p>Subject to the Boost Software License, Version 1.0. (See accompanying file <code class="filename">LICENSE_1_0.txt</code> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)</p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../../load_idp98620960.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../date_time/doxy.html#header.boost.date_time.gregorian.greg_weekday_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="greg_weekday.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "951e3dd7faa42046ea98a965ce5ee8b8", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 479, "avg_line_length": 80.88524590163935, "alnum_prop": 0.671868666396433, "repo_name": "MisterTea/HyperNEAT", "id": "738aaab8a6d05df7d4dfee8d89d08a28101061f5", "size": "4934", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "boost_1_57_0/doc/html/boost/gregorian/bad_weekday.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "91920" }, { "name": "Assembly", "bytes": "324212" }, { "name": "Batchfile", "bytes": "32748" }, { "name": "Bison", "bytes": "10393" }, { "name": "C", "bytes": "4172510" }, { "name": "C#", "bytes": "97576" }, { "name": "C++", "bytes": "163699928" }, { "name": "CLIPS", "bytes": "7056" }, { "name": "CMake", "bytes": "92433" }, { "name": "CSS", "bytes": "248695" }, { "name": "Cuda", "bytes": "26521" }, { "name": "DIGITAL Command Language", "bytes": "13695" }, { "name": "Fortran", "bytes": "1387" }, { "name": "Gnuplot", "bytes": "2361" }, { "name": "Groff", "bytes": "15745" }, { "name": "HTML", "bytes": "145331688" }, { "name": "IDL", "bytes": "15" }, { "name": "JFlex", "bytes": "1290" }, { "name": "JavaScript", "bytes": "134468" }, { "name": "Makefile", "bytes": "1053202" }, { "name": "Max", "bytes": "37424" }, { "name": "Module Management System", "bytes": "1593" }, { "name": "Objective-C", "bytes": "33988" }, { "name": "Objective-C++", "bytes": "214" }, { "name": "PHP", "bytes": "60249" }, { "name": "Pascal", "bytes": "41721" }, { "name": "Perl", "bytes": "30505" }, { "name": "Perl6", "bytes": "2130" }, { "name": "PostScript", "bytes": "81121" }, { "name": "Python", "bytes": "1943687" }, { "name": "QML", "bytes": "613" }, { "name": "QMake", "bytes": "7148" }, { "name": "Rebol", "bytes": "372" }, { "name": "SAS", "bytes": "1776" }, { "name": "Scilab", "bytes": "107733" }, { "name": "Shell", "bytes": "394881" }, { "name": "Tcl", "bytes": "29403" }, { "name": "TeX", "bytes": "1196144" }, { "name": "XSLT", "bytes": "770994" } ], "symlink_target": "" }
<?php namespace Tests; use Anekdotes\Meta\StaticRegistry; use PHPUnit\Framework\TestCase; /** * @runTestsInSeparateProcesses */ final class StaticRegistryTest extends TestCase { public function testLoadAndAll() { StaticRegistry::load(['toaster' => 'Toast', 'Mathieu' => 'Patate']); StaticRegistry::load(['Sam' => 'Cod']); $this->assertEquals(StaticRegistry::all(), ['toaster' => 'Toast', 'Mathieu' => 'Patate', 'Sam' => 'Cod']); } public function testHasTrue() { StaticRegistry::load(['Test' => 'Toast']); $this->assertTrue(StaticRegistry::has('Test')); } public function testHasFalse() { StaticRegistry::load(['Test' => 'Toast']); $this->assertFalse(StaticRegistry::has('Toast')); } public function testSetGet() { StaticRegistry::set('Toaster', 'Toast'); $this->assertEquals(StaticRegistry::get('Toaster'), 'Toast'); } public function testGetDefault() { $this->assertEquals(StaticRegistry::get('Toaster', 'Toast'), 'Toast'); } public function testGroup() { StaticRegistry::load(['toaster.Sam' => 'CoD', 'toaster.test' => 'Toast', 'Mathieu' => 'Patate']); $this->assertEquals(StaticRegistry::group('toaster'), ['Sam' => 'CoD', 'test' => 'Toast']); } }
{ "content_hash": "461bf4aa3b0ea8e73b519c70e45f7508", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 114, "avg_line_length": 24.454545454545453, "alnum_prop": 0.59182156133829, "repo_name": "anekdotes/meta", "id": "5e826c74c338974f5c26fe43df94ddfc529bfd67", "size": "1583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/StaticRegistryTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "21968" } ], "symlink_target": "" }
DEBIAN_FRONTEND=noninteractive TZ=Europe/London . "/srv/provision/tests/provisioners.sh" pre_hook provision_main provision_dashboard if [ "${VVV_DOCKER}" != 1 ]; then provision_utility_sources provision_utilities provision_sites fi post_hook
{ "content_hash": "20802749e5a1b96c0cb8721cc0b1253c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 40, "avg_line_length": 17.642857142857142, "alnum_prop": 0.7773279352226721, "repo_name": "trepmal/varying-vagrant-vagrants", "id": "5f28aa0c16d4b6df76088f473064928d01c60bb8", "size": "259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "provision/tests/run-provisioners.sh", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "2516" }, { "name": "Shell", "bytes": "64009" }, { "name": "Vim script", "bytes": "1012" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe RegionValidator do class RegionTest include ActiveModel::Validations validates_with RegionValidator attr_accessor :country attr_accessor :region end describe '#validate' do before :each do @region_test = RegionTest.new end it 'requires country to validate' do expect(@region_test).to_not be_valid expect(@region_test).to have_exactly(1).errors_on(:region) end context 'in US regions' do before :each do @region_test.country = 'USA' end context 'is not valid when' do it 'is fewer than 2 characters' do @region_test.region = '' expect(@region_test).to_not be_valid expect(@region_test).to have_exactly(1).errors_on(:region) end it 'is more than 2 characters' do @region_test.region = 'ABC' expect(@region_test).to_not be_valid expect(@region_test).to have_exactly(1).errors_on(:region) end end context 'is valid when' do it 'is specified' do # Presently no validation that region is a real state @region_test.region = 'AB' expect(@region_test).to be_valid end end end context 'for Candian regions' do before :each do @region_test.country = 'CAN' end context 'is not valid when' do it 'is fewer than 2 characters' do @region_test.region = '' expect(@region_test).to_not be_valid expect(@region_test).to have_exactly(1).errors_on(:region) end it 'is more than 2 characters' do @region_test.region = 'ABC' expect(@region_test).to_not be_valid expect(@region_test).to have_exactly(1).errors_on(:region) end it 'is not a real province' do @region_test.region = 'ZZ' expect(@region_test).to_not be_valid expect(@region_test).to have_exactly(1).errors_on(:region) end end context 'is valid when' do it 'is a real province' do @region_test.region = 'AB' expect(@region_test).to be_valid end end end end end
{ "content_hash": "31f57a1f01d3d4826b93ddd913a4c09f", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 68, "avg_line_length": 26.783132530120483, "alnum_prop": 0.5856950067476383, "repo_name": "ophrescue/RescueRails", "id": "fa6d9083b254f2a9af19ae018e72b9099737fd14", "size": "2223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/validators/region_validator_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "774988" }, { "name": "JavaScript", "bytes": "232192" }, { "name": "Ruby", "bytes": "853583" }, { "name": "SCSS", "bytes": "20081" }, { "name": "Shell", "bytes": "168" } ], "symlink_target": "" }
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Rg.ApiTypes")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Rg.ApiTypes")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "7edc865a2dccae244407200d8f56cca3", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 84, "avg_line_length": 36.9, "alnum_prop": 0.7217705510388437, "repo_name": "jenyayel/rgroup", "id": "85f8eb5676acc80bc0d9be844f7d8fd16153f5c4", "size": "1110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Rg.ApiTypes/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "199" }, { "name": "C#", "bytes": "585975" }, { "name": "CSS", "bytes": "481200" }, { "name": "Groff", "bytes": "160" }, { "name": "HTML", "bytes": "114270" }, { "name": "JavaScript", "bytes": "708769" } ], "symlink_target": "" }
import numpy as np from measure_utilities import multitask from rlscore.utilities import array_tools def fscore_singletask(Y, P): correct = Y predictions = P assert len(correct) == len(predictions) TP = 0 FP = 0 FN = 0 for i in range(len(correct)): if correct[i] == 1: if predictions[i] > 0.: TP += 1 else: FN += 1 elif correct[i] == -1: if predictions[i] > 0.: FP += 1 else: assert False P = float(TP)/(TP+FP) R = float(TP)/(TP+FN) F = 2.*(P*R)/(P+R) return F def fscore_multitask(Y, P): return multitask(Y, P, fscore_singletask) def fscore(Y, P): """F1-Score. A performance measure for binary classification problems. F1 = 2*(Precision*Recall)/(Precision+Recall) If 2-dimensional arrays are supplied as arguments, then macro-averaged F-score is computed over the columns. Parameters ---------- Y: {array-like}, shape = [n_samples] or [n_samples, n_labels] Correct labels, must belong to set {-1,1} P: {array-like}, shape = [n_samples] or [n_samples, n_labels] Predicted labels, can be any real numbers. P[i]>0 is treated as a positive, and P[i]<=0 as a negative class prediction. Returns ------- fscore: float number between 0 and 1 """ Y = array_tools.as_labelmatrix(Y) P = array_tools.as_labelmatrix(P) return np.mean(fscore_multitask(Y,P)) fscore.iserror = False
{ "content_hash": "ff4a0ffca440e62474933691ef4ee65b", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 74, "avg_line_length": 27.29824561403509, "alnum_prop": 0.5726221079691517, "repo_name": "max291/RLScore", "id": "67c5fd9d83873a6242b73c66bf372b4e94b85654", "size": "1556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rlscore/measure/fscore_measure.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "11240" }, { "name": "Python", "bytes": "426056" } ], "symlink_target": "" }
<!DOCTYPE html> <head> <title>Home Display</title> <link rel="icon" href="/static/favicon.ico"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> {% assets "display_css" %} <link rel="stylesheet" type="text/css" href="{{ ASSET_URL }}" /> {% endassets %} </head> <body> <div class="container-fluid"> <p id="note"><strong>Tap to Switch</strong></p> <div id="dashboard"> {% for d in dashboard %} <div class="row"> {{ d|safe }} </div> {% endfor %} </div> <div id="widgets"> {% for widget in widgets %} <div class="col-md-2"> {{ widget | safe }} </div> {% endfor %} </div> <div id="update"> <h1>Upgrade in Progress. Please Wait.</h1> <div class="sk-folding-cube"> <div class="sk-cube1 sk-cube"></div> <div class="sk-cube2 sk-cube"></div> <div class="sk-cube4 sk-cube"></div> <div class="sk-cube3 sk-cube"></div> </div> </div> </body> {% assets "display_js" %} <script type="text/javascript" src="{{ ASSET_URL }}"></script> {% endassets %} </html>
{ "content_hash": "c46939e79fdc4cb9e37745e5fdd4f1cb", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 107, "avg_line_length": 31.097560975609756, "alnum_prop": 0.508235294117647, "repo_name": "keaneokelley/home", "id": "b1b37db9225acabb0070c12b35767c9713c42836", "size": "1275", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "home/web/templates/display.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4165" }, { "name": "HTML", "bytes": "50344" }, { "name": "JavaScript", "bytes": "15372" }, { "name": "Python", "bytes": "107285" } ], "symlink_target": "" }
namespace BlitzML { class LassoSolver : public SparseLinearSolver { public: virtual ~LassoSolver() { } protected: value_t compute_dual_obj() const; value_t compute_primal_obj_x() const; value_t compute_primal_obj_y() const; void update_bias(int max_newton_itr=4); void setup_proximal_newton_problem(); void perform_backtracking(); value_t update_coordinates_in_working_set(); void update_bias_subproblem() { } void scale_Delta_Aomega_by_2nd_derivatives() { } void unscale_Delta_Aomega_by_2nd_derivatives() { } inline value_t update_feature_lasso(index_t working_set_ind); }; }
{ "content_hash": "c20f88a28bd32900f4dc20f43de8b8f2", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 65, "avg_line_length": 24.53846153846154, "alnum_prop": 0.6818181818181818, "repo_name": "tbjohns/BlitzML", "id": "232f4c30ffa9bca47c4b4ad1e38867c94510c818", "size": "709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/blitzml/sparse_linear/lasso_solver.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "520072" }, { "name": "Makefile", "bytes": "672" }, { "name": "Python", "bytes": "62710" }, { "name": "Shell", "bytes": "62" } ], "symlink_target": "" }
Arbiter.MediaDownloader = function(_featureDb, _schema, _server, _mediaDir, _finishedLayers, _totalLayers){ this.db = _featureDb; this.schema = _schema; this.server = _server; this.mediaDir = _mediaDir; var credentials = Arbiter.Util.getEncodedCredentials( this.server.getUsername(), this.server.getPassword()); this.url = Arbiter.Util.getFileServiceURL(this.server.getUrl()); this.header = null; if(Arbiter.Util.existsAndNotNull(credentials)){ this.header = { Authorization: 'Basic ' + credentials }; } this.onDownloadComplete = null; this.onDownloadFailure = null; this.features = []; this.index = -1; this.finishedMediaCount = 0; this.totalMediaCount = 0; this.finishedFeatures = 0; this.totalFeatures = 0; this.finishedLayers = _finishedLayers; this.totalLayers = _totalLayers; }; Arbiter.MediaDownloader.prototype.pop = function(){ if(++this.index < this.features.length){ return this.features[this.index]; } return undefined; }; Arbiter.MediaDownloader.prototype.startDownload = function(onSuccess, onFailure){ var context = this; this.onDownloadComplete = onSuccess; this.onDownloadFailure = onFailure; this.getFeatures(function(){ var mediaDownloadCounter = new Arbiter.MediaDownloadCounter( context.schema, context.features); context.totalFeatures = context.features.length; context.totalMediaCount = mediaDownloadCounter.getCount(); if(context.totalMediaCount === 0){ var finishedMediaCount = 0; if(++context.finishedLayers === context.totalLayers){ Arbiter.Cordova.updateMediaDownloadingStatus(context.schema.getFeatureType(), finishedMediaCount, context.totalMediaCount, context.finishedLayers, context.totalLayers) } if(Arbiter.Util.funcExists(context.onDownloadComplete)){ context.onDownloadComplete(); } return; } context.startDownloadingNext(); }, function(e){ // TODO: Handle errors console.log(e); if(Arbiter.Util.funcExists(context.onDownloadComplete)){ context.onDownloadComplete(); } }); }; Arbiter.MediaDownloader.prototype.getFeatures = function(onSuccess, onFailure){ var context = this; var featureType = this.schema.getFeatureType(); this.db.transaction(function(tx){ tx.executeSql("select * from " + featureType + ";", [], function(tx, res){ for(var i = 0, count = res.rows.length; i < count; i++){ context.features.push(res.rows.item(i)); } if(Arbiter.Util.funcExists(onSuccess)){ onSuccess(); } }, function(tx, e){ if(Arbiter.Util.funcExists(onFailure)){ onFailure("MediaDownloader.js Error getting features - " + e); } }); }, function(e){ if(Arbiter.Util.funcExists(onFailure)){ onFailure("MediaDownloader.js Error getting features - " + e); } }); }; Arbiter.MediaDownloader.prototype.startDownloadingNext = function(){ var context = this; var feature = this.pop(); if(feature !== undefined){ var mediaDownloaderHelper = new Arbiter.MediaDownloaderHelper(feature, this.schema, this.header, this.url, this.mediaDir, this.finishedMediaCount, this.totalMediaCount, this.finishedFeatures, this.totalFeatures, this.finishedLayers, this.totalLayers); var proceed = function(_finishedMediaCount){ ++context.finishedFeatures; context.finishedMediaCount = _finishedMediaCount; context.startDownloadingNext(); }; mediaDownloaderHelper.startDownload(function(_finishedMediaCount){ proceed(_finishedMediaCount); }, function(e, _finishedMediaCount){ // If it was a timeout, cancel the remaining requests, otherwise continue if(e === Arbiter.Error.Sync.TIMED_OUT){ if(Arbiter.Util.existsAndNotNull(context.onDownloadFailure)){ onDownloadFailure(e); } }else{ proceed(_finishedMediaCount); } }); }else{ if(Arbiter.Util.funcExists(this.onDownloadComplete)){ this.onDownloadComplete(); } } };
{ "content_hash": "e618387319cce31239de5fec73604e7e", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 81, "avg_line_length": 24.368098159509202, "alnum_prop": 0.7031722054380665, "repo_name": "ROGUE-JCTD/Arbiter-Android", "id": "f3a9b52ce8449e4d32efd23c42f71dc8e9e82502", "size": "3972", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Arbiter-Android/assets/www/js/Arbiter/Syncing/Media/MediaDownloader.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7006" }, { "name": "CSS", "bytes": "52499" }, { "name": "HTML", "bytes": "32077377" }, { "name": "Java", "bytes": "974332" }, { "name": "JavaScript", "bytes": "10097267" }, { "name": "Python", "bytes": "185976" }, { "name": "Shell", "bytes": "6299" } ], "symlink_target": "" }
package com.amazonaws.services.workdocs.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/workdocs-2016-05-01/DeleteNotificationSubscription" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteNotificationSubscriptionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteNotificationSubscriptionResult == false) return false; DeleteNotificationSubscriptionResult other = (DeleteNotificationSubscriptionResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeleteNotificationSubscriptionResult clone() { try { return (DeleteNotificationSubscriptionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
{ "content_hash": "04293f1acdb9004bb178cd6fabdb86be", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 151, "avg_line_length": 29.18032786885246, "alnum_prop": 0.6511235955056179, "repo_name": "dagnir/aws-sdk-java", "id": "fb64dbfe824d0a966dafa351f338d59e66d71fb8", "size": "2360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-workdocs/src/main/java/com/amazonaws/services/workdocs/model/DeleteNotificationSubscriptionResult.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "157317" }, { "name": "Gherkin", "bytes": "25556" }, { "name": "Java", "bytes": "165755153" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
package com.google.appengine.tools.remoteapi; import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPMethod; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.URLFetchService; import com.google.appengine.api.urlfetch.URLFetchServiceFactory; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import org.apache.http.cookie.Cookie; import org.apache.http.entity.ContentType; /** * An {@link AppEngineClient} implementation that uses {@link URLFetchService}. * This implementation must be used when the client is an App Engine container * since URLFetchService is the only way to make HTTP requests in this * environment. * */ class HostedAppEngineClient extends AppEngineClient { private final URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService(); HostedAppEngineClient(RemoteApiOptions options, List<Cookie> authCookies, String appId) { super(options, authCookies, appId); } private void addCookies(HTTPRequest req) { for (Cookie cookie : getAuthCookies()) { req.addHeader( new HTTPHeader("Cookie", String.format("%s=%s", cookie.getName(), cookie.getValue()))); } } @Override public Response get(String path) throws IOException { return createResponse(doGet(path)); } private HTTPResponse doGet(String path) throws IOException { HTTPRequest req = new HTTPRequest(new URL(makeUrl(path)), HTTPMethod.GET); req.getFetchOptions().doNotFollowRedirects(); for (String[] headerPair : getHeadersForGet()) { req.addHeader(new HTTPHeader(headerPair[0], headerPair[1])); } addCookies(req); return urlFetch.fetch(req); } @Override public Response post(String path, String mimeType, byte[] body) throws IOException { return createResponse(doPost(path, mimeType, body)); } private HTTPResponse doPost(String path, String mimeType, byte[] body) throws IOException { HTTPRequest req = new HTTPRequest(new URL(makeUrl(path)), HTTPMethod.POST); req.getFetchOptions().doNotFollowRedirects(); for (String[] headerPair : getHeadersForPost(mimeType)) { req.addHeader(new HTTPHeader(headerPair[0], headerPair[1])); } addCookies(req); req.setPayload(body); return urlFetch.fetch(req); } @Override public LegacyResponse legacyGet(String path) throws IOException { return createLegacyResponse(doGet(path)); } @Override public LegacyResponse legacyPost(String path, String mimeType, byte[] body) throws IOException { return createLegacyResponse(doPost(path, mimeType, body)); } static Response createResponse(HTTPResponse resp) { return new Response(resp.getResponseCode(), resp.getContent(), getCharset(resp)); } static LegacyResponse createLegacyResponse(HTTPResponse resp) { return new LegacyResponse(resp.getResponseCode(), resp.getContent(), getCharset(resp)); } static Charset getCharset(HTTPResponse resp) { for (HTTPHeader header : resp.getHeaders()) { if (header.getName().toLowerCase().equals("content-type")) { ContentType contentType = ContentType.parse(header.getValue()); return contentType.getCharset(); } } return null; } }
{ "content_hash": "988ad3d5c289793e5585bfe9443cfbb2", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 97, "avg_line_length": 33.11764705882353, "alnum_prop": 0.7350503256364713, "repo_name": "GoogleCloudPlatform/appengine-java-standard", "id": "0dd0c58ca3438ac3e4eace5a76d471494004a555", "size": "3972", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "remoteapi/src/main/java/com/google/appengine/tools/remoteapi/HostedAppEngineClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2237" }, { "name": "CSS", "bytes": "15037" }, { "name": "FreeMarker", "bytes": "2577" }, { "name": "GAP", "bytes": "21948" }, { "name": "HTML", "bytes": "1173" }, { "name": "Java", "bytes": "9377837" }, { "name": "JavaScript", "bytes": "9465" }, { "name": "Shell", "bytes": "13619" }, { "name": "Starlark", "bytes": "2612" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_25) on Tue Jan 13 02:32:25 EST 2015 --> <title>TokenExtractorImpl</title> <meta name="date" content="2015-01-13"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="TokenExtractorImpl"; } } catch(err) { } //--> var methods = {"i0":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../jsimple/oauth/extractors/TokenExtractor20Impl.html" title="class in jsimple.oauth.extractors"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../index.html?jsimple/oauth/extractors/TokenExtractorImpl.html" target="_top">Frames</a></li> <li><a href="TokenExtractorImpl.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;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">jsimple.oauth.extractors</div> <h2 title="Class TokenExtractorImpl" class="title">Class TokenExtractorImpl</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>jsimple.oauth.extractors.TokenExtractorImpl</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../jsimple/oauth/extractors/AccessTokenExtractor.html" title="interface in jsimple.oauth.extractors">AccessTokenExtractor</a>, <a href="../../../jsimple/oauth/extractors/RequestTokenExtractor.html" title="interface in jsimple.oauth.extractors">RequestTokenExtractor</a></dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">TokenExtractorImpl</span> extends java.lang.Object implements <a href="../../../jsimple/oauth/extractors/RequestTokenExtractor.html" title="interface in jsimple.oauth.extractors">RequestTokenExtractor</a>, <a href="../../../jsimple/oauth/extractors/AccessTokenExtractor.html" title="interface in jsimple.oauth.extractors">AccessTokenExtractor</a></pre> <div class="block">Default implementation of and . Conforms to OAuth 1.0a <p/> The process for extracting access and request tokens is similar so this class can do both things.</div> </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="memberSummary" 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><span class="memberNameLink"><a href="../../../jsimple/oauth/extractors/TokenExtractorImpl.html#TokenExtractorImpl--">TokenExtractorImpl</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../jsimple/oauth/model/Token.html" title="class in jsimple.oauth.model">Token</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../jsimple/oauth/extractors/TokenExtractorImpl.html#extract-java.lang.String-">extract</a></span>(java.lang.String&nbsp;response)</code> <div class="block">Extracts the request token from the contents of an Http Response</div> </td> </tr> </table> <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>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, 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="TokenExtractorImpl--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>TokenExtractorImpl</h4> <pre>public&nbsp;TokenExtractorImpl()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="extract-java.lang.String-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>extract</h4> <pre>public&nbsp;<a href="../../../jsimple/oauth/model/Token.html" title="class in jsimple.oauth.model">Token</a>&nbsp;extract(java.lang.String&nbsp;response)</pre> <div class="block">Extracts the request token from the contents of an Http Response</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../jsimple/oauth/extractors/AccessTokenExtractor.html#extract-java.lang.String-">extract</a></code>&nbsp;in interface&nbsp;<code><a href="../../../jsimple/oauth/extractors/AccessTokenExtractor.html" title="interface in jsimple.oauth.extractors">AccessTokenExtractor</a></code></dd> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../jsimple/oauth/extractors/RequestTokenExtractor.html#extract-java.lang.String-">extract</a></code>&nbsp;in interface&nbsp;<code><a href="../../../jsimple/oauth/extractors/RequestTokenExtractor.html" title="interface in jsimple.oauth.extractors">RequestTokenExtractor</a></code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>response</code> - the contents of the response</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>OAuth access token</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> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../jsimple/oauth/extractors/TokenExtractor20Impl.html" title="class in jsimple.oauth.extractors"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../index.html?jsimple/oauth/extractors/TokenExtractorImpl.html" target="_top">Frames</a></li> <li><a href="TokenExtractorImpl.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;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": "e7b51f3e91367fc086d2f381abb60834", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 391, "avg_line_length": 37.83103448275862, "alnum_prop": 0.6591012669765746, "repo_name": "juniversal/juniversal.github.io", "id": "cd433c42e0ae800617d30856023a71f9f618d029", "size": "10971", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jsimpledoc/jsimple/oauth/extractors/TokenExtractorImpl.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "73353" }, { "name": "HTML", "bytes": "3905174" }, { "name": "JavaScript", "bytes": "10497" }, { "name": "Ruby", "bytes": "49" } ], "symlink_target": "" }
ProbablyEngine.condition.register('twohand', function(target) return IsEquippedItemType("Two-Hand") end) ProbablyEngine.condition.register('onehand', function(target) return IsEquippedItemType("One-Hand") end) -- SPEC ID 251 ProbablyEngine.rotation.register(251, { -- Blood Tap {{ { "Blood Tap", "player.runes(unholy).count = 0" }, { "Blood Tap", "player.runes(frost).count = 0" }, { "Blood Tap", "player.runes(death).count = 0" }, } , { "player.buff(Blood Charge).count >= 5", "player.runes(death).count = 0" }}, -- Survival { "Icebound Fortitude", "player.health <= 45" }, { "Anti-Magic Shell", "player.health <= 45" }, -- Interrupts { "Mind Freeze", "modifier.interrupts" }, { "Strangualte", { "modifier.interrupts", "!modifier.last(Mind Freeze)" } }, { "Defile", "modifier.shift", "ground" }, { "Chains of Ice", "modifier.control" }, -- Cooldowns { "Pillar of Frost", "modifier.cooldowns" }, { "Raise Dead", { "modifier.cooldowns", "player.buff(Pillar of Frost)" }}, { "Empower Rune Weapon", { "modifier.cooldowns", "player.runicpower <= 70", "player.runes(unholy).count = 0", "player.runes(frost).count = 0", "player.runes(death).count = 0", }}, -- Disease Control { "Unholy Blight", "player.enemies(10) > 3" }, {{ {{ { "Plague Leech", "player.runes(unholy).count = 0" }, { "Plague Leech", "player.runes(frost).count = 0" }, { "Plague Leech", "player.runes(death).count = 0" }, }, "player.spell(Outbreak).cooldown = 0" }, {{ { "Plague Leech", "player.runes(unholy).count = 0" }, { "Plague Leech", "player.runes(frost).count = 0" }, { "Plague Leech", "player.runes(death).count = 0" }, }, "target.debuff(Blood Plague).duration < 6" }, } , { "target.debuff(Blood Plague)", "target.debuff(Frost Fever)" }}, { "Outbreak", { "target.debuff(Frost Fever).duration < 3", "target.debuff(Blood Plague).duration < 3", }, "target" }, { "Howling Blast", "target.debuff(Frost Fever).duration < 3" }, { "Plague Strike", { "target.debuff(Blood Plague).duration < 3", "player.runes(unholy).count >= 1" } }, --{ "Unholy Blight", (function() return UnitsAroundUnit('target', 10) >= 4 end) }, { "Death and Decay", "modifier.shift", "target.ground" }, -- DW Rotation {{ -- AoE {{ { "Pestilence", "modifier.last(Outbreak)" }, { "Pestilence", "modifier.last(Plague Strike)" }, { "Howling Blast" }, { "Frost Strike", "player.runicpower >= 75" }, { "Death and Decay", "target.ground" }, { "Plague Strike", { "player.runes(unholy).count = 2", "player.spell(Death and Decay).cooldown", }}, { "Frost Strike" }, }, "modifier.multitarget" }, -- Single Target {{ { "Frost Strike", "player.buff(Killing Machine)" }, { "Frost Strike", "player.runicpower > 88" }, { "Howling Blast", "player.runes(death).count > 1" }, { "Howling Blast", "player.runes(frost).count > 1" }, --{ "Unholy Blight", "target.debuff(Frost Fever).duration < 3" }, --{ "Unholy Blight", "target.debuff(Blood Plague).duration < 3" }, { "Soul Reaper", "target.health < 35" }, { "Howling Blast", "player.buff(Freezing Fog)" }, { "Frost Strike", "player.runicpower > 76" }, { "Death Strike", "player.buff(Dark Succor)" }, { "Death Strike", "player.health <= 65" }, { "Obliterate", { "player.runes(unholy).count > 0", "!player.buff(Killing Machine)" }}, { "Howling Blast" }, -- actions.single_target+=/frost_strike,if=talent.runic_empowerment.enabled&unholy=1 -- actions.single_target+=/blood_tap,if=talent.blood_tap.enabled&(target.health.pct-3*(target.health.pct%target.time_to_die)>35|buff.blood_charge.stack>=8) { "Frost Strike", "player.runicpower >= 40" }, }, "!modifier.multitarget" }, }, "player.onehand" }, -- 2H Rotation {{ -- AoE {{ { "Blood Tap", { "player.buff(Blood Charge).count >= 5", "!player.runes(blood).count == 2", "!player.runes(frost).count == 2", "!player.runes(unholy).count == 2", }}, { "Pestilence", { "target.debuff(Blood Plague) >= 28", "!modifier.last" }}, { "Howling Blast" }, { "Frost Strike", "player.runicpower >= 75" }, { "Defile", "modifier.shift", "ground" }, { "Plague Strike", { "player.runes(unholy).count = 2", "player.spell(Death and Decay).cooldown", }}, { "Frost Strike" }, }, "modifier.multitarget" }, -- Single Target {{ { "Soul Reaper", "target.health < 35" }, { "Howling Blast", "player.buff(Freezing Fog)" }, {{ { "Death Strike", "player.buff(Killing Machine)" }, { "Seath Strike", "player.runicpower <= 75" }, }, "player.health <= 65"}, {{ { "Obliterate", "player.buff(Killing Machine)" }, { "Obliterate", "player.runicpower <= 75" }, }, "player.health > 65"}, { "Blood Tap", "player.buff(Blood Charge).count >= 5" }, { "Frost Strike", "!player.buff(Killing Machine)" }, { "Frost Strike", "player.spell(Obliterate).cooldown >= 4" }, }, "!modifier.multitarget" }, }, "player.twohand" }, },{ { "Horn of Winter", "!player.buff(Horn of Winter)" }, })
{ "content_hash": "9485393153a6ca4cfb2d1c6a1474c20b", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 161, "avg_line_length": 33.079754601226995, "alnum_prop": 0.5667655786350149, "repo_name": "adde88/Probably", "id": "69102885599a2f4522a72b82d847c203f563b644", "size": "5392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rotations/deathknight/frost.lua", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Lua", "bytes": "330609" }, { "name": "TeX", "bytes": "176" } ], "symlink_target": "" }
from efl import ecore from efl.elementary.box import Box from efl.elementary.frame import Frame from efl.elementary.button import Button from efl.elementary.entry import Entry, markup_to_utf8 from efl.evas import EVAS_HINT_EXPAND, EVAS_HINT_FILL EXPAND_BOTH = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND EXPAND_HORIZ = EVAS_HINT_EXPAND, 0.0 FILL_BOTH = EVAS_HINT_FILL, EVAS_HINT_FILL FILL_HORIZ = EVAS_HINT_FILL, 0.5 class EmbeddedTerminal(Box): def __init__(self, parent_widget, titles=None, *args, **kwargs): Box.__init__(self, parent_widget, *args, **kwargs) self.outPut = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.outPut.editable_set(False) self.outPut.scrollable_set(True) self.outPut.callback_changed_add(self.changedCb) self.outPut.show() frame = Frame(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) frame.text = "Input:" frame.autocollapse_set(True) frame.collapse_go(True) frame.show() bx = Box(self, size_hint_weight=EXPAND_HORIZ, size_hint_align=FILL_HORIZ) bx.horizontal = True bx.show() frame.content = bx self.inPut = Entry(self, size_hint_weight=EXPAND_BOTH, size_hint_align=FILL_BOTH) self.inPut.single_line_set(True) self.inPut.callback_activated_add(self.enterPressed) self.inPut.show() enterButton = Button(self) enterButton.text = "Execute" enterButton.callback_pressed_add(self.enterPressed) enterButton.show() bx.pack_end(self.inPut) bx.pack_end(enterButton) self.pack_end(self.outPut) self.pack_end(frame) self.cmd_exe = None self.done_cb = None def changedCb(self, obj): obj.cursor_end_set() def enterPressed(self, btn): if not self.cmd_exe: self.runCommand(self.inPut.text) self.inPut.text = "" else: ourResult = self.cmd_exe.send("%s\n"%self.inPut.text) self.inPut.text = "" def runCommand(self, command, done_cb=None): command = markup_to_utf8(command) self.cmd_exe = cmd = ecore.Exe( command, ecore.ECORE_EXE_PIPE_READ | ecore.ECORE_EXE_PIPE_ERROR | ecore.ECORE_EXE_PIPE_WRITE ) cmd.on_add_event_add(self.command_started) cmd.on_data_event_add(self.received_data) cmd.on_error_event_add(self.received_error) cmd.on_del_event_add(self.command_done) self.done_cb = done_cb def command_started(self, cmd, event, *args, **kwargs): self.outPut.entry_append("---------------------------------") self.outPut.entry_append("<br>") def received_data(self, cmd, event, *args, **kwargs): self.outPut.entry_append("%s"%event.data) self.outPut.entry_append("<br>") def received_error(self, cmd, event, *args, **kwargs): self.outPut.entry_append("Error: %s" % event.data) def command_done(self, cmd, event, *args, **kwargs): self.outPut.entry_append("---------------------------------") self.outPut.entry_append("<br>") self.cmd_exe = None if self.done_cb: if callable(self.done_cb): self.done_cb()
{ "content_hash": "ad5e3aa74707b2499a41a3c6f8d81c1d", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 90, "avg_line_length": 35.29896907216495, "alnum_prop": 0.5896612149532711, "repo_name": "JeffHoogland/python-elm-extensions", "id": "1c41eddbcb665b20c36629b49fac1572c0ff3214", "size": "3424", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "elmextensions/embeddedterminal.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "77794" } ], "symlink_target": "" }
class NTPSnippetsLauncher : public ntp_snippets::NTPSnippetsScheduler { public: static NTPSnippetsLauncher* Get(); // ntp_snippets::NTPSnippetsScheduler implementation. bool Schedule(base::TimeDelta period_wifi, base::TimeDelta period_fallback) override; bool Unschedule() override; private: friend struct base::DefaultLazyInstanceTraits<NTPSnippetsLauncher>; // Constructor and destructor marked private to enforce singleton. NTPSnippetsLauncher(); virtual ~NTPSnippetsLauncher(); base::android::ScopedJavaGlobalRef<jobject> java_launcher_; DISALLOW_COPY_AND_ASSIGN(NTPSnippetsLauncher); }; #endif // CHROME_BROWSER_ANDROID_NTP_NTP_SNIPPETS_LAUNCHER_H_
{ "content_hash": "6581ea8633671de6d37409c5eed1a8d4", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 71, "avg_line_length": 31.772727272727273, "alnum_prop": 0.7668097281831188, "repo_name": "ssaroha/node-webrtc", "id": "2dfbb4bafeca2bd7a48ebde53d3e63c432cc55fc", "size": "1394", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "third_party/webrtc/include/chromium/src/chrome/browser/android/ntp/ntp_snippets_launcher.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "6179" }, { "name": "C", "bytes": "2679" }, { "name": "C++", "bytes": "54327" }, { "name": "HTML", "bytes": "434" }, { "name": "JavaScript", "bytes": "42707" }, { "name": "Python", "bytes": "3835" } ], "symlink_target": "" }
<?php class Upgrade_3_0_14 extends MIDASUpgrade { public function preUpgrade() { // Insert common metadata $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','contributor','author','Author of the data')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','date','uploaded','Date when the data was uploaded')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','date','issued','Date when the data was released')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','date','created','Date when the data was created')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','identifier','citation','Citation of the data')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','identifier','uri','URI identifier')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','identifier','pubmed','PubMed identifier')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','identifier','doi','Digital Object Identifier')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','description','general','General description field')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','description','provenance','Provenance of the data')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','description','sponsorship','Sponsor of the data')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','description','publisher','Publisher of the data')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','subject','keyword','Keyword')"); $this->db->query("INSERT INTO metadata (metadatatype,element,qualifier,description) VALUES ('0','subject','ocis','OCIS subject')"); } public function mysql() { } public function pgsql() { } public function postUpgrade() { } } ?>
{ "content_hash": "0022c52212a249f56dce1bf340d40823", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 155, "avg_line_length": 60.794871794871796, "alnum_prop": 0.7026571067060312, "repo_name": "mgrauer/midas3score", "id": "752ff9c50668c3a5c3ab96fc58a40dac8e3e848b", "size": "2371", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/database/upgrade/3.0.14.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "198666" }, { "name": "C", "bytes": "1028" }, { "name": "C++", "bytes": "31222" }, { "name": "Java", "bytes": "34890" }, { "name": "JavaScript", "bytes": "664866" }, { "name": "PHP", "bytes": "29033551" }, { "name": "Python", "bytes": "16812" }, { "name": "Shell", "bytes": "3319" } ], "symlink_target": "" }
var DOCUMENTER_CURRENT_VERSION = "v3.7.1";
{ "content_hash": "bcc436e705d12c77c420ab8cd4150b62", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 42, "avg_line_length": 43, "alnum_prop": 0.7209302325581395, "repo_name": "dmbates/MixedModels.jl", "id": "3e937940fded03dab6256665d9fb743a628faabd", "size": "43", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v3.7.1/siteinfo.js", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "138755" } ], "symlink_target": "" }
package be.thalarion.android.powerampd.protocol; import be.thalarion.android.powerampd.R; public class ProtocolOK implements Protocol { private final String message; public ProtocolOK(String message) { this.message = message; } public ProtocolOK() { this(null); } @Override public String toString() { if (this.message == null) { return String.format("%s\n", getClass().getResource("proto_ok")); } else return String.format("%s %s\n", getClass().getResource("proto_ok"), this.message); } }
{ "content_hash": "26375ef9d26f1b85635bf1fa22ecdf00", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 97, "avg_line_length": 24.82608695652174, "alnum_prop": 0.637478108581436, "repo_name": "floriandejonckheere/powerampd", "id": "4f54b94b29cf4d6841575d13c69de1e734cc8654", "size": "571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/be/thalarion/android/powerampd/protocol/ProtocolOK.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "85301" } ], "symlink_target": "" }
package bazaar4idea.provider.update; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.update.UpdatedFiles; interface BzrUpdater { void update(UpdatedFiles updatedFiles, ProgressIndicator indicator) throws VcsException; }
{ "content_hash": "1245e40fc3a127d2fbdd018830a0d019", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 90, "avg_line_length": 28.363636363636363, "alnum_prop": 0.8397435897435898, "repo_name": "bwrsandman/bzr4j", "id": "8f1e38b19a5d7baf0d53f17eca62b64ed8342ffb", "size": "896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/intellij/src/main/java/bazaar4idea/provider/update/BzrUpdater.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1044148" }, { "name": "Shell", "bytes": "31" } ], "symlink_target": "" }
from __future__ import unicode_literals from djangobmf.apps import ContribTemplate class AccountingConfig(ContribTemplate): name = 'djangobmf.contrib.accounting' label = "djangobmf_accounting"
{ "content_hash": "720c547172d12fd558582fb798d7709f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 42, "avg_line_length": 25.5, "alnum_prop": 0.7794117647058824, "repo_name": "django-bmf/django-bmf", "id": "04d0bd830b2747468b9fa484ca795b98a97b9893", "size": "204", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "djangobmf/contrib/accounting/apps.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "11420" }, { "name": "CoffeeScript", "bytes": "3197" }, { "name": "HTML", "bytes": "117091" }, { "name": "JavaScript", "bytes": "80435" }, { "name": "Python", "bytes": "774167" }, { "name": "Shell", "bytes": "736" } ], "symlink_target": "" }
DROP TABLE __migrations__;
{ "content_hash": "60ecca7232b162942cc56923f71e056e", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 26, "avg_line_length": 27, "alnum_prop": 0.7037037037037037, "repo_name": "raster-foundry/raster-foundry", "id": "6ac55a98eb4792cf180bac5bfd543c8e09a7e949", "size": "85", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "app-backend/db/src/main/resources/migrations/V2__Remove_slick_leftovers.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2188" }, { "name": "Groovy", "bytes": "7139" }, { "name": "HTML", "bytes": "2537" }, { "name": "Jinja", "bytes": "1343" }, { "name": "PLpgSQL", "bytes": "28868" }, { "name": "Python", "bytes": "100298" }, { "name": "Scala", "bytes": "2189261" }, { "name": "Shell", "bytes": "48349" } ], "symlink_target": "" }
<?php require_once("model/auth.php"); require_once("model/Cepage.php"); if(!isset($_POST)) { header('Location: ./cepages.php'); exit(0); } if(empty($_POST['nom'])) { // The user shouldn't be able to send a form without this field (required or locked attribute). But they can make a custom GET request and send it, bypassing the HTML verification. Never trust user input. header('Location: ./cepages.php'); exit(0); } if(!isset($_GET['add'])) { $errorInfo = Cepage_update_entry($_POST['nom'], $_POST['description']); } else { $errorInfo = Cepage_add_entry($_POST['nom'], $_POST['description']); } if(!empty($errorInfo[2])) { $driver = $db->getAttribute(PDO::ATTR_DRIVER_NAME); $cepage_key = htmlspecialchars($_POST['nom']); $page_title = 'Le cépage ' . $cepage_key . ' n\'a pas été ' . (isset($_GET['add'])?'ajouté':'édité'); require_once("view/edition-erreur.php"); } else { header('Location: cepages.php'); }
{ "content_hash": "ae3c6b6c479dadaae351656a4090405b", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 205, "avg_line_length": 25.72222222222222, "alnum_prop": 0.6533477321814255, "repo_name": "dolfinsbizou/NA17", "id": "f2fb68bf67d51678651975a47264ba1b20a1ee6e", "size": "932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cepage-editer-valider.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5420" }, { "name": "JavaScript", "bytes": "3060" }, { "name": "PHP", "bytes": "76531" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">scrollview</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> </resources>
{ "content_hash": "64fb3ddd8d94b03e6ca96987dbf036a0", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 27.5, "alnum_prop": 0.6772727272727272, "repo_name": "rahulpareek2440/AndroidPrograms", "id": "a7b356466374d10b90e699cce6ea0b0dfdc3a802", "size": "220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scrollview/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1726" }, { "name": "Groff", "bytes": "496" }, { "name": "HTML", "bytes": "104173" }, { "name": "Java", "bytes": "366083" } ], "symlink_target": "" }
import tensorflow as tf def image_grid(input_tensor, grid_shape, image_shape): """ form_image_grid forms a grid of image tiles from input_tensor. :param input_tensor - batch of images, shape (N, height, width, n_channels) :param grid_shape - shape (in tiles) of the grid, e.g. (10, 10) :param image_shape - shape of a single image, e.g. (28, 28, 1) """ # take the subset of images input_tensor = input_tensor[:grid_shape[0] * grid_shape[1]] # add black tiles if needed required_pad = grid_shape[0] * grid_shape[1] - tf.shape(input_tensor)[0] def add_pad(): padding = tf.zeros((required_pad,) + image_shape) return tf.concat([input_tensor, padding], axis=0) input_tensor = tf.cond(required_pad > 0, add_pad, lambda: input_tensor) # height and width of the grid height, width = grid_shape[0] * image_shape[0], grid_shape[1] * image_shape[1] # form the grid tensor input_tensor = tf.reshape(input_tensor, grid_shape + image_shape) # flip height and width input_tensor = tf.transpose(input_tensor, [0, 1, 3, 2, 4]) # form the rows input_tensor = tf.reshape(input_tensor, [grid_shape[0], width, image_shape[0], image_shape[2]]) # flip width and height again input_tensor = tf.transpose(input_tensor, [0, 2, 1, 3]) # form the columns input_tensor = tf.reshape(input_tensor, [1, height, width, image_shape[2]]) return input_tensor
{ "content_hash": "e1ef4c04f2b68007656e3717d346d14a", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 99, "avg_line_length": 42.5, "alnum_prop": 0.6498269896193771, "repo_name": "taimir/keras-layers", "id": "2bc1f8323fa7872c03e773b61350184f704a8a9b", "size": "1445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "klayers/utils/visualization.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "44038" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; namespace System.Data { internal sealed class FunctionNode : ExpressionNode { internal readonly string _name; internal readonly int _info = -1; internal int _argumentCount = 0; internal const int initialCapacity = 1; internal ExpressionNode[] _arguments; private static readonly Function[] s_funcs = new Function[] { new Function("Abs", FunctionId.Abs, typeof(object), true, false, 1, typeof(object), null, null), new Function("IIf", FunctionId.Iif, typeof(object), false, false, 3, typeof(object), typeof(object), typeof(object)), new Function("In", FunctionId.In, typeof(bool), false, true, 1, null, null, null), new Function("IsNull", FunctionId.IsNull, typeof(object), false, false, 2, typeof(object), typeof(object), null), new Function("Len", FunctionId.Len, typeof(int), true, false, 1, typeof(string), null, null), new Function("Substring", FunctionId.Substring, typeof(string), true, false, 3, typeof(string), typeof(int), typeof(int)), new Function("Trim", FunctionId.Trim, typeof(string), true, false, 1, typeof(string), null, null), // convert new Function("Convert", FunctionId.Convert, typeof(object), false, true, 1, typeof(object), null, null), new Function("DateTimeOffset", FunctionId.DateTimeOffset, typeof(DateTimeOffset), false, true, 3, typeof(DateTime), typeof(int), typeof(int)), // store aggregates here new Function("Max", FunctionId.Max, typeof(object), false, false, 1, null, null, null), new Function("Min", FunctionId.Min, typeof(object), false, false, 1, null, null, null), new Function("Sum", FunctionId.Sum, typeof(object), false, false, 1, null, null, null), new Function("Count", FunctionId.Count, typeof(object), false, false, 1, null, null, null), new Function("Var", FunctionId.Var, typeof(object), false, false, 1, null, null, null), new Function("StDev", FunctionId.StDev, typeof(object), false, false, 1, null, null, null), new Function("Avg", FunctionId.Avg, typeof(object), false, false, 1, null, null, null), }; internal FunctionNode(DataTable table, string name) : base(table) { _name = name; for (int i = 0; i < s_funcs.Length; i++) { if (string.Equals(s_funcs[i]._name, name, StringComparison.OrdinalIgnoreCase)) { // we found the reserved word.. _info = i; break; } } if (_info < 0) { throw ExprException.UndefinedFunction(_name); } } internal void AddArgument(ExpressionNode argument) { if (!s_funcs[_info]._isVariantArgumentList && _argumentCount >= s_funcs[_info]._argumentCount) throw ExprException.FunctionArgumentCount(_name); if (_arguments == null) { _arguments = new ExpressionNode[initialCapacity]; } else if (_argumentCount == _arguments.Length) { ExpressionNode[] bigger = new ExpressionNode[_argumentCount * 2]; Array.Copy(_arguments, 0, bigger, 0, _argumentCount); _arguments = bigger; } _arguments[_argumentCount++] = argument; } internal override void Bind(DataTable table, List<DataColumn> list) { BindTable(table); Check(); // special case for the Convert function bind only the first argument: // the second argument should be a Type stored as a name node, replace it with constant. if (s_funcs[_info]._id == FunctionId.Convert) { if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); _arguments[0].Bind(table, list); if (_arguments[1].GetType() == typeof(NameNode)) { NameNode type = (NameNode)_arguments[1]; _arguments[1] = new ConstNode(table, ValueType.Str, type._name); } _arguments[1].Bind(table, list); } else { for (int i = 0; i < _argumentCount; i++) { _arguments[i].Bind(table, list); } } } internal override object Eval() { return Eval(null, DataRowVersion.Default); } internal override object Eval(DataRow row, DataRowVersion version) { Debug.Assert(_info < s_funcs.Length && _info >= 0, "Invalid function info."); object[] argumentValues = new object[_argumentCount]; Debug.Assert(_argumentCount == s_funcs[_info]._argumentCount || s_funcs[_info]._isVariantArgumentList, "Invalid argument argumentCount."); // special case of the Convert function if (s_funcs[_info]._id == FunctionId.Convert) { if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); argumentValues[0] = _arguments[0].Eval(row, version); argumentValues[1] = GetDataType(_arguments[1]); } else if (s_funcs[_info]._id != FunctionId.Iif) { // We do not want to evaluate arguments of IIF, we will already do it in EvalFunction/ second point: we may go to div by 0 for (int i = 0; i < _argumentCount; i++) { argumentValues[i] = _arguments[i].Eval(row, version); if (s_funcs[_info]._isValidateArguments) { if ((argumentValues[i] == DBNull.Value) || (typeof(object) == s_funcs[_info]._parameters[i])) { // currently all supported functions with IsValidateArguments set to true // NOTE: for IIF and ISNULL IsValidateArguments set to false return DBNull.Value; } if (argumentValues[i].GetType() != s_funcs[_info]._parameters[i]) { // We are allowing conversions in one very specific case: int, int64,...'nice' numeric to numeric.. if (s_funcs[_info]._parameters[i] == typeof(int) && ExpressionNode.IsInteger(DataStorage.GetStorageType(argumentValues[i].GetType()))) { argumentValues[i] = Convert.ToInt32(argumentValues[i], FormatProvider); } else if ((s_funcs[_info]._id == FunctionId.Trim) || (s_funcs[_info]._id == FunctionId.Substring) || (s_funcs[_info]._id == FunctionId.Len)) { if ((typeof(string) != (argumentValues[i].GetType())) && (typeof(SqlString) != (argumentValues[i].GetType()))) { throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]); } } else { throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]); } } } } } return EvalFunction(s_funcs[_info]._id, argumentValues, row, version); } internal override object Eval(int[] recordNos) { throw ExprException.ComputeNotAggregate(ToString()); } internal override bool IsConstant() { // Currently all function calls with const arguments return constant. // That could change in the future (if we implement Rand()...) // CONSIDER: We could be smarter for Iif. bool constant = true; for (int i = 0; i < _argumentCount; i++) { constant = constant && _arguments[i].IsConstant(); } Debug.Assert(_info > -1, "All function nodes should be bound at this point."); // default info is -1, it means if not bounded, it should be -1, not 0!! return (constant); } internal override bool IsTableConstant() { for (int i = 0; i < _argumentCount; i++) { if (!_arguments[i].IsTableConstant()) { return false; } } return true; } internal override bool HasLocalAggregate() { for (int i = 0; i < _argumentCount; i++) { if (_arguments[i].HasLocalAggregate()) { return true; } } return false; } internal override bool HasRemoteAggregate() { for (int i = 0; i < _argumentCount; i++) { if (_arguments[i].HasRemoteAggregate()) { return true; } } return false; } internal override bool DependsOn(DataColumn column) { for (int i = 0; i < _argumentCount; i++) { if (_arguments[i].DependsOn(column)) return true; } return false; } internal override ExpressionNode Optimize() { for (int i = 0; i < _argumentCount; i++) { _arguments[i] = _arguments[i].Optimize(); } Debug.Assert(_info > -1, "Optimizing unbound function "); // default info is -1, it means if not bounded, it should be -1, not 0!! if (s_funcs[_info]._id == FunctionId.In) { // we can not optimize the in node, just check that it has all constant arguments if (!IsConstant()) { throw ExprException.NonConstantArgument(); } } else { if (IsConstant()) { return new ConstNode(table, ValueType.Object, Eval(), false); } } return this; } private Type GetDataType(ExpressionNode node) { Type nodeType = node.GetType(); string typeName = null; if (nodeType == typeof(NameNode)) { typeName = ((NameNode)node)._name; } if (nodeType == typeof(ConstNode)) { typeName = ((ConstNode)node)._val.ToString(); } if (typeName == null) { throw ExprException.ArgumentType(s_funcs[_info]._name, 2, typeof(Type)); } Type dataType = Type.GetType(typeName); if (dataType == null) { throw ExprException.InvalidType(typeName); } return dataType; } private object EvalFunction(FunctionId id, object[] argumentValues, DataRow row, DataRowVersion version) { StorageType storageType; switch (id) { case FunctionId.Abs: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); if (ExpressionNode.IsInteger(storageType)) return (Math.Abs((long)argumentValues[0])); if (ExpressionNode.IsNumeric(storageType)) return (Math.Abs((double)argumentValues[0])); throw ExprException.ArgumentTypeInteger(s_funcs[_info]._name, 1); case FunctionId.cBool: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); return storageType switch { StorageType.Boolean => (bool)argumentValues[0], StorageType.Int32 => ((int)argumentValues[0] != 0), StorageType.Double => ((double)argumentValues[0] != 0.0), StorageType.String => bool.Parse((string)argumentValues[0]), _ => throw ExprException.DatatypeConvertion(argumentValues[0].GetType(), typeof(bool)), }; case FunctionId.cInt: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToInt32(argumentValues[0], FormatProvider); case FunctionId.cDate: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToDateTime(argumentValues[0], FormatProvider); case FunctionId.cDbl: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToDouble(argumentValues[0], FormatProvider); case FunctionId.cStr: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToString(argumentValues[0], FormatProvider); case FunctionId.Charindex: Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); Debug.Assert(argumentValues[0] is string, "Invalid argument type for " + s_funcs[_info]._name); Debug.Assert(argumentValues[1] is string, "Invalid argument type for " + s_funcs[_info]._name); if (DataStorage.IsObjectNull(argumentValues[0]) || DataStorage.IsObjectNull(argumentValues[1])) return DBNull.Value; if (argumentValues[0] is SqlString) argumentValues[0] = ((SqlString)argumentValues[0]).Value; if (argumentValues[1] is SqlString) argumentValues[1] = ((SqlString)argumentValues[1]).Value; return ((string)argumentValues[1]).IndexOf((string)argumentValues[0], StringComparison.Ordinal); case FunctionId.Iif: Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider)); object first = _arguments[0].Eval(row, version); if (DataExpression.ToBoolean(first) != false) { return _arguments[1].Eval(row, version); } else { return _arguments[2].Eval(row, version); } case FunctionId.In: // we never evaluate IN directly: IN as a binary operator, so evaluation of this should be in // BinaryNode class throw ExprException.NYI(s_funcs[_info]._name); case FunctionId.IsNull: Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount: "); if (DataStorage.IsObjectNull(argumentValues[0])) return argumentValues[1]; else return argumentValues[0]; case FunctionId.Len: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name); if (argumentValues[0] is SqlString) { if (((SqlString)argumentValues[0]).IsNull) { return DBNull.Value; } else { argumentValues[0] = ((SqlString)argumentValues[0]).Value; } } return ((string)argumentValues[0]).Length; case FunctionId.Substring: Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider)); Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid first argument " + argumentValues[0].GetType().FullName + " in " + s_funcs[_info]._name); Debug.Assert(argumentValues[1] is int, "Invalid second argument " + argumentValues[1].GetType().FullName + " in " + s_funcs[_info]._name); Debug.Assert(argumentValues[2] is int, "Invalid third argument " + argumentValues[2].GetType().FullName + " in " + s_funcs[_info]._name); // work around the differences in .NET and VBA implementation of the Substring function // 1. The <index> Argument is 0-based in .NET, and 1-based in VBA // 2. If the <Length> argument is longer then the string length .NET throws an ArgumentException // but our users still want to get a result. int start = (int)argumentValues[1] - 1; int length = (int)argumentValues[2]; if (start < 0) throw ExprException.FunctionArgumentOutOfRange("index", "Substring"); if (length < 0) throw ExprException.FunctionArgumentOutOfRange("length", "Substring"); if (length == 0) return string.Empty; if (argumentValues[0] is SqlString) argumentValues[0] = ((SqlString)argumentValues[0]).Value; int src_length = ((string)argumentValues[0]).Length; if (start > src_length) { return DBNull.Value; } if (start + length > src_length) { length = src_length - start; } return ((string)argumentValues[0]).Substring(start, length); case FunctionId.Trim: { Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name); if (DataStorage.IsObjectNull(argumentValues[0])) return DBNull.Value; if (argumentValues[0] is SqlString) argumentValues[0] = ((SqlString)argumentValues[0]).Value; return (((string)argumentValues[0]).Trim()); } case FunctionId.Convert: if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); if (argumentValues[0] == DBNull.Value) { return DBNull.Value; } Type type = (Type)argumentValues[1]; StorageType mytype = DataStorage.GetStorageType(type); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); if (mytype == StorageType.DateTimeOffset) { if (storageType == StorageType.String) { return SqlConvert.ConvertStringToDateTimeOffset((string)argumentValues[0], FormatProvider); } } if (StorageType.Object != mytype) { if ((mytype == StorageType.Guid) && (storageType == StorageType.String)) return new Guid((string)argumentValues[0]); if (ExpressionNode.IsFloatSql(storageType) && ExpressionNode.IsIntegerSql(mytype)) { if (StorageType.Single == storageType) { return SqlConvert.ChangeType2((float)SqlConvert.ChangeType2(argumentValues[0], StorageType.Single, typeof(float), FormatProvider), mytype, type, FormatProvider); } else if (StorageType.Double == storageType) { return SqlConvert.ChangeType2((double)SqlConvert.ChangeType2(argumentValues[0], StorageType.Double, typeof(double), FormatProvider), mytype, type, FormatProvider); } else if (StorageType.Decimal == storageType) { return SqlConvert.ChangeType2((decimal)SqlConvert.ChangeType2(argumentValues[0], StorageType.Decimal, typeof(decimal), FormatProvider), mytype, type, FormatProvider); } return SqlConvert.ChangeType2(argumentValues[0], mytype, type, FormatProvider); } return SqlConvert.ChangeType2(argumentValues[0], mytype, type, FormatProvider); } return argumentValues[0]; case FunctionId.DateTimeOffset: if (argumentValues[0] == DBNull.Value || argumentValues[1] == DBNull.Value || argumentValues[2] == DBNull.Value) return DBNull.Value; switch (((DateTime)argumentValues[0]).Kind) { case DateTimeKind.Utc: if ((int)argumentValues[1] != 0 && (int)argumentValues[2] != 0) { throw ExprException.MismatchKindandTimeSpan(); } break; case DateTimeKind.Local: if (DateTimeOffset.Now.Offset.Hours != (int)argumentValues[1] && DateTimeOffset.Now.Offset.Minutes != (int)argumentValues[2]) { throw ExprException.MismatchKindandTimeSpan(); } break; case DateTimeKind.Unspecified: break; } if ((int)argumentValues[1] < -14 || (int)argumentValues[1] > 14) throw ExprException.InvalidHoursArgument(); if ((int)argumentValues[2] < -59 || (int)argumentValues[2] > 59) throw ExprException.InvalidMinutesArgument(); // range should be within -14 hours and +14 hours if ((int)argumentValues[1] == 14 && (int)argumentValues[2] > 0) throw ExprException.InvalidTimeZoneRange(); if ((int)argumentValues[1] == -14 && (int)argumentValues[2] < 0) throw ExprException.InvalidTimeZoneRange(); return new DateTimeOffset((DateTime)argumentValues[0], new TimeSpan((int)argumentValues[1], (int)argumentValues[2], 0)); default: throw ExprException.UndefinedFunction(s_funcs[_info]._name); } } internal FunctionId Aggregate { get { if (IsAggregate) { return s_funcs[_info]._id; } return FunctionId.none; } } internal bool IsAggregate { get { bool aggregate = (s_funcs[_info]._id == FunctionId.Sum) || (s_funcs[_info]._id == FunctionId.Avg) || (s_funcs[_info]._id == FunctionId.Min) || (s_funcs[_info]._id == FunctionId.Max) || (s_funcs[_info]._id == FunctionId.Count) || (s_funcs[_info]._id == FunctionId.StDev) || (s_funcs[_info]._id == FunctionId.Var); return aggregate; } } internal void Check() { if (_info < 0) throw ExprException.UndefinedFunction(_name); if (s_funcs[_info]._isVariantArgumentList) { // for finctions with variabls argument list argumentCount is a minimal number of arguments if (_argumentCount < s_funcs[_info]._argumentCount) { // Special case for the IN operator if (s_funcs[_info]._id == FunctionId.In) throw ExprException.InWithoutList(); throw ExprException.FunctionArgumentCount(_name); } } else { if (_argumentCount != s_funcs[_info]._argumentCount) throw ExprException.FunctionArgumentCount(_name); } } } internal enum FunctionId { none = -1, Ascii = 0, Char = 1, Charindex = 2, Difference = 3, Len = 4, Lower = 5, LTrim = 6, Patindex = 7, Replicate = 8, Reverse = 9, Right = 10, RTrim = 11, Soundex = 12, Space = 13, Str = 14, Stuff = 15, Substring = 16, Upper = 17, IsNull = 18, Iif = 19, Convert = 20, cInt = 21, cBool = 22, cDate = 23, cDbl = 24, cStr = 25, Abs = 26, Acos = 27, In = 28, Trim = 29, Sum = 30, Avg = 31, Min = 32, Max = 33, Count = 34, StDev = 35, // Statistical standard deviation Var = 37, // Statistical variance DateTimeOffset = 38, } internal sealed class Function { internal readonly string _name; internal readonly FunctionId _id; internal readonly Type _result; internal readonly bool _isValidateArguments; internal readonly bool _isVariantArgumentList; internal readonly int _argumentCount; internal readonly Type[] _parameters = new Type[] { null, null, null }; internal Function() { _name = null; _id = FunctionId.none; _result = null; _isValidateArguments = false; _argumentCount = 0; } internal Function(string name, FunctionId id, Type result, bool IsValidateArguments, bool IsVariantArgumentList, int argumentCount, Type a1, Type a2, Type a3) { _name = name; _id = id; _result = result; _isValidateArguments = IsValidateArguments; _isVariantArgumentList = IsVariantArgumentList; _argumentCount = argumentCount; if (a1 != null) _parameters[0] = a1; if (a2 != null) _parameters[1] = a2; if (a3 != null) _parameters[2] = a3; } internal static string[] s_functionName = new string[] { "Unknown", "Ascii", "Char", "CharIndex", "Difference", "Len", "Lower", "LTrim", "Patindex", "Replicate", "Reverse", "Right", "RTrim", "Soundex", "Space", "Str", "Stuff", "Substring", "Upper", "IsNull", "Iif", "Convert", "cInt", "cBool", "cDate", "cDbl", "cStr", "Abs", "Acos", "In", "Trim", "Sum", "Avg", "Min", "Max", "Count", "StDev", "Var", "DateTimeOffset", }; } }
{ "content_hash": "bb3032c2a32b4853ee66ef5cb9e0129c", "timestamp": "", "source": "github", "line_count": 710, "max_line_length": 198, "avg_line_length": 41.86056338028169, "alnum_prop": 0.4907977524309411, "repo_name": "shimingsg/corefx", "id": "8ba6e7c0eec49a3be0ec93b8f96718be4e1511ad", "size": "29925", "binary": false, "copies": "17", "ref": "refs/heads/master", "path": "src/System.Data.Common/src/System/Data/Filter/FunctionNode.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "327222" }, { "name": "ASP", "bytes": "1687" }, { "name": "Batchfile", "bytes": "24745" }, { "name": "C", "bytes": "1113348" }, { "name": "C#", "bytes": "139667788" }, { "name": "C++", "bytes": "712083" }, { "name": "CMake", "bytes": "63626" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "Groovy", "bytes": "41755" }, { "name": "HTML", "bytes": "653" }, { "name": "Makefile", "bytes": "9085" }, { "name": "Objective-C", "bytes": "9948" }, { "name": "OpenEdge ABL", "bytes": "139178" }, { "name": "Perl", "bytes": "3895" }, { "name": "PowerShell", "bytes": "43073" }, { "name": "Python", "bytes": "1535" }, { "name": "Roff", "bytes": "4236" }, { "name": "Shell", "bytes": "72621" }, { "name": "Visual Basic", "bytes": "827108" }, { "name": "XSLT", "bytes": "462346" } ], "symlink_target": "" }
app.controller('BookingController', function ($scope, $routeParams, $http, $location, $routeParams, $rootScope) { $rootScope.menu = { 'home': false, 'destination': true, 'customize' : false, 'find_tour': false, 'blog' : false, 'contact' : false, 'about' : false } var id = $routeParams.tourId; var start_date = $routeParams.start_date; var number_of_people = $routeParams.number_of_people; // var title = //$('.title_contact option:select').val(); $http({ method: 'GET', url : BASE_URL + 'tour/getTourById/' + id }).then(function successCallback(response){ $scope.tour = response.data; }); $scope.booking = {tour_id: id, start_date: start_date, number_of_people: number_of_people}; $scope.submitBooking = function(){ $scope.submitted = true; if(!$scope.booking_form.$valid) { return; } $scope.loading = true; $http({ method: 'POST', url: BASE_URL + 'booking/create', data: $.param($scope.booking), headers : {'Content-Type': 'application/x-www-form-urlencoded'} }).then(function success(response){ if(response.data.status){ $location.path('/booking_success'); } }).finally(function(){ $scope.loading = false; }); } });
{ "content_hash": "866f8ac9124a248badf4c50ab26d79a2", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 113, "avg_line_length": 25.489795918367346, "alnum_prop": 0.6188951160928743, "repo_name": "toanphuoc/tkvacation", "id": "97a6ca75983729a08dbded735687ac5a9e5b40aa", "size": "1249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/controller/booking_controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "291036" }, { "name": "HTML", "bytes": "329909" }, { "name": "JavaScript", "bytes": "236280" }, { "name": "PHP", "bytes": "2157" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link href="fileBrowser.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script> <!-- you don't need ignore=notused in your code, this is just here to trick the cache --> <script src="../dist/ag-grid.js?ignore=notused16"></script> <link rel="stylesheet" type="text/css" href="../dist/ag-grid.css?ignore=notused16"> <link rel="stylesheet" type="text/css" href="../dist/theme-fresh.css?ignore=notused16"> <script src="fileBrowser.js"></script> </head> <body ng-app="fileBrowser"> <div ng-controller="fileBrowserController" style="border: 1px solid darkgrey; width: 600px; background-color: lightgrey; border-radius: 5px; padding: 3px;"> <div style="border: 1px solid darkgrey; margin-bottom: 2px; background-color: white;"> &nbsp; {{selectedFile}}</div> <div style="width: 100%; height: 400px;" ag-grid="gridOptions" class="ag-file-browser"> </div> </div> </body> </html>
{ "content_hash": "ef595e4fd044eb50d6bab9b39ea8fe31", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 124, "avg_line_length": 41.390243902439025, "alnum_prop": 0.6399528579846788, "repo_name": "benoror/ag-grid", "id": "371652595f22e7292a6d99dada0682db5316552f", "size": "1697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/example-file-browser/fileBrowser.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "41124" }, { "name": "JavaScript", "bytes": "613822" }, { "name": "TypeScript", "bytes": "571458" } ], "symlink_target": "" }
#include "core/paint/FilterEffectBuilder.h" #include "core/layout/LayoutObject.h" #include "core/layout/svg/ReferenceFilterBuilder.h" #include "platform/FloatConversion.h" #include "platform/LengthFunctions.h" #include "platform/graphics/ColorSpace.h" #include "platform/graphics/filters/FEBoxReflect.h" #include "platform/graphics/filters/FEColorMatrix.h" #include "platform/graphics/filters/FEComponentTransfer.h" #include "platform/graphics/filters/FEDropShadow.h" #include "platform/graphics/filters/FEGaussianBlur.h" #include "platform/graphics/filters/SourceGraphic.h" #include "wtf/MathExtras.h" #include <algorithm> namespace blink { namespace { inline void endMatrixRow(Vector<float>& matrix) { matrix.uncheckedAppend(0); matrix.uncheckedAppend(0); } inline void lastMatrixRow(Vector<float>& matrix) { matrix.uncheckedAppend(0); matrix.uncheckedAppend(0); matrix.uncheckedAppend(0); matrix.uncheckedAppend(1); matrix.uncheckedAppend(0); } Vector<float> grayscaleMatrix(double amount) { double oneMinusAmount = clampTo(1 - amount, 0.0, 1.0); // See https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#grayscaleEquivalent // for information on parameters. Vector<float> matrix; matrix.reserveInitialCapacity(20); matrix.uncheckedAppend(narrowPrecisionToFloat(0.2126 + 0.7874 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.7152 - 0.7152 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.0722 - 0.0722 * oneMinusAmount)); endMatrixRow(matrix); matrix.uncheckedAppend(narrowPrecisionToFloat(0.2126 - 0.2126 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.7152 + 0.2848 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.0722 - 0.0722 * oneMinusAmount)); endMatrixRow(matrix); matrix.uncheckedAppend(narrowPrecisionToFloat(0.2126 - 0.2126 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.7152 - 0.7152 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.0722 + 0.9278 * oneMinusAmount)); endMatrixRow(matrix); lastMatrixRow(matrix); return matrix; } Vector<float> sepiaMatrix(double amount) { double oneMinusAmount = clampTo(1 - amount, 0.0, 1.0); // See https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#sepiaEquivalent // for information on parameters. Vector<float> matrix; matrix.reserveInitialCapacity(20); matrix.uncheckedAppend(narrowPrecisionToFloat(0.393 + 0.607 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.769 - 0.769 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.189 - 0.189 * oneMinusAmount)); endMatrixRow(matrix); matrix.uncheckedAppend(narrowPrecisionToFloat(0.349 - 0.349 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.686 + 0.314 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.168 - 0.168 * oneMinusAmount)); endMatrixRow(matrix); matrix.uncheckedAppend(narrowPrecisionToFloat(0.272 - 0.272 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.534 - 0.534 * oneMinusAmount)); matrix.uncheckedAppend(narrowPrecisionToFloat(0.131 + 0.869 * oneMinusAmount)); endMatrixRow(matrix); lastMatrixRow(matrix); return matrix; } } // namespace FilterEffectBuilder::FilterEffectBuilder() { } FilterEffectBuilder::~FilterEffectBuilder() { } DEFINE_TRACE(FilterEffectBuilder) { visitor->trace(m_lastEffect); visitor->trace(m_referenceFilters); } bool FilterEffectBuilder::build(Element* element, const FilterOperations& operations, float zoom, const FloatSize* referenceBoxSize, const SkPaint* fillPaint, const SkPaint* strokePaint) { // Create a parent filter for shorthand filters. These have already been scaled by the CSS code for page zoom, so scale is 1.0 here. Filter* parentFilter = Filter::create(1.0f); FilterEffect* previousEffect = parentFilter->getSourceGraphic(); for (size_t i = 0; i < operations.operations().size(); ++i) { FilterEffect* effect = nullptr; FilterOperation* filterOperation = operations.operations().at(i).get(); switch (filterOperation->type()) { case FilterOperation::REFERENCE: { Filter* referenceFilter = ReferenceFilterBuilder::build(zoom, element, previousEffect, toReferenceFilterOperation(*filterOperation), referenceBoxSize, fillPaint, strokePaint); if (referenceFilter) { effect = referenceFilter->lastEffect(); m_referenceFilters.append(referenceFilter); } break; } case FilterOperation::GRAYSCALE: { Vector<float> inputParameters = grayscaleMatrix(toBasicColorMatrixFilterOperation(filterOperation)->amount()); effect = FEColorMatrix::create(parentFilter, FECOLORMATRIX_TYPE_MATRIX, inputParameters); break; } case FilterOperation::SEPIA: { Vector<float> inputParameters = sepiaMatrix(toBasicColorMatrixFilterOperation(filterOperation)->amount()); effect = FEColorMatrix::create(parentFilter, FECOLORMATRIX_TYPE_MATRIX, inputParameters); break; } case FilterOperation::SATURATE: { Vector<float> inputParameters; inputParameters.append(narrowPrecisionToFloat(toBasicColorMatrixFilterOperation(filterOperation)->amount())); effect = FEColorMatrix::create(parentFilter, FECOLORMATRIX_TYPE_SATURATE, inputParameters); break; } case FilterOperation::HUE_ROTATE: { Vector<float> inputParameters; inputParameters.append(narrowPrecisionToFloat(toBasicColorMatrixFilterOperation(filterOperation)->amount())); effect = FEColorMatrix::create(parentFilter, FECOLORMATRIX_TYPE_HUEROTATE, inputParameters); break; } case FilterOperation::INVERT: { BasicComponentTransferFilterOperation* componentTransferOperation = toBasicComponentTransferFilterOperation(filterOperation); ComponentTransferFunction transferFunction; transferFunction.type = FECOMPONENTTRANSFER_TYPE_TABLE; Vector<float> transferParameters; transferParameters.append(narrowPrecisionToFloat(componentTransferOperation->amount())); transferParameters.append(narrowPrecisionToFloat(1 - componentTransferOperation->amount())); transferFunction.tableValues = transferParameters; ComponentTransferFunction nullFunction; effect = FEComponentTransfer::create(parentFilter, transferFunction, transferFunction, transferFunction, nullFunction); break; } case FilterOperation::OPACITY: { ComponentTransferFunction transferFunction; transferFunction.type = FECOMPONENTTRANSFER_TYPE_TABLE; Vector<float> transferParameters; transferParameters.append(0); transferParameters.append(narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount())); transferFunction.tableValues = transferParameters; ComponentTransferFunction nullFunction; effect = FEComponentTransfer::create(parentFilter, nullFunction, nullFunction, nullFunction, transferFunction); break; } case FilterOperation::BRIGHTNESS: { ComponentTransferFunction transferFunction; transferFunction.type = FECOMPONENTTRANSFER_TYPE_LINEAR; transferFunction.slope = narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount()); transferFunction.intercept = 0; ComponentTransferFunction nullFunction; effect = FEComponentTransfer::create(parentFilter, transferFunction, transferFunction, transferFunction, nullFunction); break; } case FilterOperation::CONTRAST: { ComponentTransferFunction transferFunction; transferFunction.type = FECOMPONENTTRANSFER_TYPE_LINEAR; float amount = narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount()); transferFunction.slope = amount; transferFunction.intercept = -0.5 * amount + 0.5; ComponentTransferFunction nullFunction; effect = FEComponentTransfer::create(parentFilter, transferFunction, transferFunction, transferFunction, nullFunction); break; } case FilterOperation::BLUR: { float stdDeviation = floatValueForLength(toBlurFilterOperation(filterOperation)->stdDeviation(), 0); effect = FEGaussianBlur::create(parentFilter, stdDeviation, stdDeviation); break; } case FilterOperation::DROP_SHADOW: { DropShadowFilterOperation* dropShadowOperation = toDropShadowFilterOperation(filterOperation); float stdDeviation = dropShadowOperation->stdDeviation(); float x = dropShadowOperation->x(); float y = dropShadowOperation->y(); effect = FEDropShadow::create(parentFilter, stdDeviation, stdDeviation, x, y, dropShadowOperation->getColor(), 1); break; } case FilterOperation::BOX_REFLECT: { BoxReflectFilterOperation* boxReflectOperation = toBoxReflectFilterOperation(filterOperation); effect = FEBoxReflect::create(parentFilter, boxReflectOperation->direction(), boxReflectOperation->offset()); break; } default: break; } if (effect) { if (filterOperation->type() != FilterOperation::REFERENCE) { // Unlike SVG, filters applied here should not clip to their primitive subregions. effect->setClipsToBounds(false); effect->setOperatingColorSpace(ColorSpaceDeviceRGB); effect->inputEffects().append(previousEffect); } if (previousEffect->originTainted()) effect->setOriginTainted(); previousEffect = effect; } } m_referenceFilters.append(parentFilter); // We need to keep the old effects alive until this point, so that SVG reference filters // can share cached resources across frames. m_lastEffect = previousEffect; // If we didn't make any effects, tell our caller we are not valid if (!m_lastEffect.get()) return false; return true; } } // namespace blink
{ "content_hash": "bbfbceffb4deccf7e56a4f6a7002d99d", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 187, "avg_line_length": 43.549180327868854, "alnum_prop": 0.7043101825710522, "repo_name": "was4444/chromium.src", "id": "8d231ac7e9d38407adc519d7849482dcc1d91e0c", "size": "12021", "binary": false, "copies": "1", "ref": "refs/heads/nw15", "path": "third_party/WebKit/Source/core/paint/FilterEffectBuilder.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
// This file is automatically generated. package adila.db; /* * Acer Liquid Z500 * * DEVICE: acer_Z500 * MODEL: Z500 */ final class acer5fz500_z500 { public static final String DATA = "Acer|Liquid Z500|"; }
{ "content_hash": "431903ba33b8e15c4524d2f4f82824b9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 58, "avg_line_length": 16.76923076923077, "alnum_prop": 0.6788990825688074, "repo_name": "karim/adila", "id": "dc3b808cc24ac856e96b51c0816cd47a635d8c0f", "size": "218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "database/src/main/java/adila/db/acer5fz500_z500.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2903103" }, { "name": "Prolog", "bytes": "489" }, { "name": "Python", "bytes": "3280" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>CE USART: include Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CE USART </div> <div id="projectbrief">USART Driver for the CE course</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li class="current"><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('dir_d44c64559bbebec7f509842c48db8b23.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">include Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="subdirs"></a> Directories</h2></td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:_f_i_f_o_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="_f_i_f_o_8h.html">FIFO.h</a> <a href="_f_i_f_o_8h_source.html">[code]</a></td></tr> <tr class="memdesc:_f_i_f_o_8h"><td class="mdescLeft">&#160;</td><td class="mdescRight">FIFO setup and utilization. <br /></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:serial__interface_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="serial__interface_8h.html">serial_interface.h</a> <a href="serial__interface_8h_source.html">[code]</a></td></tr> <tr class="memdesc:serial__interface_8h"><td class="mdescLeft">&#160;</td><td class="mdescRight">Header for the <a class="el" href="struct_serial_interface.html" title="SerialInterface struct represents an interface to USART device. ">SerialInterface</a> struct and result codes. <br /></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_d44c64559bbebec7f509842c48db8b23.html">include</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li> </ul> </div> </body> </html>
{ "content_hash": "eb6d4c5d516de0258e849309e4815165", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 296, "avg_line_length": 45.4485294117647, "alnum_prop": 0.6534541336353341, "repo_name": "matthewphilyaw/ce_USART", "id": "fea0c4e13af880151ee1a1406194fbdd9aa15bd4", "size": "6181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documents/html/dir_d44c64559bbebec7f509842c48db8b23.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "26460" }, { "name": "C", "bytes": "10560905" }, { "name": "C++", "bytes": "5659" }, { "name": "CSS", "bytes": "39396" }, { "name": "HTML", "bytes": "774709" }, { "name": "JavaScript", "bytes": "87414" }, { "name": "Python", "bytes": "6507" } ], "symlink_target": "" }
package io.github.factoryfx.docu.initializr; import io.github.factoryfx.factory.SimpleFactoryBase; import io.github.factoryfx.factory.attribute.dependency.FactoryAttribute; import io.github.factoryfx.jetty.JettyServerFactory; import java.lang.Override; import org.eclipse.jetty.server.Server; /** * Root factory of the project */ public class ServerRootFactory extends SimpleFactoryBase<Server, ServerRootFactory> { public final FactoryAttribute<Server, JettyServerFactory<ServerRootFactory>> jettyServer = new FactoryAttribute<>(); @Override public Server createImpl() { return jettyServer.instance(); } }
{ "content_hash": "865ee5fb36a938046acf45fe159e112d", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 118, "avg_line_length": 34.611111111111114, "alnum_prop": 0.8057784911717496, "repo_name": "factoryfx/factoryfx", "id": "e546a6c76435f9358a17e95d426d678b0804fb0e", "size": "623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docu/src/main/java/io/github/factoryfx/docu/initializr/ServerRootFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2175" }, { "name": "HTML", "bytes": "3322" }, { "name": "Java", "bytes": "2095814" }, { "name": "JavaScript", "bytes": "105762" }, { "name": "TypeScript", "bytes": "145605" } ], "symlink_target": "" }
Initial release of razor
{ "content_hash": "1778cbce3cc24b389b295155ecb60a47", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 24, "avg_line_length": 25, "alnum_prop": 0.84, "repo_name": "jeffshantz/chef-razor", "id": "69c8224a8d12bc4c96d1173107c95d82651db903", "size": "34", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "16942" } ], "symlink_target": "" }
<?php return [ /* |-------------------------------------------------------------------------- | Proxy Active? |-------------------------------------------------------------------------- | | Determines whether the rewriting of the URLs is active. Default is false. | */ 'proxy_active' => getenv("PROXY_ACTIVE"), /* |-------------------------------------------------------------------------- | Public Absolute URL Override |-------------------------------------------------------------------------- | | Overrides the root of the path generated by various methods to be the value | specified here when resolving the "public" directory. Methods include | asset(), url(), etc. | | I.E. A value of "http://localhost/someotherpath/public" would make the | methods start with "http://localhost/someotherpath/public" instead | of the typical "http://[domain]/[application path]/public" prefix. | */ 'public_url_override' => getenv("PUBLIC_URL_OVERRIDE"), /* |-------------------------------------------------------------------------- | Public URL Schema Override |-------------------------------------------------------------------------- | | Overrides the schema (http|https) that will be prefixed to all URLs. | */ 'public_schema_override' => getenv("PUBLIC_SCHEMA_OVERRIDE"), /* |-------------------------------------------------------------------------- | Proxied Path Header |-------------------------------------------------------------------------- | | The PHP-transformed name of the header that is passing along the rewritten | base URL from the proxy. Defaults to "HTTP_X_FORWARDED_PATH". | */ 'proxy_path_header' => getenv("PROXY_PATH_HEADER"), /* |-------------------------------------------------------------------------- | Trusted Proxies |-------------------------------------------------------------------------- | | Comma-delimited list of the hostnames/IP addresses of proxy servers that | are allowed to manipulate the scheme and base URL. If no trusted proxies | have been set then proxying is allowed implicitly since this functions | as a whitelist. | */ 'trusted_proxies' => getenv("TRUSTED_PROXIES"), ];
{ "content_hash": "15ee062254818b9705fdf22c1e21565d", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 81, "avg_line_length": 36.09230769230769, "alnum_prop": 0.42071611253196933, "repo_name": "csun-metalab/laravel-4-proxypass", "id": "13553a6cc972cb6eaf684ccba790aae2f9c4432a", "size": "2346", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/config/config.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "7501" } ], "symlink_target": "" }
#include "config.h" #include "core/dom/Fullscreen.h" #include "core/HTMLNames.h" #include "core/dom/Document.h" #include "core/events/Event.h" #include "core/frame/FrameHost.h" #include "core/frame/LocalFrame.h" #include "core/frame/Settings.h" #include "core/frame/UseCounter.h" #include "core/html/HTMLIFrameElement.h" #include "core/html/HTMLMediaElement.h" #include "core/page/Chrome.h" #include "core/page/ChromeClient.h" #include "core/page/EventHandler.h" #include "core/rendering/RenderFullScreen.h" #include "platform/UserGestureIndicator.h" namespace blink { using namespace HTMLNames; static bool fullscreenIsAllowedForAllOwners(const Document& document) { for (const Element* owner = document.ownerElement(); owner; owner = owner->document().ownerElement()) { if (!isHTMLIFrameElement(owner)) return false; if (!owner->hasAttribute(allowfullscreenAttr)) return false; } return true; } static bool fullscreenIsSupported(const Document& document) { // Fullscreen is supported if there is no previously-established user preference, // security risk, or platform limitation. return !document.settings() || document.settings()->fullscreenSupported(); } static bool fullscreenElementReady(const Element& element, Fullscreen::RequestType requestType) { // A fullscreen element ready check for an element |element| returns true if all of the // following are true, and false otherwise: // |element| is in a document. if (!element.inDocument()) return false; // |element|'s node document's fullscreen enabled flag is set. if (!fullscreenIsAllowedForAllOwners(element.document())) { if (requestType == Fullscreen::PrefixedVideoRequest) UseCounter::count(element.document(), UseCounter::VideoFullscreenAllowedExemption); else return false; } // |element|'s node document's fullscreen element stack is either empty or its top element is an // inclusive ancestor of |element|. if (const Element* topElement = Fullscreen::fullscreenElementFrom(element.document())) { if (!topElement->contains(&element)) return false; } // |element| has no ancestor element whose local name is iframe and namespace is the HTML // namespace. if (Traversal<HTMLIFrameElement>::firstAncestor(element)) return false; // |element|'s node document's browsing context either has a browsing context container and the // fullscreen element ready check returns true for |element|'s node document's browsing // context's browsing context container, or it has no browsing context container. if (const Element* owner = element.document().ownerElement()) { if (!fullscreenElementReady(*owner, requestType)) return false; } return true; } static bool isPrefixed(const AtomicString& type) { return type == EventTypeNames::webkitfullscreenchange || type == EventTypeNames::webkitfullscreenerror; } static PassRefPtrWillBeRawPtr<Event> createEvent(const AtomicString& type, EventTarget& target) { EventInit initializer; initializer.bubbles = isPrefixed(type); RefPtrWillBeRawPtr<Event> event = Event::create(type, initializer); event->setTarget(&target); return event; } const char* Fullscreen::supplementName() { return "Fullscreen"; } Fullscreen& Fullscreen::from(Document& document) { Fullscreen* fullscreen = fromIfExists(document); if (!fullscreen) { fullscreen = new Fullscreen(document); DocumentSupplement::provideTo(document, supplementName(), adoptPtrWillBeNoop(fullscreen)); } return *fullscreen; } Fullscreen* Fullscreen::fromIfExistsSlow(Document& document) { return static_cast<Fullscreen*>(DocumentSupplement::from(document, supplementName())); } Element* Fullscreen::fullscreenElementFrom(Document& document) { if (Fullscreen* found = fromIfExists(document)) return found->fullscreenElement(); return 0; } Element* Fullscreen::currentFullScreenElementFrom(Document& document) { if (Fullscreen* found = fromIfExists(document)) return found->webkitCurrentFullScreenElement(); return 0; } bool Fullscreen::isFullScreen(Document& document) { return currentFullScreenElementFrom(document); } Fullscreen::Fullscreen(Document& document) : DocumentLifecycleObserver(&document) , m_fullScreenRenderer(nullptr) , m_eventQueueTimer(this, &Fullscreen::eventQueueTimerFired) { document.setHasFullscreenSupplement(); } Fullscreen::~Fullscreen() { } inline Document* Fullscreen::document() { return lifecycleContext(); } void Fullscreen::documentWasDetached() { m_eventQueue.clear(); if (m_fullScreenRenderer) m_fullScreenRenderer->destroy(); #if ENABLE(OILPAN) m_fullScreenElement = nullptr; m_fullScreenElementStack.clear(); #endif } #if !ENABLE(OILPAN) void Fullscreen::documentWasDisposed() { // NOTE: the context dispose phase is not supported in oilpan. Please // consider using the detach phase instead. m_fullScreenElement = nullptr; m_fullScreenElementStack.clear(); } #endif void Fullscreen::requestFullscreen(Element& element, RequestType requestType) { // Ignore this request if the document is not in a live frame. if (!document()->isActive()) return; // If |element| is on top of |doc|'s fullscreen element stack, terminate these substeps. if (&element == fullscreenElement()) return; do { // 1. If any of the following conditions are true, terminate these steps and queue a task to fire // an event named fullscreenerror with its bubbles attribute set to true on the context object's // node document: // The fullscreen element ready check returns false. if (!fullscreenElementReady(element, requestType)) break; // This algorithm is not allowed to show a pop-up: // An algorithm is allowed to show a pop-up if, in the task in which the algorithm is running, either: // - an activation behavior is currently being processed whose click event was trusted, or // - the event listener for a trusted click event is being handled. if (!UserGestureIndicator::processingUserGesture()) { String message = ExceptionMessages::failedToExecute("requestFullScreen", "Element", "API can only be initiated by a user gesture."); document()->executionContext()->addConsoleMessage( ConsoleMessage::create(JSMessageSource, WarningMessageLevel, message)); break; } // Fullscreen is not supported. if (!fullscreenIsSupported(element.document())) break; // 2. Let doc be element's node document. (i.e. "this") Document* currentDoc = document(); // 3. Let docs be all doc's ancestor browsing context's documents (if any) and doc. Deque<Document*> docs; do { docs.prepend(currentDoc); currentDoc = currentDoc->ownerElement() ? &currentDoc->ownerElement()->document() : 0; } while (currentDoc); // 4. For each document in docs, run these substeps: Deque<Document*>::iterator current = docs.begin(), following = docs.begin(); do { ++following; // 1. Let following document be the document after document in docs, or null if there is no // such document. Document* currentDoc = *current; Document* followingDoc = following != docs.end() ? *following : 0; // 2. If following document is null, push context object on document's fullscreen element // stack, and queue a task to fire an event named fullscreenchange with its bubbles attribute // set to true on the document. if (!followingDoc) { from(*currentDoc).pushFullscreenElementStack(element, requestType); enqueueChangeEvent(*currentDoc, requestType); continue; } // 3. Otherwise, if document's fullscreen element stack is either empty or its top element // is not following document's browsing context container, Element* topElement = fullscreenElementFrom(*currentDoc); if (!topElement || topElement != followingDoc->ownerElement()) { // ...push following document's browsing context container on document's fullscreen element // stack, and queue a task to fire an event named fullscreenchange with its bubbles attribute // set to true on document. from(*currentDoc).pushFullscreenElementStack(*followingDoc->ownerElement(), requestType); enqueueChangeEvent(*currentDoc, requestType); continue; } // 4. Otherwise, do nothing for this document. It stays the same. } while (++current != docs.end()); // 5. Return, and run the remaining steps asynchronously. // 6. Optionally, perform some animation. document()->frameHost()->chrome().client().enterFullScreenForElement(&element); // 7. Optionally, display a message indicating how the user can exit displaying the context object fullscreen. return; } while (0); enqueueErrorEvent(element, requestType); } void Fullscreen::fullyExitFullscreen(Document& document) { // To fully exit fullscreen, run these steps: // 1. Let |doc| be the top-level browsing context's document. Document& doc = document.topDocument(); // 2. If |doc|'s fullscreen element stack is empty, terminate these steps. if (!fullscreenElementFrom(doc)) return; // 3. Remove elements from |doc|'s fullscreen element stack until only the top element is left. size_t stackSize = from(doc).m_fullScreenElementStack.size(); from(doc).m_fullScreenElementStack.remove(0, stackSize - 1); ASSERT(from(doc).m_fullScreenElementStack.size() == 1); // 4. Act as if the exitFullscreen() method was invoked on |doc|. from(doc).exitFullscreen(); } void Fullscreen::exitFullscreen() { // The exitFullscreen() method must run these steps: // 1. Let doc be the context object. (i.e. "this") Document* currentDoc = document(); if (!currentDoc->isActive()) return; // 2. If doc's fullscreen element stack is empty, terminate these steps. if (m_fullScreenElementStack.isEmpty()) return; // 3. Let descendants be all the doc's descendant browsing context's documents with a non-empty fullscreen // element stack (if any), ordered so that the child of the doc is last and the document furthest // away from the doc is first. WillBeHeapDeque<RefPtrWillBeMember<Document> > descendants; for (Frame* descendant = document()->frame() ? document()->frame()->tree().traverseNext() : 0; descendant; descendant = descendant->tree().traverseNext()) { if (!descendant->isLocalFrame()) continue; ASSERT(toLocalFrame(descendant)->document()); if (fullscreenElementFrom(*toLocalFrame(descendant)->document())) descendants.prepend(toLocalFrame(descendant)->document()); } // 4. For each descendant in descendants, empty descendant's fullscreen element stack, and queue a // task to fire an event named fullscreenchange with its bubbles attribute set to true on descendant. for (WillBeHeapDeque<RefPtrWillBeMember<Document> >::iterator i = descendants.begin(); i != descendants.end(); ++i) { ASSERT(*i); RequestType requestType = from(**i).m_fullScreenElementStack.last().second; from(**i).clearFullscreenElementStack(); enqueueChangeEvent(**i, requestType); } // 5. While doc is not null, run these substeps: Element* newTop = 0; while (currentDoc) { RequestType requestType = from(*currentDoc).m_fullScreenElementStack.last().second; // 1. Pop the top element of doc's fullscreen element stack. from(*currentDoc).popFullscreenElementStack(); // If doc's fullscreen element stack is non-empty and the element now at the top is either // not in a document or its node document is not doc, repeat this substep. newTop = fullscreenElementFrom(*currentDoc); if (newTop && (!newTop->inDocument() || newTop->document() != currentDoc)) continue; // 2. Queue a task to fire an event named fullscreenchange with its bubbles attribute set to true // on doc. enqueueChangeEvent(*currentDoc, requestType); // 3. If doc's fullscreen element stack is empty and doc's browsing context has a browsing context // container, set doc to that browsing context container's node document. if (!newTop && currentDoc->ownerElement()) { currentDoc = &currentDoc->ownerElement()->document(); continue; } // 4. Otherwise, set doc to null. currentDoc = 0; } // 6. Return, and run the remaining steps asynchronously. // 7. Optionally, perform some animation. FrameHost* host = document()->frameHost(); // Speculative fix for engaget.com/videos per crbug.com/336239. // FIXME: This check is wrong. We ASSERT(document->isActive()) above // so this should be redundant and should be removed! if (!host) return; // Only exit out of full screen window mode if there are no remaining elements in the // full screen stack. if (!newTop) { // FIXME: if the frame exiting fullscreen is not the frame that entered // fullscreen (but a parent frame for example), m_fullScreenElement // might be null. We want to pass an element that is part of the // document so we will pass the documentElement in that case. // This should be fix by exiting fullscreen for a frame instead of an // element, see https://crbug.com/441259 host->chrome().client().exitFullScreenForElement( m_fullScreenElement ? m_fullScreenElement.get() : document()->documentElement()); return; } // Otherwise, notify the chrome of the new full screen element. host->chrome().client().enterFullScreenForElement(newTop); } bool Fullscreen::fullscreenEnabled(Document& document) { // 4. The fullscreenEnabled attribute must return true if the context object has its // fullscreen enabled flag set and fullscreen is supported, and false otherwise. // Top-level browsing contexts are implied to have their allowFullScreen attribute set. return fullscreenIsAllowedForAllOwners(document) && fullscreenIsSupported(document); } void Fullscreen::didEnterFullScreenForElement(Element* element) { ASSERT(element); if (!document()->isActive()) return; if (m_fullScreenRenderer) m_fullScreenRenderer->unwrapRenderer(); m_fullScreenElement = element; // Create a placeholder block for a the full-screen element, to keep the page from reflowing // when the element is removed from the normal flow. Only do this for a RenderBox, as only // a box will have a frameRect. The placeholder will be created in setFullScreenRenderer() // during layout. RenderObject* renderer = m_fullScreenElement->renderer(); bool shouldCreatePlaceholder = renderer && renderer->isBox(); if (shouldCreatePlaceholder) { m_savedPlaceholderFrameRect = toRenderBox(renderer)->frameRect(); m_savedPlaceholderRenderStyle = RenderStyle::clone(renderer->style()); } if (m_fullScreenElement != document()->documentElement()) RenderFullScreen::wrapRenderer(renderer, renderer ? renderer->parent() : 0, document()); m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true); // FIXME: This should not call updateStyleIfNeeded. document()->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::FullScreen)); document()->updateRenderTreeIfNeeded(); m_fullScreenElement->didBecomeFullscreenElement(); if (document()->frame()) document()->frame()->eventHandler().scheduleHoverStateUpdate(); m_eventQueueTimer.startOneShot(0, FROM_HERE); } void Fullscreen::didExitFullScreenForElement(Element*) { if (!m_fullScreenElement) return; if (!document()->isActive()) return; m_fullScreenElement->willStopBeingFullscreenElement(); m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false); if (m_fullScreenRenderer) m_fullScreenRenderer->unwrapRenderer(); m_fullScreenElement = nullptr; document()->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::FullScreen)); if (document()->frame()) document()->frame()->eventHandler().scheduleHoverStateUpdate(); // When fullyExitFullscreen is called, we call exitFullscreen on the topDocument(). That means // that the events will be queued there. So if we have no events here, start the timer on the // exiting document. Document* exitingDocument = document(); if (m_eventQueue.isEmpty()) exitingDocument = &document()->topDocument(); ASSERT(exitingDocument); from(*exitingDocument).m_eventQueueTimer.startOneShot(0, FROM_HERE); } void Fullscreen::setFullScreenRenderer(RenderFullScreen* renderer) { if (renderer == m_fullScreenRenderer) return; if (renderer && m_savedPlaceholderRenderStyle) { renderer->createPlaceholder(m_savedPlaceholderRenderStyle.release(), m_savedPlaceholderFrameRect); } else if (renderer && m_fullScreenRenderer && m_fullScreenRenderer->placeholder()) { RenderBlock* placeholder = m_fullScreenRenderer->placeholder(); renderer->createPlaceholder(RenderStyle::clone(placeholder->style()), placeholder->frameRect()); } if (m_fullScreenRenderer) m_fullScreenRenderer->unwrapRenderer(); ASSERT(!m_fullScreenRenderer); m_fullScreenRenderer = renderer; } void Fullscreen::fullScreenRendererDestroyed() { m_fullScreenRenderer = nullptr; } void Fullscreen::enqueueChangeEvent(Document& document, RequestType requestType) { RefPtrWillBeRawPtr<Event> event; if (requestType == UnprefixedRequest) { event = createEvent(EventTypeNames::fullscreenchange, document); } else { ASSERT(document.hasFullscreenSupplement()); Fullscreen& fullscreen = from(document); EventTarget* target = fullscreen.fullscreenElement(); if (!target) target = fullscreen.webkitCurrentFullScreenElement(); if (!target) target = &document; event = createEvent(EventTypeNames::webkitfullscreenchange, *target); } m_eventQueue.append(event); // NOTE: The timer is started in didEnterFullScreenForElement/didExitFullScreenForElement. } void Fullscreen::enqueueErrorEvent(Element& element, RequestType requestType) { RefPtrWillBeRawPtr<Event> event; if (requestType == UnprefixedRequest) event = createEvent(EventTypeNames::fullscreenerror, element.document()); else event = createEvent(EventTypeNames::webkitfullscreenerror, element); m_eventQueue.append(event); m_eventQueueTimer.startOneShot(0, FROM_HERE); } void Fullscreen::eventQueueTimerFired(Timer<Fullscreen>*) { // Since we dispatch events in this function, it's possible that the // document will be detached and GC'd. We protect it here to make sure we // can finish the function successfully. RefPtrWillBeRawPtr<Document> protectDocument(document()); WillBeHeapDeque<RefPtrWillBeMember<Event> > eventQueue; m_eventQueue.swap(eventQueue); while (!eventQueue.isEmpty()) { RefPtrWillBeRawPtr<Event> event = eventQueue.takeFirst(); Node* target = event->target()->toNode(); // If the element was removed from our tree, also message the documentElement. if (!target->inDocument() && document()->documentElement()) { ASSERT(isPrefixed(event->type())); eventQueue.append(createEvent(event->type(), *document()->documentElement())); } target->dispatchEvent(event); } } void Fullscreen::elementRemoved(Element& oldNode) { // Whenever the removing steps run with an |oldNode| and |oldNode| is in its node document's // fullscreen element stack, run these steps: // 1. If |oldNode| is at the top of its node document's fullscreen element stack, act as if the // exitFullscreen() method was invoked on that document. if (fullscreenElement() == &oldNode) { exitFullscreen(); return; } // 2. Otherwise, remove |oldNode| from its node document's fullscreen element stack. for (size_t i = 0; i < m_fullScreenElementStack.size(); ++i) { if (m_fullScreenElementStack[i].first.get() == &oldNode) { m_fullScreenElementStack.remove(i); return; } } // NOTE: |oldNode| was not in the fullscreen element stack. } void Fullscreen::clearFullscreenElementStack() { m_fullScreenElementStack.clear(); } void Fullscreen::popFullscreenElementStack() { if (m_fullScreenElementStack.isEmpty()) return; m_fullScreenElementStack.removeLast(); } void Fullscreen::pushFullscreenElementStack(Element& element, RequestType requestType) { m_fullScreenElementStack.append(std::make_pair(&element, requestType)); } void Fullscreen::trace(Visitor* visitor) { visitor->trace(m_fullScreenElement); visitor->trace(m_fullScreenElementStack); visitor->trace(m_fullScreenRenderer); visitor->trace(m_eventQueue); DocumentSupplement::trace(visitor); DocumentLifecycleObserver::trace(visitor); } } // namespace blink
{ "content_hash": "dcd9c89925f26ef83e677d60fa829bc8", "timestamp": "", "source": "github", "line_count": 589, "max_line_length": 160, "avg_line_length": 37.235993208828525, "alnum_prop": 0.6877165785154112, "repo_name": "mxOBS/deb-pkg_trusty_chromium-browser", "id": "dcbc6546310d273fce758353c611ad058d2babb4", "size": "23248", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/core/dom/Fullscreen.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "8402" }, { "name": "Assembly", "bytes": "230130" }, { "name": "Batchfile", "bytes": "34966" }, { "name": "C", "bytes": "12435900" }, { "name": "C++", "bytes": "264378706" }, { "name": "CMake", "bytes": "27829" }, { "name": "CSS", "bytes": "795726" }, { "name": "Dart", "bytes": "74976" }, { "name": "Emacs Lisp", "bytes": "2360" }, { "name": "Go", "bytes": "31783" }, { "name": "Groff", "bytes": "5283" }, { "name": "HTML", "bytes": "19491230" }, { "name": "Java", "bytes": "7637875" }, { "name": "JavaScript", "bytes": "12723911" }, { "name": "LLVM", "bytes": "1169" }, { "name": "Logos", "bytes": "6893" }, { "name": "Lua", "bytes": "14392" }, { "name": "Makefile", "bytes": "208315" }, { "name": "Objective-C", "bytes": "1460032" }, { "name": "Objective-C++", "bytes": "7760068" }, { "name": "PLpgSQL", "bytes": "175360" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "427212" }, { "name": "Python", "bytes": "11447382" }, { "name": "Ragel in Ruby Host", "bytes": "104846" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "1208350" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "nesC", "bytes": "18335" } ], "symlink_target": "" }
import time import unittest import sys from sts.entities.base import LocalEntity from sts.entities.base import SSHEntity from sts.entities.controllers import ControllerConfig from sts.entities.controllers import ControllerState from sts.entities.controllers import POXController from sts.entities.controllers import ONOSController paramiko_installed = False try: import paramiko paramiko_installed = True except ImportError: paramiko_installed = False def get_ssh_config(): """ Loads the login information for SSH server """ host = '192.168.56.11' port = 22 username = "mininet" password = "mininet" return host, port, username, password def can_connect(host, port, username, password): """ Returns True if the the login information can be used to connect to a remote ssh server. """ if not paramiko_installed: return False try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host, port, username, password) client.close() return True except Exception as exp: print >> sys.stderr, exp return False class POXControllerTest(unittest.TestCase): # TODO (AH): Test sync and namespaces def get_config(self): start_cmd = ("./pox.py --verbose --no-cli sts.syncproto.pox_syncer " "--blocking=False openflow.of_01 --address=__address__ " "--port=__port__") kill_cmd = "" cwd = "pox" config = ControllerConfig(start_cmd=start_cmd, kill_cmd=kill_cmd, cwd=cwd) return config def test_start(self): # Arrange config = self.get_config() # Act ctrl = POXController(controller_config=config) ctrl.start(None) time.sleep(5) state1 = ctrl.state check_status1 = ctrl.check_status(None) ctrl.kill() time.sleep(5) state2 = ctrl.state check_status2 = ctrl.check_status(None) #Assert self.assertEquals(state1, ControllerState.ALIVE) self.assertEquals(state2, ControllerState.DEAD) self.assertEquals(check_status1[0], True) self.assertEquals(check_status2[0], True) def test_restart(self): # Arrange config = self.get_config() # Act ctrl = POXController(controller_config=config) ctrl.start(None) time.sleep(5) state1 = ctrl.state check_status1 = ctrl.check_status(None) ctrl.kill() ctrl.restart() time.sleep(5) state2 = ctrl.state check_status2 = ctrl.check_status(None) ctrl.kill() time.sleep(5) state3 = ctrl.state check_status3 = ctrl.check_status(None) #Assert self.assertEquals(state1, ControllerState.ALIVE) self.assertEquals(state2, ControllerState.ALIVE) self.assertEquals(state3, ControllerState.DEAD) self.assertEquals(check_status1[0], True) self.assertEquals(check_status2[0], True) self.assertEquals(check_status3[0], True) def test_start(self): # Arrange config = self.get_config() # Act ctrl = POXController(controller_config=config) ctrl.start(None) time.sleep(5) state1 = ctrl.state check_status1 = ctrl.check_status(None) ctrl.kill() time.sleep(5) state2 = ctrl.state check_status2 = ctrl.check_status(None) #Assert self.assertEquals(state1, ControllerState.ALIVE) self.assertEquals(state2, ControllerState.DEAD) self.assertEquals(check_status1[0], True) self.assertEquals(check_status2[0], True) class ONOSControllerTest(unittest.TestCase): def get_config(self): start_cmd = "./start-onos.sh start" kill_cmd = "./start-onos.sh stop" restart_cmd = "./start-onos.sh stop" check = "./start-onos.sh status" address = '192.168.56.11' cwd = "ONOS" config = ControllerConfig(address=address, start_cmd=start_cmd, kill_cmd=kill_cmd, restart_cmd=restart_cmd, check_cmd=check, cwd=cwd) return config def get_executor(self): address = '192.168.56.11' ssh = SSHEntity(address, username='mininet', password='mininet', cwd='ONOS', label='ONOSDEV', redirect_output=True) return ssh def setUp(self): cmd_exec = LocalEntity(redirect_output=True) cmd_exec.execute_command("onos stop") cmd_exec.execute_command("cassandra start") cmd_exec.execute_command("cassandra start") def tearDown(self): cmd_exec = LocalEntity(redirect_output=True) cmd_exec.execute_command("onos stop") cmd_exec.execute_command("cassandra stop") cmd_exec.execute_command("zk status stop") @unittest.skipIf(not can_connect(*get_ssh_config()), "Couldn't connect to ONOS server") def test_start_kill(self): # Arrange config = self.get_config() cmd_exec = self.get_executor() # Act ctrl = ONOSController(controller_config=config, cmd_executor=cmd_exec) ctrl.start(None) time.sleep(20) state1 = ctrl.state check_status1 = ctrl.check_status(None) # clean up ctrl.kill() time.sleep(5) state2 = ctrl.state check_status2 = ctrl.check_status(None) #Assert self.assertEquals(state1, ControllerState.ALIVE) self.assertEquals(state2, ControllerState.DEAD) self.assertEquals(check_status1[0], True) self.assertEquals(check_status2[0], True)
{ "content_hash": "3b1e08b0676beb4c65ad4abfc9d5e88b", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 89, "avg_line_length": 29.126373626373628, "alnum_prop": 0.677985285795133, "repo_name": "jmiserez/sts", "id": "f3efef6aa440c132f9ef2b517e3f20e8b5dac534", "size": "5963", "binary": false, "copies": "2", "ref": "refs/heads/hb", "path": "tests/integration/sts/entities/controllers_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "1167857" }, { "name": "Shell", "bytes": "16594" } ], "symlink_target": "" }
// // GTLanguageCache.h // GoogleTranslate // #import <Foundation/Foundation.h> /*! * Object used to locally cache language objects to disk */ @interface GTLanguageCache : NSObject /*! * Pull a language list for the given language code from the cache * @param languageCode The language code for the list of languages * @return An array of GTLanguage objects for the given language code * @discussion If there is no cached languages for the given code, then this method will return nil. */ - (NSArray *)cachedLanguageListForLanguageCode:(NSString *)languageCode; /*! * Caches the given list for the specified language code * @param languageList Array of GTLanguage objects to be cached * @param languageCode The language code that specifies what language the language list is in. */ - (void)cacheLanguageList:(NSArray *)languageList forLanguageCode:(NSString *)languageCode; /*! * Clears the cache of all lists. */ - (void)clearCache; @end
{ "content_hash": "d379639362b4d8fc72151523cf2d5d52", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 101, "avg_line_length": 27.742857142857144, "alnum_prop": 0.7425334706488157, "repo_name": "waynehartman/GoogleTranslationAPI", "id": "3c95f9b49d49372c2803102ba229abbf79930e89", "size": "2549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GoogleTranslate/GTLanguageCache.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "14910" }, { "name": "Objective-C", "bytes": "711047" } ], "symlink_target": "" }
about_title=' # Über uns ' about_our_story_menu=' Chronologie ' about_our_story=' ## Chronologie ' about_iuventa_menu=' IUVENTA ' about_iuventa_title=' ## Die IUVENTA ' about_iuventa=' *Die Genauigkeit der angegeben Position ist abhängig vom aktuellen Empfang, der während Rettungseinsätzen für einige Zeit auch ausfallen kann.* Im Mai 2016 konnten wir nach unserer erfolgreichen Crowdfunding-Kampagne und durch die Hilfe unzähliger Unterstützer_innen, die IUVENTA erwerben. In den folgenden 2 Monaten wurde das Schiff umgebaut und nach Malta überführt. Seit Juli 2016 sind die Missionen der IUVENTA Jugend Rettets aktiver Beitrag zur Linderung des Leids im Mittelmeer. Ursprünglich war die 33m lange Iuventa als Fischereifahrzeug für die rauen Bedingungen der Nordsee konzipiert. Redundante Funktionen können im gesamten Schiff gefunden werden, wie z. B. zwei Hilfsmotoren und die extra robusten Konstruktionselemente des Hauptmotors, die auch unter härtesten Bedingungen einen kontinuierlichen Betrieb gewährleisten. Die großen Deckflächen ermöglichen die Unterbringung von bis zu 220 geretteten Personen. Planen können angebracht werden, um den Menschen Schutz vor Sonne, Wind und Regen zu bieten. Auf dem Hauptdeck werden zwei schnelle Rettungsboote (RHIBS) gelagert, die mit einem hydraulischen Teleskop Kran zu Wasser gelassen werden. Dieser wurde Anfang Februar 2017 durch ein besseres Modell ersetzt. Typischerweise für ein Fischereifahrzeug ist das Freibord bemerkenswert niedrig, das bietet uns zwei Vorteile: Erstens ermöglicht es das einfache Zuwasserlassen und Anbordholen der beiden Rettungsboote. Zweitens können die Boote der Geretteten längsseits genommen werden und Personen schnell und in sicherer Weise eingeladen werden. Bei normalen Rettungseinsätzen liegt die Besatzung zwischen 11 und 13 Personen. ' about_transparency_menu=' Transparenz ' about_transparency=' ## Transparenz ![Initiative Transparente Zivilgesellschaft](../f/logos/Transparente_Zivilgesellschaft.svg) Jugend **Rettet** nimmt seine Aufgaben als vertrauenswürdige und verantwortungsbewusste gemeinnützige Organisation ernst. Transparenz ist uns wichtig. Deshalb haben wir uns der [Initiative Transparente Zivilgesellschaft](http://www.transparente-zivilgesellschaft.de/) angeschlossen. Wir haben uns in diesem Rahmen verpflichtet, die nachstehenden Informationen der Öffentlichkeit auf unserer Webseite zur Verfügung zu stellen und regelmäßig zu updaten. ### 1. NAME, SITZ, ANSCHRIFT UND GRÜNDUNGSJAHR Der Verein Jugend **Rettet** e.V. wurde am 3. Oktober 2015 gegründet. Sitz und Anschrift des Vereins befinden sich in der Ruhlsdorferstraße 151, 14513 Teltow. ### 2. SATZUNG, ZIELE UND UMSETZUNG Unsere Vereinssatzung in ihrer aktuellen von der ordentlichen Mitgliederversammlung am 03. Oktober 2015 in Berlin beschlossenen Fassung finden Sie [hier](../f/files/Vereinssatzung_v1.pdf). Eine Übersicht zu den Zielen und Umsetzung des Vereins finden Sie [hier](./#intro). ### 3. ANGABEN ZUR STEUERBEGÜNSTIGUNG Die Satzung von „Jugend **Rettet** e.V.“ erfüllt nach dem letzten uns zugegangenen Bescheid des Finanzamts für Körperschaften I, Berlin (Steuernummer 27/669/53338) vom 03.11.2015 nach § 5 Abs. 1 Nr. 9 die offiziellen Kriterien zur Förderung folgender gemeinnütziger Zwecke: * Förderung der Hilfe für Flüchtlinge und Förderung der Rettung aus Lebensgefahr nach § 52 Abs. 2 Satz 1 Nr.(n) 10 und 11 AO * Förderung der Internationalen Gesinnung und Förderung des Bürgerschaftlichen Engagements nach § 52 Abs. 2 Satz 1 Nr.(n) 13 und 25 AO Folglich ist unsere Organisation von der Körperschaftssteuer und Gewerbesteuer befreit. Der Jugend **Rettet** e.V. ist berechtigt Spendenbescheinigungen auszustellen. Den offiziellen Bescheid finden Sie [hier.](../f/Gemeinnuetzigkeit_Bescheid.pdf) ### 4. NAME UND FUNKTION WESENTLICHER ENTSCHEIDUNGSTRÄGER Vorstand: * Erster Vorsitzender: Jakob Schoen * Zweite Vorsitzende: Lena Waldhoff ### 5. TÄTIGKEITSBERICHT Eine Übersicht über die Tätigkeiten des Vereins finden Sie in unserem [Jahresbericht 2015](../f/files/Jahresbericht_2015.pdf). ### 6. PERSONALSTRUKTUR Alle an Jugend **Rettet** beteiligten Personen, wie auch alle Berater_innen arbeiten ausschließlich auf ehrenamtlicher Basis. Unser Team besteht aus überwiegend jungen Menschen, deren Motivation für das Projekt auf das Retten auf einer Verbesserung der humanitären Lage im Mittelmeer basiert. Das Jugend Rettet Kernteam in Berlin besteht aus 9 Leuten. Deutschlandweit engagieren sich derzeit 60 Personen an unserer Arbeit. ### 7./8. ANGABEN ZUR MITTELHERKUNFT- UND VERWENDUNG Eine Übersicht über die Mittelherkunft- und Verwendung des Vereins finden Sie in unserem [Jahresbericht 2015](../f/files/Jahresbericht_JR_2015.pdf). ### 9. GESELLSCHAFTSRECHTLICHE VERBUNDENHEIT MIT DRITTEN Eine gesellschaftsrechtliche Verbundenheit mit Dritten, z.B. ausgegliederter Wirtschaftsbetrieb, Partnerorganisation oder Ähnliches besteht nicht. ### 10. NAMEN VON JURISTISCHEN PERSONEN, DEREN JÄHRLICHE ZAHLUNGEN MEHR ALS 10% DES GESAMTBUDGETS AUSMACHEN Jugend **Rettet** hat derzeit keine Unterstützer_innen oder Förderer_innen, deren jährliche Zahlungen mehr als 10% des Gesamtbudgets ausmachen. Unsere Arbeit trägt sich durch das Engagement und die Hilfe vieler. '
{ "content_hash": "fffc11e07c7f4286031a4dc5e1238792", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 451, "avg_line_length": 53.96938775510204, "alnum_prop": 0.8118737001323502, "repo_name": "Leonv1337/translations", "id": "404aad065b2d84a28cbb6a1ccf774a3bb2df4f3d", "size": "5360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "de/about_us.md", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "505" } ], "symlink_target": "" }
namespace System.Runtime.Remoting.Contexts { #if CONFIG_REMOTING using System.Runtime.Remoting.Messaging; public interface IDynamicMessageSink { // Process a message finish operation. void ProcessMessageFinish(IMessage replyMsg, bool bCliSide, bool bAsync); // Process a message start operation. void ProcessMessageStart(IMessage reqMsg, bool bCliSide, bool bAsync); }; // interface IDynamicMessageSink #endif // CONFIG_REMOTING }; // namespace System.Runtime.Remoting.Contexts
{ "content_hash": "43813c730d91d921db2e1f00f83fca90", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 74, "avg_line_length": 22.318181818181817, "alnum_prop": 0.790224032586558, "repo_name": "jjenki11/blaze-chem-rendering", "id": "29f840b70a02064c8ae2a9678db8ab80f858daeb", "size": "1390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "qca_designer/lib/pnetlib-0.8.0/runtime/System/Runtime/Remoting/Contexts/IDynamicMessageSink.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "2476" } ], "symlink_target": "" }
#import <Foundation/Foundation.h> #import <GLKit/GLKit.h> extern void iOS_GCanvas_Draw_Text(const unsigned short *text, unsigned int text_length, float x, float y, bool isStroke, void* context, void* fontContext); extern void iOS_GCanvas_GWebGLTxtImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, const char *src); extern void iOS_GCanvas_GWebGLTxtSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, const char *src); typedef NS_ENUM(NSUInteger, GCVContextType){ GCVContextType2D = 0, GCVContextTypeWebGL = 1 }; @class GCanvasPlugin; typedef GCanvasPlugin* (^FetchPluginBlock)(NSString * componentId); @protocol GCVImageLoaderProtocol; @interface GCanvasPlugin : NSObject @property(nonatomic, assign) BOOL gcanvasInited; /** * @abstract set LogLevel * * @param logLevel see definiation gcanvas::LogLevel, 0-debug, 1-info, 2-warn, 3-error */ + (void)setLogLevel:(NSUInteger)logLevel; + (void)setFetchPlugin:(FetchPluginBlock)block; /** * @abstract init GCanvas with componentId * @param componentId unique instance bind GCanvas */ - (instancetype)initWithComponentId:(NSString*)componentId; /** * @abstract set Canvas frame * @param frame frame of Canvas */ - (void)setFrame:(CGRect)frame; /** * @abstract set Canvas clear color * @param color clear color value */ - (void)setClearColor:(UIColor*)color; /** * @abstract add commamds received from JS Bridge "render" * @param commands commands from JS */ - (void)addCommands:(NSString *)commands; /** * @abstract execute command received from JS Bridge "render" */ - (void)execCommands; /** * @abstract remove commands after execute */ - (void)removeCommands; /** * @abstract release manager when release webview */ - (void)releaseManager; /** * @abstract fetch image texture id in this GCanvas context * * @param aid id from js */ - (GLuint)getTextureId:(NSUInteger)aid; /** * @abstract binding image with texture id, id from JS and image size. * * @param tid texture id * @param aid id from js * @param width image width * @param height image height * @param offscreen tid is offline texture, while offscreen=YES */ - (void)addTextureId:(NSUInteger)tid withAppId:(NSUInteger)aid width:(NSUInteger)width height:(NSUInteger)height offscreen:(BOOL)offscreen; /** * @abstract binding image with texture id, id from JS and image size. * * @param tid texture id * @param aid id from js * @param width image width * @param height image height */ - (void)addTextureId:(NSUInteger)tid withAppId:(NSUInteger)aid width:(NSUInteger)width height:(NSUInteger)height; /** * @abstract native download image * * @param loader impletement GCVImageLoaderProtocol protocol */ - (void)setImageLoader:(id<GCVImageLoaderProtocol>)loader; /** * @abstract set pixel rate after recived from JS * * @param ratio value */ - (void)setDevicePixelRatio:(double)ratio; /** * @abstract set GCanvas context type * * @param contextType see GCVContextType definiation */ - (void)setContextType:(GCVContextType)contextType; /** * @abstract get GCanvas context type * * @return current context type, see GCVContextType definiation */ - (int)contextType; /** * @abstract get GCanvas fps * * @return fps */ - (CGFloat)fps; /** * @abstract get GCanvas textureId * * @return fbo textureId */ - (GLuint)textureId; /** * @abstract explicit remove GCanvas */ - (void)removeGCanvas; /** * @abstract get webgl Sync call result */ - (NSString*)getSyncResult; /** * @abstract set GLKView */ - (void)setGLKView:(GLKView*)glkview; - (GLKView*)getGLKView; @end
{ "content_hash": "74467bcba6e5c45bb35b6c8ef29f45ea", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 155, "avg_line_length": 24.1840490797546, "alnum_prop": 0.6709791983764587, "repo_name": "jwxbond/GCanvas", "id": "f95cafb3add13bd7807eb51c414f88cd3b0abd59", "size": "4239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ios/BridgeModule/GCanvasPlugin.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2673420" }, { "name": "C++", "bytes": "1343130" }, { "name": "CMake", "bytes": "8322" }, { "name": "CSS", "bytes": "13047" }, { "name": "GLSL", "bytes": "21523" }, { "name": "HTML", "bytes": "7850" }, { "name": "Java", "bytes": "2081913" }, { "name": "JavaScript", "bytes": "3252726" }, { "name": "Objective-C", "bytes": "142977" }, { "name": "Objective-C++", "bytes": "38857" }, { "name": "Ruby", "bytes": "4070" }, { "name": "Shell", "bytes": "683" } ], "symlink_target": "" }
// Copyright 2016 Esri. // // 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. using UIKit; namespace ArcGISRuntimeXamarin.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
{ "content_hash": "0389af7c7e456e0a361fc4f7eca26f1b", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 131, "avg_line_length": 38.041666666666664, "alnum_prop": 0.7426067907995619, "repo_name": "Arc3D/arcgis-runtime-samples-dotnet", "id": "6413772a27f03eb9494acf21695a25a9bfafd2fb", "size": "915", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Forms/iOS/Main.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "108" }, { "name": "C#", "bytes": "2131870" }, { "name": "Visual Basic", "bytes": "619022" } ], "symlink_target": "" }
package org.apache.synapse.config.xml; public class MessageStoreMediatorSerializationTest extends AbstractTestCase { private MessageStoreMediatorFactory factory; private MessageStoreMediatorSerializer serializer; public MessageStoreMediatorSerializationTest() { super(MessageStoreMediatorSerializationTest.class.getName()); factory = new MessageStoreMediatorFactory(); serializer = new MessageStoreMediatorSerializer(); } public void testStoreMediatorSerializationScenarioOne() throws Exception { String inputXml = "<store xmlns=\"http://ws.apache.org/ns/synapse\" " + "messageStore=\"foo\"/>"; assertTrue(serialization(inputXml, factory, serializer)); assertTrue(serialization(inputXml, serializer)); } public void testStoreMediatorSerializationScenarioTwo() throws Exception { String inputXml = "<store xmlns=\"http://ws.apache.org/ns/synapse\" " + "messageStore=\"foo\" sequence=\"bar\"/>"; assertTrue(serialization(inputXml, factory, serializer)); assertTrue(serialization(inputXml, serializer)); } }
{ "content_hash": "dd1833506d63a011904d7a8460e03a64", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 79, "avg_line_length": 39.58620689655172, "alnum_prop": 0.7099303135888502, "repo_name": "asanka88/apache-synapse", "id": "d8286ee92dd629a2924ef5e7b99cae202b1695f6", "size": "1971", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/core/src/test/java/org/apache/synapse/config/xml/MessageStoreMediatorSerializationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15679" }, { "name": "DIGITAL Command Language", "bytes": "2130" }, { "name": "Java", "bytes": "6727066" }, { "name": "JavaScript", "bytes": "2344" }, { "name": "Python", "bytes": "2513" }, { "name": "Ruby", "bytes": "1709" }, { "name": "Shell", "bytes": "33943" }, { "name": "XQuery", "bytes": "1159" }, { "name": "XSLT", "bytes": "23650" } ], "symlink_target": "" }
'use strict'; var L = require('leaflet'); var streets = L.tileLayer('https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}@2x.png?access_token=pk.eyJ1IjoibXNsZWUiLCJhIjoiclpiTWV5SSJ9.P_h8r37vD8jpIH1A6i1VRg', { attribution: '<a href="https://www.mapbox.com/about/maps">© Mapbox</a> <a href="http://openstreetmap.org/copyright">© OpenStreetMap</a> | <a href="http://mapbox.com/map-feedback/">Improve this map</a>', maxZoom : 19, maxNativeZoom: 18 }), outdoors = L.tileLayer('https://api.mapbox.com/v4/mapbox.outdoors/{z}/{x}/{y}@2x.png?access_token=pk.eyJ1IjoibXNsZWUiLCJhIjoiclpiTWV5SSJ9.P_h8r37vD8jpIH1A6i1VRg', { attribution: '<a href="https://www.mapbox.com/about/maps">© Mapbox</a> <a href="http://openstreetmap.org/copyright">© OpenStreetMap</a> | <a href="http://mapbox.com/map-feedback/">Improve this map</a>', maxZoom : 19, maxNativeZoom: 18 }), satellite = L.tileLayer('https://api.mapbox.com/v4/mapbox.streets-satellite/{z}/{x}/{y}@2x.png?access_token=pk.eyJ1IjoibXNsZWUiLCJhIjoiclpiTWV5SSJ9.P_h8r37vD8jpIH1A6i1VRg', { attribution: '<a href="https://www.mapbox.com/about/maps">© Mapbox</a> <a href="http://openstreetmap.org/copyright">© OpenStreetMap</a> | <a href="http://mapbox.com/map-feedback/">Improve this map</a>', maxZoom : 19, maxNativeZoom: 18 }), osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://www.openstreetmap.org/copyright/en">OpenStreetMap</a> contributors', maxZoom : 19 }), osm_de = L.tileLayer('http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png', { attribution: '© <a href="http://www.openstreetmap.org/copyright/en">OpenStreetMap</a> contributors', maxZoom : 19 }), small_components = L.tileLayer('http://tools.geofabrik.de/osmi/tiles/routing_i/{z}/{x}/{y}.png', {}) module.exports = { defaultState: { center: L.latLng(47.076899, 15.449245), zoom: 17, waypoints: [], language: 'de', alternative: 0, layer: osm }, services: [{ label: 'Wheelchair normal', path: 'http://gitlab.wheelroute.at:5000/route/v1' }], layer: [{ 'openstreetmap.org': osm, 'Mapbox Streets': streets, 'Mapbox Outdoors': outdoors, 'Mapbox Streets Satellite': satellite, 'openstreetmap.de.org': osm_de }], overlay: { 'Small Components': small_components }, baselayer: { one: osm, two: outdoors, three: satellite, four: streets, five: osm_de } };
{ "content_hash": "d507f9d037397feed56ed9ddd72b43c2", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 206, "avg_line_length": 41.36666666666667, "alnum_prop": 0.6603545527800161, "repo_name": "wheelroute/osrm-frontend-wheelchair-normal", "id": "bd0c1bc491c65840d43d7b99c8686b968b4a7ee2", "size": "2490", "binary": false, "copies": "1", "ref": "refs/heads/wheelchair-normal", "path": "src/leaflet_options.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "29645" }, { "name": "HTML", "bytes": "152580" }, { "name": "JavaScript", "bytes": "1436942" }, { "name": "Makefile", "bytes": "76" } ], "symlink_target": "" }
from math import sqrt from itertools import product def generate_primes(limit): is_prime = [True for i in range(limit)] for i in range(2, int(sqrt(limit))): if is_prime[i]: for j in range(i * i, limit, i): is_prime[j] = False return filter(lambda x: is_prime[x], range(2, limit)) primes = set(generate_primes(1000000)) def count_prime_w_replacement(num, digit): count = 0 for c in range(0, 10): tmp = num.replace(digit, str(c)) if tmp[0] <> '0' and int(tmp) in primes: count += 1 return count ans = 1000000 for p in primes: num = str(p) for c in range(0, 3): if num.count(str(c)) == 3 and count_prime_w_replacement(num, str(c)) > 7: ans = min(ans, p) print ans
{ "content_hash": "5391abe25f373a37bf73fb51ba159f30", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 75, "avg_line_length": 23.96551724137931, "alnum_prop": 0.6489208633093525, "repo_name": "cloudzfy/euler", "id": "3ffeb79f5f92ddcda567a9401bf625f42c4d2e06", "size": "1360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/51.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "162676" } ], "symlink_target": "" }
layout: docs title: Formats permalink: /docs/formats/ --- Quill supports a number of formats, both in UI controls and API calls. By default all formats are enabled and allowed to exist within a Quill editor and can be configured with the [formats](/docs/configuration/#formats) option. This is separate from adding a control in the [Toolbar](/docs/modules/toolbar/). For example, you can configure Quill to allow bolded content to be pasted into an editor that has no bold button in the toolbar. {% include standalone/full.html %} <a class="standalone-link" href="/standalone/full/">Standalone</a> #### Inline - Background Color - `background` - Bold - `bold` - Color - `color` - Font - `font` - Inline Code - `code` - Italic - `italic` - Link - `link` - Size - `size` - Strikethrough - `strike` - Superscript/Subscript - `script` - Underline - `underline` #### Block - Blockquote - `blockquote` - Header - `header` - Indent - `indent` - List - `list` - Text Alignment - `align` - Text Direction - `direction` - Code Block - `code-block` #### Embeds - Formula - `formula` - Image - `image` - Video - `video`
{ "content_hash": "7b7ee0d0fbb06597b5ea385b71d01f1a", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 366, "avg_line_length": 27.61904761904762, "alnum_prop": 0.6724137931034483, "repo_name": "voxmedia/quill", "id": "bd929dbd7bf3290ca88a7407609e07e3a9c45109", "size": "1164", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/docs/formats.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "309756" }, { "name": "Ruby", "bytes": "71" }, { "name": "Shell", "bytes": "2607" }, { "name": "Stylus", "bytes": "16153" } ], "symlink_target": "" }
namespace cart3 { // rotations along the primary axes Cart3d rotateX(float angle, Cart3d vec); Cart3d rotateY(float angle, Cart3d vec); Cart3d rotateZ(float angle, Cart3d vec); }; #endif // _math_rotate3d_h_
{ "content_hash": "e8e79a8be766d6c51fcde033d738dacd", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 40, "avg_line_length": 21.1, "alnum_prop": 0.7393364928909952, "repo_name": "kwan0xfff/fmtk", "id": "d01924f3d2e2b72e494816d4ac2a430931522c7c", "size": "516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/math/rotate3d.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2696" }, { "name": "C++", "bytes": "82281" }, { "name": "Makefile", "bytes": "9196" }, { "name": "Python", "bytes": "15557" }, { "name": "Shell", "bytes": "1232" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.aggregation; import com.facebook.presto.operator.UpdateMemory; import com.facebook.presto.spi.function.aggregation.Accumulator; import com.facebook.presto.spi.function.aggregation.GroupedAccumulator; import java.util.List; public interface AccumulatorFactory { List<Integer> getInputChannels(); Accumulator createAccumulator(UpdateMemory updateMemory); Accumulator createIntermediateAccumulator(); GroupedAccumulator createGroupedAccumulator(UpdateMemory updateMemory); GroupedAccumulator createGroupedIntermediateAccumulator(UpdateMemory updateMemory); boolean hasOrderBy(); boolean hasDistinct(); }
{ "content_hash": "e9237e83ae800a4d79a41f9faf0b2eab", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 87, "avg_line_length": 33.432432432432435, "alnum_prop": 0.7841552142279709, "repo_name": "prestodb/presto", "id": "299d7b3ae0488e0f4421642aecc1491d0ab12095", "size": "1237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "presto-main/src/main/java/com/facebook/presto/operator/aggregation/AccumulatorFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "33331" }, { "name": "Batchfile", "bytes": "795" }, { "name": "C++", "bytes": "640275" }, { "name": "CMake", "bytes": "31361" }, { "name": "CSS", "bytes": "28319" }, { "name": "Dockerfile", "bytes": "1266" }, { "name": "HTML", "bytes": "29601" }, { "name": "Java", "bytes": "52940440" }, { "name": "JavaScript", "bytes": "286864" }, { "name": "Makefile", "bytes": "16617" }, { "name": "Mustache", "bytes": "17803" }, { "name": "NASL", "bytes": "11965" }, { "name": "PLSQL", "bytes": "85" }, { "name": "Python", "bytes": "39357" }, { "name": "Roff", "bytes": "52281" }, { "name": "Shell", "bytes": "38937" }, { "name": "Thrift", "bytes": "14675" } ], "symlink_target": "" }
/** * EcoLearnia v0.0.1 * * @fileoverview * This file includes definition of ContentEditorView. * @deprecated use conenteditorpante-component instead * * @author Young Suk Ahn Park * @date 4/29/15 */ var AmpersandView = require ('ampersand-view'); //var React = require('react'); var React = require('react'); var lodash = require ('lodash'); var ContentItemEditorComponent = require ('./contentitemeditor-component.jsx').ContentItemEditorComponent; var ContentNodeEditorComponent = require ('./contentnodeeditor-component.jsx').ContentNodeEditorComponent; var internals = {}; internals.ContentEditorView = AmpersandView.extend({ // Not needed: template: '<div data-hook="content_editor" class="content-tree"></div>', initialize: function(options) { console.log("ContentEditorView options are:", options); this.app = options.app; this.siteBaseUrl = options.siteBaseUrl; }, render: function () { var content = this.model.toJSON(); var component; if (content.kind === 'Assignment') { component = React.createElement( ContentNodeEditorComponent, { app: this.app, content: content, siteBaseUrl: this.siteBaseUrl, onSaveContent: this.saveContent.bind(this) } ); } else { component = React.createElement( ContentItemEditorComponent, { app: this.app, content: content, siteBaseUrl: this.siteBaseUrl, onSaveContent: this.saveContent.bind(this) } ); } React.render(component, this.el); return this; }, saveContent: function(content) { var normalizedContent = lodash.cloneDeep(content); if (typeof normalizedContent.parent === 'object') { delete normalizedContent.parent; delete normalizedContent.__parentObject; } this.model.set(normalizedContent); this.model.save(normalizedContent, { success: function(result) { this.app.showMessage('Save', 'Successful'); }.bind(this), error: function(error) { this.app.showMessage('Save Error', JSON.stringify(error)); }.bind(this) }); } }); module.exports.ContentEditorView = internals.ContentEditorView;
{ "content_hash": "0cf3ff0d5f3d22c09b600c4a760459d1", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 106, "avg_line_length": 28.876404494382022, "alnum_prop": 0.5723735408560311, "repo_name": "altenia/repomigrated-ecolearnia-studio", "id": "4af1ea38fd3ee45aca2b0e89dcda25ff1adbabdf", "size": "2755", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "client/views/contenteditor-view.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "183655" }, { "name": "HTML", "bytes": "43817" }, { "name": "JavaScript", "bytes": "12098891" } ], "symlink_target": "" }
<html> <head> <script>document.write('<script src="an_sso.min.js?dev=' + Date.now() + '+' + Math.floor(Math.random() * 100) + '"\><\/script>');</script> </head> <body> <script>AsmodeeNet.trackCb(false);</script> <button id="connect_bt">Sign In</button> <div id="profile" style="display:none;"> <button id="disconnect_bt">Sign Out</button> - <button id="my_identity">My identity</button> </div> <br/> <div id="output"> </div> <script> function echo() { var output = ''; for(var i = 0; i < arguments.length; i++) { output += JSON.stringify(arguments[i], null, "\t") + "\n"; } findMe('output').innerHTML = '<pre>'+output+'</pre>'; } function findMe(id) { return document.getElementById(id); } function signed(identity) { echo(identity, AsmodeeNet.getAccessHash()); // console.log(jwt_decode(AsmodeeNet.getAccessToken())); findMe('connect_bt').style.display = 'none'; findMe('profile').style.display = 'block'; } function unsigned() { findMe('profile').style.display = 'none'; findMe('connect_bt').style.display = 'block'; echo("You're logged out"); } findMe('connect_bt').addEventListener('click', function() { AsmodeeNet.signIn({ // width: 475, // height: 500, success: signed, error: function() { echo("SIGNIN ERROR", arguments); } }); }); findMe('disconnect_bt').addEventListener('click', function() { AsmodeeNet.signOut({ success: unsigned }); }); findMe('my_identity').addEventListener('click', function() { AsmodeeNet.identity({ success: function(data) { echo("My Identity", arguments); } }); }); AsmodeeNet.init({ // Required parameters client_id: 'test_direct', //'openid-ffg', //'test_direct', //'openid-dow', redirect_uri: 'http://localhost:8080/cbpop.html', //'https://community-dev.fantasyflightgames.com/oauth/callback', // Example of optional parameters base_is_host: 'http://localhost:8009/', //https://account.asmodee.net', scope: 'openid+email+profile', response_type: 'code id_token token', display: 'popup', // display type: page touch popup iframe (page by default) display_options: { // noheader: true, // lnk2bt: true, // nofooter: true, // leglnk: false }, logout_redirect_uri: 'http://localhost:8080/cbpop.html?logout_redirect=1', // if next callback for RP logout openid's feature is not provided, the AsmodeeNet SSO lib, redirect the user to the root ('/') of the current host callback_post_logout_redirect: function() { alert('Disconnected'); window.location = '/'; }, callback_signin_success: signed, callback_signin_error: function() { echo("SIGNIN ERROR", arguments); } }).discover(); </script> </body> </html>
{ "content_hash": "8d2c8a466d61f6e1c0695e2b6d8ec19b", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 159, "avg_line_length": 38.527472527472526, "alnum_prop": 0.49914432401597264, "repo_name": "daysofwonder/asmodeenet_sso_js", "id": "0c4b527fa23667c0f5d4791bb1de429563416d03", "size": "3506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/index_popup.html", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "90593" }, { "name": "HTML", "bytes": "15400" }, { "name": "JavaScript", "bytes": "721287" }, { "name": "Shell", "bytes": "11393" } ], "symlink_target": "" }
module Text.ParserCombinators.Parsec.Pos ( SourceName, Line, Column , SourcePos , sourceLine, sourceColumn, sourceName , incSourceLine, incSourceColumn , setSourceLine, setSourceColumn, setSourceName , newPos, initialPos , updatePosChar, updatePosString ) where ----------------------------------------------------------- -- Source Positions, a file name, a line and a column. -- upper left is (1,1) ----------------------------------------------------------- type SourceName = String type Line = Int type Column = Int data SourcePos = SourcePos SourceName !Line !Column deriving (Eq,Ord) newPos :: SourceName -> Line -> Column -> SourcePos newPos sourceName line column = SourcePos sourceName line column initialPos sourceName = newPos sourceName 1 1 sourceName (SourcePos name line column) = name sourceLine (SourcePos name line column) = line sourceColumn (SourcePos name line column) = column incSourceLine (SourcePos name line column) n = SourcePos name (line+n) column incSourceColumn (SourcePos name line column) n = SourcePos name line (column+n) setSourceName (SourcePos name line column) n = SourcePos n line column setSourceLine (SourcePos name line column) n = SourcePos name n column setSourceColumn (SourcePos name line column) n = SourcePos name line n ----------------------------------------------------------- -- Update source positions on characters ----------------------------------------------------------- updatePosString :: SourcePos -> String -> SourcePos updatePosString pos string = forcePos (foldl updatePosChar pos string) updatePosChar :: SourcePos -> Char -> SourcePos updatePosChar pos@(SourcePos name line column) c = forcePos $ case c of '\n' -> SourcePos name (line+1) 1 '\t' -> SourcePos name line (column + 8 - ((column-1) `mod` 8)) _ -> SourcePos name line (column + 1) forcePos :: SourcePos -> SourcePos forcePos pos@(SourcePos name line column) = seq line (seq column (pos)) ----------------------------------------------------------- -- Show positions ----------------------------------------------------------- instance Show SourcePos where show (SourcePos name line column) | null name = showLineColumn | otherwise = "\"" ++ name ++ "\" " ++ showLineColumn where showLineColumn = "(line " ++ show line ++ ", column " ++ show column ++ ")"
{ "content_hash": "495d5b9fc5377f4e8b6932ed8ccd926e", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 108, "avg_line_length": 39.140845070422536, "alnum_prop": 0.5203310543360922, "repo_name": "OS2World/DEV-UTIL-HUGS", "id": "e8727708ee7e31056d9e832134e20ecb9915c45f", "size": "3234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libraries/Text/ParserCombinators/Parsec/Pos.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "2994497" }, { "name": "C#", "bytes": "15489" }, { "name": "C++", "bytes": "97958" }, { "name": "CSS", "bytes": "888" }, { "name": "Haskell", "bytes": "2947168" }, { "name": "Objective-C", "bytes": "120" }, { "name": "R", "bytes": "40181" }, { "name": "Shell", "bytes": "4947" }, { "name": "TeX", "bytes": "24329" } ], "symlink_target": "" }
package com.datatorrent.apps; import java.io.File; import java.util.Map; import org.apache.apex.malhar.lib.fs.FSRecordReaderModule; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import com.google.common.collect.Maps; import com.datatorrent.api.DAG; import com.datatorrent.api.StreamingApplication; import com.datatorrent.api.annotation.ApplicationAnnotation; import com.datatorrent.contrib.formatter.CsvFormatter; import com.datatorrent.contrib.kafka.KafkaSinglePortOutputOperator; import com.datatorrent.contrib.parser.CsvParser; import com.datatorrent.lib.transform.TransformOperator; @ApplicationAnnotation(name="HDFS-to-Kafka-Sync") public class Application implements StreamingApplication { @Override public void populateDAG(DAG dag, Configuration conf) { FSRecordReaderModule lineReader = dag.addModule("recordReader", FSRecordReaderModule.class); KafkaSinglePortOutputOperator<String,byte[]> kafkaOutput = dag.addOperator("kafkaOutput", new KafkaSinglePortOutputOperator<String,byte[]>()); dag.addStream("data", lineReader.records, kafkaOutput.inputPort); /* * To add custom logic to your DAG, add your custom operator here with * dag.addOperator api call and connect it in the dag using the dag.addStream * api call. * * For example: * * To parse incoming csv lines, transform them and outputting them on kafka. * recordReader->CSVParser->Transform->CSVFormatter->KafkaOutput can be achieved as follows * * Adding operators: * CsvParser csvParser = dag.addOperator("csvParser", CsvParser.class); * * TransformOperator transform = dag.addOperator("transform", new TransformOperator()); * Map<String, String> expMap = Maps.newHashMap(); * expMap.put("name", "{$.name}.toUpperCase()"); * transform.setExpressionMap(expMap); * CsvFormatter formatter = dag.addOperator("formatter", new CsvFormatter()); * * Use KafkaSinglePortOutputOperator<String,String> instead of * KafkaSinglePortOutputOperator<String,String> i.e. * * Replace the following line below * KafkaSinglePortOutputOperator<String,byte[]> kafkaOutput = * dag.addOperator("kafkaOutput", new KafkaSinglePortOutputOperator<String,byte[]>()); * * with these lines * KafkaSinglePortOutputOperator<String,String> kafkaOutput = * dag.addOperator("kafkaOutput", new KafkaSinglePortOutputOperator<String,String>()); * * Connect these operators with approriate streams * Replace the following line below * dag.addStream("data", lineReader.records, out.inputPort); * * with these lines * dag.addStream("record", lineReader.records, csvParser.in); * dag.addStream("pojo", csvParser.out, transform.input); * dag.addStream("transformed", transform.output, formatter.in); * dag.addStream("string", formatter.out, kafkaOutput.inputPort); * * In properties.xml, properties-test.xml->dt.operator.kafkaOutput.prop.producerProperties * Replace * serializer.class=kafka.serializer.DefaultEncoder * with * serializer.class=kafka.serializer.StringEncoder * * In ApplicationTests.java-> * Replace the following line below * FileUtils.readFileToString(new File("src/test/resources/test_events.txt")).split("\\n"); * with * FileUtils.readFileToString(new File("src/test/resources/test_events_transformed.txt")).split("\\n"); * */ } }
{ "content_hash": "5beb83696f40c68de056b1b5e8148745", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 107, "avg_line_length": 38.77173913043478, "alnum_prop": 0.7148864592094197, "repo_name": "yogidevendra/app-templates", "id": "da0df3d09fa2fa831bcebedf208acbf4a3b78b92", "size": "4375", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hdfs-to-kafka-sync/src/main/java/com/datatorrent/apps/Application.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "146892" }, { "name": "XSLT", "bytes": "31068" } ], "symlink_target": "" }
import operator from importlib import import_module def import_string(dotted_path): """ Source: django.utils.module_loading Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path raise ImportError(msg) module = import_module(module_path) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % ( module_path, class_name) raise ImportError(msg) def split_at_longest_importable_path(dotted_path): num_path_parts = len(dotted_path.split('.')) for i in range(1, num_path_parts): path_parts = dotted_path.rsplit('.', i) import_part = path_parts[0] remainder = '.'.join(path_parts[1:]) try: module = import_module(import_part) except ImportError: continue try: operator.attrgetter(remainder)(module) except AttributeError: raise ImportError( "Unable to derive appropriate import path for {0}".format( dotted_path, ) ) else: return import_part, remainder else: return '', dotted_path
{ "content_hash": "0c345d67abfabe9a6f0408f1e9db3f7f", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 80, "avg_line_length": 28.576923076923077, "alnum_prop": 0.5915208613728129, "repo_name": "euri10/populus", "id": "4fad110098c30ef0e493161949fb1f7a5096c66a", "size": "1486", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "populus/utils/module_loading.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "275" }, { "name": "Makefile", "bytes": "1204" }, { "name": "Python", "bytes": "387929" }, { "name": "Shell", "bytes": "1937" } ], "symlink_target": "" }
This is my personal site including my blog. I hope you find it useful. ## Local Setup Get the Code: $ git clone https://github.com/jrmyward/blog.git $ cd blog Setup the Application $ bundle install $ cp config/application.yml.example config/application.yml You'll want to generate a new APP_SECRET_TOKEN to place in <code>config/application.yml</code>. $ rake secret
{ "content_hash": "2a4751976abf804f834197c2f81043ad", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 95, "avg_line_length": 20.789473684210527, "alnum_prop": 0.7164556962025317, "repo_name": "jrmyward/blog", "id": "39c75af25e0525f041bd64d976ea8a08d3314f63", "size": "420", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7851" }, { "name": "CoffeeScript", "bytes": "753" }, { "name": "HTML", "bytes": "7745" }, { "name": "JavaScript", "bytes": "5229" }, { "name": "Ruby", "bytes": "167563" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Framework\Application\UtilitiesV2; /** * Class OpenSSL * @package Framework\Application\UtilitiesV2 */ class OpenSSL { protected $cipher; /** * OpenSSL constructor. * * @param string $cipher * * @throws \Error */ public function __construct($cipher = "AES-128-CBC") { if ($this->check($cipher) == false) throw new \Error("Cipher invalid"); $this->cipher = $cipher; } /** * @param array $json * @param $key * @param $iv * @param bool $add_decrypt_info * * @return array */ public function encrypt(array $json, $key, $iv, $add_decrypt_info = true) { $array = []; foreach ($json as $index => $value) { $array[$this->encryptText($index, $key, $iv)] = $this->encryptText($value, $key, $iv); } if ($add_decrypt_info) $array["info"] = [ "key" => $key, "iv" => base64_encode($iv) ]; return $array; } /** * @param array $json * @param $key * @param $iv * * @return array */ public function decrypt(array $json, $key, $iv) { $array = []; foreach ($json as $index => $value) { if ($index == "info") continue; $array[$this->decryptText($index, $key, $iv)] = $this->decryptText($value, $key, $iv); } return $array; } /** * @param string $text * @param string $key * @param $iv * * @return string */ private function encryptText(string $text, string $key, $iv) { return (openssl_encrypt($text, $this->cipher, $key, $options = 0, $iv)); } /** * @param string $text * @param string $key * @param $iv * * @return string */ private function decryptText(string $text, string $key, $iv) { return (openssl_decrypt($text, $this->cipher, $key, OPENSSL_RAW_DATA, $iv)); } /** * @return string */ public function iv() { return (openssl_random_pseudo_bytes($this->getLength())); } /** * @return int */ private function getLength() { return (openssl_cipher_iv_length($this->cipher)); } /** * @return string */ public function generateKey() { return (base64_encode(openssl_random_pseudo_bytes(32))); } /** * @param $cipher * * @return bool */ private function check($cipher) { if (in_array($cipher, openssl_get_cipher_methods())) return true; return false; } }
{ "content_hash": "072965b510166a365970b5053ce1e6d0", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 90, "avg_line_length": 15.16875, "alnum_prop": 0.5562422744128553, "repo_name": "dialtoneuk/Syscrack2017", "id": "7e9b695ee3e0811cd65b52d8b8ea0c617ed29444", "size": "2427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Application/UtilitiesV2/OpenSSL.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "414164" }, { "name": "JavaScript", "bytes": "91735" }, { "name": "PHP", "bytes": "989042" } ], "symlink_target": "" }