text stringlengths 2 1.04M | meta dict |
|---|---|
package poller
import (
"context"
"fmt"
"testing"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"go.skia.org/infra/go/gerrit"
"go.skia.org/infra/go/httputils"
"go.skia.org/infra/go/testutils"
caches_mocks "go.skia.org/infra/skcq/go/caches/mocks"
cr_mocks "go.skia.org/infra/skcq/go/codereview/mocks"
"go.skia.org/infra/skcq/go/config"
cfg_mocks "go.skia.org/infra/skcq/go/config/mocks"
"go.skia.org/infra/skcq/go/db"
db_mocks "go.skia.org/infra/skcq/go/db/mocks"
"go.skia.org/infra/skcq/go/types"
types_mocks "go.skia.org/infra/skcq/go/types/mocks"
)
func testProcessCL(t *testing.T, testVerifierStatuses []*types.VerifierStatus, expectedOverallState types.VerifierState, dryRun bool) {
currentChangesCache := map[string]*types.CurrentlyProcessingChange{}
httpClient := httputils.NewTimeoutClient()
publicFEInstanceURL := "https://public-fe-url/"
corpFEInstanceURL := "https://corp-fe-url/"
ci := &gerrit.ChangeInfo{
Issue: int64(123),
Status: gerrit.ChangeStatusOpen,
Subject: "Test change",
Owner: &gerrit.Person{
Email: "batman@gotham.com",
},
Project: "skia",
Branch: "main",
}
clsInThisRound := map[string]bool{}
startTime := int64(111)
changePatchsetID := "123/5"
// Mock db.
dbClient := &db_mocks.DB{}
dbClient.On("PutChangeAttempt", testutils.AnyContext, mock.AnythingOfType("*types.ChangeAttempt"), db.GetChangesCol(false)).Return(nil).Once()
// Mock current changes cache.
cc := &caches_mocks.CurrentChangesCache{}
cc.On("Get", testutils.AnyContext, dbClient).Return(currentChangesCache).Once()
cc.On("Add", testutils.AnyContext, changePatchsetID, ci.Subject, "batman@gotham.com", ci.Project, ci.Branch, dryRun, false, ci.Issue, int64(5)).Return(startTime, false, nil).Once()
cc.On("Remove", testutils.AnyContext, changePatchsetID).Return(nil).Once()
// Mock cfg reader.
skcfg := &config.SkCQCfg{}
cfgReader := &cfg_mocks.ConfigReader{}
cfgReader.On("GetSkCQCfg", testutils.AnyContext).Return(skcfg, nil).Once()
// Mock codereview.
cr := &cr_mocks.CodeReview{}
cr.On("IsDryRun", testutils.AnyContext, ci).Return(dryRun).Once()
cr.On("IsCQ", testutils.AnyContext, ci).Return(!dryRun)
cr.On("GetEarliestEquivalentPatchSetID", ci).Return(int64(5)).Once()
cr.On("GetLatestPatchSetID", ci).Return(int64(5)).Twice()
if expectedOverallState != types.VerifierWaitingState {
cr.On("RemoveFromCQ", testutils.AnyContext, ci, mock.AnythingOfType("string"), mock.AnythingOfType("string")).Once()
}
if !dryRun && expectedOverallState == types.VerifierSuccessState {
cr.On("Submit", testutils.AnyContext, ci).Return(nil).Once()
}
// Mock verifier manager.
vm := &types_mocks.VerifiersManager{}
vm.On("GetVerifiers", testutils.AnyContext, skcfg, ci, false, cfgReader).Return([]types.Verifier{}, []string{}, nil).Once()
vm.On("RunVerifiers", testutils.AnyContext, ci, []types.Verifier{}, startTime).Return(testVerifierStatuses).Once()
// Mock throttler maanger.
tm := &types_mocks.ThrottlerManager{}
tm.On("UpdateThrottler", "skia/main", mock.AnythingOfType("time.Time"), skcfg.ThrottlerCfg).Once()
processCL(context.Background(), vm, ci, cfgReader, clsInThisRound, cr, cc, httpClient, dbClient, nil, publicFEInstanceURL, corpFEInstanceURL, tm)
}
func TestProcessCL_DryRun_FailureOverallState(t *testing.T) {
testVerifierStatuses := []*types.VerifierStatus{
{State: types.VerifierSuccessState, Name: "Verifier1", Reason: "Reason1"},
{State: types.VerifierFailureState, Name: "Verifier2", Reason: "Reason2"},
{State: types.VerifierWaitingState, Name: "Verifier3", Reason: "Reason3"},
}
testProcessCL(t, testVerifierStatuses, types.VerifierFailureState, true)
}
func TestProcessCL_DryRun_SuccessOverallState(t *testing.T) {
testVerifierStatuses := []*types.VerifierStatus{
{State: types.VerifierSuccessState, Name: "Verifier1", Reason: "Reason1"},
{State: types.VerifierSuccessState, Name: "Verifier2", Reason: "Reason2"},
}
testProcessCL(t, testVerifierStatuses, types.VerifierSuccessState, true)
}
func TestProcessCL_DryRun_WaitingOverallState(t *testing.T) {
testVerifierStatuses := []*types.VerifierStatus{
{State: types.VerifierSuccessState, Name: "Verifier1", Reason: "Reason1"},
{State: types.VerifierWaitingState, Name: "Verifier2", Reason: "Reason2"},
{State: types.VerifierSuccessState, Name: "Verifier3", Reason: "Reason3"},
}
testProcessCL(t, testVerifierStatuses, types.VerifierSuccessState, true)
}
func TestProcessCL_CQRun_FailureOverallState(t *testing.T) {
testVerifierStatuses := []*types.VerifierStatus{
{State: types.VerifierSuccessState, Name: "Verifier1", Reason: "Reason1"},
{State: types.VerifierFailureState, Name: "Verifier2", Reason: "Reason2"},
{State: types.VerifierWaitingState, Name: "Verifier3", Reason: "Reason3"},
}
testProcessCL(t, testVerifierStatuses, types.VerifierFailureState, false)
}
func TestProcessCL_CQRun_WaitingOverallState(t *testing.T) {
testVerifierStatuses := []*types.VerifierStatus{
{State: types.VerifierSuccessState, Name: "Verifier1", Reason: "Reason1"},
{State: types.VerifierWaitingState, Name: "Verifier2", Reason: "Reason2"},
}
testProcessCL(t, testVerifierStatuses, types.VerifierWaitingState, false)
}
func TestProcessCL_CQRun_SuccessOverallState(t *testing.T) {
testVerifierStatuses := []*types.VerifierStatus{
{State: types.VerifierSuccessState, Name: "Verifier1", Reason: "Reason1"},
{State: types.VerifierSuccessState, Name: "Verifier2", Reason: "Reason2"},
}
testProcessCL(t, testVerifierStatuses, types.VerifierSuccessState, false)
}
func TestCleanupCL(t *testing.T) {
changeID := int64(123)
equivalentPatchsetID := int64(5)
changePatchsetID := fmt.Sprintf("%d/%d", changeID, equivalentPatchsetID)
latestPatchsetID := int64(7)
httpClient := httputils.NewTimeoutClient()
ci := &gerrit.ChangeInfo{
Issue: int64(123),
}
startTime := int64(444)
cqRecord := &types.CurrentlyProcessingChange{
ChangeID: int64(123),
LatestPatchsetID: latestPatchsetID,
StartTs: startTime,
}
// Mock current changes cache.
cc := &caches_mocks.CurrentChangesCache{}
cc.On("Remove", testutils.AnyContext, changePatchsetID).Return(nil).Once()
// Mock db.
dbClient := &db_mocks.DB{}
dbClient.On("UpdateChangeAttemptAsAbandoned", testutils.AnyContext, changeID, latestPatchsetID, db.GetChangesCol(false), startTime).Return(nil).Once()
// Mock cfg reader.
skcfg := &config.SkCQCfg{}
cfgReader := &cfg_mocks.ConfigReader{}
cfgReader.On("GetSkCQCfg", testutils.AnyContext).Return(skcfg, nil).Once()
// Mock codereview.
cr := &cr_mocks.CodeReview{}
// Mock 2 verifiers.
v1 := &types_mocks.Verifier{}
v1.On("Cleanup", testutils.AnyContext, ci, equivalentPatchsetID)
v2 := &types_mocks.Verifier{}
v2.On("Cleanup", testutils.AnyContext, ci, equivalentPatchsetID)
// Mock verifier manager.
vm := &types_mocks.VerifiersManager{}
vm.On("GetVerifiers", testutils.AnyContext, skcfg, ci, false, cfgReader).Return([]types.Verifier{v1, v2}, []string{}, nil).Once()
err := cleanupCL(context.Background(), changePatchsetID, cc, dbClient, cqRecord, ci, cfgReader, cr, httpClient, vm)
require.Nil(t, err)
}
| {
"content_hash": "f7e875b4619d59edc5306f63a878a08a",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 181,
"avg_line_length": 38.70810810810811,
"alnum_prop": 0.7380254154447703,
"repo_name": "google/skia-buildbot",
"id": "fce479032cbdb84f5cf3dfa686c3fcf7af4ca96c",
"size": "7161",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "skcq/go/poller/poller_test.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "736"
},
{
"name": "C",
"bytes": "3114"
},
{
"name": "C++",
"bytes": "18072"
},
{
"name": "CSS",
"bytes": "13967"
},
{
"name": "Dockerfile",
"bytes": "18546"
},
{
"name": "Go",
"bytes": "8744467"
},
{
"name": "HTML",
"bytes": "790880"
},
{
"name": "JavaScript",
"bytes": "1186449"
},
{
"name": "Jupyter Notebook",
"bytes": "9165"
},
{
"name": "Makefile",
"bytes": "75823"
},
{
"name": "PowerShell",
"bytes": "15305"
},
{
"name": "Python",
"bytes": "126773"
},
{
"name": "SCSS",
"bytes": "128048"
},
{
"name": "Shell",
"bytes": "232449"
},
{
"name": "Starlark",
"bytes": "234929"
},
{
"name": "TypeScript",
"bytes": "1568540"
}
],
"symlink_target": ""
} |
require 'corba'
CORBA.implement('Test.idl', {}, CORBA::IDL::CLIENT_STUB) {
module Types
class TString < String
def TString._tc; @@tc_TString ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Types/TString:1.0', 'TString', self, CORBA::_tc_string); end
end # typedef TString
end #of module Types
module Test
module Hello; end ## interface forward
Max_longlong = 9223372036854775807
Min_longlong = -9223372036854775808
Max_ulonglong = 18446744073709551615
Min_ulonglong = 0
Max_long = 2147483647
Min_long = -2147483648
Max_ulong = 4294967295
Min_ulong = 0
Max_short = 32767
Min_short = -32768
Max_ushort = 65535
Min_ushort = 0
Max_octet = 255
Min_octet = 0
class TShort < CORBA::_tc_short.get_type
def TShort._tc; @@tc_TShort ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TShort:1.0', 'TShort', self, CORBA::_tc_short); end
end # typedef TShort
class TULong < CORBA::_tc_ulong.get_type
def TULong._tc; @@tc_TULong ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TULong:1.0', 'TULong', self, CORBA::_tc_ulong); end
end # typedef TULong
class TString < String
def TString._tc; @@tc_TString ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TString:1.0', 'TString', self, CORBA::_tc_string); end
end # typedef TString
class TString2 < Test::TString
def TString2._tc; @@tc_TString2 ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TString2:1.0', 'TString2', self,Test::TString._tc); end
end # typedef TString2
class TString3 < Types::TString
def TString3._tc; @@tc_TString3 ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TString3:1.0', 'TString3', self,Types::TString._tc); end
end # typedef TString3
class TString128 < String
def TString128._tc; @@tc_TString128 ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TString128:1.0', 'TString128', self, CORBA::TypeCode::String.new(128)); end
end # typedef TString128
class TMyAny < CORBA::_tc_any.get_type
def TMyAny._tc; @@tc_TMyAny ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TMyAny:1.0', 'TMyAny', self, CORBA::_tc_any); end
end # typedef TMyAny
class TStringSeq < CORBA::StringSeq
def TStringSeq._tc; @@tc_TStringSeq ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TStringSeq:1.0', 'TStringSeq', self,CORBA::StringSeq._tc); end
end # typedef TStringSeq
MyConst = 32
MyOctet = 243
MyChar = 'A'
MyWChar = 97
MyString = 'ABC'
MyWString = [97,98,99,4660]
DIM1 = 3
class TLongCube < Array
def TLongCube._tc
@@tc_TLongCube ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TLongCube:1.0', 'TLongCube', self,
CORBA::TypeCode::Array.new(CORBA._tc_long, 3, 3, 4))
end
end # typedef TLongCube
class Test_enum < ::Fixnum
def Test_enum._tc
@@tc_Test_enum ||= CORBA::TypeCode::Enum.new('IDL:Remedy/Test/test_enum:1.0'.freeze, 'Test_enum', [
'TE_ZEROTH',
'TE_FIRST',
'TE_SECOND',
'TE_THIRD',
'TE_FOURTH'])
end
self._tc # register typecode
end # enum Test_enum
TE_ZEROTH = 0
TE_FIRST = 1
TE_SECOND = 2
TE_THIRD = 3
TE_FOURTH = 4
class S1 < CORBA::Portable::Struct
class S2 < CORBA::Portable::Struct
def S2._tc
@@tc_S2 ||= CORBA::TypeCode::Struct.new('IDL:Remedy/Test/S1/S2:1.0'.freeze, 'S2', self,
[['m_b', CORBA._tc_boolean]])
end
self._tc # register typecode
attr_accessor :m_b
def initialize(*param_)
@m_b = param_
end
end #of struct S2
def S1._tc
@@tc_S1 ||= CORBA::TypeCode::Struct.new('IDL:Remedy/Test/S1:1.0'.freeze, 'S1', self,
[['m_one', CORBA._tc_long],
['m_two', CORBA._tc_double],
['m_three', CORBA._tc_string],
['m_four', Test::S1::S2._tc],
['m_five', Test::Test_enum._tc]])
end
self._tc # register typecode
attr_accessor :m_one
attr_accessor :m_two
attr_accessor :m_three
attr_accessor :m_four
attr_accessor :m_five
def initialize(*param_)
@m_one,
@m_two,
@m_three,
@m_four,
@m_five = param_
end
end #of struct S1
class TS3Seq < Array
def TS3Seq._tc
@@tc_TS3Seq ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TS3Seq:1.0', 'TS3Seq', self,
CORBA::TypeCode::Sequence.new(CORBA::TypeCode::Recursive.new('IDL:Remedy/Test/S3:1.0')))
end
end # typedef TS3Seq
class TS3SeqSeq < Array
def TS3SeqSeq._tc
@@tc_TS3SeqSeq ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TS3SeqSeq:1.0', 'TS3SeqSeq', self,
CORBA::TypeCode::Sequence.new(Test::TS3Seq._tc).freeze)
end
end # typedef TS3SeqSeq
class S3 < CORBA::Portable::Struct
def S3._tc
@@tc_S3 ||= CORBA::TypeCode::Struct.new('IDL:Remedy/Test/S3:1.0'.freeze, 'S3', self,
[['m_seq', Test::TS3Seq._tc],
['m_has_more', CORBA._tc_boolean]])
end
self._tc # register typecode
attr_accessor :m_seq
attr_accessor :m_has_more
def initialize(*param_)
@m_seq,
@m_has_more = param_
end
end #of struct S3
class S1Seq < Array
def S1Seq._tc
@@tc_S1Seq ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/S1Seq:1.0', 'S1Seq', self,
CORBA::TypeCode::Sequence.new(Test::S1._tc).freeze)
end
end # typedef S1Seq
class TShortSeq < Array
def TShortSeq._tc
@@tc_TShortSeq ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TShortSeq:1.0', 'TShortSeq', self,
CORBA::TypeCode::Sequence.new(Test::TShort._tc, 10).freeze)
end
end # typedef TShortSeq
class TSWitch < Test::Test_enum
def TSWitch._tc; @@tc_TSWitch ||= CORBA::TypeCode::Alias.new('IDL:Remedy/Test/TSWitch:1.0', 'TSWitch', self,Test::Test_enum._tc); end
end # typedef TSWitch
class U1 < CORBA::Portable::Union
def U1._tc
@@tc_U1 ||= CORBA::TypeCode::Union.new('IDL:Remedy/Test/U1:1.0'.freeze, 'U1', self,
Test::TSWitch._tc,
[[Test::TE_ZEROTH, 'm_l', CORBA._tc_long],
[Test::TE_FIRST, 'm_str', CORBA._tc_string],
[Test::TE_SECOND, 'm_str', CORBA._tc_string],
[:default, 'm_bool', CORBA._tc_boolean]])
end
self._tc # register typecode
def m_l; @value; end
def m_l=(val); _set_value(0, val); end
def m_str; @value; end
def m_str=(val); _set_value(1, val); end
def m_bool; @value; end
def m_bool=(val); _set_value(3, val); end
end #of union U1
module Hello ## interface
Id = 'IDL:Remedy/Test/Hello:1.0'.freeze
Ids = [ Id ].freeze
def Hello._tc; @@tc_Hello ||= CORBA::TypeCode::ObjectRef.new(Id, 'Hello', self); end
self._tc # register typecode
def Hello._narrow(obj)
return CORBA::Stub.create_stub(obj)._narrow!(self)
end
def Hello._duplicate(obj)
return CORBA::Stub.create_stub(super(obj))._narrow!(self)
end
def _interface_repository_id
self.class::Id
end
def max_LongLong()
_ret = self._invoke('_get_Max_LongLong', {
:result_type => CORBA._tc_longlong})
_ret
end #of attribute get_Max_LongLong
def min_LongLong()
_ret = self._invoke('_get_Min_LongLong', {
:result_type => CORBA._tc_longlong})
_ret
end #of attribute get_Min_LongLong
def max_ULongLong()
_ret = self._invoke('_get_Max_ULongLong', {
:result_type => CORBA._tc_ulonglong})
_ret
end #of attribute get_Max_ULongLong
def min_ULongLong()
_ret = self._invoke('_get_Min_ULongLong', {
:result_type => CORBA._tc_ulonglong})
_ret
end #of attribute get_Min_ULongLong
def max_Long()
_ret = self._invoke('_get_Max_Long', {
:result_type => CORBA._tc_long})
_ret
end #of attribute get_Max_Long
def min_Long()
_ret = self._invoke('_get_Min_Long', {
:result_type => CORBA._tc_long})
_ret
end #of attribute get_Min_Long
def max_ULong()
_ret = self._invoke('_get_Max_ULong', {
:result_type => CORBA._tc_ulong})
_ret
end #of attribute get_Max_ULong
def min_ULong()
_ret = self._invoke('_get_Min_ULong', {
:result_type => CORBA._tc_ulong})
_ret
end #of attribute get_Min_ULong
def max_Short()
_ret = self._invoke('_get_Max_Short', {
:result_type => CORBA._tc_short})
_ret
end #of attribute get_Max_Short
def min_Short()
_ret = self._invoke('_get_Min_Short', {
:result_type => CORBA._tc_short})
_ret
end #of attribute get_Min_Short
def max_UShort()
_ret = self._invoke('_get_Max_UShort', {
:result_type => CORBA._tc_ushort})
_ret
end #of attribute get_Max_UShort
def min_UShort()
_ret = self._invoke('_get_Min_UShort', {
:result_type => CORBA._tc_ushort})
_ret
end #of attribute get_Min_UShort
def max_Octet()
_ret = self._invoke('_get_Max_Octet', {
:result_type => CORBA._tc_octet})
_ret
end #of attribute get_Max_Octet
def min_Octet()
_ret = self._invoke('_get_Min_Octet', {
:result_type => CORBA._tc_octet})
_ret
end #of attribute get_Min_Octet
def get_string()
_ret = self._invoke('get_string', {
:result_type => Test::TString2._tc})
_ret
end #of operation get_string
def message()
_ret = self._invoke('_get_Message', {
:result_type => Test::TString3._tc})
_ret
end #of attribute get_Message
def message=(val)
val = Test::TString3._tc.validate(val)
self._invoke('_set_Message', {
:arg_list => [
['val', CORBA::ARG_IN, Test::TString3._tc, val]],
:result_type => CORBA._tc_void})
end #of attribute set_Message
def numbers()
_ret = self._invoke('_get_Numbers', {
:result_type => Test::TShortSeq._tc})
_ret
end #of attribute get_Numbers
def numbers=(val)
val = Test::TShortSeq._tc.validate(val)
self._invoke('_set_Numbers', {
:arg_list => [
['val', CORBA::ARG_IN, Test::TShortSeq._tc, val]],
:result_type => CORBA._tc_void})
end #of attribute set_Numbers
def structSeq()
_ret = self._invoke('_get_StructSeq', {
:result_type => Test::S1Seq._tc})
_ret
end #of attribute get_StructSeq
def structSeq=(val)
val = Test::S1Seq._tc.validate(val)
self._invoke('_set_StructSeq', {
:arg_list => [
['val', CORBA::ARG_IN, Test::S1Seq._tc, val]],
:result_type => CORBA._tc_void})
end #of attribute set_StructSeq
def theCube()
_ret = self._invoke('_get_theCube', {
:result_type => Test::TLongCube._tc})
_ret
end #of attribute get_theCube
def theCube=(val)
val = Test::TLongCube._tc.validate(val)
self._invoke('_set_theCube', {
:arg_list => [
['val', CORBA::ARG_IN, Test::TLongCube._tc, val]],
:result_type => CORBA._tc_void})
end #of attribute set_theCube
def anyValue()
_ret = self._invoke('_get_AnyValue', {
:result_type => CORBA._tc_any})
_ret
end #of attribute get_AnyValue
def anyValue=(val)
val = CORBA._tc_any.validate(val)
self._invoke('_set_AnyValue', {
:arg_list => [
['val', CORBA::ARG_IN, CORBA._tc_any, val]],
:result_type => CORBA._tc_void})
end #of attribute set_AnyValue
def selfref()
_ret = self._invoke('_get_selfref', {
:result_type => Test::Hello._tc})
_ret
end #of attribute get_selfref
def s3Value()
_ret = self._invoke('_get_S3Value', {
:result_type => CORBA._tc_any})
_ret
end #of attribute get_S3Value
def s3Value=(val)
val = CORBA._tc_any.validate(val)
self._invoke('_set_S3Value', {
:arg_list => [
['val', CORBA::ARG_IN, CORBA._tc_any, val]],
:result_type => CORBA._tc_void})
end #of attribute set_S3Value
def unionValue()
_ret = self._invoke('_get_UnionValue', {
:result_type => Test::U1._tc})
_ret
end #of attribute get_UnionValue
def unionValue=(val)
val = Test::U1._tc.validate(val)
self._invoke('_set_UnionValue', {
:arg_list => [
['val', CORBA::ARG_IN, Test::U1._tc, val]],
:result_type => CORBA._tc_void})
end #of attribute set_UnionValue
def run_test(instr, inoutstr)
instr = Test::TString._tc.validate(instr)
inoutstr = CORBA._tc_string.validate(inoutstr)
_ret = self._invoke('run_test', {
:arg_list => [
['instr', CORBA::ARG_IN, Test::TString._tc, instr],
['inoutstr', CORBA::ARG_INOUT, CORBA._tc_string, inoutstr],
['outstr', CORBA::ARG_OUT, CORBA._tc_string]],
:result_type => CORBA._tc_long})
_ret
end #of operation run_test
def shutdown() # oneway
self._invoke('shutdown', {})
end #of operation shutdown
end #of interface Hello
end #of module Test
} ## end of 'Test.idl'
# -*- END -*-
| {
"content_hash": "a903d9be7b14b4da09f0dd144696315f",
"timestamp": "",
"source": "github",
"line_count": 414,
"max_line_length": 163,
"avg_line_length": 31.241545893719806,
"alnum_prop": 0.5881397866089377,
"repo_name": "noda50/RubyItk",
"id": "dcae632a9da4f5886e10c2b59fbf3ff930fb36b3",
"size": "13163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ruby2CORBA/test/Param_Test/TestC.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "6287"
},
{
"name": "C++",
"bytes": "199329"
},
{
"name": "Gnuplot",
"bytes": "255"
},
{
"name": "HTML",
"bytes": "606"
},
{
"name": "Makefile",
"bytes": "477"
},
{
"name": "Ruby",
"bytes": "1395000"
},
{
"name": "Shell",
"bytes": "3113"
}
],
"symlink_target": ""
} |
module Pohoda
module Builders
module Typ
class ClassificationVATType
include ParserCore::BaseBuilder
def builder
root = Ox::Element.new(name)
root = add_attributes_and_namespaces(root)
root << build_element('typ:id', data[:id], data[:id_attributes]) if data.key? :id
root << build_element('typ:ids', data[:ids], data[:ids_attributes]) if data.key? :ids
root << build_element('typ:classificationVATType', data[:classification_vat_type], data[:classification_vat_type_attributes]) if data.key? :classification_vat_type
root
end
end
end
end
end | {
"content_hash": "880724fcc80fadf5f6c95997ac8fbd42",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 173,
"avg_line_length": 32.6,
"alnum_prop": 0.6349693251533742,
"repo_name": "Masa331/pohoda",
"id": "1ff7d4fb4869cf83983999f59e65526c56808536",
"size": "652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/pohoda/builders/typ/classification_vat_type.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "1162589"
},
{
"name": "Shell",
"bytes": "776"
}
],
"symlink_target": ""
} |
When contributing to this repository, please first discuss the change you wish to make via issue before making a change.
Please note there is a [code of conduct](CODE_OF_CONDUCT.md), please follow it in all your interactions with the project.
## Reporting Issues and Asking Questions
Before opening an issue, please search the [issue tracker](https://github.com/soen/Conjunction/issues) to make sure your issue hasn't already been reported.
## Development
Visit the [issue tracker](https://github.com/soen/Conjunction/issues) to find a list of open issues that need attention.
Fork, then clone the repo:
```
git clone https://github.com/your-username/conjunction.git
```
### Unicorn
The project uses [Unicorn](https://github.com/kamsar/Unicorn) to serialize Sitecore items related to Conjunction, i.e template items, settings etc.
In order to use Unicorn you need to do the following:
1. Publish the Conjunction.Foundation.Content project, using a custom file system publish profile, to your local Sitecore instance
2. Copy the ``Unicorn.CustomSerializationFolder.config.example`` file from the ``App_Config/Include/Unicorn`` folder to the ``App_Config/Include/z_Developer`` folder
3. Rename the copied file to remove the ``.example`` extension
4. Edit the file to point at the serialization folder beneath your working folder
5. Run ``http://<yoursite>/unicorn.aspx`` and sync everything
### Tests
Tests are located in the ``*.Tests`` projects and are using [xUnit.net](https://xunit.github.io/). By default, the test projects use [Visual Studio runner](https://github.com/xunit/visualstudio.xunit) to run the tests.
### Docs
Improvements to the documentation are always welcome. In the docs we abide by typographic rules, so instead of ' you should use '. Same goes for “ ” and dashes (—) where appropriate. These rules only apply to the text, not to code blocks.
#### Installing Gitbook
To install the latest version of `gitbook` and prepare to build the documentation, run the following:
```
npm run docs:prepare
```
#### Building the Docs
To build the documentation, run the following:
```
npm run docs:build
```
To watch and rebuild documentation when changes occur, run the following:
```
npm run docs:watch
```
The docs will be served at [http://localhost:4000](http://localhost:4000).
#### Publishing the Docs
To publish the documentation, run the following:
```
npm run docs:publish
```
### Sending a Pull Request
In general, the contribution workflow looks like this:
* Open a new issue in the [issue tracker](https://github.com/soen/Conjunction/issues).
* Fork the repo.
* Create a new feature branch based off the master branch.
* Make sure all tests pass.
* Submit a pull request, referencing any issues it addresses.
Please try to keep your pull request focused in scope and avoid including unrelated commits.
After you have submitted your pull request, I'll get back to you as soon as possible.
Thank you for contributing! | {
"content_hash": "289d445c432c5024409547d099c4058d",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 238,
"avg_line_length": 34.976470588235294,
"alnum_prop": 0.7588294651866802,
"repo_name": "soen/Conjunction",
"id": "008b942d1b44b6e9495379d3975469a084e3123a",
"size": "2995",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CONTRIBUTING.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "116"
},
{
"name": "C#",
"bytes": "146080"
},
{
"name": "PowerShell",
"bytes": "773"
}
],
"symlink_target": ""
} |
var _ = require('lodash');
var he = require('he');
_.str = require('underscore.string');
var XRegExp = require('xregexp').XRegExp;
var crypto = require('crypto');
var cuid = require('cuid');
var fs = require('fs');
module.exports = function(self, options) {
// generate a unique identifier for a new page or other object.
// IDs are generated with the cuid module which prevents
// collisions and easy guessing of another's ID.
self.generateId = function() {
return cuid();
};
// Globally replace a string with another string.
// Regular `String.replace` does NOT offer global replace, except
// when using regular expressions, which are great but
// problematic when UTF8 characters may be present.
self.globalReplace = function(haystack, needle, replacement) {
var result = '';
while (true) {
if (!haystack.length) {
return result;
}
var index = haystack.indexOf(needle);
if (index === -1) {
result += haystack;
return result;
}
result += haystack.substr(0, index);
result += replacement;
haystack = haystack.substr(index + needle.length);
}
};
// Truncate a plaintext string at the specified number of
// characters without breaking words if possible, see
// underscore.string's prune function, of which this is
// a copy (but replacing RegExp with XRegExp for
// better UTF-8 support)
//
self.truncatePlaintext = function(str, length, pruneStr){
if (str == null) return '';
str = String(str); length = ~~length;
pruneStr = pruneStr != null ? String(pruneStr) : '...';
if (str.length <= length) return str;
var r = '.(?=\W*\w*$)';
var regex = new XRegExp(r, 'g');
var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
template = str.slice(0, length+1);
template = XRegExp.replace(template, regex, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
if (template.slice(template.length-2).match(/\w\w/))
template = template.replace(/\s*\S+$/, '');
else
template = _.str.rtrim(template.slice(0, template.length-1));
return (template+pruneStr).length > str.length ? str : str.slice(0, template.length)+pruneStr;
};
// Escape a plaintext string correctly for use in HTML.
// If `{ pretty: true }` is in the options object,
// newlines become br tags, and URLs become links to
// those URLs. Otherwise we just do basic escaping.
//
// If `{ single: true }` is in the options object,
// single-quotes are escaped, otherwise double-quotes
// are escaped.
//
// For bc, if the second argument is truthy and not an
// object, `{ pretty: true }` is assumed.
self.escapeHtml = function(s, options) {
// for bc
if (options && (typeof(options) !== 'object')) {
options = { pretty: true };
}
options = options || {};
if (s === 'undefined') {
s = '';
}
if (typeof(s) !== 'string') {
s = s + '';
}
s = s.replace(/\&/g, '&').replace(/</g, '<').replace(/\>/g, '>');
if (options.single) {
s = s.replace(/\'/g, ''');
} else {
s = s.replace(/\"/g, '"');
}
if (options.pretty) {
s = s.replace(/\r?\n/g, "<br />");
// URLs to links. Careful, newlines are already <br /> at this point
s = s.replace(/https?\:[^\s<]+/g, function(match) {
match = match.trim();
return '<a href="' + self.escapeHtml(match) + '">' + match + '</a>';
});
}
return s;
};
// Convert HTML to true plaintext, with all entities decoded.
self.htmlToPlaintext = function(html) {
// The awesomest HTML renderer ever (look out webkit):
// block element opening tags = newlines, closing tags and non-container tags just gone
html = html.replace(/<\/.*?\>/g, '');
html = html.replace(/<(h1|h2|h3|h4|h5|h6|p|br|blockquote|li|article|address|footer|pre|header|table|tr|td|th|tfoot|thead|div|dl|dt|dd).*?\>/gi, '\n');
html = html.replace(/<.*?\>/g, '');
return he.decode(html);
};
// Capitalize the first letter of a string.
self.capitalizeFirst = function(s) {
return s.charAt(0).toUpperCase() + s.substr(1);
};
// Convert other name formats such as underscore and camelCase to a hyphenated css-style
// name.
self.cssName = function(camel) {
// Keep in sync with client side version
var i;
var css = '';
var dash = false;
for (i = 0; (i < camel.length); i++) {
var c = camel.charAt(i);
var lower = ((c >= 'a') && (c <= 'z'));
var upper = ((c >= 'A') && (c <= 'Z'));
var digit = ((c >= '0') && (c <= '9'));
if (!(lower || upper || digit)) {
dash = true;
continue;
}
if (upper) {
if (i > 0) {
dash = true;
}
c = c.toLowerCase();
}
if (dash) {
css += '-';
dash = false;
}
css += c;
}
return css;
};
// Convert a name to camel case.
//
// Useful in converting CSV with friendly headings into sensible property names.
//
// Only digits and ASCII letters remain.
//
// Anything that isn't a digit or an ASCII letter prompts the next character
// to be uppercase. Existing uppercase letters also trigger uppercase, unless
// they are the first character; this preserves existing camelCase names.
self.camelName = function(s) {
// Keep in sync with client side version
var i;
var n = '';
var nextUp = false;
for (i = 0; (i < s.length); i++) {
var c = s.charAt(i);
// If the next character is already uppercase, preserve that, unless
// it is the first character
if ((i > 0) && c.match(/[A-Z]/)) {
nextUp = true;
}
if (c.match(/[A-Za-z0-9]/)) {
if (nextUp) {
n += c.toUpperCase();
nextUp = false;
} else {
n += c.toLowerCase();
}
} else {
nextUp = true;
}
}
return n;
};
// Add a slash to a path, but only if it does not already end in a slash.
self.addSlashIfNeeded = function(path) {
path += '/';
path = path.replace(/\/\/$/, '/');
return path;
};
// An id for this particular Apostrophe instance that should be
// unique even in a multiple server environment.
self.apos.pid = self.generateId();
// Perform an md5 checksum on a string. Returns hex string.
self.md5 = function(s) {
var md5 = crypto.createHash('md5');
md5.update(s);
return md5.digest('hex');
};
// perform an md5 checksum on a file. Delivers `null`, `hexString` to callback.
self.md5File = function(filename, callback) {
var md5 = crypto.createHash('md5');
var s = fs.ReadStream(filename);
s.on('data', function(d) {
md5.update(d);
});
s.on('error', function(err) {
return callback(err);
});
s.on('end', function() {
var d = md5.digest('hex');
return callback(null, d);
});
};
// Turn the provided string into a string suitable for use as a slug.
// ONE punctuation character normally forbidden in slugs may
// optionally be permitted by specifying it via options.allow.
// The separator may be changed via options.separator.
self.slugify = function(s, options) {
return require('sluggo')(s, options);
};
// Returns a string that, when used for indexes, behaves
// similarly to MySQL's default behavior for sorting, plus a little
// extra tolerance of punctuation and whitespace differences. This is
// in contrast to MongoDB's default "absolute match with same case only"
// behavior which is no good for most practical purposes involving text.
//
// The use of this method to create sortable properties like
// "titleSortified" is encouraged. It should not be used for full text
// search, as MongoDB full text search is now available (see the
// "search" option to apos.get and everything layered on top of it).
// It is however used as part of our "autocomplete" search implementation.
self.sortify = function(s) {
return self.slugify(s, { separator: ' ' });
};
// Turns a user-entered search query into a regular expression.
// If the string contains multiple words, at least one space is
// required between them in matching documents, but additional words
// may also be skipped between them, up to a reasonable limit to
// preserve performance and avoid useless strings.
//
// Although we now have MongoDB full text search this is still
// a highly useful method, for instance to locate autocomplete
// candidates via highSearchWords.
//
// If the prefix flag is true the search matches only at the start.
self.searchify = function(q, prefix) {
q = self.sortify(q);
if (prefix) {
q = '^' + q;
}
q = q.replace(/ /g, ' .{0,20}?');
q = new RegExp(q);
return q;
};
// Clone the given object recursively, discarding all
// properties whose names begin with `_` except
// for `_id`. Returns the clone.
//
// This removes the output of joins and
// other dynamic loaders, so that dynamically available
// content is not stored redundantly in MongoDB.
//
// If the object is an array, the clone is also an array.
//
// Date objects are cloned as such. All other non-JSON
// objects are cloned as plain JSON objects.
//
// If `keepScalars` is true, properties beginning with `_`
// are kept as long as they are not objects. This is useful
// when using `clonePermanent` to limit JSON inserted into
// browser attributes, rather than filtering for the database.
// Preserving simple string properties like `._url` is usually
// a good thing in the former case.
//
// Arrays are cloned as such only if they are true arrays
// (Array.isArray returns true). Otherwise all objects with
// a length property would be treated as arrays, which is
// an unrealistic restriction on apostrophe doc schemas.
self.clonePermanent = function(o, keepScalars) {
var c;
var isArray = Array.isArray(o);
if (isArray) {
c = [];
} else {
c = {};
}
function iterator(val, key) {
// careful, don't crash on numeric keys
if (typeof key === 'string') {
if ((key.charAt(0) === '_') && (key !== '_id')) {
if ((!keepScalars) || (typeof val === 'object')) {
return;
}
}
}
if ((val === null) || (val === undefined)) {
// typeof(null) is object, sigh
c[key] = null;
} else if (typeof(val) !== 'object') {
c[key] = val;
} else if (val instanceof Date) {
c[key] = new Date(val);
} else {
c[key] = self.clonePermanent(val, keepScalars);
}
}
if (isArray) {
_.each(o, iterator);
} else {
_.forOwn(o, iterator);
}
return c;
};
// `ids` should be an array of mongodb IDs. The elements of the `items` array, which
// should be the result of a mongodb query, are returned in the order specified by `ids`.
// This is useful after performing an `$in` query with MongoDB (note that `$in` does NOT sort its
// strings in the order given).
//
// Any IDs that do not actually exist for an item in the `items` array are not returned,
// and vice versa. You should not assume the result will have the same length as
// either array.
//
// Optionally you may specify a property name other than _id as the third argument.
// You may use dot notation in this argument.
self.orderById = function(ids, items, idProperty) {
if (idProperty === undefined) {
idProperty = '_id';
}
var byId = {};
_.each(items, function(item) {
var value = item;
var keys = idProperty.split('.');
_.each(keys, function(key) {
value = value[key];
});
byId[value] = item;
});
items = [];
_.each(ids, function(_id) {
if (_.has(byId, _id)) {
items.push(byId[_id]);
}
});
return items;
};
self.regExpQuote = require('regexp-quote');
// Return true if `req` is an AJAX request (`req.xhr` is set, or
// `req.query.xhr` is set to emulate it, or `req.query.apos_refresh` has
// been set by Apostrophe's content refresh mechanism).
self.isAjaxRequest = function(req) {
return (req.xhr || req.query.xhr) && (!req.query.apos_refresh);
};
// Store a "blessing" in the session for the given set of arguments
// (everything after `req`).
//
// Example:
//
// DURING PAGE RENDERING OR OTHER TRUSTED RENDERING OPERATION
//
// `apos.utils.bless(req, options, 'widget', widget.type)`
//
// ON A LATER AJAX REQUEST TO THE render-widget ROUTE
//
// `if (apos.utils.isBlessed(req, options, 'widget', widget.type)) { /* It's safe! */ }`
//
// This way we know this set of options was legitimately part of a recent page rendering
// and therefore is safe to reuse to re-render a widget that is being edited.
self.bless = function(req, options /* , arg2, arg3... */) {
var hash = self.hashBlessing(Array.prototype.slice.call(arguments, 1));
req.session.aposBlessings = req.session.aposBlessings || {};
req.session.aposBlessings[hash] = true;
};
// See apos.utils.bless. Checks whether the given set of arguments
// (everything after `req`) has been blessed in the current session.
self.isBlessed = function(req, options /* , arg2, arg3... */) {
var hash = self.hashBlessing(Array.prototype.slice.call(arguments, 1));
return req.session.aposBlessings && _.has(req.session.aposBlessings, hash);
};
// See `self.bless` and `self.isBlessed`. Creates a unique hash for a given
// set of arguments. Arguments must be JSON-friendly.
self.hashBlessing = function(args) {
var s = '';
var i;
for (i = 0; (i < args.length); i++) {
s += JSON.stringify(args[i]);
}
return self.md5(s);
};
// Sort the given array of strings in place, comparing strings in a case-insensitive way.
self.insensitiveSort = function(strings) {
strings.sort(self.insensitiveSortCompare);
};
// Sort the given array of objects in place, based on the value of the given property of each object,
// in a case-insensitive way.
self.insensitiveSortByProperty = function(objects, property) {
objects.sort(function(a, b) {
return self.insensitiveSortCompare(a[property], b[property]);
});
};
// Copmpare two strings in a case-insensitive way, returning -1, 0 or 1, suitable for use with sort().
self.insensitiveSortCompare = function(a, b) {
if (a && a.toLowerCase()) {
a = a.toLowerCase();
}
if (b && b.toLowerCase()) {
b = b.toLowerCase();
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
};
};
| {
"content_hash": "c1d8c4012dc2ce2a32cc8fa4346d5110",
"timestamp": "",
"source": "github",
"line_count": 464,
"max_line_length": 154,
"avg_line_length": 31.913793103448278,
"alnum_prop": 0.6089276066990815,
"repo_name": "koeppel/apocms",
"id": "406a307ddbfbd7e0854afd10d5c1cc16cfa7980f",
"size": "14808",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/apostrophe/lib/modules/apostrophe-utils/lib/api.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "81899"
},
{
"name": "HTML",
"bytes": "5975"
},
{
"name": "JavaScript",
"bytes": "308637"
},
{
"name": "Shell",
"bytes": "7630"
}
],
"symlink_target": ""
} |
set -eu
# This script is a convenience wrapper for making fresh test data with no
# extra dependencies. We create in the current working directory.
#
# Most people should not need to run this; it's an "every few years" maintainer
# task. So we can depend upon specific tools which make it sane to manage
# extensions.
# We're using github.com/cloudflare/cfssl
progname="$(basename "$0" .sh)"
warn() { printf >&2 '%s: %s\n' "$progname" "$*"; }
die() { warn "$@"; exit 1; }
[ -f tls.conf ] || die "no tls.conf in current directory"
ORG_NAME='Synadia Communications, Inc'
CA_COMMON_NAME='NATS top tool test suite'
# The default duration of the CA in cfssl is 5 years, changing it is
# non-obvious, so let's cap the lifetime of the issued certs to the CA duration
# to avoid confusion when the CA expires.
DURATION_YEARS=5
DURATION_STR="$(( DURATION_YEARS * 365 * 24 ))h"
csr_filter_common() {
jq --arg org "$ORG_NAME" -r 'del(.CN) | del(.names[0].L) | .names[0].O=$org'
}
ca_csr_json() {
cfssl print-defaults csr | csr_filter_common | \
jq --arg cn "$CA_COMMON_NAME" -r '.CN=$cn | del(.hosts)'
}
client_csr_json() {
cfssl print-defaults csr | csr_filter_common | \
jq -r 'del(.hosts)'
}
server_csr_json() {
cfssl print-defaults csr | csr_filter_common | \
jq -r '.hosts = ["localhost", "127.0.0.1", "::1"]'
}
ca_cfg_json() {
cfssl print-defaults config | \
jq --arg dur "$DURATION_STR" -r '.signing.profiles |= map_values(.expiry = $dur)'
}
KEY_CURVE=secp384r1
SUBJ_PREFIX='/C=US/ST=California/O=Synadia Communications, LLC/OU=NATS'
CA_PUBLIC=ca.pem
# We will delete the key when done
CA_KEY=ca-key.pem
CA_CFG=ca-config.json
ca_cfg_json > "./$CA_CFG"
ca_csr_json | cfssl genkey -initca - | cfssljson -bare ca
gencert() { cfssl gencert -ca "$CA_PUBLIC" -ca-key "$CA_KEY" -config "$CA_CFG" "$@" ; }
client_csr_json | gencert -profile=client - | cfssljson -bare client
server_csr_json | gencert -profile=www - | cfssljson -bare server
mv -v client.pem client-cert.pem
mv -v server.pem server-cert.pem
rm -v ./*.csr "$CA_KEY" "$CA_CFG"
| {
"content_hash": "ba94774f2e10654078d91ecc25ddba8e",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 87,
"avg_line_length": 30.057971014492754,
"alnum_prop": 0.6682738669238187,
"repo_name": "nats-io/nats-top",
"id": "872752c76809e8e5f49911ad4fbca87a31e5616e",
"size": "2088",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "util/test/make-new-certs.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "36567"
},
{
"name": "Makefile",
"bytes": "29"
},
{
"name": "Shell",
"bytes": "2682"
}
],
"symlink_target": ""
} |
package io.mangoo.enums;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import com.google.common.collect.Maps;
/**
*
* @author svenkubiak
*
*/
public enum Binding {
AUTHENTICATION("io.mangoo.routing.bindings.Authentication"),
DOUBLE("java.lang.Double"),
DOUBLE_PRIMITIVE("double"),
FLASH("io.mangoo.routing.bindings.Flash"),
FLOAT("java.lang.Float"),
FLOAT_PRIMITIVE("float"),
FORM("io.mangoo.routing.bindings.Form"),
INT_PRIMITIVE("int"),
INTEGER("java.lang.Integer"),
LOCALDATE("java.time.LocalDate"),
LOCALDATETIME("java.time.LocalDateTime"),
LONG("java.lang.Long"),
LONG_PRIMITIVE("long"),
MESSAGES("io.mangoo.i18n.Messages"),
OPTIONAL("java.util.Optional"),
REQUEST("io.mangoo.routing.bindings.Request"),
SESSION("io.mangoo.routing.bindings.Session"),
STRING("java.lang.String"),
UNDEFINED("undefined");
private final String value;
private static Map<String, Binding> values;
static {
Map<String, Binding> bindings = Maps.newHashMapWithExpectedSize(Binding.values().length);
for (Binding binding : Binding.values()) {
bindings.put(binding.toString().toLowerCase(Locale.ENGLISH), binding);
}
values = Collections.unmodifiableMap(bindings);
}
Binding (String value) {
this.value = value;
}
public static Binding fromString(String value) {
return values.get(value.toLowerCase(Locale.ENGLISH));
}
@Override
public String toString() {
return this.value;
}
} | {
"content_hash": "92bba465d202f9a487db389c5c02fa8a",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 97,
"avg_line_length": 27.775862068965516,
"alnum_prop": 0.6561142147734327,
"repo_name": "svenkubiak/mangooio",
"id": "4f88939606cd8950ee1c7418e0b0bf108e90abcb",
"size": "1611",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mangooio-core/src/main/java/io/mangoo/enums/Binding.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7984"
},
{
"name": "FreeMarker",
"bytes": "29167"
},
{
"name": "Groovy",
"bytes": "982"
},
{
"name": "HTML",
"bytes": "3564"
},
{
"name": "Java",
"bytes": "794555"
},
{
"name": "JavaScript",
"bytes": "26086"
}
],
"symlink_target": ""
} |
<?php
namespace Matthias\LazyServicesBundle\Tests\DependencyInjection;
use Matthias\LazyServicesBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Processor
*/
private $processor;
/**
* @var Configuration
*/
private $configuration;
protected function setUp()
{
$this->processor = new Processor();
$this->configuration = new Configuration();
}
protected function tearDown()
{
$this->processor = null;
$this->configuration = null;
}
/**
* @dataProvider configProvider
*/
public function testProcessedConfiguration(array $configs, array $expectedProcessedConfig)
{
$tree = $this->configuration->getConfigTreeBuilder()->buildTree();
$processedConfig = $this->processor->process($tree, $configs);
$this->assertEquals($expectedProcessedConfig, $processedConfig);
}
public function configProvider()
{
return array(
array(
array(),
array('lazy_service_ids' => array())
),
array(
array('matthias_lazy_services' => array()),
array('lazy_service_ids' => array())
),
array(
array(
'matthias_lazy_services' => array(
'lazy_service_ids' => array('service')
)
),
array('lazy_service_ids' => array('service'))
)
);
}
}
| {
"content_hash": "3d0cbdd915d29db1b377ecdb145acbea",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 94,
"avg_line_length": 25.323076923076922,
"alnum_prop": 0.5510328068043743,
"repo_name": "matthiasnoback/LazyServicesBundle",
"id": "000c4a01a3d317b9aab3da753ae178c71c2dc95e",
"size": "1646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tests/DependencyInjection/ConfigurationTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "15933"
}
],
"symlink_target": ""
} |
class CreateTickets < ActiveRecord::Migration
def change
create_table :tickets do |t|
t.timestamps
end
end
end
| {
"content_hash": "ac415f420b62c80f81b1d099563ed9ec",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 45,
"avg_line_length": 16.25,
"alnum_prop": 0.6846153846153846,
"repo_name": "BradRuderman/israel_hackathon",
"id": "223e399951993df25b4dea687587f551059e0f2b",
"size": "130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20131230044316_create_tickets.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2898"
},
{
"name": "JavaScript",
"bytes": "50552"
},
{
"name": "Ruby",
"bytes": "20052"
}
],
"symlink_target": ""
} |
package org.spongepowered.common.event.lifecycle;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.api.Game;
import org.spongepowered.api.command.manager.CommandFailedRegistrationException;
import org.spongepowered.api.command.manager.CommandMapping;
import org.spongepowered.api.command.registrar.CommandRegistrar;
import org.spongepowered.api.event.Cause;
import org.spongepowered.api.event.lifecycle.RegisterCommandEvent;
import org.spongepowered.common.event.lifecycle.RegisterCommandEventImpl.ResultImpl;
import org.spongepowered.plugin.PluginContainer;
import java.util.Objects;
public final class RegisterCommandEventImpl<C, R extends CommandRegistrar<C>> extends AbstractLifecycleEvent.GenericImpl<C> implements RegisterCommandEvent<C> {
private final R registrar;
public RegisterCommandEventImpl(final Cause cause, final Game game, final R registrar) {
super(cause, game, registrar.type().handledType());
this.registrar = registrar;
}
@Override
public @NonNull Result<C> register(final @NonNull PluginContainer container, final @NonNull C command, final @NonNull String alias,
final String @NonNull... aliases) throws CommandFailedRegistrationException {
return new ResultImpl<>(
this,
this.registrar.register(Objects.requireNonNull(container, "container"), Objects.requireNonNull(command, "command"),
Objects.requireNonNull(alias, "alias"), Objects.requireNonNull(aliases, "aliases"))
);
}
@Override
public String toString() {
return "RegisterCommandEvent{cause=" + this.cause + ", token=" + this.token + "}";
}
static final class ResultImpl<C, R extends CommandRegistrar<C>> implements Result<C> {
private final RegisterCommandEventImpl<C, R> parentEvent;
private final CommandMapping mapping;
ResultImpl(final RegisterCommandEventImpl<C, R> parentEvent, final CommandMapping mapping) {
this.parentEvent = parentEvent;
this.mapping = mapping;
}
@Override
public @NonNull Result<C> register(final @NonNull PluginContainer container, final @NonNull C command, final @NonNull String alias,
final String @NonNull... aliases) throws CommandFailedRegistrationException {
return this.parentEvent.register(container, command, alias, aliases);
}
@Override
public @NonNull CommandMapping mapping() {
return this.mapping;
}
}
}
| {
"content_hash": "0f86ec5234ef6ece9de89de2b84abd43",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 160,
"avg_line_length": 40.857142857142854,
"alnum_prop": 0.717948717948718,
"repo_name": "SpongePowered/Sponge",
"id": "09eb0037d28541ce0fb98c37e0794958097d4a1b",
"size": "3821",
"binary": false,
"copies": "1",
"ref": "refs/heads/api-8",
"path": "src/main/java/org/spongepowered/common/event/lifecycle/RegisterCommandEventImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "12489815"
},
{
"name": "Kotlin",
"bytes": "73840"
},
{
"name": "Shell",
"bytes": "70"
}
],
"symlink_target": ""
} |
require 'omf-expctl/nodeHandler'
| {
"content_hash": "e3279581ce4f27c84ee57e3caf173e20",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 32,
"avg_line_length": 34,
"alnum_prop": 0.7941176470588235,
"repo_name": "nathansamson/OMF",
"id": "bc6498f0e776fb2005ee8828858641eb8efbeb47",
"size": "1250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "omf-expctl/ruby/omf-expctl/handler.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "657989"
},
{
"name": "C++",
"bytes": "11324"
},
{
"name": "D",
"bytes": "7480"
},
{
"name": "Elixir",
"bytes": "6948"
},
{
"name": "JavaScript",
"bytes": "1641704"
},
{
"name": "Objective-C",
"bytes": "1874"
},
{
"name": "R",
"bytes": "33118"
},
{
"name": "Ruby",
"bytes": "1933501"
},
{
"name": "Shell",
"bytes": "33789"
}
],
"symlink_target": ""
} |
// Copyright (C) 2009 The Libphonenumber Authors
//
// 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.
// Author: Shaopeng Jia
// Author: Lara Rennie
// Open-sourced by: Philippe Liard
//
// Note that these tests use the metadata contained in the test metadata file,
// not the normal metadata file, so should not be used for regression test
// purposes - these tests are illustrative only and test functionality.
#include "phonenumbers/phonenumberutil.h"
#include <algorithm>
#include <iostream>
#include <list>
#include <set>
#include <string>
#include <gtest/gtest.h>
#include "phonenumbers/default_logger.h"
#include "phonenumbers/phonemetadata.pb.h"
#include "phonenumbers/phonenumber.h"
#include "phonenumbers/phonenumber.pb.h"
#include "phonenumbers/test_util.h"
namespace i18n {
namespace phonenumbers {
using std::find;
using std::ostream;
using google::protobuf::RepeatedPtrField;
static const int kInvalidCountryCode = 2;
class PhoneNumberUtilTest : public testing::Test {
protected:
PhoneNumberUtilTest() : phone_util_(*PhoneNumberUtil::GetInstance()) {
PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger());
}
// Wrapper functions for private functions that we want to test.
const PhoneMetadata* GetPhoneMetadata(const string& region_code) const {
return phone_util_.GetMetadataForRegion(region_code);
}
const PhoneMetadata* GetMetadataForNonGeographicalRegion(
int country_code) const {
return phone_util_.GetMetadataForNonGeographicalRegion(country_code);
}
void ExtractPossibleNumber(const string& number,
string* extracted_number) const {
phone_util_.ExtractPossibleNumber(number, extracted_number);
}
bool IsViablePhoneNumber(const string& number) const {
return phone_util_.IsViablePhoneNumber(number);
}
void Normalize(string* number) const {
phone_util_.Normalize(number);
}
PhoneNumber::CountryCodeSource MaybeStripInternationalPrefixAndNormalize(
const string& possible_idd_prefix,
string* number) const {
return phone_util_.MaybeStripInternationalPrefixAndNormalize(
possible_idd_prefix,
number);
}
void MaybeStripNationalPrefixAndCarrierCode(const PhoneMetadata& metadata,
string* number,
string* carrier_code) const {
phone_util_.MaybeStripNationalPrefixAndCarrierCode(metadata, number,
carrier_code);
}
bool MaybeStripExtension(string* number, string* extension) const {
return phone_util_.MaybeStripExtension(number, extension);
}
PhoneNumberUtil::ErrorType MaybeExtractCountryCode(
const PhoneMetadata* default_region_metadata,
bool keep_raw_input,
string* national_number,
PhoneNumber* phone_number) const {
return phone_util_.MaybeExtractCountryCode(default_region_metadata,
keep_raw_input,
national_number,
phone_number);
}
bool ContainsOnlyValidDigits(const string& s) const {
return phone_util_.ContainsOnlyValidDigits(s);
}
const PhoneNumberUtil& phone_util_;
private:
DISALLOW_COPY_AND_ASSIGN(PhoneNumberUtilTest);
};
TEST_F(PhoneNumberUtilTest, ContainsOnlyValidDigits) {
EXPECT_TRUE(ContainsOnlyValidDigits(""));
EXPECT_TRUE(ContainsOnlyValidDigits("2"));
EXPECT_TRUE(ContainsOnlyValidDigits("25"));
EXPECT_TRUE(ContainsOnlyValidDigits("\xEF\xBC\x96" /* "6" */));
EXPECT_FALSE(ContainsOnlyValidDigits("a"));
EXPECT_FALSE(ContainsOnlyValidDigits("2a"));
}
TEST_F(PhoneNumberUtilTest, GetSupportedRegions) {
std::set<string> regions;
phone_util_.GetSupportedRegions(®ions);
EXPECT_GT(regions.size(), 0U);
}
TEST_F(PhoneNumberUtilTest, GetSupportedGlobalNetworkCallingCodes) {
std::set<int> calling_codes;
phone_util_.GetSupportedGlobalNetworkCallingCodes(&calling_codes);
EXPECT_GT(calling_codes.size(), 0U);
for (std::set<int>::const_iterator it = calling_codes.begin();
it != calling_codes.end(); ++it) {
EXPECT_GT(*it, 0);
string region_code;
phone_util_.GetRegionCodeForCountryCode(*it, ®ion_code);
EXPECT_EQ(RegionCode::UN001(), region_code);
}
}
TEST_F(PhoneNumberUtilTest, GetSupportedCallingCodes) {
std::set<int> calling_codes;
phone_util_.GetSupportedCallingCodes(&calling_codes);
EXPECT_GT(calling_codes.size(), 0U);
for (std::set<int>::const_iterator it = calling_codes.begin();
it != calling_codes.end(); ++it) {
EXPECT_GT(*it, 0);
string region_code;
phone_util_.GetRegionCodeForCountryCode(*it, ®ion_code);
EXPECT_NE(RegionCode::ZZ(), region_code);
}
std::set<int> supported_global_network_calling_codes;
phone_util_.GetSupportedGlobalNetworkCallingCodes(
&supported_global_network_calling_codes);
// There should be more than just the global network calling codes in this
// set.
EXPECT_GT(calling_codes.size(),
supported_global_network_calling_codes.size());
// But they should be included. Testing one of them.
EXPECT_NE(calling_codes.find(979), calling_codes.end());
}
TEST_F(PhoneNumberUtilTest, GetSupportedTypesForRegion) {
std::set<PhoneNumberUtil::PhoneNumberType> types;
phone_util_.GetSupportedTypesForRegion(RegionCode::BR(), &types);
EXPECT_NE(types.find(PhoneNumberUtil::FIXED_LINE), types.end());
// Our test data has no mobile numbers for Brazil.
EXPECT_EQ(types.find(PhoneNumberUtil::MOBILE), types.end());
// UNKNOWN should never be returned.
EXPECT_EQ(types.find(PhoneNumberUtil::UNKNOWN), types.end());
types.clear();
// In the US, many numbers are classified as FIXED_LINE_OR_MOBILE; but we
// don't want to expose this as a supported type, instead we say FIXED_LINE
// and MOBILE are both present.
phone_util_.GetSupportedTypesForRegion(RegionCode::US(), &types);
EXPECT_NE(types.find(PhoneNumberUtil::FIXED_LINE), types.end());
EXPECT_NE(types.find(PhoneNumberUtil::MOBILE), types.end());
EXPECT_EQ(types.find(PhoneNumberUtil::FIXED_LINE_OR_MOBILE), types.end());
types.clear();
phone_util_.GetSupportedTypesForRegion(RegionCode::ZZ(), &types);
// Test the invalid region code.
EXPECT_EQ(0, types.size());
}
TEST_F(PhoneNumberUtilTest, GetSupportedTypesForNonGeoEntity) {
std::set<PhoneNumberUtil::PhoneNumberType> types;
// No data exists for 999 at all, no types should be returned.
phone_util_.GetSupportedTypesForNonGeoEntity(999, &types);
EXPECT_EQ(0, types.size());
types.clear();
phone_util_.GetSupportedTypesForNonGeoEntity(979, &types);
EXPECT_NE(types.find(PhoneNumberUtil::PREMIUM_RATE), types.end());
EXPECT_EQ(types.find(PhoneNumberUtil::MOBILE), types.end());
EXPECT_EQ(types.find(PhoneNumberUtil::UNKNOWN), types.end());
}
TEST_F(PhoneNumberUtilTest, GetRegionCodesForCountryCallingCode) {
std::list<string> regions;
phone_util_.GetRegionCodesForCountryCallingCode(1, ®ions);
EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::US())
!= regions.end());
EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::BS())
!= regions.end());
regions.clear();
phone_util_.GetRegionCodesForCountryCallingCode(44, ®ions);
EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::GB())
!= regions.end());
regions.clear();
phone_util_.GetRegionCodesForCountryCallingCode(49, ®ions);
EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::DE())
!= regions.end());
regions.clear();
phone_util_.GetRegionCodesForCountryCallingCode(800, ®ions);
EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::UN001())
!= regions.end());
regions.clear();
phone_util_.GetRegionCodesForCountryCallingCode(
kInvalidCountryCode, ®ions);
EXPECT_TRUE(regions.empty());
}
TEST_F(PhoneNumberUtilTest, GetInstanceLoadUSMetadata) {
const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::US());
EXPECT_EQ("US", metadata->id());
EXPECT_EQ(1, metadata->country_code());
EXPECT_EQ("011", metadata->international_prefix());
EXPECT_TRUE(metadata->has_national_prefix());
ASSERT_EQ(2, metadata->number_format_size());
EXPECT_EQ("(\\d{3})(\\d{3})(\\d{4})",
metadata->number_format(1).pattern());
EXPECT_EQ("$1 $2 $3", metadata->number_format(1).format());
EXPECT_EQ("[13-689]\\d{9}|2[0-35-9]\\d{8}",
metadata->general_desc().national_number_pattern());
EXPECT_EQ("[13-689]\\d{9}|2[0-35-9]\\d{8}",
metadata->fixed_line().national_number_pattern());
EXPECT_EQ(1, metadata->general_desc().possible_length_size());
EXPECT_EQ(10, metadata->general_desc().possible_length(0));
// Possible lengths are the same as the general description, so aren't stored
// separately in the toll free element as well.
EXPECT_EQ(0, metadata->toll_free().possible_length_size());
EXPECT_EQ("900\\d{7}", metadata->premium_rate().national_number_pattern());
// No shared-cost data is available, so its national number data should not be
// set.
EXPECT_FALSE(metadata->shared_cost().has_national_number_pattern());
}
TEST_F(PhoneNumberUtilTest, GetInstanceLoadDEMetadata) {
const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::DE());
EXPECT_EQ("DE", metadata->id());
EXPECT_EQ(49, metadata->country_code());
EXPECT_EQ("00", metadata->international_prefix());
EXPECT_EQ("0", metadata->national_prefix());
ASSERT_EQ(6, metadata->number_format_size());
EXPECT_EQ(1, metadata->number_format(5).leading_digits_pattern_size());
EXPECT_EQ("900", metadata->number_format(5).leading_digits_pattern(0));
EXPECT_EQ("(\\d{3})(\\d{3,4})(\\d{4})",
metadata->number_format(5).pattern());
EXPECT_EQ(2, metadata->general_desc().possible_length_local_only_size());
EXPECT_EQ(8, metadata->general_desc().possible_length_size());
// Nothing is present for fixed-line, since it is the same as the general
// desc, so for efficiency reasons we don't store an extra value.
EXPECT_EQ(0, metadata->fixed_line().possible_length_size());
EXPECT_EQ(2, metadata->mobile().possible_length_size());
EXPECT_EQ("$1 $2 $3", metadata->number_format(5).format());
EXPECT_EQ("(?:[24-6]\\d{2}|3[03-9]\\d|[789](?:0[2-9]|[1-9]\\d))\\d{1,8}",
metadata->fixed_line().national_number_pattern());
EXPECT_EQ("30123456", metadata->fixed_line().example_number());
EXPECT_EQ(10, metadata->toll_free().possible_length(0));
EXPECT_EQ("900([135]\\d{6}|9\\d{7})",
metadata->premium_rate().national_number_pattern());
}
TEST_F(PhoneNumberUtilTest, GetInstanceLoadARMetadata) {
const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::AR());
EXPECT_EQ("AR", metadata->id());
EXPECT_EQ(54, metadata->country_code());
EXPECT_EQ("00", metadata->international_prefix());
EXPECT_EQ("0", metadata->national_prefix());
EXPECT_EQ("0(?:(11|343|3715)15)?", metadata->national_prefix_for_parsing());
EXPECT_EQ("9$1", metadata->national_prefix_transform_rule());
ASSERT_EQ(5, metadata->number_format_size());
EXPECT_EQ("$2 15 $3-$4", metadata->number_format(2).format());
EXPECT_EQ("(9)(\\d{4})(\\d{2})(\\d{4})",
metadata->number_format(3).pattern());
EXPECT_EQ("(9)(\\d{4})(\\d{2})(\\d{4})",
metadata->intl_number_format(3).pattern());
EXPECT_EQ("$1 $2 $3 $4", metadata->intl_number_format(3).format());
}
TEST_F(PhoneNumberUtilTest, GetInstanceLoadInternationalTollFreeMetadata) {
const PhoneMetadata* metadata = GetMetadataForNonGeographicalRegion(800);
EXPECT_FALSE(metadata == NULL);
EXPECT_EQ("001", metadata->id());
EXPECT_EQ(800, metadata->country_code());
EXPECT_EQ("$1 $2", metadata->number_format(0).format());
EXPECT_EQ("(\\d{4})(\\d{4})", metadata->number_format(0).pattern());
EXPECT_EQ(0, metadata->general_desc().possible_length_local_only_size());
EXPECT_EQ(1, metadata->general_desc().possible_length_size());
EXPECT_EQ("12345678", metadata->toll_free().example_number());
}
TEST_F(PhoneNumberUtilTest, GetNationalSignificantNumber) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(6502530000ULL);
string national_significant_number;
phone_util_.GetNationalSignificantNumber(number,
&national_significant_number);
EXPECT_EQ("6502530000", national_significant_number);
// An Italian mobile number.
national_significant_number.clear();
number.set_country_code(39);
number.set_national_number(312345678ULL);
phone_util_.GetNationalSignificantNumber(number,
&national_significant_number);
EXPECT_EQ("312345678", national_significant_number);
// An Italian fixed line number.
national_significant_number.clear();
number.set_country_code(39);
number.set_national_number(236618300ULL);
number.set_italian_leading_zero(true);
phone_util_.GetNationalSignificantNumber(number,
&national_significant_number);
EXPECT_EQ("0236618300", national_significant_number);
national_significant_number.clear();
number.Clear();
number.set_country_code(800);
number.set_national_number(12345678ULL);
phone_util_.GetNationalSignificantNumber(number,
&national_significant_number);
EXPECT_EQ("12345678", national_significant_number);
}
TEST_F(PhoneNumberUtilTest, GetNationalSignificantNumber_ManyLeadingZeros) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(650ULL);
number.set_italian_leading_zero(true);
number.set_number_of_leading_zeros(2);
string national_significant_number;
phone_util_.GetNationalSignificantNumber(number,
&national_significant_number);
EXPECT_EQ("00650", national_significant_number);
// Set a bad value; we shouldn't crash, we shouldn't output any leading zeros
// at all.
number.set_number_of_leading_zeros(-3);
national_significant_number.clear();
phone_util_.GetNationalSignificantNumber(number,
&national_significant_number);
EXPECT_EQ("650", national_significant_number);
}
TEST_F(PhoneNumberUtilTest, GetExampleNumber) {
PhoneNumber de_number;
de_number.set_country_code(49);
de_number.set_national_number(30123456ULL);
PhoneNumber test_number;
bool success = phone_util_.GetExampleNumber(RegionCode::DE(), &test_number);
EXPECT_TRUE(success);
EXPECT_EQ(de_number, test_number);
success = phone_util_.GetExampleNumberForType(
RegionCode::DE(), PhoneNumberUtil::FIXED_LINE, &test_number);
EXPECT_TRUE(success);
EXPECT_EQ(de_number, test_number);
// Should return the same response if asked for FIXED_LINE_OR_MOBILE too.
success = phone_util_.GetExampleNumberForType(
RegionCode::DE(), PhoneNumberUtil::FIXED_LINE_OR_MOBILE, &test_number);
EXPECT_EQ(de_number, test_number);
success = phone_util_.GetExampleNumberForType(
RegionCode::DE(), PhoneNumberUtil::MOBILE, &test_number);
// We have data for the US, but no data for VOICEMAIL, so the number passed in
// should be left empty.
success = phone_util_.GetExampleNumberForType(
RegionCode::US(), PhoneNumberUtil::VOICEMAIL, &test_number);
test_number.Clear();
EXPECT_FALSE(success);
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
success = phone_util_.GetExampleNumberForType(
RegionCode::US(), PhoneNumberUtil::FIXED_LINE, &test_number);
// Here we test that the call to get an example number succeeded, and that the
// number passed in was modified.
EXPECT_TRUE(success);
EXPECT_NE(PhoneNumber::default_instance(), test_number);
success = phone_util_.GetExampleNumberForType(
RegionCode::US(), PhoneNumberUtil::MOBILE, &test_number);
EXPECT_TRUE(success);
EXPECT_NE(PhoneNumber::default_instance(), test_number);
// CS is an invalid region, so we have no data for it. We should return false.
test_number.Clear();
EXPECT_FALSE(phone_util_.GetExampleNumberForType(
RegionCode::CS(), PhoneNumberUtil::MOBILE, &test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
// RegionCode 001 is reserved for supporting non-geographical country calling
// code. We don't support getting an example number for it with this method.
EXPECT_FALSE(phone_util_.GetExampleNumber(RegionCode::UN001(), &test_number));
}
TEST_F(PhoneNumberUtilTest, GetInvalidExampleNumber) {
// RegionCode 001 is reserved for supporting non-geographical country calling
// codes. We don't support getting an invalid example number for it with
// GetInvalidExampleNumber.
PhoneNumber test_number;
EXPECT_FALSE(phone_util_.GetInvalidExampleNumber(RegionCode::UN001(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_FALSE(phone_util_.GetInvalidExampleNumber(RegionCode::CS(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_TRUE(phone_util_.GetInvalidExampleNumber(RegionCode::US(),
&test_number));
// At least the country calling code should be set correctly.
EXPECT_EQ(1, test_number.country_code());
EXPECT_NE(0, test_number.national_number());
}
TEST_F(PhoneNumberUtilTest, GetExampleNumberForNonGeoEntity) {
PhoneNumber toll_free_number;
toll_free_number.set_country_code(800);
toll_free_number.set_national_number(12345678ULL);
PhoneNumber test_number;
bool success =
phone_util_.GetExampleNumberForNonGeoEntity(800 , &test_number);
EXPECT_TRUE(success);
EXPECT_EQ(toll_free_number, test_number);
PhoneNumber universal_premium_rate;
universal_premium_rate.set_country_code(979);
universal_premium_rate.set_national_number(123456789ULL);
success = phone_util_.GetExampleNumberForNonGeoEntity(979 , &test_number);
EXPECT_TRUE(success);
EXPECT_EQ(universal_premium_rate, test_number);
}
TEST_F(PhoneNumberUtilTest, GetExampleNumberWithoutRegion) {
// In our test metadata we don't cover all types: in our real metadata, we do.
PhoneNumber test_number;
bool success = phone_util_.GetExampleNumberForType(
PhoneNumberUtil::FIXED_LINE,
&test_number);
// We test that the call to get an example number succeeded, and that the
// number passed in was modified.
EXPECT_TRUE(success);
EXPECT_NE(PhoneNumber::default_instance(), test_number);
test_number.Clear();
success = phone_util_.GetExampleNumberForType(PhoneNumberUtil::MOBILE,
&test_number);
EXPECT_TRUE(success);
EXPECT_NE(PhoneNumber::default_instance(), test_number);
test_number.Clear();
success = phone_util_.GetExampleNumberForType(PhoneNumberUtil::PREMIUM_RATE,
&test_number);
EXPECT_TRUE(success);
EXPECT_NE(PhoneNumber::default_instance(), test_number);
}
TEST_F(PhoneNumberUtilTest, FormatUSNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(1);
test_number.set_national_number(6502530000ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("650 253 0000", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+1 650 253 0000", formatted_number);
test_number.set_national_number(8002530000ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("800 253 0000", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+1 800 253 0000", formatted_number);
test_number.set_national_number(9002530000ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("900 253 0000", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+1 900 253 0000", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number);
EXPECT_EQ("tel:+1-900-253-0000", formatted_number);
test_number.set_national_number(0ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("0", formatted_number);
// Numbers with all zeros in the national number part will be formatted by
// using the raw_input if that is available no matter which format is
// specified.
test_number.set_raw_input("000-000-0000");
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("000-000-0000", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatBSNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(1);
test_number.set_national_number(2421234567ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("242 123 4567", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+1 242 123 4567", formatted_number);
test_number.set_national_number(8002530000ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("800 253 0000", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+1 800 253 0000", formatted_number);
test_number.set_national_number(9002530000ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("900 253 0000", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+1 900 253 0000", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatGBNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(44);
test_number.set_national_number(2087389353ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("(020) 8738 9353", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+44 20 8738 9353", formatted_number);
test_number.set_national_number(7912345678ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("(07912) 345 678", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+44 7912 345 678", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatDENumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(49);
test_number.set_national_number(301234ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("030/1234", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+49 30/1234", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number);
EXPECT_EQ("tel:+49-30-1234", formatted_number);
test_number.set_national_number(291123ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("0291 123", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+49 291 123", formatted_number);
test_number.set_national_number(29112345678ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("0291 12345678", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+49 291 12345678", formatted_number);
test_number.set_national_number(9123123ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("09123 123", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+49 9123 123", formatted_number);
test_number.set_national_number(80212345ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("08021 2345", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+49 8021 2345", formatted_number);
test_number.set_national_number(1234ULL);
// Note this number is correctly formatted without national prefix. Most of
// the numbers that are treated as invalid numbers by the library are short
// numbers, and they are usually not dialed with national prefix.
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("1234", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+49 1234", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatITNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(39);
test_number.set_national_number(236618300ULL);
test_number.set_italian_leading_zero(true);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("02 3661 8300", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+39 02 3661 8300", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+390236618300", formatted_number);
test_number.set_national_number(345678901ULL);
test_number.set_italian_leading_zero(false);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("345 678 901", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+39 345 678 901", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+39345678901", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatAUNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(61);
test_number.set_national_number(236618300ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("02 3661 8300", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+61 2 3661 8300", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+61236618300", formatted_number);
test_number.set_national_number(1800123456ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("1800 123 456", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+61 1800 123 456", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+611800123456", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatARNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(54);
test_number.set_national_number(1187654321ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("011 8765-4321", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+54 11 8765-4321", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+541187654321", formatted_number);
test_number.set_national_number(91187654321ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("011 15 8765-4321", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+54 9 11 8765 4321", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+5491187654321", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatMXNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(52);
test_number.set_national_number(12345678900ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("045 234 567 8900", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+52 1 234 567 8900", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+5212345678900", formatted_number);
test_number.set_national_number(15512345678ULL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("045 55 1234 5678", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+52 1 55 1234 5678", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+5215512345678", formatted_number);
test_number.set_national_number(3312345678LL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("01 33 1234 5678", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+52 33 1234 5678", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+523312345678", formatted_number);
test_number.set_national_number(8211234567LL);
phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("01 821 123 4567", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+52 821 123 4567", formatted_number);
phone_util_.Format(test_number, PhoneNumberUtil::E164,
&formatted_number);
EXPECT_EQ("+528211234567", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatOutOfCountryCallingNumber) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(1);
test_number.set_national_number(9002530000ULL);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::DE(),
&formatted_number);
EXPECT_EQ("00 1 900 253 0000", formatted_number);
test_number.set_national_number(6502530000ULL);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::BS(),
&formatted_number);
EXPECT_EQ("1 650 253 0000", formatted_number);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::PL(),
&formatted_number);
EXPECT_EQ("00 1 650 253 0000", formatted_number);
test_number.set_country_code(44);
test_number.set_national_number(7912345678ULL);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("011 44 7912 345 678", formatted_number);
test_number.set_country_code(49);
test_number.set_national_number(1234ULL);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::GB(),
&formatted_number);
EXPECT_EQ("00 49 1234", formatted_number);
// Note this number is correctly formatted without national prefix. Most of
// the numbers that are treated as invalid numbers by the library are short
// numbers, and they are usually not dialed with national prefix.
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::DE(),
&formatted_number);
EXPECT_EQ("1234", formatted_number);
test_number.set_country_code(39);
test_number.set_national_number(236618300ULL);
test_number.set_italian_leading_zero(true);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("011 39 02 3661 8300", formatted_number);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::IT(),
&formatted_number);
EXPECT_EQ("02 3661 8300", formatted_number);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::SG(),
&formatted_number);
EXPECT_EQ("+39 02 3661 8300", formatted_number);
test_number.set_country_code(65);
test_number.set_national_number(94777892ULL);
test_number.set_italian_leading_zero(false);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::SG(),
&formatted_number);
EXPECT_EQ("9477 7892", formatted_number);
test_number.set_country_code(800);
test_number.set_national_number(12345678ULL);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("011 800 1234 5678", formatted_number);
test_number.set_country_code(54);
test_number.set_national_number(91187654321ULL);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("011 54 9 11 8765 4321", formatted_number);
test_number.set_extension("1234");
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("011 54 9 11 8765 4321 ext. 1234", formatted_number);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0011 54 9 11 8765 4321 ext. 1234", formatted_number);
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AR(),
&formatted_number);
EXPECT_EQ("011 15 8765-4321 ext. 1234", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatOutOfCountryWithInvalidRegion) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(1);
test_number.set_national_number(6502530000ULL);
// AQ/Antarctica isn't a valid region code for phone number formatting,
// so this falls back to intl formatting.
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AQ(),
&formatted_number);
EXPECT_EQ("+1 650 253 0000", formatted_number);
// For region code 001, the out-of-country format always turns into the
// international format.
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::UN001(),
&formatted_number);
EXPECT_EQ("+1 650 253 0000", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatOutOfCountryWithPreferredIntlPrefix) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(39);
test_number.set_national_number(236618300ULL);
test_number.set_italian_leading_zero(true);
// This should use 0011, since that is the preferred international prefix
// (both 0011 and 0012 are accepted as possible international prefixes in our
// test metadta.)
phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0011 39 02 3661 8300", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatOutOfCountryKeepingAlphaChars) {
PhoneNumber alpha_numeric_number;
string formatted_number;
alpha_numeric_number.set_country_code(1);
alpha_numeric_number.set_national_number(8007493524ULL);
alpha_numeric_number.set_raw_input("1800 six-flag");
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0011 1 800 SIX-FLAG", formatted_number);
formatted_number.clear();
alpha_numeric_number.set_raw_input("1-800-SIX-flag");
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0011 1 800-SIX-FLAG", formatted_number);
formatted_number.clear();
alpha_numeric_number.set_raw_input("Call us from UK: 00 1 800 SIX-flag");
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0011 1 800 SIX-FLAG", formatted_number);
formatted_number.clear();
alpha_numeric_number.set_raw_input("800 SIX-flag");
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0011 1 800 SIX-FLAG", formatted_number);
// Formatting from within the NANPA region.
formatted_number.clear();
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::US(),
&formatted_number);
EXPECT_EQ("1 800 SIX-FLAG", formatted_number);
formatted_number.clear();
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::BS(),
&formatted_number);
EXPECT_EQ("1 800 SIX-FLAG", formatted_number);
// Testing that if the raw input doesn't exist, it is formatted using
// FormatOutOfCountryCallingNumber.
alpha_numeric_number.clear_raw_input();
formatted_number.clear();
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::DE(),
&formatted_number);
EXPECT_EQ("00 1 800 749 3524", formatted_number);
// Testing AU alpha number formatted from Australia.
alpha_numeric_number.set_country_code(61);
alpha_numeric_number.set_national_number(827493524ULL);
alpha_numeric_number.set_raw_input("+61 82749-FLAG");
formatted_number.clear();
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
// This number should have the national prefix prefixed.
EXPECT_EQ("082749-FLAG", formatted_number);
alpha_numeric_number.set_raw_input("082749-FLAG");
formatted_number.clear();
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
EXPECT_EQ("082749-FLAG", formatted_number);
alpha_numeric_number.set_national_number(18007493524ULL);
alpha_numeric_number.set_raw_input("1-800-SIX-flag");
formatted_number.clear();
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
// This number should not have the national prefix prefixed, in accordance
// with the override for this specific formatting rule.
EXPECT_EQ("1-800-SIX-FLAG", formatted_number);
// The metadata should not be permanently changed, since we copied it before
// modifying patterns. Here we check this.
formatted_number.clear();
alpha_numeric_number.set_national_number(1800749352ULL);
phone_util_.FormatOutOfCountryCallingNumber(alpha_numeric_number,
RegionCode::AU(),
&formatted_number);
EXPECT_EQ("1800 749 352", formatted_number);
// Testing a country with multiple international prefixes.
formatted_number.clear();
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::SG(),
&formatted_number);
EXPECT_EQ("+61 1-800-SIX-FLAG", formatted_number);
// Testing the case of calling from a non-supported region.
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AQ(),
&formatted_number);
EXPECT_EQ("+61 1-800-SIX-FLAG", formatted_number);
// Testing the case with an invalid country code.
formatted_number.clear();
alpha_numeric_number.set_country_code(0);
alpha_numeric_number.set_national_number(18007493524ULL);
alpha_numeric_number.set_raw_input("1-800-SIX-flag");
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::DE(),
&formatted_number);
// Uses the raw input only.
EXPECT_EQ("1-800-SIX-flag", formatted_number);
// Testing the case of an invalid alpha number.
formatted_number.clear();
alpha_numeric_number.set_country_code(1);
alpha_numeric_number.set_national_number(80749ULL);
alpha_numeric_number.set_raw_input("180-SIX");
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::DE(),
&formatted_number);
// No country-code stripping can be done.
EXPECT_EQ("00 1 180-SIX", formatted_number);
// Testing the case of calling from a non-supported region.
phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number,
RegionCode::AQ(),
&formatted_number);
// No country-code stripping can be done since the number is invalid.
EXPECT_EQ("+1 180-SIX", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatWithCarrierCode) {
// We only support this for AR in our test metadata.
PhoneNumber ar_number;
string formatted_number;
ar_number.set_country_code(54);
ar_number.set_national_number(91234125678ULL);
phone_util_.Format(ar_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("01234 12-5678", formatted_number);
// Test formatting with a carrier code.
phone_util_.FormatNationalNumberWithCarrierCode(ar_number, "15",
&formatted_number);
EXPECT_EQ("01234 15 12-5678", formatted_number);
phone_util_.FormatNationalNumberWithCarrierCode(ar_number, "",
&formatted_number);
EXPECT_EQ("01234 12-5678", formatted_number);
// Here the international rule is used, so no carrier code should be present.
phone_util_.Format(ar_number, PhoneNumberUtil::E164, &formatted_number);
EXPECT_EQ("+5491234125678", formatted_number);
// We don't support this for the US so there should be no change.
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(4241231234ULL);
phone_util_.Format(us_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("424 123 1234", formatted_number);
phone_util_.FormatNationalNumberWithCarrierCode(us_number, "15",
&formatted_number);
EXPECT_EQ("424 123 1234", formatted_number);
// Invalid country code should just get the NSN.
PhoneNumber invalid_number;
invalid_number.set_country_code(kInvalidCountryCode);
invalid_number.set_national_number(12345ULL);
phone_util_.FormatNationalNumberWithCarrierCode(invalid_number, "89",
&formatted_number);
EXPECT_EQ("12345", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatWithPreferredCarrierCode) {
// We only support this for AR in our test metadata.
PhoneNumber ar_number;
string formatted_number;
ar_number.set_country_code(54);
ar_number.set_national_number(91234125678ULL);
// Test formatting with no preferred carrier code stored in the number itself.
phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15",
&formatted_number);
EXPECT_EQ("01234 15 12-5678", formatted_number);
phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "",
&formatted_number);
EXPECT_EQ("01234 12-5678", formatted_number);
// Test formatting with preferred carrier code present.
ar_number.set_preferred_domestic_carrier_code("19");
phone_util_.Format(ar_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("01234 12-5678", formatted_number);
phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15",
&formatted_number);
EXPECT_EQ("01234 19 12-5678", formatted_number);
phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "",
&formatted_number);
EXPECT_EQ("01234 19 12-5678", formatted_number);
// When the preferred_domestic_carrier_code is present (even when it is just a
// space), use it instead of the default carrier code passed in.
ar_number.set_preferred_domestic_carrier_code(" ");
phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15",
&formatted_number);
EXPECT_EQ("01234 12-5678", formatted_number);
// When the preferred_domestic_carrier_code is present but empty, treat it as
// unset and use instead the default carrier code passed in.
ar_number.set_preferred_domestic_carrier_code("");
phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15",
&formatted_number);
EXPECT_EQ("01234 15 12-5678", formatted_number);
// We don't support this for the US so there should be no change.
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(4241231234ULL);
us_number.set_preferred_domestic_carrier_code("99");
phone_util_.Format(us_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("424 123 1234", formatted_number);
phone_util_.FormatNationalNumberWithPreferredCarrierCode(us_number, "15",
&formatted_number);
EXPECT_EQ("424 123 1234", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatNumberForMobileDialing) {
PhoneNumber test_number;
string formatted_number;
// Numbers are normally dialed in national format in-country, and
// international format from outside the country.
test_number.set_country_code(49);
test_number.set_national_number(30123456ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::DE(), false, /* remove formatting */
&formatted_number);
EXPECT_EQ("030123456", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::CH(), false, /* remove formatting */
&formatted_number);
EXPECT_EQ("+4930123456", formatted_number);
test_number.set_extension("1234");
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::DE(), false, /* remove formatting */
&formatted_number);
EXPECT_EQ("030123456", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::CH(), false, /* remove formatting */
&formatted_number);
EXPECT_EQ("+4930123456", formatted_number);
test_number.set_country_code(1);
test_number.clear_extension();
// US toll free numbers are marked as noInternationalDialling in the test
// metadata for testing purposes. For such numbers, we expect nothing to be
// returned when the region code is not the same one.
test_number.set_national_number(8002530000ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), true, /* keep formatting */
&formatted_number);
EXPECT_EQ("800 253 0000", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::CN(), true, &formatted_number);
EXPECT_EQ("", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, /* remove formatting */
&formatted_number);
EXPECT_EQ("8002530000", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::CN(), false, &formatted_number);
EXPECT_EQ("", formatted_number);
test_number.set_national_number(6502530000ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), true, &formatted_number);
EXPECT_EQ("+1 650 253 0000", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("+16502530000", formatted_number);
test_number.set_extension("1234");
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), true, &formatted_number);
EXPECT_EQ("+1 650 253 0000", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("+16502530000", formatted_number);
// An invalid US number, which is one digit too long.
test_number.set_national_number(65025300001ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), true, &formatted_number);
EXPECT_EQ("+1 65025300001", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("+165025300001", formatted_number);
// Star numbers. In real life they appear in Israel, but we have them in JP
// in our test metadata.
test_number.set_country_code(81);
test_number.set_national_number(2345ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::JP(), true, &formatted_number);
EXPECT_EQ("*2345", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::JP(), false, &formatted_number);
EXPECT_EQ("*2345", formatted_number);
test_number.set_country_code(800);
test_number.set_national_number(12345678ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::JP(), false, &formatted_number);
EXPECT_EQ("+80012345678", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::JP(), true, &formatted_number);
EXPECT_EQ("+800 1234 5678", formatted_number);
// UAE numbers beginning with 600 (classified as UAN) need to be dialled
// without +971 locally.
test_number.set_country_code(971);
test_number.set_national_number(600123456ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::JP(), false, &formatted_number);
EXPECT_EQ("+971600123456", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::AE(), true, &formatted_number);
EXPECT_EQ("600123456", formatted_number);
test_number.set_country_code(52);
test_number.set_national_number(3312345678ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::MX(), false, &formatted_number);
EXPECT_EQ("+523312345678", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("+523312345678", formatted_number);
// Non-geographical numbers should always be dialed in international format.
test_number.set_country_code(800);
test_number.set_national_number(12345678ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("+80012345678", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::UN001(), false, &formatted_number);
EXPECT_EQ("+80012345678", formatted_number);
// Test that a short number is formatted correctly for mobile dialing within
// the region, and is not diallable from outside the region.
test_number.set_country_code(49);
test_number.set_national_number(123L);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::DE(), false, &formatted_number);
EXPECT_EQ("123", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::IT(), false, &formatted_number);
EXPECT_EQ("", formatted_number);
// Test the special logic for Hungary, where the national prefix must be
// added before dialing from a mobile phone for regular length numbers, but
// not for short numbers.
test_number.set_country_code(36);
test_number.set_national_number(301234567ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::HU(), false, &formatted_number);
EXPECT_EQ("06301234567", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::JP(), false, &formatted_number);
EXPECT_EQ("+36301234567", formatted_number);
test_number.set_national_number(104L);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::HU(), false, &formatted_number);
EXPECT_EQ("104", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::JP(), false, &formatted_number);
EXPECT_EQ("", formatted_number);
// Test the special logic for NANPA countries, for which regular length phone
// numbers are always output in international format, but short numbers are
// in national format.
test_number.set_country_code(1);
test_number.set_national_number(6502530000ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("+16502530000", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::CA(), false, &formatted_number);
EXPECT_EQ("+16502530000", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::BR(), false, &formatted_number);
EXPECT_EQ("+16502530000", formatted_number);
test_number.set_national_number(911L);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("911", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::CA(), false, &formatted_number);
EXPECT_EQ("", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::BR(), false, &formatted_number);
EXPECT_EQ("", formatted_number);
// Test that the Australian emergency number 000 is formatted correctly.
test_number.set_country_code(61);
test_number.set_national_number(0L);
test_number.set_italian_leading_zero(true);
test_number.set_number_of_leading_zeros(2);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::AU(), false, &formatted_number);
EXPECT_EQ("000", formatted_number);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::NZ(), false, &formatted_number);
EXPECT_EQ("", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatByPattern) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(1);
test_number.set_national_number(6502530000ULL);
RepeatedPtrField<NumberFormat> number_formats;
NumberFormat* number_format = number_formats.Add();
number_format->set_pattern("(\\d{3})(\\d{3})(\\d{4})");
number_format->set_format("($1) $2-$3");
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("(650) 253-0000", formatted_number);
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("+1 (650) 253-0000", formatted_number);
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::RFC3966,
number_formats,
&formatted_number);
EXPECT_EQ("tel:+1-650-253-0000", formatted_number);
// $NP is set to '1' for the US. Here we check that for other NANPA countries
// the US rules are followed.
number_format->set_national_prefix_formatting_rule("$NP ($FG)");
number_format->set_format("$1 $2-$3");
test_number.set_country_code(1);
test_number.set_national_number(4168819999ULL);
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("1 (416) 881-9999", formatted_number);
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("+1 416 881-9999", formatted_number);
test_number.set_country_code(39);
test_number.set_national_number(236618300ULL);
test_number.set_italian_leading_zero(true);
number_format->set_pattern("(\\d{2})(\\d{5})(\\d{3})");
number_format->set_format("$1-$2 $3");
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("02-36618 300", formatted_number);
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("+39 02-36618 300", formatted_number);
test_number.set_country_code(44);
test_number.set_national_number(2012345678ULL);
test_number.set_italian_leading_zero(false);
number_format->set_national_prefix_formatting_rule("$NP$FG");
number_format->set_pattern("(\\d{2})(\\d{4})(\\d{4})");
number_format->set_format("$1 $2 $3");
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("020 1234 5678", formatted_number);
number_format->set_national_prefix_formatting_rule("($NP$FG)");
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("(020) 1234 5678", formatted_number);
number_format->set_national_prefix_formatting_rule("");
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("20 1234 5678", formatted_number);
number_format->set_national_prefix_formatting_rule("");
phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL,
number_formats,
&formatted_number);
EXPECT_EQ("+44 20 1234 5678", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatE164Number) {
PhoneNumber test_number;
string formatted_number;
test_number.set_country_code(1);
test_number.set_national_number(6502530000ULL);
phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number);
EXPECT_EQ("+16502530000", formatted_number);
test_number.set_country_code(49);
test_number.set_national_number(301234ULL);
phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number);
EXPECT_EQ("+49301234", formatted_number);
test_number.set_country_code(800);
test_number.set_national_number(12345678ULL);
phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number);
EXPECT_EQ("+80012345678", formatted_number);
}
TEST_F(PhoneNumberUtilTest, FormatNumberWithExtension) {
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(33316005ULL);
nz_number.set_extension("1234");
string formatted_number;
// Uses default extension prefix:
phone_util_.Format(nz_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("03-331 6005 ext. 1234", formatted_number);
// Uses RFC 3966 syntax.
phone_util_.Format(nz_number, PhoneNumberUtil::RFC3966, &formatted_number);
EXPECT_EQ("tel:+64-3-331-6005;ext=1234", formatted_number);
// Extension prefix overridden in the territory information for the US:
PhoneNumber us_number_with_extension;
us_number_with_extension.set_country_code(1);
us_number_with_extension.set_national_number(6502530000ULL);
us_number_with_extension.set_extension("4567");
phone_util_.Format(us_number_with_extension,
PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("650 253 0000 extn. 4567", formatted_number);
}
TEST_F(PhoneNumberUtilTest, GetLengthOfGeographicalAreaCode) {
PhoneNumber number;
// Google MTV, which has area code "650".
number.set_country_code(1);
number.set_national_number(6502530000ULL);
EXPECT_EQ(3, phone_util_.GetLengthOfGeographicalAreaCode(number));
// A North America toll-free number, which has no area code.
number.set_country_code(1);
number.set_national_number(8002530000ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number));
// An invalid US number (1 digit shorter), which has no area code.
number.set_country_code(1);
number.set_national_number(650253000ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number));
// Google London, which has area code "20".
number.set_country_code(44);
number.set_national_number(2070313000ULL);
EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number));
// A mobile number in the UK does not have an area code (by default, mobile
// numbers do not, unless they have been added to our list of exceptions).
number.set_country_code(44);
number.set_national_number(7912345678ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number));
// Google Buenos Aires, which has area code "11".
number.set_country_code(54);
number.set_national_number(1155303000ULL);
EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number));
// A mobile number in Argentina also has an area code.
number.set_country_code(54);
number.set_national_number(91187654321ULL);
EXPECT_EQ(3, phone_util_.GetLengthOfGeographicalAreaCode(number));
// Google Sydney, which has area code "2".
number.set_country_code(61);
number.set_national_number(293744000ULL);
EXPECT_EQ(1, phone_util_.GetLengthOfGeographicalAreaCode(number));
// Italian numbers - there is no national prefix, but it still has an area
// code.
number.set_country_code(39);
number.set_national_number(236618300ULL);
number.set_italian_leading_zero(true);
EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number));
// Google Singapore. Singapore has no area code and no national prefix.
number.set_country_code(65);
number.set_national_number(65218000ULL);
number.set_italian_leading_zero(false);
EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number));
// An international toll free number, which has no area code.
number.set_country_code(800);
number.set_national_number(12345678ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number));
// A mobile number from China is geographical, but does not have an area code.
PhoneNumber cn_mobile;
cn_mobile.set_country_code(86);
cn_mobile.set_national_number(18912341234ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(cn_mobile));
}
TEST_F(PhoneNumberUtilTest, GetLengthOfNationalDestinationCode) {
PhoneNumber number;
// Google MTV, which has national destination code (NDC) "650".
number.set_country_code(1);
number.set_national_number(6502530000ULL);
EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number));
// A North America toll-free number, which has NDC "800".
number.set_country_code(1);
number.set_national_number(8002530000ULL);
EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number));
// Google London, which has NDC "20".
number.set_country_code(44);
number.set_national_number(2070313000ULL);
EXPECT_EQ(2, phone_util_.GetLengthOfNationalDestinationCode(number));
// A UK mobile phone, which has NDC "7912"
number.set_country_code(44);
number.set_national_number(7912345678ULL);
EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number));
// Google Buenos Aires, which has NDC "11".
number.set_country_code(54);
number.set_national_number(1155303000ULL);
EXPECT_EQ(2, phone_util_.GetLengthOfNationalDestinationCode(number));
// An Argentinian mobile which has NDC "911".
number.set_country_code(54);
number.set_national_number(91187654321ULL);
EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number));
// Google Sydney, which has NDC "2".
number.set_country_code(61);
number.set_national_number(293744000ULL);
EXPECT_EQ(1, phone_util_.GetLengthOfNationalDestinationCode(number));
// Google Singapore. Singapore has NDC "6521".
number.set_country_code(65);
number.set_national_number(65218000ULL);
EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number));
// An invalid US number (1 digit shorter), which has no NDC.
number.set_country_code(1);
number.set_national_number(650253000ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number));
// A number containing an invalid country code, which shouldn't have any NDC.
number.set_country_code(123);
number.set_national_number(650253000ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number));
// A number that has only one group of digits after country code when
// formatted in the international format.
number.set_country_code(376);
number.set_national_number(12345ULL);
EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number));
// The same number above, but with an extension.
number.set_country_code(376);
number.set_national_number(12345ULL);
number.set_extension("321");
EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number));
// An international toll free number, which has NDC "1234".
number.Clear();
number.set_country_code(800);
number.set_national_number(12345678ULL);
EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number));
// A mobile number from China is geographical, but does not have an area code:
// however it still can be considered to have a national destination code.
PhoneNumber cn_mobile;
cn_mobile.set_country_code(86);
cn_mobile.set_national_number(18912341234ULL);
EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(cn_mobile));
}
TEST_F(PhoneNumberUtilTest, GetCountryMobileToken) {
int country_calling_code;
string mobile_token;
country_calling_code = phone_util_.GetCountryCodeForRegion(RegionCode::MX());
phone_util_.GetCountryMobileToken(country_calling_code, &mobile_token);
EXPECT_EQ("1", mobile_token);
// Country calling code for Sweden, which has no mobile token.
country_calling_code = phone_util_.GetCountryCodeForRegion(RegionCode::SE());
phone_util_.GetCountryMobileToken(country_calling_code, &mobile_token);
EXPECT_EQ("", mobile_token);
}
TEST_F(PhoneNumberUtilTest, ExtractPossibleNumber) {
// Removes preceding funky punctuation and letters but leaves the rest
// untouched.
string extracted_number;
ExtractPossibleNumber("Tel:0800-345-600", &extracted_number);
EXPECT_EQ("0800-345-600", extracted_number);
ExtractPossibleNumber("Tel:0800 FOR PIZZA", &extracted_number);
EXPECT_EQ("0800 FOR PIZZA", extracted_number);
// Should not remove plus sign.
ExtractPossibleNumber("Tel:+800-345-600", &extracted_number);
EXPECT_EQ("+800-345-600", extracted_number);
// Should recognise wide digits as possible start values.
ExtractPossibleNumber("\xEF\xBC\x90\xEF\xBC\x92\xEF\xBC\x93" /* "023" */,
&extracted_number);
EXPECT_EQ("\xEF\xBC\x90\xEF\xBC\x92\xEF\xBC\x93" /* "023" */,
extracted_number);
// Dashes are not possible start values and should be removed.
ExtractPossibleNumber("Num-\xEF\xBC\x91\xEF\xBC\x92\xEF\xBC\x93"
/* "Num-123" */, &extracted_number);
EXPECT_EQ("\xEF\xBC\x91\xEF\xBC\x92\xEF\xBC\x93" /* "123" */,
extracted_number);
// If not possible number present, return empty string.
ExtractPossibleNumber("Num-....", &extracted_number);
EXPECT_EQ("", extracted_number);
// Leading brackets are stripped - these are not used when parsing.
ExtractPossibleNumber("(650) 253-0000", &extracted_number);
EXPECT_EQ("650) 253-0000", extracted_number);
// Trailing non-alpha-numeric characters should be removed.
ExtractPossibleNumber("(650) 253-0000..- ..", &extracted_number);
EXPECT_EQ("650) 253-0000", extracted_number);
ExtractPossibleNumber("(650) 253-0000.", &extracted_number);
EXPECT_EQ("650) 253-0000", extracted_number);
// This case has a trailing RTL char.
ExtractPossibleNumber("(650) 253-0000\xE2\x80\x8F"
/* "(650) 253-0000" */, &extracted_number);
EXPECT_EQ("650) 253-0000", extracted_number);
}
TEST_F(PhoneNumberUtilTest, IsNANPACountry) {
EXPECT_TRUE(phone_util_.IsNANPACountry(RegionCode::US()));
EXPECT_TRUE(phone_util_.IsNANPACountry(RegionCode::BS()));
EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::DE()));
EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::GetUnknown()));
EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::UN001()));
}
TEST_F(PhoneNumberUtilTest, IsValidNumber) {
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(6502530000ULL);
EXPECT_TRUE(phone_util_.IsValidNumber(us_number));
PhoneNumber it_number;
it_number.set_country_code(39);
it_number.set_national_number(236618300ULL);
it_number.set_italian_leading_zero(true);
EXPECT_TRUE(phone_util_.IsValidNumber(it_number));
PhoneNumber gb_number;
gb_number.set_country_code(44);
gb_number.set_national_number(7912345678ULL);
EXPECT_TRUE(phone_util_.IsValidNumber(gb_number));
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(21387835ULL);
EXPECT_TRUE(phone_util_.IsValidNumber(nz_number));
PhoneNumber intl_toll_free_number;
intl_toll_free_number.set_country_code(800);
intl_toll_free_number.set_national_number(12345678ULL);
EXPECT_TRUE(phone_util_.IsValidNumber(intl_toll_free_number));
PhoneNumber universal_premium_rate;
universal_premium_rate.set_country_code(979);
universal_premium_rate.set_national_number(123456789ULL);
EXPECT_TRUE(phone_util_.IsValidNumber(universal_premium_rate));
}
TEST_F(PhoneNumberUtilTest, IsValidForRegion) {
// This number is valid for the Bahamas, but is not a valid US number.
PhoneNumber bs_number;
bs_number.set_country_code(1);
bs_number.set_national_number(2423232345ULL);
EXPECT_TRUE(phone_util_.IsValidNumber(bs_number));
EXPECT_TRUE(phone_util_.IsValidNumberForRegion(bs_number, RegionCode::BS()));
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(bs_number, RegionCode::US()));
bs_number.set_national_number(2421232345ULL);
// This number is no longer valid.
EXPECT_FALSE(phone_util_.IsValidNumber(bs_number));
// La Mayotte and Réunion use 'leadingDigits' to differentiate them.
PhoneNumber re_number;
re_number.set_country_code(262);
re_number.set_national_number(262123456ULL);
EXPECT_TRUE(phone_util_.IsValidNumber(re_number));
EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE()));
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT()));
// Now change the number to be a number for La Mayotte.
re_number.set_national_number(269601234ULL);
EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT()));
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE()));
// This number is no longer valid.
re_number.set_national_number(269123456ULL);
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT()));
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE()));
EXPECT_FALSE(phone_util_.IsValidNumber(re_number));
// However, it should be recognised as from La Mayotte.
string region_code;
phone_util_.GetRegionCodeForNumber(re_number, ®ion_code);
EXPECT_EQ(RegionCode::YT(), region_code);
// This number is valid in both places.
re_number.set_national_number(800123456ULL);
EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT()));
EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE()));
PhoneNumber intl_toll_free_number;
intl_toll_free_number.set_country_code(800);
intl_toll_free_number.set_national_number(12345678ULL);
EXPECT_TRUE(phone_util_.IsValidNumberForRegion(intl_toll_free_number,
RegionCode::UN001()));
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(intl_toll_free_number,
RegionCode::US()));
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(intl_toll_free_number,
RegionCode::ZZ()));
PhoneNumber invalid_number;
// Invalid country calling codes.
invalid_number.set_country_code(3923);
invalid_number.set_national_number(2366ULL);
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number,
RegionCode::ZZ()));
invalid_number.set_country_code(3923);
invalid_number.set_national_number(2366ULL);
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number,
RegionCode::UN001()));
invalid_number.set_country_code(0);
invalid_number.set_national_number(2366ULL);
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number,
RegionCode::UN001()));
invalid_number.set_country_code(0);
EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number,
RegionCode::ZZ()));
}
TEST_F(PhoneNumberUtilTest, IsNotValidNumber) {
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(2530000ULL);
EXPECT_FALSE(phone_util_.IsValidNumber(us_number));
PhoneNumber it_number;
it_number.set_country_code(39);
it_number.set_national_number(23661830000ULL);
it_number.set_italian_leading_zero(true);
EXPECT_FALSE(phone_util_.IsValidNumber(it_number));
PhoneNumber gb_number;
gb_number.set_country_code(44);
gb_number.set_national_number(791234567ULL);
EXPECT_FALSE(phone_util_.IsValidNumber(gb_number));
PhoneNumber de_number;
de_number.set_country_code(49);
de_number.set_national_number(1234ULL);
EXPECT_FALSE(phone_util_.IsValidNumber(de_number));
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(3316005ULL);
EXPECT_FALSE(phone_util_.IsValidNumber(nz_number));
PhoneNumber invalid_number;
// Invalid country calling codes.
invalid_number.set_country_code(3923);
invalid_number.set_national_number(2366ULL);
EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number));
invalid_number.set_country_code(0);
EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number));
PhoneNumber intl_toll_free_number_too_long;
intl_toll_free_number_too_long.set_country_code(800);
intl_toll_free_number_too_long.set_national_number(123456789ULL);
EXPECT_FALSE(phone_util_.IsValidNumber(intl_toll_free_number_too_long));
}
TEST_F(PhoneNumberUtilTest, GetRegionCodeForCountryCode) {
string region_code;
phone_util_.GetRegionCodeForCountryCode(1, ®ion_code);
EXPECT_EQ(RegionCode::US(), region_code);
phone_util_.GetRegionCodeForCountryCode(44, ®ion_code);
EXPECT_EQ(RegionCode::GB(), region_code);
phone_util_.GetRegionCodeForCountryCode(49, ®ion_code);
EXPECT_EQ(RegionCode::DE(), region_code);
phone_util_.GetRegionCodeForCountryCode(800, ®ion_code);
EXPECT_EQ(RegionCode::UN001(), region_code);
phone_util_.GetRegionCodeForCountryCode(979, ®ion_code);
EXPECT_EQ(RegionCode::UN001(), region_code);
}
TEST_F(PhoneNumberUtilTest, GetRegionCodeForNumber) {
string region_code;
PhoneNumber bs_number;
bs_number.set_country_code(1);
bs_number.set_national_number(2423232345ULL);
phone_util_.GetRegionCodeForNumber(bs_number, ®ion_code);
EXPECT_EQ(RegionCode::BS(), region_code);
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(4241231234ULL);
phone_util_.GetRegionCodeForNumber(us_number, ®ion_code);
EXPECT_EQ(RegionCode::US(), region_code);
PhoneNumber gb_mobile;
gb_mobile.set_country_code(44);
gb_mobile.set_national_number(7912345678ULL);
phone_util_.GetRegionCodeForNumber(gb_mobile, ®ion_code);
EXPECT_EQ(RegionCode::GB(), region_code);
PhoneNumber intl_toll_free_number;
intl_toll_free_number.set_country_code(800);
intl_toll_free_number.set_national_number(12345678ULL);
phone_util_.GetRegionCodeForNumber(intl_toll_free_number, ®ion_code);
EXPECT_EQ(RegionCode::UN001(), region_code);
PhoneNumber universal_premium_rate;
universal_premium_rate.set_country_code(979);
universal_premium_rate.set_national_number(123456789ULL);
phone_util_.GetRegionCodeForNumber(universal_premium_rate, ®ion_code);
EXPECT_EQ(RegionCode::UN001(), region_code);
}
TEST_F(PhoneNumberUtilTest, IsPossibleNumber) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(6502530000ULL);
EXPECT_TRUE(phone_util_.IsPossibleNumber(number));
number.set_country_code(1);
number.set_national_number(2530000ULL);
EXPECT_TRUE(phone_util_.IsPossibleNumber(number));
number.set_country_code(44);
number.set_national_number(2070313000ULL);
EXPECT_TRUE(phone_util_.IsPossibleNumber(number));
number.set_country_code(800);
number.set_national_number(12345678ULL);
EXPECT_TRUE(phone_util_.IsPossibleNumber(number));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+1 650 253 0000",
RegionCode::US()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+1 650 GOO OGLE",
RegionCode::US()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("(650) 253-0000",
RegionCode::US()));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForString("253-0000", RegionCode::US()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+1 650 253 0000",
RegionCode::GB()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+44 20 7031 3000",
RegionCode::GB()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("(020) 7031 300",
RegionCode::GB()));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForString("7031 3000", RegionCode::GB()));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForString("3331 6005", RegionCode::NZ()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+800 1234 5678",
RegionCode::UN001()));
}
TEST_F(PhoneNumberUtilTest, IsPossibleNumberForType_DifferentTypeLengths) {
// We use Argentinian numbers since they have different possible lengths for
// different types.
PhoneNumber number;
number.set_country_code(54);
number.set_national_number(12345ULL);
// Too short for any Argentinian number, including fixed-line.
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
// 6-digit numbers are okay for fixed-line.
number.set_national_number(123456ULL);
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
// But too short for mobile.
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE));
// And too short for toll-free.
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE));
// The same applies to 9-digit numbers.
number.set_national_number(123456789ULL);
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE));
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE));
// 10-digit numbers are universally possible.
number.set_national_number(1234567890ULL);
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE));
// 11-digit numbers are only possible for mobile numbers. Note we don't
// require the leading 9, which all mobile numbers start with, and would be
// required for a valid mobile number.
number.set_national_number(12345678901ULL);
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE));
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE));
}
TEST_F(PhoneNumberUtilTest, IsPossibleNumberForType_LocalOnly) {
PhoneNumber number;
// Here we test a number length which matches a local-only length.
number.set_country_code(49);
number.set_national_number(12ULL);
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
// Mobile numbers must be 10 or 11 digits, and there are no local-only
// lengths.
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE));
}
TEST_F(PhoneNumberUtilTest, IsPossibleNumberForType_DataMissingForSizeReasons) {
PhoneNumber number;
// Here we test something where the possible lengths match the possible
// lengths of the country as a whole, and hence aren't present in the binary
// for size reasons - this should still work.
// Local-only number.
number.set_country_code(55);
number.set_national_number(12345678ULL);
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
number.set_national_number(1234567890ULL);
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN));
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
}
TEST_F(PhoneNumberUtilTest,
IsPossibleNumberForType_NumberTypeNotSupportedForRegion) {
PhoneNumber number;
// There are *no* mobile numbers for this region at all, so we return false.
number.set_country_code(55);
number.set_national_number(12345678L);
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE));
// This matches a fixed-line length though.
EXPECT_TRUE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
EXPECT_TRUE(phone_util_.IsPossibleNumberForType(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
// There are *no* fixed-line OR mobile numbers for this country calling code
// at all, so we return false for these.
number.set_country_code(979);
number.set_national_number(123456789L);
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE));
EXPECT_FALSE(
phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE));
EXPECT_FALSE(phone_util_.IsPossibleNumberForType(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
EXPECT_TRUE(phone_util_.IsPossibleNumberForType(
number, PhoneNumberUtil::PREMIUM_RATE));
}
TEST_F(PhoneNumberUtilTest, IsPossibleNumberWithReason) {
// FYI, national numbers for country code +1 that are within 7 to 10 digits
// are possible.
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(6502530000ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(1);
number.set_national_number(2530000ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(0);
number.set_national_number(2530000ULL);
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(1);
number.set_national_number(253000ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(1);
number.set_national_number(65025300000ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(44);
number.set_national_number(2070310000ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(49);
number.set_national_number(30123456ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(65);
number.set_national_number(1234567890ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberWithReason(number));
number.set_country_code(800);
number.set_national_number(123456789ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberWithReason(number));
}
TEST_F(PhoneNumberUtilTest,
IsPossibleNumberForTypeWithReason_DifferentTypeLengths) {
// We use Argentinian numbers since they have different possible lengths for
// different types.
PhoneNumber number;
number.set_country_code(54);
number.set_national_number(12345ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
// 6-digit numbers are okay for fixed-line.
number.set_national_number(123456ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
// But too short for mobile.
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
// And too short for toll-free.
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::TOLL_FREE));
// The same applies to 9-digit numbers.
number.set_national_number(123456789ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::TOLL_FREE));
// 10-digit numbers are universally possible.
number.set_national_number(1234567890ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::TOLL_FREE));
// 11-digit numbers are possible for mobile numbers. Note we don't require the
// leading 9, which all mobile numbers start with, and would be required for a
// valid mobile number.
number.set_national_number(12345678901ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::TOLL_FREE));
}
TEST_F(PhoneNumberUtilTest, IsPossibleNumberForTypeWithReason_LocalOnly) {
PhoneNumber number;
// Here we test a number length which matches a local-only length.
number.set_country_code(49);
number.set_national_number(12ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
// Mobile numbers must be 10 or 11 digits, and there are no local-only
// lengths.
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
}
TEST_F(PhoneNumberUtilTest,
IsPossibleNumberForTypeWithReason_DataMissingForSizeReasons) {
PhoneNumber number;
// Here we test something where the possible lengths match the possible
// lengths of the country as a whole, and hence aren't present in the binary
// for size reasons - this should still work.
// Local-only number.
number.set_country_code(55);
number.set_national_number(12345678ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
// Normal-length number.
number.set_national_number(1234567890ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::UNKNOWN));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
}
TEST_F(PhoneNumberUtilTest,
IsPossibleNumberForTypeWithReason_NumberTypeNotSupportedForRegion) {
PhoneNumber number;
// There are *no* mobile numbers for this region at all, so we return
// INVALID_LENGTH.
number.set_country_code(55);
number.set_national_number(12345678ULL);
EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
// This matches a fixed-line length though.
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
// This is too short for fixed-line, and no mobile numbers exist.
number.set_national_number(1234567ULL);
EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
// This is too short for mobile, and no fixed-line number exist.
number.set_country_code(882);
number.set_national_number(1234567ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
// There are *no* fixed-line OR mobile numbers for this country calling code
// at all, so we return INVALID_LENGTH.
number.set_country_code(979);
number.set_national_number(123456789ULL);
EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::PREMIUM_RATE));
}
TEST_F(PhoneNumberUtilTest,
IsPossibleNumberForTypeWithReason_FixedLineOrMobile) {
PhoneNumber number;
// For FIXED_LINE_OR_MOBILE, a number should be considered valid if it matches
// the possible lengths for mobile *or* fixed-line numbers.
number.set_country_code(290);
number.set_national_number(1234ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
number.set_national_number(12345ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
number.set_national_number(123456ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
number.set_national_number(1234567ULL);
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE));
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::MOBILE));
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
number.set_national_number(12345678ULL);
EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::TOLL_FREE));
EXPECT_EQ(PhoneNumberUtil::TOO_LONG,
phone_util_.IsPossibleNumberForTypeWithReason(
number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE));
}
TEST_F(PhoneNumberUtilTest, IsNotPossibleNumber) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(65025300000ULL);
EXPECT_FALSE(phone_util_.IsPossibleNumber(number));
number.set_country_code(800);
number.set_national_number(123456789ULL);
EXPECT_FALSE(phone_util_.IsPossibleNumber(number));
number.set_country_code(1);
number.set_national_number(253000ULL);
EXPECT_FALSE(phone_util_.IsPossibleNumber(number));
number.set_country_code(44);
number.set_national_number(300ULL);
EXPECT_FALSE(phone_util_.IsPossibleNumber(number));
EXPECT_FALSE(phone_util_.IsPossibleNumberForString("+1 650 253 00000",
RegionCode::US()));
EXPECT_FALSE(phone_util_.IsPossibleNumberForString("(650) 253-00000",
RegionCode::US()));
EXPECT_FALSE(phone_util_.IsPossibleNumberForString("I want a Pizza",
RegionCode::US()));
EXPECT_FALSE(phone_util_.IsPossibleNumberForString("253-000",
RegionCode::US()));
EXPECT_FALSE(phone_util_.IsPossibleNumberForString("1 3000",
RegionCode::GB()));
EXPECT_FALSE(phone_util_.IsPossibleNumberForString("+44 300",
RegionCode::GB()));
EXPECT_FALSE(phone_util_.IsPossibleNumberForString("+800 1234 5678 9",
RegionCode::UN001()));
}
TEST_F(PhoneNumberUtilTest, TruncateTooLongNumber) {
// US number 650-253-0000, but entered with one additional digit at the end.
PhoneNumber too_long_number;
too_long_number.set_country_code(1);
too_long_number.set_national_number(65025300001ULL);
PhoneNumber valid_number;
valid_number.set_country_code(1);
valid_number.set_national_number(6502530000ULL);
EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number));
EXPECT_EQ(valid_number, too_long_number);
too_long_number.set_country_code(800);
too_long_number.set_national_number(123456789ULL);
valid_number.set_country_code(800);
valid_number.set_national_number(12345678ULL);
EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number));
EXPECT_EQ(valid_number, too_long_number);
// GB number 080 1234 5678, but entered with 4 extra digits at the end.
too_long_number.set_country_code(44);
too_long_number.set_national_number(80123456780123ULL);
valid_number.set_country_code(44);
valid_number.set_national_number(8012345678ULL);
EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number));
EXPECT_EQ(valid_number, too_long_number);
// IT number 022 3456 7890, but entered with 3 extra digits at the end.
too_long_number.set_country_code(39);
too_long_number.set_national_number(2234567890123ULL);
too_long_number.set_italian_leading_zero(true);
valid_number.set_country_code(39);
valid_number.set_national_number(2234567890ULL);
valid_number.set_italian_leading_zero(true);
EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number));
EXPECT_EQ(valid_number, too_long_number);
// Tests what happens when a valid number is passed in.
PhoneNumber valid_number_copy(valid_number);
EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&valid_number));
// Tests the number is not modified.
EXPECT_EQ(valid_number_copy, valid_number);
// Tests what happens when a number with invalid prefix is passed in.
PhoneNumber number_with_invalid_prefix;
number_with_invalid_prefix.set_country_code(1);
// The test metadata says US numbers cannot have prefix 240.
number_with_invalid_prefix.set_national_number(2401234567ULL);
PhoneNumber invalid_number_copy(number_with_invalid_prefix);
EXPECT_FALSE(phone_util_.TruncateTooLongNumber(&number_with_invalid_prefix));
// Tests the number is not modified.
EXPECT_EQ(invalid_number_copy, number_with_invalid_prefix);
// Tests what happens when a too short number is passed in.
PhoneNumber too_short_number;
too_short_number.set_country_code(1);
too_short_number.set_national_number(1234ULL);
PhoneNumber too_short_number_copy(too_short_number);
EXPECT_FALSE(phone_util_.TruncateTooLongNumber(&too_short_number));
// Tests the number is not modified.
EXPECT_EQ(too_short_number_copy, too_short_number);
}
TEST_F(PhoneNumberUtilTest, IsNumberGeographical) {
PhoneNumber number;
// Bahamas, mobile phone number.
number.set_country_code(1);
number.set_national_number(2423570000ULL);
EXPECT_FALSE(phone_util_.IsNumberGeographical(number));
// Australian fixed line number.
number.set_country_code(61);
number.set_national_number(236618300ULL);
EXPECT_TRUE(phone_util_.IsNumberGeographical(number));
// International toll free number.
number.set_country_code(800);
number.set_national_number(12345678ULL);
EXPECT_FALSE(phone_util_.IsNumberGeographical(number));
// We test that mobile phone numbers in relevant regions are indeed considered
// geographical.
// Argentina, mobile phone number.
number.set_country_code(54);
number.set_national_number(91187654321ULL);
EXPECT_TRUE(phone_util_.IsNumberGeographical(number));
// Mexico, mobile phone number.
number.set_country_code(52);
number.set_national_number(12345678900ULL);
EXPECT_TRUE(phone_util_.IsNumberGeographical(number));
// Mexico, another mobile phone number.
number.set_country_code(52);
number.set_national_number(15512345678ULL);
EXPECT_TRUE(phone_util_.IsNumberGeographical(number));
}
TEST_F(PhoneNumberUtilTest, FormatInOriginalFormat) {
PhoneNumber phone_number;
string formatted_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("+442087654321", RegionCode::GB(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(),
&formatted_number);
EXPECT_EQ("+44 20 8765 4321", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("02087654321", RegionCode::GB(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(),
&formatted_number);
EXPECT_EQ("(020) 8765 4321", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("011442087654321",
RegionCode::US(), &phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("011 44 20 8765 4321", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("442087654321", RegionCode::GB(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(),
&formatted_number);
EXPECT_EQ("44 20 8765 4321", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+442087654321", RegionCode::GB(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(),
&formatted_number);
EXPECT_EQ("(020) 8765 4321", formatted_number);
// Invalid numbers that we have a formatting pattern for should be formatted
// properly. Note area codes starting with 7 are intentionally excluded in
// the test metadata for testing purposes.
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("7345678901", RegionCode::US(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("734 567 8901", formatted_number);
// US is not a leading zero country, and the presence of the leading zero
// leads us to format the number using raw_input.
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("0734567 8901", RegionCode::US(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("0734567 8901", formatted_number);
// This number is valid, but we don't have a formatting pattern for it. Fall
// back to the raw input.
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("02-4567-8900", RegionCode::KR(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::KR(),
&formatted_number);
EXPECT_EQ("02-4567-8900", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("01180012345678",
RegionCode::US(), &phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("011 800 1234 5678", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("+80012345678", RegionCode::KR(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::KR(),
&formatted_number);
EXPECT_EQ("+800 1234 5678", formatted_number);
// US local numbers are formatted correctly, as we have formatting patterns
// for them.
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("2530000", RegionCode::US(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("253 0000", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Number with national prefix in the US.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("18003456789", RegionCode::US(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("1 800 345 6789", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Number without national prefix in the UK.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("2087654321", RegionCode::GB(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(),
&formatted_number);
EXPECT_EQ("20 8765 4321", formatted_number);
// Make sure no metadata is modified as a result of the previous function
// call.
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+442087654321", RegionCode::GB(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(),
&formatted_number);
EXPECT_EQ("(020) 8765 4321", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Number with national prefix in Mexico.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("013312345678", RegionCode::MX(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(),
&formatted_number);
EXPECT_EQ("01 33 1234 5678", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Number without national prefix in Mexico.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("3312345678", RegionCode::MX(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(),
&formatted_number);
EXPECT_EQ("33 1234 5678", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Italian fixed-line number.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("0212345678", RegionCode::IT(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::IT(),
&formatted_number);
EXPECT_EQ("02 1234 5678", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Number with national prefix in Japan.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("00777012", RegionCode::JP(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(),
&formatted_number);
EXPECT_EQ("0077-7012", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Number without national prefix in Japan.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("0777012", RegionCode::JP(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(),
&formatted_number);
EXPECT_EQ("0777012", formatted_number);
phone_number.Clear();
formatted_number.clear();
// Number with carrier code in Brazil.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("012 3121286979", RegionCode::BR(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::BR(),
&formatted_number);
EXPECT_EQ("012 3121286979", formatted_number);
phone_number.Clear();
formatted_number.clear();
// The default national prefix used in this case is 045. When a number with
// national prefix 044 is entered, we return the raw input as we don't want to
// change the number entered.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("044(33)1234-5678",
RegionCode::MX(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(),
&formatted_number);
EXPECT_EQ("044(33)1234-5678", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("045(33)1234-5678",
RegionCode::MX(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(),
&formatted_number);
EXPECT_EQ("045 33 1234 5678", formatted_number);
// The default international prefix used in this case is 0011. When a number
// with international prefix 0012 is entered, we return the raw input as we
// don't want to change the number entered.
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("0012 16502530000",
RegionCode::AU(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0012 16502530000", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("0011 16502530000",
RegionCode::AU(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::AU(),
&formatted_number);
EXPECT_EQ("0011 1 650 253 0000", formatted_number);
// Test the star sign is not removed from or added to the original input by
// this method.
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("*1234",
RegionCode::JP(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(),
&formatted_number);
EXPECT_EQ("*1234", formatted_number);
phone_number.Clear();
formatted_number.clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("1234",
RegionCode::JP(),
&phone_number));
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(),
&formatted_number);
EXPECT_EQ("1234", formatted_number);
// Test that an invalid national number without raw input is just formatted
// as the national number.
phone_number.Clear();
formatted_number.clear();
phone_number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY);
phone_number.set_country_code(1);
phone_number.set_national_number(650253000ULL);
phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(),
&formatted_number);
EXPECT_EQ("650253000", formatted_number);
}
TEST_F(PhoneNumberUtilTest, IsPremiumRate) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(9004433030ULL);
EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number));
number.set_country_code(39);
number.set_national_number(892123ULL);
EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number));
number.set_country_code(44);
number.set_national_number(9187654321ULL);
EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number));
number.set_country_code(49);
number.set_national_number(9001654321ULL);
EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number));
number.set_country_code(49);
number.set_national_number(90091234567ULL);
EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number));
number.set_country_code(979);
number.set_national_number(123456789ULL);
EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsTollFree) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(8881234567ULL);
EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number));
number.set_country_code(39);
number.set_national_number(803123ULL);
EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number));
number.set_country_code(44);
number.set_national_number(8012345678ULL);
EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number));
number.set_country_code(49);
number.set_national_number(8001234567ULL);
EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number));
number.set_country_code(800);
number.set_national_number(12345678ULL);
EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsMobile) {
PhoneNumber number;
// A Bahama mobile number
number.set_country_code(1);
number.set_national_number(2423570000ULL);
EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number));
number.set_country_code(39);
number.set_national_number(312345678ULL);
EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number));
number.set_country_code(44);
number.set_national_number(7912345678ULL);
EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number));
number.set_country_code(49);
number.set_national_number(15123456789ULL);
EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number));
number.set_country_code(54);
number.set_national_number(91187654321ULL);
EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsFixedLine) {
PhoneNumber number;
// A Bahama fixed-line number
number.set_country_code(1);
number.set_national_number(2423651234ULL);
EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number));
// An Italian fixed-line number
number.Clear();
number.set_country_code(39);
number.set_national_number(236618300ULL);
number.set_italian_leading_zero(true);
EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number));
number.Clear();
number.set_country_code(44);
number.set_national_number(2012345678ULL);
EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number));
number.set_country_code(49);
number.set_national_number(301234ULL);
EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsFixedLineAndMobile) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(6502531111ULL);
EXPECT_EQ(PhoneNumberUtil::FIXED_LINE_OR_MOBILE,
phone_util_.GetNumberType(number));
number.set_country_code(54);
number.set_national_number(1987654321ULL);
EXPECT_EQ(PhoneNumberUtil::FIXED_LINE_OR_MOBILE,
phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsSharedCost) {
PhoneNumber number;
number.set_country_code(44);
number.set_national_number(8431231234ULL);
EXPECT_EQ(PhoneNumberUtil::SHARED_COST, phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsVoip) {
PhoneNumber number;
number.set_country_code(44);
number.set_national_number(5631231234ULL);
EXPECT_EQ(PhoneNumberUtil::VOIP, phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsPersonalNumber) {
PhoneNumber number;
number.set_country_code(44);
number.set_national_number(7031231234ULL);
EXPECT_EQ(PhoneNumberUtil::PERSONAL_NUMBER,
phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, IsUnknown) {
PhoneNumber number;
number.set_country_code(1);
number.set_national_number(65025311111ULL);
EXPECT_EQ(PhoneNumberUtil::UNKNOWN, phone_util_.GetNumberType(number));
}
TEST_F(PhoneNumberUtilTest, GetCountryCodeForRegion) {
EXPECT_EQ(1, phone_util_.GetCountryCodeForRegion(RegionCode::US()));
EXPECT_EQ(64, phone_util_.GetCountryCodeForRegion(RegionCode::NZ()));
EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::GetUnknown()));
EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::UN001()));
// CS is already deprecated so the library doesn't support it.
EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::CS()));
}
TEST_F(PhoneNumberUtilTest, GetNationalDiallingPrefixForRegion) {
string ndd_prefix;
phone_util_.GetNddPrefixForRegion(RegionCode::US(), false, &ndd_prefix);
EXPECT_EQ("1", ndd_prefix);
// Test non-main country to see it gets the national dialling prefix for the
// main country with that country calling code.
ndd_prefix.clear();
phone_util_.GetNddPrefixForRegion(RegionCode::BS(), false, &ndd_prefix);
EXPECT_EQ("1", ndd_prefix);
ndd_prefix.clear();
phone_util_.GetNddPrefixForRegion(RegionCode::NZ(), false, &ndd_prefix);
EXPECT_EQ("0", ndd_prefix);
ndd_prefix.clear();
// Test case with non digit in the national prefix.
phone_util_.GetNddPrefixForRegion(RegionCode::AO(), false, &ndd_prefix);
EXPECT_EQ("0~0", ndd_prefix);
ndd_prefix.clear();
phone_util_.GetNddPrefixForRegion(RegionCode::AO(), true, &ndd_prefix);
EXPECT_EQ("00", ndd_prefix);
// Test cases with invalid regions.
ndd_prefix.clear();
phone_util_.GetNddPrefixForRegion(RegionCode::GetUnknown(), false,
&ndd_prefix);
EXPECT_EQ("", ndd_prefix);
ndd_prefix.clear();
phone_util_.GetNddPrefixForRegion(RegionCode::UN001(), false, &ndd_prefix);
EXPECT_EQ("", ndd_prefix);
// CS is already deprecated so the library doesn't support it.
ndd_prefix.clear();
phone_util_.GetNddPrefixForRegion(RegionCode::CS(), false, &ndd_prefix);
EXPECT_EQ("", ndd_prefix);
}
TEST_F(PhoneNumberUtilTest, IsViablePhoneNumber) {
EXPECT_FALSE(IsViablePhoneNumber("1"));
// Only one or two digits before strange non-possible punctuation.
EXPECT_FALSE(IsViablePhoneNumber("1+1+1"));
EXPECT_FALSE(IsViablePhoneNumber("80+0"));
// Two digits is viable.
EXPECT_TRUE(IsViablePhoneNumber("00"));
EXPECT_TRUE(IsViablePhoneNumber("111"));
// Alpha numbers.
EXPECT_TRUE(IsViablePhoneNumber("0800-4-pizza"));
EXPECT_TRUE(IsViablePhoneNumber("0800-4-PIZZA"));
// We need at least three digits before any alpha characters.
EXPECT_FALSE(IsViablePhoneNumber("08-PIZZA"));
EXPECT_FALSE(IsViablePhoneNumber("8-PIZZA"));
EXPECT_FALSE(IsViablePhoneNumber("12. March"));
}
TEST_F(PhoneNumberUtilTest, IsViablePhoneNumberNonAscii) {
// Only one or two digits before possible punctuation followed by more digits.
// The punctuation used here is the unicode character u+3000.
EXPECT_TRUE(IsViablePhoneNumber("1\xE3\x80\x80" "34" /* "1 34" */));
EXPECT_FALSE(IsViablePhoneNumber("1\xE3\x80\x80" "3+4" /* "1 3+4" */));
// Unicode variants of possible starting character and other allowed
// punctuation/digits.
EXPECT_TRUE(IsViablePhoneNumber("\xEF\xBC\x88" "1\xEF\xBC\x89\xE3\x80\x80"
"3456789" /* "(1) 3456789" */));
// Testing a leading + is okay.
EXPECT_TRUE(IsViablePhoneNumber("+1\xEF\xBC\x89\xE3\x80\x80"
"3456789" /* "+1) 3456789" */));
}
TEST_F(PhoneNumberUtilTest, ConvertAlphaCharactersInNumber) {
string input("1800-ABC-DEF");
phone_util_.ConvertAlphaCharactersInNumber(&input);
// Alpha chars are converted to digits; everything else is left untouched.
static const string kExpectedOutput = "1800-222-333";
EXPECT_EQ(kExpectedOutput, input);
// Try with some non-ASCII characters.
input.assign("1\xE3\x80\x80\xEF\xBC\x88" "800) ABC-DEF"
/* "1 (800) ABC-DEF" */);
static const string kExpectedFullwidthOutput =
"1\xE3\x80\x80\xEF\xBC\x88" "800) 222-333" /* "1 (800) 222-333" */;
phone_util_.ConvertAlphaCharactersInNumber(&input);
EXPECT_EQ(kExpectedFullwidthOutput, input);
}
TEST_F(PhoneNumberUtilTest, NormaliseRemovePunctuation) {
string input_number("034-56&+#2" "\xC2\xAD" "34");
Normalize(&input_number);
static const string kExpectedOutput("03456234");
EXPECT_EQ(kExpectedOutput, input_number)
<< "Conversion did not correctly remove punctuation";
}
TEST_F(PhoneNumberUtilTest, NormaliseReplaceAlphaCharacters) {
string input_number("034-I-am-HUNGRY");
Normalize(&input_number);
static const string kExpectedOutput("034426486479");
EXPECT_EQ(kExpectedOutput, input_number)
<< "Conversion did not correctly replace alpha characters";
}
TEST_F(PhoneNumberUtilTest, NormaliseOtherDigits) {
// The first digit is a full-width 2, the last digit is an Arabic-indic digit
// 5.
string input_number("\xEF\xBC\x92" "5\xD9\xA5" /* "25٥" */);
Normalize(&input_number);
static const string kExpectedOutput("255");
EXPECT_EQ(kExpectedOutput, input_number)
<< "Conversion did not correctly replace non-latin digits";
// The first digit is an Eastern-Arabic 5, the latter an Eastern-Arabic 0.
string eastern_arabic_input_number("\xDB\xB5" "2\xDB\xB0" /* "۵2۰" */);
Normalize(&eastern_arabic_input_number);
static const string kExpectedOutput2("520");
EXPECT_EQ(kExpectedOutput2, eastern_arabic_input_number)
<< "Conversion did not correctly replace non-latin digits";
}
TEST_F(PhoneNumberUtilTest, NormaliseStripAlphaCharacters) {
string input_number("034-56&+a#234");
phone_util_.NormalizeDigitsOnly(&input_number);
static const string kExpectedOutput("03456234");
EXPECT_EQ(kExpectedOutput, input_number)
<< "Conversion did not correctly remove alpha characters";
}
TEST_F(PhoneNumberUtilTest, NormaliseStripNonDiallableCharacters) {
string input_number("03*4-56&+1a#234");
phone_util_.NormalizeDiallableCharsOnly(&input_number);
static const string kExpectedOutput("03*456+1#234");
EXPECT_EQ(kExpectedOutput, input_number)
<< "Conversion did not correctly remove non-diallable characters";
}
TEST_F(PhoneNumberUtilTest, MaybeStripInternationalPrefix) {
string international_prefix("00[39]");
string number_to_strip("0034567700-3898003");
// Note the dash is removed as part of the normalization.
string stripped_number("45677003898003");
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
EXPECT_EQ(stripped_number, number_to_strip)
<< "The number was not stripped of its international prefix.";
// Now the number no longer starts with an IDD prefix, so it should now report
// FROM_DEFAULT_COUNTRY.
EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
number_to_strip.assign("00945677003898003");
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
EXPECT_EQ(stripped_number, number_to_strip)
<< "The number was not stripped of its international prefix.";
// Test it works when the international prefix is broken up by spaces.
number_to_strip.assign("00 9 45677003898003");
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
EXPECT_EQ(stripped_number, number_to_strip)
<< "The number was not stripped of its international prefix.";
// Now the number no longer starts with an IDD prefix, so it should now report
// FROM_DEFAULT_COUNTRY.
EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
// Test the + symbol is also recognised and stripped.
number_to_strip.assign("+45677003898003");
stripped_number.assign("45677003898003");
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
EXPECT_EQ(stripped_number, number_to_strip)
<< "The number supplied was not stripped of the plus symbol.";
// If the number afterwards is a zero, we should not strip this - no country
// code begins with 0.
number_to_strip.assign("0090112-3123");
stripped_number.assign("00901123123");
EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
EXPECT_EQ(stripped_number, number_to_strip)
<< "The number had a 0 after the match so shouldn't be stripped.";
// Here the 0 is separated by a space from the IDD.
number_to_strip.assign("009 0-112-3123");
EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY,
MaybeStripInternationalPrefixAndNormalize(international_prefix,
&number_to_strip));
}
TEST_F(PhoneNumberUtilTest, MaybeStripNationalPrefixAndCarrierCode) {
PhoneMetadata metadata;
metadata.set_national_prefix_for_parsing("34");
metadata.mutable_general_desc()->set_national_number_pattern("\\d{4,8}");
string number_to_strip("34356778");
string stripped_number("356778");
string carrier_code;
MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip,
&carrier_code);
EXPECT_EQ(stripped_number, number_to_strip)
<< "Should have had national prefix stripped.";
EXPECT_EQ("", carrier_code) << "Should have had no carrier code stripped.";
// Retry stripping - now the number should not start with the national prefix,
// so no more stripping should occur.
MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip,
&carrier_code);
EXPECT_EQ(stripped_number, number_to_strip)
<< "Should have had no change - no national prefix present.";
// Some countries have no national prefix. Repeat test with none specified.
metadata.clear_national_prefix_for_parsing();
MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip,
&carrier_code);
EXPECT_EQ(stripped_number, number_to_strip)
<< "Should have had no change - empty national prefix.";
// If the resultant number doesn't match the national rule, it shouldn't be
// stripped.
metadata.set_national_prefix_for_parsing("3");
number_to_strip.assign("3123");
stripped_number.assign("3123");
MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip,
&carrier_code);
EXPECT_EQ(stripped_number, number_to_strip)
<< "Should have had no change - after stripping, it wouldn't have "
<< "matched the national rule.";
// Test extracting carrier selection code.
metadata.set_national_prefix_for_parsing("0(81)?");
number_to_strip.assign("08122123456");
stripped_number.assign("22123456");
MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip,
&carrier_code);
EXPECT_EQ("81", carrier_code) << "Should have had carrier code stripped.";
EXPECT_EQ(stripped_number, number_to_strip)
<< "Should have had national prefix and carrier code stripped.";
// If there was a transform rule, check it was applied.
metadata.set_national_prefix_transform_rule("5$15");
// Note that a capturing group is present here.
metadata.set_national_prefix_for_parsing("0(\\d{2})");
number_to_strip.assign("031123");
string transformed_number("5315123");
MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip,
&carrier_code);
EXPECT_EQ(transformed_number, number_to_strip)
<< "Was not successfully transformed.";
}
TEST_F(PhoneNumberUtilTest, MaybeStripExtension) {
// One with extension.
string number("1234576 ext. 1234");
string extension;
string expected_extension("1234");
string stripped_number("1234576");
EXPECT_TRUE(MaybeStripExtension(&number, &extension));
EXPECT_EQ(stripped_number, number);
EXPECT_EQ(expected_extension, extension);
// One without extension.
number.assign("1234-576");
extension.clear();
stripped_number.assign("1234-576");
EXPECT_FALSE(MaybeStripExtension(&number, &extension));
EXPECT_EQ(stripped_number, number);
EXPECT_TRUE(extension.empty());
// One with an extension caught by the second capturing group in
// kKnownExtnPatterns.
number.assign("1234576-123#");
extension.clear();
expected_extension.assign("123");
stripped_number.assign("1234576");
EXPECT_TRUE(MaybeStripExtension(&number, &extension));
EXPECT_EQ(stripped_number, number);
EXPECT_EQ(expected_extension, extension);
number.assign("1234576 ext.123#");
extension.clear();
EXPECT_TRUE(MaybeStripExtension(&number, &extension));
EXPECT_EQ(stripped_number, number);
EXPECT_EQ(expected_extension, extension);
}
TEST_F(PhoneNumberUtilTest, MaybeExtractCountryCode) {
PhoneNumber number;
const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::US());
// Note that for the US, the IDD is 011.
string phone_number("011112-3456789");
string stripped_number("123456789");
int expected_country_code = 1;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, true, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, number.country_code_source());
EXPECT_EQ(stripped_number, phone_number);
number.Clear();
phone_number.assign("+80012345678");
stripped_number.assign("12345678");
expected_country_code = 800;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, true, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN,
number.country_code_source());
EXPECT_EQ(stripped_number, phone_number);
number.Clear();
phone_number.assign("+6423456789");
stripped_number.assign("23456789");
expected_country_code = 64;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, true, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN,
number.country_code_source());
EXPECT_EQ(stripped_number, phone_number);
// Should not have extracted a country code - no international prefix present.
number.Clear();
expected_country_code = 0;
phone_number.assign("2345-6789");
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, true, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, number.country_code_source());
EXPECT_EQ(stripped_number, phone_number);
expected_country_code = 0;
phone_number.assign("0119991123456789");
stripped_number.assign(phone_number);
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
MaybeExtractCountryCode(metadata, true, &phone_number, &number));
number.Clear();
phone_number.assign("(1 610) 619 4466");
stripped_number.assign("6106194466");
expected_country_code = 1;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, true, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN,
number.country_code_source());
EXPECT_EQ(stripped_number, phone_number);
number.Clear();
phone_number.assign("(1 610) 619 4466");
stripped_number.assign("6106194466");
expected_country_code = 1;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, false, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_FALSE(number.has_country_code_source());
EXPECT_EQ(stripped_number, phone_number);
// Should not have extracted a country code - invalid number after extraction
// of uncertain country code.
number.Clear();
phone_number.assign("(1 610) 619 446");
stripped_number.assign("1610619446");
expected_country_code = 0;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, false, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_FALSE(number.has_country_code_source());
EXPECT_EQ(stripped_number, phone_number);
number.Clear();
phone_number.assign("(1 610) 619");
stripped_number.assign("1610619");
expected_country_code = 0;
// Should not have extracted a country code - invalid number both before and
// after extraction of uncertain country code.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
MaybeExtractCountryCode(metadata, true, &phone_number, &number));
EXPECT_EQ(expected_country_code, number.country_code());
EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, number.country_code_source());
EXPECT_EQ(stripped_number, phone_number);
}
TEST_F(PhoneNumberUtilTest, CountryWithNoNumberDesc) {
string formatted_number;
// Andorra is a country where we don't have PhoneNumberDesc info in the
// metadata.
PhoneNumber ad_number;
ad_number.set_country_code(376);
ad_number.set_national_number(12345ULL);
phone_util_.Format(ad_number, PhoneNumberUtil::INTERNATIONAL,
&formatted_number);
EXPECT_EQ("+376 12345", formatted_number);
phone_util_.Format(ad_number, PhoneNumberUtil::E164, &formatted_number);
EXPECT_EQ("+37612345", formatted_number);
phone_util_.Format(ad_number, PhoneNumberUtil::NATIONAL, &formatted_number);
EXPECT_EQ("12345", formatted_number);
EXPECT_EQ(PhoneNumberUtil::UNKNOWN, phone_util_.GetNumberType(ad_number));
EXPECT_FALSE(phone_util_.IsValidNumber(ad_number));
// Test dialing a US number from within Andorra.
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(6502530000ULL);
phone_util_.FormatOutOfCountryCallingNumber(us_number, RegionCode::AD(),
&formatted_number);
EXPECT_EQ("00 1 650 253 0000", formatted_number);
}
TEST_F(PhoneNumberUtilTest, UnknownCountryCallingCode) {
PhoneNumber invalid_number;
invalid_number.set_country_code(kInvalidCountryCode);
invalid_number.set_national_number(12345ULL);
EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number));
// It's not very well defined as to what the E164 representation for a number
// with an invalid country calling code is, but just prefixing the country
// code and national number is about the best we can do.
string formatted_number;
phone_util_.Format(invalid_number, PhoneNumberUtil::E164, &formatted_number);
EXPECT_EQ("+212345", formatted_number);
}
TEST_F(PhoneNumberUtilTest, IsNumberMatchMatches) {
// Test simple matches where formatting is different, or leading zeros, or
// country code has been specified.
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331 6005",
"+64 03 331 6005"));
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+800 1234 5678",
"+80012345678"));
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 03 331-6005",
"+64 03331 6005"));
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+643 331-6005",
"+64033316005"));
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+643 331-6005",
"+6433316005"));
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005",
"+6433316005"));
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings(
"+64 3 331-6005", "tel:+64-3-331-6005;isub=123"));
// Test alpha numbers.
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+1800 siX-Flags",
"+1 800 7493 5247"));
// Test numbers with extensions.
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 extn 1234",
"+6433316005#1234"));
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 extn 1234",
"+6433316005;1234"));
// Test proto buffers.
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(33316005ULL);
nz_number.set_extension("3456");
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithOneString(nz_number,
"+643 331 6005 ext 3456"));
nz_number.clear_extension();
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithOneString(nz_number,
"+643 331 6005"));
// Check empty extensions are ignored.
nz_number.set_extension("");
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatchWithOneString(nz_number,
"+643 331 6005"));
// Check variant with two proto buffers.
PhoneNumber nz_number_2;
nz_number_2.set_country_code(64);
nz_number_2.set_national_number(33316005ULL);
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatch(nz_number, nz_number_2));
}
TEST_F(PhoneNumberUtilTest, IsNumberMatchShortMatchIfDiffNumLeadingZeros) {
PhoneNumber nz_number_one;
nz_number_one.set_country_code(64);
nz_number_one.set_national_number(33316005ULL);
nz_number_one.set_italian_leading_zero(true);
PhoneNumber nz_number_two;
nz_number_two.set_country_code(64);
nz_number_two.set_national_number(33316005ULL);
nz_number_two.set_italian_leading_zero(true);
nz_number_two.set_number_of_leading_zeros(2);
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatch(nz_number_one, nz_number_two));
nz_number_one.set_italian_leading_zero(false);
nz_number_one.set_number_of_leading_zeros(1);
nz_number_two.set_italian_leading_zero(true);
nz_number_two.set_number_of_leading_zeros(1);
// Since one doesn't have the "italian_leading_zero" set to true, we ignore
// the number of leading zeros present (1 is in any case the default value).
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatch(nz_number_one, nz_number_two));
}
TEST_F(PhoneNumberUtilTest, IsNumberMatchAcceptsProtoDefaultsAsMatch) {
PhoneNumber nz_number_one;
nz_number_one.set_country_code(64);
nz_number_one.set_national_number(33316005ULL);
nz_number_one.set_italian_leading_zero(true);
PhoneNumber nz_number_two;
nz_number_two.set_country_code(64);
nz_number_two.set_national_number(33316005ULL);
nz_number_two.set_italian_leading_zero(true);
// The default for number_of_leading_zeros is 1, so it shouldn't normally be
// set, however if it is it should be considered equivalent.
nz_number_two.set_number_of_leading_zeros(1);
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatch(nz_number_one, nz_number_two));
}
TEST_F(PhoneNumberUtilTest,
IsNumberMatchMatchesDiffLeadingZerosIfItalianLeadingZeroFalse) {
PhoneNumber nz_number_one;
nz_number_one.set_country_code(64);
nz_number_one.set_national_number(33316005ULL);
PhoneNumber nz_number_two;
nz_number_two.set_country_code(64);
nz_number_two.set_national_number(33316005ULL);
// The default for number_of_leading_zeros is 1, so it shouldn't normally be
// set, however if it is it should be considered equivalent.
nz_number_two.set_number_of_leading_zeros(1);
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatch(nz_number_one, nz_number_two));
// Even if it is set to ten, it is still equivalent because in both cases
// italian_leading_zero is not true.
nz_number_two.set_number_of_leading_zeros(10);
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatch(nz_number_one, nz_number_two));
}
TEST_F(PhoneNumberUtilTest, IsNumberMatchIgnoresSomeFields) {
// Check raw_input, country_code_source and preferred_domestic_carrier_code
// are ignored.
PhoneNumber br_number_1;
PhoneNumber br_number_2;
br_number_1.set_country_code(55);
br_number_1.set_national_number(3121286979ULL);
br_number_1.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN);
br_number_1.set_preferred_domestic_carrier_code("12");
br_number_1.set_raw_input("012 3121286979");
br_number_2.set_country_code(55);
br_number_2.set_national_number(3121286979ULL);
br_number_2.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY);
br_number_2.set_preferred_domestic_carrier_code("14");
br_number_2.set_raw_input("143121286979");
EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH,
phone_util_.IsNumberMatch(br_number_1, br_number_2));
}
TEST_F(PhoneNumberUtilTest, IsNumberMatchNonMatches) {
// NSN matches.
EXPECT_EQ(PhoneNumberUtil::NO_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("03 331 6005",
"03 331 6006"));
EXPECT_EQ(PhoneNumberUtil::NO_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+800 1234 5678",
"+1 800 1234 5678"));
// Different country code, partial number match.
EXPECT_EQ(PhoneNumberUtil::NO_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005",
"+16433316005"));
// Different country code, same number.
EXPECT_EQ(PhoneNumberUtil::NO_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005",
"+6133316005"));
// Extension different, all else the same.
EXPECT_EQ(PhoneNumberUtil::NO_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 extn 1234",
"+0116433316005#1235"));
EXPECT_EQ(PhoneNumberUtil::NO_MATCH,
phone_util_.IsNumberMatchWithTwoStrings(
"+64 3 331-6005 extn 1234", "tel:+64-3-331-6005;ext=1235"));
// NSN matches, but extension is different - not the same number.
EXPECT_EQ(PhoneNumberUtil::NO_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 ext.1235",
"3 331 6005#1234"));
// Invalid numbers that can't be parsed.
EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER,
phone_util_.IsNumberMatchWithTwoStrings("4", "3 331 6043"));
// Invalid numbers that can't be parsed.
EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER,
phone_util_.IsNumberMatchWithTwoStrings("+43", "+64 3 331 6005"));
EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER,
phone_util_.IsNumberMatchWithTwoStrings("+43", "64 3 331 6005"));
EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER,
phone_util_.IsNumberMatchWithTwoStrings("Dog", "64 3 331 6005"));
}
TEST_F(PhoneNumberUtilTest, IsNumberMatchNsnMatches) {
// NSN matches.
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005",
"03 331 6005"));
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings(
"+64 3 331-6005",
"tel:03-331-6005;isub=1234;phone-context=abc.nz"));
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(33316005ULL);
nz_number.set_extension("");
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithOneString(nz_number, "03 331 6005"));
// Here the second number possibly starts with the country code for New
// Zealand, although we are unsure.
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithOneString(nz_number,
"(64-3) 331 6005"));
// Here, the 1 might be a national prefix, if we compare it to the US number,
// so the resultant match is an NSN match.
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(2345678901ULL);
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithOneString(us_number,
"1-234-567-8901"));
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithOneString(us_number, "2345678901"));
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+1 234-567 8901",
"1 234 567 8901"));
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("1 234-567 8901",
"1 234 567 8901"));
EXPECT_EQ(PhoneNumberUtil::NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("1 234-567 8901",
"+1 234 567 8901"));
// For this case, the match will be a short NSN match, because we cannot
// assume that the 1 might be a national prefix, so don't remove it when
// parsing.
PhoneNumber random_number;
random_number.set_country_code(41);
random_number.set_national_number(2345678901ULL);
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithOneString(random_number,
"1-234-567-8901"));
}
TEST_F(PhoneNumberUtilTest, IsNumberMatchShortNsnMatches) {
// Short NSN matches with the country not specified for either one or both
// numbers.
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005",
"331 6005"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings(
"+64 3 331-6005", "tel:331-6005;phone-context=abc.nz"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings(
"+64 3 331-6005",
"tel:331-6005;isub=1234;phone-context=abc.nz"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings(
"+64 3 331-6005",
"tel:331-6005;isub=1234;phone-context=abc.nz;a=%A1"));
// We did not know that the "0" was a national prefix since neither number has
// a country code, so this is considered a SHORT_NSN_MATCH.
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("3 331-6005",
"03 331 6005"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("3 331-6005",
"331 6005"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings(
"3 331-6005", "tel:331-6005;phone-context=abc.nz"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("3 331-6005",
"+64 331 6005"));
// Short NSN match with the country specified.
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("03 331-6005",
"331 6005"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("1 234 345 6789",
"345 6789"));
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+1 (234) 345 6789",
"345 6789"));
// NSN matches, country code omitted for one number, extension missing for
// one.
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005",
"3 331 6005#1234"));
// One has Italian leading zero, one does not.
PhoneNumber it_number_1, it_number_2;
it_number_1.set_country_code(39);
it_number_1.set_national_number(1234ULL);
it_number_1.set_italian_leading_zero(true);
it_number_2.set_country_code(39);
it_number_2.set_national_number(1234ULL);
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatch(it_number_1, it_number_2));
// One has an extension, the other has an extension of "".
it_number_1.set_extension("1234");
it_number_1.clear_italian_leading_zero();
it_number_2.set_extension("");
EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH,
phone_util_.IsNumberMatch(it_number_1, it_number_2));
}
TEST_F(PhoneNumberUtilTest, ParseNationalNumber) {
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(33316005ULL);
PhoneNumber test_number;
// National prefix attached.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("033316005", RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
// Some fields are not filled in by Parse, but only by ParseAndKeepRawInput.
EXPECT_FALSE(nz_number.has_country_code_source());
EXPECT_EQ(PhoneNumber::UNSPECIFIED, nz_number.country_code_source());
// National prefix missing.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("33316005", RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
// National prefix attached and some formatting present.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03-331 6005", RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03 331 6005", RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
// Test parsing RFC3966 format with a phone context.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:03-331-6005;phone-context=+64",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:331-6005;phone-context=+64-3",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:331-6005;phone-context=+64-3",
RegionCode::US(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("My number is tel:03-331-6005;phone-context=+64",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
// Test parsing RFC3966 format with optional user-defined parameters. The
// parameters will appear after the context if present.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:03-331-6005;phone-context=+64;a=%A1",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
// Test parsing RFC3966 with an ISDN subaddress.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:03-331-6005;isub=12345;phone-context=+64",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:+64-3-331-6005;isub=12345",
RegionCode::US(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03-331-6005;phone-context=+64",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
// Testing international prefixes.
// Should strip country code.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0064 3 331 6005",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
// Try again, but this time we have an international number with Region Code
// US. It should recognise the country code and parse accordingly.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("01164 3 331 6005",
RegionCode::US(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+64 3 331 6005",
RegionCode::US(), &test_number));
EXPECT_EQ(nz_number, test_number);
// We should ignore the leading plus here, since it is not followed by a valid
// country code but instead is followed by the IDD for the US.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+01164 3 331 6005",
RegionCode::US(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+0064 3 331 6005",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+ 00 64 3 331 6005",
RegionCode::NZ(), &test_number));
EXPECT_EQ(nz_number, test_number);
PhoneNumber us_local_number;
us_local_number.set_country_code(1);
us_local_number.set_national_number(2530000ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:253-0000;phone-context=www.google.com",
RegionCode::US(), &test_number));
EXPECT_EQ(us_local_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse(
"tel:253-0000;isub=12345;phone-context=www.google.com",
RegionCode::US(), &test_number));
EXPECT_EQ(us_local_number, test_number);
// This is invalid because no "+" sign is present as part of phone-context.
// The phone context is simply ignored in this case just as if it contains a
// domain.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:2530000;isub=12345;phone-context=1-650",
RegionCode::US(), &test_number));
EXPECT_EQ(us_local_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:2530000;isub=12345;phone-context=1234.com",
RegionCode::US(), &test_number));
EXPECT_EQ(us_local_number, test_number);
// Test for http://b/issue?id=2247493
nz_number.Clear();
nz_number.set_country_code(64);
nz_number.set_national_number(64123456ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+64(0)64123456",
RegionCode::US(), &test_number));
EXPECT_EQ(nz_number, test_number);
// Check that using a "/" is fine in a phone number.
PhoneNumber de_number;
de_number.set_country_code(49);
de_number.set_national_number(12345678ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("123/45678", RegionCode::DE(), &test_number));
EXPECT_EQ(de_number, test_number);
PhoneNumber us_number;
us_number.set_country_code(1);
// Check it doesn't use the '1' as a country code when parsing if the phone
// number was already possible.
us_number.set_national_number(1234567890ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("123-456-7890", RegionCode::US(), &test_number));
EXPECT_EQ(us_number, test_number);
// Test star numbers. Although this is not strictly valid, we would like to
// make sure we can parse the output we produce when formatting the number.
PhoneNumber star_number;
star_number.set_country_code(81);
star_number.set_national_number(2345ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+81 *2345", RegionCode::JP(), &test_number));
EXPECT_EQ(star_number, test_number);
PhoneNumber short_number;
short_number.set_country_code(64);
short_number.set_national_number(12ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("12", RegionCode::NZ(), &test_number));
EXPECT_EQ(short_number, test_number);
// Test for short-code with leading zero for a country which has 0 as
// national prefix. Ensure it's not interpreted as national prefix if the
// remaining number length is local-only in terms of length. Example: In GB,
// length 6-7 are only possible local-only.
short_number.set_country_code(44);
short_number.set_national_number(123456);
short_number.set_italian_leading_zero(true);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0123456", RegionCode::GB(), &test_number));
EXPECT_EQ(short_number, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseNumberWithAlphaCharacters) {
// Test case with alpha characters.
PhoneNumber test_number;
PhoneNumber tollfree_number;
tollfree_number.set_country_code(64);
tollfree_number.set_national_number(800332005ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0800 DDA 005", RegionCode::NZ(), &test_number));
EXPECT_EQ(tollfree_number, test_number);
PhoneNumber premium_number;
premium_number.set_country_code(64);
premium_number.set_national_number(9003326005ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0900 DDA 6005", RegionCode::NZ(), &test_number));
EXPECT_EQ(premium_number, test_number);
// Not enough alpha characters for them to be considered intentional, so they
// are stripped.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0900 332 6005a",
RegionCode::NZ(), &test_number));
EXPECT_EQ(premium_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0900 332 600a5",
RegionCode::NZ(), &test_number));
EXPECT_EQ(premium_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0900 332 600A5",
RegionCode::NZ(), &test_number));
EXPECT_EQ(premium_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0900 a332 600A5",
RegionCode::NZ(), &test_number));
EXPECT_EQ(premium_number, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseWithInternationalPrefixes) {
PhoneNumber us_number;
us_number.set_country_code(1);
us_number.set_national_number(6503336000ULL);
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+1 (650) 333-6000",
RegionCode::US(), &test_number));
EXPECT_EQ(us_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+1-650-333-6000",
RegionCode::US(), &test_number));
EXPECT_EQ(us_number, test_number);
// Calling the US number from Singapore by using different service providers
// 1st test: calling using SingTel IDD service (IDD is 001)
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0011-650-333-6000",
RegionCode::SG(), &test_number));
EXPECT_EQ(us_number, test_number);
// 2nd test: calling using StarHub IDD service (IDD is 008)
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0081-650-333-6000",
RegionCode::SG(), &test_number));
EXPECT_EQ(us_number, test_number);
// 3rd test: calling using SingTel V019 service (IDD is 019)
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0191-650-333-6000",
RegionCode::SG(), &test_number));
EXPECT_EQ(us_number, test_number);
// Calling the US number from Poland
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0~01-650-333-6000",
RegionCode::PL(), &test_number));
EXPECT_EQ(us_number, test_number);
// Using "++" at the start.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("++1 (650) 333-6000",
RegionCode::PL(), &test_number));
EXPECT_EQ(us_number, test_number);
// Using a full-width plus sign.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("\xEF\xBC\x8B" "1 (650) 333-6000",
/* "+1 (650) 333-6000" */
RegionCode::SG(), &test_number));
EXPECT_EQ(us_number, test_number);
// Using a soft hyphen U+00AD.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("1 (650) 333" "\xC2\xAD" "-6000",
/* "1 (650) 333-6000" */
RegionCode::US(), &test_number));
EXPECT_EQ(us_number, test_number);
// The whole number, including punctuation, is here represented in full-width
// form.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88"
"\xEF\xBC\x96\xEF\xBC\x95\xEF\xBC\x90\xEF\xBC\x89"
"\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93"
"\xEF\xBC\x8D\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90"
"\xEF\xBC\x90",
/* "+1 (650) 333-6000" */
RegionCode::SG(), &test_number));
EXPECT_EQ(us_number, test_number);
// Using the U+30FC dash.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88"
"\xEF\xBC\x96\xEF\xBC\x95\xEF\xBC\x90\xEF\xBC\x89"
"\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93"
"\xE3\x83\xBC\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90"
"\xEF\xBC\x90",
/* "+1 (650) 333ー6000" */
RegionCode::SG(), &test_number));
EXPECT_EQ(us_number, test_number);
PhoneNumber toll_free_number;
toll_free_number.set_country_code(800);
toll_free_number.set_national_number(12345678ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("011 800 1234 5678",
RegionCode::US(), &test_number));
EXPECT_EQ(toll_free_number, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseWithLeadingZero) {
PhoneNumber it_number;
it_number.set_country_code(39);
it_number.set_national_number(236618300ULL);
it_number.set_italian_leading_zero(true);
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+39 02-36618 300",
RegionCode::NZ(), &test_number));
EXPECT_EQ(it_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("02-36618 300", RegionCode::IT(), &test_number));
EXPECT_EQ(it_number, test_number);
it_number.Clear();
it_number.set_country_code(39);
it_number.set_national_number(312345678ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("312 345 678", RegionCode::IT(), &test_number));
EXPECT_EQ(it_number, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseNationalNumberArgentina) {
// Test parsing mobile numbers of Argentina.
PhoneNumber ar_number;
ar_number.set_country_code(54);
ar_number.set_national_number(93435551212ULL);
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+54 9 343 555 1212", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0343 15 555 1212", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
ar_number.set_national_number(93715654320ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+54 9 3715 65 4320", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03715 15 65 4320", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
// Test parsing fixed-line numbers of Argentina.
ar_number.set_national_number(1137970000ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+54 11 3797 0000", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("011 3797 0000", RegionCode::AR(), &test_number));
EXPECT_EQ(ar_number, test_number);
ar_number.set_national_number(3715654321ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+54 3715 65 4321", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03715 65 4321", RegionCode::AR(), &test_number));
EXPECT_EQ(ar_number, test_number);
ar_number.set_national_number(2312340000ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+54 23 1234 0000", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("023 1234 0000", RegionCode::AR(), &test_number));
EXPECT_EQ(ar_number, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseWithXInNumber) {
// Test that having an 'x' in the phone number at the start is ok and that it
// just gets removed.
PhoneNumber ar_number;
ar_number.set_country_code(54);
ar_number.set_national_number(123456789ULL);
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0123456789", RegionCode::AR(), &test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(0) 123456789", RegionCode::AR(), &test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0 123456789", RegionCode::AR(), &test_number));
EXPECT_EQ(ar_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(0xx) 123456789", RegionCode::AR(),
&test_number));
EXPECT_EQ(ar_number, test_number);
PhoneNumber ar_from_us;
ar_from_us.set_country_code(54);
ar_from_us.set_national_number(81429712ULL);
// This test is intentionally constructed such that the number of digit after
// xx is larger than 7, so that the number won't be mistakenly treated as an
// extension, as we allow extensions up to 7 digits. This assumption is okay
// for now as all the countries where a carrier selection code is written in
// the form of xx have a national significant number of length larger than 7.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("011xx5481429712", RegionCode::US(),
&test_number));
EXPECT_EQ(ar_from_us, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseNumbersMexico) {
// Test parsing fixed-line numbers of Mexico.
PhoneNumber mx_number;
mx_number.set_country_code(52);
mx_number.set_national_number(4499780001ULL);
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+52 (449)978-0001", RegionCode::MX(),
&test_number));
EXPECT_EQ(mx_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("01 (449)978-0001", RegionCode::MX(),
&test_number));
EXPECT_EQ(mx_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(449)978-0001", RegionCode::MX(),
&test_number));
EXPECT_EQ(mx_number, test_number);
// Test parsing mobile numbers of Mexico.
mx_number.Clear();
mx_number.set_country_code(52);
mx_number.set_national_number(13312345678ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+52 1 33 1234-5678", RegionCode::MX(),
&test_number));
EXPECT_EQ(mx_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("044 (33) 1234-5678", RegionCode::MX(),
&test_number));
EXPECT_EQ(mx_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("045 33 1234-5678", RegionCode::MX(),
&test_number));
EXPECT_EQ(mx_number, test_number);
}
TEST_F(PhoneNumberUtilTest, FailedParseOnInvalidNumbers) {
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse("This is not a phone number", RegionCode::NZ(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse("1 Still not a number", RegionCode::NZ(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse("1 MICROSOFT", RegionCode::NZ(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse("12 MICROSOFT", RegionCode::NZ(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::TOO_LONG_NSN,
phone_util_.Parse("01495 72553301873 810104", RegionCode::GB(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse("+---", RegionCode::DE(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse("+***", RegionCode::DE(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse("+*******91", RegionCode::DE(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_NSN,
phone_util_.Parse("+49 0", RegionCode::DE(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
phone_util_.Parse("+210 3456 56789", RegionCode::NZ(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
// 00 is a correct IDD, but 210 is not a valid country code.
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
phone_util_.Parse("+ 00 210 3 331 6005", RegionCode::NZ(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
phone_util_.Parse("123 456 7890", RegionCode::GetUnknown(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
phone_util_.Parse("123 456 7890", RegionCode::CS(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD,
phone_util_.Parse("0044-----", RegionCode::GB(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD,
phone_util_.Parse("0044", RegionCode::GB(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD,
phone_util_.Parse("011", RegionCode::US(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD,
phone_util_.Parse("0119", RegionCode::US(),
&test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
// RFC3966 phone-context is a website.
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
phone_util_.Parse("tel:555-1234;phone-context=www.google.com",
RegionCode::ZZ(), &test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
// This is invalid because no "+" sign is present as part of phone-context.
// This should not succeed in being parsed.
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
phone_util_.Parse("tel:555-1234;phone-context=1-331",
RegionCode::ZZ(), &test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
// Only the phone-context symbol is present, but no data.
EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER,
phone_util_.Parse(";phone-context=",
RegionCode::ZZ(), &test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
}
TEST_F(PhoneNumberUtilTest, ParseNumbersWithPlusWithNoRegion) {
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(33316005ULL);
// RegionCode::GetUnknown() is allowed only if the number starts with a '+' -
// then the country code can be calculated.
PhoneNumber result_proto;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+64 3 331 6005", RegionCode::GetUnknown(),
&result_proto));
EXPECT_EQ(nz_number, result_proto);
// Test with full-width plus.
result_proto.Clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("\xEF\xBC\x8B" "64 3 331 6005",
/* "+64 3 331 6005" */
RegionCode::GetUnknown(), &result_proto));
EXPECT_EQ(nz_number, result_proto);
// Test with normal plus but leading characters that need to be stripped.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse(" +64 3 331 6005", RegionCode::GetUnknown(),
&result_proto));
EXPECT_EQ(nz_number, result_proto);
PhoneNumber toll_free_number;
toll_free_number.set_country_code(800);
toll_free_number.set_national_number(12345678ULL);
result_proto.Clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+800 1234 5678",
RegionCode::GetUnknown(), &result_proto));
EXPECT_EQ(toll_free_number, result_proto);
PhoneNumber universal_premium_rate;
universal_premium_rate.set_country_code(979);
universal_premium_rate.set_national_number(123456789ULL);
result_proto.Clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+979 123 456 789",
RegionCode::GetUnknown(), &result_proto));
EXPECT_EQ(universal_premium_rate, result_proto);
result_proto.Clear();
// Test parsing RFC3966 format with a phone context.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:03-331-6005;phone-context=+64",
RegionCode::GetUnknown(), &result_proto));
EXPECT_EQ(nz_number, result_proto);
result_proto.Clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse(" tel:03-331-6005;phone-context=+64",
RegionCode::GetUnknown(), &result_proto));
EXPECT_EQ(nz_number, result_proto);
result_proto.Clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:03-331-6005;isub=12345;phone-context=+64",
RegionCode::GetUnknown(), &result_proto));
EXPECT_EQ(nz_number, result_proto);
nz_number.set_raw_input("+64 3 331 6005");
nz_number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN);
result_proto.Clear();
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("+64 3 331 6005",
RegionCode::GetUnknown(),
&result_proto));
EXPECT_EQ(nz_number, result_proto);
}
TEST_F(PhoneNumberUtilTest, ParseNumberTooShortIfNationalPrefixStripped) {
PhoneNumber test_number;
// Test that a number whose first digits happen to coincide with the national
// prefix does not get them stripped if doing so would result in a number too
// short to be a possible (regular length) phone number for that region.
PhoneNumber by_number;
by_number.set_country_code(375);
by_number.set_national_number(8123L);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("8123", RegionCode::BY(),
&test_number));
EXPECT_EQ(by_number, test_number);
by_number.set_national_number(81234L);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("81234", RegionCode::BY(),
&test_number));
EXPECT_EQ(by_number, test_number);
// The prefix doesn't get stripped, since the input is a viable 6-digit
// number, whereas the result of stripping is only 5 digits.
by_number.set_national_number(812345L);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("812345", RegionCode::BY(),
&test_number));
EXPECT_EQ(by_number, test_number);
// The prefix gets stripped, since only 6-digit numbers are possible.
by_number.set_national_number(123456L);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("8123456", RegionCode::BY(),
&test_number));
EXPECT_EQ(by_number, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseExtensions) {
PhoneNumber nz_number;
nz_number.set_country_code(64);
nz_number.set_national_number(33316005ULL);
nz_number.set_extension("3456");
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03 331 6005 ext 3456", RegionCode::NZ(),
&test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03 331 6005x3456", RegionCode::NZ(),
&test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03-331 6005 int.3456", RegionCode::NZ(),
&test_number));
EXPECT_EQ(nz_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("03 331 6005 #3456", RegionCode::NZ(),
&test_number));
EXPECT_EQ(nz_number, test_number);
// Test the following do not extract extensions:
PhoneNumber non_extn_number;
non_extn_number.set_country_code(1);
non_extn_number.set_national_number(80074935247ULL);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("1800 six-flags", RegionCode::US(),
&test_number));
EXPECT_EQ(non_extn_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("1800 SIX-FLAGS", RegionCode::US(),
&test_number));
EXPECT_EQ(non_extn_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0~0 1800 7493 5247", RegionCode::PL(),
&test_number));
EXPECT_EQ(non_extn_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(1800) 7493.5247", RegionCode::US(),
&test_number));
EXPECT_EQ(non_extn_number, test_number);
// Check that the last instance of an extension token is matched.
PhoneNumber extn_number;
extn_number.set_country_code(1);
extn_number.set_national_number(80074935247ULL);
extn_number.set_extension("1234");
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0~0 1800 7493 5247 ~1234", RegionCode::PL(),
&test_number));
EXPECT_EQ(extn_number, test_number);
// Verifying bug-fix where the last digit of a number was previously omitted
// if it was a 0 when extracting the extension. Also verifying a few different
// cases of extensions.
PhoneNumber uk_number;
uk_number.set_country_code(44);
uk_number.set_national_number(2034567890ULL);
uk_number.set_extension("456");
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890x456", RegionCode::NZ(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890x456", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890 x456", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890 X456", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890 X 456", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890 X 456", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890 x 456 ", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44 2034567890 X 456", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44-2034567890;ext=456", RegionCode::GB(),
&test_number));
EXPECT_EQ(uk_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("tel:2034567890;ext=456;phone-context=+44",
RegionCode::ZZ(), &test_number));
EXPECT_EQ(uk_number, test_number);
// Full-width extension, "extn" only.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse(
"+442034567890\xEF\xBD\x85\xEF\xBD\x98\xEF\xBD\x94\xEF\xBD\x8E"
"456", RegionCode::GB(), &test_number));
EXPECT_EQ(uk_number, test_number);
// "xtn" only.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse(
"+44-2034567890\xEF\xBD\x98\xEF\xBD\x94\xEF\xBD\x8E""456",
RegionCode::GB(), &test_number));
EXPECT_EQ(uk_number, test_number);
// "xt" only.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+44-2034567890\xEF\xBD\x98\xEF\xBD\x94""456",
RegionCode::GB(), &test_number));
EXPECT_EQ(uk_number, test_number);
PhoneNumber us_with_extension;
us_with_extension.set_country_code(1);
us_with_extension.set_national_number(8009013355ULL);
us_with_extension.set_extension("7246433");
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 x 7246433", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 , ext 7246433", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 ; 7246433", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
// To test an extension character without surrounding spaces.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355;7246433", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 ,extension 7246433",
RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 ,extensi\xC3\xB3n 7246433",
/* "(800) 901-3355 ,extensión 7246433" */
RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
// Repeat with the small letter o with acute accent created by combining
// characters.
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 ,extensio\xCC\x81n 7246433",
/* "(800) 901-3355 ,extensión 7246433" */
RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 , 7246433", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(800) 901-3355 ext: 7246433", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
// Test that if a number has two extensions specified, we ignore the second.
PhoneNumber us_with_two_extensions_number;
us_with_two_extensions_number.set_country_code(1);
us_with_two_extensions_number.set_national_number(2121231234ULL);
us_with_two_extensions_number.set_extension("508");
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(212)123-1234 x508/x1234", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_two_extensions_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(212)123-1234 x508/ x1234", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_two_extensions_number, test_number);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("(212)123-1234 x508\\x1234", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_two_extensions_number, test_number);
// Test parsing numbers in the form (645) 123-1234-910# works, where the last
// 3 digits before the # are an extension.
us_with_extension.Clear();
us_with_extension.set_country_code(1);
us_with_extension.set_national_number(6451231234ULL);
us_with_extension.set_extension("910");
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("+1 (645) 123 1234-910#", RegionCode::US(),
&test_number));
EXPECT_EQ(us_with_extension, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseAndKeepRaw) {
PhoneNumber alpha_numeric_number;
alpha_numeric_number.set_country_code(1);
alpha_numeric_number.set_national_number(80074935247ULL);
alpha_numeric_number.set_raw_input("800 six-flags");
alpha_numeric_number.set_country_code_source(
PhoneNumber::FROM_DEFAULT_COUNTRY);
PhoneNumber test_number;
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("800 six-flags", RegionCode::US(),
&test_number));
EXPECT_EQ(alpha_numeric_number, test_number);
alpha_numeric_number.set_national_number(8007493524ULL);
alpha_numeric_number.set_raw_input("1800 six-flag");
alpha_numeric_number.set_country_code_source(
PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("1800 six-flag", RegionCode::US(),
&test_number));
EXPECT_EQ(alpha_numeric_number, test_number);
alpha_numeric_number.set_raw_input("+1800 six-flag");
alpha_numeric_number.set_country_code_source(
PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("+1800 six-flag", RegionCode::CN(),
&test_number));
EXPECT_EQ(alpha_numeric_number, test_number);
alpha_numeric_number.set_raw_input("001800 six-flag");
alpha_numeric_number.set_country_code_source(
PhoneNumber::FROM_NUMBER_WITH_IDD);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("001800 six-flag",
RegionCode::NZ(),
&test_number));
EXPECT_EQ(alpha_numeric_number, test_number);
// Try with invalid region - expect failure. We clear the test number first
// because if parsing isn't successful, the number parsed in won't be changed.
test_number.Clear();
EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR,
phone_util_.Parse("123 456 7890", RegionCode::CS(), &test_number));
EXPECT_EQ(PhoneNumber::default_instance(), test_number);
PhoneNumber korean_number;
korean_number.set_country_code(82);
korean_number.set_national_number(22123456);
korean_number.set_raw_input("08122123456");
korean_number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY);
korean_number.set_preferred_domestic_carrier_code("81");
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.ParseAndKeepRawInput("08122123456",
RegionCode::KR(),
&test_number));
EXPECT_EQ(korean_number, test_number);
}
TEST_F(PhoneNumberUtilTest, ParseItalianLeadingZeros) {
PhoneNumber zeros_number;
zeros_number.set_country_code(61);
PhoneNumber test_number;
// Test the number "011".
zeros_number.set_national_number(11L);
zeros_number.set_italian_leading_zero(true);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("011", RegionCode::AU(),
&test_number));
EXPECT_EQ(zeros_number, test_number);
// Test the number "001".
zeros_number.set_national_number(1L);
zeros_number.set_italian_leading_zero(true);
zeros_number.set_number_of_leading_zeros(2);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("001", RegionCode::AU(),
&test_number));
EXPECT_EQ(zeros_number, test_number);
// Test the number "000". This number has 2 leading zeros.
zeros_number.set_national_number(0L);
zeros_number.set_italian_leading_zero(true);
zeros_number.set_number_of_leading_zeros(2);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("000", RegionCode::AU(),
&test_number));
EXPECT_EQ(zeros_number, test_number);
// Test the number "0000". This number has 3 leading zeros.
zeros_number.set_national_number(0L);
zeros_number.set_italian_leading_zero(true);
zeros_number.set_number_of_leading_zeros(3);
EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR,
phone_util_.Parse("0000", RegionCode::AU(),
&test_number));
EXPECT_EQ(zeros_number, test_number);
}
TEST_F(PhoneNumberUtilTest, CanBeInternationallyDialled) {
PhoneNumber test_number;
test_number.set_country_code(1);
// We have no-international-dialling rules for the US in our test metadata
// that say that toll-free numbers cannot be dialled internationally.
test_number.set_national_number(8002530000ULL);
EXPECT_FALSE(phone_util_.CanBeInternationallyDialled(test_number));
// Normal US numbers can be internationally dialled.
test_number.set_national_number(6502530000ULL);
EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number));
// Invalid number.
test_number.set_national_number(2530000ULL);
EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number));
// We have no data for NZ - should return true.
test_number.set_country_code(64);
test_number.set_national_number(33316005ULL);
EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number));
test_number.set_country_code(800);
test_number.set_national_number(12345678ULL);
EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number));
}
TEST_F(PhoneNumberUtilTest, IsAlphaNumber) {
EXPECT_TRUE(phone_util_.IsAlphaNumber("1800 six-flags"));
EXPECT_TRUE(phone_util_.IsAlphaNumber("1800 six-flags ext. 1234"));
EXPECT_TRUE(phone_util_.IsAlphaNumber("+800 six-flags"));
EXPECT_TRUE(phone_util_.IsAlphaNumber("180 six-flags"));
EXPECT_FALSE(phone_util_.IsAlphaNumber("1800 123-1234"));
EXPECT_FALSE(phone_util_.IsAlphaNumber("1 six-flags"));
EXPECT_FALSE(phone_util_.IsAlphaNumber("18 six-flags"));
EXPECT_FALSE(phone_util_.IsAlphaNumber("1800 123-1234 extension: 1234"));
EXPECT_FALSE(phone_util_.IsAlphaNumber("+800 1234-1234"));
}
} // namespace phonenumbers
} // namespace i18n
| {
"content_hash": "f5f5411ec949be8edb48dad96f159ce6",
"timestamp": "",
"source": "github",
"line_count": 4501,
"max_line_length": 80,
"avg_line_length": 44.839369029104645,
"alnum_prop": 0.6686634757360447,
"repo_name": "keghani/libphonenumber",
"id": "4eb7a3ac4d1f2c01aff5ef612cdd53506b4de64b",
"size": "201954",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cpp/test/phonenumbers/phonenumberutil_test.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "16323"
},
{
"name": "C++",
"bytes": "3301387"
},
{
"name": "CMake",
"bytes": "21310"
},
{
"name": "CSS",
"bytes": "305"
},
{
"name": "HTML",
"bytes": "5569"
},
{
"name": "Java",
"bytes": "862507"
},
{
"name": "JavaScript",
"bytes": "943494"
}
],
"symlink_target": ""
} |
package com.ctrip.platform.dal.daogen.log;
public interface ILogger {
void logEvent(String type, String name);
void info(String message);
void error(Throwable e);
}
| {
"content_hash": "08313539bf57cca1be682ae7dd4a3581",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 44,
"avg_line_length": 20,
"alnum_prop": 0.7166666666666667,
"repo_name": "ctripcorp/dal",
"id": "665d552f0bd719fa497681dd9e2dddb141b42419",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dao-gen-core/src/main/java/com/ctrip/platform/dal/daogen/log/ILogger.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "617930"
},
{
"name": "CSS",
"bytes": "860913"
},
{
"name": "Java",
"bytes": "4862905"
},
{
"name": "JavaScript",
"bytes": "1687473"
},
{
"name": "Less",
"bytes": "153148"
},
{
"name": "Smarty",
"bytes": "145706"
}
],
"symlink_target": ""
} |
"""The Finger User Information Protocol (RFC 1288)"""
from twisted.protocols import basic
class Finger(basic.LineReceiver):
def lineReceived(self, line):
parts = line.split()
if not parts:
parts = ['']
if len(parts) == 1:
slash_w = 0
else:
slash_w = 1
user = parts[-1]
if '@' in user:
host_place = user.rfind('@')
user = user[:host_place]
host = user[host_place+1:]
return self.forwardQuery(slash_w, user, host)
if user:
return self.getUser(slash_w, user)
else:
return self.getDomain(slash_w)
def _refuseMessage(self, message):
self.transport.write(message+"\n")
self.transport.loseConnection()
def forwardQuery(self, slash_w, user, host):
self._refuseMessage('Finger forwarding service denied')
def getDomain(self, slash_w):
self._refuseMessage('Finger online list denied')
def getUser(self, slash_w, user):
self.transport.write('Login: '+user+'\n')
self._refuseMessage('No such user')
| {
"content_hash": "c952266b0d049e24205f14f3d0677bc6",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 63,
"avg_line_length": 29.4,
"alnum_prop": 0.5501700680272109,
"repo_name": "hlzz/dotfiles",
"id": "928632dd533682cc48a0b9981e5cbadc2fb2c5c6",
"size": "1250",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/protocols/finger.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "1240"
},
{
"name": "Arc",
"bytes": "38"
},
{
"name": "Assembly",
"bytes": "449468"
},
{
"name": "Batchfile",
"bytes": "16152"
},
{
"name": "C",
"bytes": "102303195"
},
{
"name": "C++",
"bytes": "155056606"
},
{
"name": "CMake",
"bytes": "7200627"
},
{
"name": "CSS",
"bytes": "179330"
},
{
"name": "Cuda",
"bytes": "30026"
},
{
"name": "D",
"bytes": "2152"
},
{
"name": "Emacs Lisp",
"bytes": "14892"
},
{
"name": "FORTRAN",
"bytes": "5276"
},
{
"name": "Forth",
"bytes": "3637"
},
{
"name": "GAP",
"bytes": "14495"
},
{
"name": "GLSL",
"bytes": "438205"
},
{
"name": "Gnuplot",
"bytes": "327"
},
{
"name": "Groff",
"bytes": "518260"
},
{
"name": "HLSL",
"bytes": "965"
},
{
"name": "HTML",
"bytes": "2003175"
},
{
"name": "Haskell",
"bytes": "10370"
},
{
"name": "IDL",
"bytes": "2466"
},
{
"name": "Java",
"bytes": "219109"
},
{
"name": "JavaScript",
"bytes": "1618007"
},
{
"name": "Lex",
"bytes": "119058"
},
{
"name": "Lua",
"bytes": "23167"
},
{
"name": "M",
"bytes": "1080"
},
{
"name": "M4",
"bytes": "292475"
},
{
"name": "Makefile",
"bytes": "7112810"
},
{
"name": "Matlab",
"bytes": "1582"
},
{
"name": "NSIS",
"bytes": "34176"
},
{
"name": "Objective-C",
"bytes": "65312"
},
{
"name": "Objective-C++",
"bytes": "269995"
},
{
"name": "PAWN",
"bytes": "4107117"
},
{
"name": "PHP",
"bytes": "2690"
},
{
"name": "Pascal",
"bytes": "5054"
},
{
"name": "Perl",
"bytes": "485508"
},
{
"name": "Pike",
"bytes": "1338"
},
{
"name": "Prolog",
"bytes": "5284"
},
{
"name": "Python",
"bytes": "16799659"
},
{
"name": "QMake",
"bytes": "89858"
},
{
"name": "Rebol",
"bytes": "291"
},
{
"name": "Ruby",
"bytes": "21590"
},
{
"name": "Scilab",
"bytes": "120244"
},
{
"name": "Shell",
"bytes": "2266191"
},
{
"name": "Slash",
"bytes": "1536"
},
{
"name": "Smarty",
"bytes": "1368"
},
{
"name": "Swift",
"bytes": "331"
},
{
"name": "Tcl",
"bytes": "1911873"
},
{
"name": "TeX",
"bytes": "11981"
},
{
"name": "Verilog",
"bytes": "3893"
},
{
"name": "VimL",
"bytes": "595114"
},
{
"name": "XSLT",
"bytes": "62675"
},
{
"name": "Yacc",
"bytes": "307000"
},
{
"name": "eC",
"bytes": "366863"
}
],
"symlink_target": ""
} |
using content::OpenURLParams;
using content::PageNavigator;
namespace {
void SetImageMenuItem(GtkWidget* menu_item,
const BookmarkNode* node,
BookmarkModel* model) {
GdkPixbuf* pixbuf = bookmark_utils::GetPixbufForNode(node, model, true);
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item),
gtk_image_new_from_pixbuf(pixbuf));
g_object_unref(pixbuf);
}
const BookmarkNode* GetNodeFromMenuItem(GtkWidget* menu_item) {
return static_cast<const BookmarkNode*>(
g_object_get_data(G_OBJECT(menu_item), "bookmark-node"));
}
const BookmarkNode* GetParentNodeFromEmptyMenu(GtkWidget* menu) {
return static_cast<const BookmarkNode*>(
g_object_get_data(G_OBJECT(menu), "parent-node"));
}
void* AsVoid(const BookmarkNode* node) {
return const_cast<BookmarkNode*>(node);
}
// The context menu has been dismissed, restore the X and application grabs
// to whichever menu last had them. (Assuming that menu is still showing.)
void OnContextMenuHide(GtkWidget* context_menu, GtkWidget* grab_menu) {
gtk_util::GrabAllInput(grab_menu);
// Match the ref we took when connecting this signal.
g_object_unref(grab_menu);
}
} // namespace
BookmarkMenuController::BookmarkMenuController(Browser* browser,
PageNavigator* navigator,
GtkWindow* window,
const BookmarkNode* node,
int start_child_index)
: browser_(browser),
page_navigator_(navigator),
parent_window_(window),
model_(BookmarkModelFactory::GetForProfile(browser->profile())),
node_(node),
drag_icon_(NULL),
ignore_button_release_(false),
triggering_widget_(NULL) {
menu_ = gtk_menu_new();
g_object_ref_sink(menu_);
BuildMenu(node, start_child_index, menu_);
signals_.Connect(menu_, "hide", G_CALLBACK(OnMenuHiddenThunk), this);
gtk_widget_show_all(menu_);
}
BookmarkMenuController::~BookmarkMenuController() {
model_->RemoveObserver(this);
// Make sure the hide handler runs.
gtk_widget_hide(menu_);
gtk_widget_destroy(menu_);
g_object_unref(menu_);
}
void BookmarkMenuController::Popup(GtkWidget* widget, gint button_type,
guint32 timestamp) {
model_->AddObserver(this);
triggering_widget_ = widget;
signals_.Connect(triggering_widget_, "destroy",
G_CALLBACK(gtk_widget_destroyed), &triggering_widget_);
gtk_chrome_button_set_paint_state(GTK_CHROME_BUTTON(widget),
GTK_STATE_ACTIVE);
gtk_menu_popup(GTK_MENU(menu_), NULL, NULL,
&MenuGtk::WidgetMenuPositionFunc,
widget, button_type, timestamp);
}
void BookmarkMenuController::BookmarkModelChanged() {
gtk_menu_popdown(GTK_MENU(menu_));
}
void BookmarkMenuController::BookmarkNodeFaviconChanged(
BookmarkModel* model, const BookmarkNode* node) {
std::map<const BookmarkNode*, GtkWidget*>::iterator it =
node_to_menu_widget_map_.find(node);
if (it != node_to_menu_widget_map_.end())
SetImageMenuItem(it->second, node, model);
}
void BookmarkMenuController::WillExecuteCommand() {
gtk_menu_popdown(GTK_MENU(menu_));
}
void BookmarkMenuController::CloseMenu() {
context_menu_->Cancel();
}
void BookmarkMenuController::NavigateToMenuItem(
GtkWidget* menu_item,
WindowOpenDisposition disposition) {
const BookmarkNode* node = GetNodeFromMenuItem(menu_item);
DCHECK(node);
DCHECK(page_navigator_);
page_navigator_->OpenURL(OpenURLParams(
node->url(), content::Referrer(), disposition,
content::PAGE_TRANSITION_AUTO_BOOKMARK, false));
}
void BookmarkMenuController::BuildMenu(const BookmarkNode* parent,
int start_child_index,
GtkWidget* menu) {
DCHECK(parent->empty() || start_child_index < parent->child_count());
signals_.Connect(menu, "button-press-event",
G_CALLBACK(OnMenuButtonPressedOrReleasedThunk), this);
signals_.Connect(menu, "button-release-event",
G_CALLBACK(OnMenuButtonPressedOrReleasedThunk), this);
for (int i = start_child_index; i < parent->child_count(); ++i) {
const BookmarkNode* node = parent->GetChild(i);
GtkWidget* menu_item = gtk_image_menu_item_new_with_label(
bookmark_utils::BuildMenuLabelFor(node).c_str());
g_object_set_data(G_OBJECT(menu_item), "bookmark-node", AsVoid(node));
SetImageMenuItem(menu_item, node, model_);
gtk_util::SetAlwaysShowImage(menu_item);
signals_.Connect(menu_item, "button-release-event",
G_CALLBACK(OnButtonReleasedThunk), this);
if (node->is_url()) {
signals_.Connect(menu_item, "activate",
G_CALLBACK(OnMenuItemActivatedThunk), this);
} else if (node->is_folder()) {
GtkWidget* submenu = gtk_menu_new();
BuildMenu(node, 0, submenu);
gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu);
} else {
NOTREACHED();
}
gtk_drag_source_set(menu_item, GDK_BUTTON1_MASK, NULL, 0,
static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_LINK));
int target_mask = ui::CHROME_BOOKMARK_ITEM;
if (node->is_url())
target_mask |= ui::TEXT_URI_LIST | ui::NETSCAPE_URL;
ui::SetSourceTargetListFromCodeMask(menu_item, target_mask);
signals_.Connect(menu_item, "drag-begin",
G_CALLBACK(OnMenuItemDragBeginThunk), this);
signals_.Connect(menu_item, "drag-end",
G_CALLBACK(OnMenuItemDragEndThunk), this);
signals_.Connect(menu_item, "drag-data-get",
G_CALLBACK(OnMenuItemDragGetThunk), this);
// It is important to connect to this signal after setting up the drag
// source because we only want to stifle the menu's default handler and
// not the handler that the drag source uses.
if (node->is_folder()) {
signals_.Connect(menu_item, "button-press-event",
G_CALLBACK(OnFolderButtonPressedThunk), this);
}
gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item);
node_to_menu_widget_map_[node] = menu_item;
}
if (parent->empty()) {
GtkWidget* empty_menu = gtk_menu_item_new_with_label(
l10n_util::GetStringUTF8(IDS_MENU_EMPTY_SUBMENU).c_str());
gtk_widget_set_sensitive(empty_menu, FALSE);
g_object_set_data(G_OBJECT(menu), "parent-node", AsVoid(parent));
gtk_menu_shell_append(GTK_MENU_SHELL(menu), empty_menu);
}
}
gboolean BookmarkMenuController::OnMenuButtonPressedOrReleased(
GtkWidget* sender,
GdkEventButton* event) {
// Handle middle mouse downs and right mouse ups.
if (!((event->button == 2 && event->type == GDK_BUTTON_RELEASE) ||
(event->button == 3 && event->type == GDK_BUTTON_PRESS))) {
return FALSE;
}
ignore_button_release_ = false;
GtkMenuShell* menu_shell = GTK_MENU_SHELL(sender);
// If the cursor is outside our bounds, pass this event up to the parent.
if (!gtk_util::WidgetContainsCursor(sender)) {
if (menu_shell->parent_menu_shell) {
return OnMenuButtonPressedOrReleased(menu_shell->parent_menu_shell,
event);
} else {
// We are the top level menu; we can propagate no further.
return FALSE;
}
}
// This will return NULL if we are not an empty menu.
const BookmarkNode* parent = GetParentNodeFromEmptyMenu(sender);
bool is_empty_menu = !!parent;
// If there is no active menu item and we are not an empty menu, then do
// nothing. This can happen if the user has canceled a context menu while
// the cursor is hovering over a bookmark menu. Doing nothing is not optimal
// (the hovered item should be active), but it's a hopefully rare corner
// case.
GtkWidget* menu_item = menu_shell->active_menu_item;
if (!is_empty_menu && !menu_item)
return TRUE;
const BookmarkNode* node =
menu_item ? GetNodeFromMenuItem(menu_item) : NULL;
if (event->button == 2 && node && node->is_folder()) {
chrome::OpenAll(parent_window_, page_navigator_, node, NEW_BACKGROUND_TAB);
gtk_menu_popdown(GTK_MENU(menu_));
return TRUE;
} else if (event->button == 3) {
DCHECK_NE(is_empty_menu, !!node);
if (!is_empty_menu)
parent = node->parent();
// Show the right click menu and stop processing this button event.
std::vector<const BookmarkNode*> nodes;
if (node)
nodes.push_back(node);
context_menu_controller_.reset(
new BookmarkContextMenuController(
parent_window_, this, browser_, browser_->profile(),
page_navigator_, parent, nodes));
context_menu_.reset(
new MenuGtk(NULL, context_menu_controller_->menu_model()));
// Our bookmark folder menu loses the grab to the context menu. When the
// context menu is hidden, re-assert our grab.
GtkWidget* grabbing_menu = gtk_grab_get_current();
g_object_ref(grabbing_menu);
signals_.Connect(context_menu_->widget(), "hide",
G_CALLBACK(OnContextMenuHide), grabbing_menu);
context_menu_->PopupAsContext(gfx::Point(event->x_root, event->y_root),
event->time);
return TRUE;
}
return FALSE;
}
gboolean BookmarkMenuController::OnButtonReleased(
GtkWidget* sender,
GdkEventButton* event) {
if (ignore_button_release_) {
// Don't handle this message; it was a drag.
ignore_button_release_ = false;
return FALSE;
}
// Releasing either button 1 or 2 should trigger the bookmark.
if (!gtk_menu_item_get_submenu(GTK_MENU_ITEM(sender))) {
// The menu item is a link node.
if (event->button == 1 || event->button == 2) {
WindowOpenDisposition disposition =
event_utils::DispositionFromGdkState(event->state);
NavigateToMenuItem(sender, disposition);
// We need to manually dismiss the popup menu because we're overriding
// button-release-event.
gtk_menu_popdown(GTK_MENU(menu_));
return TRUE;
}
} else {
// The menu item is a folder node.
if (event->button == 1) {
// Having overriden the normal handling, we need to manually activate
// the item.
gtk_menu_shell_select_item(GTK_MENU_SHELL(sender->parent), sender);
g_signal_emit_by_name(sender->parent, "activate-current");
return TRUE;
}
}
return FALSE;
}
gboolean BookmarkMenuController::OnFolderButtonPressed(
GtkWidget* sender, GdkEventButton* event) {
// The button press may start a drag; don't let the default handler run.
if (event->button == 1)
return TRUE;
return FALSE;
}
void BookmarkMenuController::OnMenuHidden(GtkWidget* menu) {
if (triggering_widget_)
gtk_chrome_button_unset_paint_state(GTK_CHROME_BUTTON(triggering_widget_));
}
void BookmarkMenuController::OnMenuItemActivated(GtkWidget* menu_item) {
NavigateToMenuItem(menu_item, CURRENT_TAB);
}
void BookmarkMenuController::OnMenuItemDragBegin(GtkWidget* menu_item,
GdkDragContext* drag_context) {
// The parent menu item might be removed during the drag. Ref it so |button|
// won't get destroyed.
g_object_ref(menu_item->parent);
// Signal to any future OnButtonReleased calls that we're dragging instead of
// pressing.
ignore_button_release_ = true;
const BookmarkNode* node = bookmark_utils::BookmarkNodeForWidget(menu_item);
drag_icon_ = bookmark_utils::GetDragRepresentationForNode(
node, model_, GtkThemeService::GetFrom(browser_->profile()));
gint x, y;
gtk_widget_get_pointer(menu_item, &x, &y);
gtk_drag_set_icon_widget(drag_context, drag_icon_, x, y);
// Hide our node.
gtk_widget_hide(menu_item);
}
void BookmarkMenuController::OnMenuItemDragEnd(GtkWidget* menu_item,
GdkDragContext* drag_context) {
gtk_widget_show(menu_item);
g_object_unref(menu_item->parent);
gtk_widget_destroy(drag_icon_);
drag_icon_ = NULL;
}
void BookmarkMenuController::OnMenuItemDragGet(
GtkWidget* widget, GdkDragContext* context,
GtkSelectionData* selection_data,
guint target_type, guint time) {
const BookmarkNode* node = bookmark_utils::BookmarkNodeForWidget(widget);
bookmark_utils::WriteBookmarkToSelection(node, selection_data, target_type,
browser_->profile());
}
| {
"content_hash": "3caffbc60ad78acbe1920e6e6576a784",
"timestamp": "",
"source": "github",
"line_count": 341,
"max_line_length": 80,
"avg_line_length": 36.83284457478006,
"alnum_prop": 0.6529458598726114,
"repo_name": "leighpauls/k2cro4",
"id": "70db1460f6e61d77a7bc2be3b4f549f72f20e18b",
"size": "13822",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chrome/browser/ui/gtk/bookmarks/bookmark_menu_controller_gtk.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": ""
} |
package bufanalysis
import (
"bytes"
"strconv"
)
type fileAnnotation struct {
fileInfo FileInfo
startLine int
startColumn int
endLine int
endColumn int
typeString string
message string
}
func newFileAnnotation(
fileInfo FileInfo,
startLine int,
startColumn int,
endLine int,
endColumn int,
typeString string,
message string,
) *fileAnnotation {
return &fileAnnotation{
fileInfo: fileInfo,
startLine: startLine,
startColumn: startColumn,
endLine: endLine,
endColumn: endColumn,
typeString: typeString,
message: message,
}
}
func (f *fileAnnotation) FileInfo() FileInfo {
return f.fileInfo
}
func (f *fileAnnotation) StartLine() int {
return f.startLine
}
func (f *fileAnnotation) StartColumn() int {
return f.startColumn
}
func (f *fileAnnotation) EndLine() int {
return f.endLine
}
func (f *fileAnnotation) EndColumn() int {
return f.endColumn
}
func (f *fileAnnotation) Type() string {
return f.typeString
}
func (f *fileAnnotation) Message() string {
return f.message
}
func (f *fileAnnotation) String() string {
if f == nil {
return ""
}
path := "<input>"
line := f.startLine
column := f.startColumn
message := f.message
if f.fileInfo != nil {
path = f.fileInfo.ExternalPath()
}
if line == 0 {
line = 1
}
if column == 0 {
column = 1
}
if message == "" {
message = f.typeString
// should never happen but just in case
if message == "" {
message = "FAILURE"
}
}
buffer := bytes.NewBuffer(nil)
_, _ = buffer.WriteString(path)
_, _ = buffer.WriteRune(':')
_, _ = buffer.WriteString(strconv.Itoa(line))
_, _ = buffer.WriteRune(':')
_, _ = buffer.WriteString(strconv.Itoa(column))
_, _ = buffer.WriteRune(':')
_, _ = buffer.WriteString(message)
return buffer.String()
}
| {
"content_hash": "1f79c46212e90f0eb1035dbe1e5134b5",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 48,
"avg_line_length": 18.09090909090909,
"alnum_prop": 0.6677833612506979,
"repo_name": "bufbuild/buf",
"id": "9bf5ac33dd9b3a67c3868b35822c8b48dde52fc0",
"size": "2397",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "private/bufpkg/bufanalysis/file_annotation.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "3243568"
},
{
"name": "Makefile",
"bytes": "29816"
},
{
"name": "Shell",
"bytes": "10085"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="support-v4-23.4.0">
<ANNOTATIONS>
<root url="jar://$PROJECT_DIR$/lib-zxing/build/intermediates/exploded-aar/com.android.support/support-v4/23.4.0/annotations.zip!/" />
</ANNOTATIONS>
<CLASSES>
<root url="file://$PROJECT_DIR$/lib-zxing/build/intermediates/exploded-aar/com.android.support/support-v4/23.4.0/res" />
<root url="jar://$PROJECT_DIR$/lib-zxing/build/intermediates/exploded-aar/com.android.support/support-v4/23.4.0/jars/classes.jar!/" />
<root url="jar://$PROJECT_DIR$/lib-zxing/build/intermediates/exploded-aar/com.android.support/support-v4/23.4.0/jars/libs/internal_impl-23.4.0.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/../../LiZheng/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/support-v4/23.4.0/support-v4-23.4.0-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "22711c4d838da76681102e2968935230",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 178,
"avg_line_length": 59.4375,
"alnum_prop": 0.6898002103049422,
"repo_name": "asmallkite/BeEyes",
"id": "644ebff9aa0338c02cb34760da0ec293740de766",
"size": "951",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/support_v4_23_4_0.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "325121"
}
],
"symlink_target": ""
} |
package org.dbflute.erflute.editor.view.dialog.relationship;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.dbflute.erflute.Activator;
import org.dbflute.erflute.core.dialog.AbstractDialog;
import org.dbflute.erflute.core.util.Check;
import org.dbflute.erflute.core.util.Format;
import org.dbflute.erflute.core.util.Srl;
import org.dbflute.erflute.core.widgets.CompositeFactory;
import org.dbflute.erflute.editor.controller.command.diagram_contents.element.connection.relationship.fkname.DefaultForeignKeyNameProvider;
import org.dbflute.erflute.editor.model.ERDiagram;
import org.dbflute.erflute.editor.model.diagram_contents.element.connection.Relationship;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.ERTable;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.TableView;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.column.NormalColumn;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.table.unique_key.CompoundUniqueKey;
import org.dbflute.erflute.editor.view.dialog.relationship.RelationshipDialog.ReferredColumnState;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
/**
* @author modified by jflute (originated in ermaster)
*/
public class RelationshipByExistingColumnsDialog extends AbstractDialog {
// ===================================================================================
// Definition
// ==========
private static final int COLUMN_WIDTH = 200;
// ===================================================================================
// Attribute
// =========
private final ERTable source; // foreign table e.g. MEMBER_STATUS
private final TableView target; // local table e.g. MEMBER
private final List<NormalColumn> candidateForeignKeyColumns;
private final Map<NormalColumn, List<NormalColumn>> existingRootReferredToFkColumnsMap;
private final Map<Relationship, Set<NormalColumn>> existingRelationshipToFkColumnsMap;
// -----------------------------------------------------
// Component
// ---------
private Text foreignKeyNameText; // #for_erflute
private Combo referredColumnSelector;
private ReferredColumnState referredColumnState;
private Table foreignKeyColumnMapper; // avoid abstract word 'table' here
private final List<TableEditor> mapperEditorList;
private final Map<TableEditor, List<NormalColumn>> mapperEditorToReferredColumnsMap;
private Button newColumnCheckBox; // #for_erflute
// -----------------------------------------------------
// Dialog Result
// -------------
private boolean resultReferenceForPK; // to create relationship
private CompoundUniqueKey resultReferredComplexUniqueKey; // to create relationship
private NormalColumn resultReferredSimpleUniqueColumn; // to create relationship
private List<NormalColumn> selectedReferredColumnList; // added when select referred columns, may be plural when primary
private final List<NormalColumn> selectedForeignKeyColumnList; // added when perform, may be plural when compound FK
private Relationship newCreatedRelationship; // created when perform
// ===================================================================================
// Constructor
// ===========
public RelationshipByExistingColumnsDialog(Shell parentShell, ERTable source, TableView target,
List<NormalColumn> candidateForeignKeyColumns, Map<NormalColumn, List<NormalColumn>> existingRootReferredToFkColumnsMap,
Map<Relationship, Set<NormalColumn>> existingRelationshipToFkColumnsMap) {
super(parentShell, 2);
this.source = source;
this.target = target;
this.selectedReferredColumnList = new ArrayList<>();
this.candidateForeignKeyColumns = candidateForeignKeyColumns;
this.existingRootReferredToFkColumnsMap = existingRootReferredToFkColumnsMap;
this.existingRelationshipToFkColumnsMap = existingRelationshipToFkColumnsMap;
this.mapperEditorList = new ArrayList<>();
this.mapperEditorToReferredColumnsMap = new HashMap<>();
this.selectedForeignKeyColumnList = new ArrayList<>();
}
// ===================================================================================
// Dialog Area
// ===========
@Override
protected String getTitle() {
return "dialog.title.relation";
}
// -----------------------------------------------------
// Layout
// ------
@Override
protected void initLayout(GridLayout layout) {
super.initLayout(layout);
layout.verticalSpacing = 20;
}
// -----------------------------------------------------
// Component
// ---------
@Override
protected void initComponent(Composite composite) {
createForeignKeyNameText(composite);
createGridLayout(composite);
createReferredColumnSelector(composite);
createForeignKeyColumnMapper(composite);
newColumnCheckBox = CompositeFactory.createCheckbox(this, composite, "Create new column(s)");
}
// -----------------------------------------------------
// Foreign Key Name
// ----------------
private void createForeignKeyNameText(Composite composite) {
foreignKeyNameText = CompositeFactory.createText(this, composite, "Foreign Key Name", false);
foreignKeyNameText.setText(provideDefaultForeignKeyName(source, target));
}
private String provideDefaultForeignKeyName(ERTable sourceTable, TableView targetTable) {
// #hope use selected foreign columns when duplicate
return new DefaultForeignKeyNameProvider().provide(sourceTable, targetTable);
}
// -----------------------------------------------------
// Grid Layout
// -----------
private void createGridLayout(Composite composite) {
final GridData gridData = new GridData();
gridData.horizontalSpan = 2;
final Label label = new Label(composite, SWT.NONE);
label.setLayoutData(gridData);
label.setText("Select PK or UQ column and select FK column");
}
// -----------------------------------------------------
// Referred Column Selector
// ------------------------
private void createReferredColumnSelector(Composite composite) {
final Label label = new Label(composite, SWT.NONE);
label.setText("Referred Column");
final GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
referredColumnSelector = new Combo(composite, SWT.READ_ONLY);
referredColumnSelector.setLayoutData(gridData);
referredColumnSelector.setVisibleItemCount(20);
}
// -----------------------------------------------------
// ForeignKey Column Mapper
// =-----------------------
private void createForeignKeyColumnMapper(Composite composite) {
final GridData tableGridData = new GridData();
tableGridData.horizontalSpan = 2;
tableGridData.heightHint = 100;
tableGridData.horizontalAlignment = GridData.FILL;
tableGridData.grabExcessHorizontalSpace = true;
foreignKeyColumnMapper = new Table(composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
foreignKeyColumnMapper.setLayoutData(tableGridData);
foreignKeyColumnMapper.setHeaderVisible(true);
foreignKeyColumnMapper.setLinesVisible(true);
final TableColumn referredColumn = new TableColumn(foreignKeyColumnMapper, SWT.NONE);
referredColumn.setWidth(COLUMN_WIDTH);
referredColumn.setText("Referred Column");
final TableColumn foreignKeyColumn = new TableColumn(foreignKeyColumnMapper, SWT.NONE);
foreignKeyColumn.setWidth(COLUMN_WIDTH);
foreignKeyColumn.setText("ForeignKey Column");
}
// -----------------------------------------------------
// Set up Data
// -----------
@Override
protected void setupData() {
referredColumnState = RelationshipDialog.setupReferredColumnComboData(referredColumnSelector, source);
referredColumnSelector.select(0);
prepareForeignKeyColumnMapperRows();
}
// ===================================================================================
// Listener
// ========
@Override
protected void addListener() {
super.addListener();
referredColumnSelector.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetForeignKeyColumnMapper();
validate();
}
});
foreignKeyColumnMapper.addListener(SWT.MeasureItem, new Listener() {
@Override
public void handleEvent(Event event) {
event.height = referredColumnSelector.getSize().y;
}
});
newColumnCheckBox.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetForeignKeyColumnMapper();
validate(); // to allow OK when checked
}
});
}
private void resetForeignKeyColumnMapper() {
foreignKeyColumnMapper.removeAll();
disposeMapperEditor();
prepareForeignKeyColumnMapperRows();
}
private void prepareForeignKeyColumnMapperRows() {
try {
final int referredColumnIndex = referredColumnSelector.getSelectionIndex();
if (referredColumnIndex < referredColumnState.complexUniqueKeyStartIndex) {
selectedReferredColumnList = source.getPrimaryKeys();
} else if (referredColumnIndex < referredColumnState.columnStartIndex) {
final CompoundUniqueKey complexUniqueKey =
source.getCompoundUniqueKeyList().get(referredColumnIndex - referredColumnState.complexUniqueKeyStartIndex);
selectedReferredColumnList = complexUniqueKey.getColumnList();
} else {
final NormalColumn referencedColumn =
referredColumnState.candidateColumns.get(referredColumnIndex - referredColumnState.columnStartIndex);
selectedReferredColumnList = new ArrayList<>();
selectedReferredColumnList.add(referencedColumn);
}
for (final NormalColumn referredColumn : selectedReferredColumnList) {
addColumnToMapperItem(referredColumn);
}
} catch (final Exception e) {
Activator.showExceptionDialog(e);
}
}
private void addColumnToMapperItem(NormalColumn referredColumn) {
final TableItem tableItem = new TableItem(foreignKeyColumnMapper, SWT.NONE);
tableItem.setText(0, Format.null2blank(referredColumn.getLogicalName()));
final List<NormalColumn> foreignKeyColumnList = existingRootReferredToFkColumnsMap.get(referredColumn.getFirstRootReferredColumn());
final TableEditor mapperEditor = new TableEditor(foreignKeyColumnMapper);
mapperEditor.grabHorizontal = true;
final Combo foreignKeyColumnSelector = createForeignKeyColumnSelector(foreignKeyColumnList);
mapperEditor.setEditor(foreignKeyColumnSelector, tableItem, 1);
mapperEditorList.add(mapperEditor);
mapperEditorToReferredColumnsMap.put(mapperEditor, foreignKeyColumnList);
}
protected Combo createForeignKeyColumnSelector(List<NormalColumn> foreignKeyColumnList) {
final Combo foreignKeyColumnSelector = CompositeFactory.createReadOnlyCombo(this, foreignKeyColumnMapper, /*title*/null);
foreignKeyColumnSelector.add("");
if (foreignKeyColumnList != null) {
for (final NormalColumn foreignKeyColumn : foreignKeyColumnList) {
foreignKeyColumnSelector.add(Format.toString(foreignKeyColumn.getName()));
}
}
for (final NormalColumn foreignKeyColumn : candidateForeignKeyColumns) {
foreignKeyColumnSelector.add(Format.toString(foreignKeyColumn.getName()));
}
if (foreignKeyColumnSelector.getItemCount() > 0) {
foreignKeyColumnSelector.select(0);
}
return foreignKeyColumnSelector;
}
// ===================================================================================
// Validation
// ==========
@Override
protected String doValidate() {
final String foreignKeyName = foreignKeyNameText.getText().trim();
if (Srl.is_Null_or_TrimmedEmpty(foreignKeyName)) {
return "Input foreign key name e.g. FK_XXX";
}
if (source.getDiagramSettings().isValidatePhysicalName() && !Check.isAlphabet(foreignKeyName)) {
return "error.foreign.key.name.not.alphabet";
}
final ERDiagram diagram = target.getDiagram();
final List<TableView> tableViewList = diagram.getDiagramContents().getDiagramWalkers().getTableViewList();
for (final TableView tableView : tableViewList) {
final List<Relationship> relationshipList = tableView.getIncomingRelationshipList();
for (final Relationship currentRel : relationshipList) {
final String currentForeignKeyName = currentRel.getForeignKeyName();
if (currentForeignKeyName != null) {
if (currentForeignKeyName.equalsIgnoreCase(foreignKeyName)) {
return "error.foreign.key.name.already.exists";
}
}
}
}
if (isCreateNewColumn()) {
for (final NormalColumn referredColumn : selectedReferredColumnList) {
final NormalColumn existingColumn = target.findColumnByPhysicalName(referredColumn.getPhysicalName());
if (existingColumn != null) {
return "The same name column already exists, cannot create new column";
}
}
return null;
} else {
// #hope check type difference by jflute
final Set<NormalColumn> selectedColumns = new HashSet<>();
for (final TableEditor tableEditor : mapperEditorList) {
final Combo foreignKeySelector = (Combo) tableEditor.getEditor();
final int selectionIndex = foreignKeySelector.getSelectionIndex();
if (selectionIndex == 0) {
return "error.foreign.key.not.selected";
}
final NormalColumn selectedColumn = findSelectedColumn(tableEditor);
if (selectedColumns.contains(selectedColumn)) {
return "error.foreign.key.must.be.different";
}
selectedColumns.add(selectedColumn);
}
if (existsForeignKeyColumnSet(selectedColumns)) {
return "error.foreign.key.already.exist";
}
return null;
}
}
private boolean existsForeignKeyColumnSet(Set<NormalColumn> columnSet) {
boolean exists = false;
for (final Set<NormalColumn> foreignKeyColumnSet : existingRelationshipToFkColumnsMap.values()) {
if (foreignKeyColumnSet.size() == columnSet.size()) {
exists = true;
for (final NormalColumn normalColumn : columnSet) {
if (!foreignKeyColumnSet.contains(normalColumn)) {
exists = false;
continue;
}
}
break;
}
}
return exists;
}
// ===================================================================================
// Perform OK
// ==========
@Override
protected void performOK() {
setupReferredResult(); // for new-created relationship
setupRelationship(); // using referred result
showPerformOK();
}
private void setupReferredResult() {
final int referredSelectionIndex = referredColumnSelector.getSelectionIndex();
final int complexUniqueKeyStartIndex = referredColumnState.complexUniqueKeyStartIndex;
if (referredSelectionIndex < complexUniqueKeyStartIndex) { // means selecting PK
resultReferenceForPK = true;
} else {
final int simpleUniqueyKeyStartIndex = referredColumnState.columnStartIndex;
if (referredSelectionIndex < simpleUniqueyKeyStartIndex) { // means selecting complex unique key
final List<CompoundUniqueKey> complexUniqueKeyList = source.getCompoundUniqueKeyList();
resultReferredComplexUniqueKey = complexUniqueKeyList.get(referredSelectionIndex - complexUniqueKeyStartIndex);
} else { // means selecting simple unique key
resultReferredSimpleUniqueColumn =
referredColumnState.candidateColumns.get(referredSelectionIndex - simpleUniqueyKeyStartIndex);
}
}
}
private void setupRelationship() {
newCreatedRelationship = createRelationship();
newCreatedRelationship.setForeignKeyName(foreignKeyNameText.getText().trim());
if (isCreateNewColumn()) {
// TODO ymd コマンド外の操作でカラムを追加しているため、undoしてもカラムが削除されない。コマンド化する。
for (final NormalColumn referredColumn : selectedReferredColumnList) {
final NormalColumn newColumn = new NormalColumn(referredColumn, newCreatedRelationship, resultReferenceForPK);
adjustNewForeignKeyColumn(newColumn);
selectedForeignKeyColumnList.add(newColumn);
target.addColumn(newColumn);
}
} else {
for (final TableEditor mapperEditor : mapperEditorList) {
selectedForeignKeyColumnList.add(findSelectedColumn(mapperEditor));
}
}
}
private Relationship createRelationship() {
return new Relationship(resultReferenceForPK, resultReferredComplexUniqueKey, resultReferredSimpleUniqueColumn);
}
private void adjustNewForeignKeyColumn(NormalColumn newColumn) {
newColumn.setPrimaryKey(false);
}
private void showPerformOK() {
final StringBuilder sb = new StringBuilder();
sb.append("Performed the relationship dialog:");
final String ln = "\n";
sb.append(ln).append("[Relationship]");
sb.append(ln).append(" tables: from ").append(target.getPhysicalName()).append(" to ").append(source.getPhysicalName());
sb.append(ln).append(" candidateForeignKeyColumns: ").append(candidateForeignKeyColumns);
sb.append(ln).append(" existingRootReferredToFkColumnsMap: ").append(existingRootReferredToFkColumnsMap);
sb.append(ln).append(" existingRelationshipToFkColumnsMap: ").append(existingRelationshipToFkColumnsMap);
sb.append(ln).append(" selectedReferredColumnList: ").append(selectedReferredColumnList);
sb.append(ln).append(" selectedForeignKeyColumnList: ").append(selectedForeignKeyColumnList);
sb.append(ln).append(" resultReferenceForPK: ").append(resultReferenceForPK);
sb.append(ln).append(" resultReferredComplexUniqueKey: ").append(resultReferredComplexUniqueKey);
sb.append(ln).append(" resultReferredSimpleUniqueColumn: ").append(resultReferredSimpleUniqueColumn);
Activator.debug(this, "performOK()", sb.toString());
}
// ===================================================================================
// Assist Logic
// ============
private boolean isCreateNewColumn() {
return newColumnCheckBox.getSelection();
}
private NormalColumn findSelectedColumn(TableEditor tableEditor) { // not null
final Combo foreignKeySelector = (Combo) tableEditor.getEditor();
final int selectionIndex = foreignKeySelector.getSelectionIndex();
int startIndex = 1;
NormalColumn foreignKeyColumn = null;
final List<NormalColumn> foreignKeyList = mapperEditorToReferredColumnsMap.get(tableEditor);
if (foreignKeyList != null) {
if (selectionIndex <= foreignKeyList.size()) {
foreignKeyColumn = foreignKeyList.get(selectionIndex - startIndex);
} else {
startIndex += foreignKeyList.size();
}
}
if (foreignKeyColumn == null) {
foreignKeyColumn = candidateForeignKeyColumns.get(selectionIndex - startIndex);
}
return foreignKeyColumn;
}
// ===================================================================================
// Basic Override
// ==============
@Override
public boolean close() {
disposeMapperEditor();
return super.close();
}
private void disposeMapperEditor() {
for (final TableEditor tableEditor : mapperEditorList) {
tableEditor.getEditor().dispose();
tableEditor.dispose();
}
mapperEditorList.clear();
mapperEditorToReferredColumnsMap.clear();
}
// ===================================================================================
// Accessor
// ========
// -----------------------------------------------------
// Dialog Result
// -------------
public List<NormalColumn> getSelectedReferencedColumnList() {
return selectedReferredColumnList;
}
public List<NormalColumn> getSelectedForeignKeyColumnList() {
return selectedForeignKeyColumnList;
}
public Relationship getNewCreatedRelationship() {
return newCreatedRelationship;
}
}
| {
"content_hash": "4ec8a308844b6113d586fbb932274758",
"timestamp": "",
"source": "github",
"line_count": 489,
"max_line_length": 140,
"avg_line_length": 50.49488752556237,
"alnum_prop": 0.5759355256763324,
"repo_name": "dbflute-session/erflute",
"id": "81a81a68f484ddd9b7e071d6fefb6c185d73d101",
"size": "24780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/dbflute/erflute/editor/view/dialog/relationship/RelationshipByExistingColumnsDialog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2620003"
}
],
"symlink_target": ""
} |
// Apache License 2.0
//
// Copyright 2017 Marcos Dimitrio
//
// 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 SimpleInjector;
using SolutionCreator.Wpf.Services.Defaults;
using SolutionCreator.Wpf.Services.IO;
using SolutionCreator.Wpf.Services.MessageExchange;
using SolutionCreator.Wpf.ViewModel;
namespace SolutionCreator.Wpf.DependencyInjection
{
public static class WpfMappings
{
public static void RegisterServices(Container container, Lifestyle lifestyle)
{
container.Register<IMessagingService, MessagingService>(lifestyle);
container.Register<IDefaultsService, DefaultsService>(lifestyle);
container.Register<IDialogServices, DialogServices>(lifestyle);
// ViewModels
container.Register<MainWindowViewModel>(lifestyle);
}
}
} | {
"content_hash": "492ccae48f17cd196b0ca535cdccc706",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 85,
"avg_line_length": 36.32432432432432,
"alnum_prop": 0.7403273809523809,
"repo_name": "marcosdimitrio/SolutionCreator",
"id": "11b3b874cbfa0e8de701c0ea0c82573c68c08596",
"size": "1346",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SolutionCreator.Wpf/DependencyInjection/WpfMappings.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "431"
},
{
"name": "C#",
"bytes": "96789"
}
],
"symlink_target": ""
} |
>Command line interface for easier control XAMPP
## Installation
Open your `Terminal`, go to folder where you downloaded **xammp-cli** and run `sh ./installer`:
```bash
cd /path/to/xampp-cli
sh ./installer
```
## Help
If you need help, open `Terminal` and type `xampp` without arguments. Available commands:
* **add** - adds a new host from existing folder (Usage: `sudo xampp add <domain> [path/to/project]`). If directory `path/to/project` doesn't exist, it will be created. If you run this command with one argument, a new host will be added from a folder that has the same name (Usage: `sudo xampp add <domain>`). If directory `domain` doesn't exist, it will be created in current directory.
* **remove** - removes host from XAMPP (Usage: `sudo xampp remove <domain>`). That command removes host from `/opt/lampp/etc/extra/httpd-vhosts.conf` and `/etc/hosts`, and removes symbolic link to project from `htdocs`.
* **gui** - runs `manager-linux.run` or `manager-linux-x64.run`.
* All default XAMPP commands (`start`, `startapache`, `startmysql`, `startftp`, `stop`, `stopapache`, `stopmysql`, `stopftp`, `reload`, `reloadapache`, `reloadmysql`, `reloadftp`, `backup`, `restart`, `security`, `oci8`, `enablessl`, `disablessl`).
## Contribution
If you find an error or have questions, please report to [issues](https://github.com/ziyaddin/xampp/issues).
## About
Copyright (C) 2019 Ziyaddin Sadigov ([@zsadigov](http://twitter.com/zsadigov)).
| {
"content_hash": "d145717bb72ef2559ac78bb2da2727fc",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 387,
"avg_line_length": 63.04347826086956,
"alnum_prop": 0.72,
"repo_name": "ziyaddin/xampp-cli",
"id": "f40579a503cb3b5b2723bdc4d5143413de6bd1db",
"size": "1462",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "5482"
}
],
"symlink_target": ""
} |
package org.datavaultplatform.broker.controllers.admin;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.datavaultplatform.broker.services.BillingService;
import org.datavaultplatform.broker.services.ExternalMetadataService;
import org.datavaultplatform.broker.services.VaultsService;
import org.datavaultplatform.common.model.BillingInfo;
import org.datavaultplatform.common.model.PendingVault;
import org.datavaultplatform.common.model.Vault;
import org.datavaultplatform.common.response.BillingInformation;
import org.datavaultplatform.common.response.VaultInfo;
import org.datavaultplatform.common.response.VaultsData;
import org.jsondoc.core.annotation.ApiQueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BillingController {
private ExternalMetadataService externalMetadataService;
private VaultsService vaultsService;
private BillingService billingService;
private static final Logger LOGGER = LoggerFactory.getLogger(BillingController.class);
@RequestMapping(value = "/admin/billing/search", method = RequestMethod.GET)
public VaultsData searchAllBillingVaults(@RequestHeader(value = "X-UserID", required = true) String userID,
@RequestParam String query,
@RequestParam(value = "sort", required = false) String sort,
@RequestParam(value = "order", required = false)
@ApiQueryParam(name = "order", description = "Vault sort order", allowedvalues = {"asc", "desc"}, defaultvalue = "asc", required = false) String order,
@RequestParam(value = "offset", required = false)
@ApiQueryParam(name = "offset", description = "Vault row id ", defaultvalue = "0", required = false) String offset,
@RequestParam(value = "maxResult", required = false)
@ApiQueryParam(name = "maxResult", description = "Number of records", required = false) String maxResult) throws Exception {
List<VaultInfo> billingResponses = new ArrayList<>();
int recordsTotal = 0;
int recordsFiltered = 0;
List<Vault> vaults = vaultsService.search(userID, query, sort, order, offset, maxResult);
if(CollectionUtils.isNotEmpty(vaults)) {
for (Vault vault : vaults) {
billingResponses.add(vault.convertToResponseBilling());
}
//calculate and create a map of project size
Map<String, Long> projectSizeMap = vaultsService.getAllProjectsSize();
//update project Size in the response
for(VaultInfo vault: billingResponses) {
if(vault.getProjectId() != null) {
vault.setProjectSize(projectSizeMap.get(vault.getProjectId()));
}
}
recordsTotal = vaultsService.getTotalNumberOfVaults(userID);
recordsFiltered = vaultsService.getTotalNumberOfVaults(userID, query);
}
VaultsData data = new VaultsData();
data.setRecordsTotal(recordsTotal);
data.setRecordsFiltered(recordsFiltered);
data.setData(billingResponses);
return data;
}
@RequestMapping(value = "/admin/billing/{vaultId}", method = RequestMethod.GET)
public BillingInformation getVaultBillingInfo(@RequestHeader(value = "X-UserID", required = true) String userID,
@PathVariable("vaultId") String vaultId) throws Exception {
BillingInformation vaultBillingInfo = vaultsService.getVault(vaultId).convertToBillingDetailsResponse();
return vaultBillingInfo;
}
@RequestMapping(value = "/admin/billing/{vaultid}/updateBilling", method = RequestMethod.POST)
public BillingInformation updateBillingDetails(@RequestHeader(value = "X-UserID", required = true) String userID,
@PathVariable("vaultid") String vaultID,
@RequestBody() BillingInformation billingDetails) throws Exception {
Vault vault = vaultsService.getVault(vaultID);
vault.setProjectId(billingDetails.getProjectId());
vaultsService.updateVault(vault);
if(null!=vault)
{
BillingInfo billinginfo = vault.getBillinginfo();
if(billinginfo == null) {
billinginfo = new BillingInfo();
}
if (billinginfo.getBillingType() == null) {
billinginfo.setBillingType(PendingVault.Billing_Type.ORIG);
}
billinginfo.setAmountBilled(billingDetails.getAmountBilled());
billinginfo.setAmountToBeBilled(billingDetails.getAmountToBeBilled());
billinginfo.setBudgetCode(billingDetails.getBudgetCode());
billinginfo.setContactName(billingDetails.getContactName());
billinginfo.setSchool(billingDetails.getSchool());
billinginfo.setSpecialComments(billingDetails.getSpecialComments());
billinginfo.setSubUnit(billingDetails.getSubUnit());
billinginfo.setVault(vault);
billingService.saveOrUpdateVault(billinginfo);
}
return vault.convertToBillingDetailsResponse();
}
public ExternalMetadataService getExternalMetadataService() {
return externalMetadataService;
}
public void setExternalMetadataService(ExternalMetadataService externalMetadataService) {
this.externalMetadataService = externalMetadataService;
}
public VaultsService getVaultsService() {
return vaultsService;
}
public void setVaultsService(VaultsService vaultsService) {
this.vaultsService = vaultsService;
}
public BillingService getBillingService() {
return billingService;
}
public void setBillingService(BillingService billingService) {
this.billingService = billingService;
}
}
| {
"content_hash": "75df0d7c6c6907acf0c104f1a05b40a4",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 201,
"avg_line_length": 46.21897810218978,
"alnum_prop": 0.7084649399873658,
"repo_name": "DataVault/datavault",
"id": "fd5216cad6144754d926d2d1007f122e064c2177",
"size": "6332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "datavault-broker/src/main/java/org/datavaultplatform/broker/controllers/admin/BillingController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "210721"
},
{
"name": "Dockerfile",
"bytes": "5770"
},
{
"name": "FreeMarker",
"bytes": "498482"
},
{
"name": "HTML",
"bytes": "38493"
},
{
"name": "Java",
"bytes": "1501190"
},
{
"name": "JavaScript",
"bytes": "822575"
},
{
"name": "Less",
"bytes": "51957"
},
{
"name": "Perl",
"bytes": "3891"
},
{
"name": "Shell",
"bytes": "7500"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace BoardingHouse
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
| {
"content_hash": "fad3bf5aecb13b4d6cd9bf00b78e6ade",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 60,
"avg_line_length": 22.61111111111111,
"alnum_prop": 0.687960687960688,
"repo_name": "anovkova/BoardingHouse",
"id": "ab226be31641648c22882ffe906e9e2088320858",
"size": "409",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BoardingHouse/Global.asax.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "104"
},
{
"name": "C#",
"bytes": "62993"
},
{
"name": "CSS",
"bytes": "9410"
},
{
"name": "HTML",
"bytes": "11160"
},
{
"name": "JavaScript",
"bytes": "672470"
}
],
"symlink_target": ""
} |
package net.happybrackets.intellij_plugin.menu;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.IconLoader;
import net.happybrackets.intellij_plugin.controller.ControllerEngine;
import net.happybrackets.intellij_plugin.controller.network.ControllerAdvertiser;
import net.happybrackets.intellij_plugin.controller.network.DeviceConnection;
import net.happybrackets.intellij_plugin.SimulatorShell;
public class RunSimulatorMenu extends AnAction {
public static String getLastSdkPath() {
return lastSdkPath;
}
public static String getLastProjectPath() {
return lastProjectPath;
}
// Add these global variables so we can run this while debugging the plugin
static String lastSdkPath = "";
static String lastProjectPath = "";
// Flag to store if they had multicast on when they ran simulator
boolean multicastOnly = false;
@Override
public void actionPerformed(AnActionEvent e) {
try {
Project current_project = e.getProject();
ProjectRootManager rootManager = ProjectRootManager.getInstance(current_project);
Sdk sdk = rootManager.getProjectSdk();
String sdk_path = sdk.getHomePath() + "/bin/";
DeviceConnection connection = ControllerEngine.getInstance().getDeviceConnection();
ControllerEngine.getInstance().startDeviceCommunication();
// we will make sure we do not have advertising disabled
connection.setDisableAdvertise(false);
String project_path = current_project.getBaseDir().getCanonicalPath();
ControllerAdvertiser advertiser = ControllerEngine.getInstance().getControllerAdvertiser();
if (SimulatorShell.isRunning()){
SimulatorShell.killSimulator();
// we only want
advertiser.setSendLocalHost(false);
}
else {
//displayNotification("Try run Simulator at " + project_path, NotificationType.INFORMATION);
if (SimulatorShell.runSimulator(sdk_path, project_path)){
// we need to advertise on localhost
advertiser.setSendLocalHost(true);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void update(AnActionEvent event) {
try {
String menu_text = "Run Simulator";
String menu_icon = "/icons/play.png";
Project current_project = event.getProject();
String project_path = current_project.getBaseDir().getCanonicalPath();
ProjectRootManager rootManager = ProjectRootManager.getInstance(current_project);
Sdk sdk = rootManager.getProjectSdk();
lastSdkPath = sdk.getHomePath() + "/bin/";
lastProjectPath = project_path;
boolean simulator_exists = SimulatorShell.simulatorExists(project_path);
if (SimulatorShell.isRunning()) {
menu_text = "Stop Simulator";
menu_icon = "/icons/stop.png";
event.getPresentation().setEnabled(true);
}
else{
event.getPresentation().setEnabled(simulator_exists);
}
event.getPresentation().setText(menu_text);
event.getPresentation().setIcon(IconLoader.getIcon(menu_icon));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| {
"content_hash": "2016577691651bc535049cb6cfb8ca74",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 108,
"avg_line_length": 34.94392523364486,
"alnum_prop": 0.6474993313720246,
"repo_name": "orsjb/HappyBrackets",
"id": "943bfa9ebe698a804dd92639936fd9e116bde0df",
"size": "3739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IntelliJ Plugin/src/net/happybrackets/intellij_plugin/menu/RunSimulatorMenu.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "436"
},
{
"name": "CSS",
"bytes": "12842"
},
{
"name": "Groovy",
"bytes": "384"
},
{
"name": "HTML",
"bytes": "4861342"
},
{
"name": "Java",
"bytes": "1905535"
},
{
"name": "JavaScript",
"bytes": "827"
},
{
"name": "PHP",
"bytes": "3097"
},
{
"name": "Python",
"bytes": "230"
},
{
"name": "Shell",
"bytes": "47737"
}
],
"symlink_target": ""
} |
using System;
using Collectively.Messages.Commands;
using Collectively.Common.Domain;
using Collectively.Common.Services;
using It = Machine.Specifications.It;
using RawRabbit;
using Moq;
using Collectively.Services.Remarks.Services;
using Collectively.Services.Remarks.Handlers;
using Collectively.Messages.Commands.Remarks;
using Collectively.Messages.Events.Remarks;
using Machine.Specifications;
using RawRabbit.Pipe;
using System.Threading;
namespace Collectively.Services.Remarks.Tests.Specs.Handlers
{
public abstract class DeleteRemarkHandler_specs : SpecsBase
{
protected static DeleteRemarkHandler DeleteRemarkHandler;
protected static IHandler Handler;
protected static Mock<IRemarkService> RemarkServiceMock;
protected static Mock<IGroupService> GroupServiceMock;
protected static Mock<IExceptionHandler> ExceptionHandlerMock;
protected static Mock<IResourceFactory> ResourceFactoryMock;
protected static DeleteRemark Command;
protected static Exception Exception;
protected static void Initialize()
{
InitializeBus();
ExceptionHandlerMock = new Mock<IExceptionHandler>();
Handler = new Handler(ExceptionHandlerMock.Object);
RemarkServiceMock = new Mock<IRemarkService>();
GroupServiceMock = new Mock<IGroupService>();
ResourceFactoryMock = new Mock<IResourceFactory>();
Command = new DeleteRemark
{
Request = new Request
{
Name = "delete_remark",
Id = Guid.NewGuid(),
CreatedAt = DateTime.Now,
Origin = "test",
Resource = ""
},
UserId = "userId",
RemarkId = Guid.NewGuid()
};
DeleteRemarkHandler = new DeleteRemarkHandler(Handler, BusClientMock.Object,
RemarkServiceMock.Object, GroupServiceMock.Object, ResourceFactoryMock.Object);
}
}
[Subject("DeleteRemarkHandler HandleAsync")]
public class when_invoking_delete_remark_handle_async : DeleteRemarkHandler_specs
{
Establish context = () =>
{
Initialize();
};
Because of = () => DeleteRemarkHandler.HandleAsync(Command).Await();
It should_call_delete_async_on_remark_service = () =>
{
RemarkServiceMock.Verify(x => x.DeleteAsync(Command.RemarkId), Times.Once);
};
It should_publish_remark_deleted_event = () =>
{
VerifyPublishAsync(Moq.It.IsAny<RemarkDeleted>(), Times.Once);
};
}
[Subject("DeleteRemarkHandler HandleAsync")]
public class when_invoking_delete_remark_handle_async_and_service_throws_exception : DeleteRemarkHandler_specs
{
protected static string ErrorCode = "Error";
Establish context = () =>
{
Initialize();
RemarkServiceMock.Setup(x => x.DeleteAsync(Command.RemarkId))
.Throws(new ServiceException(ErrorCode));
};
Because of = () => Exception = Catch.Exception(() => DeleteRemarkHandler.HandleAsync(Command).Await());
It should_call_delete_async_on_remark_service = () =>
{
RemarkServiceMock.Verify(x => x.DeleteAsync(Command.RemarkId), Times.Once);
};
It should_not_publish_remark_deleted_event = () =>
{
VerifyPublishAsync(Moq.It.IsAny<RemarkDeleted>(), Times.Never);
};
It should_publish_delete_remark_rejected_message = () =>
{
VerifyPublishAsync(Moq.It.Is<DeleteRemarkRejected>(m =>
m.RequestId == Command.Request.Id
&& m.RemarkId == Command.RemarkId
&& m.UserId == Command.UserId
&& m.Code == ErrorCode), Times.Once);
};
}
} | {
"content_hash": "c493e39963ad2c2751b2c43e13d14e3c",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 114,
"avg_line_length": 36.00909090909091,
"alnum_prop": 0.6167634435748548,
"repo_name": "noordwind/Collectively.Services.Remarks",
"id": "41bf7f639ab05ffbfb4d50a43563b14abff63a7d",
"size": "3963",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/Collectively.Services.Remarks.Tests/Specs/Handlers/DeleteRemarkHandler_specs.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "305982"
},
{
"name": "Shell",
"bytes": "1540"
}
],
"symlink_target": ""
} |
package integration
import (
"testing"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/apis/autoscaling"
"k8s.io/kubernetes/pkg/apis/batch"
expapi "k8s.io/kubernetes/pkg/apis/extensions"
extensions_v1beta1 "k8s.io/kubernetes/pkg/apis/extensions/v1beta1"
kclientset14 "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_4"
testutil "github.com/openshift/origin/test/util"
testserver "github.com/openshift/origin/test/util/server"
)
func TestExtensionsAPIDisabledAutoscaleBatchEnabled(t *testing.T) {
const projName = "ext-disabled-batch-enabled-proj"
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterConfig, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Disable all extensions API versions
// Leave autoscaling/batch APIs enabled
masterConfig.KubernetesMasterConfig.DisabledAPIGroupVersions = map[string][]string{"extensions": {"*"}}
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminKubeClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// create the containing project
if _, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, projName, "admin"); err != nil {
t.Fatalf("unexpected error creating the project: %v", err)
}
projectAdminClient, projectAdminKubeClient, projectAdminKubeConfig, err := testutil.GetClientForUser(*clusterAdminClientConfig, "admin")
if err != nil {
t.Fatalf("unexpected error getting project admin client: %v", err)
}
projectAdminKubeClient14 := kclientset14.NewForConfigOrDie(projectAdminKubeConfig)
if err := testutil.WaitForPolicyUpdate(projectAdminClient, projName, "get", expapi.Resource("horizontalpodautoscalers"), true); err != nil {
t.Fatalf("unexpected error waiting for policy update: %v", err)
}
validHPA := &autoscaling.HorizontalPodAutoscaler{
ObjectMeta: kapi.ObjectMeta{Name: "myjob"},
Spec: autoscaling.HorizontalPodAutoscalerSpec{
ScaleTargetRef: autoscaling.CrossVersionObjectReference{Name: "foo", Kind: "ReplicationController"},
MaxReplicas: 1,
},
}
validJob := &batch.Job{
ObjectMeta: kapi.ObjectMeta{Name: "myjob"},
Spec: batch.JobSpec{
Template: kapi.PodTemplateSpec{
Spec: kapi.PodSpec{
Containers: []kapi.Container{{Name: "mycontainer", Image: "myimage"}},
RestartPolicy: kapi.RestartPolicyNever,
},
},
},
}
legacyAutoscalers := legacyExtensionsAutoscaling{
projectAdminKubeClient.Autoscaling().HorizontalPodAutoscalers(projName),
projectAdminKubeClient.ExtensionsClient.RESTClient,
projName,
}
// make sure extensions API objects cannot be listed or created
if _, err := legacyAutoscalers.List(kapi.ListOptions{}); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error listing HPA, got %v", err)
}
if _, err := legacyAutoscalers.Create(validHPA); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error creating HPA, got %v", err)
}
if _, err := projectAdminKubeClient14.Extensions().Jobs(projName).List(kapi.ListOptions{}); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error listing jobs, got %v", err)
}
if _, err := projectAdminKubeClient14.Extensions().Jobs(projName).Create(&extensions_v1beta1.Job{}); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error creating job, got %v", err)
}
// make sure autoscaling and batch API objects can be listed and created
if _, err := projectAdminKubeClient.Autoscaling().HorizontalPodAutoscalers(projName).List(kapi.ListOptions{}); err != nil {
t.Fatalf("unexpected error: %#v", err)
}
if _, err := projectAdminKubeClient.Autoscaling().HorizontalPodAutoscalers(projName).Create(validHPA); err != nil {
t.Fatalf("unexpected error: %#v", err)
}
if _, err := projectAdminKubeClient.Batch().Jobs(projName).List(kapi.ListOptions{}); err != nil {
t.Fatalf("unexpected error: %#v", err)
}
if _, err := projectAdminKubeClient.Batch().Jobs(projName).Create(validJob); err != nil {
t.Fatalf("unexpected error: %#v", err)
}
// Delete the containing project
if err := testutil.DeleteAndWaitForNamespaceTermination(clusterAdminKubeClient, projName); err != nil {
t.Fatalf("unexpected error: %#v", err)
}
// recreate the containing project
if _, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, projName, "admin"); err != nil {
t.Fatalf("unexpected error creating the project: %v", err)
}
projectAdminClient, projectAdminKubeClient, _, err = testutil.GetClientForUser(*clusterAdminClientConfig, "admin")
if err != nil {
t.Fatalf("unexpected error getting project admin client: %v", err)
}
if err := testutil.WaitForPolicyUpdate(projectAdminClient, projName, "get", expapi.Resource("horizontalpodautoscalers"), true); err != nil {
t.Fatalf("unexpected error waiting for policy update: %v", err)
}
// make sure the created objects got cleaned up by namespace deletion
if hpas, err := projectAdminKubeClient.Autoscaling().HorizontalPodAutoscalers(projName).List(kapi.ListOptions{}); err != nil {
t.Fatalf("unexpected error: %#v", err)
} else if len(hpas.Items) > 0 {
t.Fatalf("expected 0 HPA objects, got %#v", hpas.Items)
}
if jobs, err := projectAdminKubeClient.Batch().Jobs(projName).List(kapi.ListOptions{}); err != nil {
t.Fatalf("unexpected error: %#v", err)
} else if len(jobs.Items) > 0 {
t.Fatalf("expected 0 Job objects, got %#v", jobs.Items)
}
}
func TestExtensionsAPIDisabled(t *testing.T) {
const projName = "ext-disabled-proj"
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterConfig, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Disable all extensions API versions
masterConfig.KubernetesMasterConfig.DisabledAPIGroupVersions = map[string][]string{"extensions": {"*"}, "autoscaling": {"*"}, "batch": {"*"}}
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminKubeClient, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// create the containing project
if _, err := testserver.CreateNewProject(clusterAdminClient, *clusterAdminClientConfig, projName, "admin"); err != nil {
t.Fatalf("unexpected error creating the project: %v", err)
}
projectAdminClient, projectAdminKubeClient, projectAdminKubeConfig, err := testutil.GetClientForUser(*clusterAdminClientConfig, "admin")
if err != nil {
t.Fatalf("unexpected error getting project admin client: %v", err)
}
projectAdminKubeClient14 := kclientset14.NewForConfigOrDie(projectAdminKubeConfig)
if err := testutil.WaitForPolicyUpdate(projectAdminClient, projName, "get", expapi.Resource("horizontalpodautoscalers"), true); err != nil {
t.Fatalf("unexpected error waiting for policy update: %v", err)
}
legacyAutoscalers := legacyExtensionsAutoscaling{
projectAdminKubeClient.Autoscaling().HorizontalPodAutoscalers(projName),
projectAdminKubeClient.AutoscalingClient.RESTClient,
projName,
}
// make sure extensions API objects cannot be listed or created
if _, err := legacyAutoscalers.List(kapi.ListOptions{}); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error listing HPA, got %v", err)
}
if _, err := legacyAutoscalers.Create(&autoscaling.HorizontalPodAutoscaler{}); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error creating HPA, got %v", err)
}
if _, err := projectAdminKubeClient14.Extensions().Jobs(projName).List(kapi.ListOptions{}); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error listing jobs, got %v", err)
}
if _, err := projectAdminKubeClient14.Extensions().Jobs(projName).Create(&extensions_v1beta1.Job{}); !errors.IsNotFound(err) {
t.Fatalf("expected NotFound error creating job, got %v", err)
}
// Delete the containing project
if err := testutil.DeleteAndWaitForNamespaceTermination(clusterAdminKubeClient, projName); err != nil {
t.Fatalf("unexpected error: %#v", err)
}
}
| {
"content_hash": "2b9451cda2bb04a586df6327962c0006",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 142,
"avg_line_length": 40.591743119266056,
"alnum_prop": 0.7421177534184653,
"repo_name": "chmouel/origin",
"id": "cc69fc9c4d6107a17489cce876e83f30e08a2468",
"size": "8849",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "test/integration/extensions_api_disabled_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Go",
"bytes": "13144121"
},
{
"name": "Groff",
"bytes": "2049"
},
{
"name": "Makefile",
"bytes": "8481"
},
{
"name": "Protocol Buffer",
"bytes": "542565"
},
{
"name": "Python",
"bytes": "16665"
},
{
"name": "Ruby",
"bytes": "363"
},
{
"name": "Shell",
"bytes": "2332694"
}
],
"symlink_target": ""
} |
import options from './options';
import importHelper from '../helpers/import';
jest.mock('../helpers/import', () => ({
importTabGroupsJson: jest.fn().mockImplementation(() => Promise.resolve()),
}));
describe('options', () => {
describe('#import', () => {
beforeEach(() => {
options.showImportProgress = jest.fn();
options.showImportMessage = jest.fn();
delete options.importField;
options.importField = { value: '{ "foo": "bar" }' };
options.port = { postMessage: jest.fn() };
});
test('imports JSON data and displays success message', () =>
options.import().then(() => {
expect(importHelper.importTabGroupsJson.mock.calls).toMatchSnapshot();
expect(options.showImportProgress).toBeCalled();
expect(options.showImportMessage.mock.calls).toMatchSnapshot();
}));
test('imports JSON data and displays failed folder/bookmark creations', () => {
importHelper.importTabGroupsJson = jest.fn().mockImplementation((json, errorCallback) => {
errorCallback({ type: 'folder', name: 'Group A', error: 'Folder creation failed' });
errorCallback({ type: 'bookmark', name: 'https://developer.mozilla.org/en-US/', error: 'Bookmark creation failed' });
errorCallback({ type: 'bookmark', name: 'https://github.com/', error: 'Bookmark creation failed' });
return Promise.resolve();
});
return options.import().then(() => {
expect(importHelper.importTabGroupsJson.mock.calls).toMatchSnapshot();
expect(options.showImportProgress).toBeCalled();
expect(options.showImportMessage.mock.calls).toMatchSnapshot();
});
});
test('displays error on complete import failure', () => {
importHelper.importTabGroupsJson = jest.fn().mockImplementation(() => Promise.reject('Bad'));
return options.import().then(() => {
expect(importHelper.importTabGroupsJson.mock.calls).toMatchSnapshot();
expect(options.showImportProgress).toBeCalled();
expect(options.showImportMessage.mock.calls).toMatchSnapshot();
});
});
});
});
| {
"content_hash": "0b4353adc93ef418af5f25838fb11370",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 125,
"avg_line_length": 44,
"alnum_prop": 0.6472537878787878,
"repo_name": "hupf/tabmarks",
"id": "c99e5c3cbee593c41fa1acfaa6f8759c92a52b52",
"size": "2112",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/options/options.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "986"
},
{
"name": "HTML",
"bytes": "4873"
},
{
"name": "JavaScript",
"bytes": "43417"
}
],
"symlink_target": ""
} |
package com.zhou.android.main;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.zhou.android.R;
import com.zhou.android.common.BaseActivity;
import com.zhou.android.common.Tools;
/**
* ScrollView 自动滑动
* <p>
* Created by ZhOu on 2017/3/23.
*/
public class ScrollTestActivity extends BaseActivity {
private ScrollView scrollView;
private LinearLayout ll_content;
private Handler handler = new Handler();
private int padding = 0;
@Override
protected void setContentView() {
setContentView(R.layout.activity_scroll);
}
@Override
protected void init() {
scrollView = (ScrollView) findViewById(R.id.scrollView);
ll_content = (LinearLayout) findViewById(R.id.ll_content);
padding = Tools.dip2px(this, 15);
for (int i = 1; i < 8; i++) {
addItem("ItemTitle_" + i, "ItemContent_" + i);
}
}
@Override
protected void addListener() {
}
private void addItem(String title, String content) {
final TextView tv_title = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = padding / 3;
tv_title.setLayoutParams(params);
tv_title.setTextColor(Color.WHITE);
tv_title.setPadding(padding, padding, padding, padding);
tv_title.setBackgroundColor(Color.rgb(60, 120, 216));
Drawable drawable = getResources().getDrawable(R.drawable.btn_status);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tv_title.setCompoundDrawables(null, null, drawable, null);
tv_title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
tv_title.setText(title);
tv_title.setSelected(false);
final TextView tv_content = new TextView(this);
tv_content.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Tools.dip2px(this, 200)));
tv_content.setTextColor(Color.BLACK);
tv_content.setGravity(Gravity.CENTER);
tv_content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
tv_content.setText(content);
tv_content.setVisibility(View.GONE);
tv_title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
boolean show = tv_title.isSelected();
tv_title.setSelected(!show);
tv_content.setVisibility(show ? View.GONE : View.VISIBLE);
if (!show)
handler.postDelayed(new Runnable() {
@Override
public void run() {
int[] loc = new int[2];
v.getLocationOnScreen(loc);
int offset = loc[1] - v.getHeight() - padding * 2;//v.getTop();
if (offset < 0)
offset = 0;
scrollView.smoothScrollBy(0, offset);
}
}, 200);
}
});
ll_content.addView(tv_title);
ll_content.addView(tv_content);
}
}
| {
"content_hash": "a52ad2ef9ffa1091c46c1283d7cc3456",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 153,
"avg_line_length": 35.86734693877551,
"alnum_prop": 0.615931721194879,
"repo_name": "Zhouzhouzhou/AndroidDemo",
"id": "f005b5871cf0d8f812995a82520ab6cf037099ea",
"size": "3523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/zhou/android/main/ScrollTestActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AIDL",
"bytes": "1149"
},
{
"name": "HTML",
"bytes": "787"
},
{
"name": "Java",
"bytes": "438499"
},
{
"name": "Kotlin",
"bytes": "208112"
}
],
"symlink_target": ""
} |
.class public final Lcom/google/android/gms/ads/R;
.super Ljava/lang/Object;
.source "R.java"
# annotations
.annotation system Ldalvik/annotation/MemberClasses;
value = {
Lcom/google/android/gms/ads/R$styleable;,
Lcom/google/android/gms/ads/R$xml;,
Lcom/google/android/gms/ads/R$style;,
Lcom/google/android/gms/ads/R$string;,
Lcom/google/android/gms/ads/R$raw;,
Lcom/google/android/gms/ads/R$layout;,
Lcom/google/android/gms/ads/R$integer;,
Lcom/google/android/gms/ads/R$id;,
Lcom/google/android/gms/ads/R$drawable;,
Lcom/google/android/gms/ads/R$dimen;,
Lcom/google/android/gms/ads/R$color;,
Lcom/google/android/gms/ads/R$attr;,
Lcom/google/android/gms/ads/R$anim;
}
.end annotation
# direct methods
.method public constructor <init>()V
.registers 1
.prologue
.line 10
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
| {
"content_hash": "02f7e8e06d4bbf805f4f113683325de9",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 53,
"avg_line_length": 28.057142857142857,
"alnum_prop": 0.654786150712831,
"repo_name": "shenxdtw/PokemonGo-Plugin",
"id": "2cf548f393b2f3fb7bc6c16aaf236ec5eead5b94",
"size": "982",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PokemonGo_Smali/com/google/android/gms/ads/R.smali",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Smali",
"bytes": "35925787"
}
],
"symlink_target": ""
} |
package hudson.plugins.robot.graph;
import hudson.model.FreeStyleBuild;
import hudson.plugins.robot.RobotParser;
import hudson.plugins.robot.model.RobotResult;
import junit.framework.TestCase;
import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.mockito.Mockito.*;
public class RobotGraphHelperTest extends TestCase {
private static final String xLabelFormat = "#$build";
private RobotResult mockResult1;
private RobotResult mockResult2;
protected void setUp() throws Exception {
super.setUp();
RobotParser.RobotParserCallable remoteOperation = new RobotParser.RobotParserCallable("output.xml", null, null);
RobotResult result = remoteOperation.invoke(new File(new RobotGraphHelperTest().getClass().getResource("output.xml").toURI()).getParentFile(), null);
result.tally(null);
// Mocked builds to play as owners of test results
FreeStyleBuild mockBuild1 = mock(FreeStyleBuild.class);
FreeStyleBuild mockBuild2 = mock(FreeStyleBuild.class);
when(mockBuild2.compareTo(mockBuild1)).thenReturn(1);
when(mockBuild1.compareTo(mockBuild2)).thenReturn(-1);
// This is to pass hudson.util.Graph constructor
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(0L);
when(mockBuild1.getTimestamp()).thenReturn(c);
when(mockBuild2.getTimestamp()).thenReturn(c);
// set up some results chains
mockResult1 = spy(result);
doReturn(null).when(mockResult1).getPreviousResult();
doReturn(mockBuild1).when(mockResult1).getOwner();
mockResult2 = spy(result);
doReturn(mockResult1).when(mockResult2).getPreviousResult();
doReturn(mockBuild2).when(mockResult2).getOwner();
}
public void testShouldLimitResultsGraphDataSet() throws Exception {
RobotGraph limitedResultsGraph = RobotGraphHelper.createTestResultsGraphForTestObject(
mockResult2, false, false, false, false, false, xLabelFormat,1);
assertEquals(1, limitedResultsGraph.getDataset().getColumnCount());
}
public void testShouldReturnAllResultsGraphDataIfNotLimited() throws Exception {
RobotGraph notlimitedResultsGraph = RobotGraphHelper.createTestResultsGraphForTestObject(
mockResult2, false, false, false, false, false, xLabelFormat,0);
assertEquals(2, notlimitedResultsGraph.getDataset().getColumnCount());
}
public void testShouldReturnAllResultsGraphDataIfLimitIsBiggerThanDataAmount() throws Exception {
RobotGraph notlimitedResultsGraph = RobotGraphHelper.createTestResultsGraphForTestObject(
mockResult2, false, false, false, false, false, xLabelFormat,10);
assertEquals(2, notlimitedResultsGraph.getDataset().getColumnCount());
}
public void testShouldLimitDurationGraphDataSet() throws Exception {
RobotGraph limitedResultsGraph = RobotGraphHelper.createDurationGraphForTestObject(
mockResult2, false, 1,xLabelFormat,false);
assertEquals(1, limitedResultsGraph.getDataset().getColumnCount());
}
public void testShouldReturnAllDurationGraphDataIfNotLimited() throws Exception {
RobotGraph notlimitedResultsGraph = RobotGraphHelper.createDurationGraphForTestObject(
mockResult2, false, 0, xLabelFormat,false);
assertEquals(2, notlimitedResultsGraph.getDataset().getColumnCount());
}
public void testShouldReturnAllDurationDataIfLimitIsBiggerThanDataAmount() throws Exception {
RobotGraph notlimitedResultsGraph = RobotGraphHelper.createDurationGraphForTestObject(
mockResult2, false, 10, xLabelFormat,false);
assertEquals(2, notlimitedResultsGraph.getDataset().getColumnCount());
}
}
| {
"content_hash": "cc84676b682572fc3f7935a42d49a1ca",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 151,
"avg_line_length": 38.924731182795696,
"alnum_prop": 0.7806629834254144,
"repo_name": "jenkinsci/robot-plugin",
"id": "6096f52fb2145b902b6768289e89452d619d9009",
"size": "4238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/hudson/plugins/robot/graph/RobotGraphHelperTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1690399"
},
{
"name": "Java",
"bytes": "219164"
},
{
"name": "JavaScript",
"bytes": "4632"
}
],
"symlink_target": ""
} |
<?php
namespace Google\Service\Monitoring;
class ListAlertPoliciesResponse extends \Google\Collection
{
protected $collection_key = 'alertPolicies';
protected $alertPoliciesType = AlertPolicy::class;
protected $alertPoliciesDataType = 'array';
/**
* @var string
*/
public $nextPageToken;
/**
* @var int
*/
public $totalSize;
/**
* @param AlertPolicy[]
*/
public function setAlertPolicies($alertPolicies)
{
$this->alertPolicies = $alertPolicies;
}
/**
* @return AlertPolicy[]
*/
public function getAlertPolicies()
{
return $this->alertPolicies;
}
/**
* @param string
*/
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
/**
* @return string
*/
public function getNextPageToken()
{
return $this->nextPageToken;
}
/**
* @param int
*/
public function setTotalSize($totalSize)
{
$this->totalSize = $totalSize;
}
/**
* @return int
*/
public function getTotalSize()
{
return $this->totalSize;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ListAlertPoliciesResponse::class, 'Google_Service_Monitoring_ListAlertPoliciesResponse');
| {
"content_hash": "3ecc83edbf326f44cabff83ec8605d2e",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 101,
"avg_line_length": 19.307692307692307,
"alnum_prop": 0.6613545816733067,
"repo_name": "googleapis/google-api-php-client-services",
"id": "5e1fed8f6e3dfea01f489992fe09e9734cfc23ab",
"size": "1845",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "src/Monitoring/ListAlertPoliciesResponse.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "55414116"
},
{
"name": "Python",
"bytes": "427325"
},
{
"name": "Shell",
"bytes": "787"
}
],
"symlink_target": ""
} |
@interface GLHomeViewController : UIViewController
@end
| {
"content_hash": "ccc40ffe7828ff45fc53f72ca2446a10",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 50,
"avg_line_length": 19,
"alnum_prop": 0.8421052631578947,
"repo_name": "CoderGLMumu/Revaluation_Bili_iOS",
"id": "bd3ec88aa55acba47900b82d89a3667265be73db",
"size": "222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "revaluation_Bili/revaluation_Bili/Classes/1Home(首页)/0Home(首页)/ViewController/GLHomeViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "851963"
},
{
"name": "Ruby",
"bytes": "482"
},
{
"name": "Swift",
"bytes": "11964"
}
],
"symlink_target": ""
} |
"use strict"
import IPFS from "ipfs"
import Room from "ipfs-pubsub-room"
const ipfs = new IPFS({
repo: repo(),
EXPERIMENTAL: {
pubsub: true
}
})
function repo() {
// random repo path -> multiple ipfs nodes in the same browser
return "ipfs/ipfs-chat/" + Math.random()
}
ipfs.once("ready", () => ipfs.id((err, info) => {
if (err) { throw err }
myId = info.id
peerInfo[info.id] = {
id: info.id,
number: 0,
name: myName ? myName : info.id.slice(-6)
}
chat.addMessage({type: "system", data: "IPFS node ready with address " + info.id})
}))
ipfs.on("error", (err) => chat.addMessage({type: "error", data: "IpfsError: " + err}))
const room = Room(ipfs, "ipfs-chat-room")
room.on("peer joined", (peer) => {
if (myName) {
room.sendTo(peer, JSON.stringify({name: myName}))
}
chat.addMessage({type: "system", data: "Peer " + formatName(peer) + " joined."})
})
room.on("peer left", (peer) =>
chat.addMessage({type: "system", data: "Peer " + formatName(peer) + " left."}))
room.on("message", (message) => {
try {
// interpret data as JSON
let data = JSON.parse(message.data)
if (data.msg) {
chat.addMessage({type: "chat", name: formatName(message.from), data: data.msg})
} else if (data.priv) {
lastPrivateFrom = message.from
chat.addMessage({type: "chat", name: "From " + formatName(message.from), data: data.priv})
} else if (data.name) {
let info = getInfo(message.from)
chat.addMessage({
type: "system",
name: formatName(info.id),
data: "is now known as [" + data.name + "]."
})
info.name = data.name
}
} catch(err) {
if (err.name == "SyntaxError") {
// JSON.parse() failed
console.log("Error: not JSON: " + message.data)
} else {
throw err
}
}
})
room.on("error", (err) => chat.addMessage({type: "error", data: "RoomError: " + err}))
var lastPrivateFrom = undefined
var myId = undefined
var myName = undefined
var counter = 0
var peerInfo = {}
/* Get info to a given peer id. Always returns an object. */
function getInfo(id) {
var info = peerInfo[id]
if (!info) {
info = peerInfo[id] = {
id: id,
number: ++counter,
name: id.slice(-6)
}
}
return info
}
function formatName(id) {
if (!id) { return "" }
let info = getInfo(id)
return "[" + info.number + (info.name ? ":" + info.name : "") + "]"
}
/* Try to find a peer identified by a given string. Either by name, number, or id. */
function findInfo(string) {
var result = undefined
Object.keys(peerInfo).forEach((id) => {
let peer = peerInfo[id]
if (string == peer.number || string == peer.id) {
result = peer
return // break forEach
} else if (peer.name.toUpperCase().startsWith(string.toUpperCase())) {
result = peer
}
})
return result
}
/* Send a private message if the peer is in the room. */
function trySendTo(id, message) {
if (room.hasPeer(id)) {
chat.addMessage({type: "chat", name: "To " + formatName(id), data: message})
room.sendTo(id, JSON.stringify({priv: message}))
} else {
chat.addSystemMessage("Peer is not available.")
}
}
/* Inititalize ChatBox and CommandParser */
import ChatBox from "./chat-box.js"
import CommandParser from "./command-parser.js"
const chat = new ChatBox("chat_box")
const parser = new CommandParser((feedback) => chat.addSystemMessage(feedback))
chat.on("input", (message) => {
if (!parser.parse(message)) {
room.broadcast(JSON.stringify({msg: message}))
}
})
parser.addHelpCommand()
parser.addCommand("whoami", "Display your own id and name.", () => {
if (myId) {
let info = getInfo(myId)
chat.addSystemMessage("I am " + info.id + ", known as " + info.name + ".")
} else {
// ipfs not started
chat.addSystemMessage("I am " + myName + ".")
}
})
parser.addCommand("peers", "List all known peers.", () => {
room.getPeers()
.map(id => getInfo(id))
.sort((a, b) => { return a.number - b.number })
.forEach((peer) => {
chat.addSystemMessage(formatName(peer.id) + " " + peer.id)
})
})
parser.addCommand("name", "Change your name.", (_, ...rest) => {
let name = rest.join(" ")
myName = name
if (myId) {
if (!name) { name = myId.slice(-6) }
room.broadcast(JSON.stringify({name: name}))
}
})
parser.addCommand("w", "Whisper to a selected peer.", (_, target, ...rest) => {
let peer = findInfo(target)
if (!peer) {
chat.addSystemMessage("Unknown peer: " + target)
return
}
trySendTo(peer.id, rest.join(" "))
})
parser.addCommand("r", "Reply to last private message.", (_, ...rest) => {
trySendTo(lastPrivateFrom, rest.join(" "))
})
parser.addCommand("clear", "Clear the chat. Removes all messages.", () => {
chat.clear()
})
| {
"content_hash": "9e1ffe12d1925b443cbcbdc2f1e1985c",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 96,
"avg_line_length": 27.15340909090909,
"alnum_prop": 0.6047290228081188,
"repo_name": "t-gebauer/ipfs-chat",
"id": "170e094a796e5e59391ba564c6ef016be26a778f",
"size": "4779",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "746"
},
{
"name": "HTML",
"bytes": "270"
},
{
"name": "JavaScript",
"bytes": "7552"
}
],
"symlink_target": ""
} |
import RvApp from './rv-app.vue';
export { RvApp };
| {
"content_hash": "3c2ab65d9ed68fead16c5d7921a61f1d",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 33,
"avg_line_length": 26,
"alnum_prop": 0.6538461538461539,
"repo_name": "nobelhuang/rackview",
"id": "2e96709084e67dc1e8ccdfd1799015021df4d6e1",
"size": "52",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/app/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3056"
},
{
"name": "HTML",
"bytes": "196"
},
{
"name": "JavaScript",
"bytes": "20868"
},
{
"name": "TypeScript",
"bytes": "2199"
},
{
"name": "Vue",
"bytes": "7179"
}
],
"symlink_target": ""
} |
"use strict";
const ESLint = require("../utils/eslint");
const chai = require("chai");
chai.should();
describe("modules/esm", function () {
it("should not be enforced if module is not used", function () {
let results = ESLint.run("@jsdevtools/modular/es6",
"const foo = 5;\n" +
"let bar = { foo: foo };"
);
results.errorCount.should.equal(0);
});
it('should not allow the "use strict" pragma', function () {
let results = ESLint.run("@jsdevtools/modular/modules/esm", '"use strict";');
results.errorCount.should.equal(1);
results.rules.should.deep.equal(["strict"]);
results.messages[0].message.should.equal("'use strict' is unnecessary inside of modules.");
});
it("should allow ES6 module syntax", function () {
let results = ESLint.run(
["@jsdevtools/modular/es6", "@jsdevtools/modular/modules/esm"],
"import foo from 'bar';"
);
results.errorCount.should.equal(0);
});
it('should not allow ES6 module syntax if followed by the "modules/cjs" module', function () {
let results = ESLint.run(
["@jsdevtools/modular/es6", "@jsdevtools/modular/modules/esm", "@jsdevtools/modular/modules/cjs"],
"import foo from 'bar';"
);
results.errorCount.should.equal(1);
results.messages.should.have.lengthOf(1);
results.messages[0].message.should.equal("Parsing error: 'import' and 'export' may appear only with 'sourceType: module'");
});
});
| {
"content_hash": "e582bd96455a127e48991996cf972802",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 127,
"avg_line_length": 36.175,
"alnum_prop": 0.6516931582584657,
"repo_name": "BigstickCarpet/eslint-config-modular",
"id": "df5c626968a90982c352cf04cacdcc4caa6c154d",
"size": "1447",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/specs/modules-esm.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "31470"
}
],
"symlink_target": ""
} |
import React, { useState, useCallback, useEffect } from 'react';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useMulti } from '../../lib/crud/withMulti';
import moment from '../../lib/moment-timezone';
import { timeframeToTimeBlock, TimeframeType } from './timeframeUtils'
import { useTimezone } from '../common/withTimezone';
import { QueryLink } from '../../lib/reactRouterWrapper';
import type { ContentTypeString } from './PostsPage/ContentType';
const styles = (theme: ThemeType): JssStyles => ({
root: {
marginBottom: theme.spacing.unit*4
},
timeBlockTitle: {
whiteSpace: "pre",
textOverflow: "ellipsis",
...theme.typography.postStyle,
position: "sticky",
paddingTop: 4,
paddingBottom: 4,
zIndex: 1
},
smallScreenTitle: {
[theme.breakpoints.down('xs')]: {
display: "none",
},
},
largeScreenTitle: {
[theme.breakpoints.up('sm')]: {
display: "none",
},
},
loadMore: {
marginTop: 6,
},
noPosts: {
marginLeft: "23px",
color: "rgba(0,0,0,0.5)",
},
posts: {
boxShadow: theme.boxShadow
},
frontpageSubtitle: {
marginBottom: 6
},
otherSubtitle: {
marginTop: 6,
marginBottom: 6
},
divider: {/* Exists only to get overriden by the eaTheme */}
})
interface PostTypeOptions {
name: ContentTypeString
postIsType: (post: PostsBase)=>boolean
label: string
}
const postTypes: PostTypeOptions[] = [
{name: 'frontpage', postIsType: (post: PostsBase) => !!post.frontpageDate, label: 'Frontpage Posts'},
{name: 'personal', postIsType: (post: PostsBase) => !post.frontpageDate, label: 'Personal Blogposts'}
]
const PostsTimeBlock = ({ terms, timeBlockLoadComplete, startDate, hideIfEmpty, timeframe, displayShortform=true, classes, includeTags=true}: {
terms: PostsViewTerms,
timeBlockLoadComplete: ()=>void,
startDate: any,
hideIfEmpty: boolean,
timeframe: TimeframeType,
displayShortform: any,
classes: ClassesType,
includeTags?: boolean,
}) => {
const [noShortform, setNoShortform] = useState(false);
const [noTags, setNoTags] = useState(false);
const { timezone } = useTimezone();
const { results: posts, totalCount, loading, loadMoreProps } = useMulti({
terms,
collectionName: "Posts",
fragmentName: 'PostsList',
enableTotal: true,
itemsPerPage: 50,
});
useEffect(() => {
if (!loading && timeBlockLoadComplete) {
timeBlockLoadComplete();
}
// No dependency list because we want this to be called even when it looks
// like nothing has changed, to signal loading is complete
});
// Child component needs a way to tell us about the presence of shortforms
const reportEmptyShortform = useCallback(() => {
setNoShortform(true);
}, []);
const reportEmptyTags = useCallback(() => {
setNoTags(true);
}, []);
const getTitle = (startDate, timeframe, size) => {
if (timeframe === 'yearly') return startDate.format('YYYY')
if (timeframe === 'monthly') return startDate.format('MMMM YYYY')
let result = size === 'smUp' ? startDate.format('ddd, MMM Do YYYY') : startDate.format('dddd, MMMM Do YYYY')
if (timeframe === 'weekly') result = `Week Of ${result}`
return result
}
const render = () => {
const { PostsItem2, LoadMore, ShortformTimeBlock, TagEditsTimeBlock, ContentType, Divider, Typography } = Components
const timeBlock = timeframeToTimeBlock[timeframe]
const noPosts = !loading && (!posts || (posts.length === 0))
// The most recent timeBlock is hidden if there are no posts or shortforms
// on it, to avoid having an awkward empty partial timeBlock when it's close
// to midnight.
if (noPosts && noShortform && noTags && hideIfEmpty) {
return null
}
const postGroups = postTypes.map(type => ({
...type,
posts: posts?.filter(type.postIsType) || []
}))
return (
<div className={classes.root}>
<QueryLink merge query={{
after: moment.tz(startDate, timezone).startOf(timeBlock).format("YYYY-MM-DD"),
before: moment.tz(startDate, timezone).endOf(timeBlock).add(1, 'd').format("YYYY-MM-DD"),
limit: 100
}}>
<Typography variant="headline" className={classes.timeBlockTitle}>
{['yearly', 'monthly'].includes(timeframe) && <div>
{getTitle(startDate, timeframe, null)}
</div>}
{['weekly', 'daily'].includes(timeframe) && <div>
<div className={classes.smallScreenTitle}>
{getTitle(startDate, timeframe, 'xsDown')}
</div>
<div className={classes.largeScreenTitle}>
{getTitle(startDate, timeframe, 'smUp')}
</div>
</div>}
</Typography>
</QueryLink>
<div className={classes.dayContent}>
{ noPosts && <div className={classes.noPosts}>
No posts for {
timeframe === 'daily' ?
startDate.format('MMMM Do YYYY') :
// Should be pretty rare. Basically people running off the end of
// the Forum history on yearly
`this ${timeBlock}`
}
</div> }
{postGroups.map(({name, posts, label}) => {
if (posts?.length > 0) return <div key={name}>
<div
className={name === 'frontpage' ? classes.frontpageSubtitle : classes.otherSubtitle}
>
<ContentType type={name} label={label} />
</div>
<div className={classes.posts}>
{posts.map((post, i) =>
<PostsItem2 key={post._id} post={post} index={i} dense showBottomBorder={i < posts!.length -1}/>
)}
</div>
</div>
})}
{(posts && posts.length < totalCount!) && <div className={classes.loadMore}>
<LoadMore
{...loadMoreProps}
/>
</div>}
{displayShortform && <ShortformTimeBlock
reportEmpty={reportEmptyShortform}
terms={{
view: "topShortform",
// NB: The comments before differs from posts in that before is not
// inclusive
before: moment.tz(startDate, timezone).endOf(timeBlock).toString(),
after: moment.tz(startDate, timezone).startOf(timeBlock).toString()
}}
/>}
{timeframe==="daily" && includeTags && <TagEditsTimeBlock
before={moment.tz(startDate, timezone).endOf(timeBlock).toString()}
after={moment.tz(startDate, timezone).startOf(timeBlock).toString()}
reportEmpty={reportEmptyTags}
/>}
</div>
{!loading && <div className={classes.divider}>
<Divider wings={false} />
</div>}
</div>
);
}
return render();
};
const PostsTimeBlockComponent = registerComponent('PostsTimeBlock', PostsTimeBlock, {
styles,
});
declare global {
interface ComponentTypes {
PostsTimeBlock: typeof PostsTimeBlockComponent
}
}
| {
"content_hash": "ae96a344e92e42dc08cc602b58300f7c",
"timestamp": "",
"source": "github",
"line_count": 216,
"max_line_length": 143,
"avg_line_length": 33.041666666666664,
"alnum_prop": 0.597590023819532,
"repo_name": "Discordius/Lesswrong2",
"id": "236c26221fb3f21bd28d73285e80e091f6da367d",
"size": "7137",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "packages/lesswrong/components/posts/PostsTimeBlock.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "284055"
},
{
"name": "HTML",
"bytes": "11699"
},
{
"name": "JavaScript",
"bytes": "1598090"
},
{
"name": "Python",
"bytes": "1774"
},
{
"name": "Shell",
"bytes": "3910"
}
],
"symlink_target": ""
} |
<?php
require_once('config.php');
require_once('connect.php');
require_once($lang);
if(isset($_POST['submit'])){
$query="UPDATE eventcalender
SET year=%s, month=%s, day=%s, starttime='%s', stoptime='%s', title='%s', description='%s', url='%s'
WHERE id=$_GET[id]";
$filter = array("'", '"');
$order = array("\r\n", "\n", "\r", "<br>");
$year = $_POST['inputYear'];
$month = $_POST['inputMonth'];
$day = $_POST['inputDay'];
$starttime = htmlentities($_POST['inputStartTime']);
$stoptime = htmlentities($_POST['inputStopTime']);
$title = str_replace($order, "<br>", str_replace($filter, "\'", $_POST['inputTitle']));
$description = str_replace($order, "<br>", str_replace($filter, "\'", $_POST['inputDescription']));
$url = htmlentities($_POST['inputLink']);
if($starttime == $stoptime){
$stoptime = "";
}
$query = sprintf($query, $year, $month, $day, $starttime, $stoptime, $title, $description, $url);
if ($result = mysqli_query($con, $query)) {
#Add later some fancy msg
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<title>Edit Event</title>
<link rel="stylesheet" href="css/bootstrap.min.css" >
<style>
body {
padding-top: 50px;
}
.starter-template {
padding: 40px 15px;
text-align: center;
}
</style>
</head>
<body onLoad="editEvent(<?=$_GET['id']?>)">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php"><?=$lg['EVENT_CALENDER']?></a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1><?=$lg['EDIT_EVENT']?></h1>
<p id="someInfo"></p>
<form class="form-horizontal" action="edit_event.php?id=<?=$_GET['id']?>" method="post">
<div class="form-group">
<label for="inputDay" class="col-sm-2 control-label">Day</label>
<div class="col-sm-2">
<input type="number" min="1" max="31" class="form-control" id="inputDay" name="inputDay" value="<?=date('d')?>">
</div>
<label for="inputMonth" class="col-sm-2 control-label">Month</label>
<div class="col-sm-2">
<input type="number" min="1" max="12" class="form-control" id="inputMonth" name="inputMonth" value="<?=date('n')?>">
</div>
<label for="inputYear" class="col-sm-2 control-label" >Year</label>
<div class="col-sm-2">
<input type="number" length="4" class="form-control" id="inputYear" name="inputYear" value="<?=date('Y')?>" required>
</div>
</div>
<div class="form-group">
<label for="inputStartTime" class="col-sm-2 control-label" >Start Time</label>
<div class="col-sm-4">
<input type="text" length="5" class="form-control" id="inputStartTime" name="inputStartTime" value="<?=date('H:m')?>">
</div>
<label for="inputStopTime" class="col-sm-2 control-label" >Stop Time</label>
<div class="col-sm-4">
<input type="text" length="5" class="form-control" id="inputStopTime" name="inputStopTime" value="<?=date('H:m')?>">
</div>
</div>
<div class="form-group">
<label for="inputTitle" class="col-sm-2 control-label" >Event title</label>
<div class="col-sm-10">
<input type="text" length="255" class="form-control" id="inputTitle" name="inputTitle" placeholder="Event title" required>
</div>
</div>
<div class="form-group">
<label for="inputLink" class="col-sm-2 control-label" >Link to more info</label>
<div class="col-sm-10">
<input type="url" length="255" class="form-control" id="inputLink" name="inputLink" placeholder="https://">
</div>
</div>
<div class="form-group">
<label for="inputDescription" class="col-sm-2 control-label" >Event description</label>
<div class="col-sm-10">
<textarea type="text" class="form-control" id="inputDescription" name="inputDescription" placeholder="Event description"></textarea>
</div>
</div>
<div class="form-group">
<input type="hidden" id="eventId">
<div class="col-sm-offset-2 col-sm-10" style="text-align:right;">
<button type="submit" class="btn btn-success" name="submit">Save</button>
</div>
</div>
</form>
</div>
</div><!-- /.container -->
<script type="text/javascript" src="js/calender.js"></script>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</body>
</html>
| {
"content_hash": "a47bdc2d863f722bc6516ad3452fe407",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 203,
"avg_line_length": 42.06666666666667,
"alnum_prop": 0.561014263074485,
"repo_name": "jask0/event-kalender",
"id": "c1aa4283abf647d801b07de9e104f93e91139810",
"size": "6310",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "calender/edit_event.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5662"
},
{
"name": "PHP",
"bytes": "30031"
}
],
"symlink_target": ""
} |
import PropTypes from 'prop-types'
import React, { Component } from 'react'
export default class TagEditor extends Component {
render () {
const { entity } = this.props
return (
<div className='custom-editor'>
<div>
<h1><i className='fa fa-folder' /> {entity.name}</h1>
</div>
</div>
)
}
}
TagEditor.propTypes = {
entity: PropTypes.object.isRequired
}
| {
"content_hash": "9ab50798c74d78f1aa3f146a0b39d447",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 63,
"avg_line_length": 20.55,
"alnum_prop": 0.6034063260340633,
"repo_name": "jsreport/jsreport-studio",
"id": "8d272f71e6d3d8e713444192f0c63f1a558765c6",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/Editor/FolderEditor.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24441"
},
{
"name": "HTML",
"bytes": "5860"
},
{
"name": "JavaScript",
"bytes": "390102"
}
],
"symlink_target": ""
} |
package com.intellij.execution.runners;
import com.intellij.execution.*;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessNotCreatedException;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.LayeredIcon;
import com.intellij.ui.content.Content;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.awt.geom.Ellipse2D;
public class ExecutionUtil {
private static final Logger LOG = Logger.getInstance("com.intellij.execution.runners.ExecutionUtil");
private static final NotificationGroup ourNotificationGroup = NotificationGroup.logOnlyGroup("Execution");
private ExecutionUtil() {
}
public static void handleExecutionError(@NotNull Project project,
@NotNull String toolWindowId,
@NotNull RunProfile runProfile,
@NotNull ExecutionException e) {
handleExecutionError(project, toolWindowId, runProfile.getName(), e);
}
public static void handleExecutionError(@NotNull ExecutionEnvironment environment, @NotNull ExecutionException e) {
handleExecutionError(environment.getProject(),
ExecutionManager.getInstance(environment.getProject()).getContentManager().getToolWindowIdByEnvironment(environment),
environment.getRunProfile().getName(), e);
}
public static void handleExecutionError(@NotNull final Project project,
@NotNull final String toolWindowId,
@NotNull String taskName,
@NotNull ExecutionException e) {
if (e instanceof RunCanceledByUserException) {
return;
}
LOG.debug(e);
String description = e.getMessage();
if (StringUtil.isEmptyOrSpaces(description)) {
LOG.warn("Execution error without description", e);
description = "Unknown error";
}
HyperlinkListener listener = null;
if ((description.contains("87") || description.contains("111") || description.contains("206")) &&
e instanceof ProcessNotCreatedException &&
!PropertiesComponent.getInstance(project).isTrueValue("dynamic.classpath")) {
final String commandLineString = ((ProcessNotCreatedException)e).getCommandLine().getCommandLineString();
if (commandLineString.length() > 1024 * 32) {
description = "Command line is too long. In order to reduce its length classpath file can be used.<br>" +
"Would you like to enable classpath file mode for all run configurations of your project?<br>" +
"<a href=\"\">Enable</a>";
listener = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent event) {
PropertiesComponent.getInstance(project).setValue("dynamic.classpath", "true");
}
};
}
}
final String title = ExecutionBundle.message("error.running.configuration.message", taskName);
final String fullMessage = title + ":<br>" + description;
if (ApplicationManager.getApplication().isUnitTestMode()) {
LOG.error(fullMessage, e);
}
if (listener == null) {
listener = ExceptionUtil.findCause(e, HyperlinkListener.class);
}
final HyperlinkListener finalListener = listener;
final String finalDescription = description;
UIUtil.invokeLaterIfNeeded(() -> {
if (project.isDisposed()) {
return;
}
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
if (toolWindowManager.canShowNotification(toolWindowId)) {
//noinspection SSBasedInspection
toolWindowManager.notifyByBalloon(toolWindowId, MessageType.ERROR, fullMessage, null, finalListener);
}
else {
Messages.showErrorDialog(project, UIUtil.toHtml(fullMessage), "");
}
NotificationListener notificationListener = finalListener == null ? null : (notification, event) -> {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
finalListener.hyperlinkUpdate(event);
}
};
ourNotificationGroup.createNotification(title, finalDescription, NotificationType.ERROR, notificationListener).notify(project);
});
}
public static void restartIfActive(@NotNull RunContentDescriptor descriptor) {
ProcessHandler processHandler = descriptor.getProcessHandler();
if (processHandler != null
&& processHandler.isStartNotified()
&& !processHandler.isProcessTerminating()
&& !processHandler.isProcessTerminated()) {
restart(descriptor);
}
}
public static void restart(@NotNull RunContentDescriptor descriptor) {
restart(descriptor.getComponent());
}
public static void restart(@NotNull Content content) {
restart(content.getComponent());
}
private static void restart(@Nullable JComponent component) {
if (component != null) {
ExecutionEnvironment environment = LangDataKeys.EXECUTION_ENVIRONMENT.getData(DataManager.getInstance().getDataContext(component));
if (environment != null) {
restart(environment);
}
}
}
public static void restart(@NotNull ExecutionEnvironment environment) {
if (!ExecutorRegistry.getInstance().isStarting(environment)) {
ExecutionManager.getInstance(environment.getProject()).restartRunProfile(environment);
}
}
public static void runConfiguration(@NotNull RunnerAndConfigurationSettings configuration, @NotNull Executor executor) {
ExecutionEnvironmentBuilder builder = createEnvironment(executor, configuration);
if (builder != null) {
ExecutionManager.getInstance(configuration.getConfiguration().getProject()).restartRunProfile(builder
.activeTarget()
.build());
}
}
@Nullable
public static ExecutionEnvironmentBuilder createEnvironment(@NotNull Executor executor, @NotNull RunnerAndConfigurationSettings settings) {
try {
return ExecutionEnvironmentBuilder.create(executor, settings);
}
catch (ExecutionException e) {
Project project = settings.getConfiguration().getProject();
RunContentManager manager = ExecutionManager.getInstance(project).getContentManager();
String toolWindowId = manager.getContentDescriptorToolWindowId(settings);
if (toolWindowId == null) {
toolWindowId = executor.getToolWindowId();
}
handleExecutionError(project, toolWindowId, settings.getConfiguration().getName(), e);
return null;
}
}
public static Icon getLiveIndicator(@Nullable final Icon base) {
return new LayeredIcon(base, new Icon() {
@SuppressWarnings("UseJBColor")
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
int iSize = JBUI.scale(4);
Graphics2D g2d = (Graphics2D)g.create();
try {
GraphicsUtil.setupAAPainting(g2d);
g2d.setColor(Color.GREEN);
Ellipse2D.Double shape =
new Ellipse2D.Double(x + getIconWidth() - iSize, y + getIconHeight() - iSize, iSize, iSize);
g2d.fill(shape);
g2d.setColor(ColorUtil.withAlpha(Color.BLACK, .40));
g2d.draw(shape);
}
finally {
g2d.dispose();
}
}
@Override
public int getIconWidth() {
return base != null ? base.getIconWidth() : 13;
}
@Override
public int getIconHeight() {
return base != null ? base.getIconHeight() : 13;
}
});
}
}
| {
"content_hash": "7fd2f62e1dbcb09df097b5be9c47e4ec",
"timestamp": "",
"source": "github",
"line_count": 221,
"max_line_length": 142,
"avg_line_length": 40.321266968325794,
"alnum_prop": 0.6817416676018404,
"repo_name": "youdonghai/intellij-community",
"id": "6be040d8b74fbc69c54943fd7e32411b60905068",
"size": "9511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/lang-api/src/com/intellij/execution/runners/ExecutionUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "60477"
},
{
"name": "C",
"bytes": "195270"
},
{
"name": "C#",
"bytes": "1264"
},
{
"name": "C++",
"bytes": "197804"
},
{
"name": "CMake",
"bytes": "1195"
},
{
"name": "CSS",
"bytes": "201445"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Cucumber",
"bytes": "14382"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groff",
"bytes": "35232"
},
{
"name": "Groovy",
"bytes": "3078038"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1837329"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "160121025"
},
{
"name": "JavaScript",
"bytes": "570364"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "2803472"
},
{
"name": "Lex",
"bytes": "183993"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "49795"
},
{
"name": "Objective-C",
"bytes": "28750"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6639"
},
{
"name": "Python",
"bytes": "24055272"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "63389"
},
{
"name": "Smalltalk",
"bytes": "338"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
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.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_accelerated="false" android:color="@color/background_material_light" />
<item android:color="@android:color/transparent" />
</selector>
<!-- From: file:/C:/Users/Jacques/AndroidStudioProjects/TP%20Formation%20Android/5%20-%20Service%20tiers/5%20-%20TP%20Localisation/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/color/abc_background_cache_hint_selector_material_light.xml --> | {
"content_hash": "95d18aa6fb7bfe00172c893b02f315eb",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 275,
"avg_line_length": 56.19047619047619,
"alnum_prop": 0.7423728813559322,
"repo_name": "jacquesgiraudel/TP-Formation-Android",
"id": "4d2576e0ca9d98919bd4967fbfca7f5ad5754634",
"size": "1180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "5 - Service tiers/5 - TP Localisation/app/build/intermediates/res/debug/color/abc_background_cache_hint_selector_material_light.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1142"
},
{
"name": "HTML",
"bytes": "6856"
},
{
"name": "Java",
"bytes": "6493986"
},
{
"name": "Makefile",
"bytes": "1349"
}
],
"symlink_target": ""
} |
use super::utils::make_iterator_snippet;
use super::NEVER_LOOP;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::higher::ForLoop;
use clippy_utils::source::snippet;
use rustc_errors::Applicability;
use rustc_hir::{Block, Expr, ExprKind, HirId, InlineAsmOperand, Pat, Stmt, StmtKind};
use rustc_lint::LateContext;
use rustc_span::Span;
use std::iter::{once, Iterator};
pub(super) fn check(
cx: &LateContext<'tcx>,
block: &'tcx Block<'_>,
loop_id: HirId,
span: Span,
for_loop: Option<&ForLoop<'_>>,
) {
match never_loop_block(block, loop_id) {
NeverLoopResult::AlwaysBreak => {
span_lint_and_then(cx, NEVER_LOOP, span, "this loop never actually loops", |diag| {
if let Some(ForLoop {
arg: iterator,
pat,
span: for_span,
..
}) = for_loop
{
// Suggests using an `if let` instead. This is `Unspecified` because the
// loop may (probably) contain `break` statements which would be invalid
// in an `if let`.
diag.span_suggestion_verbose(
for_span.with_hi(iterator.span.hi()),
"if you need the first element of the iterator, try writing",
for_to_if_let_sugg(cx, iterator, pat),
Applicability::Unspecified,
);
}
});
},
NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
}
}
enum NeverLoopResult {
// A break/return always get triggered but not necessarily for the main loop.
AlwaysBreak,
// A continue may occur for the main loop.
MayContinueMainLoop,
Otherwise,
}
#[must_use]
fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
match *arg {
NeverLoopResult::AlwaysBreak | NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
}
}
// Combine two results for parts that are called in order.
#[must_use]
fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
match first {
NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
NeverLoopResult::Otherwise => second,
}
}
// Combine two results where both parts are called but not necessarily in order.
#[must_use]
fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
match (left, right) {
(NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
NeverLoopResult::MayContinueMainLoop
},
(NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
(NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
}
}
// Combine two results where only one of the part may have been executed.
#[must_use]
fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
match (b1, b2) {
(NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
(NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
NeverLoopResult::MayContinueMainLoop
},
(NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
}
}
fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult {
let stmts = block.stmts.iter().map(stmt_to_expr);
let expr = once(block.expr);
let mut iter = stmts.chain(expr).flatten();
never_loop_expr_seq(&mut iter, main_loop_id)
}
fn never_loop_expr_seq<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
es.map(|e| never_loop_expr(e, main_loop_id))
.fold(NeverLoopResult::Otherwise, combine_seq)
}
fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> {
match stmt.kind {
StmtKind::Semi(e, ..) | StmtKind::Expr(e, ..) => Some(e),
StmtKind::Local(local) => local.init,
StmtKind::Item(..) => None,
}
}
fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
match expr.kind {
ExprKind::Box(e)
| ExprKind::Unary(_, e)
| ExprKind::Cast(e, _)
| ExprKind::Type(e, _)
| ExprKind::Let(_, e, _)
| ExprKind::Field(e, _)
| ExprKind::AddrOf(_, _, e)
| ExprKind::Struct(_, _, Some(e))
| ExprKind::Repeat(e, _)
| ExprKind::DropTemps(e) => never_loop_expr(e, main_loop_id),
ExprKind::Array(es) | ExprKind::MethodCall(_, _, es, _) | ExprKind::Tup(es) => {
never_loop_expr_all(&mut es.iter(), main_loop_id)
},
ExprKind::Call(e, es) => never_loop_expr_all(&mut once(e).chain(es.iter()), main_loop_id),
ExprKind::Binary(_, e1, e2)
| ExprKind::Assign(e1, e2, _)
| ExprKind::AssignOp(_, e1, e2)
| ExprKind::Index(e1, e2) => never_loop_expr_all(&mut [e1, e2].iter().copied(), main_loop_id),
ExprKind::Loop(b, _, _, _) => {
// Break can come from the inner loop so remove them.
absorb_break(&never_loop_block(b, main_loop_id))
},
ExprKind::If(e, e2, e3) => {
let e1 = never_loop_expr(e, main_loop_id);
let e2 = never_loop_expr(e2, main_loop_id);
let e3 = e3
.as_ref()
.map_or(NeverLoopResult::Otherwise, |e| never_loop_expr(e, main_loop_id));
combine_seq(e1, combine_branches(e2, e3))
},
ExprKind::Match(e, arms, _) => {
let e = never_loop_expr(e, main_loop_id);
if arms.is_empty() {
e
} else {
let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
combine_seq(e, arms)
}
},
ExprKind::Block(b, _) => never_loop_block(b, main_loop_id),
ExprKind::Continue(d) => {
let id = d
.target_id
.expect("target ID can only be missing in the presence of compilation errors");
if id == main_loop_id {
NeverLoopResult::MayContinueMainLoop
} else {
NeverLoopResult::AlwaysBreak
}
},
ExprKind::Break(_, e) | ExprKind::Ret(e) => e.as_ref().map_or(NeverLoopResult::AlwaysBreak, |e| {
combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
}),
ExprKind::InlineAsm(asm) => asm
.operands
.iter()
.map(|(o, _)| match o {
InlineAsmOperand::In { expr, .. }
| InlineAsmOperand::InOut { expr, .. }
| InlineAsmOperand::Sym { expr } => never_loop_expr(expr, main_loop_id),
InlineAsmOperand::Out { expr, .. } => never_loop_expr_all(&mut expr.iter(), main_loop_id),
InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
never_loop_expr_all(&mut once(in_expr).chain(out_expr.iter()), main_loop_id)
},
InlineAsmOperand::Const { .. } => NeverLoopResult::Otherwise,
})
.fold(NeverLoopResult::Otherwise, combine_both),
ExprKind::Struct(_, _, None)
| ExprKind::Yield(_, _)
| ExprKind::Closure(_, _, _, _, _)
| ExprKind::LlvmInlineAsm(_)
| ExprKind::Path(_)
| ExprKind::ConstBlock(_)
| ExprKind::Lit(_)
| ExprKind::Err => NeverLoopResult::Otherwise,
}
}
fn never_loop_expr_all<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
es.map(|e| never_loop_expr(e, main_loop_id))
.fold(NeverLoopResult::Otherwise, combine_both)
}
fn never_loop_expr_branch<'a, T: Iterator<Item = &'a Expr<'a>>>(e: &mut T, main_loop_id: HirId) -> NeverLoopResult {
e.map(|e| never_loop_expr(e, main_loop_id))
.fold(NeverLoopResult::AlwaysBreak, combine_branches)
}
fn for_to_if_let_sugg(cx: &LateContext<'_>, iterator: &Expr<'_>, pat: &Pat<'_>) -> String {
let pat_snippet = snippet(cx, pat.span, "_");
let iter_snippet = make_iterator_snippet(cx, iterator, &mut Applicability::Unspecified);
format!(
"if let Some({pat}) = {iter}.next()",
pat = pat_snippet,
iter = iter_snippet
)
}
| {
"content_hash": "0331116cfddfa346a99640a85bdc0534",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 116,
"avg_line_length": 40.539906103286384,
"alnum_prop": 0.5712796757382744,
"repo_name": "graydon/rust",
"id": "86b7d6d989acc75fd6fc3dde238947886588aa51",
"size": "8635",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/tools/clippy/clippy_lints/src/loops/never_loop.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4990"
},
{
"name": "Assembly",
"bytes": "20064"
},
{
"name": "Awk",
"bytes": "159"
},
{
"name": "Bison",
"bytes": "78848"
},
{
"name": "C",
"bytes": "725899"
},
{
"name": "C++",
"bytes": "55803"
},
{
"name": "CSS",
"bytes": "22181"
},
{
"name": "JavaScript",
"bytes": "36295"
},
{
"name": "LLVM",
"bytes": "1587"
},
{
"name": "Makefile",
"bytes": "227056"
},
{
"name": "Puppet",
"bytes": "16300"
},
{
"name": "Python",
"bytes": "142548"
},
{
"name": "RenderScript",
"bytes": "99815"
},
{
"name": "Rust",
"bytes": "18342682"
},
{
"name": "Shell",
"bytes": "269546"
},
{
"name": "TeX",
"bytes": "57"
}
],
"symlink_target": ""
} |
package module4;
import java.util.ArrayList;
import java.util.List;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.data.Feature;
import de.fhpotsdam.unfolding.data.GeoJSONReader;
import de.fhpotsdam.unfolding.data.PointFeature;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.AbstractShapeMarker;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.MultiMarker;
import de.fhpotsdam.unfolding.providers.Google;
import de.fhpotsdam.unfolding.providers.MBTilesMapProvider;
import de.fhpotsdam.unfolding.utils.MapUtils;
import parsing.ParseFeed;
import processing.core.PApplet;
/** EarthquakeCityMap
* An application with an interactive map displaying earthquake data.
* Author: UC San Diego Intermediate Software Development MOOC team
* @author Your name here
* Date: July 17, 2015
* */
public class EarthquakeCityMap extends PApplet {
// We will use member variables, instead of local variables, to store the data
// that the setUp and draw methods will need to access (as well as other methods)
// You will use many of these variables, but the only one you should need to add
// code to modify is countryQuakes, where you will store the number of earthquakes
// per country.
// You can ignore this. It's to get rid of eclipse warnings
private static final long serialVersionUID = 1L;
// IF YOU ARE WORKING OFFILINE, change the value of this variable to true
private static final boolean offline = false;
/** This is where to find the local tiles, for working without an Internet connection */
public static String mbTilesString = "blankLight-1-3.mbtiles";
//feed with magnitude 2.5+ Earthquakes
private String earthquakesURL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom";
// The files containing city names and info and country names and info
private String cityFile = "city-data.json";
private String countryFile = "countries.geo.json";
// The map
private UnfoldingMap map;
// Markers for each city
private List<Marker> cityMarkers;
// Markers for each earthquake
private List<Marker> quakeMarkers;
// A List of country markers
private List<Marker> countryMarkers;
public void setup() {
// (1) Initializing canvas and map tiles
size(900, 700, OPENGL);
if (offline) {
map = new UnfoldingMap(this, 200, 50, 650, 600, new MBTilesMapProvider(mbTilesString));
earthquakesURL = "2.5_week.atom"; // The same feed, but saved August 7, 2015
}
else {
map = new UnfoldingMap(this, 200, 50, 650, 600, new Google.GoogleMapProvider());
// IF YOU WANT TO TEST WITH A LOCAL FILE, uncomment the next line
//earthquakesURL = "2.5_week.atom";
}
MapUtils.createDefaultEventDispatcher(this, map);
// FOR TESTING: Set earthquakesURL to be one of the testing files by uncommenting
// one of the lines below. This will work whether you are online or offline
//earthquakesURL = "test1.atom";
//earthquakesURL = "test2.atom";
// WHEN TAKING THIS QUIZ: Uncomment the next line
//earthquakesURL = "quiz1.atom";
// (2) Reading in earthquake data and geometric properties
// STEP 1: load country features and markers
List<Feature> countries = GeoJSONReader.loadData(this, countryFile);
countryMarkers = MapUtils.createSimpleMarkers(countries);
// STEP 2: read in city data
List<Feature> cities = GeoJSONReader.loadData(this, cityFile);
cityMarkers = new ArrayList<Marker>();
for(Feature city : cities) {
cityMarkers.add(new CityMarker(city));
}
// STEP 3: read in earthquake RSS feed
List<PointFeature> earthquakes = ParseFeed.parseEarthquake(this, earthquakesURL);
quakeMarkers = new ArrayList<Marker>();
for(PointFeature feature : earthquakes) {
//check if LandQuake
if(isLand(feature)) {
quakeMarkers.add(new LandQuakeMarker(feature));
}
// OceanQuakes
else {
quakeMarkers.add(new OceanQuakeMarker(feature));
}
}
// could be used for debugging
printQuakes();
// (3) Add markers to map
// NOTE: Country markers are not added to the map. They are used
// for their geometric properties
map.addMarkers(quakeMarkers);
map.addMarkers(cityMarkers);
} // End setup
public void draw() {
background(0);
map.draw();
addKey();
}
// helper method to draw key in GUI
// TODO: Update this method as appropriate
private void addKey() {
// Remember you can use Processing's graphics methods here
fill(255, 250, 240);
rect(25, 50, 150, 250);
fill(0);
textAlign(LEFT, CENTER);
textSize(12);
text("Earthquake Key", 50, 75);
fill(color(128, 0, 0));
triangle(50, 105, 55, 95, 60, 105);
fill(color(255, 255, 255));
ellipse(55, 125, 15, 15);
fill(color(255, 255, 255));
rect(50, 144, 12, 12);
fill(color(255, 225, 0));
ellipse(55, 200, 15, 15);
fill(color(0, 0, 255));
ellipse(55, 225, 15, 15);
fill(color(255, 0, 0));
ellipse(55, 250, 15, 15);
fill(color(255, 255, 255));
ellipse(55, 275, 15, 15);
fill(0, 0, 0);
line(50,270,60,280);
line(50,280,60,270);
text("City Marker", 75, 100);
text("Land Quake", 75, 125);
text("Ocean Quake", 75, 150);
text("Size ~ Magnitude", 50, 175);
text("Shallow", 75, 200);
text("Intermediate", 75, 225);
text("Deep", 75, 250);
text("Past Day", 75, 275);
}
// Checks whether this quake occurred on land. If it did, it sets the
// "country" property of its PointFeature to the country where it occurred
// and returns true. Notice that the helper method isInCountry will
// set this "country" property already. Otherwise it returns false.
private boolean isLand(PointFeature earthquake) {
// IMPLEMENT THIS: loop over all countries to check if location is in any of them
// TODO: Implement this method using the helper method isInCountry
for(Marker country : countryMarkers){
if (isInCountry(earthquake,country)){
return true;
}
}
// not inside any country
return false;
}
// prints countries with number of earthquakes
// You will want to loop through the country markers or country features
// (either will work) and then for each country, loop through
// the quakes to count how many occurred in that country.
// Recall that the country markers have a "name" property,
// And LandQuakeMarkers have a "country" property set.
private void printQuakes()
{
// TODO: Implement this method
int num_landquakes=0;
int num_oceanquakes = quakeMarkers.size();
for(Marker country : countryMarkers){
for(Marker quake : quakeMarkers) {
if (quake.getProperty("country")!=null) {
if (quake.getProperty("country")==country.getProperty("name")){
num_landquakes++;
}
}
}
if (num_landquakes!=0) {
System.out.println(((String) country.getProperty("name")) + ":" + num_landquakes);
num_oceanquakes = num_oceanquakes-num_landquakes;
}
num_landquakes=0;
}
System.out.println("OCEAN QUAKES:"+num_oceanquakes);
}
// helper method to test whether a given earthquake is in a given country
// This will also add the country property to the properties of the earthquake
// feature if it's in one of the countries.
// You should not have to modify this code
private boolean isInCountry(PointFeature earthquake, Marker country) {
// getting location of feature
Location checkLoc = earthquake.getLocation();
// some countries represented it as MultiMarker
// looping over SimplePolygonMarkers which make them up to use isInsideByLoc
if(country.getClass() == MultiMarker.class) {
// looping over markers making up MultiMarker
for(Marker marker : ((MultiMarker)country).getMarkers()) {
// checking if inside
if(((AbstractShapeMarker)marker).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
// return if is inside one
return true;
}
}
}
// check if inside country represented by SimplePolygonMarker
else if(((AbstractShapeMarker)country).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
return true;
}
return false;
}
}
| {
"content_hash": "57fac0035662a1aaa127b18b98b4fb66",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 106,
"avg_line_length": 31.896153846153847,
"alnum_prop": 0.6999879416375256,
"repo_name": "devchandan/UCSDUnfoldingMaps",
"id": "ca9e272790373afdd66142195c928bcb2459dcfe",
"size": "8293",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/module4/EarthquakeCityMap.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "101056"
}
],
"symlink_target": ""
} |
namespace Orvado.IdleShutdown
{
partial class IdleService
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
| {
"content_hash": "abfc37f3a7fc3ae1d9f9542d8a4de5ca",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 101,
"avg_line_length": 23.864864864864863,
"alnum_prop": 0.6749716874292185,
"repo_name": "orvado/Idle-Shutdown",
"id": "667b8a6c41be885485b6d16b617222b147f256e6",
"size": "885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IdleShutdown/IdleService.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "27423"
}
],
"symlink_target": ""
} |
import os
c = get_config()
#------------------------------------------------------------------------------
# InteractiveShellApp(Configurable) configuration
#------------------------------------------------------------------------------
## A Mixin for applications that start InteractiveShell instances.
#
# Provides configurables for loading extensions and executing files as part of
# configuring a Shell environment.
#
# The following methods should be called by the :meth:`initialize` method of the
# subclass:
#
# - :meth:`init_path`
# - :meth:`init_shell` (to be implemented by the subclass)
# - :meth:`init_gui_pylab`
# - :meth:`init_extensions`
# - :meth:`init_code`
## Execute the given command string.
#c.InteractiveShellApp.code_to_run = ''
## Run the file referenced by the PYTHONSTARTUP environment variable at IPython
# startup.
#c.InteractiveShellApp.exec_PYTHONSTARTUP = True
## List of files to run at IPython startup.
c.InteractiveShellApp.exec_files = [
]
## lines of code to run at IPython startup.
c.InteractiveShellApp.exec_lines = [
'import numpy as np',
# enable autoreload
'%autoreload 2',
]
## A list of dotted module names of IPython extensions to load.
c.InteractiveShellApp.extensions = ['autoreload']
## dotted module name of an IPython extension to load.
#c.InteractiveShellApp.extra_extension = ''
## A file to be run
#c.InteractiveShellApp.file_to_run = ''
## Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk2', 'gtk3',
# 'osx', 'pyglet', 'qt', 'qt4', 'qt5', 'tk', 'wx', 'gtk2', 'qt4').
# c.InteractiveShellApp.gui = 'qt5'
## Should variables loaded at startup (by startup files, exec_lines, etc.) be
# hidden from tools like %who?
#c.InteractiveShellApp.hide_initial_ns = True
## Configure matplotlib for interactive use with the default matplotlib backend.
#c.InteractiveShellApp.matplotlib = None
## Run the module as a script.
#c.InteractiveShellApp.module_to_run = ''
## Pre-load matplotlib and numpy for interactive use, selecting a particular
# matplotlib backend and loop integration.
#c.InteractiveShellApp.pylab = None
## If true, IPython will populate the user namespace with numpy, pylab, etc. and
# an ``import *`` is done from numpy and pylab, when using pylab mode.
#
# When False, pylab mode should not import any names into the user namespace.
#c.InteractiveShellApp.pylab_import_all = True
## Reraise exceptions encountered loading IPython extensions?
#c.InteractiveShellApp.reraise_ipython_extension_failures = False
#------------------------------------------------------------------------------
# Application(SingletonConfigurable) configuration
#------------------------------------------------------------------------------
## This is an application.
## The date format used by logging formatters for %(asctime)s
#c.Application.log_datefmt = '%Y-%m-%d %H:%M:%S'
## The Logging format template
#c.Application.log_format = '[%(name)s]%(highlevel)s %(message)s'
## Set the log level by value or name.
#c.Application.log_level = 30
#------------------------------------------------------------------------------
# BaseIPythonApplication(Application) configuration
#------------------------------------------------------------------------------
## IPython: an enhanced interactive Python shell.
## Whether to create profile dir if it doesn't exist
#c.BaseIPythonApplication.auto_create = False
## Whether to install the default config files into the profile dir. If a new
# profile is being created, and IPython contains config files for that profile,
# then they will be staged into the new directory. Otherwise, default config
# files will be automatically generated.
#c.BaseIPythonApplication.copy_config_files = False
## Path to an extra config file to load.
#
# If specified, load this config file in addition to any other IPython config.
#c.BaseIPythonApplication.extra_config_file = u''
## The name of the IPython directory. This directory is used for logging
# configuration (through profiles), history storage, etc. The default is usually
# $HOME/.ipython. This option can also be specified through the environment
# variable IPYTHONDIR.
#c.BaseIPythonApplication.ipython_dir = u''
## Whether to overwrite existing config files when copying
#c.BaseIPythonApplication.overwrite = False
## The IPython profile to use.
#c.BaseIPythonApplication.profile = u'default'
## Create a massive crash report when IPython encounters what may be an internal
# error. The default is to append a short message to the usual traceback
#c.BaseIPythonApplication.verbose_crash = False
#------------------------------------------------------------------------------
# TerminalIPythonApp(BaseIPythonApplication,InteractiveShellApp) configuration
#------------------------------------------------------------------------------
## Whether to display a banner upon starting IPython.
# c.TerminalIPythonApp.display_banner = True
## If a command or file is given via the command-line, e.g. 'ipython foo.py',
# start an interactive shell after executing the file or command.
#c.TerminalIPythonApp.force_interact = False
## Start IPython quickly by skipping the loading of config files.
#c.TerminalIPythonApp.quick = False
#------------------------------------------------------------------------------
# InteractiveShell(SingletonConfigurable) configuration
#------------------------------------------------------------------------------
## An enhanced, interactive shell for Python.
## 'all', 'last', 'last_expr' or 'none', specifying which nodes should be run
# interactively (displaying output from expressions).
#c.InteractiveShell.ast_node_interactivity = 'last_expr'
## A list of ast.NodeTransformer subclass instances, which will be applied to
# user input before code is run.
#c.InteractiveShell.ast_transformers = []
## Make IPython automatically call any callable object even if you didn't type
# explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
# The value can be '0' to disable the feature, '1' for 'smart' autocall, where
# it is not applied if there are no more arguments on the line, and '2' for
# 'full' autocall, where all callable objects are automatically called (even if
# no arguments are present).
#c.InteractiveShell.autocall = 0
## Autoindent IPython code entered interactively.
#c.InteractiveShell.autoindent = True
## Enable magic commands to be called without the leading %.
#c.InteractiveShell.automagic = True
## The part of the banner to be printed before the profile
#c.InteractiveShell.banner1 = 'Python 2.7.12 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:42:40) \nType "copyright", "credits" or "license" for more information.\n\nIPython 5.1.0 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython\'s features.\n%quickref -> Quick reference.\nhelp -> Python\'s own help system.\nobject? -> Details about \'object\', use \'object??\' for extra details.\n'
## The part of the banner to be printed after the profile
#c.InteractiveShell.banner2 = ''
## Set the size of the output cache. The default is 1000, you can change it
# permanently in your config file. Setting it to 0 completely disables the
# caching system, and the minimum value accepted is 20 (if you provide a value
# less than 20, it is reset to 0 and a warning is issued). This limit is
# defined because otherwise you'll spend more time re-flushing a too small cache
# than working
#c.InteractiveShell.cache_size = 1000
## Use colors for displaying information about objects. Because this information
# is passed through a pager (like 'less'), and some pagers get confused with
# color codes, this capability can be turned off.
#c.InteractiveShell.color_info = True
## Set the color scheme (NoColor, Neutral, Linux, or LightBG).
c.InteractiveShell.colors = 'Linux'
##
#c.InteractiveShell.debug = False
## **Deprecated**
#
# Will be removed in IPython 6.0
#
# Enable deep (recursive) reloading by default. IPython can use the deep_reload
# module which reloads changes in modules recursively (it replaces the reload()
# function, so you don't need to change anything to use it). `deep_reload`
# forces a full reload of modules whose code may have changed, which the default
# reload() function does not. When deep_reload is off, IPython will use the
# normal reload(), but deep_reload will still be available as dreload().
#c.InteractiveShell.deep_reload = False
## Don't call post-execute functions that have failed in the past.
#c.InteractiveShell.disable_failing_post_execute = False
## If True, anything that would be passed to the pager will be displayed as
# regular output instead.
#c.InteractiveShell.display_page = False
## (Provisional API) enables html representation in mime bundles sent to pagers.
#c.InteractiveShell.enable_html_pager = False
## Total length of command history
#c.InteractiveShell.history_length = 10000
## The number of saved history entries to be loaded into the history buffer at
# startup.
#c.InteractiveShell.history_load_length = 1000
##
#c.InteractiveShell.ipython_dir = ''
## Start logging to the given file in append mode. Use `logfile` to specify a log
# file to **overwrite** logs to.
#c.InteractiveShell.logappend = ''
## The name of the logfile to use.
#c.InteractiveShell.logfile = ''
## Start logging to the default log file in overwrite mode. Use `logappend` to
# specify a log file to **append** logs to.
#c.InteractiveShell.logstart = False
##
#c.InteractiveShell.object_info_string_level = 0
## Automatically call the pdb debugger after every exception.
#c.InteractiveShell.pdb = False
## Deprecated since IPython 4.0 and ignored since 5.0, set
# TerminalInteractiveShell.prompts object directly.
#c.InteractiveShell.prompt_in1 = 'In [\\#]: '
## Deprecated since IPython 4.0 and ignored since 5.0, set
# TerminalInteractiveShell.prompts object directly.
#c.InteractiveShell.prompt_in2 = ' .\\D.: '
## Deprecated since IPython 4.0 and ignored since 5.0, set
# TerminalInteractiveShell.prompts object directly.
#c.InteractiveShell.prompt_out = 'Out[\\#]: '
## Deprecated since IPython 4.0 and ignored since 5.0, set
# TerminalInteractiveShell.prompts object directly.
#c.InteractiveShell.prompts_pad_left = True
##
#c.InteractiveShell.quiet = False
##
#c.InteractiveShell.separate_in = '\n'
##
#c.InteractiveShell.separate_out = ''
##
#c.InteractiveShell.separate_out2 = ''
## Show rewritten input, e.g. for autocall.
#c.InteractiveShell.show_rewritten_input = True
## Enables rich html representation of docstrings. (This requires the docrepr
# module).
#c.InteractiveShell.sphinxify_docstring = False
##
#c.InteractiveShell.wildcards_case_sensitive = True
##
#c.InteractiveShell.xmode = 'Context'
#------------------------------------------------------------------------------
# TerminalInteractiveShell(InteractiveShell) configuration
#------------------------------------------------------------------------------
## Set to confirm when you try to exit IPython with an EOF (Control-D in Unix,
# Control-Z/Enter in Windows). By typing 'exit' or 'quit', you can force a
# direct exit without any confirmation.
#c.TerminalInteractiveShell.confirm_exit = True
## Options for displaying tab completions, 'column', 'multicolumn', and
# 'readlinelike'. These options are for `prompt_toolkit`, see `prompt_toolkit`
# documentation for more information.
#c.TerminalInteractiveShell.display_completions = 'multicolumn'
## Shortcut style to use at the prompt. 'vi' or 'emacs'.
#c.TerminalInteractiveShell.editing_mode = 'emacs'
## Set the editor used by IPython (default to $EDITOR/vi/notepad).
c.TerminalInteractiveShell.editor = 'gvim'
## Highlight matching brackets .
#c.TerminalInteractiveShell.highlight_matching_brackets = True
## The name of a Pygments style to use for syntax highlighting: manni, igor,
# lovelace, xcode, vim, autumn, vs, rrt, native, perldoc, borland, tango, emacs,
# friendly, monokai, paraiso-dark, colorful, murphy, bw, pastie, algol_nu,
# paraiso-light, trac, default, algol, fruity
c.TerminalInteractiveShell.highlighting_style = 'paraiso-dark'
## Override highlighting format for specific tokens
#c.TerminalInteractiveShell.highlighting_style_overrides = {}
## Enable mouse support in the prompt
#c.TerminalInteractiveShell.mouse_support = False
## Class used to generate Prompt token for prompt_toolkit
#c.TerminalInteractiveShell.prompts_class = 'IPython.terminal.prompts.Prompts'
## Use `raw_input` for the REPL, without completion, multiline input, and prompt
# colors.
#
# Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR.
# Known usage are: IPython own testing machinery, and emacs inferior-shell
# integration through elpy.
#
# This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT` environment
# variable is set, or the current terminal is not a tty.
#c.TerminalInteractiveShell.simple_prompt = False
## Number of line at the bottom of the screen to reserve for the completion menu
#c.TerminalInteractiveShell.space_for_menu = 6
## Automatically set the terminal title
c.TerminalInteractiveShell.term_title = False
## Use 24bit colors instead of 256 colors in prompt highlighting. If your
# terminal supports true color, the following command should print 'TRUECOLOR'
# in orange: printf "\x1b[38;2;255;100;0mTRUECOLOR\x1b[0m\n"
#c.TerminalInteractiveShell.true_color = False
#------------------------------------------------------------------------------
# HistoryAccessor(HistoryAccessorBase) configuration
#------------------------------------------------------------------------------
## Access the history database without adding to it.
#
# This is intended for use by standalone history tools. IPython shells use
# HistoryManager, below, which is a subclass of this.
## Options for configuring the SQLite connection
#
# These options are passed as keyword args to sqlite3.connect when establishing
# database conenctions.
#c.HistoryAccessor.connection_options = {}
## enable the SQLite history
#
# set enabled=False to disable the SQLite history, in which case there will be
# no stored history, no SQLite connection, and no background saving thread.
# This may be necessary in some threaded environments where IPython is embedded.
#c.HistoryAccessor.enabled = True
## Path to file to use for SQLite history database.
#
# By default, IPython will put the history database in the IPython profile
# directory. If you would rather share one history among profiles, you can set
# this value in each, so that they are consistent.
#
# Due to an issue with fcntl, SQLite is known to misbehave on some NFS mounts.
# If you see IPython hanging, try setting this to something on a local disk,
# e.g::
#
# ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
#
# you can also use the specific value `:memory:` (including the colon at both
# end but not the back ticks), to avoid creating an history file.
#c.HistoryAccessor.hist_file = u''
#------------------------------------------------------------------------------
# HistoryManager(HistoryAccessor) configuration
#------------------------------------------------------------------------------
## A class to organize all history-related functionality in one place.
## Write to database every x commands (higher values save disk access & power).
# Values of 1 or less effectively disable caching.
#c.HistoryManager.db_cache_size = 0
## Should the history database include output? (default: no)
#c.HistoryManager.db_log_output = False
#------------------------------------------------------------------------------
# ProfileDir(LoggingConfigurable) configuration
#------------------------------------------------------------------------------
## An object to manage the profile directory and its resources.
#
# The profile directory is used by all IPython applications, to manage
# configuration, logging and security.
#
# This object knows how to find, create and manage these directories. This
# should be used by any code that wants to handle profiles.
## Set the profile location directly. This overrides the logic used by the
# `profile` option.
#c.ProfileDir.location = u''
#------------------------------------------------------------------------------
# BaseFormatter(Configurable) configuration
#------------------------------------------------------------------------------
## A base formatter class that is configurable.
#
# This formatter should usually be used as the base class of all formatters. It
# is a traited :class:`Configurable` class and includes an extensible API for
# users to determine how their objects are formatted. The following logic is
# used to find a function to format an given object.
#
# 1. The object is introspected to see if it has a method with the name
# :attr:`print_method`. If is does, that object is passed to that method
# for formatting.
# 2. If no print method is found, three internal dictionaries are consulted
# to find print method: :attr:`singleton_printers`, :attr:`type_printers`
# and :attr:`deferred_printers`.
#
# Users should use these dictionaries to register functions that will be used to
# compute the format data for their objects (if those objects don't have the
# special print methods). The easiest way of using these dictionaries is through
# the :meth:`for_type` and :meth:`for_type_by_name` methods.
#
# If no function/callable is found to compute the format data, ``None`` is
# returned and this format type is not used.
##
#c.BaseFormatter.deferred_printers = {}
##
#c.BaseFormatter.enabled = True
##
#c.BaseFormatter.singleton_printers = {}
##
#c.BaseFormatter.type_printers = {}
#------------------------------------------------------------------------------
# PlainTextFormatter(BaseFormatter) configuration
#------------------------------------------------------------------------------
## The default pretty-printer.
#
# This uses :mod:`IPython.lib.pretty` to compute the format data of the object.
# If the object cannot be pretty printed, :func:`repr` is used. See the
# documentation of :mod:`IPython.lib.pretty` for details on how to write pretty
# printers. Here is a simple example::
#
# def dtype_pprinter(obj, p, cycle):
# if cycle:
# return p.text('dtype(...)')
# if hasattr(obj, 'fields'):
# if obj.fields is None:
# p.text(repr(obj))
# else:
# p.begin_group(7, 'dtype([')
# for i, field in enumerate(obj.descr):
# if i > 0:
# p.text(',')
# p.breakable()
# p.pretty(field)
# p.end_group(7, '])')
##
#c.PlainTextFormatter.float_precision = ''
## Truncate large collections (lists, dicts, tuples, sets) to this size.
#
# Set to 0 to disable truncation.
#c.PlainTextFormatter.max_seq_length = 1000
##
#c.PlainTextFormatter.max_width = 79
##
#c.PlainTextFormatter.newline = '\n'
##
#c.PlainTextFormatter.pprint = True
##
#c.PlainTextFormatter.verbose = False
#------------------------------------------------------------------------------
# Completer(Configurable) configuration
#------------------------------------------------------------------------------
## Activate greedy completion PENDING DEPRECTION. this is now mostly taken care
# of with Jedi.
#
# This will enable completion on elements of lists, results of function calls,
# etc., but can be unsafe because the code is actually evaluated on TAB.
#c.Completer.greedy = False
#------------------------------------------------------------------------------
# IPCompleter(Completer) configuration
#------------------------------------------------------------------------------
## Extension of the completer class with IPython-specific features
## DEPRECATED as of version 5.0.
#
# Instruct the completer to use __all__ for the completion
#
# Specifically, when completing on ``object.<tab>``.
#
# When True: only those names in obj.__all__ will be included.
#
# When False [default]: the __all__ attribute is ignored
#c.IPCompleter.limit_to__all__ = False
## Whether to merge completion results into a single list
#
# If False, only the completion results from the first non-empty completer will
# be returned.
#c.IPCompleter.merge_completions = True
## Instruct the completer to omit private method names
#
# Specifically, when completing on ``object.<tab>``.
#
# When 2 [default]: all names that start with '_' will be excluded.
#
# When 1: all 'magic' names (``__foo__``) will be excluded.
#
# When 0: nothing will be excluded.
#c.IPCompleter.omit__names = 2
#------------------------------------------------------------------------------
# ScriptMagics(Magics) configuration
#------------------------------------------------------------------------------
## Magics for talking to scripts
#
# This defines a base `%%script` cell magic for running a cell with a program in
# a subprocess, and registers a few top-level magics that call %%script with
# common interpreters.
## Extra script cell magics to define
#
# This generates simple wrappers of `%%script foo` as `%%foo`.
#
# If you want to add script magics that aren't on your path, specify them in
# script_paths
#c.ScriptMagics.script_magics = []
## Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
#
# Only necessary for items in script_magics where the default path will not find
# the right interpreter.
#c.ScriptMagics.script_paths = {}
#------------------------------------------------------------------------------
# StoreMagics(Magics) configuration
#------------------------------------------------------------------------------
## Lightweight persistence for python variables.
#
# Provides the %store magic.
## If True, any %store-d variables will be automatically restored when IPython
# starts.
#c.StoreMagics.autorestore = False
| {
"content_hash": "4fa8e8fdc730f398bac65c221fd9480f",
"timestamp": "",
"source": "github",
"line_count": 574,
"max_line_length": 436,
"avg_line_length": 38.48432055749129,
"alnum_prop": 0.6577636939791761,
"repo_name": "google/skywater-pdk-libs-sky130_bag3_pr",
"id": "810c6411a6fede561e7feadc29a5375a1cc7d0fa",
"size": "23059",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "workspace_setup/ipython_config.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "413733"
},
{
"name": "Python",
"bytes": "88295"
},
{
"name": "Shell",
"bytes": "7141"
}
],
"symlink_target": ""
} |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/walletdb.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <fs.h>
#include <key_io.h>
#include <protocol.h>
#include <serialize.h>
#include <sync.h>
#include <util.h>
#include <utiltime.h>
#include <wallet/wallet.h>
#include <atomic>
#include <boost/thread.hpp>
//
// WalletBatch
//
bool WalletBatch::WriteName(const std::string& strAddress, const std::string& strName)
{
return WriteIC(std::make_pair(std::string("name"), strAddress), strName);
}
bool WalletBatch::EraseName(const std::string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
return EraseIC(std::make_pair(std::string("name"), strAddress));
}
bool WalletBatch::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
{
return WriteIC(std::make_pair(std::string("purpose"), strAddress), strPurpose);
}
bool WalletBatch::ErasePurpose(const std::string& strAddress)
{
return EraseIC(std::make_pair(std::string("purpose"), strAddress));
}
bool WalletBatch::WriteTx(const CWalletTx& wtx)
{
return WriteIC(std::make_pair(std::string("tx"), wtx.GetHash()), wtx);
}
bool WalletBatch::EraseTx(uint256 hash)
{
return EraseIC(std::make_pair(std::string("tx"), hash));
}
bool WalletBatch::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
if (!WriteIC(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta, false)) {
return false;
}
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
return WriteIC(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
bool WalletBatch::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata &keyMeta)
{
if (!WriteIC(std::make_pair(std::string("keymeta"), vchPubKey), keyMeta)) {
return false;
}
if (!WriteIC(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false)) {
return false;
}
EraseIC(std::make_pair(std::string("key"), vchPubKey));
EraseIC(std::make_pair(std::string("wkey"), vchPubKey));
return true;
}
bool WalletBatch::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
{
return WriteIC(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
}
bool WalletBatch::WriteCScript(const uint160& hash, const CScript& redeemScript)
{
return WriteIC(std::make_pair(std::string("cscript"), hash), redeemScript, false);
}
bool WalletBatch::WriteWatchOnly(const CScript &dest, const CKeyMetadata& keyMeta)
{
if (!WriteIC(std::make_pair(std::string("watchmeta"), dest), keyMeta)) {
return false;
}
return WriteIC(std::make_pair(std::string("watchs"), dest), '1');
}
bool WalletBatch::EraseWatchOnly(const CScript &dest)
{
if (!EraseIC(std::make_pair(std::string("watchmeta"), dest))) {
return false;
}
return EraseIC(std::make_pair(std::string("watchs"), dest));
}
bool WalletBatch::WriteBestBlock(const CBlockLocator& locator)
{
WriteIC(std::string("bestblock"), CBlockLocator()); // Write empty block locator so versions that require a merkle branch automatically rescan
return WriteIC(std::string("bestblock_nomerkle"), locator);
}
bool WalletBatch::ReadBestBlock(CBlockLocator& locator)
{
if (m_batch.Read(std::string("bestblock"), locator) && !locator.vHave.empty()) return true;
return m_batch.Read(std::string("bestblock_nomerkle"), locator);
}
bool WalletBatch::WriteOrderPosNext(int64_t nOrderPosNext)
{
return WriteIC(std::string("orderposnext"), nOrderPosNext);
}
bool WalletBatch::ReadPool(int64_t nPool, CKeyPool& keypool)
{
return m_batch.Read(std::make_pair(std::string("pool"), nPool), keypool);
}
bool WalletBatch::WritePool(int64_t nPool, const CKeyPool& keypool)
{
return WriteIC(std::make_pair(std::string("pool"), nPool), keypool);
}
bool WalletBatch::ErasePool(int64_t nPool)
{
return EraseIC(std::make_pair(std::string("pool"), nPool));
}
bool WalletBatch::WriteMinVersion(int nVersion)
{
return WriteIC(std::string("minversion"), nVersion);
}
bool WalletBatch::ReadAccount(const std::string& strAccount, CAccount& account)
{
account.SetNull();
return m_batch.Read(std::make_pair(std::string("acc"), strAccount), account);
}
bool WalletBatch::WriteAccount(const std::string& strAccount, const CAccount& account)
{
return WriteIC(std::make_pair(std::string("acc"), strAccount), account);
}
bool WalletBatch::EraseAccount(const std::string& strAccount)
{
return EraseIC(std::make_pair(std::string("acc"), strAccount));
}
bool WalletBatch::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return WriteIC(std::make_pair(std::string("acentry"), std::make_pair(acentry.strAccount, nAccEntryNum)), acentry);
}
CAmount WalletBatch::GetAccountCreditDebit(const std::string& strAccount)
{
std::list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
CAmount nCreditDebit = 0;
for (const CAccountingEntry& entry : entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void WalletBatch::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = m_batch.GetCursor();
if (!pcursor)
throw std::runtime_error(std::string(__func__) + ": cannot create DB cursor");
bool setRange = true;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (setRange)
ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? std::string("") : strAccount), uint64_t(0)));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = m_batch.ReadAtCursor(pcursor, ssKey, ssValue, setRange);
setRange = false;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw std::runtime_error(std::string(__func__) + ": error scanning DB");
}
// Unserialize
std::string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
ssKey >> acentry.nEntryNo;
entries.push_back(acentry);
}
pcursor->close();
}
class CWalletScanState {
public:
unsigned int nKeys;
unsigned int nCKeys;
unsigned int nWatchKeys;
unsigned int nKeyMeta;
unsigned int m_unknown_records;
bool fIsEncrypted;
bool fAnyUnordered;
int nFileVersion;
std::vector<uint256> vWalletUpgrade;
CWalletScanState() {
nKeys = nCKeys = nWatchKeys = nKeyMeta = m_unknown_records = 0;
fIsEncrypted = false;
fAnyUnordered = false;
nFileVersion = 0;
}
};
bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
CWalletScanState &wss, std::string& strType, std::string& strErr)
{
try {
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
ssKey >> strType;
if (strType == "name")
{
std::string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[DecodeDestination(strAddress)].name;
}
else if (strType == "purpose")
{
std::string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[DecodeDestination(strAddress)].purpose;
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx wtx(nullptr /* pwallet */, MakeTransactionRef());
ssValue >> wtx;
CValidationState state;
if (!(CheckTransaction(*wtx.tx, state) && (wtx.GetHash() == hash) && state.IsValid()))
return false;
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
{
if (!ssValue.empty())
{
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
}
if (wtx.nOrderPos == -1)
wss.fAnyUnordered = true;
pwallet->LoadToWallet(wtx);
}
else if (strType == "acentry")
{
std::string strAccount;
ssKey >> strAccount;
uint64_t nNumber;
ssKey >> nNumber;
if (nNumber > pwallet->nAccountingEntryNumber) {
pwallet->nAccountingEntryNumber = nNumber;
}
if (!wss.fAnyUnordered)
{
CAccountingEntry acentry;
ssValue >> acentry;
if (acentry.nOrderPos == -1)
wss.fAnyUnordered = true;
}
}
else if (strType == "watchs")
{
wss.nWatchKeys++;
CScript script;
ssKey >> script;
char fYes;
ssValue >> fYes;
if (fYes == '1')
pwallet->LoadWatchOnly(script);
}
else if (strType == "key" || strType == "wkey")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid())
{
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
CKey key;
CPrivKey pkey;
uint256 hash;
if (strType == "key")
{
wss.nKeys++;
ssValue >> pkey;
} else {
CWalletKey wkey;
ssValue >> wkey;
pkey = wkey.vchPrivKey;
}
// Old wallets store keys as "key" [pubkey] => [privkey]
// ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
// using EC operations as a checksum.
// Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
// remaining backwards-compatible.
try
{
ssValue >> hash;
}
catch (...) {}
bool fSkipCheck = false;
if (!hash.IsNull())
{
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + pkey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
if (Hash(vchKey.begin(), vchKey.end()) != hash)
{
strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
return false;
}
fSkipCheck = true;
}
if (!key.Load(pkey, vchPubKey, fSkipCheck))
{
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (!pwallet->LoadKey(key, vchPubKey))
{
strErr = "Error reading wallet database: LoadKey failed";
return false;
}
}
else if (strType == "mkey")
{
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if(pwallet->mapMasterKeys.count(nID) != 0)
{
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
return false;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
}
else if (strType == "ckey")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid())
{
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
std::vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
wss.nCKeys++;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
strErr = "Error reading wallet database: LoadCryptedKey failed";
return false;
}
wss.fIsEncrypted = true;
}
else if (strType == "keymeta")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadKeyMetadata(vchPubKey.GetID(), keyMeta);
}
else if (strType == "watchmeta")
{
CScript script;
ssKey >> script;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadScriptMetadata(CScriptID(script), keyMeta);
}
else if (strType == "defaultkey")
{
// We don't want or need the default key, but if there is one set,
// we want to make sure that it is valid so that we can detect corruption
CPubKey vchPubKey;
ssValue >> vchPubKey;
if (!vchPubKey.IsValid()) {
strErr = "Error reading wallet database: Default Key corrupt";
return false;
}
}
else if (strType == "pool")
{
int64_t nIndex;
ssKey >> nIndex;
CKeyPool keypool;
ssValue >> keypool;
pwallet->LoadKeyPool(nIndex, keypool);
}
else if (strType == "version")
{
ssValue >> wss.nFileVersion;
if (wss.nFileVersion == 10300)
wss.nFileVersion = 300;
}
else if (strType == "cscript")
{
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> script;
if (!pwallet->LoadCScript(script))
{
strErr = "Error reading wallet database: LoadCScript failed";
return false;
}
}
else if (strType == "orderposnext")
{
ssValue >> pwallet->nOrderPosNext;
}
else if (strType == "destdata")
{
std::string strAddress, strKey, strValue;
ssKey >> strAddress;
ssKey >> strKey;
ssValue >> strValue;
if (!pwallet->LoadDestData(DecodeDestination(strAddress), strKey, strValue))
{
strErr = "Error reading wallet database: LoadDestData failed";
return false;
}
}
else if (strType == "hdchain")
{
CHDChain chain;
ssValue >> chain;
if (!pwallet->SetHDChain(chain, true))
{
strErr = "Error reading wallet database: SetHDChain failed";
return false;
}
} else if (strType != "bestblock" && strType != "bestblock_nomerkle"){
wss.m_unknown_records++;
}
} catch (...)
{
return false;
}
return true;
}
bool WalletBatch::IsKeyType(const std::string& strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
DBErrors WalletBatch::LoadWallet(CWallet* pwallet)
{
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DBErrors::LOAD_OK;
LOCK(pwallet->cs_wallet);
try {
int nMinVersion = 0;
if (m_batch.Read((std::string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DBErrors::TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = m_batch.GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
return DBErrors::CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = m_batch.ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
return DBErrors::CORRUPT;
}
// Try to be tolerant of single corrupt records:
std::string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
{
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType) || strType == "defaultkey")
result = DBErrors::CORRUPT;
else
{
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
gArgs.SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
LogPrintf("%s\n", strErr);
}
pcursor->close();
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (...) {
result = DBErrors::CORRUPT;
}
if (fNoncriticalErrors && result == DBErrors::LOAD_OK)
result = DBErrors::NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
if (result != DBErrors::LOAD_OK)
return result;
LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total. Unknown wallet records: %u\n",
wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys, wss.m_unknown_records);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys + wss.nWatchKeys) != wss.nKeyMeta)
pwallet->UpdateTimeFirstKey(1);
for (uint256 hash : wss.vWalletUpgrade)
WriteTx(pwallet->mapWallet.at(hash));
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
return DBErrors::NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
if (wss.fAnyUnordered)
result = pwallet->ReorderTransactions();
pwallet->laccentries.clear();
ListAccountCreditDebit("*", pwallet->laccentries);
for (CAccountingEntry& entry : pwallet->laccentries) {
pwallet->wtxOrdered.insert(make_pair(entry.nOrderPos, CWallet::TxPair(nullptr, &entry)));
}
return result;
}
DBErrors WalletBatch::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx)
{
DBErrors result = DBErrors::LOAD_OK;
try {
int nMinVersion = 0;
if (m_batch.Read((std::string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DBErrors::TOO_NEW;
}
// Get cursor
Dbc* pcursor = m_batch.GetCursor();
if (!pcursor)
{
LogPrintf("Error getting wallet database cursor\n");
return DBErrors::CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = m_batch.ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
LogPrintf("Error reading next record from wallet database\n");
return DBErrors::CORRUPT;
}
std::string strType;
ssKey >> strType;
if (strType == "tx") {
uint256 hash;
ssKey >> hash;
CWalletTx wtx(nullptr /* pwallet */, MakeTransactionRef());
ssValue >> wtx;
vTxHash.push_back(hash);
vWtx.push_back(wtx);
}
}
pcursor->close();
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (...) {
result = DBErrors::CORRUPT;
}
return result;
}
DBErrors WalletBatch::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uint256>& vTxHashOut)
{
// build list of wallet TXs and hashes
std::vector<uint256> vTxHash;
std::vector<CWalletTx> vWtx;
DBErrors err = FindWalletTx(vTxHash, vWtx);
if (err != DBErrors::LOAD_OK) {
return err;
}
std::sort(vTxHash.begin(), vTxHash.end());
std::sort(vTxHashIn.begin(), vTxHashIn.end());
// erase each matching wallet TX
bool delerror = false;
std::vector<uint256>::iterator it = vTxHashIn.begin();
for (uint256 hash : vTxHash) {
while (it < vTxHashIn.end() && (*it) < hash) {
it++;
}
if (it == vTxHashIn.end()) {
break;
}
else if ((*it) == hash) {
if(!EraseTx(hash)) {
LogPrint(BCLog::DB, "Transaction was found for deletion but returned database error: %s\n", hash.GetHex());
delerror = true;
}
vTxHashOut.push_back(hash);
}
}
if (delerror) {
return DBErrors::CORRUPT;
}
return DBErrors::LOAD_OK;
}
DBErrors WalletBatch::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
// build list of wallet TXs
std::vector<uint256> vTxHash;
DBErrors err = FindWalletTx(vTxHash, vWtx);
if (err != DBErrors::LOAD_OK)
return err;
// erase each wallet TX
for (uint256& hash : vTxHash) {
if (!EraseTx(hash))
return DBErrors::CORRUPT;
}
return DBErrors::LOAD_OK;
}
void MaybeCompactWalletDB()
{
static std::atomic<bool> fOneThread(false);
if (fOneThread.exchange(true)) {
return;
}
if (!gArgs.GetBoolArg("-flushwallet", DEFAULT_FLUSHWALLET)) {
return;
}
for (CWalletRef pwallet : vpwallets) {
WalletDatabase& dbh = pwallet->GetDBHandle();
unsigned int nUpdateCounter = dbh.nUpdateCounter;
if (dbh.nLastSeen != nUpdateCounter) {
dbh.nLastSeen = nUpdateCounter;
dbh.nLastWalletUpdate = GetTime();
}
if (dbh.nLastFlushed != nUpdateCounter && GetTime() - dbh.nLastWalletUpdate >= 2) {
if (BerkeleyBatch::PeriodicFlush(dbh)) {
dbh.nLastFlushed = nUpdateCounter;
}
}
}
fOneThread = false;
}
//
// Try to (very carefully!) recover wallet file if there is a problem.
//
bool WalletBatch::Recover(const fs::path& wallet_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& out_backup_filename)
{
return BerkeleyBatch::Recover(wallet_path, callbackDataIn, recoverKVcallback, out_backup_filename);
}
bool WalletBatch::Recover(const fs::path& wallet_path, std::string& out_backup_filename)
{
// recover without a key filter callback
// results in recovering all record types
return WalletBatch::Recover(wallet_path, nullptr, nullptr, out_backup_filename);
}
bool WalletBatch::RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue)
{
CWallet *dummyWallet = reinterpret_cast<CWallet*>(callbackData);
CWalletScanState dummyWss;
std::string strType, strErr;
bool fReadOK;
{
// Required in LoadKeyMetadata():
LOCK(dummyWallet->cs_wallet);
fReadOK = ReadKeyValue(dummyWallet, ssKey, ssValue,
dummyWss, strType, strErr);
}
if (!IsKeyType(strType) && strType != "hdchain")
return false;
if (!fReadOK)
{
LogPrintf("WARNING: WalletBatch::Recover skipping %s: %s\n", strType, strErr);
return false;
}
return true;
}
bool WalletBatch::VerifyEnvironment(const fs::path& wallet_path, std::string& errorStr)
{
return BerkeleyBatch::VerifyEnvironment(wallet_path, errorStr);
}
bool WalletBatch::VerifyDatabaseFile(const fs::path& wallet_path, std::string& warningStr, std::string& errorStr)
{
return BerkeleyBatch::VerifyDatabaseFile(wallet_path, warningStr, errorStr, WalletBatch::Recover);
}
bool WalletBatch::WriteDestData(const std::string &address, const std::string &key, const std::string &value)
{
return WriteIC(std::make_pair(std::string("destdata"), std::make_pair(address, key)), value);
}
bool WalletBatch::EraseDestData(const std::string &address, const std::string &key)
{
return EraseIC(std::make_pair(std::string("destdata"), std::make_pair(address, key)));
}
bool WalletBatch::WriteHDChain(const CHDChain& chain)
{
return WriteIC(std::string("hdchain"), chain);
}
bool WalletBatch::TxnBegin()
{
return m_batch.TxnBegin();
}
bool WalletBatch::TxnCommit()
{
return m_batch.TxnCommit();
}
bool WalletBatch::TxnAbort()
{
return m_batch.TxnAbort();
}
bool WalletBatch::ReadVersion(int& nVersion)
{
return m_batch.ReadVersion(nVersion);
}
bool WalletBatch::WriteVersion(int nVersion)
{
return m_batch.WriteVersion(nVersion);
}
| {
"content_hash": "1ebd1869b00e4a2b44b7075edf586592",
"timestamp": "",
"source": "github",
"line_count": 866,
"max_line_length": 197,
"avg_line_length": 31.594688221709006,
"alnum_prop": 0.5771353386206645,
"repo_name": "TheBlueMatt/bitcoin",
"id": "bcc7cf877d4ba1e56704e27fd2a03256fb7f94ad",
"size": "27361",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/wallet/walletdb.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28453"
},
{
"name": "C",
"bytes": "682719"
},
{
"name": "C++",
"bytes": "5617014"
},
{
"name": "HTML",
"bytes": "21860"
},
{
"name": "Java",
"bytes": "30290"
},
{
"name": "M4",
"bytes": "197004"
},
{
"name": "Makefile",
"bytes": "114174"
},
{
"name": "Objective-C",
"bytes": "148160"
},
{
"name": "Objective-C++",
"bytes": "6763"
},
{
"name": "Python",
"bytes": "1315012"
},
{
"name": "QMake",
"bytes": "756"
},
{
"name": "Shell",
"bytes": "77381"
}
],
"symlink_target": ""
} |
export { default as shallowEqualObjects } from './objects';
export { default as shallowEqualArrays } from './arrays';
| {
"content_hash": "910c31db49b2bac81003515da63be821",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 59,
"avg_line_length": 59,
"alnum_prop": 0.7457627118644068,
"repo_name": "moroshko/shallow-equal",
"id": "92868adf028cefce7776cf83ec9d8a085103f13f",
"size": "118",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3821"
}
],
"symlink_target": ""
} |
package electric.dbs;
import java.sql.*;
import javax.servlet.http.*;
import electric.*;
import java.text.SimpleDateFormat;
import electric.electricUtils.*;
public class Dbware
{
private static final String LOAD_WARE_BY_ID =
"SELECT * FROM [WARE] WHERE [Id]=?";
private static final String INSERT_WARE =
"INSERT INTO [WARE] ([Id],[Pname],[Pmodel],[Pcost],[Pheft]," +
"[Pfacturer],[Pnote],[Createdate],[STATUS]) VALUES " +
"(?,?,?,?,?,?,?,?,?)";
private static final String UPDATE_WARE =
"UPDATE [WARE] SET [Pname]=?,[Pmodel]=?,[Pcost]=?,[Pheft]=?," +
"[Pfacturer]=?,[Pnote]=?,[Status]=? WHERE [Id]=?";
private static final String Del_ware =
"UPDATE [WARE] SET [Status]=? WHERE [Id]=?";
private static final String CLEAR_WARE = "DELETE FROM [WARE] WHERE STATUS=" +
FinalConstants.STATUS_DELETE;
private int Id;
private String Pname;
private String Pmodel;
private String Pcost;
private String Pheft;
private String Pfacturer;
private String Pnote;
private String Createdate;
private int Status;
public Dbware(HttpServletRequest request) {
this.Id = DbSequenceManager.nextID(FinalConstants.T_WARE);
this.Pname = ParamUtils.getEscapeHTMLParameter(request, "pname");
this.Pmodel = ParamUtils.getEscapeHTMLParameter(request, "pmodel");
this.Pcost = ParamUtils.getEscapeHTMLParameter(request, "pcost");
this.Pheft = ParamUtils.getEscapeHTMLParameter(request, "pheft");
this.Pfacturer = ParamUtils.getEscapeHTMLParameter(request, "pfacturer");
this.Pnote = ParamUtils.getEscapeHTMLParameter(request, "pnote");
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMdd");
String shiftDateToDate = simpleDate.format(new java.util.Date());
this.Createdate = shiftDateToDate;
this.Status = FinalConstants.STATUS_NORMAL;
insertIntoDb();
}
public Dbware()
{}
public Dbware(int Id) throws WareNotFoundException {
this.Id = Id;
if (Id <= 0) {
return;
}
loadFromDb();
}
public static Dbware getInstance(int Id) throws
WareNotFoundException {
return new Dbware(Id);
}
protected void delete() {
setStatus(FinalConstants.STATUS_DELETE);
}
protected static void clear() {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(CLEAR_WARE);
pstmt.executeUpdate();
}
catch (SQLException sqle) {
System.err.println(
"SQLException in DbTChatRooms.java:clearTChatRooms(): " + sqle);
sqle.printStackTrace();
}
finally {
try {
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/////////////////////////////////////////////////////////////////
public int getId() {
return this.Id;
}
public String getPname()
{
return this.Pname;
}
public String getPmodel()
{
return this.Pmodel;
}
public String getPcost()
{
return this.Pcost;
}
public String getPheft()
{
return this.Pheft;
}
public String getPfacturer()
{
return this.Pfacturer;
}
public String getPnote()
{
return this.Pnote;
}
public String getCreateDate()
{
return this.Createdate;
}
public int getStatus()
{
return this.Status;
}
//////////////////////WRITE METHODS/////////////////////////////
/////////////////////////////////////////////////////////////////
public void setId(int Id) {
this.Id=Id;
saveToDb();
}
public void setPname(String Pname)
{
this.Pname=Pname;
saveToDb();
}
public void setPmodel(String Pmodel)
{
this.Pmodel=Pmodel;
saveToDb();
}
public void setPcost(String Pcost)
{
this.Pcost=Pcost;
saveToDb();
}
public void setPheft(String Pheft)
{
this.Pheft=Pheft;
saveToDb();
}
public void setPfacturer(String Pfacturer)
{
this.Pfacturer=Pfacturer;
saveToDb();
}
public void setPnote(String pnote)
{
this.Pnote=Pnote;
saveToDb();
}
public void setCreateDate(String CreateDate)
{
this.Createdate=CreateDate;
saveToDb();
}
public void setStatus(int status)
{
this.Status=status;
DELToDb();
}
////////////////////////////////////////////////////////////////////////////////
public void modify(HttpServletRequest request) {
this.Id = ParamUtils.getIntParameter(request, "id");
this.Pname = ParamUtils.getEscapeHTMLParameter(request, "pname");
this.Pmodel = ParamUtils.getEscapeHTMLParameter(request, "pmodel");
this.Pcost = ParamUtils.getEscapeHTMLParameter(request, "pcost");
this.Pheft = ParamUtils.getEscapeHTMLParameter(request, "pheft");
this.Pfacturer = ParamUtils.getEscapeHTMLParameter(request, "pfacturer");
this.Pnote = ParamUtils.getEscapeHTMLParameter(request, "pnote");
this.Status = FinalConstants.STATUS_NORMAL;
saveToDb();
}
private void loadFromDb() throws WareNotFoundException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_WARE_BY_ID);
pstmt.setInt(1,Id);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) {
throw new WareNotFoundException("´ÓÊý¾Ý±í[ware]ÖжÁÈ¡Óû§Êý¾Ýʧ°Ü,Óû¶ÁÈ¡µÄÓû§ID:[ " +
Id + "]!");
}
this.Id = rs.getInt("Id");
this.Pname= rs.getString("Pname");
this.Pmodel=rs.getString("Pmodel");
this.Pcost=rs.getString("Pcost");
this.Pheft=rs.getString("Pheft");
this.Pfacturer=rs.getString("Pfacturer");
this.Pnote=rs.getString("Pnote");
this.Createdate=rs.getString("Createdate");
this.Status=rs.getInt("Status");
}
catch (SQLException sqle) {
throw new WareNotFoundException("´ÓÊý¾Ý±í[WARE]ÖжÁÈ¡Óû§Êý¾Ýʧ°Ü,Óû¶ÁÈ¡µÄÓû§ID:[ " +
Id + "]!");
}
finally {
try {
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void insertIntoDb() {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(INSERT_WARE);
pstmt.setInt(1, this.Id);
pstmt.setString(2,StringUtils.toChinese(this.Pname));
pstmt.setString(3,StringUtils.toChinese(this.Pmodel));
pstmt.setString(4, StringUtils.toChinese(this.Pcost));
pstmt.setString(5, StringUtils.toChinese(this.Pheft));
pstmt.setString(6, StringUtils.toChinese(this.Pfacturer));
pstmt.setString(7, StringUtils.toChinese(this.Pnote));
pstmt.setString(8, StringUtils.toChinese(this.Createdate));
pstmt.setInt(9, this.Status);
pstmt.executeUpdate();
}
catch (SQLException sqle) {
System.err.println("´íÎóλÖÃ: Dbware:insertIntoDb()-" + sqle);
sqle.printStackTrace();
}
finally {
try {
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void saveToDb() {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(UPDATE_WARE);
System.out.println(UPDATE_WARE);
pstmt.setString(1, StringUtils.toChinese(this.Pname));
pstmt.setString(2, StringUtils.toChinese(this.Pmodel));
pstmt.setString(3, StringUtils.toChinese(this.Pcost));
pstmt.setString(4, StringUtils.toChinese(this.Pheft));
pstmt.setString(5, StringUtils.toChinese(this.Pfacturer));
pstmt.setString(6, StringUtils.toChinese(this.Pnote));
pstmt.setInt(7, this.Status);
pstmt.setInt(8, this.Id);
pstmt.executeUpdate();
}
catch (SQLException sqle) {
System.err.println("´íÎóλÖÃ: DbWare.java:saveToDb(): " + sqle);
sqle.printStackTrace();
}
finally {
try {
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void DELToDb() {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(Del_ware);
System.out.println(Del_ware);
pstmt.setInt(1, this.Status);
pstmt.setInt(2, this.Id);
pstmt.executeUpdate();
}
catch (SQLException sqle) {
System.err.println("´íÎóλÖÃ: DbShop.java:DELToDb(): " + sqle);
sqle.printStackTrace();
}
finally {
try {
pstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
| {
"content_hash": "918c17908cfe6c83427614d42aa372a7",
"timestamp": "",
"source": "github",
"line_count": 364,
"max_line_length": 92,
"avg_line_length": 24.681318681318682,
"alnum_prop": 0.6207702582368655,
"repo_name": "java-scott/java-project",
"id": "c96fbf0a7fc0d34b81df9ff58cbbf56892883f01",
"size": "9137",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "实战突击:JavaWeb项目整合开发/18/src/electric/dbs/Dbware.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "76093"
},
{
"name": "FreeMarker",
"bytes": "4912"
},
{
"name": "HTML",
"bytes": "78841"
},
{
"name": "Java",
"bytes": "4357896"
},
{
"name": "JavaScript",
"bytes": "68490"
}
],
"symlink_target": ""
} |
from certidude.decorators import serialize
from certidude.relational import RelationalMixin
from .utils.firewall import login_required, authorize_admin
class LogResource(RelationalMixin):
SQL_CREATE_TABLES = "log_tables.sql"
@serialize
@login_required
@authorize_admin
def on_get(self, req, resp):
# TODO: Add last id parameter
return self.iterfetch("select * from log order by created desc limit ?",
req.get_param_as_int("limit", required=True))
| {
"content_hash": "6b9821b2a8df1d7f610fe4f5b2129c20",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 80,
"avg_line_length": 35.5,
"alnum_prop": 0.7142857142857143,
"repo_name": "laurivosandi/certidude",
"id": "738ac1af4749e777b6eded57b75760d4e379ef34",
"size": "498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "certidude/api/log.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1975"
},
{
"name": "HTML",
"bytes": "49742"
},
{
"name": "JavaScript",
"bytes": "26756"
},
{
"name": "PLSQL",
"bytes": "552"
},
{
"name": "PowerShell",
"bytes": "3496"
},
{
"name": "Python",
"bytes": "287173"
},
{
"name": "Shell",
"bytes": "38036"
}
],
"symlink_target": ""
} |
Android app find your desire museum and see all the available exhibits
| {
"content_hash": "19b0be266fdd6f7cd913e4c4e84d05ec",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 70,
"avg_line_length": 71,
"alnum_prop": 0.8309859154929577,
"repo_name": "GBardis/MuseDroid",
"id": "3b372bd951a54d99fea2b6bf46523155142353bc",
"size": "83",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "151039"
}
],
"symlink_target": ""
} |
"""
Examples to show usage of the azure-core-tracing-opentelemetry
with the App Configuration SDK and exporting to
Azure monitor backend. This example traces calls for creating
a configuration setting via the App Configuration sdk. The telemetry
will be collected automatically and sent to Application Insights
via the AzureMonitorTraceExporter
"""
import os
# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs
from azure.core.settings import settings
from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan
settings.tracing_implementation = OpenTelemetrySpan
# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python
# for details
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
# azure monitor trace exporter to send telemetry to appinsights
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
span_processor = BatchSpanProcessor(
AzureMonitorTraceExporter.from_connection_string(
os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
)
trace.get_tracer_provider().add_span_processor(span_processor)
# Example with App Configs SDKs
from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting
connection_str = "<connection_string>"
client = AzureAppConfigurationClient.from_connection_string(connection_str)
with tracer.start_as_current_span(name="AppConfig"):
config_setting = ConfigurationSetting(
key="MyKey",
label="MyLabel",
value="my value",
content_type="my content type",
tags={"my tag": "my tag value"}
)
added_config_setting = client.add_configuration_setting(config_setting)
| {
"content_hash": "2bc04aa4093a977ba02986d2c8a90f0d",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 100,
"avg_line_length": 37.22,
"alnum_prop": 0.7925846319183235,
"repo_name": "Azure/azure-sdk-for-python",
"id": "01762681bce388dead44a7dcec925cf6574963fc",
"size": "1955",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1224"
},
{
"name": "Bicep",
"bytes": "24196"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "4892"
},
{
"name": "HTML",
"bytes": "12058"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "Jinja",
"bytes": "10377"
},
{
"name": "Jupyter Notebook",
"bytes": "272022"
},
{
"name": "PowerShell",
"bytes": "518535"
},
{
"name": "Python",
"bytes": "715484989"
},
{
"name": "Shell",
"bytes": "3631"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="250dp"
android:minHeight="40dp"
android:updatePeriodMillis="1800000"
android:previewImage="@drawable/ic_launcher"
android:initialLayout="@layout/widget"
android:widgetCategory="home_screen">
</appwidget-provider> | {
"content_hash": "e0de6700ae5b10b4828fceb14499bc26",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 78,
"avg_line_length": 37.3,
"alnum_prop": 0.739946380697051,
"repo_name": "mattlogan/SurgePriceWidget",
"id": "f216634f74312dc8718899b0bb2b0d424ffd4120",
"size": "373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/xml/surge_price_appwidget_info.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "1192"
},
{
"name": "Java",
"bytes": "12315"
}
],
"symlink_target": ""
} |
#include "ecma-alloc.h"
#include "ecma-globals.h"
#include "ecma-gc.h"
#include "ecma-lcache.h"
#include "jrt.h"
#include "jmem.h"
JERRY_STATIC_ASSERT (sizeof (ecma_property_value_t) == sizeof (ecma_value_t),
size_of_ecma_property_value_t_must_be_equal_to_size_of_ecma_value_t);
JERRY_STATIC_ASSERT (((sizeof (ecma_property_value_t) - 1) & sizeof (ecma_property_value_t)) == 0,
size_of_ecma_property_value_t_must_be_power_of_2);
JERRY_STATIC_ASSERT (sizeof (ecma_string_t) == sizeof (uint64_t),
size_of_ecma_string_t_must_be_less_than_or_equal_to_8_bytes);
JERRY_STATIC_ASSERT (sizeof (ecma_extended_object_t) - sizeof (ecma_object_t) <= sizeof (uint64_t),
size_of_ecma_extended_object_part_must_be_less_than_or_equal_to_8_bytes);
/** \addtogroup ecma ECMA
* @{
*
* \addtogroup ecmaalloc Routines for allocation/freeing memory for ECMA data types
* @{
*/
/**
* Implementation of routines for allocation/freeing memory for ECMA data types.
*
* All allocation routines from this module have the same structure:
* 1. Try to allocate memory.
* 2. If allocation was successful, return pointer to the allocated block.
* 3. Run garbage collection.
* 4. Try to allocate memory.
* 5. If allocation was successful, return pointer to the allocated block;
* else - shutdown engine.
*/
/**
* Allocate memory for ecma-number
*
* @return pointer to allocated memory
*/
ecma_number_t *
ecma_alloc_number (void)
{
return (ecma_number_t *) jmem_pools_alloc (sizeof (ecma_number_t));
} /* ecma_alloc_number */
/**
* Dealloc memory from an ecma-number
*/
void
ecma_dealloc_number (ecma_number_t *number_p) /**< number to be freed */
{
jmem_pools_free ((uint8_t *) number_p, sizeof (ecma_number_t));
} /* ecma_dealloc_number */
/**
* Allocate memory for ecma-object
*
* @return pointer to allocated memory
*/
inline ecma_object_t * JERRY_ATTR_ALWAYS_INLINE
ecma_alloc_object (void)
{
#ifdef JMEM_STATS
jmem_stats_allocate_object_bytes (sizeof (ecma_object_t));
#endif /* JMEM_STATS */
return (ecma_object_t *) jmem_pools_alloc (sizeof (ecma_object_t));
} /* ecma_alloc_object */
/**
* Dealloc memory from an ecma-object
*/
inline void JERRY_ATTR_ALWAYS_INLINE
ecma_dealloc_object (ecma_object_t *object_p) /**< object to be freed */
{
#ifdef JMEM_STATS
jmem_stats_free_object_bytes (sizeof (ecma_object_t));
#endif /* JMEM_STATS */
jmem_pools_free (object_p, sizeof (ecma_object_t));
} /* ecma_dealloc_object */
/**
* Allocate memory for extended object
*
* @return pointer to allocated memory
*/
inline ecma_extended_object_t * JERRY_ATTR_ALWAYS_INLINE
ecma_alloc_extended_object (size_t size) /**< size of object */
{
#ifdef JMEM_STATS
jmem_stats_allocate_object_bytes (size);
#endif /* JMEM_STATS */
return jmem_heap_alloc_block (size);
} /* ecma_alloc_extended_object */
/**
* Dealloc memory of an extended object
*/
inline void JERRY_ATTR_ALWAYS_INLINE
ecma_dealloc_extended_object (ecma_object_t *object_p, /**< extended object */
size_t size) /**< size of object */
{
#ifdef JMEM_STATS
jmem_stats_free_object_bytes (size);
#endif /* JMEM_STATS */
jmem_heap_free_block (object_p, size);
} /* ecma_dealloc_extended_object */
/**
* Allocate memory for ecma-string descriptor
*
* @return pointer to allocated memory
*/
inline ecma_string_t * JERRY_ATTR_ALWAYS_INLINE
ecma_alloc_string (void)
{
#ifdef JMEM_STATS
jmem_stats_allocate_string_bytes (sizeof (ecma_string_t));
#endif /* JMEM_STATS */
return (ecma_string_t *) jmem_pools_alloc (sizeof (ecma_string_t));
} /* ecma_alloc_string */
/**
* Dealloc memory from ecma-string descriptor
*/
inline void JERRY_ATTR_ALWAYS_INLINE
ecma_dealloc_string (ecma_string_t *string_p) /**< string to be freed */
{
#ifdef JMEM_STATS
jmem_stats_free_string_bytes (sizeof (ecma_string_t));
#endif /* JMEM_STATS */
jmem_pools_free (string_p, sizeof (ecma_string_t));
} /* ecma_dealloc_string */
/**
* Allocate memory for string with character data
*
* @return pointer to allocated memory
*/
inline ecma_string_t * JERRY_ATTR_ALWAYS_INLINE
ecma_alloc_string_buffer (size_t size) /**< size of string */
{
#ifdef JMEM_STATS
jmem_stats_allocate_string_bytes (size);
#endif /* JMEM_STATS */
return jmem_heap_alloc_block (size);
} /* ecma_alloc_string_buffer */
/**
* Dealloc memory of a string with character data
*/
inline void JERRY_ATTR_ALWAYS_INLINE
ecma_dealloc_string_buffer (ecma_string_t *string_p, /**< string with data */
size_t size) /**< size of string */
{
#ifdef JMEM_STATS
jmem_stats_free_string_bytes (size);
#endif /* JMEM_STATS */
jmem_heap_free_block (string_p, size);
} /* ecma_dealloc_string_buffer */
/**
* Allocate memory for getter-setter pointer pair
*
* @return pointer to allocated memory
*/
inline ecma_getter_setter_pointers_t * JERRY_ATTR_ALWAYS_INLINE
ecma_alloc_getter_setter_pointers (void)
{
#ifdef JMEM_STATS
jmem_stats_allocate_property_bytes (sizeof (ecma_property_pair_t));
#endif /* JMEM_STATS */
return (ecma_getter_setter_pointers_t *) jmem_pools_alloc (sizeof (ecma_getter_setter_pointers_t));
} /* ecma_alloc_getter_setter_pointers */
/**
* Dealloc memory from getter-setter pointer pair
*/
inline void JERRY_ATTR_ALWAYS_INLINE
ecma_dealloc_getter_setter_pointers (ecma_getter_setter_pointers_t *getter_setter_pointers_p) /**< pointer pair
* to be freed */
{
#ifdef JMEM_STATS
jmem_stats_free_property_bytes (sizeof (ecma_property_pair_t));
#endif /* JMEM_STATS */
jmem_pools_free (getter_setter_pointers_p, sizeof (ecma_getter_setter_pointers_t));
} /* ecma_dealloc_getter_setter_pointers */
/**
* Allocate memory for ecma-property pair
*
* @return pointer to allocated memory
*/
inline ecma_property_pair_t * JERRY_ATTR_ALWAYS_INLINE
ecma_alloc_property_pair (void)
{
#ifdef JMEM_STATS
jmem_stats_allocate_property_bytes (sizeof (ecma_property_pair_t));
#endif /* JMEM_STATS */
return jmem_heap_alloc_block (sizeof (ecma_property_pair_t));
} /* ecma_alloc_property_pair */
/**
* Dealloc memory of an ecma-property
*/
inline void JERRY_ATTR_ALWAYS_INLINE
ecma_dealloc_property_pair (ecma_property_pair_t *property_pair_p) /**< property pair to be freed */
{
#ifdef JMEM_STATS
jmem_stats_free_property_bytes (sizeof (ecma_property_pair_t));
#endif /* JMEM_STATS */
jmem_heap_free_block (property_pair_p, sizeof (ecma_property_pair_t));
} /* ecma_dealloc_property_pair */
/**
* @}
* @}
*/
| {
"content_hash": "7adc7bbafa768d2c547fd3c6a5f0e8ce",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 112,
"avg_line_length": 28.358974358974358,
"alnum_prop": 0.6752561784207354,
"repo_name": "yichoi/jerryscript",
"id": "c41456a3f47efb065cfd96df3c15d9f7d5ec9fc3",
"size": "7268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jerry-core/ecma/base/ecma-alloc.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1898"
},
{
"name": "C",
"bytes": "3320703"
},
{
"name": "C++",
"bytes": "252504"
},
{
"name": "CMake",
"bytes": "50175"
},
{
"name": "JavaScript",
"bytes": "1674779"
},
{
"name": "Makefile",
"bytes": "17988"
},
{
"name": "Python",
"bytes": "154989"
},
{
"name": "Shell",
"bytes": "55868"
},
{
"name": "Tcl",
"bytes": "45226"
}
],
"symlink_target": ""
} |
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("Sif.Framework.Demo.Setup")]
[assembly: AssemblyDescription("Utilities for setting up a database for demonstration use.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Systemic Pty Ltd")]
[assembly: AssemblyProduct("Sif.Framework.Demo.Setup")]
[assembly: AssemblyCopyright("Copyright © Systemic Pty Ltd 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("efe10eeb-be82-41af-8fe3-322867391856")]
// 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("3.2.1.12")]
[assembly: AssemblyFileVersion("3.2.1.12")]
| {
"content_hash": "ea534104bc875f277df76991f628b356",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 93,
"avg_line_length": 42.02777777777778,
"alnum_prop": 0.7521480502313285,
"repo_name": "nsip/Sif3Framework-dotNet",
"id": "0b25556eb0e61ebcecd9758a2f3a0323ee0d69ec",
"size": "1516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Code/Sif3FrameworkDemo/Sif.Framework.Demo.Setup/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "375"
},
{
"name": "Batchfile",
"bytes": "7586"
},
{
"name": "C#",
"bytes": "7318736"
}
],
"symlink_target": ""
} |
<!--
TODO: Please edit this Readme.developer.md file to include information
for developers or advanced users, for example:
* Information about app internals and implementation details
* How to report bugs or contribute to development
-->
## Implementation
This app runs the "batch" command of CNVkit and exposes most of the available
options.
## Running this app with additional computational resources
The program is parallelized and will attempt to use all of the available cores,
if given the same number or more samples to process.
This app has the following entry points:
* main
When running this app, you can override the instance type to be used by
providing the ``systemRequirements`` field to ```/applet-XXXX/run``` or
```/app-XXXX/run```, as follows:
{
systemRequirements: {
"main": {"instanceType": "mem2_hdd2_x2"}
},
[...]
}
See <a
href="https://wiki.dnanexus.com/API-Specification-v1.0.0/IO-and-Run-Specifications#Run-Specification">Run
Specification</a> in the API documentation for more information about the
available instance types.
| {
"content_hash": "2f1ee1f34b245d0c8541ad86e2ee2bf4",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 105,
"avg_line_length": 28.81578947368421,
"alnum_prop": 0.7397260273972602,
"repo_name": "etal/cnvkit-dnanexus",
"id": "201d27842f817d3d263c9fc42a6096700d5cd2ed",
"size": "1128",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cnvkit_batch/Readme.developer.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "411"
},
{
"name": "Python",
"bytes": "37576"
},
{
"name": "Shell",
"bytes": "3391"
}
],
"symlink_target": ""
} |
import {
async,
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder }
from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { RioLoginModal } from './index';
describe('Component: Login Modal', () => {
let builder: TestComponentBuilder;
beforeEachProviders(() => [RioLoginModal]);
beforeEach(inject([TestComponentBuilder],
function (tcb: TestComponentBuilder) {
builder = tcb;
})
);
it('should inject the component', inject([RioLoginModal],
(component: RioLoginModal) => {
expect(component).toBeTruthy();
}));
it('should create the component', async(inject([], () => {
return builder.createAsync(RioLoginModal)
.then((fixture: ComponentFixture<any>) => {
fixture.detectChanges();
let element = fixture.nativeElement;
expect(element.querySelector('rio-modal-content')).not.toBeNull();
expect(element.querySelector('h1').innerText).toEqual('Login');
expect(element.querySelector('rio-login-form')).not.toBeNull();
expect(fixture.componentInstance.submit).toBeTruthy();
});
})));
it('should emit an event when handleSubmit is called',
async(inject([], () => {
return builder.createAsync(RioLoginModal)
.then((fixture: ComponentFixture<any>) => {
let login = { username: 'user', password: 'pass' };
fixture.componentInstance.handleSubmit(login);
fixture.componentInstance.submit.subscribe(data => {
expect(data).toBeDefined();
expect(data.username).toEqual('user');
expect(data.password).toEqual('pass');
});
});
}))
);
});
| {
"content_hash": "ac4ef662dfa23ca9c476ea5989ad8acd",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 74,
"avg_line_length": 30.637931034482758,
"alnum_prop": 0.6381541924592009,
"repo_name": "clbond/angular2-chat",
"id": "cfd11b48d0cd6be03fd11f335fbd3b0d12c1d7cf",
"size": "1777",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/login/login-modal.test.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2916"
},
{
"name": "HTML",
"bytes": "2987"
},
{
"name": "JavaScript",
"bytes": "13951"
},
{
"name": "RobotFramework",
"bytes": "3971"
},
{
"name": "TypeScript",
"bytes": "97068"
}
],
"symlink_target": ""
} |
Repository for my Racket code
| {
"content_hash": "6d67dbe4527c1e3419430e2174053d18",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 29,
"avg_line_length": 30,
"alnum_prop": 0.8333333333333334,
"repo_name": "hectoregm/racket",
"id": "e49ff653bce54d58f811fdc5921782d4bf3df608",
"size": "39",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "1332"
},
{
"name": "Racket",
"bytes": "141937"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "663cdad7aee9003c10dbf3e85fc603eb",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "efdcebc64bc93c4df8d3ce4d03165d54d00b45fe",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Marchantiophyta/Marchantiopsida/Marchantiales/Aytoniaceae/Mannia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
if File.exist?('spec/codeclimate_env.rb')
require 'codeclimate_env.rb'
require 'codeclimate-test-reporter'
CodeClimate::TestReporter.start
end
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path('../dummy/config/environment', __FILE__)
require 'rspec/rails'
require 'factory_girl'
require 'factories'
require 'database_cleaner'
require 'rspec/autorun'
require 'pry-nav'
require 'pry-rails'
require 'pry-stack_explorer'
require 'pry-theme'
require 'shoulda-matchers'
require 'rspec/collection_matchers'
include Fuel
# ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
config.before :each, type: :controller do
controller.class.include Fuel::Engine.routes.url_helpers
end
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
# config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
# config.order = "random"
config.include FactoryGirl::Syntax::Methods
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
| {
"content_hash": "33bf4c8e00e5eb7c877b9ae92035e64f",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 79,
"avg_line_length": 28.710526315789473,
"alnum_prop": 0.733730522456462,
"repo_name": "LaunchPadLab/fuel",
"id": "c61c9a4c7db731b802be87588ed243a4a84c037e",
"size": "2182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "29876"
},
{
"name": "HTML",
"bytes": "26623"
},
{
"name": "JavaScript",
"bytes": "38985"
},
{
"name": "Ruby",
"bytes": "78884"
}
],
"symlink_target": ""
} |
$packageName = 'amule.portable'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url = 'https://sourceforge.net/projects/amule/files/aMule/2.3.2/aMule-2.3.2.zip'
$checksum = 'd82741ed3a0b5772401c9155f72ba960c5df0a55fa6b1170aa0ff7e332dbb1bc'
$checksumType = 'sha256'
Install-ChocolateyZipPackage -PackageName "$packageName" `
-Url "$url" `
-UnzipLocation "$toolsDir" `
-Checksum "$checksum" `
-ChecksumType "$checksumType" | {
"content_hash": "555ece9f6c7727afbc6bcd2306a78718",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 81,
"avg_line_length": 51.09090909090909,
"alnum_prop": 0.6103202846975089,
"repo_name": "dtgm/chocolatey-packages",
"id": "26cdf14d3795d699b908839f338664226c19c138",
"size": "564",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "automatic/_output/amule.portable/2.3.2/tools/chocolateyInstall.ps1",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AutoHotkey",
"bytes": "347616"
},
{
"name": "AutoIt",
"bytes": "13530"
},
{
"name": "Batchfile",
"bytes": "1404"
},
{
"name": "C#",
"bytes": "8134"
},
{
"name": "HTML",
"bytes": "80818"
},
{
"name": "PowerShell",
"bytes": "13124493"
}
],
"symlink_target": ""
} |
package generated.zcsclient.account;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for modifyZimletPrefsSpec complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="modifyZimletPrefsSpec">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="presence" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "modifyZimletPrefsSpec")
public class testModifyZimletPrefsSpec {
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "presence", required = true)
protected String presence;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the presence property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPresence() {
return presence;
}
/**
* Sets the value of the presence property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPresence(String value) {
this.presence = value;
}
}
| {
"content_hash": "d8ee83848ecc47676ae8d028b79fc962",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 104,
"avg_line_length": 23.977011494252874,
"alnum_prop": 0.5963566634707574,
"repo_name": "nico01f/z-pec",
"id": "c9d752ea8e2847560b1f12aa79a8d2409caba4b9",
"size": "2086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ZimbraSoap/src/wsdl-test/generated/zcsclient/account/testModifyZimletPrefsSpec.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "18110"
},
{
"name": "C",
"bytes": "61139"
},
{
"name": "C#",
"bytes": "1461640"
},
{
"name": "C++",
"bytes": "723279"
},
{
"name": "CSS",
"bytes": "2648118"
},
{
"name": "Groff",
"bytes": "15389"
},
{
"name": "HTML",
"bytes": "83875860"
},
{
"name": "Java",
"bytes": "49998455"
},
{
"name": "JavaScript",
"bytes": "39307223"
},
{
"name": "Makefile",
"bytes": "13060"
},
{
"name": "PHP",
"bytes": "4263"
},
{
"name": "PLSQL",
"bytes": "17047"
},
{
"name": "Perl",
"bytes": "2030870"
},
{
"name": "PowerShell",
"bytes": "1485"
},
{
"name": "Python",
"bytes": "129210"
},
{
"name": "Shell",
"bytes": "575209"
},
{
"name": "XSLT",
"bytes": "20635"
}
],
"symlink_target": ""
} |
$(function() {
// Active tab
$("div.custom-tab-menu>div.list-group>a").click(function(e) {
e.preventDefault();
$(this).siblings('a.active').removeClass("active");
$(this).addClass("active");
var index = $(this).index();
$("div.custom-tab>div.custom-tab-content").removeClass("active");
$("div.custom-tab>div.custom-tab-content").eq(index).addClass("active");
});
});
| {
"content_hash": "a9e493cbf38d7f70701cb07e705e460e",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 80,
"avg_line_length": 35.666666666666664,
"alnum_prop": 0.5747663551401869,
"repo_name": "wso2-dev-ux/product-is",
"id": "387f8bcc02fa478a605f7b07dce62a65db097499",
"size": "1084",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Markup/QSG-samples/SSO/pickUp/js/swift.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "536952"
},
{
"name": "HTML",
"bytes": "90947"
},
{
"name": "JavaScript",
"bytes": "93589"
}
],
"symlink_target": ""
} |
<?php
include("../includes/head.php");
include("../includes/menu.php");
?>
<?php
$error = "";
$success = "";
if (isset($_POST["boton"])){
$Nombre = $_POST["Nombre"];
$Direccion = $_POST["Direccion"];
$Dpi = $_POST["Dpi"];
$FechaNacimiento = $_POST["FechaNacimiento"];
$Pais = $_POST["Pais"];
$Departamento = $_POST["Departamento"];
$EstadoCivil = $_POST["EstadoCivil"];
$Genero = $_POST["Genero"];
$Correo = $_POST["Correo"];
$Clave = "23";
$Estatus = "A";
$Aseguradora = $_POST["Aseguradora"];
$Poliza = $_POST["Poliza"];
$Poliza_Expiracion = $_POST["Poliza_Expiracion"];
$Poliza_Certificado = $_POST["Poliza_Certificado"];
if ($Poliza_Expiracion == ""){
$Poliza_Expiracion = "1900-01-01";
}
$Poliza_Observacion = $_POST["Poliza_Observacion"];
$stmt = $db->prepare("select ifnull(max(id),0)+1 as id from paciente where corporacion = ?;");
$stmt->bind_param('i', $USER_CORPORATION);
$stmt->execute();
$result = $stmt->get_result();
$rowArray = mysqli_fetch_array($result);
$Id = $rowArray["id"];
$qry = "insert into paciente (fecharegistro, corporacion, id, nombre, direccion, dpi, fechanacimiento, pais, departamento, estado_civil, correo, clave, genero, estatus, aseguradora, poliza, poliza_expiracion, poliza_certificado, poliza_observacion) " .
" values (curdate(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); ";
$stmt = $db->prepare($qry);
$stmt->bind_param('iissssiiissisissss', $USER_CORPORATION, $Id, $Nombre, $Direccion, $Dpi, $FechaNacimiento, $Pais, $Departamento, $EstadoCivil, $Correo, $Clave, $Genero, $Estatus, $Aseguradora, $Poliza, $Poliza_Expiracion, $Poliza_Certificado, $Poliza_Observacion);
$rc = $stmt->execute();
if (!$rc) {
$typeError = "error";
$textError = "NO se pudo guardar el registro. Error: " . $stmt->error;
}else{
$typeError = "success";
$textError = "Información ha sido guardada exitosamente.";
}
}
?>
<div class="container" style="padding-bottom: 30px;">
<?php
if ($typeError){
alert($typeError, $textError);
}
?>
<div class="row">
<div class="twelve columns">
<div class="box_c">
<div class="box_c_heading cf">
<p>Nuevo Paciente</p>
</div>
<div class="box_c_content form_a">
<div class="tab_pane" style="">
<form action="" method="post" class="nice custom" style="">
<div class="formRow">
<label for="nice_text_oversized">Nombre</label>
<input type="text" required id="Nombre" name="Nombre" required class="input-text large">
</div>
<div class="formRow">
<label for="nice_text_medium">Dirección</label>
<textarea name="Direccion" id="Direccion" required cols="1" rows="1" class="large"></textarea>
</div>
<div class="formRow">
<label for="nice_text_oversized">DPI</label>
<input type="text" required id="Dpi" name="Dpi" required class="input-text large">
</div>
<div class="formRow">
<label for="nice_text_oversized">Fecha de Nacimiento</label>
<input type="date" required id="FechaNacimiento" name="FechaNacimiento" required class="input-text medium">
</div>
<div class="formRow">
<label for="nice_text_oversized">Pais de Nacimiento</label>
<select id="Pais" name="Pais" class="custom dropdown medium" >
<?php newSelector("pais", "id", "descripcion", " where estatus = 'A'", ""); ?>
</select>
</div>
<div class="formRow">
<label for="nice_text_oversized">Departamento de Nacimiento</label>
<select id="Departamento" name="Departamento" class="custom dropdown medium" >
</select>
<script type="text/javascript">
$(document).on("ready", function(){
$("#Pais").on("change", function(){
$("#Departamento").empty();
$.post("../ws/departamentos.php", {
pais: $("#Pais").val()
}, function(data){
if (data == null)
return;
console.log(data);
$.each(data, function( key, value ) {
console.log(key);
console.log(value);
$('#Departamento')
.append($("<option></option>")
.attr("value",value.id)
.text(value.descripcion));
});
}, "json");
});
$("#Pais").change();
});
</script>
</div>
<div class="formRow">
<label for="nice_text_oversized">Estado Civil</label>
<select id="EstadoCivil" name="EstadoCivil" class="custom dropdown medium" >
<?php newSelector("estado_civil", "id", "descripcion", " where estatus = 'A' and corporacion = " . $USER_CORPORATION, ""); ?>
</select>
</div>
<div class="formRow">
<label for="nice_text_oversized">Genero</label>
<select id="Genero" name="Genero" class="custom dropdown medium" >
<?php newSelector("genero", "id", "descripcion", " where estatus = 'A' and corporacion = " . $USER_CORPORATION, ""); ?>
</select>
</div>
<div class="formRow">
<label for="nice_text_oversized">Aseguradora</label>
<select id="Aseguradora" name="Aseguradora" class="custom dropdown medium" >
<?php newSelector("aseguradora", "id", "nombre", " where estatus = 'A' and corporacion = " . $USER_CORPORATION, ""); ?>
</select>
<script type="text/javascript">
$(document).on("ready", function(){
$("#Aseguradora").on("change", function(){
if ($("#Aseguradora option:selected").index()!= 0){
$("#datos_poliza").slideDown("fast");
}else{
$("#datos_poliza").slideUp("fast");
$("#datos_poliza").find("#Poliza").val('');
$("#datos_poliza").find("#Poliza_Expiracion").val('');
$("#datos_poliza").find("#Poliza_Certificado").val('');
$("#datos_poliza").find("#Poliza_Observacion").val('');
}
});
});
</script>
</div>
<div id="datos_poliza" style="display:none;">
<div class="box_c_heading cf">
<p>Datos de la Poliza</p>
</div>
<div class="formRow">
<label for="nice_text_oversized"># Poliza</label>
<input type="text" id="Poliza" name="Poliza" class="input-text large">
</div>
<div class="formRow">
<label for="nice_text_oversized">Fecha de Expiracion de la Poliza</label>
<input type="date" id="Poliza_Expiracion" name="Poliza_Expiracion" class="input-text large">
</div>
<div class="formRow">
<label for="nice_text_oversized">Certificado de la Poliza</label>
<input type="text" id="Poliza_Certificado" name="Poliza_Certificado" class="input-text large">
</div>
<div class="formRow">
<label for="nice_text_medium">Observación de la Póliza</label>
<textarea name="Poliza_Observacion" id="Poliza_Observacion" cols="1" rows="1" class="large"></textarea>
</div>
</div>
<div class="formRow">
<label for="nice_text_oversized">Correo Electrónico</label>
<input type="email" id="Correo" name="Correo" required class="input-text large">
</div>
<div class="formRow">
<button type="submit" name="boton" class="button small nice blue radius">Guardar</button>
<a href="index.php" class="clear_form">Cancelar</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
include("../includes/footer.php");
?> | {
"content_hash": "098182acd2481c6c8f1b035338a6aaf3",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 268,
"avg_line_length": 40.12,
"alnum_prop": 0.5398803589232303,
"repo_name": "wariosolis/UMG",
"id": "3ed4fc61709cc52b2287cfc44a5ef6c1f51e08bc",
"size": "8024",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wario/app/pacientes/new.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "273259"
},
{
"name": "Java",
"bytes": "21819"
},
{
"name": "JavaScript",
"bytes": "84133"
},
{
"name": "PHP",
"bytes": "449363"
}
],
"symlink_target": ""
} |
letter-fighter
==============
A fighter game with letter elements. Flixel project
| {
"content_hash": "f5d6d9a7e49eb9933e93e25e85090529",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 51,
"avg_line_length": 20.75,
"alnum_prop": 0.6746987951807228,
"repo_name": "kaleidosgu/letter-fighter",
"id": "60f3490e9cc165a2b14d04ff38aeec5388a89c2c",
"size": "83",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "492384"
},
{
"name": "Shell",
"bytes": "3212"
}
],
"symlink_target": ""
} |
title: "Processing ERB files with Rails Webpacker"
path: /posts/processing-erb-files-with-rails-webpacker
author: Dwight Watson
date: 2017-07-20
tags: ["ruby on rails"]
---
When using Webpacker you may want to interpolate some values into your assets. For example, API keys are best to come from the deployment environment rather than being hard-coded into your assets. With Webpacker this is really easy, you can just append `.erb` to your scripts and import it.
First, import the script that requires processing including the `.erb` suffix.
```js
import './api.js.erb';
```
Then just include your embedded Ruby as you would usually.
```js
export default new ApiClient({
apiKey: '<%= ENV['API_CLIENT_KEY'] %>'
});
```
| {
"content_hash": "9f65aa631a174dd8eecb00fd6b818dbb",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 290,
"avg_line_length": 34,
"alnum_prop": 0.7205882352941176,
"repo_name": "dwightwatson/neontsunami",
"id": "d351cbed39aa233dd838972f7c3b93f72bcf175f",
"size": "753",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/markdown/134-processing-erb-files-with-rails-webpacker.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2562"
},
{
"name": "JavaScript",
"bytes": "15421"
}
],
"symlink_target": ""
} |
<!--
- Copyright 1999-2011 Alibaba Group.
-
- 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.alibaba</groupId>
<artifactId>dubbo-remoting</artifactId>
<version>2.4.9</version>
</parent>
<artifactId>dubbo-remoting-zookeeper</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>The zookeeper remoting module of dubbo project</description>
<properties>
<skip_maven_deploy>true</skip_maven_deploy>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo-common</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
</dependency>
<dependency>
<groupId>com.netflix.curator</groupId>
<artifactId>curator-framework</artifactId>
</dependency>
</dependencies>
</project> | {
"content_hash": "44a7829bbad5b94228d8b8beeec7f40d",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 104,
"avg_line_length": 36.68,
"alnum_prop": 0.7082878953107961,
"repo_name": "wupengyu/dubbo-router",
"id": "2f91cd93e1f325017880e1eb580f643e4b0af4c8",
"size": "1834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dubbo-remoting/dubbo-remoting-zookeeper/pom.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7731"
},
{
"name": "CSS",
"bytes": "18582"
},
{
"name": "Java",
"bytes": "4569815"
},
{
"name": "JavaScript",
"bytes": "63148"
},
{
"name": "Lex",
"bytes": "4154"
},
{
"name": "Shell",
"bytes": "39642"
},
{
"name": "Thrift",
"bytes": "668"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/personalize/Personalize_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Personalize
{
namespace Model
{
/**
* <p>Provides a summary of the properties of a campaign. For a complete listing,
* call the <a
* href="https://docs.aws.amazon.com/personalize/latest/dg/API_DescribeCampaign.html">DescribeCampaign</a>
* API.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/CampaignSummary">AWS
* API Reference</a></p>
*/
class AWS_PERSONALIZE_API CampaignSummary
{
public:
CampaignSummary();
CampaignSummary(Aws::Utils::Json::JsonView jsonValue);
CampaignSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the campaign.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The name of the campaign.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>The name of the campaign.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the campaign.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The name of the campaign.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The name of the campaign.</p>
*/
inline CampaignSummary& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The name of the campaign.</p>
*/
inline CampaignSummary& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The name of the campaign.</p>
*/
inline CampaignSummary& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline const Aws::String& GetCampaignArn() const{ return m_campaignArn; }
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline bool CampaignArnHasBeenSet() const { return m_campaignArnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline void SetCampaignArn(const Aws::String& value) { m_campaignArnHasBeenSet = true; m_campaignArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline void SetCampaignArn(Aws::String&& value) { m_campaignArnHasBeenSet = true; m_campaignArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline void SetCampaignArn(const char* value) { m_campaignArnHasBeenSet = true; m_campaignArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline CampaignSummary& WithCampaignArn(const Aws::String& value) { SetCampaignArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline CampaignSummary& WithCampaignArn(Aws::String&& value) { SetCampaignArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the campaign.</p>
*/
inline CampaignSummary& WithCampaignArn(const char* value) { SetCampaignArn(value); return *this;}
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline const Aws::String& GetStatus() const{ return m_status; }
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline void SetStatus(const Aws::String& value) { m_statusHasBeenSet = true; m_status = value; }
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline void SetStatus(Aws::String&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline void SetStatus(const char* value) { m_statusHasBeenSet = true; m_status.assign(value); }
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline CampaignSummary& WithStatus(const Aws::String& value) { SetStatus(value); return *this;}
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline CampaignSummary& WithStatus(Aws::String&& value) { SetStatus(std::move(value)); return *this;}
/**
* <p>The status of the campaign.</p> <p>A campaign can be in one of the following
* states:</p> <ul> <li> <p>CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or-
* CREATE FAILED</p> </li> <li> <p>DELETE PENDING > DELETE IN_PROGRESS</p> </li>
* </ul>
*/
inline CampaignSummary& WithStatus(const char* value) { SetStatus(value); return *this;}
/**
* <p>The date and time (in Unix time) that the campaign was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreationDateTime() const{ return m_creationDateTime; }
/**
* <p>The date and time (in Unix time) that the campaign was created.</p>
*/
inline bool CreationDateTimeHasBeenSet() const { return m_creationDateTimeHasBeenSet; }
/**
* <p>The date and time (in Unix time) that the campaign was created.</p>
*/
inline void SetCreationDateTime(const Aws::Utils::DateTime& value) { m_creationDateTimeHasBeenSet = true; m_creationDateTime = value; }
/**
* <p>The date and time (in Unix time) that the campaign was created.</p>
*/
inline void SetCreationDateTime(Aws::Utils::DateTime&& value) { m_creationDateTimeHasBeenSet = true; m_creationDateTime = std::move(value); }
/**
* <p>The date and time (in Unix time) that the campaign was created.</p>
*/
inline CampaignSummary& WithCreationDateTime(const Aws::Utils::DateTime& value) { SetCreationDateTime(value); return *this;}
/**
* <p>The date and time (in Unix time) that the campaign was created.</p>
*/
inline CampaignSummary& WithCreationDateTime(Aws::Utils::DateTime&& value) { SetCreationDateTime(std::move(value)); return *this;}
/**
* <p>The date and time (in Unix time) that the campaign was last updated.</p>
*/
inline const Aws::Utils::DateTime& GetLastUpdatedDateTime() const{ return m_lastUpdatedDateTime; }
/**
* <p>The date and time (in Unix time) that the campaign was last updated.</p>
*/
inline bool LastUpdatedDateTimeHasBeenSet() const { return m_lastUpdatedDateTimeHasBeenSet; }
/**
* <p>The date and time (in Unix time) that the campaign was last updated.</p>
*/
inline void SetLastUpdatedDateTime(const Aws::Utils::DateTime& value) { m_lastUpdatedDateTimeHasBeenSet = true; m_lastUpdatedDateTime = value; }
/**
* <p>The date and time (in Unix time) that the campaign was last updated.</p>
*/
inline void SetLastUpdatedDateTime(Aws::Utils::DateTime&& value) { m_lastUpdatedDateTimeHasBeenSet = true; m_lastUpdatedDateTime = std::move(value); }
/**
* <p>The date and time (in Unix time) that the campaign was last updated.</p>
*/
inline CampaignSummary& WithLastUpdatedDateTime(const Aws::Utils::DateTime& value) { SetLastUpdatedDateTime(value); return *this;}
/**
* <p>The date and time (in Unix time) that the campaign was last updated.</p>
*/
inline CampaignSummary& WithLastUpdatedDateTime(Aws::Utils::DateTime&& value) { SetLastUpdatedDateTime(std::move(value)); return *this;}
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline const Aws::String& GetFailureReason() const{ return m_failureReason; }
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline bool FailureReasonHasBeenSet() const { return m_failureReasonHasBeenSet; }
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline void SetFailureReason(const Aws::String& value) { m_failureReasonHasBeenSet = true; m_failureReason = value; }
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline void SetFailureReason(Aws::String&& value) { m_failureReasonHasBeenSet = true; m_failureReason = std::move(value); }
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline void SetFailureReason(const char* value) { m_failureReasonHasBeenSet = true; m_failureReason.assign(value); }
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline CampaignSummary& WithFailureReason(const Aws::String& value) { SetFailureReason(value); return *this;}
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline CampaignSummary& WithFailureReason(Aws::String&& value) { SetFailureReason(std::move(value)); return *this;}
/**
* <p>If a campaign fails, the reason behind the failure.</p>
*/
inline CampaignSummary& WithFailureReason(const char* value) { SetFailureReason(value); return *this;}
private:
Aws::String m_name;
bool m_nameHasBeenSet;
Aws::String m_campaignArn;
bool m_campaignArnHasBeenSet;
Aws::String m_status;
bool m_statusHasBeenSet;
Aws::Utils::DateTime m_creationDateTime;
bool m_creationDateTimeHasBeenSet;
Aws::Utils::DateTime m_lastUpdatedDateTime;
bool m_lastUpdatedDateTimeHasBeenSet;
Aws::String m_failureReason;
bool m_failureReasonHasBeenSet;
};
} // namespace Model
} // namespace Personalize
} // namespace Aws
| {
"content_hash": "602655a7ddba7384b1873d3337ddfab7",
"timestamp": "",
"source": "github",
"line_count": 313,
"max_line_length": 154,
"avg_line_length": 36.61341853035144,
"alnum_prop": 0.6421465968586387,
"repo_name": "cedral/aws-sdk-cpp",
"id": "71a82e5000ddbf8d5dd4a541569df1b9b2b81162",
"size": "11579",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-personalize/include/aws/personalize/model/CampaignSummary.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "294220"
},
{
"name": "C++",
"bytes": "428637022"
},
{
"name": "CMake",
"bytes": "862025"
},
{
"name": "Dockerfile",
"bytes": "11688"
},
{
"name": "HTML",
"bytes": "7904"
},
{
"name": "Java",
"bytes": "352201"
},
{
"name": "Python",
"bytes": "106761"
},
{
"name": "Shell",
"bytes": "10891"
}
],
"symlink_target": ""
} |
//************************************************************/
//
// String Utilities Header
//
// Some useful string utilities for Spectrum
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN
// @Date: 13.10.2014
// @Email: gibsjose@mail.gvsu.edu
//
//************************************************************/
#ifndef SPXSTRINGUTILITIES_H
#define SPXSTRINGUTILITIES_H
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include "SPXException.h"
class SPXStringUtilities {
private:
//Class used for RemoveCharacters method
class IsChars
{
public:
IsChars(const char* charsToRemove) : chars(charsToRemove) {};
bool operator()(char c)
{
for(const char* testChar = chars; *testChar != 0; ++testChar)
{
if(*testChar == c) { return true; }
}
return false;
}
private:
const char* chars;
};
public:
//static std::string CompareTwoSTring(std::string firstValue, std::string secondValue);
//static std::string LCSubstr(std::string x, std::string y);
static std::string ReplaceString(std::string org, std::string replacedstring, std::string replacingstring){
std::string fline=org;
fline.replace(fline.find(replacedstring),replacedstring.length(),replacingstring);
//std::cout<<"ReplaceString: org string= "<<org<<" replace string= "<<replacedstring<<" replacing string= "<< replacingstring <<" new string= "<<fline<< std::endl;
return fline;
};
template<typename T>
static T StringToNumber(const std::string& numberAsString) {
T valor;
// Replace D (from Fortran written files) to standard scientific notation
std::string str1=numberAsString;
if (isdigit((int)LeftTrim(str1).at(0)) || LeftTrim(str1).at(0)=='-') {
if (str1.find("D")!=std::string::npos) {
//std::cout<<"Replace old string "<<str1<<std::endl;
str1.replace(numberAsString.find("D"),1,"e");
//std::cout<<"Replace D to E new string "<<str1<<std::endl;
//double valor1=atof(str1.c_str());
//std::cout<<"valor1= "<< std::scientific << valor1 <<std::endl;
}
}
std::stringstream stream(numberAsString);
//std::stringstream stream(str1);
stream >> valor;
if (stream.fail()) {
//throw SPXParseException("Could not convert string " + numberAsString + " to a number");
throw SPXParseException("Could not convert string " + str1 + " to a number");
}
//std::cout<<"valor= "<< std::scientific <<valor<<std::endl;
return valor;
}
template<typename T>
static T GetNumberfromStringVector(std::vector <std::string> names, const std::string& String) {
//
for(int i = 0; i < names.size(); i++) {
// if (TString(names.at(i)).Contains(String)) {
if (names.at(i).find(String) != std::string::npos) {
for(int j = i+1; j < names.size(); j++) {
if (!names.at(j).empty()) {
return StringToNumber<T>(names.at(j));
}
}
}
}
return 0;
}
static bool BeginsWith(std::string &s, std::string &b) {
if(s.find(b) == 0) {
return true;
} else {
return false;
}
}
//Trim LEADING whitespace
static std::string LeftTrim(std::string s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
//Trim TRAILING whitespace
static std::string RightTrim(std::string s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
//Trim all whitespace
static std::string Trim(std::string s) {
return LeftTrim(RightTrim(s));
}
//Removes any of the characters in the 'remove' string from the string s
static std::string RemoveCharacters(std::string s, const std::string &remove) {
s.erase(std::remove_if(s.begin(), s.end(), IsChars(remove.c_str())), s.end());
return s;
}
//Delete's the first occurrance of a substring from a string (if it exists)
static std::string RemoveFirstSubstring(std::string s, const std::string &substring) {
size_t pos = s.find(substring);
if(pos != std::string::npos) {
s.erase(pos, substring.length());
}
return s;
}
static std::string ReplaceAll(std::string s, const std::string &from, const std::string &to) {
size_t start_pos = 0;
while((start_pos = s.find(from, start_pos)) != std::string::npos) {
s.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return s;
}
//First split a string based on a delimiter, and for each token remove the given characters
static std::vector<std::string> SplitStringAndRemoveCharacters(std::string s, const std::string &delimiter, const std::string &remove) {
size_t pos = 0;
std::vector<std::string> tokens;
std::string token;
bool debug = false;
if(debug) std::cout << "s = " << s << ", delimiter = " << delimiter;
while((pos = s.find(delimiter)) != std::string::npos) {
if(debug) std::cout << "Found delimiter at pos = " << pos << std::endl;
token = s.substr(0, pos);
token = RemoveCharacters(token, remove);
tokens.push_back(token);
if(debug) std::cout << "Added token to vector: " << s.substr(0, pos) << std::endl;
s.erase(0, pos + delimiter.length());
if(debug) std::cout << "Erased token and delimiter" << std::endl;
}
if(debug) std::cout << "Adding last token to vector: " << s << std::endl;
token = s;
token = RemoveCharacters(token, remove);
tokens.push_back(token);
return tokens;
}
//Splits a string based on a delimiter string
static std::vector<std::string> SplitString(std::string s, const std::string &delimiter) {
size_t pos = 0;
std::vector<std::string> tokens;
bool debug = false;
if(debug) std::cout << "s = " << s << ", delimiter = " << delimiter;
while((pos = s.find(delimiter)) != std::string::npos) {
if(debug) std::cout << "Found delimiter at pos = " << pos << std::endl;
tokens.push_back(s.substr(0, pos));
if(debug) std::cout << "Added token to vector: " << s.substr(0, pos) << std::endl;
s.erase(0, pos + delimiter.length());
if(debug) std::cout << "Erased token and delimiter" << std::endl;
}
if(debug) std::cout << "Adding last token to vector: " << s << std::endl;
tokens.push_back(s);
return tokens;
}
//Splits a string based on a delimiter string, stopping after 'n' splits
static std::vector<std::string> SplitString(std::string s, const std::string &delimiter, int n) {
size_t pos = 0;
std::vector<std::string> tokens;
unsigned int count = 0;
bool debug = false;
if(debug) std::cout << "s = " << s << ", delimiter = " << delimiter;
while((pos = s.find(delimiter)) != std::string::npos) {
if(count >= n) {
break;
}
if(debug) std::cout << "Found delimiter at pos = " << pos << std::endl;
tokens.push_back(s.substr(0, pos));
if(debug) std::cout << "Added token to vector: " << s.substr(0, pos) << std::endl;
s.erase(0, pos + delimiter.length());
if(debug) std::cout << "Erased token and delimiter" << std::endl;
count++;
}
if(debug) std::cout << "Adding last token to vector: " << s << std::endl;
tokens.push_back(s);
return tokens;
}
static std::string ToUpper(const std::string & s) {
std::string str = s;
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
return str;
}
static unsigned int GetIndexOfStringInVector(std::vector<std::string> v, std::string s) {
unsigned int index = std::find(v.begin(), v.end(), s) - v.begin();
if(index >= v.size()) {
throw SPXGeneralException("SPXStringUtilities::GetIndexOfStringInVector: String not found in vector: Index out of bounds");
} else {
return index;
}
}
static std::vector<std::string> ParseString(std::string rawData, char delimeter) {
std::stringstream lineStream(rawData);
std::string cell;
std::vector<std::string> parsedDataVec;
parsedDataVec.clear();
while(getline(lineStream,cell,delimeter)) {
cell.erase( std::remove(cell.begin(), cell.end(), ' '), cell.end() ); //remove any whitespace
parsedDataVec.push_back(cell);
}
if(parsedDataVec.size()==0) parsedDataVec.push_back(rawData);
return parsedDataVec;
}
static std::vector<double> ParseStringToDoubleVector(std::string rawData, char delimiter) {
std::vector<double> dVector;
std::stringstream lineStream(rawData);
std::string cell;
dVector.clear();
while(getline(lineStream, cell, delimiter)) {
//Remove whitespace
cell = Trim(cell);
//Skip if cell is empty
if(!cell.empty()) {
try {
double val = StringToNumber<double>(cell);
//dVector.push_back((double)atof(cell.c_str()));
dVector.push_back(val);
//std::cout<<" val= "<<std::scientific <<val<<" vec= "<<dVector.back()<<std::endl;
} catch(const SPXException &e) {
throw;
}
}
}
return dVector;
}
static std::vector<bool> ParseStringToBooleanVector(std::string rawData, char delimiter) {
std::vector<bool> dVector;
std::stringstream lineStream(rawData);
std::string cell;
dVector.clear();
while(getline(lineStream, cell, delimiter)) {
//Remove whitespace
cell = Trim(cell);
//Skip if cell is empty
if(!cell.empty()) {
try {
std::transform(cell.begin(), cell.end(), cell.begin(), ::tolower);
bool val=false;
if (cell == "true" || cell == "yes" || cell == "on" || cell == "1")
val=true;
else if (cell == "false" || cell == "no" || cell == "off" || cell == "0")
val=false;
dVector.push_back(val);
} catch(const SPXException &e) {
throw;
}
}
}
return dVector;
}
static std::vector<std::string> CommaSeparatedListToVector(const std::string &csl) {
return ParseString(csl, ',');
}
static std::string VectorToCommaSeparatedList(std::vector<std::string> &v) {
std::string csl;
csl.clear();
for(std::vector<std::string>::iterator it = v.begin(); it != v.end(); ++it) {
csl += *it;
if((it + 1) != v.end()) {
csl += ", ";
}
}
return csl;
}
};
template<typename T> static T GetStringfromVector(std::vector <std::string> names, const std::string& String);
#endif
| {
"content_hash": "163cd696f6f44252c671769c8691a47e",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 165,
"avg_line_length": 29.4985835694051,
"alnum_prop": 0.6085662153077883,
"repo_name": "gibsjose/Spectrum",
"id": "c037446fc3674c33e8fca7279d9b09a8c3866dd8",
"size": "10413",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SPXStringUtilities.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7608"
},
{
"name": "C++",
"bytes": "1149535"
},
{
"name": "Makefile",
"bytes": "2956"
},
{
"name": "Python",
"bytes": "21576"
},
{
"name": "Shell",
"bytes": "16124"
}
],
"symlink_target": ""
} |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Equivalent to the expression RegExp.prototype.exec(string) != null
es5id: 15.10.6.3_A1_T13
description: RegExp is /t[a-b|q-s]/ and tested string is true
---*/
var __string = true;
__re = /t[a-b|q-s]/;
//CHECK#0
if (__re.test(__string) !== (__re.exec(__string) !== null)) {
$ERROR('#0: var __string = true;__re = /t[a-b|q-s]/; __re.test(__string) === (__re.exec(__string) !== null)');
}
| {
"content_hash": "5517c7b758b06d1af682e1879a32dd4d",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 111,
"avg_line_length": 33.375,
"alnum_prop": 0.6179775280898876,
"repo_name": "PiotrDabkowski/Js2Py",
"id": "5a2dd8994003b33d1dc59acadb5a7ec33f2ce66e",
"size": "534",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_cases/built-ins/RegExp/prototype/test/S15.10.6.3_A1_T13.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "289"
},
{
"name": "JavaScript",
"bytes": "8556970"
},
{
"name": "Python",
"bytes": "4583980"
},
{
"name": "Shell",
"bytes": "457"
}
],
"symlink_target": ""
} |
module avam.menu {
angular.module('avam-menu', ["ngAnimate"]);
} | {
"content_hash": "b01e8f7319f2b2626fed59041a37a7a0",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 47,
"avg_line_length": 22.666666666666668,
"alnum_prop": 0.6470588235294118,
"repo_name": "vickykatoch/avam-web",
"id": "d5e41c30e838d22ad83d13e435d2d7d7145db532",
"size": "116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/avam-menu/avamMenu.module.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5276"
},
{
"name": "HTML",
"bytes": "5910"
},
{
"name": "JavaScript",
"bytes": "35202"
},
{
"name": "TypeScript",
"bytes": "11570"
}
],
"symlink_target": ""
} |
package models.daos.slick
import javax.inject
import models.User
import models.MessageModels._
import models.daos.slick.DBTableDefinitions._
import play.api.db.slick._
import play.api.db.slick.Config.driver.simple._
import models.daos.slick.DBAuthTableDefinitions._
import com.mohiva.play.silhouette.api.LoginInfo
import scala.concurrent.Future
import java.util.UUID
import play.Logger
import play.api.libs.json.Json
import models.daos.slick.DBAuthTableDefinitions.DBUser
import play.api.libs.json._
import play.api.libs.functional.syntax._
/**
* Created by mehdi on 6/3/15.
*/
class MessagesDAO {
import play.api.Play.current
def all(sessionId: UUID, drop: Int, take: Int) = {
DB.withSession { implicit s =>
val q = for {
m <- slickMessages if m.sessionId === sessionId
u <- slickUsers if m.authorId === u.id
} yield (m.id, m.content, m.creationDate, u)
q.drop(drop).take(take).list.map(m =>
MessageWithAuthor(m._1, m._2, m._3, m._4)
)
}
}
def find(messageId: UUID) = {
DB.withSession { implicit s =>
slickSessions.filter(_.id === messageId).firstOption
}
}
} | {
"content_hash": "f7c20f2ca8aad0fb2739933c5efcdd81",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 58,
"avg_line_length": 24.53191489361702,
"alnum_prop": 0.6895056374674762,
"repo_name": "meedi/session-montpellier",
"id": "2062424543b32750eeefe82a8d9dd5a0c8241cb3",
"size": "1153",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/models/daos/slick/MessagesDAO.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "150808"
},
{
"name": "HTML",
"bytes": "10037"
},
{
"name": "JavaScript",
"bytes": "24318"
},
{
"name": "Scala",
"bytes": "38355"
}
],
"symlink_target": ""
} |
// ------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------
namespace Amqp
{
using System;
using System.Threading;
using Amqp.Framing;
/// <summary>
/// The SenderLink represents a link that sends outgoing messages.
/// </summary>
public partial class SenderLink : Link
{
// flow control
SequenceNumber deliveryCount;
int credit;
// outgoing queue
SenderSettleMode settleMode;
LinkedList outgoingList;
bool writing;
/// <summary>
/// Initializes a sender link.
/// </summary>
/// <param name="session">The session within which to create the link.</param>
/// <param name="name">The link name.</param>
/// <param name="address">The node address.</param>
public SenderLink(Session session, string name, string address)
: this(session, name, new Target() { Address = address }, null)
{
}
/// <summary>
/// Initializes a sender link.
/// </summary>
/// <param name="session">The session within which to create the link.</param>
/// <param name="name">The link name.</param>
/// <param name="target">The target on attach that specifies the message target.</param>
/// <param name="onAttached">The callback to invoke when an attach is received from peer.</param>
public SenderLink(Session session, string name, Target target, OnAttached onAttached)
: this(session, name, new Attach() { Source = new Source(), Target = target }, onAttached)
{
}
/// <summary>
/// Initializes a sender link.
/// </summary>
/// <param name="session">The session within which to create the link.</param>
/// <param name="name">The link name.</param>
/// <param name="attach">The attach frame to send for this link.</param>
/// <param name="onAttached">The callback to invoke when an attach is received from peer.</param>
public SenderLink(Session session, string name, Attach attach, OnAttached onAttached)
: base(session, name, onAttached)
{
this.settleMode = attach.SndSettleMode;
this.outgoingList = new LinkedList();
this.SendAttach(false, this.deliveryCount, attach);
}
/// <summary>
/// Sends a message and synchronously waits for an acknowledgement. Throws
/// TimeoutException if ack is not received in 60 seconds.
/// </summary>
/// <param name="message">The message to send.</param>
public void Send(Message message)
{
this.SendInternal(message, AmqpObject.DefaultTimeout);
}
/// <summary>
/// Sends a message and synchronously waits for an acknowledgement. Throws
/// TimeoutException if ack is not received in the specified time.
/// </summary>
/// <param name="message">The message to send.</param>
/// <param name="timeout">The time to wait for the acknowledgement.</param>
public void Send(Message message, TimeSpan timeout)
{
this.SendInternal(message, (int)(timeout.Ticks / 10000));
}
void SendInternal(Message message, int waitMilliseconds)
{
ManualResetEvent acked = new ManualResetEvent(false);
Outcome outcome = null;
OutcomeCallback callback = (l, m, o, s) =>
{
outcome = o;
acked.Set();
};
this.Send(message, callback, acked);
bool signaled = acked.WaitOne(waitMilliseconds);
if (!signaled)
{
this.OnTimeout(message);
throw new TimeoutException(Fx.Format(SRAmqp.AmqpTimeout, "send", waitMilliseconds, "message"));
}
if (outcome != null)
{
if (outcome.Descriptor.Code == Codec.Released.Code)
{
Released released = (Released)outcome;
throw new AmqpException(ErrorCode.MessageReleased, null);
}
else if (outcome.Descriptor.Code == Codec.Rejected.Code)
{
Rejected rejected = (Rejected)outcome;
throw new AmqpException(rejected.Error);
}
}
}
/// <summary>
/// Sends a message asynchronously. If callback is null, the message is sent without
/// requesting for an acknowledgement (best effort).
/// </summary>
/// <param name="message">The message to send.</param>
/// <param name="callback">The callback to invoke when acknowledgement is received.</param>
/// <param name="state">The object that is passed back to the outcome callback.</param>
public void Send(Message message, OutcomeCallback callback, object state)
{
DeliveryState deliveryState = null;
#if NETFX || NETFX40
deliveryState = Amqp.Transactions.ResourceManager.GetTransactionalStateAsync(this).Result;
#endif
this.Send(message, deliveryState, callback, state);
}
/// <summary>
/// Sends a message asynchronously. If callback is null, the message is sent without
/// requesting for an acknowledgement (best effort). This method is not transaction aware. If you need transaction support,
/// use <see cref="Send(Amqp.Message,Amqp.OutcomeCallback,object)"/>.
/// </summary>
/// <param name="message">The message to send.</param>
/// <param name="deliveryState">The transactional state of the message. If null, no transaction is used.</param>
/// <param name="callback">The callback to invoke when acknowledgement is received.</param>
/// <param name="state">The object that is passed back to the outcome callback.</param>
public void Send(Message message, DeliveryState deliveryState, OutcomeCallback callback, object state)
{
const int reservedBytes = 40;
#if NETFX || NETFX40 || DOTNET
var buffer = message.Encode(this.Session.Connection.BufferManager, reservedBytes);
#else
var buffer = message.Encode(reservedBytes);
#endif
if (buffer.Length < 1)
{
throw new ArgumentException("Cannot send an empty message.");
}
Delivery delivery = new Delivery()
{
Message = message,
Buffer = buffer,
ReservedBufferSize = reservedBytes,
State = deliveryState,
Link = this,
OnOutcome = callback,
UserToken = state,
Settled = this.settleMode == SenderSettleMode.Settled || callback == null
};
lock (this.ThisLock)
{
this.ThrowIfDetaching("Send");
if (this.credit <= 0 || this.writing)
{
this.outgoingList.Add(delivery);
return;
}
delivery.Tag = Delivery.GetDeliveryTag(this.deliveryCount);
this.credit--;
this.deliveryCount++;
this.writing = true;
}
this.WriteDelivery(delivery);
}
void OnTimeout(Message message)
{
lock (this.ThisLock)
{
this.outgoingList.Remove(message.Delivery);
}
if (message.Delivery.BytesTransfered > 0)
{
this.Session.DisposeDelivery(false, message.Delivery, new Released(), true);
}
}
internal override void OnFlow(Flow flow)
{
Delivery delivery = null;
lock (this.ThisLock)
{
this.credit = (flow.DeliveryCount + flow.LinkCredit) - this.deliveryCount;
if (this.writing || this.credit <= 0 || this.outgoingList.First == null)
{
return;
}
delivery = (Delivery)this.outgoingList.First;
this.outgoingList.Remove(delivery);
delivery.Tag = Delivery.GetDeliveryTag(this.deliveryCount);
this.credit--;
this.deliveryCount++;
this.writing = true;
}
this.WriteDelivery(delivery);
}
internal override void OnTransfer(Delivery delivery, Transfer transfer, ByteBuffer buffer)
{
throw new InvalidOperationException();
}
internal override void OnDeliveryStateChanged(Delivery delivery)
{
// some broker may not settle the message when sending dispositions
if (!delivery.Settled)
{
this.Session.DisposeDelivery(false, delivery, delivery.State, true);
}
if (delivery.OnOutcome != null)
{
Outcome outcome = delivery.State as Outcome;
#if NETFX || NETFX40 || DOTNET
if (delivery.State != null && delivery.State is Amqp.Transactions.TransactionalState)
{
outcome = ((Amqp.Transactions.TransactionalState)delivery.State).Outcome;
}
#endif
delivery.OnOutcome(this, delivery.Message, outcome, delivery.UserToken);
}
}
/// <summary>
/// Closes the sender link.
/// </summary>
/// <param name="error">The error for the closure.</param>
/// <returns></returns>
protected override bool OnClose(Error error)
{
lock (this.ThisLock)
{
bool wait = this.writing || (this.credit == 0 && this.outgoingList.First != null);
if (this.CloseCalled && wait && !this.Session.IsClosed)
{
return false;
}
}
this.OnAbort(error);
return base.OnClose(error);
}
/// <summary>
/// Aborts the sender link.
/// </summary>
/// <param name="error">The error for the abort.</param>
protected override void OnAbort(Error error)
{
Delivery toRelease;
lock (this.ThisLock)
{
toRelease = (Delivery)this.outgoingList.Clear();
}
Delivery.ReleaseAll(toRelease, error);
Delivery.ReleaseAll(this.Session.RemoveDeliveries(this), error);
}
void WriteDelivery(Delivery delivery)
{
while (delivery != null)
{
delivery.Handle = this.Handle;
try
{
bool settled = delivery.Settled;
this.Session.SendDelivery(delivery);
if (settled && delivery.OnOutcome != null)
{
delivery.OnOutcome(this, delivery.Message, new Accepted(), delivery.UserToken);
}
}
catch
{
lock (this.ThisLock)
{
this.writing = false;
}
throw;
}
bool shouldClose = false;
lock (this.ThisLock)
{
delivery = (Delivery)this.outgoingList.First;
if (delivery == null || this.credit == 0)
{
shouldClose = this.CloseCalled;
delivery = null;
this.writing = false;
}
else if (this.credit > 0)
{
this.outgoingList.Remove(delivery);
delivery.Tag = Delivery.GetDeliveryTag(this.deliveryCount);
this.credit--;
this.deliveryCount++;
}
}
if (shouldClose)
{
Error error = this.Error;
this.OnAbort(error);
if (base.OnClose(error))
{
this.NotifyClosed(error);
}
}
}
}
}
} | {
"content_hash": "2728cce3452a81ce9079bf92b2b257a0",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 131,
"avg_line_length": 37.62889518413598,
"alnum_prop": 0.5281939320936535,
"repo_name": "ChugR/amqpnetlite",
"id": "00c86394d7c8f9356ad3ea784ea02af5ff63518f",
"size": "13285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SenderLink.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7439"
},
{
"name": "C#",
"bytes": "1300421"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18010
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Thinktecture.IdentityServer.Web.Areas.Admin.App_LocalResources.Shared.EditorTemplates
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Object_cshtml {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Object_cshtml() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Thinktecture.IdentityServer.Web.Areas.Admin.App_LocalResources.Shared.EditorTempl" +
"ates.Object.cshtml", typeof(Object_cshtml).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| {
"content_hash": "c97152e773461a12cf0d97511abe36b0",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 198,
"avg_line_length": 46.75,
"alnum_prop": 0.6066176470588235,
"repo_name": "OBHITA/PROCenter",
"id": "9a03ca5c7c35e59274475c1587e494e40245f852",
"size": "2994",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IdentityServer/src/OnPremise/WebSite/Areas/Admin/App_LocalResources/Shared/EditorTemplates/Object.cshtml.Designer.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "5171"
},
{
"name": "Batchfile",
"bytes": "8423"
},
{
"name": "C#",
"bytes": "5709857"
},
{
"name": "CSS",
"bytes": "6068607"
},
{
"name": "CoffeeScript",
"bytes": "808"
},
{
"name": "HTML",
"bytes": "2093418"
},
{
"name": "JavaScript",
"bytes": "4650209"
},
{
"name": "PHP",
"bytes": "611"
},
{
"name": "PowerShell",
"bytes": "188034"
},
{
"name": "Ruby",
"bytes": "25242"
}
],
"symlink_target": ""
} |
package br.senac.tads.pi3.uriel.exercicio01;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;
/**
*
* @author uriel.pgoliveira
*/
public class exercicios01 {
private Connection obterConexao() throws SQLException, ClassNotFoundException {
Connection conn = null;
// Passo 1: Registrar driver JDBC.
Class.forName("org.apache.derby.jdbc.ClientDataSource");
// Passo 2: Abrir a conexão
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/agendabd;SecurityMechanism=3",
"app", // usuario
"app"); // senha
return conn;
}
public static Scanner teclado = new Scanner(System.in);
/* String connectionUrl = "jdbc:sqlserver://localhost:1433;\" +\n"
+ " \"databaseName=db1;user=usuarioDB;password=1234";*/
public void cadastro(){
PreparedStatement ps = null;
Connection conn = null;
String nome,email,telefone,dataNasct;
System.out.println("Digite seu nome: ");
nome = teclado.nextLine();
teclado.next();
System.out.println("Digite seu email: ");
email = teclado.nextLine();
teclado.next();
System.out.println("Digite seu telefone: ");
telefone = teclado.nextLine();
teclado.next();
System.out.println("Digite a data de nascimento (DD/MM/AA): ");
dataNasct = teclado.nextLine();
teclado.next();
try {
conn = obterConexao();
ps = conn.prepareStatement("INSERT INTO TB_PESSOA (NM_PESSOA, DT_NASCIMENTO, VL_TELEFONE, VL_EMAIL) VALUES (?, ?, ?, ?)");
ps.setString(1, nome);
ps.setString(2, email);
ps.setString(3, telefone);
ps.setString(4, dataNasct);
//stmt.setDate(5, new java.sql.Date(System.currentTimeMillis()));
ps.executeUpdate();
System.out.println("Registro incluido com sucesso.");
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
if (ps != null) {
try
{
ps.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void modificar(){
PreparedStatement ps = null;
Connection conn = null;
String nome,email,telefone,dataNasct;
System.out.println("Digite os dados a serem atualizados: \n");
System.out.println("Digite o Id com dados a serem atualizados: ");
int id = teclado.nextInt();
System.out.println("Digite seu nome: ");
nome = teclado.nextLine();
teclado.next();
System.out.println("Digite seu email: ");
email = teclado.nextLine();
teclado.next();
System.out.println("Digite seu telefone: ");
telefone = teclado.nextLine();
teclado.next();
System.out.println("Digite a data de nascimento (DD/MM/AA): ");
dataNasct = teclado.nextLine();
teclado.next();
try {//(NM_PESSOA, DT_NASCIMENTO, VL_TELEFONE, VL_EMAIL) VALUES (?, ?, ?, ?, ?)
conn = obterConexao();
ps = conn.prepareStatement("UPDA ENTO = ?, VL_TELEFONE = ?, VL_EMAIL=? WHERE ID_PESSOA = ?");
ps.setString(1, nome);
ps.setString(2, email);
ps.setString(3, telefone);
ps.setString(4, dataNasct);
ps.setInt(5, id);
ps.executeUpdate();
System.out.println("Registro atualizado com sucesso.");
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
if (ps != null) {
try
{
ps.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void excluir(){
PreparedStatement ps = null;
Connection conn = null;
System.out.println("Digite o Id com dados a ser deletado: ");
int id = teclado.nextInt();
byte opcao;
System.out.println("Tem certeza?\n" +
"Digite 1 para 'sim', 2 para 'não' e 3 para voltar");
opcao = teclado.nextByte();
if (opcao==1){
try {//(NM_PESSOA, DT_NASCIMENTO, VL_TELEFONE, VL_EMAIL) VALUES (?, ?, ?, ?, ?)
conn = obterConexao();
ps = conn.prepareStatement("DELETE * FROM TB_PESSOA WHERE ID_PESSOA = ?");
ps.setInt(1, id);
ps.executeUpdate();
System.out.println("Registro atualizado com sucesso.\n");
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
if (ps != null) {
try
{
ps.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
else if (opcao==2){
System.out.println("");
}
else {
System.out.println("Opção inválida");
}
}
public void listagem(){
Statement s = null;
Connection conn = null;
try {
conn = obterConexao();
s = conn.createStatement();
ResultSet resultados = s.executeQuery("SELECT ID_PESSOA, NM_PESSOA, DT_NASCIMENTO, VL_TELEFONE, VL_EMAIL FROM TB_PESSOA");
DateFormat formatadorData = new SimpleDateFormat("dd/MM/yyyy");
while (resultados.next()) {
Long id = resultados.getLong("ID_PESSOA");
String nome = resultados.getString("NM_PESSOA");
String dataNasct = resultados.getString("DT_NASCIMENTO");
String email = resultados.getString("VL_EMAIL");
String telefone = resultados.getString("VL_TELEFONE");
System.out.println(String.valueOf(id) + ", " + nome + ", " + dataNasct + ", " + email + ", " + telefone);
}
} catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
if (s != null) {
try
{
s.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException ex)
{
Logger.getLogger(exercicios01.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void main(String args[]){
byte cod=0;
exercicios01 app = new exercicios01();
/*
String connectionUrl = "jdbc:sqlserver://192.168.0.1:1433;databaseName=bd1;user=usuario;password=senha";
*/
do {
System.out.println("Bem vindo ao sistema de cadastro!\n"
+ "Digite 1 para cadastrar\n"
+ "Digite 2 para listar\n"
+ "Digite 3 para sair\n");
cod = teclado.nextByte();
if (cod==1)
{
app.cadastro();
}
else if (cod==2)
{
}
} while(cod!=3);
}
}
| {
"content_hash": "297c1be19a8c5c891ad174ac21ce8dec",
"timestamp": "",
"source": "github",
"line_count": 340,
"max_line_length": 142,
"avg_line_length": 33.088235294117645,
"alnum_prop": 0.44177777777777777,
"repo_name": "Morthanc/exercicio01",
"id": "42dc6df05fa83e83cbf24c51f01bf5b617f9d70c",
"size": "11255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/br/senac/tads/pi3/uriel/exercicio01/exercicios01.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "11255"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<hsdoc version="1.1.0">
<info cname="系统公用"/>
<extendMap>
<entity>
<key>CresModuleExtendProperty</key>
<value><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<cresextend:CresMoudleExtendProperty xmlns:cresextend="http://www.hundsun.com/ares/studio/cres/extend/1.0.0" subSysID="3" dataBaseName="USERDB"/>
]]></value>
</entity>
</extendMap>
</hsdoc>
| {
"content_hash": "822a6518af79c2e7b636de05d82bae08",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 145,
"avg_line_length": 31.76923076923077,
"alnum_prop": 0.6585956416464891,
"repo_name": "hundsun/uf-base",
"id": "9691d431312e5dbab504921323cd778d25593378",
"size": "421",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Demo4CRES/atom/demopub/module.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "420343"
}
],
"symlink_target": ""
} |
import { HtmlAst } from './html_ast';
export declare class HtmlParser {
parse(template: string, sourceInfo: string): HtmlAst[];
unparse(nodes: HtmlAst[]): string;
}
| {
"content_hash": "4efc8c6a2b49f9c61b5d8cbbd831c6c2",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 59,
"avg_line_length": 35.6,
"alnum_prop": 0.6685393258426966,
"repo_name": "hilts-vaughan/webrtc-components",
"id": "62b1a37aa5e0a1e4cb0c0ee5ba8400ccbb6b15d7",
"size": "178",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "client/node_modules/angular2/src/core/compiler/html_parser.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3203"
},
{
"name": "HTML",
"bytes": "6202"
},
{
"name": "JavaScript",
"bytes": "1918073"
},
{
"name": "TypeScript",
"bytes": "45654"
}
],
"symlink_target": ""
} |
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.UI.Controls;
using SharpDX.XInput;
using System;
using Windows.UI.Xaml;
namespace XInputHelper
{
// Usage:
// Add namespace using
// xmlns:xinput="using:XInputHelper"
//
// Add inside SceneView:
// <xinput:XInputSceneController.Controller>
// <xinput:XInputSceneController />
// </xinput:XInputSceneController.Controller>
//
//
//
//
//
//
//
public class XInputSceneController
{
private SceneView sceneView;
private DispatcherTimer timer;
private SharpDX.XInput.Controller controller;
private bool relativeToDirection;
private DateTime time;
public XInputSceneController()
{
controller = new SharpDX.XInput.Controller(SharpDX.XInput.UserIndex.One);
}
private void SetSceneView(SceneView sceneView)
{
if (this.sceneView != null)
{
//Clean up
this.sceneView.Loaded -= _sceneView_Loaded;
this.sceneView.Unloaded -= _sceneView_Unloaded;
Stop();
}
this.sceneView = sceneView;
if (sceneView != null)
{
this.sceneView.Loaded += _sceneView_Loaded;
this.sceneView.Unloaded += _sceneView_Unloaded;
Start(); //We should only start if already loaded, but no way to detect that currently
}
}
private void Start()
{
if (timer == null)
{
timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1.0 / 200) };
timer.Tick += timer_Tick;
time = DateTime.Now;
timer.Start();
}
}
private void Stop()
{
if (timer != null)
{
timer.Tick -= timer_Tick;
timer.Stop();
timer = null;
}
}
private void timer_Tick(object sender, object e)
{
UpdateView();
}
private void UpdateView()
{
if (sceneView == null)
return;
if (controller == null || !controller.IsConnected)
return;
//The Camera might change whil doing all the calculations...
var originalCamera = sceneView.Camera;
if (originalCamera == null)
return;
var newCamera = originalCamera;
var state = controller.GetState();
var time2 = DateTime.Now;
bool isRightShoulderPressed = state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.RightShoulder);
//Choose if staying at the same alitude or not
if (isRightShoulderPressed)
{
var elapsed = time2 - time;
if (elapsed != TimeSpan.Zero && elapsed > TimeSpan.FromSeconds(0.25))
{
timer.Stop();
timer.Start();
relativeToDirection = !relativeToDirection;
time = time2;
}
}
else
time = time2;
double LeftThumbStickX = 0;
double LeftThumbStickY = 0;
double RightThumbStickX = 0;
double RightThumbStickY = 0;
var gamePad = new NormalizedGamepad(state.Gamepad);
LeftThumbStickX = gamePad.LeftThumbXNormalized;
LeftThumbStickY = gamePad.LeftThumbYNormalized;
RightThumbStickX = gamePad.RightThumbXNormalized;
RightThumbStickY = gamePad.RightThumbYNormalized;
if ((LeftThumbStickX != 0) || (LeftThumbStickY != 0) || (RightThumbStickX != 0) || (RightThumbStickY != 0))
{
//Move sideways (crab move), so calling move forward after modifying heading and tilt, then resetting heading and tilt
if (LeftThumbStickX != 0)
{
//Distance depends on the altitude, but must have minimum values (one way and the other) to not be almost nothing when altitude gets to 0)
var distance = (double)LeftThumbStickX * newCamera.Location.Z / 40;
if (distance > 0 && distance < 0.75)
distance = 0.75;
if (distance < 0 && distance > -0.75)
distance = -0.75;
var pitch = newCamera.Pitch;
newCamera = newCamera.RotateTo(newCamera.Heading, 90, newCamera.Roll).RotateTo(90, 0, 0).MoveForward(distance).RotateTo(-90, 0, 0);
newCamera = newCamera.RotateTo(newCamera.Heading, pitch, newCamera.Roll);
}
var distance2 = (double)LeftThumbStickY * newCamera.Location.Z / 40;
if (distance2 > 0 && distance2 < 1)
distance2 = 1;
if (distance2 < 0 && distance2 > -1)
distance2 = -1;
//Move in the direction of the camera (modify the elevation)
newCamera = newCamera.MoveForward(distance2).RotateTo((double)RightThumbStickX, newCamera.Pitch > 2 ? -(double)RightThumbStickY : RightThumbStickY < 0 ? -(double)RightThumbStickY : 0, 0);
//If move in the direction of the camera but staying at the same elevation.
if (!relativeToDirection)
newCamera = newCamera.MoveTo(new MapPoint(newCamera.Location.X, newCamera.Location.Y, originalCamera.Location.Z, newCamera.Location.SpatialReference));
}
//Triggers are just elevating the camera
double elevationDistance = (double)(state.Gamepad.RightTrigger - state.Gamepad.LeftTrigger);
if ((elevationDistance != 0) && (newCamera.Location.Z != double.NaN))
{
var distance = elevationDistance * Math.Abs(newCamera.Location.Z) / 10000;
newCamera = newCamera.Elevate(distance > 1 ? distance : distance < 1 ? distance : distance < 0 ? -1 : 1);
}
if (state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadUp))
newCamera = newCamera.RotateTo(0, newCamera.Pitch, newCamera.Roll);
if (state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadDown))
newCamera = newCamera.RotateTo(180, newCamera.Pitch, newCamera.Roll);
if (state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadLeft))
newCamera = newCamera.RotateTo(270, newCamera.Pitch, newCamera.Roll);
if (state.Gamepad.Buttons.HasFlag(GamepadButtonFlags.DPadRight))
newCamera = newCamera.RotateTo(90, newCamera.Pitch, newCamera.Roll);
if (!newCamera.IsEqual(originalCamera))
sceneView.SetViewpointCamera(newCamera);
}
private void _sceneView_Unloaded(object sender, RoutedEventArgs e)
{
Stop();
}
private void _sceneView_Loaded(object sender, RoutedEventArgs e)
{
Start();
}
public static XInputSceneController GetController(DependencyObject obj)
{
return (XInputSceneController)obj.GetValue(ControllerProperty);
}
public static void SetController(DependencyObject obj, XInputSceneController value)
{
obj.SetValue(ControllerProperty, value);
}
public static readonly DependencyProperty ControllerProperty =
DependencyProperty.RegisterAttached("Controller", typeof(XInputSceneController), typeof(XInputSceneController), new PropertyMetadata(null, OnControllerPropertyChanged));
private static void OnControllerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var oldCtrl = e.OldValue as XInputSceneController;
var newCtrl = e.NewValue as XInputSceneController;
if (oldCtrl != null)
oldCtrl.SetSceneView(null);
if (newCtrl != null)
newCtrl.SetSceneView(d as SceneView);
}
}
} | {
"content_hash": "4a7fed08065496ceebc3df8ed53d5913",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 203,
"avg_line_length": 39.60386473429951,
"alnum_prop": 0.5703830202488411,
"repo_name": "Esri/arcgis-runtime-demos-dotnet",
"id": "dc022f2fc6156d2e4ae0586645279515e2365667",
"size": "8200",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/KmlViewer/XInputHelper/XInputSceneController.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "784276"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>windows-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>4.1.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.mobile.windows</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Mobile Device Management Windows Impl</name>
<description>WSO2 Carbon - Mobile Device Management Windows Implementation</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.devicemgt.plugins.version}</Bundle-Version>
<Bundle-Description>Device Management Mobile Windows Impl Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.mobile.windows.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.xml,
javax.xml.bind.*,
javax.sql,
javax.naming,
javax.xml.parsers; version=0.0.0,
org.w3c.dom,
org.wso2.carbon.context,
org.wso2.carbon.utils.*,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.core.dao.*,
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.policy.mgt.common.*,
org.wso2.carbon.registry.core,
org.wso2.carbon.registry.core.session,
org.wso2.carbon.registry.core.service,
org.wso2.carbon.registry.api,
org.wso2.carbon.device.mgt.extensions.license.mgt.registry
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.mobile.windows.internal,
org.wso2.carbon.device.mgt.mobile.windows.*
</Export-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.policy.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.policy.mgt.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.wso2</groupId>
<artifactId>jdbc-pool</artifactId>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
</project>
| {
"content_hash": "973a7697e44bd0cbf28e0bae1438e87e",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 204,
"avg_line_length": 43.16201117318436,
"alnum_prop": 0.5345586331866425,
"repo_name": "wso2/carbon-device-mgt-plugins",
"id": "0d8f8cbaac10a65c430dbb2a3a5084fc6fc2e230",
"size": "7726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "912"
},
{
"name": "C",
"bytes": "2475"
},
{
"name": "C++",
"bytes": "14451"
},
{
"name": "CSS",
"bytes": "565755"
},
{
"name": "HTML",
"bytes": "679943"
},
{
"name": "Java",
"bytes": "3852899"
},
{
"name": "JavaScript",
"bytes": "9901466"
},
{
"name": "PLSQL",
"bytes": "4277"
},
{
"name": "Python",
"bytes": "36818"
},
{
"name": "Shell",
"bytes": "16631"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_31) on Fri Oct 05 17:19:53 PDT 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.examples.ExampleDriver (Hadoop 0.20.2-cdh3u5 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-05">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.examples.ExampleDriver (Hadoop 0.20.2-cdh3u5 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/examples/ExampleDriver.html" title="class in org.apache.hadoop.examples"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/examples//class-useExampleDriver.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExampleDriver.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.examples.ExampleDriver</B></H2>
</CENTER>
No usage of org.apache.hadoop.examples.ExampleDriver
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/examples/ExampleDriver.html" title="class in org.apache.hadoop.examples"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/examples//class-useExampleDriver.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExampleDriver.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| {
"content_hash": "dc146aa52b42f78bec6be8c4821e281c",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 223,
"avg_line_length": 41.875,
"alnum_prop": 0.618407960199005,
"repo_name": "baggioss/hadoop-cdh3u5",
"id": "ab0b105bf41c38fe6071b7862e86fabead8828d4",
"size": "6030",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "docs/api/org/apache/hadoop/examples/class-use/ExampleDriver.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "480865"
},
{
"name": "C++",
"bytes": "403118"
},
{
"name": "Java",
"bytes": "16133869"
},
{
"name": "JavaScript",
"bytes": "59122"
},
{
"name": "Objective-C",
"bytes": "118273"
},
{
"name": "PHP",
"bytes": "152555"
},
{
"name": "Perl",
"bytes": "140392"
},
{
"name": "Python",
"bytes": "1217631"
},
{
"name": "Ruby",
"bytes": "28485"
},
{
"name": "Shell",
"bytes": "1437758"
},
{
"name": "Smalltalk",
"bytes": "56562"
},
{
"name": "XML",
"bytes": "9558"
}
],
"symlink_target": ""
} |
import unittest
from nova import crypto
from nova import exception
from nova import flags
from nova import log as logging
from nova import test
from nova.auth import manager
from nova.api.ec2 import cloud
from nova.auth import fakeldap
FLAGS = flags.FLAGS
LOG = logging.getLogger(__name__)
class user_generator(object):
def __init__(self, manager, **user_state):
if 'name' not in user_state:
user_state['name'] = 'test1'
self.manager = manager
self.user = manager.create_user(**user_state)
def __enter__(self):
return self.user
def __exit__(self, value, type, trace):
self.manager.delete_user(self.user)
class project_generator(object):
def __init__(self, manager, **project_state):
if 'name' not in project_state:
project_state['name'] = 'testproj'
if 'manager_user' not in project_state:
project_state['manager_user'] = 'test1'
self.manager = manager
self.project = manager.create_project(**project_state)
def __enter__(self):
return self.project
def __exit__(self, value, type, trace):
self.manager.delete_project(self.project)
class user_and_project_generator(object):
def __init__(self, manager, user_state=None, project_state=None):
if not user_state:
user_state = {}
if not project_state:
project_state = {}
self.manager = manager
if 'name' not in user_state:
user_state['name'] = 'test1'
if 'name' not in project_state:
project_state['name'] = 'testproj'
if 'manager_user' not in project_state:
project_state['manager_user'] = 'test1'
self.user = manager.create_user(**user_state)
self.project = manager.create_project(**project_state)
def __enter__(self):
return (self.user, self.project)
def __exit__(self, value, type, trace):
self.manager.delete_user(self.user)
self.manager.delete_project(self.project)
class _AuthManagerBaseTestCase(test.TestCase):
user_not_found_type = exception.UserNotFound
def setUp(self):
super(_AuthManagerBaseTestCase, self).setUp()
self.flags(auth_driver=self.auth_driver,
connection_type='fake')
self.manager = manager.AuthManager(new=True)
self.manager.mc.cache = {}
def test_create_and_find_user(self):
with user_generator(self.manager):
self.assert_(self.manager.get_user('test1'))
def test_create_and_find_with_properties(self):
with user_generator(self.manager, name="herbert", secret="classified",
access="private-party"):
u = self.manager.get_user('herbert')
self.assertEqual('herbert', u.id)
self.assertEqual('herbert', u.name)
self.assertEqual('classified', u.secret)
self.assertEqual('private-party', u.access)
def test_create_user_twice(self):
self.manager.create_user('test-1')
self.assertRaises(exception.UserExists, self.manager.create_user,
'test-1')
def test_signature_is_valid(self):
with user_generator(self.manager, name='admin', secret='admin',
access='admin'):
with project_generator(self.manager, name="admin",
manager_user='admin'):
accesskey = 'admin:admin'
expected_result = (self.manager.get_user('admin'),
self.manager.get_project('admin'))
# captured sig and query string using boto 1.9b/euca2ools 1.2
sig = 'd67Wzd9Bwz8xid9QU+lzWXcF2Y3tRicYABPJgrqfrwM='
auth_params = {'AWSAccessKeyId': 'admin:admin',
'Action': 'DescribeAvailabilityZones',
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'Timestamp': '2011-04-22T11:29:29',
'Version': '2009-11-30'}
self.assertTrue(expected_result, self.manager.authenticate(
accesskey,
sig,
auth_params,
'GET',
'127.0.0.1:8773',
'/services/Cloud/'))
# captured sig and query string using RightAWS 1.10.0
sig = 'ECYLU6xdFG0ZqRVhQybPJQNJ5W4B9n8fGs6+/fuGD2c='
auth_params = {'AWSAccessKeyId': 'admin:admin',
'Action': 'DescribeAvailabilityZones',
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'Timestamp': '2011-04-22T11:29:49.000Z',
'Version': '2008-12-01'}
self.assertTrue(expected_result, self.manager.authenticate(
accesskey,
sig,
auth_params,
'GET',
'127.0.0.1',
'/services/Cloud'))
def test_can_get_credentials(self):
self.flags(auth_strategy='deprecated')
st = {'access': 'access', 'secret': 'secret'}
with user_and_project_generator(self.manager, user_state=st) as (u, p):
credentials = self.manager.get_environment_rc(u, p)
LOG.debug(credentials)
self.assertTrue('export EC2_ACCESS_KEY="access:testproj"\n'
in credentials)
self.assertTrue('export EC2_SECRET_KEY="secret"\n' in credentials)
def test_can_list_users(self):
with user_generator(self.manager):
with user_generator(self.manager, name="test2"):
users = self.manager.get_users()
self.assert_(filter(lambda u: u.id == 'test1', users))
self.assert_(filter(lambda u: u.id == 'test2', users))
self.assert_(not filter(lambda u: u.id == 'test3', users))
def test_can_add_and_remove_user_role(self):
with user_generator(self.manager):
self.assertFalse(self.manager.has_role('test1', 'itsec'))
self.manager.add_role('test1', 'itsec')
self.assertTrue(self.manager.has_role('test1', 'itsec'))
self.manager.remove_role('test1', 'itsec')
self.assertFalse(self.manager.has_role('test1', 'itsec'))
def test_can_create_and_get_project(self):
with user_and_project_generator(self.manager) as (u, p):
self.assert_(self.manager.get_user('test1'))
self.assert_(self.manager.get_user('test1'))
self.assert_(self.manager.get_project('testproj'))
def test_can_list_projects(self):
with user_and_project_generator(self.manager):
with project_generator(self.manager, name="testproj2"):
projects = self.manager.get_projects()
self.assert_(filter(lambda p: p.name == 'testproj', projects))
self.assert_(filter(lambda p: p.name == 'testproj2', projects))
self.assert_(not filter(lambda p: p.name == 'testproj3',
projects))
def test_can_create_and_get_project_with_attributes(self):
with user_generator(self.manager):
with project_generator(self.manager, description='A test project'):
project = self.manager.get_project('testproj')
self.assertEqual('A test project', project.description)
def test_can_create_project_with_manager(self):
with user_and_project_generator(self.manager) as (user, project):
self.assertEqual('test1', project.project_manager_id)
self.assertTrue(self.manager.is_project_manager(user, project))
def test_can_create_project_twice(self):
with user_and_project_generator(self.manager) as (user1, project):
self.assertRaises(exception.ProjectExists,
self.manager.create_project, "testproj", "test1")
def test_create_project_assigns_manager_to_members(self):
with user_and_project_generator(self.manager) as (user, project):
self.assertTrue(self.manager.is_project_member(user, project))
def test_create_project_with_manager_and_members(self):
with user_generator(self.manager, name='test2') as user2:
with user_and_project_generator(self.manager,
project_state={'member_users': ['test2']}) as (user1, project):
self.assertTrue(self.manager.is_project_member(
user1, project))
self.assertTrue(self.manager.is_project_member(
user2, project))
def test_create_project_with_manager_and_missing_members(self):
self.assertRaises(self.user_not_found_type,
self.manager.create_project, "testproj", "test1",
member_users="test2")
def test_no_extra_project_members(self):
with user_generator(self.manager, name='test2') as baduser:
with user_and_project_generator(self.manager) as (user, project):
self.assertFalse(self.manager.is_project_member(baduser,
project))
def test_no_extra_project_managers(self):
with user_generator(self.manager, name='test2') as baduser:
with user_and_project_generator(self.manager) as (user, project):
self.assertFalse(self.manager.is_project_manager(baduser,
project))
def test_can_add_user_to_project(self):
with user_generator(self.manager, name='test2') as user:
with user_and_project_generator(self.manager) as (_user, project):
self.manager.add_to_project(user, project)
project = self.manager.get_project('testproj')
self.assertTrue(self.manager.is_project_member(user, project))
def test_can_remove_user_from_project(self):
with user_generator(self.manager, name='test2') as user:
with user_and_project_generator(self.manager) as (_user, project):
self.manager.add_to_project(user, project)
project = self.manager.get_project('testproj')
self.assertTrue(self.manager.is_project_member(user, project))
self.manager.remove_from_project(user, project)
project = self.manager.get_project('testproj')
self.assertFalse(self.manager.is_project_member(user, project))
def test_can_add_remove_user_with_role(self):
with user_generator(self.manager, name='test2') as user:
with user_and_project_generator(self.manager) as (_user, project):
# NOTE(todd): after modifying users you must reload project
self.manager.add_to_project(user, project)
project = self.manager.get_project('testproj')
self.manager.add_role(user, 'developer', project)
self.assertTrue(self.manager.is_project_member(user, project))
self.manager.remove_from_project(user, project)
project = self.manager.get_project('testproj')
self.assertFalse(self.manager.has_role(user, 'developer',
project))
self.assertFalse(self.manager.is_project_member(user, project))
def test_adding_role_to_project_is_ignored_unless_added_to_user(self):
with user_and_project_generator(self.manager) as (user, project):
self.assertFalse(self.manager.has_role(user, 'sysadmin', project))
self.manager.add_role(user, 'sysadmin', project)
# NOTE(todd): it will still show up in get_user_roles(u, project)
self.assertFalse(self.manager.has_role(user, 'sysadmin', project))
self.manager.add_role(user, 'sysadmin')
self.assertTrue(self.manager.has_role(user, 'sysadmin', project))
def test_add_user_role_doesnt_infect_project_roles(self):
with user_and_project_generator(self.manager) as (user, project):
self.assertFalse(self.manager.has_role(user, 'sysadmin', project))
self.manager.add_role(user, 'sysadmin')
self.assertFalse(self.manager.has_role(user, 'sysadmin', project))
def test_can_list_user_roles(self):
with user_and_project_generator(self.manager) as (user, project):
self.manager.add_role(user, 'sysadmin')
roles = self.manager.get_user_roles(user)
self.assertTrue('sysadmin' in roles)
self.assertFalse('netadmin' in roles)
def test_can_list_project_roles(self):
with user_and_project_generator(self.manager) as (user, project):
self.manager.add_role(user, 'sysadmin')
self.manager.add_role(user, 'sysadmin', project)
self.manager.add_role(user, 'netadmin', project)
project_roles = self.manager.get_user_roles(user, project)
self.assertTrue('sysadmin' in project_roles)
self.assertTrue('netadmin' in project_roles)
# has role should be false user-level role is missing
self.assertFalse(self.manager.has_role(user, 'netadmin', project))
def test_can_remove_user_roles(self):
with user_and_project_generator(self.manager) as (user, project):
self.manager.add_role(user, 'sysadmin')
self.assertTrue(self.manager.has_role(user, 'sysadmin'))
self.manager.remove_role(user, 'sysadmin')
self.assertFalse(self.manager.has_role(user, 'sysadmin'))
def test_removing_user_role_hides_it_from_project(self):
with user_and_project_generator(self.manager) as (user, project):
self.manager.add_role(user, 'sysadmin')
self.manager.add_role(user, 'sysadmin', project)
self.assertTrue(self.manager.has_role(user, 'sysadmin', project))
self.manager.remove_role(user, 'sysadmin')
self.assertFalse(self.manager.has_role(user, 'sysadmin', project))
def test_can_remove_project_role_but_keep_user_role(self):
with user_and_project_generator(self.manager) as (user, project):
self.manager.add_role(user, 'sysadmin')
self.manager.add_role(user, 'sysadmin', project)
self.assertTrue(self.manager.has_role(user, 'sysadmin'))
self.manager.remove_role(user, 'sysadmin', project)
self.assertFalse(self.manager.has_role(user, 'sysadmin', project))
self.assertTrue(self.manager.has_role(user, 'sysadmin'))
def test_can_retrieve_project_by_user(self):
with user_and_project_generator(self.manager) as (user, project):
self.assertEqual(1, len(self.manager.get_projects('test1')))
def test_can_modify_project(self):
with user_and_project_generator(self.manager):
with user_generator(self.manager, name='test2'):
self.manager.modify_project('testproj', 'test2', 'new desc')
project = self.manager.get_project('testproj')
self.assertEqual('test2', project.project_manager_id)
self.assertEqual('new desc', project.description)
def test_can_call_modify_project_but_do_nothing(self):
with user_and_project_generator(self.manager):
self.manager.modify_project('testproj')
project = self.manager.get_project('testproj')
self.assertEqual('test1', project.project_manager_id)
self.assertEqual('testproj', project.description)
def test_modify_project_adds_new_manager(self):
with user_and_project_generator(self.manager):
with user_generator(self.manager, name='test2'):
self.manager.modify_project('testproj', 'test2', 'new desc')
project = self.manager.get_project('testproj')
self.assertTrue('test2' in project.member_ids)
def test_create_project_with_missing_user(self):
with user_generator(self.manager):
self.assertRaises(self.user_not_found_type,
self.manager.create_project, 'testproj',
'not_real')
def test_can_delete_project(self):
with user_generator(self.manager):
self.manager.create_project('testproj', 'test1')
self.assert_(self.manager.get_project('testproj'))
self.manager.delete_project('testproj')
projectlist = self.manager.get_projects()
self.assert_(not filter(lambda p: p.name == 'testproj',
projectlist))
def test_can_delete_user(self):
self.manager.create_user('test1')
self.assert_(self.manager.get_user('test1'))
self.manager.delete_user('test1')
userlist = self.manager.get_users()
self.assert_(not filter(lambda u: u.id == 'test1', userlist))
def test_can_modify_users(self):
with user_generator(self.manager):
self.manager.modify_user('test1', 'access', 'secret', True)
user = self.manager.get_user('test1')
self.assertEqual('access', user.access)
self.assertEqual('secret', user.secret)
self.assertTrue(user.is_admin())
def test_can_call_modify_user_but_do_nothing(self):
with user_generator(self.manager):
old_user = self.manager.get_user('test1')
self.manager.modify_user('test1')
user = self.manager.get_user('test1')
self.assertEqual(old_user.access, user.access)
self.assertEqual(old_user.secret, user.secret)
self.assertEqual(old_user.is_admin(), user.is_admin())
def test_get_nonexistent_user_raises_notfound_exception(self):
self.assertRaises(exception.NotFound,
self.manager.get_user,
'joeblow')
class AuthManagerLdapTestCase(_AuthManagerBaseTestCase):
auth_driver = 'nova.auth.ldapdriver.FakeLdapDriver'
user_not_found_type = exception.LDAPUserNotFound
def test_reconnect_on_server_failure(self):
self.manager.get_users()
fakeldap.server_fail = True
try:
self.assertRaises(fakeldap.SERVER_DOWN, self.manager.get_users)
finally:
fakeldap.server_fail = False
self.manager.get_users()
class AuthManagerDbTestCase(_AuthManagerBaseTestCase):
auth_driver = 'nova.auth.dbdriver.DbDriver'
user_not_found_type = exception.UserNotFound
if __name__ == "__main__":
# TODO(anotherjesse): Implement use_fake as an option
unittest.main()
| {
"content_hash": "cbd30d1f193582f166c846ba87e63196",
"timestamp": "",
"source": "github",
"line_count": 406,
"max_line_length": 79,
"avg_line_length": 46.73645320197044,
"alnum_prop": 0.5951515151515151,
"repo_name": "anbangr/trusted-nova",
"id": "6549d6e96cd5776be9e4d2c8f73dbbf81973fffc",
"size": "19752",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "nova/tests/test_auth.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "7403"
},
{
"name": "Python",
"bytes": "5690299"
},
{
"name": "Shell",
"bytes": "27086"
}
],
"symlink_target": ""
} |
static HWND g_hWnd = NULL;
static INT64 g_Time = 0;
static INT64 g_TicksPerSecond = 0;
static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT;
static bool g_HasGamepad = false;
static bool g_WantUpdateHasGamepad = true;
static bool g_WantUpdateMonitors = true;
// Forward Declarations
static void ImGui_ImplWin32_InitPlatformInterface();
static void ImGui_ImplWin32_ShutdownPlatformInterface();
static void ImGui_ImplWin32_UpdateMonitors();
// Functions
bool ImGui_ImplWin32_Init(void* hwnd)
{
if (!::QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond))
return false;
if (!::QueryPerformanceCounter((LARGE_INTEGER *)&g_Time))
return false;
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy)
io.BackendPlatformName = "imgui_impl_win32";
// Our mouse update function expect PlatformHandle to be filled for the main viewport
g_hWnd = (HWND)hwnd;
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)g_hWnd;
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
ImGui_ImplWin32_InitPlatformInterface();
// Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime.
io.KeyMap[ImGuiKey_Tab] = VK_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
io.KeyMap[ImGuiKey_Home] = VK_HOME;
io.KeyMap[ImGuiKey_End] = VK_END;
io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
io.KeyMap[ImGuiKey_Space] = VK_SPACE;
io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
io.KeyMap[ImGuiKey_KeyPadEnter] = VK_RETURN;
io.KeyMap[ImGuiKey_A] = 'A';
io.KeyMap[ImGuiKey_C] = 'C';
io.KeyMap[ImGuiKey_V] = 'V';
io.KeyMap[ImGuiKey_X] = 'X';
io.KeyMap[ImGuiKey_Y] = 'Y';
io.KeyMap[ImGuiKey_Z] = 'Z';
return true;
}
void ImGui_ImplWin32_Shutdown()
{
ImGui_ImplWin32_ShutdownPlatformInterface();
g_hWnd = (HWND)0;
}
static bool ImGui_ImplWin32_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return false;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
::SetCursor(NULL);
}
else
{
// Show OS mouse cursor
LPTSTR win32_cursor = IDC_ARROW;
switch (imgui_cursor)
{
case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break;
case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break;
}
::SetCursor(::LoadCursor(NULL, win32_cursor));
}
return true;
}
// This code supports multi-viewports (multiple OS Windows mapped into different Dear ImGui viewports)
// Because of that, it is a little more complicated than your typical single-viewport binding code!
static void ImGui_ImplWin32_UpdateMousePos()
{
ImGuiIO& io = ImGui::GetIO();
// Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
// (When multi-viewports are enabled, all imgui positions are same as OS positions)
if (io.WantSetMousePos)
{
POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0)
::ClientToScreen(g_hWnd, &pos);
::SetCursorPos(pos.x, pos.y);
}
io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
io.MouseHoveredViewport = 0;
// Set imgui mouse position
POINT mouse_screen_pos;
if (!::GetCursorPos(&mouse_screen_pos))
return;
if (HWND focused_hwnd = ::GetForegroundWindow())
{
if (::IsChild(focused_hwnd, g_hWnd))
focused_hwnd = g_hWnd;
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
// Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
// This is the position you can get with GetCursorPos(). In theory adding viewport->Pos is also the reverse operation of doing ScreenToClient().
if (ImGui::FindViewportByPlatformHandle((void*)focused_hwnd) != NULL)
io.MousePos = ImVec2((float)mouse_screen_pos.x, (float)mouse_screen_pos.y);
}
else
{
// Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window.)
// This is the position you can get with GetCursorPos() + ScreenToClient() or from WM_MOUSEMOVE.
if (focused_hwnd == g_hWnd)
{
POINT mouse_client_pos = mouse_screen_pos;
::ScreenToClient(focused_hwnd, &mouse_client_pos);
io.MousePos = ImVec2((float)mouse_client_pos.x, (float)mouse_client_pos.y);
}
}
}
// (Optional) When using multiple viewports: set io.MouseHoveredViewport to the viewport the OS mouse cursor is hovering.
// Important: this information is not easy to provide and many high-level windowing library won't be able to provide it correctly, because
// - This is _ignoring_ viewports with the ImGuiViewportFlags_NoInputs flag (pass-through windows).
// - This is _regardless_ of whether another viewport is focused or being dragged from.
// If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the back-end, imgui will ignore this field and infer the information by relying on the
// rectangles and last focused time of every viewports it knows about. It will be unaware of foreign windows that may be sitting between or over your windows.
if (HWND hovered_hwnd = ::WindowFromPoint(mouse_screen_pos))
if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hovered_hwnd))
if ((viewport->Flags & ImGuiViewportFlags_NoInputs) == 0) // FIXME: We still get our NoInputs window with WM_NCHITTEST/HTTRANSPARENT code when decorated?
io.MouseHoveredViewport = viewport->ID;
}
// Gamepad navigation mapping
static void ImGui_ImplWin32_UpdateGamepads()
{
#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
ImGuiIO& io = ImGui::GetIO();
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
// Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow.
// Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE.
if (g_WantUpdateHasGamepad)
{
XINPUT_CAPABILITIES caps;
g_HasGamepad = (XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS);
g_WantUpdateHasGamepad = false;
}
XINPUT_STATE xinput_state;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
if (g_HasGamepad && XInputGetState(0, &xinput_state) == ERROR_SUCCESS)
{
const XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
#define MAP_BUTTON(NAV_NO, BUTTON_ENUM) { io.NavInputs[NAV_NO] = (gamepad.wButtons & BUTTON_ENUM) ? 1.0f : 0.0f; }
#define MAP_ANALOG(NAV_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; }
MAP_BUTTON(ImGuiNavInput_Activate, XINPUT_GAMEPAD_A); // Cross / A
MAP_BUTTON(ImGuiNavInput_Cancel, XINPUT_GAMEPAD_B); // Circle / B
MAP_BUTTON(ImGuiNavInput_Menu, XINPUT_GAMEPAD_X); // Square / X
MAP_BUTTON(ImGuiNavInput_Input, XINPUT_GAMEPAD_Y); // Triangle / Y
MAP_BUTTON(ImGuiNavInput_DpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); // D-Pad Left
MAP_BUTTON(ImGuiNavInput_DpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); // D-Pad Right
MAP_BUTTON(ImGuiNavInput_DpadUp, XINPUT_GAMEPAD_DPAD_UP); // D-Pad Up
MAP_BUTTON(ImGuiNavInput_DpadDown, XINPUT_GAMEPAD_DPAD_DOWN); // D-Pad Down
MAP_BUTTON(ImGuiNavInput_FocusPrev, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_FocusNext, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
MAP_BUTTON(ImGuiNavInput_TweakSlow, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB
MAP_BUTTON(ImGuiNavInput_TweakFast, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
MAP_ANALOG(ImGuiNavInput_LStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
MAP_ANALOG(ImGuiNavInput_LStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
MAP_ANALOG(ImGuiNavInput_LStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
MAP_ANALOG(ImGuiNavInput_LStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32767);
#undef MAP_BUTTON
#undef MAP_ANALOG
}
#endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
}
static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM)
{
MONITORINFO info = { 0 };
info.cbSize = sizeof(MONITORINFO);
if (!::GetMonitorInfo(monitor, &info))
return TRUE;
ImGuiPlatformMonitor imgui_monitor;
imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top);
imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top));
imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top);
imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top));
imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
ImGuiPlatformIO& io = ImGui::GetPlatformIO();
if (info.dwFlags & MONITORINFOF_PRIMARY)
io.Monitors.push_front(imgui_monitor);
else
io.Monitors.push_back(imgui_monitor);
return TRUE;
}
static void ImGui_ImplWin32_UpdateMonitors()
{
ImGui::GetPlatformIO().Monitors.resize(0);
::EnumDisplayMonitors(NULL, NULL, ImGui_ImplWin32_UpdateMonitors_EnumFunc, NULL);
g_WantUpdateMonitors = false;
}
void ImGui_ImplWin32_NewFrame()
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame().");
// Setup display size (every frame to accommodate for window resizing)
RECT rect;
::GetClientRect(g_hWnd, &rect);
io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
if (g_WantUpdateMonitors)
ImGui_ImplWin32_UpdateMonitors();
// Setup time step
INT64 current_time;
::QueryPerformanceCounter((LARGE_INTEGER *)¤t_time);
io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond;
g_Time = current_time;
// Read keyboard modifiers inputs
io.KeyCtrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0;
io.KeyShift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0;
io.KeyAlt = (::GetKeyState(VK_MENU) & 0x8000) != 0;
io.KeySuper = false;
// io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below.
// Update OS mouse position
ImGui_ImplWin32_UpdateMousePos();
// Update OS mouse cursor with the cursor requested by imgui
ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
if (g_LastMouseCursor != mouse_cursor)
{
g_LastMouseCursor = mouse_cursor;
ImGui_ImplWin32_UpdateMouseCursor();
}
// Update game controllers (if enabled and available)
ImGui_ImplWin32_UpdateGamepads();
}
// Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
#ifndef WM_MOUSEHWHEEL
#define WM_MOUSEHWHEEL 0x020E
#endif
#ifndef DBT_DEVNODES_CHANGED
#define DBT_DEVNODES_CHANGED 0x0007
#endif
// Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
// Call from your application's message handler.
// When implementing your own back-end, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds.
// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
#if 0
// Copy this line into your .cpp file to forward declare the function.
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#endif
IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui::GetCurrentContext() == NULL)
return 0;
ImGuiIO& io = ImGui::GetIO();
switch (msg)
{
case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK:
{
int button = 0;
if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; }
if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; }
if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; }
if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
::SetCapture(hwnd);
io.MouseDown[button] = true;
return 0;
}
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
case WM_XBUTTONUP:
{
int button = 0;
if (msg == WM_LBUTTONUP) { button = 0; }
if (msg == WM_RBUTTONUP) { button = 1; }
if (msg == WM_MBUTTONUP) { button = 2; }
if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
io.MouseDown[button] = false;
if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
::ReleaseCapture();
return 0;
}
case WM_MOUSEWHEEL:
io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
return 0;
case WM_MOUSEHWHEEL:
io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
return 0;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (wParam < 256)
io.KeysDown[wParam] = 1;
return 0;
case WM_KEYUP:
case WM_SYSKEYUP:
if (wParam < 256)
io.KeysDown[wParam] = 0;
return 0;
case WM_CHAR:
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
if (wParam > 0 && wParam < 0x10000)
io.AddInputCharacterUTF16((unsigned short)wParam);
return 0;
case WM_SETCURSOR:
if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
return 1;
return 0;
case WM_DEVICECHANGE:
if ((UINT)wParam == DBT_DEVNODES_CHANGED)
g_WantUpdateHasGamepad = true;
return 0;
case WM_DISPLAYCHANGE:
g_WantUpdateMonitors = true;
return 0;
}
return 0;
}
//--------------------------------------------------------------------------------------------------------
// DPI-related helpers (optional)
//--------------------------------------------------------------------------------------------------------
// - Use to enable DPI awareness without having to create an application manifest.
// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
//---------------------------------------------------------------------------------------------------------
// This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable.
// ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
// If you are trying to implement your own back-end for your own engine, you may ignore that noise.
//---------------------------------------------------------------------------------------------------------
// Implement some of the functions and types normally declared in recent Windows SDK.
#if !defined(_versionhelpers_H_INCLUDED_) && !defined(_INC_VERSIONHELPERS)
static BOOL IsWindowsVersionOrGreater(WORD major, WORD minor, WORD sp)
{
OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0, { 0 }, sp, 0, 0, 0, 0 };
DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR;
ULONGLONG cond = ::VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL);
cond = ::VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL);
cond = ::VerSetConditionMask(cond, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
return ::VerifyVersionInfoW(&osvi, mask, cond);
}
#define IsWindows8Point1OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WINBLUE
#endif
#ifndef DPI_ENUMS_DECLARED
typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
#endif
#ifndef _DPI_AWARENESS_CONTEXTS_
DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3
#endif
#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
#endif
typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+
typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+
typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update)
// Helper function to enable DPI awareness without setting up a manifest
void ImGui_ImplWin32_EnableDpiAwareness()
{
// Make sure monitors will be updated with latest correct scaling
g_WantUpdateMonitors = true;
// if (IsWindows10OrGreater()) // This needs a manifest to succeed. Instead we try to grab the function pointer!
{
static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
{
SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
return;
}
}
if (IsWindows8Point1OrGreater())
{
static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
{
SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
return;
}
}
#if _WIN32_WINNT >= 0x0600
::SetProcessDPIAware();
#endif
}
#if defined(_MSC_VER) && !defined(NOGDI)
#pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps()
#endif
float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
{
UINT xdpi = 96, ydpi = 96;
if (IsWindows8Point1OrGreater())
{
static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"))
GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
}
#ifndef NOGDI
else
{
const HDC dc = ::GetDC(NULL);
xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
::ReleaseDC(NULL, dc);
}
#endif
IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
return xdpi / 96.0f;
}
float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
{
HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
}
//--------------------------------------------------------------------------------------------------------
// IME (Input Method Editor) basic support for e.g. Asian language users
//--------------------------------------------------------------------------------------------------------
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have Win32 functions
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
#endif
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(__GNUC__)
#define HAS_WIN32_IME 1
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImGui_ImplWin32_SetImeInputPos(ImGuiViewport* viewport, ImVec2 pos)
{
COMPOSITIONFORM cf = { CFS_FORCE_POSITION,{ (LONG)(pos.x - viewport->Pos.x), (LONG)(pos.y - viewport->Pos.y) },{ 0, 0, 0, 0 } };
if (HWND hwnd = (HWND)viewport->PlatformHandle)
if (HIMC himc = ::ImmGetContext(hwnd))
{
::ImmSetCompositionWindow(himc, &cf);
::ImmReleaseContext(hwnd, himc);
}
}
#else
#define HAS_WIN32_IME 0
#endif
//--------------------------------------------------------------------------------------------------------
// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
// This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
//--------------------------------------------------------------------------------------------------------
// Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data.
struct ImGuiViewportDataWin32
{
HWND Hwnd;
bool HwndOwned;
DWORD DwStyle;
DWORD DwExStyle;
ImGuiViewportDataWin32() { Hwnd = NULL; HwndOwned = false; DwStyle = DwExStyle = 0; }
~ImGuiViewportDataWin32() { IM_ASSERT(Hwnd == NULL); }
};
static void ImGui_ImplWin32_GetWin32StyleFromViewportFlags(ImGuiViewportFlags flags, DWORD* out_style, DWORD* out_ex_style)
{
if (flags & ImGuiViewportFlags_NoDecoration)
*out_style = WS_POPUP;
else
*out_style = WS_OVERLAPPEDWINDOW;
if (flags & ImGuiViewportFlags_NoTaskBarIcon)
*out_ex_style = WS_EX_TOOLWINDOW;
else
*out_ex_style = WS_EX_APPWINDOW;
if (flags & ImGuiViewportFlags_TopMost)
*out_ex_style |= WS_EX_TOPMOST;
}
static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
viewport->PlatformUserData = data;
// Select style and parent window
ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &data->DwStyle, &data->DwExStyle);
HWND parent_window = NULL;
if (viewport->ParentViewportId != 0)
if (ImGuiViewport* parent_viewport = ImGui::FindViewportByID(viewport->ParentViewportId))
parent_window = (HWND)parent_viewport->PlatformHandle;
// Create window
RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
data->Hwnd = ::CreateWindowEx(
data->DwExStyle, _T("ImGui Platform"), _T("Untitled"), data->DwStyle, // Style, class name, window name
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area
parent_window, NULL, ::GetModuleHandle(NULL), NULL); // Parent window, Menu, Instance, Param
data->HwndOwned = true;
viewport->PlatformRequestResize = false;
viewport->PlatformHandle = viewport->PlatformHandleRaw = data->Hwnd;
}
static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport)
{
if (ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData)
{
if (::GetCapture() == data->Hwnd)
{
// Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event.
::ReleaseCapture();
::SetCapture(g_hWnd);
}
if (data->Hwnd && data->HwndOwned)
::DestroyWindow(data->Hwnd);
data->Hwnd = NULL;
IM_DELETE(data);
}
viewport->PlatformUserData = viewport->PlatformHandle = NULL;
}
static void ImGui_ImplWin32_ShowWindow(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
::ShowWindow(data->Hwnd, SW_SHOWNA);
else
::ShowWindow(data->Hwnd, SW_SHOW);
}
static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport* viewport)
{
// (Optional) Update Win32 style if it changed _after_ creation.
// Generally they won't change unless configuration flags are changed, but advanced uses (such as manually rewriting viewport flags) make this useful.
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
DWORD new_style;
DWORD new_ex_style;
ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &new_style, &new_ex_style);
// Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows)
if (data->DwStyle != new_style || data->DwExStyle != new_ex_style)
{
data->DwStyle = new_style;
data->DwExStyle = new_ex_style;
::SetWindowLong(data->Hwnd, GWL_STYLE, data->DwStyle);
::SetWindowLong(data->Hwnd, GWL_EXSTYLE, data->DwExStyle);
RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen
::SetWindowPos(data->Hwnd, NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
::ShowWindow(data->Hwnd, SW_SHOWNA); // This is necessary when we alter the style
viewport->PlatformRequestMove = viewport->PlatformRequestResize = true;
}
}
static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
POINT pos = { 0, 0 };
::ClientToScreen(data->Hwnd, &pos);
return ImVec2((float)pos.x, (float)pos.y);
}
static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
RECT rect = { (LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y };
::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle);
::SetWindowPos(data->Hwnd, NULL, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
}
static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
RECT rect;
::GetClientRect(data->Hwnd, &rect);
return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top));
}
static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
RECT rect = { 0, 0, (LONG)size.x, (LONG)size.y };
::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen
::SetWindowPos(data->Hwnd, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}
static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
::BringWindowToTop(data->Hwnd);
::SetForegroundWindow(data->Hwnd);
::SetFocus(data->Hwnd);
}
static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
return ::GetForegroundWindow() == data->Hwnd;
}
static bool ImGui_ImplWin32_GetWindowMinimized(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
return ::IsIconic(data->Hwnd) != 0;
}
static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport* viewport, const char* title)
{
// ::SetWindowTextA() doesn't properly handle UTF-8 so we explicitely convert our string.
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
int n = ::MultiByteToWideChar(CP_UTF8, 0, title, -1, NULL, 0);
ImVector<wchar_t> title_w;
title_w.resize(n);
::MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w.Data, n);
::SetWindowTextW(data->Hwnd, title_w.Data);
}
static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f);
if (alpha < 1.0f)
{
DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED;
::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
::SetLayeredWindowAttributes(data->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA);
}
else
{
DWORD style = ::GetWindowLongW(data->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED;
::SetWindowLongW(data->Hwnd, GWL_EXSTYLE, style);
}
}
static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport* viewport)
{
ImGuiViewportDataWin32* data = (ImGuiViewportDataWin32*)viewport->PlatformUserData;
IM_ASSERT(data->Hwnd != 0);
return ImGui_ImplWin32_GetDpiScaleForHwnd(data->Hwnd);
}
// FIXME-DPI: Testing DPI related ideas
static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport* viewport)
{
(void)viewport;
#if 0
ImGuiStyle default_style;
//default_style.WindowPadding = ImVec2(0, 0);
//default_style.WindowBorderSize = 0.0f;
//default_style.ItemSpacing.y = 3.0f;
//default_style.FramePadding = ImVec2(0, 0);
default_style.ScaleAllSizes(viewport->DpiScale);
ImGuiStyle& style = ImGui::GetStyle();
style = default_style;
#endif
}
static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hWnd))
{
switch (msg)
{
case WM_CLOSE:
viewport->PlatformRequestClose = true;
return 0;
case WM_MOVE:
viewport->PlatformRequestMove = true;
break;
case WM_SIZE:
viewport->PlatformRequestResize = true;
break;
case WM_MOUSEACTIVATE:
if (viewport->Flags & ImGuiViewportFlags_NoFocusOnClick)
return MA_NOACTIVATE;
break;
case WM_NCHITTEST:
// Let mouse pass-through the window. This will allow the back-end to set io.MouseHoveredViewport properly (which is OPTIONAL).
// The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
// If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
// your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
if (viewport->Flags & ImGuiViewportFlags_NoInputs)
return HTTRANSPARENT;
break;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
static void ImGui_ImplWin32_InitPlatformInterface()
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = ::GetModuleHandle(NULL);
wcex.hIcon = NULL;
wcex.hCursor = NULL;
wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = _T("ImGui Platform");
wcex.hIconSm = NULL;
::RegisterClassEx(&wcex);
ImGui_ImplWin32_UpdateMonitors();
// Register platform interface (will be coupled with a renderer interface)
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow;
platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow;
platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow;
platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos;
platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos;
platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize;
platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize;
platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus;
platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus;
platform_io.Platform_GetWindowMinimized = ImGui_ImplWin32_GetWindowMinimized;
platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle;
platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha;
platform_io.Platform_UpdateWindow = ImGui_ImplWin32_UpdateWindow;
platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale; // FIXME-DPI
platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI
#if HAS_WIN32_IME
platform_io.Platform_SetImeInputPos = ImGui_ImplWin32_SetImeInputPos;
#endif
// Register main window handle (which is owned by the main application, not by us)
// This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
ImGuiViewportDataWin32* data = IM_NEW(ImGuiViewportDataWin32)();
data->Hwnd = g_hWnd;
data->HwndOwned = false;
main_viewport->PlatformUserData = data;
main_viewport->PlatformHandle = (void*)g_hWnd;
}
static void ImGui_ImplWin32_ShutdownPlatformInterface()
{
::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(NULL));
}
//---------------------------------------------------------------------------------------------------------
| {
"content_hash": "64b46cd4eddc9344b47570d3ed7e81d2",
"timestamp": "",
"source": "github",
"line_count": 820,
"max_line_length": 203,
"avg_line_length": 46.50365853658536,
"alnum_prop": 0.6702069074030368,
"repo_name": "aliascc/Arenal-Engine",
"id": "207e54fe25029e9354d81498269a6aa36fcf5e7b",
"size": "42255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "3rdParty/ImGui/Project/imgui/imgui_impl_win32.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AngelScript",
"bytes": "18836"
},
{
"name": "C",
"bytes": "303572"
},
{
"name": "C++",
"bytes": "5281556"
},
{
"name": "HLSL",
"bytes": "124916"
},
{
"name": "Python",
"bytes": "1946"
}
],
"symlink_target": ""
} |
'use strict';
const gulp = require('gulp');
const path = require('path');
const tools = require('urbanjs-tools');
tools.tasks.tslint.register(gulp, 'tslint', {
configFile: path.join(__dirname, '../../tslint.json'),
extensions: ['.ts', '.tsx'],
files: 'index.ts'
});
| {
"content_hash": "7bced011cf00f24a563a4b5afade9e37",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 56,
"avg_line_length": 24.90909090909091,
"alnum_prop": 0.635036496350365,
"repo_name": "urbanjs/urbanjs-tools",
"id": "2ec69ada9160f0bd1dcaf0dd6ee0eda0ebbb1b62",
"size": "274",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "packages/urbanjs-tool-tslint/tests/valid-project/gulpfile.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "999"
},
{
"name": "HTML",
"bytes": "1071"
},
{
"name": "JavaScript",
"bytes": "33695"
},
{
"name": "TypeScript",
"bytes": "208948"
}
],
"symlink_target": ""
} |
CREATE OR REPLACE VIEW vacuum_progress AS
SELECT
p.pid,
clock_timestamp() - a.xact_start AS duration,
coalesce(wait_event_type ||'.'|| wait_event, 'f') AS waiting,
(CASE
WHEN a.query ~ '^autovacuum.*to prevent wraparound' THEN 'wraparound'
WHEN a.query ~ '^vacuum' THEN 'user'
ELSE 'regular'
END) AS mode,
p.datname AS database,
p.relid::regclass AS table,
p.phase,
pg_size_pretty(p.heap_blks_total *
current_setting('block_size')::int) AS table_size,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
pg_size_pretty(p.heap_blks_scanned *
current_setting('block_size')::int) AS scanned,
pg_size_pretty(p.heap_blks_vacuumed *
current_setting('block_size')::int) AS vacuumed,
(CASE WHEN p.heap_blks_total > 0 THEN
round(100.0 * p.heap_blks_scanned /
p.heap_blks_total, 1) else 0 end) AS scanned_pct,
(CASE WHEN p.heap_blks_total > 0 THEN
round(100.0 * p.heap_blks_vacuumed /
p.heap_blks_total, 1) else 0 end) AS vacuumed_pct,
p.index_vacuum_count,
round(100.0 * p.num_dead_tuples /
p.max_dead_tuples,1) AS dead_pct
FROM pg_catalog.pg_stat_progress_vacuum AS p
JOIN pg_catalog.pg_stat_activity AS a USING (pid)
ORDER BY duration DESC;
| {
"content_hash": "31006aa65b0b9496b2cafa00270b52e3",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 78,
"avg_line_length": 41,
"alnum_prop": 0.6371951219512195,
"repo_name": "bricklen/pg-scripts",
"id": "b32e5b2b0b8673adb316c3103705204e22e03d36",
"size": "1655",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vacuum_progress.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PLpgSQL",
"bytes": "39260"
},
{
"name": "Python",
"bytes": "21999"
},
{
"name": "Shell",
"bytes": "13133"
}
],
"symlink_target": ""
} |
/**
* Sugar method for returning the desired object at the end of a promise chain
* @param {any} object the item with which to resolve the promise chain
* @returns {function}
* @example
* var item = {
* prop: 2
* };
* Promise
* .resolve(item.prop)
* .then(resolveWith(item))
* .then(function(res) {
* require('assert').deepEqual(res, {prop:2});
* return 'success'
* })
* // => success
*
*/
export default function resolveWith(object) {
return function resolver() {
return Promise.resolve(object);
};
}
| {
"content_hash": "42fd10e61e661475f56ec1b35feb5ac5",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 78,
"avg_line_length": 21.68,
"alnum_prop": 0.6309963099630996,
"repo_name": "ianwremmel/spark-js-sdk",
"id": "4d439dc9a2c2731acd7db45993cb6e0085be1b1d",
"size": "614",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "packages/node_modules/@ciscospark/common/src/resolve-with.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1176688"
},
{
"name": "Shell",
"bytes": "19963"
}
],
"symlink_target": ""
} |
<?php
namespace Produce\SitradocBundle\Util;
class consultas {
public static function comboTrabajador($cn, $filtro) {
$sql = "SELECT top 30 CODIGO_TRABAJADOR,(LTRIM(RTRIM(NOMBRES_TRABAJADOR))+' '+LTRIM(RTRIM(APELLIDOS_TRABAJADOR)))as TRABAJADOR, LTRIM(RTRIM(EMAIL))";
$sql.=" FROM db_general.jcardenas.H_TRABAJADOR ";
$sql.=" WHERE LTRIM(RTRIM(APELLIDOS_TRABAJADOR)) LIKE '$filtro%'";
$sql.=" order by NOMBRES_TRABAJADOR ASC";
$query = $cn->prepare($sql); //preparo consulta
$query->execute(); //ejecuto la consulta
$result = $query->fetchAll(); //guardo los resultados
$select = "";
foreach ($result as $cbo) {
$select .="<option value='" . $cbo["CODIGO_TRABAJADOR"] . "'>" . $cbo["TRABAJADOR"] . "</option>";
}
return $select;
}
public static function comboDestinatarios($cn, $filtro) {
$sql = "SELECT TOP 20 CODIGO_DEPENDENCIA,LTRIM(RTRIM(DEPENDENCIA))AS DEPENDENCIA FROM db_general.jcardenas.H_DEPENDENCIA where DEPENDENCIA LIKE '$filtro%'";
$query = $cn->prepare($sql);
$query->execute();
$result = $query->fetchAll();
$select = "";
foreach ($result as $cbo) {
$select .="<option value='" . $cbo["CODIGO_DEPENDENCIA"] . "'>" . $cbo["DEPENDENCIA"] . "</option>";
}
return $select;
}
public static function comboTipoDocumento($cn) {
$sql = "select ID_CLASE_DOCUMENTO_INTERNO as ID,DESCRIPCION from dbo.CLASE_DOCUMENTO_INTERNO ORDER BY (LTRIM(RTRIM(DESCRIPCION)))";
$query = $cn->prepare($sql);
$query->execute();
$result = $query->fetchAll();
return $result;
}
public static function listaCicloProyecto($cn, $usuario) {
$sql = "select DAT.ID_DOCUMENTO_PROY AS CODIGO,CLA.DESCRIPCION AS TIPO_DE_DOCUMENTO,convert(char(10), DAT.AUDITMOD, 103) as FECHA_CREACION,";
$sql.=" CIC.DESCRIPCION AS CICLO,DAT.INDICATIVO_OFICIO AS INDICATIVO_DEL_DOCUMENTO, DAT.ASUNTO AS ASUNTO, DAT.USUARIO AS USUARIO";
$sql.=" from DAT_DOCUMENTO_PROYECTO DAT INNER JOIN TBL_CICLO_FIRMA CIC ON DAT.ID_CICLOFIRMA=CIC.ID_CICLOFIRMA INNER JOIN";
$sql.=" dbo.CLASE_DOCUMENTO_INTERNO CLA ON DAT.ID_CLASE_DOCUMENTO_INTERNO=CLA.ID_CLASE_DOCUMENTO_INTERNO where CIC.ID_CICLOFIRMA=1";
$sql.=" AND USUARIO= '$usuario' order by convert(DATETIME, DAT.AUDITMOD, 103) desc";
$query = $cn->prepare($sql);
$query->execute();
$result_query = $query->fetchAll();
return $result_query;
}
public static function listaParaFirmar($cn, $usuario) {
$sql = " SELECT DAT.ID_DOCUMENTO_PROY AS CODIGO,CLA.DESCRIPCION AS TIPO_DE_DOCUMENTO,convert(char(10), DAT.AUDITMOD, 103) as FECHA_CREACION,";
$sql .= " CIC.DESCRIPCION AS CICLO,DAT.INDICATIVO_OFICIO AS INDICATIVO_DEL_DOCUMENTO, DAT.ASUNTO AS ASUNTO, DAT.USUARIO AS USUARIO,";
$sql .= " (SELECT count(*) FROM DAT_DETALLE_FIRMANTE q WHERE q.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY AND q.CODIGO_TRABAJADOR = f.CODIGO_TRABAJADOR and ";
$sql .= " q.NUMERO_FIRMA = (SELECT min(bx.NUMERO_FIRMA) FROM DAT_DETALLE_FIRMANTE bx WHERE bx.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY AND bx.ID_ESTADOFIRMA = 2 ) ) as canbesign,";
$sql .= " f.codigo_trabajador as codigo_firmante, f.NUMERO_FIRMA AS NUM_FIRMA, (SELECT max(bx.NUMERO_FIRMA) FROM DAT_DETALLE_FIRMANTE bx WHERE bx.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY) as cant_firma from DAT_DOCUMENTO_PROYECTO DAT INNER JOIN TBL_CICLO_FIRMA CIC ON DAT.ID_CICLOFIRMA=CIC.ID_CICLOFIRMA INNER JOIN";
$sql .= " dbo.CLASE_DOCUMENTO_INTERNO CLA ON DAT.ID_CLASE_DOCUMENTO_INTERNO = CLA.ID_CLASE_DOCUMENTO_INTERNO";
$sql .=" INNER JOIN DAT_DETALLE_FIRMANTE f";
$sql .=" ON DAT.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY";
$sql .=" INNER JOIN db_general.jcardenas.H_TRABAJADOR t";
$sql .=" ON f.codigo_trabajador = t.codigo_trabajador";
$sql .=" where CIC.ID_CICLOFIRMA = 2";
$sql .=" AND t.EMAIL = '$usuario'";
$sql .=" AND DAT.ID_CICLOFIRMA = 2";
$sql .=" AND f.ID_CODIGOFIRMA = 1";
$sql .=" AND f.ID_ESTADOFIRMA = 2 order by convert(DATETIME, DAT.AUDITMOD, 103) desc";
$query = $cn->prepare($sql);
$query->execute();
$result_query = $query->fetchAll();
return $result_query;
}
public static function listaParaVistoBueno($cn, $usuario) {
$sql = " SELECT DAT.ID_DOCUMENTO_PROY AS CODIGO,CLA.DESCRIPCION AS TIPO_DE_DOCUMENTO,convert(char(10), DAT.AUDITMOD, 103) as FECHA_CREACION,";
$sql .= " CIC.DESCRIPCION AS CICLO,DAT.INDICATIVO_OFICIO AS INDICATIVO_DEL_DOCUMENTO, DAT.ASUNTO AS ASUNTO, DAT.USUARIO AS USUARIO,";
$sql .= " (SELECT count(*) FROM DAT_DETALLE_FIRMANTE q WHERE q.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY AND q.CODIGO_TRABAJADOR = f.CODIGO_TRABAJADOR and ";
$sql .= " q.NUMERO_FIRMA = (SELECT min(bx.NUMERO_FIRMA) FROM DAT_DETALLE_FIRMANTE bx WHERE bx.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY AND bx.ID_ESTADOFIRMA = 2 ) ) as canbesign,";
$sql .= " f.codigo_trabajador as codigo_firmante, f.NUMERO_FIRMA AS NUM_FIRMA, (SELECT max(bx.NUMERO_FIRMA) FROM DAT_DETALLE_FIRMANTE bx WHERE bx.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY) as cant_firma from DAT_DOCUMENTO_PROYECTO DAT INNER JOIN TBL_CICLO_FIRMA CIC ON DAT.ID_CICLOFIRMA=CIC.ID_CICLOFIRMA INNER JOIN";
$sql .= " dbo.CLASE_DOCUMENTO_INTERNO CLA ON DAT.ID_CLASE_DOCUMENTO_INTERNO = CLA.ID_CLASE_DOCUMENTO_INTERNO";
$sql .=" INNER JOIN DAT_DETALLE_FIRMANTE f";
$sql .=" ON DAT.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY";
$sql .=" INNER JOIN db_general.jcardenas.H_TRABAJADOR t";
$sql .=" ON f.codigo_trabajador = t.codigo_trabajador";
$sql .=" where CIC.ID_CICLOFIRMA = 2";
$sql .=" AND t.EMAIL = '$usuario'";
$sql .=" AND DAT.ID_CICLOFIRMA = 2";
$sql .=" AND f.ID_CODIGOFIRMA = 2";
$sql .=" AND f.ID_ESTADOFIRMA = 2 order by convert(DATETIME, DAT.AUDITMOD, 103) desc";
$query = $cn->prepare($sql);
$query->execute();
$result_query = $query->fetchAll();
return $result_query;
}
public static function detalleProyecto($controller, $request) {
$DB_TRAMITE_DOCUMENTARIO = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
$codigo_proy = $request->request->get("CODIGO");
$sql = " select (select t.APELLIDOS_TRABAJADOR + ' ' + t.NOMBRES_TRABAJADOR from db_general.jcardenas.h_trabajador t WHERE t.CODIGO_TRABAJADOR = f.CODIGO_TRABAJADOR) as nombre_firmante,";
$sql .=" (select dep.DEPENDENCIA from db_general.jcardenas.h_trabajador t, db_general.jcardenas.H_DEPENDENCIA dep WHERE t.CODIGO_DEPENDENCIA = dep.CODIGO_DEPENDENCIA and t.CODIGO_TRABAJADOR = f.CODIGO_TRABAJADOR) as unidad_organica_firmante,";
$sql .=" (select t.APELLIDOS_TRABAJADOR + ' ' + t.NOMBRES_TRABAJADOR, f.NUMERO_FIRMA AS NUM_FIRMA from db_general.jcardenas.h_trabajador t WHERE t.CODIGO_TRABAJADOR = dt.CODIGO_TRABAJADOR_destino) as nombre_destino,";
$sql .=" (select DES_CARGO from TBL_CARGO_DEPENDENCIA tcar where tcar.CODDEP = dt.CODDEP_DESTINO)as cargo,";
$sql .=" (select dep.DEPENDENCIA from db_general.jcardenas.h_trabajador t, db_general.jcardenas.H_DEPENDENCIA dep WHERE t.CODIGO_DEPENDENCIA = dep.CODIGO_DEPENDENCIA and t.CODIGO_TRABAJADOR = dt.CODIGO_TRABAJADOR_destino) unidad_organica_destino,";
$sql .=" d.ASUNTO as asunto, '' as referencia from DAT_DOCUMENTO_PROYECTO d, DAT_DETALLE_FIRMANTE f, DAT_DETALLE_DESTINO dt where d.ID_DOCUMENTO_PROY = f.ID_DOCUMENTO_PROY and d.ID_DOCUMENTO_PROY = dt.ID_DOCUMENTO_PROY and f.ID_CODIGOFIRMA = 1 and";
$sql .=" f.ID_DOCUMENTO_PROY = $codigo_proy";
$query = $DB_TRAMITE_DOCUMENTARIO->prepare($sql);
$query->execute();
$result_docu = $query->fetchAll();
foreach ($result_docu as $rs) {
$nombre_firmante = $rs["nombre_firmante"];
$u_organica_firmantes = $rs["unidad_organica_firmante"];
$nombre_destino = $rs["nombre_destino"];
$cargo = $rs["cargo"];
$unidad_organica_destino = $rs["unidad_organica_destino"];
$asunto = $rs["asunto"];
$referencia = $rs["referencia"];
$string_datos.=$nombre_firmante . "|" . $u_organica_firmantes . "|" . $asunto . "|" . $nombre_destino . "|" . $cargo . "|" . $unidad_organica_destino . "|" . $referencia . "#";
}
$string_datos = substr($string_datos, 0, ( strlen($string_datos) - 1));
return $string_datos;
}
public static function nuevoDocumentoProyecto($controller, $request, $user) {
$DB_TRAMITE_DOCUMENTARIO = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
$sql_trabajador = "SELECT CODIGO_TRABAJADOR FROM db_general.jcardenas.H_TRABAJADOR WHERE EMAIL='$user'";
$query1 = $DB_TRAMITE_DOCUMENTARIO->prepare($sql_trabajador);
$query1->execute();
$result_trabajador = $query1->fetchAll();
$sql_oficina = "select coddep from db_general.jcardenas.h_trabajador where email='$user' AND ESTADO='ACTIVO'";
$query2 = $DB_TRAMITE_DOCUMENTARIO->prepare($sql_oficina);
$query2->execute();
$result_oficina = $query2->fetchAll();
$numresult = count($result_oficina);
$codigo_trabajador = $result_trabajador[0]["CODIGO_TRABAJADOR"];
$codigo_oficina = $result_oficina[0]["coddep"];
$cbo_tipo_documento = $request->request->get("cbo_tipo_documento");
$txt_asunto = $request->request->get("txt_asunto");
$txt_observaciones = $request->request->get("txt_observaciones");
$new_documento = "exec [web_tramite].[sp_new_proyecto_documento]";
$new_documento.="@a1=1,";
$new_documento.="@a2=4,";
$new_documento.="@a3=1,";
$new_documento.="@a4=$cbo_tipo_documento,"; /* id_clase_de_documento informe, oficio, memo */
$new_documento.="@a5=$codigo_oficina,"; /* coddep codigo de oficina */
$new_documento.="@a6='$txt_asunto',"; /* asunto */
$new_documento.="@a7='$txt_observaciones',"; /* observaciones */
$new_documento.="@a8='',"; /* fecha maxima de plazo */
$new_documento.="@a9='$codigo_trabajador',"; /* codigo_trabajador */
$new_documento.="@a10 ='$user'"; /* usuario */
$query3 = $DB_TRAMITE_DOCUMENTARIO->prepare($new_documento);
$query3->execute();
$cbo_firmantes = $request->request->get("cbo_firmantes");
$cbo_destinatarios = $request->request->get("cbo_destinatarios");
$firmantes = explode(",", $cbo_firmantes);
$destinatarios = explode(",", $cbo_destinatarios);
$id_proy_query = "select TOP 1 ID_DOCUMENTO_PROY from web_tramite.DAT_DOCUMENTO_PROYECTO order by ID_DOCUMENTO_PROY desc";
$query4 = $DB_TRAMITE_DOCUMENTARIO->prepare($id_proy_query);
$query4->execute();
$result_id_proy = $query4->fetchAll();
$id_proy = $result_id_proy[0]["ID_DOCUMENTO_PROY"];
if ($firmantes[0] != "") {
foreach ($firmantes as $cod_emp) {
$sp_new_proyecto_destino_firma_query = "exec [web_tramite].[sp_new_proyecto_destino_firma]";
$sp_new_proyecto_destino_firma_query.="@IDPROY='$id_proy',";
$sp_new_proyecto_destino_firma_query.="@A1='" . $cod_emp . "',"; //--CODIGO TRABAJADOR
$sp_new_proyecto_destino_firma_query.="@A2='$user',"; //--USUARIO
$sp_new_proyecto_destino_firma_query.="@A3=''"; //--CODDEP
$query5 = $DB_TRAMITE_DOCUMENTARIO->prepare($sp_new_proyecto_destino_firma_query);
$query5->execute();
}
}
//firma principal
$sp_new_proyecto_destino_firma_principal = "exec [web_tramite].[sp_new_proyecto_destino_firma_principal]";
$sp_new_proyecto_destino_firma_principal.="@IDPROY='$id_proy',";
$sp_new_proyecto_destino_firma_principal.="@A1='" . $codigo_trabajador . "',"; //--CODIGO TRABAJADOR
$sp_new_proyecto_destino_firma_principal.="@A2='$user',"; //--USUARIO
$sp_new_proyecto_destino_firma_principal.="@A3=''"; //--CODDEP
$query6 = $DB_TRAMITE_DOCUMENTARIO->prepare($sp_new_proyecto_destino_firma_principal);
$query6->execute();
foreach ($destinatarios as $dest) {
$sp_new_proyecto_destino_oficina_firma = " sp_new_proyecto_destino_oficina_firma";
$sp_new_proyecto_destino_oficina_firma .= " @IDPROY='$id_proy' ,";
$sp_new_proyecto_destino_oficina_firma .= " @A1='$codigo_trabajador', "; //--CODIGO TRABAJADOR
$sp_new_proyecto_destino_oficina_firma .= " @A2='$user',"; //--USUARIO
$sp_new_proyecto_destino_oficina_firma .= " @A3='', "; //--CODDEP
$sp_new_proyecto_destino_oficina_firma .= " @A4='" . $dest . "' "; //--CODDEP DESTINO
$query7 = $DB_TRAMITE_DOCUMENTARIO->prepare($sp_new_proyecto_destino_oficina_firma);
$query7->execute();
}
return "se inserto correctamente";
}
public function parafirma($controller, $id_docu) {
$DB_TRAMITE_DOCUMENTARIO = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
$id_documento_proy = $id_docu;
$sql_trabajador = "update web_tramite.DAT_DOCUMENTO_PROYECTO set ID_CICLOFIRMA = '2' WHERE ID_DOCUMENTO_PROY = '$id_documento_proy'";
$query1 = $DB_TRAMITE_DOCUMENTARIO->prepare($sql_trabajador);
$query1->execute();
return "Se envio para firma.";
}
public static function retornarestadoDocumento($controller, $request) {
$DB_TRAMITE_DOCUMENTARIO = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
$id_documento_proy = $request->request->get("id_docu");
$sql_trabajador = "update web_tramite.DAT_DOCUMENTO_PROYECTO set ID_CICLOFIRMA = '1' WHERE ID_DOCUMENTO_PROY = '$id_documento_proy'";
$query1 = $DB_TRAMITE_DOCUMENTARIO->prepare($sql_trabajador);
$query1->execute();
return "Se retorno a estado en proyecto.";
}
public static function vistoBuenoDocumento($controller, $request) {
$DB_TRAMITE_DOCUMENTARIO = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
$id_documento_proy = $request->request->get("id_docu");
$sql_trabajador = "update web_tramite.DAT_DOCUMENTO_PROYECTO set ID_CICLOFIRMA = '7' WHERE ID_DOCUMENTO_PROY = '$id_documento_proy'";
$query1 = $DB_TRAMITE_DOCUMENTARIO->prepare($sql_trabajador);
$query1->execute();
return "Se dio el visto bueno al Documento.";
}
public function muestraDocumento($controller, $request) {
$cn = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
$codigo_documento = $request->request->get("id_doc");
$sql = "select ID_CLASE_DOCUMENTO_INTERNO,ID_DOCUMENTO_PROY,ASUNTO,OBSERVACIONES from DAT_DOCUMENTO_PROYECTO WHERE ID_DOCUMENTO_PROY = '$codigo_documento'";
$query = $cn->prepare($sql);
$query->execute();
$result_query = $query->fetchAll();
$respuesta = "";
$sql2 = " select tr.CODIGO_TRABAJADOR,(LTRIM(RTRIM(tr.NOMBRES_TRABAJADOR))+' '+LTRIM(RTRIM(tr.APELLIDOS_TRABAJADOR)))as TRABAJADOR";
$sql2.=" from DAT_DETALLE_FIRMANTE dat inner join DB_GENERAL.jcardenas.H_TRABAJADOR tr on dat.CODIGO_TRABAJADOR=tr.CODIGO_TRABAJADOR";
$sql2.=" where dat.ID_DOCUMENTO_PROY=$codigo_documento AND dat.ID_CODIGOFIRMA<>1";
$query2 = $cn->prepare($sql2);
$query2->execute();
$result_query2 = $query2->fetchAll();
$firmantes = "";
if (count($result_query2) > 0) {
foreach ($result_query2 as $row) {
$firmantes.=$row["CODIGO_TRABAJADOR"] . "|";
$firmantes.=$row["TRABAJADOR"] . "#";
}
$firmantes = substr($firmantes, 0, strlen($firmantes) - 1);
}
$sql3 = " select h_dep.CODIGO_DEPENDENCIA, LTRIM(RTRIM(h_dep.DEPENDENCIA))AS DEPENDENCIA from";
$sql3 .=" web_tramite.DAT_DETALLE_DESTINO det inner join db_general.jcardenas.H_DEPENDENCIA h_dep on det.CODDEP_DESTINO=h_dep.CODIGO_DEPENDENCIA";
$sql3 .=" WHERE det.ID_DOCUMENTO_PROY=$codigo_documento";
$query3 = $cn->prepare($sql3);
$query3->execute();
$result_query3 = $query3->fetchAll();
$destino = "";
if (count($result_query3) > 0) {
foreach ($result_query3 as $row2) {
$destino.=$row2["CODIGO_DEPENDENCIA"] . "|";
$destino.=$row2["DEPENDENCIA"] . "#";
}
$destino = substr($destino, 0, strlen($destino) - 1);
}
$respuesta.=$result_query[0]["ID_CLASE_DOCUMENTO_INTERNO"] . "$$";
$respuesta.=$result_query[0]["ASUNTO"] . "$$";
$respuesta.=$result_query[0]["OBSERVACIONES"] . "$$";
$respuesta.=$firmantes . "$$";
$respuesta.=$destino;
return $respuesta;
}
public function editardocumento($controller, $request, $user) {
$cn = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
$cbo_tipo_documento = $request->request->get("cbo_tipo_documento");
$txt_asunto = $request->request->get("txt_asunto");
$txt_observaciones = $request->request->get("txt_observaciones");
$cbo_firmantes = $request->request->get("cbo_firmantes");
$cbo_destinatarios = $request->request->get("cbo_destinatarios");
$id_doc = $request->request->get("num_doc");
$sql = "UPDATE web_tramite.DAT_DOCUMENTO_PROYECTO set ASUNTO='$txt_asunto',";
$sql.=" ID_CLASE_DOCUMENTO_INTERNO='$cbo_tipo_documento',OBSERVACIONES='$txt_observaciones'";
$sql.=" where ID_DOCUMENTO_PROY=$id_doc";
$query = $cn->prepare($sql);
$query->execute();
$firmantes = explode(",", $cbo_firmantes);
$sp_new_proyecto_destino_firma_query = "";
$sql2 = "DELETE DAT_DETALLE_FIRMANTE where ID_DOCUMENTO_PROY='$id_doc' AND ID_CODIGOFIRMA<>1";
$query2 = $cn->prepare($sql2);
$query2->execute();
if (trim($firmantes[0]) != "") {
foreach ($firmantes as $cod_emp) {
$sp_new_proyecto_destino_firma_query = "exec [web_tramite].[sp_new_proyecto_destino_firma]";
$sp_new_proyecto_destino_firma_query.="@IDPROY='$id_doc',";
$sp_new_proyecto_destino_firma_query.="@A1='$cod_emp',"; //--CODIGO TRABAJADOR
$sp_new_proyecto_destino_firma_query.="@A2='$user',"; //--USUARIO
$sp_new_proyecto_destino_firma_query.="@A3=''"; //--CODDEP
$query3 = $cn->prepare($sp_new_proyecto_destino_firma_query);
$query3->execute();
}
}
$sql_actualiza_crea_proy = " UPDATE DAT_DETALLE_FIRMANTE ";
$sql_actualiza_crea_proy .= " set NUMERO_FIRMA=(SELECT (COUNT(NUMERO_FIRMA)+1)FROM DAT_DETALLE_FIRMANTE WHERE ID_DOCUMENTO_PROY=$id_doc and ID_CODIGOFIRMA<>1)";
$sql_actualiza_crea_proy .= " WHERE ID_DOCUMENTO_PROY=$id_doc and ID_CODIGOFIRMA=1";
$query4 = $cn->prepare($sql_actualiza_crea_proy);
$query4->execute();
$destinos = explode(",", $cbo_destinatarios);
$sp_new_proyecto_destino_oficina = "";
$sql5 = "DELETE DAT_DETALLE_DESTINO where ID_DOCUMENTO_PROY='$id_doc'";
$query5 = $cn->prepare($sql5);
$query5->execute();
if (trim($destinos[0]) != "") {
$sql6 = "select CODIGO_TRABAJADOR,USUARIO from DAT_DOCUMENTO_PROYECTO WHERE ID_DOCUMENTO_PROY=$id_doc";
$query6 = $cn->prepare($sql6);
$query6->execute();
$rs_proy = $query6->fetchAll();
foreach ($destinos as $dest) {
$sp_new_proyecto_destino_oficina = "exec [web_tramite].[sp_new_proyecto_destino_oficina_firma]";
$sp_new_proyecto_destino_oficina .= "@IDPROY=$id_doc,";
$sp_new_proyecto_destino_oficina .= "@A1=" . $rs_proy[0]["CODIGO_TRABAJADOR"] . ",";
$sp_new_proyecto_destino_oficina .= "@A2=" . $rs_proy[0]["USUARIO"] . ",";
$sp_new_proyecto_destino_oficina .= "@A3='',";
$sp_new_proyecto_destino_oficina .= "@A4=$dest";
$query7 = $cn->prepare($sp_new_proyecto_destino_oficina);
$query7->execute();
}
}
return "SE ACTUALIZO DOCUMENTO";
}
public function listar_jqgrid($controller, $sql_select, $sql_where, $sidx, $sord, $page, $limit) {
$DB_TRAMITE_DOCUMENTARIO = $controller->getDoctrine()->getConnection("DB_TRAMITE_DOCUMENTARIO");
if (!$sidx)
$sidx = 1;
$sql_select = trim($sql_select);
$sql_where = trim($sql_where) == "" ? "" : "where $sql_where";
$order_by = trim($sidx) == "" ? "" : "order by $sidx $sord";
$sql_no_select = substr($sql_select, 6, strlen($sql_select));
$sql_colums = "SELECT TOP $limit $sql_no_select";
$sql_not_in = "";
// CONSULTA CANTIDAD DE FILAS
$sql_num = "WITH DATOS AS($sql_select $sql_where)SELECT COUNT(*) FROM DATOS";
$count_query = $DB_TRAMITE_DOCUMENTARIO->prepare($sql_num);
$count_query->execute();
$num_rows = $count_query->fetchColumn();
// END CONSULTA CANTIDAD DE FILAS
//En base al numero de registros se obtiene el numero de paginas
if ($num_rows > 0) {
$total_pages = ceil($num_rows / $limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages)
$page = $total_pages;
//Almacena numero de registro donde se va a empezar a recuperar los registros para la pagina
$start = $limit * $page - $limit;
if ($sql_where != "") {
$array_from_cad = explode("FROM", $sql_no_select);
$from_cade = $array_from_cad[count($array_from_cad) - 1];
$array_prim_dato = explode(",", $sql_no_select);
$prim_dato = $array_prim_dato[0];
$sql_not_in = "AND $prim_dato NOT IN (SELECT TOP $start $prim_dato FROM $from_cade $sql_where $order_by)";
}
$sql_result = "$sql_colums $sql_where $sql_not_in $order_by";
// $result_query = $DB_TRAMITE_DOCUMENTARIO->prepare($sql_result);
// $result_query->execute();
//
// $resultado = (json_encode($result_query->fetchAll()));
return $sql_result;
}
}
?>
| {
"content_hash": "986c4d5a217e2cecb1cfd623ca317cd3",
"timestamp": "",
"source": "github",
"line_count": 459,
"max_line_length": 324,
"avg_line_length": 49.40958605664488,
"alnum_prop": 0.6106089333744874,
"repo_name": "georgeunix/as",
"id": "3e8bf159c8db5f502c62226e15ae97a935d7888b",
"size": "22679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Produce/SitradocBundle/Util/consultas.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "246215"
},
{
"name": "JavaScript",
"bytes": "4084599"
},
{
"name": "PHP",
"bytes": "624105"
}
],
"symlink_target": ""
} |
package com.hazelcast.client.impl.protocol.task.map;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.MapValuesWithPagingPredicateCodec;
import com.hazelcast.instance.Node;
import com.hazelcast.map.impl.query.QueryResultRow;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.Predicate;
import com.hazelcast.util.IterationType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class MapValuesWithPagingPredicateMessageTask
extends DefaultMapQueryMessageTask<MapValuesWithPagingPredicateCodec.RequestParameters> {
public MapValuesWithPagingPredicateMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
super(clientMessage, node, connection);
}
@Override
protected Object reduce(Collection<QueryResultRow> result) {
List<Map.Entry<Data, Data>> entries = new ArrayList<Map.Entry<Data, Data>>(result.size());
for (QueryResultRow resultRow : result) {
entries.add(resultRow);
}
return entries;
}
@Override
protected Predicate getPredicate() {
return serializationService.toObject(parameters.predicate);
}
@Override
protected IterationType getIterationType() {
return IterationType.ENTRY;
}
@Override
protected MapValuesWithPagingPredicateCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
return MapValuesWithPagingPredicateCodec.decodeRequest(clientMessage);
}
@Override
protected ClientMessage encodeResponse(Object response) {
return MapValuesWithPagingPredicateCodec.encodeResponse((List<Map.Entry<Data, Data>>) response);
}
@Override
public Object[] getParameters() {
return new Object[]{parameters.predicate};
}
@Override
public String getDistributedObjectName() {
return parameters.name;
}
@Override
public String getMethodName() {
return "values";
}
}
| {
"content_hash": "73b9e7a358c50cf5700132a93f3b3b93",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 116,
"avg_line_length": 30.17142857142857,
"alnum_prop": 0.740530303030303,
"repo_name": "lmjacksoniii/hazelcast",
"id": "0d31e6a0fdbd8bb384bb7165fc1de48531bfa509",
"size": "2737",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/map/MapValuesWithPagingPredicateMessageTask.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "948"
},
{
"name": "Java",
"bytes": "28952463"
},
{
"name": "Shell",
"bytes": "13259"
}
],
"symlink_target": ""
} |
package com.hyh.plg.activity;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by tangdongwei on 2018/5/21.
*/
public class ActivityCachePool implements Map<Integer, IActivity> {
private static volatile ActivityCachePool mInstance = null;
private HashMap<Integer, WeakReference<IActivity>> mCache;
private ActivityCachePool() {
this.mCache = new HashMap<>();
}
public static ActivityCachePool getInstance() {
if (mInstance == null) {
synchronized (ActivityCachePool.class) {
if (mInstance == null) {
mInstance = new ActivityCachePool();
}
}
}
return mInstance;
}
@Override
public int size() {
return mCache.size();
}
@Override
public boolean isEmpty() {
return mCache.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return mCache.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return mCache.containsValue(value);
}
@Override
public IActivity get(Object key) {
WeakReference<IActivity> weakReference = mCache.get(key);
return weakReference == null ? null : weakReference.get();
}
@Override
public IActivity put(Integer key, IActivity value) {
WeakReference<IActivity> weakReference = new WeakReference<IActivity>(value);
WeakReference<IActivity> old = mCache.put(key, weakReference);
return old == null ? null : old.get();
}
@Override
public IActivity remove(Object key) {
WeakReference<IActivity> weakReference = mCache.remove(key);
return weakReference == null ? null : weakReference.get();
}
@Override
public void putAll(Map<? extends Integer, ? extends IActivity> m) {
return;
}
@Override
public void clear() {
mCache.clear();
}
@Override
public Set<Integer> keySet() {
return mCache.keySet();
}
@Override
public Collection<IActivity> values() {
return null;
}
@Override
public Set<Entry<Integer, IActivity>> entrySet() {
return null;
}
}
| {
"content_hash": "1165fe040d79fda9355a3ca02e7951bc",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 85,
"avg_line_length": 23.824742268041238,
"alnum_prop": 0.61964517524881,
"repo_name": "EricHyh/FileDownloader",
"id": "88f253f26af0acb081d8788523d6909873c266f9",
"size": "2311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib-plugin-core/src/main/java/com/hyh/plg/activity/ActivityCachePool.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "11700"
},
{
"name": "Java",
"bytes": "1576112"
}
],
"symlink_target": ""
} |
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Update password</div>
<div class="panel-body">
@if (session('update_password.status'))
<div class="alert alert-success">
<i class="fa fa-btn fa-check-circle"></i>{{ session('update_password.status') }}
</div>
@endif
<form class="form-horizontal" role="form" method="POST" action="{{ secure_url('settings/user/password') }}">
{!! csrf_field() !!}
{!! method_field('PATCH') !!}
<div class="form-group{{ $errors->has('update_password.current_password') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Current password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="update_password[current_password]" />
@if ($errors->has('update_password.current_password'))
<span class="help-block">
<strong>{{ $errors->first('update_password.current_password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('update_password.password') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">New password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="update_password[password]" />
@if ($errors->has('update_password.password'))
<span class="help-block">
<strong>{{ $errors->first('update_password.password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('update_password.password_confirmation') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Confirm password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="update_password[password_confirmation]" />
@if ($errors->has('update_password.password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('update_password.password_confirmation') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-save"></i>Update password
</button>
</div>
</div>
</form>
</div>
</div>
</div> | {
"content_hash": "3f01602fb58653d15c5ab4a65a5cf444",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 120,
"avg_line_length": 46.59701492537314,
"alnum_prop": 0.44650864830237025,
"repo_name": "Letersecure/leter",
"id": "9d18b16a5091a3543ebb0e0bd6c49afe5074a4b1",
"size": "3122",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "resources/views/settings/parts/update_password.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "CSS",
"bytes": "144091"
},
{
"name": "JavaScript",
"bytes": "20664"
},
{
"name": "PHP",
"bytes": "156368"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.buffsftw.skatespots">
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
keytool -list -v -keystore mystore.keystorekeytool -list -v -keystore mystore.keystore
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name="buffsftw.skatespots.MainNavDrawer"
android:label="@string/title_activity_nav_drawer"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="buffsftw.skatespots.LoginActivity"
android:label="@string/title_activity_login"></activity>
</application>
</manifest> | {
"content_hash": "4fdaeb721cc6cfdb74506b942780171a",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 108,
"avg_line_length": 45.75925925925926,
"alnum_prop": 0.6543909348441926,
"repo_name": "AdamMarcus/SkateSpots",
"id": "97a9f28612c798aee00356d1005d0f168d08c5f8",
"size": "2471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "58825"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reactive.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Refit; // InterfaceStubGenerator looks for this
using RichardSzalay.MockHttp;
using Xunit;
namespace Refit.Tests
{
#pragma warning disable IDE1006 // Naming Styles
public class RootObject
{
public string _id { get; set; }
public string _rev { get; set; }
public string name { get; set; }
}
#pragma warning restore IDE1006 // Naming Styles
public class BigObject
{
public byte[] BigData { get; set; }
}
[Headers("User-Agent: Refit Integration Tests")]
public interface INpmJs
{
[Get("/congruence")]
Task<RootObject> GetCongruence();
}
public interface IRequestBin
{
[Post("/1h3a5jm1")]
Task Post();
[Post("/foo")]
Task PostRawStringDefault([Body] string str);
[Post("/foo")]
Task PostRawStringJson([Body(BodySerializationMethod.Serialized)] string str);
[Post("/foo")]
Task PostRawStringUrlEncoded([Body(BodySerializationMethod.UrlEncoded)] string str);
[Post("/1h3a5jm1")]
Task PostGeneric<T>(T param);
[Post("/foo")]
Task PostVoidReturnBodyBuffered<T>([Body(buffered: true)] T param);
[Post("/foo")]
Task<string> PostNonVoidReturnBodyBuffered<T>([Body(buffered: true)] T param);
[Post("/big")]
Task PostBig(BigObject big);
[Get("/foo/{arguments}")]
Task SomeApiThatUsesVariableNameFromCodeGen(string arguments);
}
public interface IApiBindPathToObject
{
[Get("/foos/{request.someProperty}/bar/{request.someProperty2}")]
Task GetFooBars(PathBoundObject request);
[Get("/foos/{Requestparams.SomeProperty}/bar/{requestParams.SoMeProPerty2}")]
Task GetFooBarsWithDifferentCasing(PathBoundObject requestParams);
[Get("/foos/{id}/{request.someProperty}/bar/{request.someProperty2}")]
Task GetBarsByFoo(string id, PathBoundObject request);
[Get("/foos/{someProperty}/bar/{request.someProperty2}")]
Task GetFooBars(PathBoundObject request, string someProperty);
[Get("/foos/{request.someProperty}/bar")]
Task GetBarsByFoo(PathBoundObject request);
[Get("/foo")]
Task GetBarsWithCustomQueryFormat(PathBoundObjectWithQueryFormat request);
[Get("/foos/{request.someProperty}/bar/{request.someProperty3}")]
Task GetFooBarsDerived(PathBoundDerivedObject request);
[Get("/foos/{request.values}")]
Task GetFoos(PathBoundList request);
[Get("/foos2/{values}")]
Task GetFoos2(List<int> values);
[Post("/foos/{request.someProperty}/bar/{request.someProperty2}")]
Task PostFooBar(PathBoundObject request, [Body]object someObject);
[Get("/foos/{request.someProperty}/bar/{request.someProperty2}")]
Task GetFooBars(PathBoundObjectWithQuery request);
[Post("/foos/{request.someProperty}/bar/{request.someProperty2}")]
Task<HttpResponseMessage> PostFooBar(PathBoundObject request, [Query] ModelObject someQueryParams);
[Multipart]
[Post("/foos/{request.someProperty}/bar/{request.someProperty2}")]
Task<HttpResponseMessage> PostFooBarStreamPart(PathBoundObject request, [Query] ModelObject someQueryParams, StreamPart stream);
[Multipart]
[Post("/foos/{request.someProperty}/bar/{request.someProperty2}")]
Task<HttpResponseMessage> PostFooBarStreamPart(PathBoundObject request, StreamPart stream);
[Multipart]
[Post("/foos/{request.someProperty}/bar/{request.someProperty2}")]
Task<HttpResponseMessage> PostFooBarStreamPart(PathBoundObjectWithQuery request, StreamPart stream);
}
public class PathBoundList
{
public List<int> Values { get; set; }
}
public class PathBoundDerivedObject : PathBoundObject
{
public string SomeProperty3 { get; set; }
}
public class PathBoundObject
{
public int SomeProperty { get; set; }
public string SomeProperty2 { get; set; }
}
public class PathBoundObjectWithQuery
{
public int SomeProperty { get; set; }
public string SomeProperty2 { get; set; }
[Query]
public string SomeQuery { get; set; }
}
public class PathBoundObjectWithQueryFormat
{
[Query(Format = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'")]
public DateTime SomeQueryWithFormat { get; set; }
}
public interface INoRefitHereBuddy
{
Task Post();
}
public interface IAmHalfRefit
{
[Post("/anything")]
Task Post();
Task Get();
}
public interface IRefitInterfaceWithStaticMethod
{
[Get("")]
Task Get();
#if NETCOREAPP3_1_OR_GREATER
public static IRefitInterfaceWithStaticMethod Create()
{
// This is a C# 8 factory method
return RestService.For<IRefitInterfaceWithStaticMethod>("http://foo/");
}
#endif
}
public class ErrorResponse
{
public string[] Errors { get; set; }
}
public interface IHttpBinApi<TResponse, in TParam, in THeader>
where TResponse : class
where THeader : struct
{
[Get("")]
Task<TResponse> Get(TParam param, [Header("X-Refit")] THeader header);
[Get("/get?hardcoded=true")]
Task<TResponse> GetQuery([Query("_")]TParam param);
[Post("/post?hardcoded=true")]
Task<TResponse> PostQuery([Query("_")]TParam param);
[Get("")]
Task<TResponse> GetQueryWithIncludeParameterName([Query(".", "search")]TParam param);
[Get("/get?hardcoded=true")]
Task<TValue> GetQuery1<TValue>([Query("_")]TParam param);
}
public interface IBrokenWebApi
{
[Post("/what-spec")]
Task<bool> PostAValue([Body] string derp);
}
public interface IHttpContentApi
{
[Post("/blah")]
Task<HttpContent> PostFileUpload([Body] HttpContent content);
[Post("/blah")]
Task<ApiResponse<HttpContent>> PostFileUploadWithMetadata([Body] HttpContent content);
}
public interface IStreamApi
{
[Post("/{filename}")]
Task<Stream> GetRemoteFile(string filename);
[Post("/{filename}")]
Task<ApiResponse<Stream>> GetRemoteFileWithMetadata(string filename);
}
public interface IApiWithDecimal
{
[Get("/withDecimal")]
Task<string> GetWithDecimal(decimal value);
}
public interface IBodylessApi
{
[Post("/nobody")]
[Headers("Content-Type: application/x-www-form-urlencoded; charset=UTF-8")]
Task Post();
[Get("/nobody")]
[Headers("Content-Type: application/x-www-form-urlencoded; charset=UTF-8")]
Task Get();
[Head("/nobody")]
[Headers("Content-Type: application/x-www-form-urlencoded; charset=UTF-8")]
Task Head();
}
public interface ITrimTrailingForwardSlashApi
{
HttpClient Client { get; }
[Get("/someendpoint")]
Task Get();
}
public interface IValidApi
{
[Get("/someendpoint")]
Task Get();
}
public class HttpBinGet
{
public Dictionary<string, object> Args { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Origin { get; set; }
public string Url { get; set; }
}
public class RestServiceIntegrationTests
{
#if NETCOREAPP3_1_OR_GREATER
[Fact]
public void CanCreateInstanceUsingStaticMethod()
{
var instance = IRefitInterfaceWithStaticMethod.Create();
Assert.NotNull(instance);
}
#endif
[Fact]
public async Task CanAddContentHeadersToPostWithoutBody()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "http://foo/nobody")
// The content length header is set automatically by the HttpContent instance,
// so checking the header as a string doesn't work
.With(r => r.Content?.Headers.ContentLength == 0)
// But we added content type ourselves, so this should work
.WithHeaders("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.WithContent("")
.Respond("application/json", "Ok");
var fixture = RestService.For<IBodylessApi>("http://foo", settings);
await fixture.Post();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithNoParametersTest()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/someendpoint")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<ITrimTrailingForwardSlashApi>("http://foo", settings);
await fixture.Get();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task BaseAddressFromHttpClientMatchesTest()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/someendpoint")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var client = new HttpClient(mockHttp)
{
BaseAddress = new Uri("http://foo")
};
var fixture = RestService.For<ITrimTrailingForwardSlashApi>(client);
await fixture.Get();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task BaseAddressWithTrailingSlashFromHttpClientMatchesTest()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/someendpoint")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var client = new HttpClient(mockHttp)
{
BaseAddress = new Uri("http://foo/")
};
var fixture = RestService.For<ITrimTrailingForwardSlashApi>(client);
await fixture.Get();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task BaseAddressWithTrailingSlashCalledBeforeFromHttpClientMatchesTest()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/someendpoint")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var client = new HttpClient(mockHttp)
{
BaseAddress = new Uri("http://foo/")
};
await client.GetAsync("/firstRequest"); ;
var fixture = RestService.For<ITrimTrailingForwardSlashApi>(client);
await fixture.Get();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithNoParametersTestTrailingSlashInBase()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/someendpoint")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<ITrimTrailingForwardSlashApi>("http://foo/", settings);
await fixture.Get();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObject()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/1/bar/barNone")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetFooBars(new PathBoundObject()
{
SomeProperty = 1,
SomeProperty2 = "barNone"
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObjectDifferentCasing()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/1/bar/barNone")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetFooBarsWithDifferentCasing(new PathBoundObject()
{
SomeProperty = 1,
SomeProperty2 = "barNone"
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObjectAndParameter()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/myId/22/bar/bart")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetBarsByFoo("myId", new PathBoundObject()
{
SomeProperty = 22,
SomeProperty2 = "bart"
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObjectAndParameterParameterPrecedence()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/chooseMe/bar/barNone")
.WithExactQueryString(new[] { new KeyValuePair<string, string>("SomeProperty", "1") })
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetFooBars(new PathBoundObject()
{
SomeProperty = 1,
SomeProperty2 = "barNone"
}, "chooseMe");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundDerivedObject()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/1/bar/test")
.WithExactQueryString(new[] { new KeyValuePair<string, string>("SomeProperty2", "barNone") })
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetFooBarsDerived(new PathBoundDerivedObject()
{
SomeProperty = 1,
SomeProperty2 = "barNone",
SomeProperty3 = "test"
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObjectAndQueryParameter()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/22/bar")
.WithExactQueryString(new[] { new KeyValuePair<string, string>("SomeProperty2", "bart") })
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetBarsByFoo(new PathBoundObject()
{
SomeProperty = 22,
SomeProperty2 = "bart"
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostFooBarPathBoundObject()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, "http://foo/foos/22/bar/bart")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.PostFooBar(new PathBoundObject()
{
SomeProperty = 22,
SomeProperty2 = "bart"
}, new { });
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PathBoundObjectsRespectFormatter()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/22%2C23")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
UrlParameterFormatter = new TestEnumerableUrlParameterFormatter()
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetFoos(new PathBoundList()
{
Values = new List<int>() { 22, 23 }
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObjectAndQuery()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foos/1/bar/barNone")
.WithExactQueryString("SomeQuery=test")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetFooBars(new PathBoundObjectWithQuery()
{
SomeProperty = 1,
SomeProperty2 = "barNone",
SomeQuery = "test"
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObjectAndQueryWithFormat()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Get, "http://foo/foo")
.WithExactQueryString("SomeQueryWithFormat=2020-03-05T13:55:00Z")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.GetBarsWithCustomQueryFormat(new PathBoundObjectWithQueryFormat
{
SomeQueryWithFormat = new DateTime(2020, 03, 05, 13, 55, 00)
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithPathBoundObjectAndQueryObject()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, "http://foo/foos/1/bar/barNone")
.WithExactQueryString("Property1=test&Property2=test2")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
await fixture.PostFooBar(new PathBoundObject()
{
SomeProperty = 1,
SomeProperty2 = "barNone"
}, new ModelObject()
{
Property1 = "test",
Property2 = "test2"
});
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostFooBarPathMultipart()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, "http://foo/foos/22/bar/bar")
.WithExactQueryString("")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
using var stream = GetTestFileStream("Test Files/Test.pdf");
await fixture.PostFooBarStreamPart(new PathBoundObject()
{
SomeProperty = 22,
SomeProperty2 = "bar"
}, new StreamPart(stream, "Test.pdf", "application/pdf"));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostFooBarPathQueryMultipart()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, "http://foo/foos/22/bar/bar")
.WithExactQueryString("SomeQuery=test")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
using var stream = GetTestFileStream("Test Files/Test.pdf");
await fixture.PostFooBarStreamPart(new PathBoundObjectWithQuery()
{
SomeProperty = 22,
SomeProperty2 = "bar",
SomeQuery = "test"
}, new StreamPart(stream, "Test.pdf", "application/pdf"));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostFooBarPathQueryObjectMultipart()
{
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, "http://foo/foos/22/bar/bar")
.WithExactQueryString("Property1=test&Property2=test2")
.Respond("application/json", "Ok");
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IApiBindPathToObject>("http://foo", settings);
using var stream = GetTestFileStream("Test Files/Test.pdf");
await fixture.PostFooBarStreamPart(new PathBoundObject
{
SomeProperty = 22,
SomeProperty2 = "bar"
}, new ModelObject()
{
Property1 = "test",
Property2 = "test2"
}, new StreamPart(stream, "Test.pdf", "application/pdf"));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task DoesntAddAutoAddContentToGetRequest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "http://foo/nobody")
// We can't add HttpContent to a GET request,
// because HttpClient doesn't allow it and it will
// blow up at runtime
.With(r => r.Content == null)
.Respond("application/json", "Ok");
var fixture = RestService.For<IBodylessApi>("http://foo", settings);
await fixture.Get();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task DoesntAddAutoAddContentToHeadRequest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Head, "http://foo/nobody")
// We can't add HttpContent to a HEAD request,
// because HttpClient doesn't allow it and it will
// blow up at runtime
.With(r => r.Content == null)
.Respond("application/json", "Ok");
var fixture = RestService.For<IBodylessApi>("http://foo", settings);
await fixture.Head();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task GetWithDecimal()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "http://foo/withDecimal")
.WithExactQueryString(new[] { new KeyValuePair<string, string>("value", "3.456") })
.Respond("application/json", "Ok");
var fixture = RestService.For<IApiWithDecimal>("http://foo", settings);
const decimal val = 3.456M;
var result = await fixture.GetWithDecimal(val);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheGitHubUserApiAsApiResponse()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
var responseMessage = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{ 'login':'octocat', 'avatar_url':'http://foo/bar' }", System.Text.Encoding.UTF8, "application/json"),
};
responseMessage.Headers.Add("Cookie", "Value");
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/users/octocat").Respond(req => responseMessage);
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetUserWithMetadata("octocat");
Assert.True(result.Headers.Any());
Assert.True(result.IsSuccessStatusCode);
Assert.NotNull(result.ReasonPhrase);
Assert.NotNull(result.RequestMessage);
Assert.False(result.StatusCode == default);
Assert.NotNull(result.Version);
Assert.Equal("octocat", result.Content.Login);
Assert.False(string.IsNullOrEmpty(result.Content.AvatarUrl));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheNonExistentApiAsApiResponse()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/give-me-some-404-action")
.Respond(HttpStatusCode.NotFound);
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
using var result = await fixture.NothingToSeeHereWithMetadata();
Assert.False(result.IsSuccessStatusCode);
Assert.NotNull(result.ReasonPhrase);
Assert.NotNull(result.RequestMessage);
Assert.True(result.StatusCode == HttpStatusCode.NotFound);
Assert.NotNull(result.Version);
Assert.Null(result.Content);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheNonExistentApi()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/give-me-some-404-action")
.Respond(HttpStatusCode.NotFound);
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
try
{
var result = await fixture.NothingToSeeHere();
}
catch (Exception ex)
{
Assert.IsType<ApiException>(ex);
}
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheGitHubUserApiAsObservableApiResponse()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
var responseMessage = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{ 'login':'octocat', 'avatar_url':'http://foo/bar' }", System.Text.Encoding.UTF8, "application/json"),
};
responseMessage.Headers.Add("Cookie", "Value");
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/users/octocat").Respond(req => responseMessage);
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetUserObservableWithMetadata("octocat")
.Timeout(TimeSpan.FromSeconds(10));
Assert.True(result.Headers.Any());
Assert.True(result.IsSuccessStatusCode);
Assert.NotNull(result.ReasonPhrase);
Assert.NotNull(result.RequestMessage);
Assert.False(result.StatusCode == default);
Assert.NotNull(result.Version);
Assert.Equal("octocat", result.Content.Login);
Assert.False(string.IsNullOrEmpty(result.Content.AvatarUrl));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheGitHubUserApi()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/users/octocat")
.Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetUser("octocat");
Assert.Equal("octocat", result.Login);
Assert.False(string.IsNullOrEmpty(result.AvatarUrl));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitWithCamelCaseParameter()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/users/octocat")
.Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetUserCamelCase("octocat");
Assert.Equal("octocat", result.Login);
Assert.False(string.IsNullOrEmpty(result.AvatarUrl));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheGitHubOrgMembersApi()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/orgs/github/members")
.Respond("application/json", "[{ 'login':'octocat', 'avatar_url':'http://foo/bar', 'type':'User'}]");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetOrgMembers("github");
Assert.True(result.Count > 0);
Assert.Contains(result, member => member.Type == "User");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheGitHubOrgMembersApiInParallel()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/orgs/github/members")
.Respond("application/json", "[{ 'login':'octocat', 'avatar_url':'http://foo/bar', 'type':'User'}]");
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/orgs/github/members")
.Respond("application/json", "[{ 'login':'octocat', 'avatar_url':'http://foo/bar', 'type':'User'}]");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var task1 = fixture.GetOrgMembers("github");
var task2 = fixture.GetOrgMembers("github");
await Task.WhenAll(task1, task2);
Assert.True(task1.Result.Count > 0);
Assert.Contains(task1.Result, member => member.Type == "User");
Assert.True(task2.Result.Count > 0);
Assert.Contains(task2.Result, member => member.Type == "User");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task RequestCanceledBeforeResponseRead()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
var cts = new CancellationTokenSource();
mockHttp.When(HttpMethod.Get, "https://api.github.com/orgs/github/members")
.Respond(req =>
{
// Cancel the request
cts.Cancel();
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("[{ 'login':'octocat', 'avatar_url':'http://foo/bar', 'type':'User'}]", Encoding.UTF8, "application/json")
};
});
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
await Assert.ThrowsAsync<TaskCanceledException>(async () => await fixture.GetOrgMembers("github", cts.Token));
}
[Fact]
public async Task HitTheGitHubUserSearchApi()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/search/users")
.WithQueryString("q", "tom repos:>42 followers:>1000")
.Respond("application/json", "{ 'total_count': 1, 'items': [{ 'login':'octocat', 'avatar_url':'http://foo/bar', 'type':'User'}]}");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.FindUsers("tom repos:>42 followers:>1000");
Assert.True(result.TotalCount > 0);
Assert.Contains(result.Items, member => member.Type == "User");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheGitHubUserApiAsObservable()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Get, "https://api.github.com/users/octocat")
.Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetUserObservable("octocat")
.Timeout(TimeSpan.FromSeconds(10));
Assert.Equal("octocat", result.Login);
Assert.False(string.IsNullOrEmpty(result.AvatarUrl));
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task HitTheGitHubUserApiAsObservableAndSubscribeAfterTheFact()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.When(HttpMethod.Get, "https://api.github.com/users/octocat")
.Respond("application/json", "{ 'login':'octocat', 'avatar_url':'http://foo/bar' }");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var obs = fixture.GetUserObservable("octocat")
.Timeout(TimeSpan.FromSeconds(10));
// NB: We're gonna await twice, so that the 2nd await is definitely
// after the result has completed.
await obs;
var result2 = await obs;
Assert.Equal("octocat", result2.Login);
Assert.False(string.IsNullOrEmpty(result2.AvatarUrl));
}
[Fact]
public async Task TwoSubscriptionsResultInTwoRequests()
{
var input = new TestHttpMessageHandler
{
// we need to use a factory here to ensure each request gets its own httpcontent instance
ContentFactory = () => new StringContent("test")
};
var client = new HttpClient(input) { BaseAddress = new Uri("http://foo") };
var fixture = RestService.For<IGitHubApi>(client);
Assert.Equal(0, input.MessagesSent);
var obs = fixture.GetIndexObservable()
.Timeout(TimeSpan.FromSeconds(10));
var result1 = await obs;
Assert.Equal(1, input.MessagesSent);
var result2 = await obs;
Assert.Equal(2, input.MessagesSent);
// NB: TestHttpMessageHandler returns what we tell it to ('test' by default)
Assert.Contains("test", result1);
Assert.Contains("test", result2);
}
[Fact]
public async Task ShouldRetHttpResponseMessage()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.When(HttpMethod.Get, "https://api.github.com/")
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetIndex();
Assert.NotNull(result);
Assert.True(result.IsSuccessStatusCode);
}
[Fact]
public async Task ShouldRetHttpResponseMessageWithNestedInterface()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.When(HttpMethod.Get, "https://api.github.com/")
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<TestNested.INestedGitHubApi>("https://api.github.com", settings);
var result = await fixture.GetIndex();
Assert.NotNull(result);
Assert.True(result.IsSuccessStatusCode);
}
[Fact]
public async Task HitTheNpmJs()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "https://registry.npmjs.org/congruence")
.Respond("application/json", "{ \"_id\":\"congruence\", \"_rev\":\"rev\" , \"name\":\"name\"}");
var fixture = RestService.For<INpmJs>("https://registry.npmjs.org", settings);
var result = await fixture.GetCongruence();
Assert.Equal("congruence", result._id);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostToRequestBin()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1")
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
await fixture.Post();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostStringDefaultToRequestBin()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/foo")
.WithContent("raw string")
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
await fixture.PostRawStringDefault("raw string");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostStringJsonToRequestBin()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/foo")
.WithContent("\"json string\"")
.WithHeaders("Content-Type", "application/json; charset=utf-8")
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
await fixture.PostRawStringJson("json string");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostStringUrlToRequestBin()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/foo")
.WithContent("url%26string")
.WithHeaders("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
await fixture.PostRawStringUrlEncoded("url&string");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostToRequestBinWithGenerics()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1")
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
await fixture.PostGeneric(5);
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.ResetExpectations();
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1")
.Respond(HttpStatusCode.OK);
await fixture.PostGeneric("4");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostWithVoidReturnBufferedBodyExpectContentLengthHeader()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var postBody = new Dictionary<string, string>
{
{ "some", "body" },
{ "once", "told me" }
};
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/foo")
.With(request => request.Content?.Headers.ContentLength > 0)
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
await fixture.PostVoidReturnBodyBuffered(postBody);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task PostWithNonVoidReturnBufferedBodyExpectContentLengthHeader()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var postBody = new Dictionary<string, string>
{
{ "some", "body" },
{ "once", "told me" }
};
const string expectedResponse = "some response";
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/foo")
.With(request => request.Content?.Headers.ContentLength > 0)
.Respond("text/plain", expectedResponse);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
var result = await fixture.PostNonVoidReturnBodyBuffered(postBody);
mockHttp.VerifyNoOutstandingExpectation();
Assert.Equal(expectedResponse, result);
}
[Fact]
public async Task UseMethodWithArgumentsParameter()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
mockHttp.Expect(HttpMethod.Get, "http://httpbin.org/foo/something")
.Respond(HttpStatusCode.OK);
await fixture.SomeApiThatUsesVariableNameFromCodeGen("something");
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task CanGetDataOutOfErrorResponses()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.When(HttpMethod.Get, "https://api.github.com/give-me-some-404-action")
.Respond(HttpStatusCode.NotFound, "application/json", "{'message': 'Not Found', 'documentation_url': 'http://foo/bar'}");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
try
{
await fixture.NothingToSeeHere();
Assert.True(false);
}
catch (ApiException exception)
{
Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
var content = await exception.GetContentAsAsync<Dictionary<string, string>>();
Assert.Equal("Not Found", content["message"]);
Assert.NotNull(content["documentation_url"]);
}
}
[Fact]
public async Task CanSerializeBigData()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new SystemTextJsonContentSerializer()
};
var bigObject = new BigObject
{
BigData = Enumerable.Range(0, 800000).Select(x => (byte)(x % 256)).ToArray()
};
mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/big")
.With(m =>
{
async Task<bool> T()
{
using var s = await m.Content.ReadAsStreamAsync();
var it = await System.Text.Json.JsonSerializer.DeserializeAsync<BigObject>(s, new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase });
return it.BigData.SequenceEqual(bigObject.BigData);
}
return T().Result;
})
.Respond(HttpStatusCode.OK);
var fixture = RestService.For<IRequestBin>("http://httpbin.org/", settings);
await fixture.PostBig(bigObject);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task ErrorsFromApiReturnErrorContent()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Post, "https://api.github.com/users")
.Respond(HttpStatusCode.BadRequest, "application/json", "{ 'errors': [ 'error1', 'message' ]}");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await Assert.ThrowsAsync<ApiException>(async () => await fixture.CreateUser(new User { Name = "foo" }));
var errors = await result.GetContentAsAsync<ErrorResponse>();
Assert.Contains("error1", errors.Errors);
Assert.Contains("message", errors.Errors);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task ErrorsFromApiReturnErrorContentWhenApiResponse()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = new NewtonsoftJsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() })
};
mockHttp.Expect(HttpMethod.Post, "https://api.github.com/users")
.Respond(HttpStatusCode.BadRequest, "application/json", "{ 'errors': [ 'error1', 'message' ]}");
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
using var response = await fixture.CreateUserWithMetadata(new User { Name = "foo" });
Assert.False(response.IsSuccessStatusCode);
Assert.NotNull(response.Error);
var errors = await response.Error.GetContentAsAsync<ErrorResponse>();
Assert.Contains("error1", errors.Errors);
Assert.Contains("message", errors.Errors);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public void NonRefitInterfacesThrowMeaningfulExceptions()
{
try
{
RestService.For<INoRefitHereBuddy>("http://example.com");
}
catch (InvalidOperationException exception)
{
Assert.StartsWith("INoRefitHereBuddy", exception.Message);
}
}
[Fact]
public async Task NonRefitMethodsThrowMeaningfulExceptions()
{
try
{
var fixture = RestService.For<IAmHalfRefit>("http://example.com");
await fixture.Get();
}
catch (NotImplementedException exception)
{
Assert.Contains("no Refit HTTP method attribute", exception.Message);
}
}
[Fact]
public async Task GenericsWork()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "http://httpbin.org/get")
.WithHeaders("X-Refit", "99")
.WithQueryString("param", "foo")
.Respond("application/json", "{\"url\": \"http://httpbin.org/get?param=foo\", \"args\": {\"param\": \"foo\"}, \"headers\":{\"X-Refit\":\"99\"}}");
var fixture = RestService.For<IHttpBinApi<HttpBinGet, string, int>>("http://httpbin.org/get", settings);
var result = await fixture.Get("foo", 99);
Assert.Equal("http://httpbin.org/get?param=foo", result.Url);
Assert.Equal("foo", result.Args["param"]);
Assert.Equal("99", result.Headers["X-Refit"]);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task ValueTypesArentValidButTheyWorkAnyway()
{
var handler = new TestHttpMessageHandler("true");
var fixture = RestService.For<IBrokenWebApi>(new HttpClient(handler) { BaseAddress = new Uri("http://nowhere.com") });
var result = await fixture.PostAValue("Does this work?");
Assert.True(result);
}
[Fact]
public async void MissingBaseUrlThrowsArgumentException()
{
var client = new HttpClient(); // No BaseUrl specified
var fixture = RestService.For<IGitHubApi>(client);
// We should get an InvalidOperationException if we call a method without a base address set
await Assert.ThrowsAsync<InvalidOperationException>(async () => await fixture.GetUser(null));
}
[Fact]
public async Task SimpleDynamicQueryparametersTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.WithHeaders("X-Refit", "99")
.Respond("application/json", "{\"url\": \"https://httpbin.org/get?FirstName=John&LastName=Rambo\", \"args\": {\"FirstName\": \"John\", \"lName\": \"Rambo\"}}");
var myParams = new MySimpleQueryParams
{
FirstName = "John",
LastName = "Rambo"
};
var fixture = RestService.For<IHttpBinApi<HttpBinGet, MySimpleQueryParams, int>>("https://httpbin.org/get", settings);
var resp = await fixture.Get(myParams, 99);
Assert.Equal("John", resp.Args["FirstName"]);
Assert.Equal("Rambo", resp.Args["lName"]);
}
[Fact]
public async Task ComplexDynamicQueryparametersTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", "{\"url\": \"https://httpbin.org/get?hardcoded=true&FirstName=John&LastName=Rambo&Addr_Zip=9999&Addr_Street=HomeStreet 99&MetaData_Age=99&MetaData_Initials=JR&MetaData_Birthday=10%2F31%2F1918 4%3A21%3A16 PM&Other=12345&Other=10%2F31%2F2017 4%3A21%3A17 PM&Other=696e8653-6671-4484-a65f-9485af95fd3a\", \"args\": { \"Addr_Street\": \"HomeStreet 99\", \"Addr_Zip\": \"9999\", \"FirstName\": \"John\", \"LastName\": \"Rambo\", \"MetaData_Age\": \"99\", \"MetaData_Birthday\": \"10/31/1981 4:32:59 PM\", \"MetaData_Initials\": \"JR\", \"Other\": [\"12345\",\"10/31/2017 4:32:59 PM\",\"60282dd2-f79a-4400-be01-bcb0e86e7bc6\"], \"hardcoded\": \"true\"}}");
var myParams = new MyComplexQueryParams
{
FirstName = "John",
LastName = "Rambo"
};
myParams.Address.Postcode = 9999;
myParams.Address.Street = "HomeStreet 99";
myParams.MetaData.Add("Age", 99);
myParams.MetaData.Add("Initials", "JR");
myParams.MetaData.Add("Birthday", new DateTime(1981, 10, 31, 16, 24, 59));
myParams.Other.Add(12345);
myParams.Other.Add(new DateTime(2017, 10, 31, 16, 24, 59));
myParams.Other.Add(new Guid("60282dd2-f79a-4400-be01-bcb0e86e7bc6"));
var fixture = RestService.For<IHttpBinApi<HttpBinGet, MyComplexQueryParams, int>>("https://httpbin.org", settings);
var resp = await fixture.GetQuery(myParams);
Assert.Equal("John", resp.Args["FirstName"]);
Assert.Equal("Rambo", resp.Args["LastName"]);
Assert.Equal("9999", resp.Args["Addr_Zip"]);
}
[Fact]
public async Task ComplexPostDynamicQueryparametersTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "https://httpbin.org/post")
.Respond("application/json", "{\"url\": \"https://httpbin.org/post?hardcoded=true&FirstName=John&LastName=Rambo&Addr_Zip=9999&Addr_Street=HomeStreet 99&MetaData_Age=99&MetaData_Initials=JR&MetaData_Birthday=10%2F31%2F1918 4%3A21%3A16 PM&Other=12345&Other=10%2F31%2F2017 4%3A21%3A17 PM&Other=696e8653-6671-4484-a65f-9485af95fd3a\", \"args\": { \"Addr_Street\": \"HomeStreet 99\", \"Addr_Zip\": \"9999\", \"FirstName\": \"John\", \"LastName\": \"Rambo\", \"MetaData_Age\": \"99\", \"MetaData_Birthday\": \"10/31/1981 4:32:59 PM\", \"MetaData_Initials\": \"JR\", \"Other\": [\"12345\",\"10/31/2017 4:32:59 PM\",\"60282dd2-f79a-4400-be01-bcb0e86e7bc6\"], \"hardcoded\": \"true\"}}");
var myParams = new MyComplexQueryParams
{
FirstName = "John",
LastName = "Rambo"
};
myParams.Address.Postcode = 9999;
myParams.Address.Street = "HomeStreet 99";
myParams.MetaData.Add("Age", 99);
myParams.MetaData.Add("Initials", "JR");
myParams.MetaData.Add("Birthday", new DateTime(1981, 10, 31, 16, 24, 59));
myParams.Other.Add(12345);
myParams.Other.Add(new DateTime(2017, 10, 31, 16, 24, 59));
myParams.Other.Add(new Guid("60282dd2-f79a-4400-be01-bcb0e86e7bc6"));
var fixture = RestService.For<IHttpBinApi<HttpBinGet, MyComplexQueryParams, int>>("https://httpbin.org", settings);
var resp = await fixture.PostQuery(myParams);
Assert.Equal("John", resp.Args["FirstName"]);
Assert.Equal("Rambo", resp.Args["LastName"]);
Assert.Equal("9999", resp.Args["Addr_Zip"]);
}
[Fact]
public async Task GenericMethodTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
const string response = "4";
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", response);
var myParams = new Dictionary<string, object>
{
["FirstName"] = "John",
["LastName"] = "Rambo",
["Address"] = new
{
Zip = 9999,
Street = "HomeStreet 99"
}
};
var fixture = RestService.For<IHttpBinApi<HttpBinGet, Dictionary<string, object>, int>>("https://httpbin.org", settings);
// Use the generic to get it as an ApiResponse of string
var resp = await fixture.GetQuery1<ApiResponse<string>>(myParams);
Assert.Equal(response, resp.Content);
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", response);
// Get as string
var resp1 = await fixture.GetQuery1<string>(myParams);
Assert.Equal(response, resp1);
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", response);
var resp2 = await fixture.GetQuery1<int>(myParams);
Assert.Equal(4, resp2);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task InheritedMethodTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IAmInterfaceC>("https://httpbin.org", settings);
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get").Respond("application/json", nameof(IAmInterfaceA.Ping));
var resp = await fixture.Ping();
Assert.Equal(nameof(IAmInterfaceA.Ping), resp);
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", nameof(IAmInterfaceB.Pong));
resp = await fixture.Pong();
Assert.Equal(nameof(IAmInterfaceB.Pong), resp);
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", nameof(IAmInterfaceC.Pang));
resp = await fixture.Pang();
Assert.Equal(nameof(IAmInterfaceC.Pang), resp);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task InheritedInterfaceWithOnlyBaseMethodsTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IContainAandB>("https://httpbin.org", settings);
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get").Respond("application/json", nameof(IAmInterfaceA.Ping));
var resp = await fixture.Ping();
Assert.Equal(nameof(IAmInterfaceA.Ping), resp);
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", nameof(IAmInterfaceB.Pong));
resp = await fixture.Pong();
Assert.Equal(nameof(IAmInterfaceB.Pong), resp);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task InheritedInterfaceWithoutRefitInBaseMethodsTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
var fixture = RestService.For<IImplementTheInterfaceAndUseRefit>("https://httpbin.org", settings);
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/doSomething")
.WithQueryString("parameter", "4")
.Respond("application/json", nameof(IImplementTheInterfaceAndUseRefit.DoSomething));
await fixture.DoSomething(4);
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/DoSomethingElse")
.Respond("application/json", nameof(IImplementTheInterfaceAndUseRefit.DoSomethingElse));
await fixture.DoSomethingElse();
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/DoSomethingElse")
.Respond("application/json", nameof(IImplementTheInterfaceAndUseRefit.DoSomethingElse));
await ((IAmInterfaceEWithNoRefit<int>)fixture).DoSomethingElse();
mockHttp.VerifyNoOutstandingExpectation();
Assert.Throws<InvalidOperationException>(() => RestService.For<IAmInterfaceEWithNoRefit<int>>("https://httpbin.org"));
}
[Fact]
public async Task DictionaryDynamicQueryparametersTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", "{\"url\": \"https://httpbin.org/get?hardcoded=true&FirstName=John&LastName=Rambo&Address_Zip=9999&Address_Street=HomeStreet 99\", \"args\": {\"Address_Street\": \"HomeStreet 99\",\"Address_Zip\": \"9999\",\"FirstName\": \"John\",\"LastName\": \"Rambo\",\"hardcoded\": \"true\"}}");
var myParams = new Dictionary<string, object>
{
["FirstName"] = "John",
["LastName"] = "Rambo",
["Address"] = new
{
Zip = 9999,
Street = "HomeStreet 99"
}
};
var fixture = RestService.For<IHttpBinApi<HttpBinGet, Dictionary<string, object>, int>>("https://httpbin.org", settings);
var resp = await fixture.GetQuery(myParams);
Assert.Equal("John", resp.Args["FirstName"]);
Assert.Equal("Rambo", resp.Args["LastName"]);
Assert.Equal("9999", resp.Args["Address_Zip"]);
}
[Fact]
public async Task ComplexDynamicQueryparametersTestWithIncludeParameterName()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get")
.Respond("application/json", "{\"url\": \"https://httpbin.org/get?search.FirstName=John&search.LastName=Rambo&search.Addr.Zip=9999&search.Addr.Street=HomeStreet 99\", \"args\": {\"search.Addr.Street\": \"HomeStreet 99\",\"search.Addr.Zip\": \"9999\",\"search.FirstName\": \"John\",\"search.LastName\": \"Rambo\"}}");
var myParams = new MyComplexQueryParams
{
FirstName = "John",
LastName = "Rambo"
};
myParams.Address.Postcode = 9999;
myParams.Address.Street = "HomeStreet 99";
var fixture = RestService.For<IHttpBinApi<HttpBinGet, MyComplexQueryParams, int>>("https://httpbin.org/get", settings);
var resp = await fixture.GetQueryWithIncludeParameterName(myParams);
Assert.Equal("John", resp.Args["search.FirstName"]);
Assert.Equal("Rambo", resp.Args["search.LastName"]);
Assert.Equal("9999", resp.Args["search.Addr.Zip"]);
}
[Fact]
public async Task ServiceOutsideNamespaceGetRequest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Get, "http://foo/")
// We can't add HttpContent to a GET request,
// because HttpClient doesn't allow it and it will
// blow up at runtime
.With(r => r.Content == null)
.Respond("application/json", "Ok");
var fixture = RestService.For<IServiceWithoutNamespace>("http://foo", settings);
await fixture.GetRoot();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task ServiceOutsideNamespacePostRequest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp
};
mockHttp.Expect(HttpMethod.Post, "http://foo/")
.Respond("application/json", "Ok");
var fixture = RestService.For<IServiceWithoutNamespace>("http://foo", settings);
await fixture.PostRoot();
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public async Task CanSerializeContentAsXml()
{
var mockHttp = new MockHttpMessageHandler();
var contentSerializer = new XmlContentSerializer();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
ContentSerializer = contentSerializer
};
mockHttp
.Expect(HttpMethod.Post, "/users")
.WithHeaders("Content-Type:application/xml; charset=utf-8")
.Respond(req => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("<User><Name>Created</Name></User>", Encoding.UTF8, "application/xml")
});
var fixture = RestService.For<IGitHubApi>("https://api.github.com", settings);
var result = await fixture.CreateUser(new User()).ConfigureAwait(false);
Assert.Equal("Created", result.Name);
mockHttp.VerifyNoOutstandingExpectation();
}
[Fact]
public void ShouldTrimTrailingForwardSlashFromBaseUrl()
{
var expectedBaseAddress = "http://example.com/api";
var inputBaseAddress = "http://example.com/api/";
var fixture = RestService.For<ITrimTrailingForwardSlashApi>(inputBaseAddress);
Assert.Equal(fixture.Client.BaseAddress.AbsoluteUri, expectedBaseAddress);
}
[Fact]
public void ShouldThrowArgumentExceptionIfHostUrlIsNull()
{
try
{
RestService.For<IValidApi>(hostUrl: null);
}
catch (ArgumentException ex)
{
Assert.Equal("hostUrl", ex.ParamName);
return;
}
Assert.False(true, "Exception not thrown.");
}
[Fact]
public void ShouldThrowArgumentExceptionIfHostUrlIsEmpty()
{
try
{
RestService.For<IValidApi>(hostUrl: "");
}
catch (ArgumentException ex)
{
Assert.Equal("hostUrl", ex.ParamName);
return;
}
Assert.False(true, "Exception not thrown.");
}
[Fact]
public void ShouldThrowArgumentExceptionIfHostUrlIsWhitespace()
{
try
{
RestService.For<IValidApi>(hostUrl: " ");
}
catch (ArgumentException ex)
{
Assert.Equal("hostUrl", ex.ParamName);
return;
}
Assert.False(true, "Exception not thrown.");
}
[Fact]
public void NonGenericCreate()
{
var expectedBaseAddress = "http://example.com/api";
var inputBaseAddress = "http://example.com/api/";
var fixture = RestService.For(typeof(ITrimTrailingForwardSlashApi), inputBaseAddress) as ITrimTrailingForwardSlashApi;
Assert.Equal(fixture.Client.BaseAddress.AbsoluteUri, expectedBaseAddress);
}
[Fact]
public async Task TypeCollisionTest()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings
{
HttpMessageHandlerFactory = () => mockHttp,
};
const string Url = "https://httpbin.org/get";
mockHttp.Expect(HttpMethod.Get, Url)
.Respond("application/json", "{ }");
var fixtureA = RestService.For<ITypeCollisionApiA>(Url);
var respA = await fixtureA.SomeARequest();
var fixtureB = RestService.For<ITypeCollisionApiB>(Url);
var respB = await fixtureB.SomeBRequest();
Assert.IsType<CollisionA.SomeType>(respA);
Assert.IsType<CollisionB.SomeType>(respB);
}
internal static Stream GetTestFileStream(string relativeFilePath)
{
const char namespaceSeparator = '.';
// get calling assembly
var assembly = Assembly.GetCallingAssembly();
// compute resource name suffix
var relativeName = "." + relativeFilePath
.Replace('\\', namespaceSeparator)
.Replace('/', namespaceSeparator)
.Replace(' ', '_');
// get resource stream
var fullName = assembly
.GetManifestResourceNames()
.FirstOrDefault(name => name.EndsWith(relativeName, StringComparison.InvariantCulture));
if (fullName == null)
{
throw new Exception($"Unable to find resource for path \"{relativeFilePath}\". Resource with name ending on \"{relativeName}\" was not found in assembly.");
}
var stream = assembly.GetManifestResourceStream(fullName);
if (stream == null)
{
throw new Exception($"Unable to find resource for path \"{relativeFilePath}\". Resource named \"{fullName}\" was not found in assembly.");
}
return stream;
}
}
}
| {
"content_hash": "8b94142304bfe66c590cc01ce282c13c",
"timestamp": "",
"source": "github",
"line_count": 2169,
"max_line_length": 695,
"avg_line_length": 36.10096818810512,
"alnum_prop": 0.574486290435871,
"repo_name": "PKRoma/refit",
"id": "bcf391f89ab1d7d30663e4a3acdef05c010eddaf",
"size": "78305",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "Refit.Tests/RestService.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "596954"
},
{
"name": "CSS",
"bytes": "10701"
}
],
"symlink_target": ""
} |
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.util.concurrent.Futures.getChecked;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.Future;
/** Positive cases for {@link FuturesGetCheckedIllegalExceptionType}. */
public class FuturesGetCheckedIllegalExceptionTypePositiveCases {
<T extends RuntimeException> void runtime(
Future<?> future, Class<? extends RuntimeException> c1, Class<T> c2) throws Exception {
// BUG: Diagnostic contains: getUnchecked(future)
getChecked(future, RuntimeException.class);
// BUG: Diagnostic contains: getUnchecked(future)
getChecked(future, IllegalArgumentException.class);
// BUG: Diagnostic contains: getUnchecked(future)
getChecked(future, RuntimeException.class, 0, SECONDS);
// BUG: Diagnostic contains: getUnchecked(future)
getChecked(future, c1);
// BUG: Diagnostic contains: getUnchecked(future)
getChecked(future, c2);
}
void visibility(Future<?> future) throws Exception {
// BUG: Diagnostic contains: parameters
getChecked(future, PrivateConstructorException.class);
// BUG: Diagnostic contains: parameters
getChecked(future, PackagePrivateConstructorException.class);
// BUG: Diagnostic contains: parameters
getChecked(future, ProtectedConstructorException.class);
}
void parameters(Future<?> future) throws Exception {
// BUG: Diagnostic contains: parameters
getChecked(future, OtherParameterTypeException.class);
// TODO(cpovirk): Consider a specialized error message if inner classes prove to be common.
// BUG: Diagnostic contains: parameters
getChecked(future, InnerClassWithExplicitConstructorException.class);
// BUG: Diagnostic contains: parameters
getChecked(future, InnerClassWithImplicitConstructorException.class);
}
public static class PrivateConstructorException extends Exception {
private PrivateConstructorException() {}
}
public static class PackagePrivateConstructorException extends Exception {
PackagePrivateConstructorException() {}
}
public static class ProtectedConstructorException extends Exception {
protected ProtectedConstructorException() {}
}
public class OtherParameterTypeException extends Exception {
public OtherParameterTypeException(int it) {}
}
public class InnerClassWithExplicitConstructorException extends Exception {
public InnerClassWithExplicitConstructorException() {}
}
public class InnerClassWithImplicitConstructorException extends Exception {}
}
| {
"content_hash": "afa9093defc755ba3fd138e06084baf2",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 95,
"avg_line_length": 38.984848484848484,
"alnum_prop": 0.7749708511465215,
"repo_name": "google/error-prone",
"id": "3a8cd33365476b46b071fcd648ed31e86cfd2a33",
"size": "3174",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/src/test/java/com/google/errorprone/bugpatterns/testdata/FuturesGetCheckedIllegalExceptionTypePositiveCases.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9329704"
},
{
"name": "Mustache",
"bytes": "1939"
},
{
"name": "Shell",
"bytes": "1915"
},
{
"name": "Starlark",
"bytes": "959"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Umbraco.Core.Macros
{
/// <summary>
/// Parses the macro syntax in a string and renders out it's contents
/// </summary>
internal class MacroTagParser
{
/// <summary>
/// This will accept a text block and seach/parse it for macro markup.
/// When either a text block or a a macro is found, it will call the callback method.
/// </summary>
/// <param name="text"> </param>
/// <param name="textFoundCallback"></param>
/// <param name="macroFoundCallback"></param>
/// <returns></returns>
/// <remarks>
/// This method simply parses the macro contents, it does not create a string or result,
/// this is up to the developer calling this method to implement this with the callbacks.
/// </remarks>
internal static void ParseMacros(
string text,
Action<string> textFoundCallback,
Action<string, Dictionary<string, string>> macroFoundCallback )
{
if (textFoundCallback == null) throw new ArgumentNullException("textFoundCallback");
if (macroFoundCallback == null) throw new ArgumentNullException("macroFoundCallback");
string elementText = text;
var fieldResult = new StringBuilder(elementText);
//NOTE: This is legacy code, this is definitely not the correct way to do a while loop! :)
var stop = false;
while (!stop)
{
var tagIndex = fieldResult.ToString().ToLower().IndexOf("<?umbraco");
if (tagIndex < 0)
tagIndex = fieldResult.ToString().ToLower().IndexOf("<umbraco:macro");
if (tagIndex > -1)
{
var tempElementContent = "";
//text block found, call the call back method
textFoundCallback(fieldResult.ToString().Substring(0, tagIndex));
fieldResult.Remove(0, tagIndex);
var tag = fieldResult.ToString().Substring(0, fieldResult.ToString().IndexOf(">") + 1);
var attributes = XmlHelper.GetAttributesFromElement(tag);
// Check whether it's a single tag (<?.../>) or a tag with children (<?..>...</?...>)
if (tag.Substring(tag.Length - 2, 1) != "/" && tag.IndexOf(" ") > -1)
{
String closingTag = "</" + (tag.Substring(1, tag.IndexOf(" ") - 1)) + ">";
// Tag with children are only used when a macro is inserted by the umbraco-editor, in the
// following format: "<?UMBRACO_MACRO ...><IMG SRC="..."..></?UMBRACO_MACRO>", so we
// need to delete extra information inserted which is the image-tag and the closing
// umbraco_macro tag
if (fieldResult.ToString().IndexOf(closingTag) > -1)
{
fieldResult.Remove(0, fieldResult.ToString().IndexOf(closingTag));
}
}
var macroAlias = attributes.ContainsKey("macroalias") ? attributes["macroalias"] : attributes["alias"];
//call the callback now that we have the macro parsed
macroFoundCallback(macroAlias, attributes);
fieldResult.Remove(0, fieldResult.ToString().IndexOf(">") + 1);
fieldResult.Insert(0, tempElementContent);
}
else
{
//text block found, call the call back method
textFoundCallback(fieldResult.ToString());
stop = true; //break;
}
}
}
}
} | {
"content_hash": "d23daa52e76f2f21f08ad1df2421ecf1",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 111,
"avg_line_length": 37.10344827586207,
"alnum_prop": 0.6425030978934325,
"repo_name": "Myster/Umbraco-CMS",
"id": "ad4b18052857e251f1846c20506e85988ea5c4b3",
"size": "3228",
"binary": false,
"copies": "7",
"ref": "refs/heads/6.1.3",
"path": "src/Umbraco.Core/Macros/MacroTagParser.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "746463"
},
{
"name": "ActionScript",
"bytes": "11355"
},
{
"name": "C#",
"bytes": "11066330"
},
{
"name": "CSS",
"bytes": "289128"
},
{
"name": "JavaScript",
"bytes": "2551925"
},
{
"name": "PowerShell",
"bytes": "1212"
},
{
"name": "Python",
"bytes": "876"
},
{
"name": "Ruby",
"bytes": "765"
},
{
"name": "Shell",
"bytes": "10962"
},
{
"name": "XSLT",
"bytes": "49960"
}
],
"symlink_target": ""
} |
""" Manages the user oauth tokens for you.
This goes one level higher than the :mod:`oauth_helper` by taking care of the management. It will
track access tokens and refresh tokens for users and refresh the access tokens as needed for you.
It will handle all storage and retrieval work for you. The only task it can't do for you is the
actual authorization on behalf of a user :)
.. note::
This was never meant to scale to infinity. I only needed something to handle more than one,
but less than ten user accounts. I believe this implementation can scale up to 100 safely
without a significant impact to performance, but after that I would not rely on this, and
instead suck it up and start using a database. """
if __name__ == '__main__':
# Hack to run smoothly in test mode
import sys
sys.path.append('../../')
import datetime
import cPickle as pickle
from os import path
from helpers.exceptions import NotYetImplementedError, MissingArgumentError, UserDoesNotExistError
from oauth_helper import OAuthHelper
__author__ = "Casey Duquette"
__copyright__ = "Copyright 2013"
__credits__ = ["Casey Duquette"]
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "Casey Duquette"
__email__ = ""
class OAuthUser(object):
""" A user of the oauth system """
def __init__(self, login=None, access_token=None, refresh_token=None, expires_in=None):
super(OAuthUser, self).__init__()
self.login = login
self.access_token = access_token
self.refresh_token = refresh_token
self.expires_in = expires_in
# Making 'email' synonomous with 'login'
@property
def login(self):
return getattr(self, 'email', None)
@login.setter
def login(self, value):
setattr(self, 'email', value)
class OAuthManager(object):
""" Manages OAuth tokens for users and allows an application to get setup with OAuth as painless as possible.
.. code:: python
# Example usage
print "Testing oauth manager"
oauth_manager = OAuthManager()
oauth_helper = oauth_manager.oauth_helper
oauth_manager.json_path = '../../oauth2-details.sjson'
oauth_manager.offline_store_path = '../../oauth2-creds.data'
print "User store count is " + str(len(oauth_manager.store))
email = raw_input("What is your full email address: ")
resp = oauth_helper.first_time_oauth_token()
oauth_helper.test_access_token(email, access_token=resp['access_token'])
oauth_manager.set_access_token(email, resp['access_token'], resp['refresh_token'], resp['expires_in'])
print "User store count is " + str(len(oauth_manager.store))
...
# To get a current oauth login string that is refreshed for you and can be used for imap login
oauth_manager.oauth_login_string('email')
"""
def __init__(self):
super(OAuthManager, self).__init__()
self.oauth_helper = OAuthHelper()
self.store = dict()
@property
def json_path(self):
return self.oauth_helper.json_path
@json_path.setter
def json_path(self, value):
self.oauth_helper.json_path = value
@property
def offline_store_path(self):
return getattr(self, '_offline_store_path', None)
@offline_store_path.setter
def offline_store_path(self, value):
setattr(self, '_offline_store_path', value)
if len(self.store):
# already have users in store, assume they should be saved
self.save()
else:
# no users yet, try and load
self.load()
@property
def offline_encrypted(self):
return getattr(self, 'offline_encrypted', False)
@offline_encrypted.setter
def offline_encrypted(self, value):
if value != False:
raise NotYetImplementedError()
setattr(self, 'offline_encrypted', value)
def get_access_token(self, email):
""" Returns a valid, non-expired access token or None if the user doesn't exist. """
if email is None:
raise MissingArgumentError()
if email not in self.store:
raise UserDoesNotExistError()
self.validate_access_token(email)
return self.store.get(email).access_token
def set_access_token(self, email, access_token, refresh_token, expires_in):
if None in [email, access_token, refresh_token, expires_in]:
raise MissingArgumentError()
user = self.store[email] if email in self.store else OAuthUser()
for p in ['email', 'access_token', 'refresh_token', 'expires_in']:
setattr(user, p, locals()[p])
user.expires_at = datetime.datetime.utcnow() + datetime.timedelta(seconds=user.expires_in)
self.store[email] = user
self.save()
def validate_access_token(self, email):
if email is None:
raise MissingArgumentError()
if email not in self.store:
raise UserDoesNotExistError()
user = self.store[email]
if datetime.datetime.utcnow() >= user.expires_at:
# need to refresh access token
self.refresh_access_token(email)
def refresh_access_token(self, email):
if email is None:
raise MissingArgumentError()
if email not in self.store:
raise UserDoesNotExistError()
user = self.store[email]
response = self.oauth_helper.refresh_token(refresh_token=user.refresh_token)
self.set_access_token(email, response['access_token'], user.refresh_token, response['expires_in'])
def oauth_login_string(self, email, base64_encode=True):
"""
.. note::
If using imaplib, you must pass base64_encode=False
"""
if email is None:
raise MissingArgumentError()
if email not in self.store:
raise UserDoesNotExistError()
return self.oauth_helper.generate_oauth_string(user_email=email, access_token=self.get_access_token(email), base64_encode=base64_encode)
def save(self):
if self.offline_store_path:
pickle.dump( self.store, open( self.offline_store_path, "wb" ) )
def load(self):
if self.offline_store_path and path.exists(self.offline_store_path):
self.store = pickle.load( open( self.offline_store_path, "rb" ) )
for user in self.store.values():
print "Loaded " + user.email
def get_users(self):
return self.store.values()
if __name__ == '__main__':
print "Testing oauth manager"
oauth_manager = OAuthManager()
oauth_helper = oauth_manager.oauth_helper
oauth_manager.json_path = '../../oauth2-details.sjson'
oauth_manager.offline_store_path = '../../oauth2-creds.data'
print "User store count is " + str(len(oauth_manager.store))
email = raw_input("What is your full email address: ")
resp = oauth_helper.first_time_oauth_token()
oauth_helper.test_access_token(email, access_token=resp['access_token'])
oauth_manager.set_access_token(email, resp['access_token'], resp['refresh_token'], resp['expires_in'])
print "User store count is " + str(len(oauth_manager.store))
| {
"content_hash": "770689d62dcfe305d034612d0b59110c",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 138,
"avg_line_length": 34.844086021505376,
"alnum_prop": 0.7167103841999691,
"repo_name": "beeftornado/google-oauth2-wrapper",
"id": "2b4ddd9d5518ebad683b0e6ea38de8e0bad9ddb5",
"size": "7620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "helpers/oauth/oauth_manager.py",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>rational: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.0~camlp4 / rational - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
rational
<small>
8.6.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-09-09 03:51:12 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-09 03:51:12 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp4 4.05+1 Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils 1 Virtual package relying on findutils
coq 8.5.0~camlp4 Formal proof management system.
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlbuild 0.14.0 OCamlbuild is a build system with builtin rules to easily build most OCaml projects.
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/rational"
license: "LGPL 2.1"
build: [make]
install: [make "install"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: Integers" "keyword: rational numbers" "keyword: quotient types" "keyword: subset types" "category: Mathematics/Arithmetic and Number Theory/Rational numbers" ]
authors: [ "Samuel Boutin" ]
bug-reports: "https://github.com/coq-contribs/rational/issues"
dev-repo: "git+https://github.com/coq-contribs/rational.git"
synopsis: "A definition of rational numbers"
description: """
Definition of integers as the usual symetric
completion of a semi-group and of rational numbers as the product of
integers and strictly positive integers quotiented by the usual relation.
This implementation assumes two sets of axioms allowing to define
quotient types and subset types. These sets of axioms should be
proved coherent by mixing up the deliverable model and the setoid model
(both are presented in Martin Hofmann' thesis)."""
url {
src: "https://github.com/coq-contribs/rational/archive/v8.6.0.tar.gz"
checksum: "md5=c72f2408a598286b2acca2b05164d836"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-rational.8.6.0 coq.8.5.0~camlp4</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0~camlp4).
The following dependencies couldn't be met:
- coq-rational -> coq >= 8.6
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-rational.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "8f9ece62f0f96900790806c0c7bd1531",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 227,
"avg_line_length": 43.101190476190474,
"alnum_prop": 0.5608341389310869,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "e98d0e3bcc4f83c2214a9e3ef6e76203bc3a9bb1",
"size": "7243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.5.0~camlp4/rational/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package com.alicode.game.dogedash.worlds;
import java.util.Iterator;
import com.alicode.game.dogedash.Assets;
import com.alicode.game.dogedash.DogeDashCore;
import com.alicode.game.dogedash.GamePoints;
import com.alicode.game.dogedash.Statics;
import com.alicode.game.dogedash.models.Background;
import com.alicode.game.dogedash.models.Bush;
import com.alicode.game.dogedash.models.DogeBiscuit;
import com.alicode.game.dogedash.models.DogeCoin;
import com.alicode.game.dogedash.models.DogeCostumes;
import com.alicode.game.dogedash.models.DogeOnHitEffect;
import com.alicode.game.dogedash.models.Flower;
import com.alicode.game.dogedash.models.MotherDoge;
import com.alicode.game.dogedash.models.Puppy;
import com.alicode.game.dogedash.models.enemies.EnemyBee;
import com.alicode.game.dogedash.models.enemies.EnemyLog;
import com.alicode.game.dogedash.models.enemies.EnemyMud;
import com.alicode.game.dogedash.models.enemies.EnemyPuddle;
import com.alicode.game.dogedash.utils.txt.FPSLogger;
import com.alicode.game.dogedash.utils.txt.GameScore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
public class WorldOne extends Table {
private Background background, background2;
private MotherDoge motherDoge;
private DogeCostumes dogeCostumes;
// private FPSLogger fpsLog;
private GameScore gamePoints;
private Group backgroundGroup;
private Group onGroundGroup;
private Group inBetweenGroup;
private Group floatingGroup;
private Array<Puppy> puppies;
private Array<Flower> flowers;
private Array<Bush> bushes;
private Array<DogeCoin> dogeCoins;
private Array<DogeBiscuit> dogeBiscuits;
private Array<DogeOnHitEffect> dogeOnHitEffects;
private Array<EnemyBee> enemyBees;
private Array<EnemyMud> enemyMuds;
private Array<EnemyPuddle> enemyPuddles;
private Array<EnemyLog> enemyLogs;
private long enemyDelta, flowerDelta, puppyDelta, bushDelta, enemyLogDelta, enemyPuddleDelta, enemyMudDelta, dogeCoinDelta, dogeBiscuitDelta;
private float puppyRespawnTime, puppyRespawnCooldown;
private float enemyRespawnTime, enemyRespawnCooldown;
private float flowerRespawnTime, flowerRespawnCooldown;
private float bushRespawnTime, bushRespawnCooldown;
private float enemyMudRespawnTime, enemyMudRespawnCooldown;
private float enemyPuddleRespawnTime, enemyPuddleRespawnCooldown;
private float enemyLogRespawnTime, enemyLogRespawnCooldown;
private float dogeCoinRespawnTime, dogeCoinRespawnCooldown;
private float dogeBiscuitRespawnTime, dogeBiscuitRespawnCooldown;
private int levelEnemyLimit;
public WorldOne() {
setBounds(0, 0, 800, 480);
setClip(true);
background = new Background(0, 0);
background2 = new Background(Assets.bg_big_day.getWidth(), 0);
motherDoge = new MotherDoge();
dogeCostumes = new DogeCostumes();
puppies = new Array<Puppy>();
flowers = new Array<Flower>();
bushes = new Array<Bush>();
dogeCoins = new Array<DogeCoin>();
dogeBiscuits = new Array<DogeBiscuit>();
dogeOnHitEffects = new Array<DogeOnHitEffect>();
enemyBees = new Array<EnemyBee>();
enemyLogs = new Array<EnemyLog>();
enemyPuddles = new Array<EnemyPuddle>();
enemyMuds = new Array<EnemyMud>();
backgroundGroup = new Group();
onGroundGroup = new Group();
inBetweenGroup = new Group();
floatingGroup = new Group();
// fpsLog = new FPSLogger();
gamePoints = new GameScore();
addActor(backgroundGroup);
addActor(onGroundGroup);
addActor(inBetweenGroup);
addActor(floatingGroup);
// addActor(fpsLog);
addActor(gamePoints);
backgroundGroup.addActor(background);
backgroundGroup.addActor(background2);
floatingGroup.addActor(motherDoge);
floatingGroup.addActor(dogeCostumes);
puppyRespawnCooldown = 5000000000f;
enemyRespawnCooldown = 2000000000f;
flowerRespawnCooldown = 900000000f;
bushRespawnCooldown = 30000000000f;
dogeCoinRespawnCooldown = 20000000000f;
dogeBiscuitRespawnCooldown = 10000000000f;
enemyLogRespawnCooldown = 4000000000f;
enemyMudRespawnCooldown = 3000000000f;
enemyPuddleRespawnCooldown = 10000000000f;
switch (Statics.gameLevelDifficulty) {
case 1:
levelEnemyLimit = Statics.easyMaxEnemies;
break;
case 2:
levelEnemyLimit = Statics.normalMaxEnemies;
break;
case 3:
levelEnemyLimit = Statics.hardMaxEnemies;
break;
}
}
@Override
public void act(float delta) {
super.act(delta);
if (Statics.state == Statics.GameState.Running) {
updateRespawnTimes();
GamePoints.currentScore++;
}
updateBees();
updateFlowers();
updatePups();
updateBushes();
updateEnemyLogs();
updateEnemyMuds();
updateEnemyPuddles();
updateDogeCoins();
updateDogeBiscuits();
}
private void updateRespawnTimes() {
if (GamePoints.finalScore() > 500) {
enemyRespawnCooldown = 2000000000f / 2;
GamePoints.currentScore++;
}
if (GamePoints.finalScore() > 5000) {
enemyRespawnCooldown = 2000000000f / 3;
GamePoints.currentScore++;
}
if (GamePoints.finalScore() > 8000) {
enemyRespawnCooldown = 2000000000f / 4;
GamePoints.currentScore++;
}
if (GamePoints.finalScore() > 10000) {
enemyRespawnCooldown = 2000000000f / 5;
GamePoints.currentScore++;
}
if (GamePoints.finalScore() > 100000) {
enemyRespawnCooldown = 2000000000f / 6;
GamePoints.currentScore++;
}
if (GamePoints.finalScore() > 1000000) {
enemyRespawnCooldown = 2000000000f / 7;
GamePoints.currentScore++;
}
enemyRespawnTime = TimeUtils.nanoTime() - enemyDelta;
puppyRespawnTime = TimeUtils.nanoTime() - puppyDelta;
flowerRespawnTime = TimeUtils.nanoTime() - flowerDelta;
bushRespawnTime = TimeUtils.nanoTime() - bushDelta;
enemyLogRespawnTime = TimeUtils.nanoTime() - enemyLogDelta;
enemyPuddleRespawnTime = TimeUtils.nanoTime() - enemyPuddleDelta;
enemyMudRespawnTime = TimeUtils.nanoTime() - enemyMudDelta;
dogeCoinRespawnTime = TimeUtils.nanoTime() - dogeCoinDelta;
dogeBiscuitRespawnTime = TimeUtils.nanoTime() - dogeBiscuitDelta;
if (enemyRespawnTime > enemyRespawnCooldown) {
spawnBee();
}
if (puppyRespawnTime > puppyRespawnCooldown) {
spawnPup();
}
if (flowerRespawnTime > flowerRespawnCooldown) {
spawnFlower();
}
if (bushRespawnTime > bushRespawnCooldown) {
spawnBush();
}
// if (enemyLogRespawnTime > enemyLogRespawnCooldown) {
// spawnLog();
// }
if (enemyMudRespawnTime > enemyMudRespawnCooldown) {
spawnMud();
}
if (enemyPuddleRespawnTime > enemyPuddleRespawnCooldown) {
spawnPuddle();
}
if (dogeCoinRespawnTime > dogeCoinRespawnCooldown) {
spawnDogeCoin();
}
// if (dogeBiscuitRespawnTime > dogeBiscuitRespawnCooldown) {
// spawnDogeBiscuit();
// }
}
private void updateDogeBiscuits() {
Iterator<DogeBiscuit> dCoinIter = dogeBiscuits.iterator();
while (dCoinIter.hasNext()) {
DogeBiscuit dogeBiscuit = dCoinIter.next();
if (dogeBiscuit.getBounds().x + dogeBiscuit.getWidth() < 0) {
dogeBiscuit.disposeTrail();
dCoinIter.remove();
removeActor(dogeBiscuit);
}
if (dogeBiscuit.getBounds().overlaps(motherDoge.getBounds())) {
dCoinIter.remove();
dogeBiscuit.playerHit();
}
}
}
private void updateDogeCoins() {
Iterator<DogeCoin> dCoinIter = dogeCoins.iterator();
while (dCoinIter.hasNext()) {
DogeCoin dogeCoin = dCoinIter.next();
if (dogeCoin.getBounds().x + dogeCoin.getWidth() < 0) {
dogeCoin.disposeTrail();
dCoinIter.remove();
removeActor(dogeCoin);
}
if (dogeCoin.getBounds().overlaps(motherDoge.getBounds())) {
dCoinIter.remove();
dogeCoin.playerHit();
}
}
}
private void updateEnemyPuddles() {
Iterator<EnemyPuddle> logIter = enemyPuddles.iterator();
while (logIter.hasNext()) {
EnemyPuddle enemyPuddle = logIter.next();
if (enemyPuddle.getBounds().x + enemyPuddle.getWidth() < 0) {
logIter.remove();
removeActor(enemyPuddle);
GamePoints.puppyMissedNum++;
}
if (enemyPuddle.getBounds().overlaps(motherDoge.getBounds())) {
if (!Statics.playerJump) {
if (enemyPuddle.getX() > motherDoge.getX()) {
if (enemyPuddle.getY() > motherDoge.getY())
enemyPuddle.playerHit(true, true);
else
enemyPuddle.playerHit(true, false);
} else {
if (enemyPuddle.getY() > motherDoge.getY())
enemyPuddle.playerHit(false, true);
else
enemyPuddle.playerHit(false, false);
}
}
if (Statics.playerJump) {
spawnDogeSwag();
}
if (Statics.isSuperD) {
logIter.remove();
}
}
}
}
private void updateEnemyMuds() {
Iterator<EnemyMud> logIter = enemyMuds.iterator();
while (logIter.hasNext()) {
EnemyMud enemyMud = logIter.next();
if (enemyMud.getBounds().x + enemyMud.getWidth() < 0) {
logIter.remove();
removeActor(enemyMud);
}
if (enemyMud.getBounds().overlaps(motherDoge.getBounds())) {
if (!Statics.playerJump) {
spawnDogePow();
if (enemyMud.getX() > motherDoge.getX()) {
if (enemyMud.getY() > motherDoge.getY())
enemyMud.playerHit(true, true);
else
enemyMud.playerHit(true, false);
} else {
if (enemyMud.getY() > motherDoge.getY())
enemyMud.playerHit(false, true);
else
enemyMud.playerHit(false, false);
}
}
if (Statics.playerJump) {
spawnDogeSwag();
}
if (Statics.isSuperD)
logIter.remove();
}
}
}
private void updateEnemyLogs() {
Iterator<EnemyLog> logIter = enemyLogs.iterator();
while (logIter.hasNext()) {
EnemyLog enemyLog = logIter.next();
if (enemyLog.getBounds().x + enemyLog.getWidth() < 0) {
logIter.remove();
removeActor(enemyLog);
// Gdx.app.log(DogeDashCore.LOG, "enemyLogs " + enemyLogs.size);
}
if (enemyLog.getBounds().overlaps(motherDoge.getBounds())) {
if (!Statics.playerJump) {
spawnDogePow();
if (enemyLog.getX() > motherDoge.getX()) {
if (enemyLog.getY() > motherDoge.getY())
enemyLog.playerHit(true, true);
else
enemyLog.playerHit(true, false);
} else {
if (enemyLog.getY() > motherDoge.getY())
enemyLog.playerHit(false, true);
else
enemyLog.playerHit(false, false);
}
}
if (Statics.playerJump) {
spawnDogeSwag();
}
if (Statics.isSuperD)
logIter.remove();
}
}
}
private void updateBees() {
Iterator<EnemyBee> beeIter = enemyBees.iterator();
while (beeIter.hasNext()) {
EnemyBee enemyBee = beeIter.next();
if (enemyBee.getBounds().x + enemyBee.getWidth() < 0) {
beeIter.remove();
removeActor(enemyBee);
}
if (enemyBee.getBounds().overlaps(motherDoge.getBounds())) {
if (!Statics.playerJump && !Statics.playerHitByBee) {
beeIter.remove();
spawnDogePow();
floatingGroup.addActor(enemyBee);
inBetweenGroup.removeActor(enemyBee);
if (enemyBee.getX() > motherDoge.getX()) {
if (enemyBee.getY() > motherDoge.getY())
enemyBee.playerHit(true, true);
else
enemyBee.playerHit(true, false);
} else {
if (enemyBee.getY() > motherDoge.getY())
enemyBee.playerHit(false, true);
else
enemyBee.playerHit(false, false);
}
}
if (Statics.playerJump) {
spawnDogeSwag();
}
}
}
}
private void updateFlowers() {
Iterator<Flower> flowerIter = flowers.iterator();
while (flowerIter.hasNext()) {
Flower flower = flowerIter.next();
flower.setZIndex(2);
if (flower.getBounds().x + flower.getWidth() <= 0) {
flowerIter.remove();
removeActor(flower);
}
}
}
private void updatePups() {
Iterator<Puppy> iter = puppies.iterator();
while (iter.hasNext()) {
Puppy puppy = iter.next();
if (puppy.getBounds().x + puppy.getWidth() <= 0) {
iter.remove();
removeActor(puppy);
}
if (puppy.getBounds().overlaps(motherDoge.getBounds()) && !Statics.playerJump) {
iter.remove();
GamePoints.puppyCaughtNum++;
puppy.playerHit();
}
}
}
private void updateBushes() {
Iterator<Bush> iter = bushes.iterator();
while (iter.hasNext()) {
Bush bush = iter.next();
if (bush.getBounds().x + bush.getWidth() <= 0) {
iter.remove();
removeActor(bush);
}
if (bush.getBounds().overlaps(motherDoge.getBounds())) {
if (!Statics.playerJump) {
if (bush.getX() > motherDoge.getX()) {
if (bush.getY() > motherDoge.getY())
bush.playerHit(true, true);
else
bush.playerHit(true, false);
} else {
if (bush.getY() > motherDoge.getY())
bush.playerHit(false, true);
else
bush.playerHit(false, false);
}
}
}
}
}
private void spawnDogeSwag() {
if (!Statics.playerGotSwag) {
DogeOnHitEffect dogeOnHitEffect = new DogeOnHitEffect(MotherDoge.playerX + Assets.character.getRegionHeight(), MotherDoge.playerY + Assets.character.getRegionWidth());
dogeOnHitEffects.add(dogeOnHitEffect);
dogeOnHitEffect.playerGotSwag();
floatingGroup.addActor(dogeOnHitEffect);
}
}
private void spawnDogePow() {
if (!Statics.playerGotPow) {
DogeOnHitEffect dogeOnHitEffect = new DogeOnHitEffect(MotherDoge.playerX + Assets.character.getRegionHeight(), MotherDoge.playerY + Assets.character.getRegionWidth());
dogeOnHitEffects.add(dogeOnHitEffect);
dogeOnHitEffect.playerGotHit();
floatingGroup.addActor(dogeOnHitEffect);
}
}
private void spawnDogeBiscuit() {
float yPos = 0 + (int) (Math.random() * 460);
DogeBiscuit dogeBiscuit = new DogeBiscuit(getWidth() + yPos*2, yPos);
dogeBiscuits.add(dogeBiscuit);
inBetweenGroup.addActor(dogeBiscuit);
dogeBiscuitDelta = TimeUtils.nanoTime();
}
private void spawnDogeCoin() {
float yPos = 0 + (int) (Math.random() * 460);
DogeCoin dogeCoin = new DogeCoin(getWidth() + yPos*2, yPos);
dogeCoins.add(dogeCoin);
inBetweenGroup.addActor(dogeCoin);
dogeCoinDelta = TimeUtils.nanoTime();
}
private void spawnFlower() {
float yPos = 0 + (int) (Math.random() * 460);
Flower flower = new Flower(getWidth() + yPos*2, yPos);
flowers.add(flower);
backgroundGroup.addActor(flower);
flowerDelta = TimeUtils.nanoTime();
}
private void spawnBush() {
float yPos = 0 + (int) (Math.random() * 460);
Bush bush = new Bush(getWidth() + yPos*2, yPos);
bushes.add(bush);
floatingGroup.addActor(bush);
bushDelta = TimeUtils.nanoTime();
}
private void spawnPup() {
float yPos = 10 + (int) (Math.random() * 460);
Puppy puppy = new Puppy(getWidth() + yPos*2, yPos);
puppies.add(puppy);
inBetweenGroup.addActor(puppy);
puppyDelta = TimeUtils.nanoTime();
}
private void spawnBee() {
Statics.enemySpeed+=0.05;
if (enemyBees.size <= levelEnemyLimit) {
float yPos = 0 + (int) (Math.random() * 460);
EnemyBee enemyBee = new EnemyBee(getWidth() + yPos*2, yPos);
enemyBees.add(enemyBee);
inBetweenGroup.addActor(enemyBee);
enemyDelta = TimeUtils.nanoTime();
}
}
private void spawnPuddle() {
float yPos = 0 + (int) (Math.random() * 460);
EnemyPuddle enemyPuddle = new EnemyPuddle(getWidth() + yPos*2, yPos);
enemyPuddles.add(enemyPuddle);
onGroundGroup.addActor(enemyPuddle);
enemyPuddleDelta = TimeUtils.nanoTime();
}
private void spawnMud() {
float yPos = 0 + (int) (Math.random() * 460);
EnemyMud enemyMud = new EnemyMud(getWidth() + yPos*2, yPos);
enemyMuds.add(enemyMud);
onGroundGroup.addActor(enemyMud);
enemyMudDelta = TimeUtils.nanoTime();
}
private void spawnLog() {
float yPos = 0 + (int) (Math.random() * 460);
EnemyLog enemyLog = new EnemyLog(getWidth() + yPos*2, yPos);
enemyLogs.add(enemyLog);
inBetweenGroup.addActor(enemyLog);
enemyLogDelta = TimeUtils.nanoTime();
}
public Array<EnemyBee> getEnemyBees() {
return enemyBees;
}
public void setEnemyBees(Array<EnemyBee> enemyBees) {
this.enemyBees = enemyBees;
}
public MotherDoge getMotherDoge() {
return motherDoge;
}
public void setMotherDoge(MotherDoge motherDoge) {
this.motherDoge = motherDoge;
}
public DogeCostumes getDogeCostumes() {
return dogeCostumes;
}
public void setDogeCostumes(DogeCostumes dogeCostumes) {
this.dogeCostumes = dogeCostumes;
}
}
| {
"content_hash": "95fc067a8baf1af25c25661463f2e079",
"timestamp": "",
"source": "github",
"line_count": 594,
"max_line_length": 170,
"avg_line_length": 27.252525252525253,
"alnum_prop": 0.7007659995058068,
"repo_name": "Mazinkam/DogeDash",
"id": "f29a4e7bcda65048c79420a6764754aa2fe8ba09",
"size": "16188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dogeDash/dogeDash/src/com/alicode/game/dogedash/worlds/WorldOne.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1033"
},
{
"name": "C++",
"bytes": "1"
},
{
"name": "CSS",
"bytes": "54310"
},
{
"name": "Java",
"bytes": "333440"
},
{
"name": "JavaScript",
"bytes": "238721"
}
],
"symlink_target": ""
} |
"""OLECF plugin related functions and classes for testing."""
import pyolecf
from plaso.containers import sessions
from plaso.storage import fake_storage
from tests.parsers import test_lib
class OleCfPluginTestCase(test_lib.ParserTestCase):
"""The unit test case for OLE CF based plugins."""
def _ParseOleCfFileWithPlugin(
self, path_segments, plugin_object, codepage=u'cp1252',
knowledge_base_values=None):
"""Parses a file as an OLE compound file and returns an event generator.
Args:
path_segments: a list of strings containinge the path segments inside
plugin_object: an OLE CF plugin object (instance of OleCfPlugin).
codepage: optional string containing the codepage.
knowledge_base_values: optional dictionary containing the knowledge base
values.
Returns:
A storage writer object (instance of FakeStorageWriter).
"""
session = sessions.Session()
storage_writer = fake_storage.FakeStorageWriter(session)
storage_writer.Open()
file_entry = self._GetTestFileEntry(path_segments)
parser_mediator = self._CreateParserMediator(
storage_writer, file_entry=file_entry,
knowledge_base_values=knowledge_base_values)
file_object = file_entry.GetFileObject()
try:
olecf_file = pyolecf.file()
olecf_file.set_ascii_codepage(codepage)
olecf_file.open_file_object(file_object)
# Get a list of all root items from the OLE CF file.
root_item = olecf_file.root_item
item_names = [item.name for item in root_item.sub_items]
plugin_object.Process(
parser_mediator, root_item=root_item, item_names=item_names)
olecf_file.close()
finally:
file_object.close()
return storage_writer
| {
"content_hash": "a58bca5925e4af3d65f0ad096619d903",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 78,
"avg_line_length": 31.385964912280702,
"alnum_prop": 0.6970374510899944,
"repo_name": "dc3-plaso/plaso",
"id": "948b0afe27a7ca7519f399c967a7cc767a066a74",
"size": "1813",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/parsers/olecf_plugins/test_lib.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1683"
},
{
"name": "Makefile",
"bytes": "1151"
},
{
"name": "Python",
"bytes": "3875098"
},
{
"name": "Shell",
"bytes": "17861"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="InstituteLaRateMaintenanceDocument" parent="InstituteLaRateMaintenanceDocument-parentBean"/>
<bean id="InstituteLaRateMaintenanceDocument-parentBean" abstract="true" parent="KcMaintenanceDocumentEntry">
<property name="businessObjectClass" value="org.kuali.kra.bo.InstituteLaRate"/>
<property name="maintainableClass" value="org.kuali.rice.kns.maintenance.KualiMaintainableImpl"/>
<property name="maintainableSections">
<list>
<ref bean="InstituteLaRateMaintenanceDocument-EditInstituteLaRates"/>
</list>
</property>
<property name="lockingKeys">
<list>
<value>fiscalYear</value>
<value>onOffCampusFlag</value>
<value>rateClassCode</value>
<value>rateTypeCode</value>
<value>startDate</value>
<value>unitNumber</value>
</list>
</property>
<!-- Vivantech Fix : #70 / [#90560868] adding active indicator field and disabling the delete. -->
<property name="allowsRecordDeletion" value="false" />
<property name="documentTypeName" value="InstituteLaRateMaintenanceDocument"/>
<property name="businessRulesClass" value="org.kuali.kra.budget.rates.InstituteRateMaintenanceDocumentRule"/>
<property name="documentAuthorizerClass" value="org.kuali.rice.kns.document.authorization.MaintenanceDocumentAuthorizerBase"/>
</bean>
<!-- Maintenance Section Definitions -->
<bean id="InstituteLaRateMaintenanceDocument-EditInstituteLaRates" parent="InstituteLaRateMaintenanceDocument-EditInstituteLaRates-parentBean"/>
<bean id="InstituteLaRateMaintenanceDocument-EditInstituteLaRates-parentBean" abstract="true" parent="MaintainableSectionDefinition">
<property name="id" value="Edit Institute La Rates"/>
<property name="title" value="Edit Institute La Rates"/>
<!-- Vivantech Fix : #70 / [#90560868] adding active indicator field and disabling the delete. -->
<property name="maintainableItems">
<list>
<bean parent="MaintainableFieldDefinition" p:name="fiscalYear" p:required="true"/>
<bean parent="MaintainableFieldDefinition" p:name="onOffCampusFlag" p:required="true"/>
<bean parent="MaintainableFieldDefinition" p:name="rateClassCode" p:required="true"/>
<bean parent="MaintainableFieldDefinition" p:name="rateTypeCode" p:required="true"/>
<bean parent="MaintainableFieldDefinition" p:name="startDate" p:required="true"/>
<bean parent="MaintainableFieldDefinition" p:name="unitNumber" p:required="true"/>
<bean parent="MaintainableFieldDefinition" p:name="instituteRate" p:required="true"/>
<bean parent="MaintainableFieldDefinition" p:name="active" p:required="true" p:defaultValue="true"/>
<bean parent="MaintainableFieldDefinition" p:name="versionNumber"/>
</list>
</property>
</bean>
</beans> | {
"content_hash": "1164e1d566e669dd69cee507bfa3f003",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 339,
"avg_line_length": 54.47457627118644,
"alnum_prop": 0.7230864965774736,
"repo_name": "vivantech/kc_fixes",
"id": "d4c98cc46bab5b0aeb9d46c8026600413535b68e",
"size": "3214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/org/kuali/kra/datadictionary/docs/InstituteLaRateMaintenanceDocument.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "595"
},
{
"name": "CSS",
"bytes": "1277181"
},
{
"name": "HTML",
"bytes": "21478104"
},
{
"name": "Java",
"bytes": "25178010"
},
{
"name": "JavaScript",
"bytes": "7250670"
},
{
"name": "PHP",
"bytes": "15534"
},
{
"name": "PLSQL",
"bytes": "374321"
},
{
"name": "Perl",
"bytes": "1278"
},
{
"name": "Scheme",
"bytes": "8283377"
},
{
"name": "Shell",
"bytes": "1100"
},
{
"name": "XSLT",
"bytes": "17866049"
}
],
"symlink_target": ""
} |
#include <AVSCommon/Utils/Logger/Logger.h>
#include "BlueZ/BlueZConstants.h"
#include "BlueZ/MediaEndpoint.h"
// https://github.com/Arkq/bluez-alsa
// Version 1.2.0
#include <bluez-alsa/a2dp-rtp.h>
#include <poll.h>
namespace alexaClientSDK {
namespace bluetoothImplementations {
namespace blueZ {
/**
* General error for DBus methods.
*/
constexpr const char* DBUS_ERROR_FAILED = "org.bluez.Error.Rejected";
/**
* Timeout to wait for new data coming from BlueZ audio stream. This value defines how often media stream thread would
* check if it need to close.
*/
static const std::chrono::milliseconds POLL_TIMEOUT_MS(100);
/// Name of the BlueZ MediaEndpoint1::SetConfiguration method.
constexpr const char* MEDIAENDPOINT1_SETCONFIGURATION_METHOD_NAME = "SetConfiguration";
/// Name of the BlueZ MediaEndpoint1::SelectConfiguration method.
constexpr const char* MEDIAENDPOINT1_SELECTCONFIGURATION_METHOD_NAME = "SelectConfiguration";
/// Name of the BlueZ MediaEndpoint1::ClearConfiguration method.
constexpr const char* MEDIAENDPOINT1_CLEARCONFIGURATION_METHOD_NAME = "ClearConfiguration";
/// Name of the BlueZ MediaEndpoint1::Release method.
constexpr const char* MEDIAENDPOINT1_RELEASE_METHOD_NAME = "Release";
/// @c selectCompatibleConfig() should check 4 options
constexpr int CHECK_4_OPTIONS = 4;
/// @c selectCompatibleConfig() should check 2 options
constexpr int CHECK_2_OPTIONS = 2;
/// First frequency mask to be used in @c selectCompatibleConfig().
constexpr uint8_t FIRST_FREQUENCY = 0x10;
/// First channel mode mask to be used in @c selectCompatibleConfig().
constexpr uint8_t FIRST_CHANNEL_MODE = 0x01;
/// First block length mask to be used in @c selectCompatibleConfig().
constexpr uint8_t FIRST_BLOCK_LENGTH = 0x10;
/// First subbands mask to be used in @c selectCompatibleConfig().
constexpr uint8_t FIRST_SUBBANDS = 0x04;
/// First allocation method mask to be used in @c selectCompatibleConfig().
constexpr uint8_t FIRST_ALLOCATION_METHOD = 0x01;
/// Sampling rate 16000
constexpr int SAMPLING_RATE_16000 = 16000;
/// Sampling rate 32000
constexpr int SAMPLING_RATE_32000 = 32000;
/// Sampling rate 44100
constexpr int SAMPLING_RATE_44100 = 44100;
/// Sampling rate 48000
constexpr int SAMPLING_RATE_48000 = 48000;
/// Max sane frame length for SBC codec
constexpr size_t MAX_SANE_FRAME_LENGTH = 200;
/// Min sane frame length for SBC codec
constexpr size_t MIN_SANE_FRAME_LENGTH = 1;
/// Max sane code size for SBC codec. Max compression ratio for 8-band settings
constexpr size_t MAX_SANE_CODE_SIZE = MAX_SANE_FRAME_LENGTH * 32;
/// Min sane code size for SBC codec
constexpr size_t MIN_SANE_CODE_SIZE = 1;
// Standard SDK per module logging constants
#define TAG "MediaEndpoint"
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)
/**
* XML description of the MediaEndpoint1 interface to be implemented by this obejct. The format is defined by DBus.
* This data is used during the registration of the media endpoint object.
*/
static const gchar mediaEndpointIntrospectionXml[] =
"<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection "
"1.0//EN\"\n"
"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\";>\n"
"<node>"
" <interface name=\"org.bluez.MediaEndpoint1\">"
" <method name=\"SetConfiguration\">"
" <arg name=\"transport\" direction=\"in\" type=\"o\"/>"
" <arg name=\"properties\" direction=\"in\" type=\"a{sv}\"/>"
" </method>"
" <method name=\"SelectConfiguration\">"
" <arg name=\"capabilities\" direction=\"in\" type=\"ay\"/>"
" <arg name=\"configuration\" direction=\"out\" type=\"ay\"/>"
" </method>"
" <method name=\"ClearConfiguration\">"
" <arg name=\"transport\" direction=\"in\" type=\"o\"/>"
" </method>"
" <method name=\"Release\">"
" </method>"
" </interface>"
"</node>";
MediaEndpoint::MediaEndpoint(std::shared_ptr<DBusConnection> connection, const std::string& endpointPath) :
DBusObject(
connection,
mediaEndpointIntrospectionXml,
endpointPath,
{{MEDIAENDPOINT1_SETCONFIGURATION_METHOD_NAME, &MediaEndpoint::onSetConfiguration},
{MEDIAENDPOINT1_SELECTCONFIGURATION_METHOD_NAME, &MediaEndpoint::onSelectConfiguration},
{MEDIAENDPOINT1_CLEARCONFIGURATION_METHOD_NAME, &MediaEndpoint::onClearConfiguration},
{MEDIAENDPOINT1_RELEASE_METHOD_NAME, &MediaEndpoint::onRelease}}),
m_endpointPath{endpointPath},
m_operatingModeChanged{false},
m_operatingMode{OperatingMode::INACTIVE} {
m_thread = std::thread(&MediaEndpoint::mediaThread, this);
}
MediaEndpoint::~MediaEndpoint() {
ACSDK_DEBUG5(LX(__func__));
setOperatingMode(OperatingMode::RELEASED);
if (m_thread.joinable()) {
m_thread.join();
}
ACSDK_DEBUG5(LX(__func__).m("MediaEndpoit finalized."));
}
void MediaEndpoint::abortStreaming() {
setOperatingMode(OperatingMode::INACTIVE);
std::shared_ptr<DBusProxy> deviceProxy =
DBusProxy::create(BlueZConstants::BLUEZ_DEVICE_INTERFACE, m_streamingDevicePath);
if (deviceProxy) {
deviceProxy->callMethod("Disconnect");
}
}
// This code in this method is based on a work of Arkadiusz Bokowy licensed under the terms of the MIT license.
// https://github.com/Arkq/bluez-alsa/blob/88aefeea56b7ea20668796c2c7a8312bf595eef4/src/io.c#L144
void MediaEndpoint::mediaThread() {
pollfd pollStruct = {/* fd */ 0, /* requested events */ POLLIN, /* returned events */ 0};
std::shared_ptr<MediaContext> mediaContext;
while (m_operatingMode != OperatingMode::RELEASED) {
// Reset any media context that could still esist.
{
std::unique_lock<std::mutex> modeLock(m_mutex);
m_modeChangeSignal.wait(modeLock, [this]() { return m_operatingModeChanged; });
m_operatingModeChanged = false;
if (OperatingMode::SINK != m_operatingMode) {
continue;
}
if (!m_currentMediaContext || !m_currentMediaContext->isSBCInitialized()) {
ACSDK_ERROR(LX("mediaThreadFailed").d("reason", "no valid media context, no media streaming started"));
continue;
}
mediaContext = m_currentMediaContext;
}
ACSDK_DEBUG5(LX("Starting media streaming..."));
pollStruct.fd = mediaContext->getStreamFD();
m_ioBuffer.resize(static_cast<unsigned long>(mediaContext->getReadMTU()));
const size_t sbcCodeSize = sbc_get_codesize(mediaContext->getSBCContextPtr());
const size_t sbcFrameLength = sbc_get_frame_length(mediaContext->getSBCContextPtr());
ACSDK_DEBUG9(LX(__func__).d("code size", sbcCodeSize).d("frame length", sbcFrameLength));
if (sbcFrameLength < MIN_SANE_FRAME_LENGTH || sbcFrameLength > MAX_SANE_FRAME_LENGTH) {
ACSDK_ERROR(LX("mediaThreadFailed").d("reason", "Invalid sbcFrameLength"));
abortStreaming();
continue;
}
if (sbcCodeSize < MIN_SANE_CODE_SIZE || sbcCodeSize > MAX_SANE_CODE_SIZE) {
ACSDK_ERROR(LX("mediaThreadFailed").d("reason", "Invalid sbcCodeSize"));
abortStreaming();
continue;
}
// output buffer size = decoded block size * (number of encoded blocks in the input buffer + 1 to fill
// possible gap)
const size_t outBufferSize = sbcCodeSize * (m_ioBuffer.size() / sbcFrameLength + 1);
m_sbcBuffer.resize(outBufferSize);
ACSDK_DEBUG7(
LX(__func__).d("codesize", sbcCodeSize).d("frame len", sbcFrameLength).d("output buf size", outBufferSize));
int positionInReadBuf = 0;
// Staying in current mode
while (OperatingMode::SINK == m_operatingMode) {
int timeout = poll(&pollStruct, 1, static_cast<int>(POLL_TIMEOUT_MS.count()));
if (0 == timeout) {
continue;
}
if (timeout < 0) {
ACSDK_ERROR(LX("mediaThreadFailed").d("reason", "Failed to poll bluetooth media stream"));
abortStreaming();
break;
}
// Check if we are still in SINK mode
if (OperatingMode::SINK != m_operatingMode) {
break;
}
ssize_t bytesReadSigned =
read(pollStruct.fd, m_ioBuffer.data() + positionInReadBuf, m_ioBuffer.size() - positionInReadBuf);
if (bytesReadSigned < 0) {
ACSDK_ERROR(
LX("mediaThreadFailed").d("reason", "Failed to read bluetooth media stream").d("errno", errno));
abortStreaming();
break;
}
if (0 == bytesReadSigned) {
// End of stream. Switch to inactive mode
setOperatingMode(OperatingMode::INACTIVE);
break;
}
size_t bytesRead = static_cast<size_t>(bytesReadSigned);
if (bytesRead < sizeof(rtp_header)) {
// Invalid RPT frame. Skip it.
ACSDK_DEBUG9(LX(__func__).d("reason", "Invalid RPT frame, skipping..."));
continue;
}
// Decode RTP frame and SCB payload
rtp_header_t* rtpHeader = reinterpret_cast<rtp_header_t*>(m_ioBuffer.data());
const rtp_payload_sbc_t* rtpPayload =
reinterpret_cast<const rtp_payload_sbc_t*>(&rtpHeader->csrc[rtpHeader->cc]);
const uint8_t* payloadData = reinterpret_cast<const uint8_t*>(rtpPayload + 1);
uint8_t* output = m_sbcBuffer.data();
size_t headersSize = reinterpret_cast<size_t>(payloadData) - reinterpret_cast<size_t>(m_ioBuffer.data());
size_t inputLength = bytesRead - headersSize;
if (inputLength > m_ioBuffer.size()) {
// Invalid RTP frame, skip it
ACSDK_DEBUG9(LX(__func__).d("reason", "Invalid RPT packet, skipping"));
continue;
}
size_t outputLength = outBufferSize;
size_t frameCount = rtpPayload->frame_count;
while (frameCount-- && inputLength >= sbcFrameLength) {
ssize_t bytesProcessed = 0;
size_t bytesDecoded = 0;
if ((bytesProcessed = sbc_decode(
mediaContext->getSBCContextPtr(),
payloadData,
inputLength,
output,
outputLength,
&bytesDecoded)) < 0) {
ACSDK_ERROR(LX("mediaThreadFailed")
.d("reason", "SBC decoding error")
.d("error", strerror(-bytesProcessed)));
break;
}
payloadData += bytesProcessed;
inputLength -= bytesProcessed;
output += bytesDecoded;
outputLength -= bytesDecoded;
}
size_t writeSize = output - m_sbcBuffer.data();
// Check if we are still in SINK mode
if (OperatingMode::SINK != m_operatingMode) {
break;
}
m_ioStream->send(m_sbcBuffer.data(), writeSize);
} // IO loop, continue while still in SINK mode
} // while(true) - thread loop
mediaContext.reset();
ACSDK_DEBUG5(LX("Exiting media thread."));
}
std::shared_ptr<avsCommon::utils::bluetooth::FormattedAudioStreamAdapter> MediaEndpoint::getAudioStream() {
std::lock_guard<std::mutex> guard(m_streamMutex);
if (m_ioStream) {
return m_ioStream;
}
m_ioStream = std::make_shared<avsCommon::utils::bluetooth::FormattedAudioStreamAdapter>(m_audioFormat);
return m_ioStream;
}
std::string MediaEndpoint::getEndpointPath() const {
return m_endpointPath;
}
std::string MediaEndpoint::getStreamingDevicePath() const {
return m_streamingDevicePath;
}
void MediaEndpoint::setOperatingMode(OperatingMode mode) {
std::lock_guard<std::mutex> modeLock(m_mutex);
m_operatingMode = mode;
m_operatingModeChanged = true;
ACSDK_DEBUG5(LX(__func__).d("newMode", operatingModeToString(mode)));
m_modeChangeSignal.notify_all();
}
void MediaEndpoint::onMediaTransportStateChanged(
avsCommon::utils::bluetooth::MediaStreamingState newState,
const std::string& devicePath) {
ACSDK_DEBUG5(LX(__func__).d("devicePath", devicePath));
if (OperatingMode::RELEASED == m_operatingMode) {
// We have released the media thread already. Nothing to do here.
return;
}
// TODO: Move to Device Manager as soon as SOURCE media endpoint is implemented
if (devicePath != m_streamingDevicePath) {
return;
}
if (avsCommon::utils::bluetooth::MediaStreamingState::PENDING == newState) {
// "pending": Streaming but not acquired
std::shared_ptr<DBusProxy> transportProxy =
DBusProxy::create(BlueZConstants::BLUEZ_MEDIATRANSPORT_INTERFACE, m_streamingDevicePath);
if (!transportProxy) {
ACSDK_ERROR(LX("onMediaTransportStateChangedFailed")
.d("reason", "Failed to get MediaTransport1 proxy")
.d("path", devicePath));
return;
}
ManagedGError error;
// Do not free, we do not own this object.
GUnixFDList* fdList = nullptr;
ManagedGVariant transportDetails =
transportProxy->callMethodWithFDList("Acquire", nullptr, &fdList, error.toOutputParameter());
if (error.hasError()) {
ACSDK_ERROR(LX("onMediaTransportStateChangedFailed")
.d("reason", "Failed to acquire media stream")
.d("error", error.getMessage()));
return;
} else if (!fdList) {
ACSDK_ERROR(
LX("onMediaTransportStateChangedFailed").d("reason", "nullFdList").d("error", error.getMessage()));
return;
}
gint32 streamFDIndex = 0;
guint16 readMTU = 0;
guint16 writeMTU = 0;
g_variant_get(transportDetails.get(), "(hqq)", &streamFDIndex, &readMTU, &writeMTU);
if (streamFDIndex > g_unix_fd_list_get_length(fdList)) {
ACSDK_ERROR(LX("onMediaTransportStateChangedFailed")
.d("reason", "indexOutOfBounds")
.d("fdIndex", streamFDIndex)
.d("fdListLength", g_unix_fd_list_get_length(fdList)));
return;
}
// g_unix_fd_list_get duplicates the fd
gint streamFD = g_unix_fd_list_get(fdList, streamFDIndex, error.toOutputParameter());
if (streamFD < 0) {
ACSDK_ERROR(LX("onMediaTransportStateChangedFailed").d("reason", "Invalid media stream file descriptor"));
return;
}
if (error.hasError()) {
ACSDK_ERROR(
LX("onMediaTransportStateChangedFailed").d("reason", "failedToGetFD").d("error", error.getMessage()));
close(streamFD);
return;
}
ACSDK_DEBUG9(LX("Transport details")
.d("File Descriptor Index", streamFDIndex)
.d("File Descriptor", streamFD)
.d("read MTU", readMTU)
.d("write MTU", writeMTU));
{
std::lock_guard<std::mutex> modeLock(m_mutex);
if (!m_currentMediaContext) {
m_currentMediaContext = std::make_shared<MediaContext>();
}
m_currentMediaContext->setStreamFD(streamFD);
m_currentMediaContext->setReadMTU(readMTU);
m_currentMediaContext->setWriteMTU(writeMTU);
}
// Make sure we have stream created
getAudioStream();
setOperatingMode(OperatingMode::SINK);
} else if (avsCommon::utils::bluetooth::MediaStreamingState::IDLE == newState) {
setOperatingMode(OperatingMode::INACTIVE);
}
}
void MediaEndpoint::onSetConfiguration(GVariant* arguments, GDBusMethodInvocation* invocation) {
ACSDK_DEBUG5(LX(__func__));
{
std::lock_guard<std::mutex> modeLock(m_mutex);
if (!m_currentMediaContext) {
m_currentMediaContext = std::make_shared<MediaContext>();
}
m_currentMediaContext->setSBCInitialized(false);
const char* path = nullptr;
GVariant* configuration = nullptr;
GVariant* variant = g_dbus_method_invocation_get_parameters(invocation);
g_variant_get(variant, "(o*)", &path, &configuration);
GVariantMapReader mapReader(configuration);
ManagedGVariant sbcConfigVar = mapReader.getVariant("Configuration");
if (sbcConfigVar.hasValue()) {
gsize configSize = 0;
gconstpointer ptr = g_variant_get_fixed_array(sbcConfigVar.get(), &configSize, 1);
if (ptr) {
sbc_t* sbcContext = m_currentMediaContext->getSBCContextPtr();
int sbcError = -sbc_init_a2dp(sbcContext, 0, ptr, configSize);
if (sbcError != 0) {
ACSDK_ERROR(LX("onSetConfigurationFailed")
.d("reason", "Failed to init SBC decoder")
.d("error", strerror(sbcError)));
g_dbus_method_invocation_return_dbus_error(
invocation, DBUS_ERROR_FAILED, "Failed to init SBC decoder");
return;
} else {
m_audioFormat.encoding = avsCommon::utils::AudioFormat::Encoding::LPCM;
m_audioFormat.endianness = SBC_LE == sbcContext->endian
? avsCommon::utils::AudioFormat::Endianness::LITTLE
: avsCommon::utils::AudioFormat::Endianness::BIG;
m_audioFormat.sampleSizeInBits = 16;
m_audioFormat.numChannels = SBC_MODE_MONO == sbcContext->mode ? 1 : 2;
switch (sbcContext->frequency) {
case SBC_FREQ_16000:
m_audioFormat.sampleRateHz = SAMPLING_RATE_16000;
break;
case SBC_FREQ_32000:
m_audioFormat.sampleRateHz = SAMPLING_RATE_32000;
break;
case SBC_FREQ_44100:
m_audioFormat.sampleRateHz = SAMPLING_RATE_44100;
break;
case SBC_FREQ_48000:
default:
m_audioFormat.sampleRateHz = SAMPLING_RATE_48000;
break;
}
m_audioFormat.layout = avsCommon::utils::AudioFormat::Layout::INTERLEAVED;
m_audioFormat.dataSigned = true;
ACSDK_DEBUG5(LX("Bluetooth stream parameters")
.d("numChannels", m_audioFormat.numChannels)
.d("rate", m_audioFormat.sampleRateHz));
m_currentMediaContext->setSBCInitialized(true);
}
} else {
ACSDK_ERROR(
LX("onSetConfigurationFailed").d("reason", "Failed to convert sbc configuration to bytestream"));
g_dbus_method_invocation_return_dbus_error(
invocation, DBUS_ERROR_FAILED, "Failed to convert sbc configuration to bytestream");
return;
}
} else {
ACSDK_ERROR(LX("onSetConfigurationFailed").d("reason", "Failed to read SBC configuration"));
g_dbus_method_invocation_return_dbus_error(
invocation, DBUS_ERROR_FAILED, "Failed to read SBC configuration");
return;
}
ACSDK_DEBUG3(LX(__func__).d("mediaTransport", path));
m_streamingDevicePath = path;
}
g_dbus_method_invocation_return_value(invocation, nullptr);
}
/**
* This method effectively just selects the first non-zero bit in a provided range withing a byte. Search is done
* from right to left
* @param caps the byte to search in
* @param mask a mask with a one-hot bit to start search with
* @param width total number of bits to search in
* @return A byte with one bit set according to selected configuration.
*/
static uint8_t selectCompatibleConfig(uint8_t caps, uint8_t mask, int width) {
for (; !(caps & mask) && width > 0; mask <<= 1, width--)
;
return mask;
}
void MediaEndpoint::onSelectConfiguration(GVariant* arguments, GDBusMethodInvocation* invocation) {
ACSDK_DEBUG5(LX(__func__));
GVariantTupleReader capsTuple(g_dbus_method_invocation_get_parameters(invocation));
ManagedGVariant streamSupportedCapabilitiesBytes = capsTuple.getVariant(0);
gsize configSize = 0;
gconstpointer ptr = g_variant_get_fixed_array(streamSupportedCapabilitiesBytes.get(), &configSize, sizeof(uint8_t));
if (ptr && configSize >= 4) {
auto capabilitiesBytes = static_cast<const uint8_t*>(ptr);
uint8_t byte1 = capabilitiesBytes[0];
uint8_t byte2 = capabilitiesBytes[1];
// The following logic heavily depends on the correct format of SBC capabilities
// Select the best possible configuration
uint8_t selectedConfig1 = selectCompatibleConfig(byte1, FIRST_FREQUENCY, CHECK_4_OPTIONS);
selectedConfig1 |= selectCompatibleConfig(byte1, FIRST_CHANNEL_MODE, CHECK_4_OPTIONS);
uint8_t selectedConfig2 = selectCompatibleConfig(byte2, FIRST_BLOCK_LENGTH, CHECK_4_OPTIONS);
selectedConfig2 |= selectCompatibleConfig(byte2, FIRST_SUBBANDS, CHECK_2_OPTIONS);
selectedConfig2 |= selectCompatibleConfig(byte2, FIRST_ALLOCATION_METHOD, CHECK_2_OPTIONS);
GVariantBuilder* capBuilder = g_variant_builder_new(G_VARIANT_TYPE("ay"));
g_variant_builder_add(capBuilder, "y", selectedConfig1);
g_variant_builder_add(capBuilder, "y", selectedConfig2);
g_variant_builder_add(capBuilder, "y", capabilitiesBytes[2]);
g_variant_builder_add(capBuilder, "y", capabilitiesBytes[3]);
g_dbus_method_invocation_return_value(invocation, g_variant_new("(ay)", capBuilder));
} else {
ACSDK_ERROR(LX("onSelectConfigurationFailed").d("reason", "Invalid SBC config"));
}
}
void MediaEndpoint::onClearConfiguration(GVariant* arguments, GDBusMethodInvocation* invocation) {
ACSDK_DEBUG5(LX(__func__));
g_dbus_method_invocation_return_value(invocation, nullptr);
}
std::string MediaEndpoint::operatingModeToString(OperatingMode mode) {
switch (mode) {
case OperatingMode::INACTIVE:
return "INACTIVE";
case OperatingMode::SINK:
return "SINK";
case OperatingMode::SOURCE:
return "SOURCE";
case OperatingMode::RELEASED:
return "RELEASED";
}
return "UNKNOWN";
}
void MediaEndpoint::onRelease(GVariant* arguments, GDBusMethodInvocation* invocation) {
ACSDK_DEBUG5(LX(__func__));
g_dbus_method_invocation_return_value(invocation, nullptr);
}
} // namespace blueZ
} // namespace bluetoothImplementations
} // namespace alexaClientSDK
| {
"content_hash": "bf860bcbd1dd0b4830293a19a112e017",
"timestamp": "",
"source": "github",
"line_count": 593,
"max_line_length": 120,
"avg_line_length": 39.67116357504216,
"alnum_prop": 0.6100743889479278,
"repo_name": "alexa/avs-device-sdk",
"id": "bdbf127699dde6ebf099dfd82570e25070ed0cab",
"size": "24103",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BluetoothImplementations/BlueZ/src/MediaEndpoint.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "45439"
},
{
"name": "C++",
"bytes": "32228121"
},
{
"name": "CMake",
"bytes": "279679"
},
{
"name": "PLSQL",
"bytes": "144"
},
{
"name": "Python",
"bytes": "7916"
},
{
"name": "Shell",
"bytes": "61345"
}
],
"symlink_target": ""
} |
package org.ripple.bouncycastle.math.ec.custom.sec;
import java.math.BigInteger;
import org.ripple.bouncycastle.math.ec.ECCurve;
import org.ripple.bouncycastle.math.ec.ECFieldElement;
import org.ripple.bouncycastle.math.ec.ECPoint;
import org.ripple.bouncycastle.util.encoders.Hex;
public class SecP256R1Curve extends ECCurve.AbstractFp
{
public static final BigInteger q = new BigInteger(1,
Hex.decode("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"));
private static final int SecP256R1_DEFAULT_COORDS = COORD_JACOBIAN;
protected SecP256R1Point infinity;
public SecP256R1Curve()
{
super(q);
this.infinity = new SecP256R1Point(this, null, null);
this.a = fromBigInteger(new BigInteger(1,
Hex.decode("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC")));
this.b = fromBigInteger(new BigInteger(1,
Hex.decode("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B")));
this.order = new BigInteger(1, Hex.decode("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"));
this.cofactor = BigInteger.valueOf(1);
this.coord = SecP256R1_DEFAULT_COORDS;
}
protected ECCurve cloneCurve()
{
return new SecP256R1Curve();
}
public boolean supportsCoordinateSystem(int coord)
{
switch (coord)
{
case COORD_JACOBIAN:
return true;
default:
return false;
}
}
public BigInteger getQ()
{
return q;
}
public int getFieldSize()
{
return q.bitLength();
}
public ECFieldElement fromBigInteger(BigInteger x)
{
return new SecP256R1FieldElement(x);
}
protected ECPoint createRawPoint(ECFieldElement x, ECFieldElement y, boolean withCompression)
{
return new SecP256R1Point(this, x, y, withCompression);
}
protected ECPoint createRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, boolean withCompression)
{
return new SecP256R1Point(this, x, y, zs, withCompression);
}
public ECPoint getInfinity()
{
return infinity;
}
}
| {
"content_hash": "21184fc1afb3984039ea926b20af6878",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 119,
"avg_line_length": 27.675,
"alnum_prop": 0.6869918699186992,
"repo_name": "cping/RipplePower",
"id": "ffbafaa770b7912a24e486cb065dc2abc097eaa4",
"size": "2214",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "eclipse/jcoinlibs/src/org/ripple/bouncycastle/math/ec/custom/sec/SecP256R1Curve.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1424"
},
{
"name": "C++",
"bytes": "161794"
},
{
"name": "HTML",
"bytes": "1274"
},
{
"name": "Java",
"bytes": "15692829"
},
{
"name": "Objective-C",
"bytes": "403"
}
],
"symlink_target": ""
} |
class CefRequestHandlerCToCpp
: public CefCToCpp<CefRequestHandlerCToCpp, CefRequestHandler,
cef_request_handler_t> {
public:
explicit CefRequestHandlerCToCpp(cef_request_handler_t* str)
: CefCToCpp<CefRequestHandlerCToCpp, CefRequestHandler,
cef_request_handler_t>(str) {}
virtual ~CefRequestHandlerCToCpp() {}
// CefRequestHandler methods
virtual bool OnBeforeBrowse(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request,
NavType navType, bool isRedirect) OVERRIDE;
virtual bool OnBeforeResourceLoad(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefRequest> request, CefString& redirectUrl,
CefRefPtr<CefStreamReader>& resourceStream,
CefRefPtr<CefResponse> response, int loadFlags) OVERRIDE;
virtual void OnResourceRedirect(CefRefPtr<CefBrowser> browser,
const CefString& old_url, CefString& new_url) OVERRIDE;
virtual void OnResourceResponse(CefRefPtr<CefBrowser> browser,
const CefString& url, CefRefPtr<CefResponse> response,
CefRefPtr<CefContentFilter>& filter) OVERRIDE;
virtual bool OnProtocolExecution(CefRefPtr<CefBrowser> browser,
const CefString& url, bool& allowOSExecution) OVERRIDE;
virtual bool GetDownloadHandler(CefRefPtr<CefBrowser> browser,
const CefString& mimeType, const CefString& fileName,
int64 contentLength, CefRefPtr<CefDownloadHandler>& handler) OVERRIDE;
virtual bool GetAuthCredentials(CefRefPtr<CefBrowser> browser, bool isProxy,
const CefString& host, int port, const CefString& realm,
const CefString& scheme, CefString& username,
CefString& password) OVERRIDE;
virtual CefRefPtr<CefCookieManager> GetCookieManager(
CefRefPtr<CefBrowser> browser, const CefString& main_url) OVERRIDE;
};
#endif // BUILDING_CEF_SHARED
#endif // CEF_LIBCEF_DLL_CTOCPP_REQUEST_HANDLER_CTOCPP_H_
| {
"content_hash": "0c37f0eb9bda727cc89c2c52945dc2e2",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 78,
"avg_line_length": 49.63157894736842,
"alnum_prop": 0.7661717921527041,
"repo_name": "hernad/CEF1",
"id": "e67127e5415ebcef599125aa07719646e28cd56e",
"size": "2896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libcef_dll/ctocpp/request_handler_ctocpp.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "430086"
},
{
"name": "C++",
"bytes": "2479698"
},
{
"name": "Objective-C",
"bytes": "168625"
},
{
"name": "Shell",
"bytes": "39"
}
],
"symlink_target": ""
} |
{% extends "layout.html" %}
{% block page_title %}
Apprenticeships
{% endblock %}
{% block content %}
<style>
.people-nav a {
{% include "includes/nav-on-state-css.html" %}
}
</style>
<main id="content" role="main">
{% include "includes/phase_banner_beta.html" %}
{% include "includes/secondary-nav-provider.html" %}
<!--div class="breadcrumbs">
<ol role="breadcrumbs">
<li><a href="/{% include "includes/sprint-link.html" %}/balance">Access my funds</a></li>
</ol>
</div-->
<div class="breadcrumbs back-breadcrumb">
<ol role="breadcrumbs">
{% include "includes/breadcrumbs/register-back.html" %}
</ol>
</div>
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge" >Agreement not signed</h1>
<form action="go-to-AML-and-do-the-thing">
<div class="notice long">
<i style = " " class="icon icon-important">
<span class="visually-hidden">Warning</span>
</i>
<strong class="bold-small">
<Organisation name> doesn't have a signed agreement with the Skills Funding Agency (SFA).
Without a signed agreement you can add apprentice details, but won't be able to authorise
payments to training providers.</strong>
<strong class="bold-small">
Only account owners can sign SFA agreements. If you're not sure who the owner is, you can <a href="/">check your team details</a>.
</strong>
</div>
<div style="margin-top:35px"></div>
<input class="button" id="search-provider" type="submit" value="Review your agreement">
<p style="margin-top:20px;"><a href="find-provider">Continue anyway</a></p>
</form>
<!--details style="margin-bottom:25px">
<summary><span class="summary">What is a UKPRN?</span></summary>
<div class="panel panel-border-narrow" >
<p>
A UK provider registration number (UKPRN) is a unique number that each training provider has to help identify them. Your training provider will be able to tell you their UKPRN.
</p>
</div>
</details-->
<!-- template to pull in the start tabs so this doesn't get too messy - it is pulling in the tabs -->
<!-- {% include "includes/start-tabs.html" %} -->
</div>
<div class="column-one-third">
<!--aside class="related">
<h2 class="heading-medium" style="margin-top:10px">Existing account</h2>
<nav role="navigation">
<ul class="robSideNav">
<li>
<a href="../login">Sign in</a>
</li>
</ul>
</nav>
</aside-->
</div>
</div>
</main>
<script>
//jquery that runs the tabs. Uses the jquery.tabs.js from gov.uk
$( document ).ready(function() {
// change the tabs themselves to active - should be in the above but isn't working because it's looking for a not li so I added this as a quick fix.
$("ul#tabs-nav li").click(function(e){
if (!$(this).hasClass("active")) {
var tabNum = $(this).index();
var nthChild = tabNum+1;
$("ul#tabs-nav li.active").removeClass("active");
$(this).addClass("active");
$("ul#tabs-nav li.active").removeClass("active");
$("ul#tabs-nav li:nth-child("+nthChild+")").addClass("active");
}
});
});
$('ul.tabs-nav').each(function(){
// For each set of tabs, we want to keep track of
// which tab is active and its associated content
var $active, $content, $links = $(this).find('a');
// If the location.hash matches one of the links, use that as the active tab.
// If no match is found, use the first link as the initial active tab.
$active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
// $active.addClass('active');
console.log($active)
$content = $($active[0].hash);
// Hide the remaining content
$links.not($active).each(function () {
$(this.hash).hide();
});
// Bind the click event handler
$(this).on('click', 'a', function(e){
// Make the old tab inactive.
// $active.removeClass('active');
$content.hide();
// Update the variables with the new link and content
// $active = $(this);
$content = $(this.hash);
// Make the tab active.
// $active.addClass('active');
$content.show();
// Prevent the anchor's default click action
e.preventDefault();
});
});
</script>
{% endblock %}
| {
"content_hash": "31397c5e5ee26d32d2bd065eaf9c17f6",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 182,
"avg_line_length": 29.159235668789808,
"alnum_prop": 0.581039755351682,
"repo_name": "SkillsFundingAgency/das-alpha-ui",
"id": "53f7012153b39e1aa1eaf85bc3ac8768c2e4de0c",
"size": "4578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/programmeEight/contracts/new-contract/employer-contract-not-signed.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5646795"
},
{
"name": "HTML",
"bytes": "45025099"
},
{
"name": "JavaScript",
"bytes": "7708559"
},
{
"name": "Ruby",
"bytes": "299"
},
{
"name": "Shell",
"bytes": "1961"
}
],
"symlink_target": ""
} |
var fs = require('fs-extra');
var when = require('when');
var nodeFn = require('when/node/function');
var keys = require('when/keys');
var fspath = require("path");
var mkdirp = fs.mkdirs;
var log = require("../log");
var promiseDir = nodeFn.lift(mkdirp);
var initialFlowLoadComplete = false;
var settings;
var flowsFile;
var flowsFullPath;
var flowsFileBackup;
var credentialsFile;
var credentialsFileBackup;
var oldCredentialsFile;
var sessionsFile;
var libDir;
var libFlowsDir;
var globalSettingsFile;
function getFileMeta(root,path) {
var fn = fspath.join(root,path);
var fd = fs.openSync(fn,"r");
var size = fs.fstatSync(fd).size;
var meta = {};
var read = 0;
var length = 10;
var remaining = "";
var buffer = Buffer(length);
while(read < size) {
read+=fs.readSync(fd,buffer,0,length);
var data = remaining+buffer.toString();
var parts = data.split("\n");
remaining = parts.splice(-1);
for (var i=0;i<parts.length;i+=1) {
var match = /^\/\/ (\w+): (.*)/.exec(parts[i]);
if (match) {
meta[match[1]] = match[2];
} else {
read = size;
break;
}
}
}
fs.closeSync(fd);
return meta;
}
function getFileBody(root,path) {
var body = "";
var fn = fspath.join(root,path);
var fd = fs.openSync(fn,"r");
var size = fs.fstatSync(fd).size;
var scanning = true;
var read = 0;
var length = 50;
var remaining = "";
var buffer = Buffer(length);
while(read < size) {
var thisRead = fs.readSync(fd,buffer,0,length);
read += thisRead;
if (scanning) {
var data = remaining+buffer.slice(0,thisRead).toString();
var parts = data.split("\n");
remaining = parts.splice(-1)[0];
for (var i=0;i<parts.length;i+=1) {
if (! /^\/\/ \w+: /.test(parts[i])) {
scanning = false;
body += parts[i]+"\n";
}
}
if (! /^\/\/ \w+: /.test(remaining)) {
scanning = false;
}
if (!scanning) {
body += remaining;
}
} else {
body += buffer.slice(0,thisRead).toString();
}
}
fs.closeSync(fd);
return body;
}
/**
* Write content to a file using UTF8 encoding.
* This forces a fsync before completing to ensure
* the write hits disk.
*/
function writeFile(path,content) {
return when.promise(function(resolve,reject) {
var stream = fs.createWriteStream(path);
stream.on('open',function(fd) {
stream.end(content,'utf8',function() {
fs.fsync(fd,resolve);
});
});
stream.on('error',function(err) {
reject(err);
});
});
}
var localfilesystem = {
init: function(_settings) {
settings = _settings;
var promises = [];
if (!settings.userDir) {
try {
fs.statSync(fspath.join(process.env.NODE_RED_HOME,".config.json"));
settings.userDir = process.env.NODE_RED_HOME;
} catch(err) {
settings.userDir = fspath.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE || process.env.NODE_RED_HOME,".node-red");
if (!settings.readOnly) {
promises.push(promiseDir(settings.userDir));
}
}
}
if (settings.flowFile) {
flowsFile = settings.flowFile;
// handle Unix and Windows "C:\"
if ((flowsFile[0] == "/") || (flowsFile[1] == ":")) {
// Absolute path
flowsFullPath = flowsFile;
} else if (flowsFile.substring(0,2) === "./") {
// Relative to cwd
flowsFullPath = fspath.join(process.cwd(),flowsFile);
} else {
try {
fs.statSync(fspath.join(process.cwd(),flowsFile));
// Found in cwd
flowsFullPath = fspath.join(process.cwd(),flowsFile);
} catch(err) {
// Use userDir
flowsFullPath = fspath.join(settings.userDir,flowsFile);
}
}
} else {
flowsFile = 'flows_'+require('os').hostname()+'.json';
flowsFullPath = fspath.join(settings.userDir,flowsFile);
}
var ffExt = fspath.extname(flowsFullPath);
var ffName = fspath.basename(flowsFullPath);
var ffBase = fspath.basename(flowsFullPath,ffExt);
var ffDir = fspath.dirname(flowsFullPath);
credentialsFile = fspath.join(settings.userDir,ffBase+"_cred"+ffExt);
credentialsFileBackup = fspath.join(settings.userDir,"."+ffBase+"_cred"+ffExt+".backup");
oldCredentialsFile = fspath.join(settings.userDir,"credentials.json");
flowsFileBackup = fspath.join(ffDir,"."+ffName+".backup");
sessionsFile = fspath.join(settings.userDir,".sessions.json");
libDir = fspath.join(settings.userDir,"lib");
libFlowsDir = fspath.join(libDir,"flows");
globalSettingsFile = fspath.join(settings.userDir,".config.json");
if (!settings.readOnly) {
promises.push(promiseDir(libFlowsDir));
}
return when.all(promises);
},
getFlows: function() {
return when.promise(function(resolve) {
if (!initialFlowLoadComplete) {
initialFlowLoadComplete = true;
log.info(log._("storage.localfilesystem.user-dir",{path:settings.userDir}));
log.info(log._("storage.localfilesystem.flows-file",{path:flowsFullPath}));
}
fs.readFile(flowsFullPath,'utf8',function(err,data) {
if (!err) {
return resolve(JSON.parse(data));
}
log.info(log._("storage.localfilesystem.create"));
resolve([]);
});
});
},
saveFlows: function(flows) {
if (settings.readOnly) {
return when.resolve();
}
try {
fs.renameSync(flowsFullPath,flowsFileBackup);
} catch(err) {
}
var flowData;
if (settings.flowFilePretty) {
flowData = JSON.stringify(flows,null,4);
} else {
flowData = JSON.stringify(flows);
}
return writeFile(flowsFullPath, flowData);
},
getCredentials: function() {
return when.promise(function(resolve) {
fs.readFile(credentialsFile,'utf8',function(err,data) {
if (!err) {
resolve(JSON.parse(data));
} else {
fs.readFile(oldCredentialsFile,'utf8',function(err,data) {
if (!err) {
resolve(JSON.parse(data));
} else {
resolve({});
}
});
}
});
});
},
saveCredentials: function(credentials) {
if (settings.readOnly) {
return when.resolve();
}
try {
fs.renameSync(credentialsFile,credentialsFileBackup);
} catch(err) {
}
var credentialData;
if (settings.flowFilePretty) {
credentialData = JSON.stringify(credentials,null,4);
} else {
credentialData = JSON.stringify(credentials);
}
return writeFile(credentialsFile, credentialData);
},
getSettings: function() {
return when.promise(function(resolve,reject) {
fs.readFile(globalSettingsFile,'utf8',function(err,data) {
if (!err) {
try {
return resolve(JSON.parse(data));
} catch(err2) {
log.trace("Corrupted config detected - resetting");
}
}
return resolve({});
})
})
},
saveSettings: function(settings) {
if (settings.readOnly) {
return when.resolve();
}
return writeFile(globalSettingsFile,JSON.stringify(settings,null,1));
},
getSessions: function() {
return when.promise(function(resolve,reject) {
fs.readFile(sessionsFile,'utf8',function(err,data){
if (!err) {
try {
return resolve(JSON.parse(data));
} catch(err2) {
log.trace("Corrupted sessions file - resetting");
}
}
resolve({});
})
});
},
saveSessions: function(sessions) {
if (settings.readOnly) {
return when.resolve();
}
return writeFile(sessionsFile,JSON.stringify(sessions));
},
getLibraryEntry: function(type,path) {
var root = fspath.join(libDir,type);
var rootPath = fspath.join(libDir,type,path);
return promiseDir(root).then(function () {
return nodeFn.call(fs.lstat, rootPath).then(function(stats) {
if (stats.isFile()) {
return getFileBody(root,path);
}
if (path.substr(-1) == '/') {
path = path.substr(0,path.length-1);
}
return nodeFn.call(fs.readdir, rootPath).then(function(fns) {
var dirs = [];
var files = [];
fns.sort().filter(function(fn) {
var fullPath = fspath.join(path,fn);
var absoluteFullPath = fspath.join(root,fullPath);
if (fn[0] != ".") {
var stats = fs.lstatSync(absoluteFullPath);
if (stats.isDirectory()) {
dirs.push(fn);
} else {
var meta = getFileMeta(root,fullPath);
meta.fn = fn;
files.push(meta);
}
}
});
return dirs.concat(files);
});
}).otherwise(function(err) {
if (type === "flows" && !/\.json$/.test(path)) {
return localfilesystem.getLibraryEntry(type,path+".json")
.otherwise(function(e) {
throw err;
});
} else {
throw err;
}
});
});
},
saveLibraryEntry: function(type,path,meta,body) {
if (settings.readOnly) {
return when.resolve();
}
var fn = fspath.join(libDir, type, path);
var headers = "";
for (var i in meta) {
if (meta.hasOwnProperty(i)) {
headers += "// "+i+": "+meta[i]+"\n";
}
}
return promiseDir(fspath.dirname(fn)).then(function () {
writeFile(fn,headers+body);
});
}
};
module.exports = localfilesystem;
| {
"content_hash": "52ae5cc27616b58ba72eb913f0430a95",
"timestamp": "",
"source": "github",
"line_count": 353,
"max_line_length": 157,
"avg_line_length": 32.28045325779037,
"alnum_prop": 0.48793330408073715,
"repo_name": "redconnect-io/node-red",
"id": "08dda1b4bca432d32d031f0a82e3b43b85333941",
"size": "11991",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "red/runtime/storage/localfilesystem.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "71278"
},
{
"name": "HTML",
"bytes": "244393"
},
{
"name": "JavaScript",
"bytes": "1440100"
},
{
"name": "Python",
"bytes": "7471"
},
{
"name": "Shell",
"bytes": "1864"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.