text
stringlengths
2
1.04M
meta
dict
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: The TF Game rules // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "sdk_gamerules.h" #include "ammodef.h" #include "KeyValues.h" #include "weapon_sdkbase.h" #ifdef CLIENT_DLL #else #include "voice_gamemgr.h" #include "team.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifndef CLIENT_DLL LINK_ENTITY_TO_CLASS(info_player_terrorist, CPointEntity); LINK_ENTITY_TO_CLASS(info_player_counterterrorist,CPointEntity); #endif REGISTER_GAMERULES_CLASS( CSDKGameRules ); BEGIN_NETWORK_TABLE_NOBASE( CSDKGameRules, DT_SDKGameRules ) END_NETWORK_TABLE() LINK_ENTITY_TO_CLASS( sdk_gamerules, CSDKGameRulesProxy ); IMPLEMENT_NETWORKCLASS_ALIASED( SDKGameRulesProxy, DT_SDKGameRulesProxy ) #ifdef CLIENT_DLL void RecvProxy_SDKGameRules( const RecvProp *pProp, void **pOut, void *pData, int objectID ) { CSDKGameRules *pRules = SDKGameRules(); Assert( pRules ); *pOut = pRules; } BEGIN_RECV_TABLE( CSDKGameRulesProxy, DT_SDKGameRulesProxy ) RecvPropDataTable( "sdk_gamerules_data", 0, 0, &REFERENCE_RECV_TABLE( DT_SDKGameRules ), RecvProxy_SDKGameRules ) END_RECV_TABLE() #else void *SendProxy_SDKGameRules( const SendProp *pProp, const void *pStructBase, const void *pData, CSendProxyRecipients *pRecipients, int objectID ) { CSDKGameRules *pRules = SDKGameRules(); Assert( pRules ); pRecipients->SetAllRecipients(); return pRules; } BEGIN_SEND_TABLE( CSDKGameRulesProxy, DT_SDKGameRulesProxy ) SendPropDataTable( "sdk_gamerules_data", 0, &REFERENCE_SEND_TABLE( DT_SDKGameRules ), SendProxy_SDKGameRules ) END_SEND_TABLE() #endif #ifdef CLIENT_DLL #else // --------------------------------------------------------------------------------------------------- // // Voice helper // --------------------------------------------------------------------------------------------------- // class CVoiceGameMgrHelper : public IVoiceGameMgrHelper { public: virtual bool CanPlayerHearPlayer( CBasePlayer *pListener, CBasePlayer *pTalker ) { // Dead players can only be heard by other dead team mates if ( pTalker->IsAlive() == false ) { if ( pListener->IsAlive() == false ) return ( pListener->InSameTeam( pTalker ) ); return false; } return ( pListener->InSameTeam( pTalker ) ); } }; CVoiceGameMgrHelper g_VoiceGameMgrHelper; IVoiceGameMgrHelper *g_pVoiceGameMgrHelper = &g_VoiceGameMgrHelper; // --------------------------------------------------------------------------------------------------- // // Globals. // --------------------------------------------------------------------------------------------------- // // NOTE: the indices here must match TEAM_TERRORIST, TEAM_CT, TEAM_SPECTATOR, etc. char *sTeamNames[] = { "Unassigned", "Spectator", "Terrorist", "Counter-Terrorist" }; // --------------------------------------------------------------------------------------------------- // // Global helper functions. // --------------------------------------------------------------------------------------------------- // // Helper function to parse arguments to player commands. const char* FindEngineArg( const char *pName ) { int nArgs = engine->Cmd_Argc(); for ( int i=1; i < nArgs; i++ ) { if ( stricmp( engine->Cmd_Argv(i), pName ) == 0 ) return (i+1) < nArgs ? engine->Cmd_Argv(i+1) : ""; } return 0; } int FindEngineArgInt( const char *pName, int defaultVal ) { const char *pVal = FindEngineArg( pName ); if ( pVal ) return atoi( pVal ); else return defaultVal; } // World.cpp calls this but we don't use it in SDK. void InitBodyQue() { } // --------------------------------------------------------------------------------------------------- // // CSDKGameRules implementation. // --------------------------------------------------------------------------------------------------- // CSDKGameRules::CSDKGameRules() { // Create the team managers for ( int i = 0; i < ARRAYSIZE( sTeamNames ); i++ ) { CTeam *pTeam = static_cast<CTeam*>(CreateEntityByName( "sdk_team_manager" )); pTeam->Init( sTeamNames[i], i ); g_Teams.AddToTail( pTeam ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CSDKGameRules::~CSDKGameRules() { // Note, don't delete each team since they are in the gEntList and will // automatically be deleted from there, instead. g_Teams.Purge(); } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- bool CSDKGameRules::ClientCommand( const char *pcmd, CBaseEntity *pEdict ) { return BaseClass::ClientCommand( pcmd, pEdict ); } //----------------------------------------------------------------------------- // Purpose: Player has just spawned. Equip them. //----------------------------------------------------------------------------- void CSDKGameRules::RadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrcIn, float flRadius, int iClassIgnore ) { RadiusDamage( info, vecSrcIn, flRadius, iClassIgnore, false ); } // Add the ability to ignore the world trace void CSDKGameRules::RadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrcIn, float flRadius, int iClassIgnore, bool bIgnoreWorld ) { CBaseEntity *pEntity = NULL; trace_t tr; float flAdjustedDamage, falloff; Vector vecSpot; Vector vecToTarget; Vector vecEndPos; Vector vecSrc = vecSrcIn; if ( flRadius ) falloff = info.GetDamage() / flRadius; else falloff = 1.0; int bInWater = (UTIL_PointContents ( vecSrc ) & MASK_WATER) ? true : false; vecSrc.z += 1;// in case grenade is lying on the ground // iterate on all entities in the vicinity. for ( CEntitySphereQuery sphere( vecSrc, flRadius ); ( pEntity = sphere.GetCurrentEntity() ) != NULL; sphere.NextEntity() ) { if ( pEntity->m_takedamage != DAMAGE_NO ) { // UNDONE: this should check a damage mask, not an ignore if ( iClassIgnore != CLASS_NONE && pEntity->Classify() == iClassIgnore ) {// houndeyes don't hurt other houndeyes with their attack continue; } // blast's don't tavel into or out of water if (bInWater && pEntity->GetWaterLevel() == 0) continue; if (!bInWater && pEntity->GetWaterLevel() == 3) continue; // radius damage can only be blocked by the world vecSpot = pEntity->BodyTarget( vecSrc ); bool bHit = false; if( bIgnoreWorld ) { vecEndPos = vecSpot; bHit = true; } else { UTIL_TraceLine( vecSrc, vecSpot, MASK_SOLID_BRUSHONLY, info.GetInflictor(), COLLISION_GROUP_NONE, &tr ); if (tr.startsolid) { // if we're stuck inside them, fixup the position and distance tr.endpos = vecSrc; tr.fraction = 0.0; } vecEndPos = tr.endpos; if( tr.fraction == 1.0 || tr.m_pEnt == pEntity ) { bHit = true; } } if ( bHit ) { // the explosion can 'see' this entity, so hurt them! //vecToTarget = ( vecSrc - vecEndPos ); vecToTarget = ( vecEndPos - vecSrc ); // decrease damage for an ent that's farther from the bomb. flAdjustedDamage = vecToTarget.Length() * falloff; flAdjustedDamage = info.GetDamage() - flAdjustedDamage; if ( flAdjustedDamage > 0 ) { CTakeDamageInfo adjustedInfo = info; adjustedInfo.SetDamage( flAdjustedDamage ); Vector dir = vecToTarget; VectorNormalize( dir ); // If we don't have a damage force, manufacture one if ( adjustedInfo.GetDamagePosition() == vec3_origin || adjustedInfo.GetDamageForce() == vec3_origin ) { CalculateExplosiveDamageForce( &adjustedInfo, dir, vecSrc, 1.5 /* explosion scale! */ ); } else { // Assume the force passed in is the maximum force. Decay it based on falloff. float flForce = adjustedInfo.GetDamageForce().Length() * falloff; adjustedInfo.SetDamageForce( dir * flForce ); adjustedInfo.SetDamagePosition( vecSrc ); } pEntity->TakeDamage( adjustedInfo ); // Now hit all triggers along the way that respond to damage... pEntity->TraceAttackToTriggers( adjustedInfo, vecSrc, vecEndPos, dir ); } } } } } void CSDKGameRules::Think() { BaseClass::Think(); } #endif bool CSDKGameRules::ShouldCollide( int collisionGroup0, int collisionGroup1 ) { if ( collisionGroup0 > collisionGroup1 ) { // swap so that lowest is always first swap(collisionGroup0,collisionGroup1); } //Don't stand on COLLISION_GROUP_WEAPON if( collisionGroup0 == COLLISION_GROUP_PLAYER_MOVEMENT && collisionGroup1 == COLLISION_GROUP_WEAPON ) { return false; } return BaseClass::ShouldCollide( collisionGroup0, collisionGroup1 ); } //----------------------------------------------------------------------------- // Purpose: Init CS ammo definitions //----------------------------------------------------------------------------- // shared ammo definition // JAY: Trying to make a more physical bullet response #define BULLET_MASS_GRAINS_TO_LB(grains) (0.002285*(grains)/16.0f) #define BULLET_MASS_GRAINS_TO_KG(grains) lbs2kg(BULLET_MASS_GRAINS_TO_LB(grains)) // exaggerate all of the forces, but use real numbers to keep them consistent #define BULLET_IMPULSE_EXAGGERATION 1 // convert a velocity in ft/sec and a mass in grains to an impulse in kg in/s #define BULLET_IMPULSE(grains, ftpersec) ((ftpersec)*12*BULLET_MASS_GRAINS_TO_KG(grains)*BULLET_IMPULSE_EXAGGERATION) CAmmoDef* GetAmmoDef() { static CAmmoDef def; static bool bInitted = false; if ( !bInitted ) { bInitted = true; // def.AddAmmoType( BULLET_PLAYER_50AE, DMG_BULLET, TRACER_LINE, 0, 0, "ammo_50AE_max", 2400, 0, 10, 14 ); def.AddAmmoType( AMMO_GRENADE, DMG_BLAST, TRACER_LINE, 0, 0, 1/*max carry*/, 1, 0 ); def.AddAmmoType( AMMO_BULLETS, DMG_BULLET, TRACER_LINE, 0, 0, 1/*max carry*/, 1, 0 ); } return &def; } #ifndef CLIENT_DLL const char *CSDKGameRules::GetChatPrefix( bool bTeamOnly, CBasePlayer *pPlayer ) { return "(chat prefix)"; } #endif //----------------------------------------------------------------------------- // Purpose: Find the relationship between players (teamplay vs. deathmatch) //----------------------------------------------------------------------------- int CSDKGameRules::PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget ) { #ifndef CLIENT_DLL // half life multiplay has a simple concept of Player Relationships. // you are either on another player's team, or you are not. if ( !pPlayer || !pTarget || !pTarget->IsPlayer() || IsTeamplay() == false ) return GR_NOTTEAMMATE; if ( (*GetTeamID(pPlayer) != '\0') && (*GetTeamID(pTarget) != '\0') && !stricmp( GetTeamID(pPlayer), GetTeamID(pTarget) ) ) return GR_TEAMMATE; #endif return GR_NOTTEAMMATE; }
{ "content_hash": "5bba0f14c79750554962d38f8558d34d", "timestamp": "", "source": "github", "line_count": 392, "max_line_length": 147, "avg_line_length": 28.714285714285715, "alnum_prop": 0.5740049751243781, "repo_name": "sswires/ham-and-jam", "id": "3dead650dbc3ff01a1869739724b4bf7202749ac", "size": "11256", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "game_shared/sdk/sdk_gamerules.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "590722" }, { "name": "C++", "bytes": "32419935" }, { "name": "Makefile", "bytes": "14652" }, { "name": "Objective-C", "bytes": "33408" }, { "name": "Perl", "bytes": "70416" }, { "name": "Shell", "bytes": "10593" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b46e6cb4c1c919e299017e97faed9ed6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "aaaca990ca2cabe417cf9afc772d251cb17dad03", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Campanulaceae/Cyananthus/Cyananthus hookeri/ Syn. Cyananthus hookeri levicaulis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Then /^I should have zero news_articles$/ do expect(NewsArticle.all.size).to eq(0) end Then /^I should have one news_article$/ do expect(NewsArticle.all.size).to eq(1) end Given /^news_article$/ do FactoryGirl.create(:news_article, title: 'About the Company') end
{ "content_hash": "2059feddaabe0c43482999801b65d88d", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 63, "avg_line_length": 24.727272727272727, "alnum_prop": 0.7242647058823529, "repo_name": "Vizzuality/grid-arendal", "id": "c0df19a6d472d615efa8093da117d5719137b4e4", "size": "302", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "features/step_definitions/news_article_steps.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "236064" }, { "name": "Gherkin", "bytes": "17927" }, { "name": "HTML", "bytes": "27525609" }, { "name": "JavaScript", "bytes": "135270" }, { "name": "Ruby", "bytes": "352657" } ], "symlink_target": "" }
package containerservice // Copyright (c) Microsoft and contributors. 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 // // 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // AgentPoolsClient is the the Container Service Client. type AgentPoolsClient struct { BaseClient } // NewAgentPoolsClient creates an instance of the AgentPoolsClient client. func NewAgentPoolsClient(subscriptionID string) AgentPoolsClient { return NewAgentPoolsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewAgentPoolsClientWithBaseURI creates an instance of the AgentPoolsClient client. func NewAgentPoolsClientWithBaseURI(baseURI string, subscriptionID string) AgentPoolsClient { return AgentPoolsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates an agent pool in the specified managed cluster. // Parameters: // resourceGroupName - the name of the resource group. // resourceName - the name of the managed cluster resource. // agentPoolName - the name of the agent pool. // parameters - parameters supplied to the Create or Update an agent pool operation. func (client AgentPoolsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, parameters AgentPool) (result AgentPoolsCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AgentPoolsClient.CreateOrUpdate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: resourceName, Constraints: []validation.Constraint{{Target: "resourceName", Name: validation.MaxLength, Rule: 63, Chain: nil}, {Target: "resourceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.ManagedClusterAgentPoolProfileProperties", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.ManagedClusterAgentPoolProfileProperties.Count", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "parameters.ManagedClusterAgentPoolProfileProperties.Count", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, {Target: "parameters.ManagedClusterAgentPoolProfileProperties.Count", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, }}, }}}}}); err != nil { return result, validation.NewError("containerservice.AgentPoolsClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, resourceName, agentPoolName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client AgentPoolsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string, parameters AgentPool) (*http.Request, error) { pathParameters := map[string]interface{}{ "agentPoolName": autorest.Encode("path", agentPoolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/agentPools/{agentPoolName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client AgentPoolsClient) CreateOrUpdateSender(req *http.Request) (future AgentPoolsCreateOrUpdateFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client AgentPoolsClient) CreateOrUpdateResponder(resp *http.Response) (result AgentPool, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes the agent pool in the specified managed cluster. // Parameters: // resourceGroupName - the name of the resource group. // resourceName - the name of the managed cluster resource. // agentPoolName - the name of the agent pool. func (client AgentPoolsClient) Delete(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string) (result AgentPoolsDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AgentPoolsClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: resourceName, Constraints: []validation.Constraint{{Target: "resourceName", Name: validation.MaxLength, Rule: 63, Chain: nil}, {Target: "resourceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$`, Chain: nil}}}}); err != nil { return result, validation.NewError("containerservice.AgentPoolsClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, resourceGroupName, resourceName, agentPoolName) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client AgentPoolsClient) DeletePreparer(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "agentPoolName": autorest.Encode("path", agentPoolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/agentPools/{agentPoolName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client AgentPoolsClient) DeleteSender(req *http.Request) (future AgentPoolsDeleteFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client AgentPoolsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get gets the details of the agent pool by managed cluster and resource group. // Parameters: // resourceGroupName - the name of the resource group. // resourceName - the name of the managed cluster resource. // agentPoolName - the name of the agent pool. func (client AgentPoolsClient) Get(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string) (result AgentPool, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AgentPoolsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: resourceName, Constraints: []validation.Constraint{{Target: "resourceName", Name: validation.MaxLength, Rule: 63, Chain: nil}, {Target: "resourceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$`, Chain: nil}}}}); err != nil { return result, validation.NewError("containerservice.AgentPoolsClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, resourceName, agentPoolName) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client AgentPoolsClient) GetPreparer(ctx context.Context, resourceGroupName string, resourceName string, agentPoolName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "agentPoolName": autorest.Encode("path", agentPoolName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/agentPools/{agentPoolName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client AgentPoolsClient) GetSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client AgentPoolsClient) GetResponder(resp *http.Response) (result AgentPool, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets a list of agent pools in the specified managed cluster. The operation returns properties of each agent // pool. // Parameters: // resourceGroupName - the name of the resource group. // resourceName - the name of the managed cluster resource. func (client AgentPoolsClient) List(ctx context.Context, resourceGroupName string, resourceName string) (result AgentPoolListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AgentPoolsClient.List") defer func() { sc := -1 if result.aplr.Response.Response != nil { sc = result.aplr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: resourceName, Constraints: []validation.Constraint{{Target: "resourceName", Name: validation.MaxLength, Rule: 63, Chain: nil}, {Target: "resourceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$`, Chain: nil}}}}); err != nil { return result, validation.NewError("containerservice.AgentPoolsClient", "List", err.Error()) } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, resourceName) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.aplr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "List", resp, "Failure sending request") return } result.aplr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client AgentPoolsClient) ListPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "resourceName": autorest.Encode("path", resourceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/agentPools", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client AgentPoolsClient) ListSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client AgentPoolsClient) ListResponder(resp *http.Response) (result AgentPoolListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client AgentPoolsClient) listNextResults(ctx context.Context, lastResults AgentPoolListResult) (result AgentPoolListResult, err error) { req, err := lastResults.agentPoolListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "containerservice.AgentPoolsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client AgentPoolsClient) ListComplete(ctx context.Context, resourceGroupName string, resourceName string) (result AgentPoolListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/AgentPoolsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, resourceName) return }
{ "content_hash": "fcb3a79ca195444a0375779e01d48dad", "timestamp": "", "source": "github", "line_count": 444, "max_line_length": 211, "avg_line_length": 43.722972972972975, "alnum_prop": 0.7542883634677793, "repo_name": "Miciah/origin", "id": "2de1c02faf0c981d5144e3e7a5834f5c4251bbd5", "size": "19413", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "vendor/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2019-04-30/containerservice/agentpools.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "921" }, { "name": "Dockerfile", "bytes": "2240" }, { "name": "Go", "bytes": "2447734" }, { "name": "Makefile", "bytes": "7214" }, { "name": "Python", "bytes": "14593" }, { "name": "Shell", "bytes": "310508" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6.2 (C:\Users\Octavio\AppData\Local\Programs\Python\Python36-32\python.exe)" project-jdk-type="Python SDK" /> </project>
{ "content_hash": "6286bc9fe677dc0bd5c1289295fdee6a", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 187, "avg_line_length": 64.75, "alnum_prop": 0.7297297297297297, "repo_name": "Schifer/FPI", "id": "05f53f3659acf9ce23ee71abdb96d07ba4206f54", "size": "259", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "first_assignment/.idea/misc.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "818" }, { "name": "Matlab", "bytes": "5830" }, { "name": "Python", "bytes": "37095" } ], "symlink_target": "" }
from .handler import Handler from .device_hive import DeviceHive from .device_hive_api import DeviceHiveApi from .transports.transport import TransportError from .api_request import ApiRequestError from .api_response import ApiResponseError from .device import DeviceError from .network import NetworkError from .device_type import DeviceTypeError from .subscription import SubscriptionError from .user import UserError
{ "content_hash": "81e625473ddb6c3d41cd3e90f69455a0", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 48, "avg_line_length": 38.18181818181818, "alnum_prop": 0.8523809523809524, "repo_name": "devicehive/devicehive-python", "id": "339e154436d1578918285cda1a5c4c8ed144665c", "size": "1077", "binary": false, "copies": "1", "ref": "refs/heads/stable", "path": "devicehive/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "231773" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <system systemId="file:/C:/Projects/NHINC/Current/Product/Production/Common/Interfaces/src/wsdl/EntityDocRetrieveSecured.wsdl" uri="wsdl/EntityDocRetrieveSecured.wsdl"/> <system systemId="file:/C:/Projects/NHINC/Current/Product/Production/Common/Interfaces/src/wsdl/NhincProxyDocRetrieveSecured.wsdl" uri="wsdl/NhincProxyDocRetrieveSecured.wsdl"/> </catalog>
{ "content_hash": "8266904223c0510d5fdb1bf3597b7b3b", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 181, "avg_line_length": 8.53125, "alnum_prop": 0.6135531135531136, "repo_name": "sailajaa/CONNECT", "id": "80b9638c971b933104988fe061a9de5fa14c2ad3", "size": "546", "binary": false, "copies": "5", "ref": "refs/heads/CONNECT_integration", "path": "Product/Production/Adapters/DocumentRetrieve_a0/src/main/webapp/WEB-INF/jax-ws-catalog.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "5539" }, { "name": "Groovy", "bytes": "1641" }, { "name": "Java", "bytes": "12552183" }, { "name": "Python", "bytes": "773" }, { "name": "Shell", "bytes": "14607" }, { "name": "XSLT", "bytes": "35057" } ], "symlink_target": "" }
<?php class Google_Service_Dataflow_TemplateMetadata extends Google_Collection { protected $collection_key = 'parameters'; public $description; public $name; protected $parametersType = 'Google_Service_Dataflow_ParameterMetadata'; protected $parametersDataType = 'array'; public function setDescription($description) { $this->description = $description; } public function getDescription() { return $this->description; } public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } /** * @param Google_Service_Dataflow_ParameterMetadata[] */ public function setParameters($parameters) { $this->parameters = $parameters; } /** * @return Google_Service_Dataflow_ParameterMetadata[] */ public function getParameters() { return $this->parameters; } }
{ "content_hash": "c6946cdc0c7cf1104553c267ddaa7438", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 74, "avg_line_length": 20.952380952380953, "alnum_prop": 0.6829545454545455, "repo_name": "bshaffer/google-api-php-client-services", "id": "24b960b701e9a22e61ab78b8dc706809ce430d59", "size": "1470", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Google/Service/Dataflow/TemplateMetadata.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "9540154" } ], "symlink_target": "" }
import Cat from './cat.js'; import Dog from './dog.js'; export { Dog, Cat };
{ "content_hash": "4bf2ea915a812af96af8c74ecef92df8", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 27, "avg_line_length": 25.666666666666668, "alnum_prop": 0.6233766233766234, "repo_name": "xkm2000/library-starterkit", "id": "6f1e8e65840b9f84cb3e044e2d640e52fdd2470d", "size": "77", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.js", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2083" } ], "symlink_target": "" }
package revel import ( "bytes" "errors" "fmt" "github.com/xeonx/timeago" "html" "html/template" "reflect" "strings" "time" ) var ( // The functions available for use in the templates. TemplateFuncs = map[string]interface{}{ "url": ReverseURL, "set": func(viewArgs map[string]interface{}, key string, value interface{}) template.JS { viewArgs[key] = value return template.JS("") }, "append": func(viewArgs map[string]interface{}, key string, value interface{}) template.JS { if viewArgs[key] == nil { viewArgs[key] = []interface{}{value} } else { viewArgs[key] = append(viewArgs[key].([]interface{}), value) } return template.JS("") }, "field": NewField, "firstof": func(args ...interface{}) interface{} { for _, val := range args { switch val.(type) { case nil: continue case string: if val == "" { continue } return val default: return val } } return nil }, "option": func(f *Field, val interface{}, label string) template.HTML { selected := "" if f.Flash() == val || (f.Flash() == "" && f.Value() == val) { selected = " selected" } return template.HTML(fmt.Sprintf(`<option value="%s"%s>%s</option>`, html.EscapeString(fmt.Sprintf("%v", val)), selected, html.EscapeString(label))) }, "radio": func(f *Field, val string) template.HTML { checked := "" if f.Flash() == val { checked = " checked" } return template.HTML(fmt.Sprintf(`<input type="radio" name="%s" value="%s"%s>`, html.EscapeString(f.Name), html.EscapeString(val), checked)) }, "checkbox": func(f *Field, val string) template.HTML { checked := "" if f.Flash() == val { checked = " checked" } return template.HTML(fmt.Sprintf(`<input type="checkbox" name="%s" value="%s"%s>`, html.EscapeString(f.Name), html.EscapeString(val), checked)) }, // Pads the given string with &nbsp;'s up to the given width. "pad": func(str string, width int) template.HTML { if len(str) >= width { return template.HTML(html.EscapeString(str)) } return template.HTML(html.EscapeString(str) + strings.Repeat("&nbsp;", width-len(str))) }, "errorClass": func(name string, viewArgs map[string]interface{}) template.HTML { errorMap, ok := viewArgs["errors"].(map[string]*ValidationError) if !ok || errorMap == nil { templateLog.Warn("errorClass: Called 'errorClass' without 'errors' in the view args.") return template.HTML("") } valError, ok := errorMap[name] if !ok || valError == nil { return template.HTML("") } return template.HTML(ErrorCSSClass) }, "msg": func(viewArgs map[string]interface{}, message string, args ...interface{}) template.HTML { str, ok := viewArgs[CurrentLocaleViewArg].(string) if !ok { return "" } return template.HTML(MessageFunc(str, message, args...)) }, // Replaces newlines with <br> "nl2br": func(text string) template.HTML { return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1)) }, // Skips sanitation on the parameter. Do not use with dynamic data. "raw": func(text string) template.HTML { return template.HTML(text) }, // Pluralize, a helper for pluralizing words to correspond to data of dynamic length. // items - a slice of items, or an integer indicating how many items there are. // pluralOverrides - optional arguments specifying the output in the // singular and plural cases. by default "" and "s" "pluralize": func(items interface{}, pluralOverrides ...string) string { singular, plural := "", "s" if len(pluralOverrides) >= 1 { singular = pluralOverrides[0] if len(pluralOverrides) == 2 { plural = pluralOverrides[1] } } switch v := reflect.ValueOf(items); v.Kind() { case reflect.Int: if items.(int) != 1 { return plural } case reflect.Slice: if v.Len() != 1 { return plural } default: templateLog.Error("pluralize: unexpected type: ", "value", v) } return singular }, // Format a date according to the application's default date(time) format. "date": func(date time.Time) string { return date.Format(DateFormat) }, "datetime": func(date time.Time) string { return date.Format(DateTimeFormat) }, "slug": Slug, "even": func(a int) bool { return (a % 2) == 0 }, // Using https://github.com/xeonx/timeago "timeago": TimeAgo, "i18ntemplate": func(args ...interface{}) (template.HTML, error) { templateName, lang := "", "" var viewArgs interface{} switch len(args) { case 0: templateLog.Error("i18ntemplate: No arguments passed to template call") case 1: // Assume only the template name is passed in templateName = args[0].(string) case 2: // Assume template name and viewArgs is passed in templateName = args[0].(string) viewArgs = args[1] // Try to extract language from the view args if viewargsmap, ok := viewArgs.(map[string]interface{}); ok { lang, _ = viewargsmap[CurrentLocaleViewArg].(string) } default: // Assume third argument is the region templateName = args[0].(string) viewArgs = args[1] lang, _ = args[2].(string) if len(args) > 3 { templateLog.Error("i18ntemplate: Received more parameters then needed for", "template", templateName) } } var buf bytes.Buffer // Get template tmpl, err := MainTemplateLoader.TemplateLang(templateName, lang) if err == nil { err = tmpl.Render(&buf, viewArgs) } else { templateLog.Error("i18ntemplate: Failed to render i18ntemplate ", "name", templateName, "error", err) } return template.HTML(buf.String()), err }, } ) ///////////////////// // Template functions ///////////////////// // ReverseURL returns a url capable of invoking a given controller method: // "Application.ShowApp 123" => "/app/123" func ReverseURL(args ...interface{}) (template.URL, error) { if len(args) == 0 { return "", errors.New("no arguments provided to reverse route") } action := args[0].(string) if action == "Root" { return template.URL(AppRoot), nil } pathData, found := splitActionPath(nil, action, true) if !found { return "", fmt.Errorf("reversing '%s', expected 'Controller.Action'", action) } // Look up the types. if pathData.TypeOfController == nil { return "", fmt.Errorf("Failed reversing %s: controller not found %#v", action, pathData) } // Note method name is case insensitive search methodType := pathData.TypeOfController.Method(pathData.MethodName) if methodType == nil { return "", errors.New("revel/controller: In " + action + " failed to find function " + pathData.MethodName) } if len(methodType.Args) < len(args)-1 { return "", fmt.Errorf("reversing %s: route defines %d args, but received %d", action, len(methodType.Args), len(args)-1) } // Unbind the arguments. argsByName := make(map[string]string) // Bind any static args first fixedParams := len(pathData.FixedParamsByName) for i, argValue := range args[1:] { Unbind(argsByName, methodType.Args[i+fixedParams].Name, argValue) } return template.URL(MainRouter.Reverse(args[0].(string), argsByName).URL), nil } func Slug(text string) string { separator := "-" text = strings.ToLower(text) text = invalidSlugPattern.ReplaceAllString(text, "") text = whiteSpacePattern.ReplaceAllString(text, separator) text = strings.Trim(text, separator) return text } var timeAgoLangs = map[string]timeago.Config{} func TimeAgo(args ...interface{}) string { datetime := time.Now() lang := "" var viewArgs interface{} switch len(args) { case 0: templateLog.Error("TimeAgo: No arguements passed to timeago") case 1: // only the time is passed in datetime = args[0].(time.Time) case 2: // time and region is passed in datetime = args[0].(time.Time) switch v := reflect.ValueOf(args[1]); v.Kind() { case reflect.String: // second params type string equals region lang, _ = args[1].(string) case reflect.Map: // second params type map equals viewArgs viewArgs = args[1] if viewargsmap, ok := viewArgs.(map[string]interface{}); ok { lang, _ = viewargsmap[CurrentLocaleViewArg].(string) } default: templateLog.Error("TimeAgo: unexpected type: ", "value", v) } default: // Assume third argument is the region datetime = args[0].(time.Time) if reflect.ValueOf(args[1]).Kind() != reflect.Map { templateLog.Error("TimeAgo: unexpected type", "value", args[1]) } if reflect.ValueOf(args[2]).Kind() != reflect.String { templateLog.Error("TimeAgo: unexpected type: ", "value", args[2]) } viewArgs = args[1] lang, _ = args[2].(string) if len(args) > 3 { templateLog.Error("TimeAgo: Received more parameters then needed for timeago") } } if lang == "" { lang, _ = Config.String(defaultLanguageOption) if lang == "en" { timeAgoLangs[lang] = timeago.English } } _, ok := timeAgoLangs[lang] if !ok { timeAgoLangs[lang] = timeago.Config{ PastPrefix: "", PastSuffix: " " + MessageFunc(lang, "ago"), FuturePrefix: MessageFunc(lang, "in") + " ", FutureSuffix: "", Periods: []timeago.FormatPeriod{ {time.Second, MessageFunc(lang, "about a second"), MessageFunc(lang, "%d seconds")}, {time.Minute, MessageFunc(lang, "about a minute"), MessageFunc(lang, "%d minutes")}, {time.Hour, MessageFunc(lang, "about an hour"), MessageFunc(lang, "%d hours")}, {timeago.Day, MessageFunc(lang, "one day"), MessageFunc(lang, "%d days")}, {timeago.Month, MessageFunc(lang, "one month"), MessageFunc(lang, "%d months")}, {timeago.Year, MessageFunc(lang, "one year"), MessageFunc(lang, "%d years")}, }, Zero: MessageFunc(lang, "about a second"), Max: 73 * time.Hour, DefaultLayout: "2006-01-02", } } return timeAgoLangs[lang].Format(datetime) }
{ "content_hash": "67f9eab23470181c22f477aeb486ca30", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 109, "avg_line_length": 30.57894736842105, "alnum_prop": 0.6478687860686443, "repo_name": "notzippy/revel", "id": "f27a48904c1a16d9bf4dc4ae94446d819ad5f171", "size": "9877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "template_functions.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "408933" }, { "name": "HTML", "bytes": "6808" }, { "name": "JavaScript", "bytes": "26" }, { "name": "NewLisp", "bytes": "118" } ], "symlink_target": "" }
<?php /* Smarty version Smarty-3.1.21-dev, created on 2017-05-21 09:40:09 compiled from "D:\xampp\htdocs\sach\application\views\templates\quanly\contents\tables\datatable.html" */ ?> <?php /*%%SmartyHeaderCode:228685921445988af63-51855721%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( 'b4f8001c54e82f5292403965a256f52c3313a3ef' => array ( 0 => 'D:\\xampp\\htdocs\\sach\\application\\views\\templates\\quanly\\contents\\tables\\datatable.html', 1 => 1445208488, 2 => 'file', ), ), 'nocache_hash' => '228685921445988af63-51855721', 'function' => array ( ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.21-dev', 'unifunc' => 'content_59214459922116_50108912', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_59214459922116_50108912')) {function content_59214459922116_50108912($_smarty_tpl) {?><!-- Start page header --> <div class="header-content"> <h2><i class="fa fa-table"></i> Datatable <span>responsive datatable samples</span></h2> <div class="breadcrumb-wrapper hidden-xs"> <span class="label">You are here:</span> <ol class="breadcrumb"> <li> <i class="fa fa-home"></i> <a href="<?php echo base_url('production/admin/codeigniter/dashboard');?> ">Dashboard</a> <i class="fa fa-angle-right"></i> </li> <li> <a href="#">Tables</a> <i class="fa fa-angle-right"></i> </li> <li class="active">Datatable</li> </ol> </div><!-- /.breadcrumb-wrapper --> </div><!-- /.header-content --> <!--/ End page header --> <!-- Start body content --> <div class="body-content animated fadeIn"> <div class="row"> <div class="col-md-12"> <!-- Start repeater --> <div class="panel rounded shadow no-overflow"> <div class="panel-heading"> <div class="pull-left"> <h3 class="panel-title">Product List</h3> </div> <div class="pull-right"> <button class="btn btn-sm" data-action="refresh" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Refresh"><i class="fa fa-refresh"></i></button> <button class="btn btn-sm" data-action="collapse" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Collapse"><i class="fa fa-angle-up"></i></button> <button class="btn btn-sm" data-action="remove" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Remove"><i class="fa fa-times"></i></button> </div> <div class="clearfix"></div> </div><!-- /.panel-heading --> <div class="panel-body"> <!-- Start repeater --> <div class="fuelux"> <div class="repeater" data-staticheight="400" id="myRepeater"> <div class="repeater-header"> <div class="repeater-header-left"> <div class="repeater-search"> <div class="search input-group"> <input type="search" class="form-control" placeholder="Search"/> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <span class="glyphicon glyphicon-search"></span> <span class="sr-only">Search</span> </button> </span> </div> </div> </div> <div class="repeater-header-right"> <div class="btn-group selectlist repeater-filters" data-resize="auto"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> <span class="selected-label">&nbsp;</span> <span class="caret"></span> <span class="sr-only">Toggle Filters</span> </button> <ul id="test" class="dropdown-menu" role="menu"> <li data-value="all" data-selected="true" class="text-left"><a href="#">All Filter</a></li> <li data-value="music"><a href="#">Music</a></li> <li data-value="electronics"><a href="#">Electronics</a></li> <li data-value="fashion"><a href="#">Fashion</a></li> <li data-value="home_garden"><a href="#">Home & garden</a></li> <li data-value="sport"><a href="#">Sporting goods</a></li> </ul> <input class="hidden hidden-field" name="filterSelection" readonly="readonly" aria-hidden="true" type="text"/> </div> <div class="btn-group repeater-views" data-toggle="buttons"> <label class="btn btn-success active"> <input name="repeaterViews" type="radio" value="list"><span class="glyphicon glyphicon-list"></span> </label> <label class="btn btn-success"> <input name="repeaterViews" type="radio" value="thumbnail"><span class="glyphicon glyphicon-th"></span> </label> </div> </div> </div> <div class="repeater-viewport"> <div class="repeater-canvas"></div> <div class="loader repeater-loader"></div> </div> <div class="repeater-footer"> <div class="repeater-footer-left"> <div class="repeater-itemization"> <span><span class="repeater-start"></span> - <span class="repeater-end"></span> of <span class="repeater-count"></span> items</span> <div class="btn-group selectlist" data-resize="auto"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <span class="selected-label">&nbsp;</span> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu" role="menu"> <li data-value="5"><a href="#">5</a></li> <li data-value="10" data-selected="true"><a href="#">10</a></li> <li data-value="20"><a href="#">20</a></li> <li data-value="50" data-foo="bar" data-fizz="buzz"><a href="#">50</a></li> <li data-value="100"><a href="#">100</a></li> </ul> <input class="hidden hidden-field" name="itemsPerPage" readonly="readonly" aria-hidden="true" type="text"/> </div> <span>Per Page</span> </div> </div> <div class="repeater-footer-right"> <div class="repeater-pagination"> <button type="button" class="btn btn-default btn-sm repeater-prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous Page</span> </button> <label class="page-label" id="myPageLabel">Page</label> <div class="repeater-primaryPaging active"> <div class="input-group input-append dropdown combobox"> <input type="text" class="form-control" aria-labelledby="myPageLabel"> <div class="input-group-btn"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu dropdown-menu-right"></ul> </div> </div> </div> <input type="text" class="form-control repeater-secondaryPaging" aria-labelledby="myPageLabel"> <span>of <span class="repeater-pages"></span></span> <button type="button" class="btn btn-default btn-sm repeater-next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next Page</span> </button> </div> </div> </div> </div> </div> <!--/ End repeater --> </div><!-- /.panel-body --> </div><!-- /.panel --> <!--/ End repeater --> <!-- Start datatable using ajax --> <div class="panel rounded shadow"> <div class="panel-heading"> <div class="pull-left"> <h3 class="panel-title">Employee List <span class="label label-danger">AJAX Support</span></h3> </div> <div class="pull-right"> <button class="btn btn-sm" data-action="refresh" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Refresh"><i class="fa fa-refresh"></i></button> <button class="btn btn-sm" data-action="collapse" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Collapse"><i class="fa fa-angle-up"></i></button> <button class="btn btn-sm" data-action="remove" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Remove"><i class="fa fa-times"></i></button> </div> <div class="clearfix"></div> </div><!-- /.panel-heading --> <div class="panel-body"> <!-- Start datatable --> <table id="datatable-ajax" class="table table-striped table-primary"> <thead> <tr> <th data-class="expand">Name</th> <th data-hide="phone">Position</th> <th data-hide="phone">Office</th> <th data-hide="phone">Age</th> <th data-hide="phone,tablet">Start date</th> <th data-hide="phone,tablet">Salary</th> </tr> </thead> <!--tbody section is required--> <tbody></tbody> <!--tfoot section is optional--> <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> </table> <!--/ End datatable --> </div><!-- /.panel-body --> </div><!-- /.panel --> <!--/ End datatable using ajax --> <!-- Start datatable using dom --> <div class="panel rounded shadow"> <div class="panel-heading"> <div class="pull-left"> <h3 class="panel-title">Post List <span class="label label-danger">DOM Support</span></h3> </div> <div class="pull-right"> <button class="btn btn-sm" data-action="refresh" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Refresh"><i class="fa fa-refresh"></i></button> <button class="btn btn-sm" data-action="collapse" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Collapse"><i class="fa fa-angle-up"></i></button> <button class="btn btn-sm" data-action="remove" data-container="body" data-toggle="tooltip" data-placement="top" data-title="Remove"><i class="fa fa-times"></i></button> </div> <div class="clearfix"></div> </div><!-- /.panel-heading --> <div class="panel-body"> <!-- Start datatable --> <table id="datatable-dom" class="table table-striped table-lilac"> <thead> <tr> <th data-class="expand" class="text-center">Image</th> <th data-hide="phone">Title</th> <th data-hide="phone">Description</th> <th data-hide="phone,tablet" class="text-center">Comments</th> <th data-hide="phone,tablet">Date</th> <th data-hide="phone,tablet" style="min-width: 200px" class="text-center">Action</th> </tr> </thead> <tbody> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>Built Using Bootstrap 3</td> <td>A front-end toolkit for creating websites. It is a collection of CSS, HTML and other interface components...</td> <td class="text-center"><span class="label label-info">32</span></td> <td>10/28/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>Development Using LESS</td> <td>Blankon admin easy to use and re-developed because blankon admin developed using LESS...</td> <td class="text-center"><span class="label label-info">5</span></td> <td>10/30/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>Code Quality</td> <td>Quality source Code nicely formatted and commented to make editing this template...</td> <td class="text-center"><span class="label label-info">67</span></td> <td>11/03/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>40+ JQuery Plugins</td> <td>Blankon includes custom plugins, forms, validations, charts, tables, datatables, notifications...</td> <td class="text-center"><span class="label label-info">132</span></td> <td>11/04/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>5+ Widget Types</td> <td>5 Widget types available on this template. like as overview, social, blog, weather and miscellaneous widget...</td> <td class="text-center"><span class="label label-info">45</span></td> <td>11/09/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>5 Icon Types</td> <td>5 Kind of icons available on this template. Glyphicons Pro (save $59)...</td> <td class="text-center"><span class="label label-info">332</span></td> <td>11/13/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>Easy to Customize</td> <td>Blankon admin is a simple design and very user friendly. In each section of the script we provide...</td> <td class="text-center"><span class="label label-info">32</span></td> <td>11/15/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> <tr> <td class="text-center" style="width: 1%"><img src="http://img.djavaui.com/?create=160x100,81B71A?f=ffffff" alt="..." width="160" class="mt-5 mb-5"/></td> <td>Playing Sounds</td> <td>Today websites are full of events (new mail, new chat-message, content update etc.)...</td> <td class="text-center"><span class="label label-info">116</span></td> <td>11/20/2014</td> <td class="text-center"> <a href="#" class="btn btn-sm btn-success btn-xs btn-push"><i class="fa fa-eye"></i> Detail</a> <a href="#" class="btn btn-sm btn-primary btn-xs btn-push"><i class="fa fa-pencil"></i> Edit</a> <a href="#" class="btn btn-sm btn-danger btn-xs btn-push"><i class="fa fa-trash"></i> Delete</a> </td> </tr> </tbody> <tfoot> <tr> <th data-class="expand" class="text-center">Image</th> <th data-hide="phone">Title</th> <th data-hide="phone">Description</th> <th data-hide="phone,tablet" class="text-center">Comments</th> <th data-hide="phone,tablet">Date</th> <th data-hide="phone,tablet" class="text-center">Action</th> </tr> </tfoot> </table> <!--/ End datatable --> </div><!-- /.panel-body --> </div><!-- /.panel --> <!--/ End datatable using dom --> </div><!-- /.col-md-12 --> </div><!-- /.row --> </div><!-- /.body-content --> <!--/ End body content --><?php }} ?>
{ "content_hash": "626a46da726232074f87389bbf4e8ccb", "timestamp": "", "source": "github", "line_count": 358, "max_line_length": 200, "avg_line_length": 69.59217877094972, "alnum_prop": 0.4204061973187766, "repo_name": "minhquang520/sach", "id": "ae83b25f03bb2db904206866af0a7a55613f08fd", "size": "24914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/templates_c/b4f8001c54e82f5292403965a256f52c3313a3ef.file.datatable.html.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "819" }, { "name": "CSS", "bytes": "3490617" }, { "name": "HTML", "bytes": "11373186" }, { "name": "JavaScript", "bytes": "2760535" }, { "name": "PHP", "bytes": "5176405" }, { "name": "Ruby", "bytes": "2849" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Septosporium heterosporum Ellis & Galloway ### Remarks null
{ "content_hash": "1ef1cc023f7c1f4d0c9ade684e06d932", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 42, "avg_line_length": 11.307692307692308, "alnum_prop": 0.7278911564625851, "repo_name": "mdoering/backbone", "id": "6ba357a8b7585a9fc9cf40760e5aee2cc8c1dab8", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Septosporium/Septosporium heterosporum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * @namespace */ namespace Zend\Cache; /** * @package Zend_Cache * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Frontend { /** * Set a frontend option * * @param string $name * @param mixed $value * @return void */ public function setOption($name, $value); /** * Retrieve an option value * * @param string $name * @return mixed */ public function getOption($name); /** * Set cache lifetime * * @param int $newLifetime * @return void */ public function setLifetime($newLifetime); /** * Set the cache backend * * @param Backend $backendObject * @return void */ public function setBackend(Backend $backendObject); /** * Retrieve the cache backend * * @return Backend */ public function getBackend(); /** * Load a cached item * * @param string $id * @param bool $doNotTestCacheValidity * @param bool $doNotUnserialize * @return mixed */ public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false); /** * Test if a cache exists for a given identifier * * @param string $id * @return bool */ public function test($id); /** * Save some data in a cache * * @param mixed $data Data to put in cache (can be another type than string if automatic_serialization is on) * @param string $id Cache id (if not set, the last cache id will be used) * @param array $tags Cache tags * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime) * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends * @throws \Zend\Cache\Exception * @return boolean True if no problem */ public function save($data, $id = null, $tags = array(), $specificLifetime = false, $priority = 8); /** * Remove a cached item * * @param string $id * @return void */ public function remove($id); /** * Clean the cache of multiple or all items * * @param string $mode * @param array $tags * @return void */ public function clean($mode = 'all', $tags = array()); /** * Retrieve all cache identifiers matching ALL the given tags * * @param array $tags * @return array */ public function getIdsMatchingTags($tags = array()); /** * Get cache identifiers matching NONE of the given tags * * @param array $tags * @return array */ public function getIdsNotMatchingTags($tags = array()); /** * Get cache identifiers matching ANY of the given tags * * @param array $tags * @return array */ public function getIdsMatchingAnyTags($tags = array()); /** * Get all cache identifiers * * @return array */ public function getIds(); /** * Get all tags * * @return array */ public function getTags(); /** * Retrieve the filling percentage of the backend storage * * @return int */ public function getFillingPercentage(); /** * Retrieve all metadata for a given cache identifier * * @param string $id * @return array */ public function getMetadatas($id); /** * Extend the lifetime of a given cache identifier * * @param string $id * @param int $extraLifetime * @return bool */ public function touch($id, $extraLifetime); }
{ "content_hash": "7725547bd0ff1e0d42eed15da93b6b77", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 135, "avg_line_length": 23.375757575757575, "alnum_prop": 0.5742805289084781, "repo_name": "phphatesme/LiveTest", "id": "645c292ebb9ab2b8ad82dae800d0ee2f3ef833dd", "size": "4528", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/lib/Zend/Cache/Frontend.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "14662639" }, { "name": "Shell", "bytes": "613" } ], "symlink_target": "" }
'use strict'; var defaults = require('../data/defaults'); var lodash = require('lodash'); var reverseConfig = require('reverse-config'); var packageName = require('../package').name; function expand(array) { var bundles = {}; array.forEach(function (bundle) { if ('string' == typeof bundle) { bundles[bundle] = {}; } else { lodash.merge(bundles, bundle); } }); return bundles; } function sourceExpression(input) { var expression; if ('/' !== input.charAt(input.length)) { input += '/'; } expression = input .replace(/^\.\//, '') .replace(/\//g, '[\\/\\\\]'); return new RegExp(expression); } function mergeConfig(options) { var config = JSON.parse(JSON.stringify(defaults)); var moduleConfig = reverseConfig.get(packageName); function setConfig(key) { config[key] = moduleConfig[key]; } function setOption(key) { // runtime options can't overwrite package config options if (moduleConfig && moduleConfig.hasOwnProperty(key)) { throw new Error('Refusing to overwrite `' + key + '`'); } config[key] = options[key]; } if (moduleConfig) { Object.keys(moduleConfig).forEach(setConfig); } if (options) { Object.keys(options).forEach(setOption); } if (Array.isArray(config.bundles)) { config.bundles = expand(config.bundles); } config.babel = [ /node_modules[\/\\]_app[\/\\]/, sourceExpression(config.babel || config.source) ]; return config; } module.exports = mergeConfig;
{ "content_hash": "e398ab84f4f091a6cb6baa7bba0a766b", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 67, "avg_line_length": 23.47142857142857, "alnum_prop": 0.5794278758368837, "repo_name": "infonl/jsxmas", "id": "d9282fe4a71ec6e7a7fff25acf8106ecd4fcdd4a", "size": "1643", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "library/merge-config.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "383" }, { "name": "JavaScript", "bytes": "15192" } ], "symlink_target": "" }
set +h # disable hashall shopt -s -o pipefail set -e PKG_NAME="libgpg-error" PKG_VERSION="1.19" TARBALL="${PKG_NAME}-${PKG_VERSION}.tar.bz2" SRC_DIR="${PKG_NAME}-${PKG_VERSION}" function prepare() { ln -sv "/source/$TARBALL" "$TARBALL" } function unpack() { tar xf ${TARBALL} } function build() { ./configure --prefix=/usr --disable-static && make $MAKE_PARALLEL } function check() { make $MAKE_PARALLEL check } function instal() { make $MAKE_PARALLEL install mv -v /usr/lib/libgpg-error.so.* /lib ln -sfv ../../lib/$(readlink /usr/lib/libgpg-error.so) /usr/lib/libgpg-error.so } function clean() { rm -rf "${SRC_DIR}" "$TARBALL" } clean;prepare;unpack;pushd ${SRC_DIR};build;[[ $MAKE_CHECK = TRUE ]] && check;instal;popd;clean
{ "content_hash": "e0f02b03238b1bd3f142887e02524add", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 95, "avg_line_length": 19.846153846153847, "alnum_prop": 0.6369509043927648, "repo_name": "PandaLinux/pandaOS", "id": "d9a17c12158455a2bc609f70c9395578826b24e1", "size": "785", "binary": false, "copies": "1", "ref": "refs/heads/plasma", "path": "phase3/libgpg-error/build.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "196588" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="generator" content="Source Themes Academic 4.0.0"> <meta name="generator" content="Hugo 0.54.0" /> <meta name="author" content="Man Parvesh Singh Randhawa"> <meta name="description" content="Software Engineer | Lifelong learner"> <link rel="alternate" hreflang="en-us" href="https://manparvesh.com/tags/food/"> <meta name="theme-color" content="#0095eb"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css" integrity="sha384-aOkxzJ5uQz7WBObEZcHvV5JvRW3TUc2rNPA7pe3AwnsUohiw1Vj2Rgx2KSOkF5+h" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" integrity="sha256-ygkqlh3CYSUri3LhQxzdcm0n1EQvH2Y+U5S2idbLtxs=" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" crossorigin="anonymous"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Montserrat:400,700|Roboto:400,400italic,700|Roboto+Mono"> <link rel="stylesheet" href="/styles.css"> <script> window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create', 'UA-79116900-2', 'auto'); ga('set', 'anonymizeIp', true); ga('require', 'eventTracker'); ga('require', 'outboundLinkTracker'); ga('require', 'urlChangeTracker'); ga('send', 'pageview'); </script> <script async src="//www.google-analytics.com/analytics.js"></script> <script async src="https://cdnjs.cloudflare.com/ajax/libs/autotrack/2.4.1/autotrack.js" integrity="sha512-HUmooslVKj4m6OBu0OgzjXXr+QuFYy/k7eLI5jdeEy/F4RSgMn6XRWRGkFi5IFaFgy7uFTkegp3Z0XnJf3Jq+g==" crossorigin="anonymous"></script> <link rel="alternate" href="https://manparvesh.com/tags/food/index.xml" type="application/rss+xml" title="Man Parvesh Singh Randhawa"> <link rel="feed" href="https://manparvesh.com/tags/food/index.xml" type="application/rss+xml" title="Man Parvesh Singh Randhawa"> <link rel="manifest" href="/site.webmanifest"> <link rel="icon" type="image/png" href="/img/icon.png"> <link rel="apple-touch-icon" type="image/png" href="/img/icon-192.png"> <link rel="canonical" href="https://manparvesh.com/tags/food/"> <meta property="twitter:card" content="summary_large_image"> <meta property="og:site_name" content="Man Parvesh Singh Randhawa"> <meta property="og:url" content="https://manparvesh.com/tags/food/"> <meta property="og:title" content="food | Man Parvesh Singh Randhawa"> <meta property="og:description" content="Software Engineer | Lifelong learner"><meta property="og:image" content="https://manparvesh.com/img/portrait.jpg"> <meta property="og:locale" content="en-us"> <meta property="og:updated_time" content="2016-09-30T10:31:26&#43;08:00"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.js"></script> <script> window.addEventListener("load", function(){ window.cookieconsent.initialise({ "palette": { "popup": { "background": "#0095eb", "text": "#fff" }, "button": { "background": "#fff", "text": "#0095eb" } }, "theme": "classic", "content": { "message": "This website uses cookies to ensure you get the best experience on our website.", "dismiss": "Got it!", "link": "Learn more", "href": "https://cookies.insites.com" } })}); </script> <title>food | Man Parvesh Singh Randhawa</title> </head> <body id="top" data-spy="scroll" data-target="#TableOfContents" data-offset="71" > <aside class="search-results" id="search"> <div class="container"> <section class="search-header"> <div class="row no-gutters justify-content-between mb-3"> <div class="col-6"> <h1>Search</h1> </div> <div class="col-6 col-search-close"> <a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a> </div> </div> <div id="search-box"> <input name="q" id="search-query" placeholder="Search..." autocapitalize="off" autocomplete="off" autocorrect="off" role="textbox" spellcheck="false" type="search"> </div> </section> <section class="section-search-results"> <div id="search-hits"> </div> </section> </div> </aside> <nav class="navbar navbar-light fixed-top navbar-expand-lg py-0" id="navbar-main"> <div class="container"> <a class="navbar-brand" href="/">Man Parvesh Singh Randhawa</a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation"> <span><i class="fas fa-bars"></i></span> </button> <div class="collapse navbar-collapse" id="navbar"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="/#about"> <span>Home</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#experience"> <span>Experience</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#publications"> <span>Publications</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#posts"> <span>Posts</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#projects"> <span>Projects</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/#contact"> <span>Contact</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/learning/"> <span>Learning</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="/files/manparvesh.pdf"> <span>CV</span> </a> </li> <li class="nav-item"> <a class="nav-link js-search" href="#"><i class="fas fa-search" aria-hidden="true"></i></a> </li> <li class="nav-item"> <a class="nav-link js-dark-toggle" href="#"><i class="fas fa-moon" aria-hidden="true"></i></a> </li> </ul> </div> </div> </nav> <div class="universal-wrapper pt-3"> <h1 itemprop="name">food</h1> </div> <div class="universal-wrapper"> <div> <h2><a href="/post/2016-09-30-food-love/">Food and fitness</a></h2> <div class="article-style"> My love for food v/s my fitness state </div> </div> </div> <div class="container"> <footer class="site-footer"> <p class="powered-by"> &copy; Man Parvesh Singh Randhawa &middot; Powered by the <a href="https://sourcethemes.com/academic/" target="_blank" rel="noopener">Academic theme</a> for <a href="https://gohugo.io" target="_blank" rel="noopener">Hugo</a>. <span class="float-right" aria-hidden="true"> <a href="#" id="back_to_top"> <span class="button_icon"> <i class="fas fa-chevron-up fa-2x"></i> </span> </a> </span> </p> </footer> </div> <div id="modal" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Cite</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <pre><code class="tex hljs"></code></pre> </div> <div class="modal-footer"> <a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank"> <i class="fas fa-copy"></i> Copy </a> <a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank"> <i class="fas fa-download"></i> Download </a> <div id="modal-error"></div> </div> </div> </div> </div> <script src="/js/mathjax-config.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha512-+NqPlbbtM1QqiK8ZAo4Yrj2c4lNQoGv8P79DPtKzj++l5jnN39rHA/xsqn8zE9l0uSoxaCdrOgFs6yjyfbBxSg==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.3/imagesloaded.pkgd.min.js" integrity="sha512-umsR78NN0D23AzgoZ11K7raBD+R6hqKojyBZs1w8WvYlsI+QuKRGBx3LFCwhatzBunCjDuJpDHwxD13sLMbpRA==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha256-VsEqElsCHSGmnmHXGQzvoWjWwoznFSZc6hs7ARLRacQ=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.4/isotope.pkgd.min.js" integrity="sha512-VDBOIlDbuC4VWxGJNmuFRQ0Li0SKkDpmGyuhAG5LTDLd/dJ/S0WMVxriR2Y+CyPL5gzjpN4f/6iqWVBJlht0tQ==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" integrity="sha256-X5PoE3KU5l+JcX+w09p/wHl9AzK333C4hJ2I9S5mD4M=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js" integrity="sha256-/BfiIkHlHoVihZdc6TFuj7MmJ0TWcWsMXkeDFwhi0zw=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_CHTML-full" integrity="sha256-GhM+5JHb6QUzOQPXSJLEWP7R73CbkisjzK5Eyij4U9w=" crossorigin="anonymous" async></script> <script id="dsq-count-scr" src="//blog-manparvesh.disqus.com/count.js" async></script> <script>hljs.initHighlightingOnLoad();</script> <script> const search_index_filename = "/index.json"; const i18n = { 'placeholder': "Search...", 'results': "results found", 'no_results': "No results found" }; const content_type = { 'post': "Posts", 'project': "Projects", 'publication' : "Publications", 'talk' : "Talks" }; </script> <script id="search-hit-fuse-template" type="text/x-template"> <div class="search-hit" id="summary-{{key}}"> <div class="search-hit-content"> <div class="search-hit-name"> <a href="{{relpermalink}}">{{title}}</a> <div class="article-metadata search-hit-type">{{type}}</div> <p class="search-hit-description">{{snippet}}</p> </div> </div> </div> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin="anonymous"></script> <script src="/js/academic.min.c1b0baf12cd491effaeeb294faf1e83e.js"></script> </body> </html>
{ "content_hash": "fe29706a16839a52513c84cc1a65059c", "timestamp": "", "source": "github", "line_count": 607, "max_line_length": 251, "avg_line_length": 22.237232289950576, "alnum_prop": 0.5595643799081346, "repo_name": "manparvesh/manparvesh.github.io", "id": "202474b7c34a1752a40d4bc6a8cc3dc36ba3b766", "size": "13500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tags/food/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "49543" }, { "name": "HTML", "bytes": "4224374" }, { "name": "JavaScript", "bytes": "77923" }, { "name": "Jupyter Notebook", "bytes": "44712" }, { "name": "Python", "bytes": "25645" } ], "symlink_target": "" }
package org.elasticsearch.index.analysis; import org.apache.lucene.analysis.CharArraySet; import org.apache.lucene.analysis.bg.BulgarianAnalyzer; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.assistedinject.Assisted; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.index.Index; import org.elasticsearch.index.settings.IndexSettings; /** * */ public class BulgarianAnalyzerProvider extends AbstractIndexAnalyzerProvider<BulgarianAnalyzer> { private final BulgarianAnalyzer analyzer; @Inject public BulgarianAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); analyzer = new BulgarianAnalyzer(version, Analysis.parseStopWords(env, settings, BulgarianAnalyzer.getDefaultStopSet(), version), Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET)); } @Override public BulgarianAnalyzer get() { return this.analyzer; } }
{ "content_hash": "49f360abf8b96acb49af14ff6b7fa48c", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 159, "avg_line_length": 35.09090909090909, "alnum_prop": 0.772020725388601, "repo_name": "Kreolwolf1/Elastic", "id": "2acfc857c7d86523bc131f480e61dd2e92e7dd3a", "size": "1963", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/elasticsearch/index/analysis/BulgarianAnalyzerProvider.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.arakhne.afc.attrs.xml; import java.io.IOException; import java.net.URL; import java.util.Date; import org.w3c.dom.Element; import org.arakhne.afc.attrs.attr.Attribute; import org.arakhne.afc.attrs.attr.AttributeException; import org.arakhne.afc.attrs.attr.AttributeImpl; import org.arakhne.afc.attrs.attr.AttributeType; import org.arakhne.afc.attrs.collection.AttributeCollection; import org.arakhne.afc.attrs.collection.AttributeProvider; import org.arakhne.afc.inputoutput.path.PathBuilder; import org.arakhne.afc.inputoutput.xml.DateFormatException; import org.arakhne.afc.inputoutput.xml.XMLBuilder; import org.arakhne.afc.inputoutput.xml.XMLResources; import org.arakhne.afc.inputoutput.xml.XMLUtil; /** * This class provides XML utilities related to attributes. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 15.0 */ public final class XMLAttributeUtil { /** <code>&lt;attribute /&gt;</code>. */ public static final String NODE_ATTRIBUTE = "attribute"; //$NON-NLS-1$ /** <code>&lt;attributes /&gt;</code>. */ public static final String NODE_ATTRIBUTES = "attributes"; //$NON-NLS-1$ /** <code>geoid=""</code>. */ public static final String ATTR_GEOID = "geoId"; //$NON-NLS-1$ /** <code>type=""</code>. */ public static final String ATTR_TYPE = "type"; //$NON-NLS-1$ /** <code>value=""</code>. */ public static final String ATTR_VALUE = "value"; //$NON-NLS-1$ private XMLAttributeUtil() { // } /** Put in the given XML element the attributes stored in the given container. * This function ignores the attributes with the names "id", "name", "color", * "icon", and "geoId" if the parameter <var>writeStandardAttribute</var> * is <code>false</code>. * * @param element is the XML element to fill. * @param container is the container of attributes. * @param builder is the tool to create XML nodes. * @param resources is the tool that permits to gather the resources. * @param writeStandardAttribute indicates if the attributes "id", "name", "color", * and "geoId" should be write or not. */ @SuppressWarnings("checkstyle:cyclomaticcomplexity") public static void writeAttributeContainer(Element element, AttributeProvider container, XMLBuilder builder, XMLResources resources, boolean writeStandardAttribute) { final Element attrsNode = builder.createElement(NODE_ATTRIBUTES); for (final Attribute attr : container.attributes()) { final AttributeType attrType = attr.getType(); if (attr.isAssigned()) { try { final String name = attr.getName(); if (writeStandardAttribute || (!XMLUtil.ATTR_ID.equalsIgnoreCase(name) && !XMLUtil.ATTR_NAME.equalsIgnoreCase(name) && !XMLUtil.ATTR_COLOR.equalsIgnoreCase(name) && !ATTR_GEOID.equalsIgnoreCase(name))) { final Element attrNode; switch (attrType) { case DATE: attrNode = builder.createElement(NODE_ATTRIBUTE); attrNode.setAttribute(XMLUtil.ATTR_NAME, attr.getName()); attrNode.setAttribute(ATTR_TYPE, attrType.name()); attrNode.setAttribute(ATTR_VALUE, XMLUtil.toString(attr.getDate())); break; case URL: attrNode = builder.createElement(NODE_ATTRIBUTE); attrNode.setAttribute(XMLUtil.ATTR_NAME, attr.getName()); attrNode.setAttribute(ATTR_TYPE, attrType.name()); attrNode.setAttribute(ATTR_VALUE, resources.add(attr.getURL())); break; //$CASES-OMITTED$ default: final String value = attr.getString(); if (value != null && !"".equals(value)) { //$NON-NLS-1$ attrNode = builder.createElement(NODE_ATTRIBUTE); attrNode.setAttribute(XMLUtil.ATTR_NAME, attr.getName()); attrNode.setAttribute(ATTR_VALUE, value); attrNode.setAttribute(ATTR_TYPE, attrType.name()); attrsNode.appendChild(attrNode); } } } } catch (AssertionError e) { throw e; } catch (Throwable exception) { // } } } if (attrsNode.getChildNodes().getLength() > 0) { element.appendChild(attrsNode); } } /** Put the attributes in the given container from the given XML element. * This function ignores the attributes with the names "id", "name", "color", * and "geoId" if the parameter <var>readStandardAttribute</var> * is <code>false</code>. * * @param element is the XML element to fill. * @param container is the container of attributes. * @param pathBuilder is the tool to make paths absolute. * @param resources is the tool that permits to gather the resources. * @param readStandardAttribute indicates if the attributes "id", "name", "color", * and "geoId" should be write or not. * @throws IOException in case of error. */ @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:nestedifdepth"}) public static void readAttributeContainer(Element element, AttributeCollection container, PathBuilder pathBuilder, XMLResources resources, boolean readStandardAttribute) throws IOException { for (final Element attrNode : XMLUtil.getElementsFromPath(element, NODE_ATTRIBUTES, NODE_ATTRIBUTE)) { final String name = XMLUtil.getAttributeValue(attrNode, XMLUtil.ATTR_NAME); if (name != null && (readStandardAttribute || (!"".equals(name) //$NON-NLS-1$ && !XMLUtil.ATTR_ID.equalsIgnoreCase(name) && !XMLUtil.ATTR_NAME.equalsIgnoreCase(name) && !XMLUtil.ATTR_COLOR.equalsIgnoreCase(name) && !ATTR_GEOID.equalsIgnoreCase(name)))) { final String type = XMLUtil.getAttributeValue(attrNode, ATTR_TYPE); if (type != null && !"".equals(type)) { //$NON-NLS-1$ AttributeType attrType; try { attrType = AttributeType.valueOf(type); } catch (Throwable exception) { attrType = null; } if (attrType != null) { final String value; switch (attrType) { case DATE: value = XMLUtil.getAttributeValue(attrNode, ATTR_VALUE); if (value != null && !"".equals(value)) { //$NON-NLS-1$ try { final Date d = XMLUtil.parseDate(value); final AttributeImpl attr = new AttributeImpl(name, d); container.setAttribute(attr); } catch (DateFormatException e) { throw new IOException(e); } catch (AttributeException e) { throw new IOException(e); } } break; case URL: value = XMLUtil.getAttributeValue(attrNode, ATTR_VALUE); if (value != null && !"".equals(value)) { //$NON-NLS-1$ try { final long id = XMLResources.getNumericalIdentifier(value); final URL url = resources.getResourceURL(id); if (url != null) { final AttributeImpl attr = new AttributeImpl(name, url); container.setAttribute(attr); } } catch (IllegalArgumentException e) { throw new IOException(e); } catch (AttributeException e) { throw new IOException(e); } } break; //$CASES-OMITTED$ default: value = XMLUtil.getAttributeValue(attrNode, ATTR_VALUE); if (value != null && !"".equals(value)) { //$NON-NLS-1$ final AttributeImpl attr = new AttributeImpl(name, value); attr.cast(attrType); try { container.setAttribute(attr); } catch (AttributeException e) { throw new IOException(e); } } break; } } } } } } }
{ "content_hash": "cb079a8cc60bf25df94f42e09398817f", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 109, "avg_line_length": 36.857142857142854, "alnum_prop": 0.664929163325314, "repo_name": "gallandarakhneorg/afc", "id": "5b35a9ef84f0cbaf100ea874f2b41bc4f323bd98", "size": "8400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "advanced/attributes/src/main/java/org/arakhne/afc/attrs/xml/XMLAttributeUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "62" }, { "name": "HTML", "bytes": "35" }, { "name": "Java", "bytes": "15844113" }, { "name": "MATLAB", "bytes": "3002" }, { "name": "Perl", "bytes": "637" }, { "name": "Shell", "bytes": "4656" }, { "name": "Visual Basic .NET", "bytes": "50562" } ], "symlink_target": "" }
/** * This package contains AST classes for representing parsed JSON values. * * <p>The root of the AST class hierarchy is {@link com.semmle.js.ast.json.JSONValue}, which in turn * extends {@link com.semmle.js.ast.SourceElement}. * * <p>Nodes accept visitors implementing interface {@link com.semmle.js.ast.json.Visitor}. */ package com.semmle.js.ast.json;
{ "content_hash": "010f33ccbb78defd53c3c1b6ca5c0c30", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 100, "avg_line_length": 40.44444444444444, "alnum_prop": 0.7335164835164835, "repo_name": "github/codeql", "id": "fac0bbc3c22996c7d100033a72a818ecc0a0e529", "size": "364", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "javascript/extractor/src/com/semmle/js/ast/json/package-info.java", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "3739" }, { "name": "Batchfile", "bytes": "3534" }, { "name": "C", "bytes": "410440" }, { "name": "C#", "bytes": "21146000" }, { "name": "C++", "bytes": "1352639" }, { "name": "CMake", "bytes": "1809" }, { "name": "CodeQL", "bytes": "32583145" }, { "name": "Dockerfile", "bytes": "496" }, { "name": "EJS", "bytes": "1478" }, { "name": "Emacs Lisp", "bytes": "3445" }, { "name": "Go", "bytes": "697562" }, { "name": "HTML", "bytes": "58008" }, { "name": "Handlebars", "bytes": "1000" }, { "name": "Java", "bytes": "5417683" }, { "name": "JavaScript", "bytes": "2432320" }, { "name": "Kotlin", "bytes": "12163740" }, { "name": "Lua", "bytes": "13113" }, { "name": "Makefile", "bytes": "8631" }, { "name": "Mustache", "bytes": "17025" }, { "name": "Nunjucks", "bytes": "923" }, { "name": "Perl", "bytes": "1941" }, { "name": "PowerShell", "bytes": "1295" }, { "name": "Python", "bytes": "1649035" }, { "name": "RAML", "bytes": "2825" }, { "name": "Ruby", "bytes": "299268" }, { "name": "Rust", "bytes": "234024" }, { "name": "Shell", "bytes": "23973" }, { "name": "Smalltalk", "bytes": "23" }, { "name": "Starlark", "bytes": "27062" }, { "name": "Swift", "bytes": "204309" }, { "name": "Thrift", "bytes": "3020" }, { "name": "TypeScript", "bytes": "219623" }, { "name": "Vim Script", "bytes": "1949" }, { "name": "Vue", "bytes": "2881" } ], "symlink_target": "" }
namespace NRepository.MongoDb.Interceptors { using System; using System.Collections.Generic; using System.Linq; using MongoDB.Driver; using NRepository.Core; using NRepository.Core.Command; using NRepository.MongoDb.Events; public class WriteConcernModifyCommandInterceptor : IModifyCommandInterceptor { public WriteConcernModifyCommandInterceptor(string collectionName) : this(new WriteConcern()) { if (String.IsNullOrWhiteSpace(collectionName)) throw new ArgumentException("collectionName is null or empty.", "collectionName"); CollectionName = collectionName; } public WriteConcernModifyCommandInterceptor(WriteConcern writeConcern, string collectionName) : this(writeConcern) { if (String.IsNullOrWhiteSpace(collectionName)) throw new ArgumentException("collectionName is null or empty.", "collectionName"); CollectionName = collectionName; } public WriteConcernModifyCommandInterceptor(WriteConcern writeConcern) { if (writeConcern == null) throw new ArgumentNullException("writeConcern", "writeConcern is null."); WriteConcern = writeConcern; } public WriteConcernModifyCommandInterceptor() : this(new WriteConcern()) { } public string CollectionName { get; private set; } public WriteConcern WriteConcern { get; private set; } public WriteConcernResult WriteConcernResult { get; private set; } public bool CheckElementNames { get; set; } public void Modify<T>(ICommandRepository commandRepository, Action<T> modifyAction, T entity) where T : class { var mongoDatabase = commandRepository.ObjectContext as MongoDatabase; if (mongoDatabase == null) throw new NotSupportedException("Modify can only be used with a MongoDatabase context"); var mongoInsertOptions = new MongoInsertOptions { WriteConcern = WriteConcern, CheckElementNames = CheckElementNames }; WriteConcernResult = mongoDatabase.GetCollection<T>(typeof(T).FullName).Save(entity, mongoInsertOptions); var evnt = new MongoDbEntityModifiedEvent(commandRepository, entity, WriteConcernResult); commandRepository.RaiseEvent(evnt); } } }
{ "content_hash": "84716e1117b2d5ad1ac6935492cb9d42", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 117, "avg_line_length": 31.023255813953487, "alnum_prop": 0.6173163418290855, "repo_name": "j-kelly/NRepository.MongoDb", "id": "8d0ed45af1920e4faf509a227965acbb369b7d3b", "size": "2670", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/NRepository.MongoDb/Interceptors/WriteConcernModifyCommandInterceptor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "68500" } ], "symlink_target": "" }
package org.utn.edu.ar.model.persistence.gaeDatastore; import java.util.ArrayList; import java.util.Date; import com.google.appengine.api.datastore.*; import com.google.appengine.repackaged.com.google.common.collect.Lists; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.cmd.*; import com.googlecode.objectify.util.Closeable; import org.utn.edu.ar.model.PlayerService; import org.utn.edu.ar.model.domain.Sport; import org.utn.edu.ar.model.exceptions.sport.SportNotFoundException; import org.utn.edu.ar.model.persistence.ISportStorage; import org.utn.edu.ar.model.persistence.memoryStorage.SportStorage; import com.googlecode.objectify.util.Closeable; import org.utn.edu.ar.controller.SportController; import java.util.List; import static com.googlecode.objectify.ObjectifyService.ofy; /** * Created by norchow on 22/11/15. */ public class GaeSportStorage extends SportStorage implements ISportStorage{ static { ObjectifyService.begin(); ObjectifyService.register(Sport.class); } @Override public List<Sport> getAllSports() { return ofy().load().type(Sport.class).list(); } @Override public Sport getSportById(Long id) { return ofy().load().type(Sport.class).id(id).now(); } public Sport getSportByName(String name) { return ofy().load().type(Sport.class).filter("name", name).first().now(); } @Override public boolean exists(String sportName) { return (getSportByName(sportName) != null); } @Override public boolean exists(Long id) { return (getSportById(id) != null); } @Override public Sport createSport(String sportName) { Sport currentSport = new Sport(sportName); ofy().save().entity(currentSport).now(); return ofy().load().entity(currentSport).now(); } public void removeSport(Long sportId) { ofy().delete().type(Sport.class).id(sportId); } }
{ "content_hash": "642d5671c5a2905525cf808e5538e8ff", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 81, "avg_line_length": 30.29230769230769, "alnum_prop": 0.7089893346876587, "repo_name": "leomora/gae-bookingmatches-app", "id": "ea61c2ef07114c6b56bec54914a7b92beb3aab49", "size": "1969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/utn/edu/ar/model/persistence/gaeDatastore/GaeSportStorage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "289" }, { "name": "HTML", "bytes": "13803" }, { "name": "Java", "bytes": "98813" }, { "name": "JavaScript", "bytes": "23669" } ], "symlink_target": "" }
package com.intellij.ide.structureView.impl.java; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.treeView.smartTree.ActionPresentation; import com.intellij.ide.util.treeView.smartTree.Sorter; import com.intellij.openapi.util.IconLoader; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Comparator; public class VisibilitySorter implements Sorter{ public static final Sorter INSTANCE = new VisibilitySorter(); private static final Icon ICON = IconLoader.getIcon("/objectBrowser/visibilitySort.png"); private static final ActionPresentation PRESENTATION = new ActionPresentation() { public String getText() { return IdeBundle.message("action.structureview.sort.by.visibility"); } public String getDescription() { return null; } public Icon getIcon() { return ICON; } }; @NonNls public static final String ID = "VISIBILITY_SORTER"; public Comparator getComparator() { return VisibilityComparator.IMSTANCE; } public boolean isVisible() { return true; } @NotNull public ActionPresentation getPresentation() { return PRESENTATION; } @NotNull public String getName() { return ID; } }
{ "content_hash": "0dd80e241537f804c000e02071a5812e", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 91, "avg_line_length": 24.84313725490196, "alnum_prop": 0.7419100236779794, "repo_name": "jexp/idea2", "id": "722c80e8ed4ec30cfc26023a70b64d2b6930450d", "size": "1867", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "java/java-impl/src/com/intellij/ide/structureView/impl/java/VisibilitySorter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "6350" }, { "name": "C#", "bytes": "103" }, { "name": "C++", "bytes": "30760" }, { "name": "Erlang", "bytes": "10" }, { "name": "Java", "bytes": "72888555" }, { "name": "JavaScript", "bytes": "910" }, { "name": "PHP", "bytes": "133" }, { "name": "Perl", "bytes": "6523" }, { "name": "Shell", "bytes": "4068" } ], "symlink_target": "" }
package com.google.api.codegen.py; import com.google.api.codegen.config.ApiConfig; import com.google.api.codegen.config.MethodConfig; import com.google.api.codegen.py.PythonImport.ImportType; import com.google.api.tools.framework.model.Field; import com.google.api.tools.framework.model.Interface; import com.google.api.tools.framework.model.MessageType; import com.google.api.tools.framework.model.Method; import com.google.api.tools.framework.model.ProtoElement; import com.google.api.tools.framework.model.ProtoFile; import com.google.api.tools.framework.model.TypeRef; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; public class PythonImportHandler { // TODO (geigerj): Read this from configuration? private final List<String> COMMON_PROTOS = Lists.newArrayList( "google.iam", "google.protobuf", "google.api", "google.longrunning", "google.rpc", "google.type", "google.logging.type"); /** * Bi-map from short names to PythonImport objects for imports. Should only be modified through * addImport() to maintain the invariant that elements of this map are in 1:1 correspondence with * those in fileImports. */ private final BiMap<String, PythonImport> stringImports = HashBiMap.create(); /** * Bi-map from proto files to short names for imports. Should only be modified through addImport() * to maintain the invariant that elements of this map are in 1:1 correspondence with those in * stringImports. */ private final BiMap<ProtoFile, String> fileImports = HashBiMap.create(); /** This constructor is for the main imports of a generated service file */ public PythonImportHandler(Interface service, ApiConfig apiConfig) { // Add non-service-specific imports. addImportStandard("json"); addImportStandard("os"); addImportStandard("pkg_resources"); addImportStandard("platform"); addImportExternal("google.gax"); addImportExternal("google.gax", "api_callable"); addImportExternal("google.gax", "config"); addImportExternal("google.gax", "path_template"); // only if add enum import if there are enums for (TypeRef type : service.getModel().getSymbolTable().getDeclaredTypes()) { if (type.isEnum() && type.getEnumType().isReachable()) { addImportLocal(apiConfig.getPackageName(), "enums"); break; } } // Add method request-type imports. for (MethodConfig methodConfig : apiConfig.getInterfaceConfig(service).getMethodConfigs()) { if (methodConfig.isLongRunningOperation()) { addImportExternal("google.gapic.longrunning", "operations_client"); addImportForMessage(methodConfig.getLongRunningConfig().getReturnType().getMessageType()); addImportForMessage(methodConfig.getLongRunningConfig().getMetadataType().getMessageType()); } Method method = methodConfig.getMethod(); addImport( method.getInputMessage().getFile(), PythonImport.create( ImportType.APP, protoPackageToPythonPackage( method.getInputMessage().getFile().getProto().getPackage()), PythonProtoElements.getPbFileName(method.getInputMessage()))); for (Field field : method.getInputMessage().getMessageFields()) { addImportForMessage(field.getType().getMessageType()); } } } /** This constructor is used for doc messages. */ public PythonImportHandler(ProtoFile file, Set<ProtoFile> importableProtoFiles) { for (MessageType message : file.getMessages()) { for (Field field : message.getMessageFields()) { MessageType messageType = field.getType().getMessageType(); // Don't include imports to messages in the same file. ProtoFile messageParentFile = messageType.getFile(); if (!messageParentFile.equals(file) && importableProtoFiles.contains(messageParentFile)) { addImport( messageParentFile, PythonImport.create( ImportType.APP, protoPackageToPythonPackage(messageType.getFile().getProto().getPackage()), PythonProtoElements.getPbFileName(messageType))); } } } } // Independent import handler to support fragment generation from discovery sources public PythonImportHandler() {} /** * Returns the path to a proto element. If fullyQualified is false, returns the fully qualified * path. * * <p>For example, with message `Hello.World` under import `hello`, if fullyQualified is true: for * `path.to.hello.Hello.World`, it returns `path.to.hello.Hello.World` false: for * `path.to.hello.Hello.World`, it returns `hello.Hello.World` */ public String elementPath(ProtoElement elt, boolean fullyQualified) { String prefix = PythonProtoElements.prefixInFile(elt); String path; if (fullyQualified) { path = protoPackageToPythonPackage(elt.getFile().getProto().getPackage()) + "." + PythonProtoElements.getPbFileName(elt); } else { path = fileToModule(elt.getFile()); } if (Strings.isNullOrEmpty(path)) { // path is either empty or the prefix string. path = prefix; } else { // If path isn't empty: if (!Strings.isNullOrEmpty(prefix)) { // If prefix isn't empty, append it to path. path += "." + prefix; } } path += "." + elt.getSimpleName(); return path; } /* * Adds an import to the import maps. */ private PythonImport addImport(ProtoFile file, PythonImport imp) { // No conflict if (stringImports.get(imp.shortName()) == null) { if (file != null && fileImports.containsKey(file)) { throw new IllegalArgumentException( "fileImports already has " + file.getSimpleName() + " for " + fileImports.get(file) + " but adding " + imp.shortName()); } fileImports.put(file, imp.shortName()); stringImports.put(imp.shortName(), imp); return imp; // Redundant import } else if (stringImports.get(imp.shortName()).importString().equals(imp.importString())) { return imp; // Conflict } else { String oldShortName = imp.shortName(); PythonImport formerImp = stringImports.remove(oldShortName); ProtoFile formerFile = fileImports.inverse().remove(oldShortName); PythonImport disambiguatedNewImp = imp.disambiguate(); PythonImport disambiguatedOldImp = formerImp.disambiguate(); // If we mangled both names, un-mangle the older one; otherwise we'll be in an infinite // mangling cycle. if (disambiguatedNewImp.shortName().equals(oldShortName + "_") && disambiguatedOldImp.shortName().equals(oldShortName + "_")) { disambiguatedOldImp = formerImp; } addImport(formerFile, disambiguatedOldImp); return addImport(file, disambiguatedNewImp); } } // Helper methods to support generating imports from snippets for discovery fragment generation. // Some are written with overloads since snippet engine currently does not support varargs. public PythonImport addImport(ImportType type, String... names) { return addImport(null, PythonImport.create(type, names)); } public String addImportStandard(String moduleName) { return addImport(ImportType.STDLIB, moduleName).shortName(); } public String addImportStandard(String moduleName, String attributeName) { return addImport(ImportType.STDLIB, moduleName, attributeName).shortName(); } public String addImportExternal(String moduleName) { return addImport(ImportType.THIRD_PARTY, moduleName).shortName(); } public String addImportExternal(String moduleName, String attributeName) { return addImport(ImportType.THIRD_PARTY, moduleName, attributeName).shortName(); } public String addImportLocal(String moduleName, String attributeName) { return addImport(ImportType.APP, moduleName, attributeName).shortName(); } /** Add an import for the proto associated with the given message. */ private PythonImport addImportForMessage(MessageType messageType) { return addImport( messageType.getFile(), PythonImport.create( ImportType.APP, protoPackageToPythonPackage(messageType.getFile().getProto().getPackage()), PythonProtoElements.getPbFileName(messageType))); } /** Calculate the imports map and return a sorted set of python import output strings. */ public List<String> calculateImports() { // Order by import type, then lexicographically List<String> stdlibResult = new ArrayList<>(); List<String> thirdPartyResult = new ArrayList<>(); List<String> appResult = new ArrayList<>(); for (PythonImport protoImport : stringImports.values()) { switch (protoImport.type()) { case STDLIB: stdlibResult.add(protoImport.importString()); break; case THIRD_PARTY: thirdPartyResult.add(protoImport.importString()); break; case APP: appResult.add(protoImport.importString()); break; } } Collections.sort(stdlibResult); Collections.sort(thirdPartyResult); Collections.sort(appResult); List<String> all = new ArrayList<>(); if (stdlibResult.size() > 0) { all.addAll(stdlibResult); all.add(""); } if (thirdPartyResult.size() > 0) { all.addAll(thirdPartyResult); all.add(""); } all.addAll(appResult); return all; } public String fileToModule(ProtoFile file) { if (fileImports.containsKey(file)) { return fileImports.get(file); } else { return ""; } } public String fileToImport(ProtoFile file) { if (fileImports.containsKey(file)) { return stringImports.get(fileImports.get(file)).importString(); } else { return ""; } } private String protoPackageToPythonPackage(String protoPackage) { return protoPackageToPythonPackage(protoPackage, "."); } public String protoPackageToPythonPackage(String protoPackage, String sep) { for (String commonProto : COMMON_PROTOS) { String canonical = Joiner.on(".").join(Splitter.on(sep).split(protoPackage)); if (canonical.startsWith(commonProto)) { return protoPackage; } } List<String> packages = Lists.newArrayList(Splitter.on(sep).split(protoPackage)); if (packages.get(0).equals("google")) { if (packages.size() > 1 && packages.get(1).equals("cloud")) { packages = packages.subList(2, packages.size()); } else { packages = packages.subList(1, packages.size()); } packages.addAll(0, Lists.newArrayList("google", "cloud", "proto")); return Joiner.on(sep).join(packages); } return protoPackage; } }
{ "content_hash": "2a8e51ea9d7dd55a3a51646d33400c91", "timestamp": "", "source": "github", "line_count": 308, "max_line_length": 100, "avg_line_length": 36.47727272727273, "alnum_prop": 0.6756564307966177, "repo_name": "jcanizales/toolkit", "id": "277293246a7f26f601b93e7a0b5bdd8a88b3de19", "size": "11826", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/api/codegen/py/PythonImportHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1910" }, { "name": "Java", "bytes": "1702832" }, { "name": "Protocol Buffer", "bytes": "48238" }, { "name": "Python", "bytes": "419" } ], "symlink_target": "" }
SELECT * FROM dbusers WHERE lastupdate IS NOT NULL AND ServerLogin LIKE '%** Orphaned **%' AND DatabaseUserID NOT IN ('guest', 'INFORMATION_SCHEMA', 'sys', 'cdc', 'BUILTIN\Administrators') ORDER BY 1, 2, 3 -- Status SELECT * FROM SQLDBUsers WHERE ServerLogin = '** Orphaned **' AND DatabaseUserID NOT IN ('guest', 'INFORMATION_SCHEMA', 'sys', 'cdc', 'BUILTIN\Administrators') AND ServerName NOT IN ('PSQLRPT21' -- can't remove users from db's in restore mode) ORDER BY 1, 3, 4
{ "content_hash": "56cd1371c655ceffdcc2160ecfedc122", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 90, "avg_line_length": 30.764705882352942, "alnum_prop": 0.6520076481835564, "repo_name": "antlr/codebuff", "id": "224571f870eed046889e8884b74afcc055ed17bf", "size": "535", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "output/tsql/1.4.15/OrphanedUserCleanup_bits.sql", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ANTLR", "bytes": "1479752" }, { "name": "GAP", "bytes": "146955" }, { "name": "Java", "bytes": "32484822" }, { "name": "Python", "bytes": "113118" }, { "name": "SQLPL", "bytes": "605792" }, { "name": "Shell", "bytes": "445" } ], "symlink_target": "" }
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/Color', 'dojo/_base/array', 'dojo/DeferredList', 'dojo/dom-class', 'dojo/dom-construct', 'dojo/dom-style', 'dojo/on', 'esri/geometry/geometryEngine', 'esri/geometry/Polyline', 'esri/graphic', 'esri/layers/FeatureLayer', 'esri/symbols/SimpleMarkerSymbol', 'esri/symbols/SimpleLineSymbol', 'esri/symbols/Font', 'esri/symbols/TextSymbol', 'esri/tasks/query' ], function( declare, lang, Color, array, DeferredList, domClass, domConstruct, domStyle, on, geometryEngine, Polyline, Graphic, FeatureLayer, SimpleMarkerSymbol, SimpleLineSymbol, Font, TextSymbol, Query ) { var closestInfo = declare('ClosestInfo', null, { constructor: function(tab, container, parent) { this.tab = tab; this.container = container; this.parent = parent; this.incident = null; this.graphicsLayer = null; this.map = parent.map; this.domainMap = {}; this.dateFields = []; this.dateFields = {}; }, updateForIncident: function(incident, distance, graphicsLayer) { array.forEach(this.tab.tabLayers, lang.hitch(this, function(tab) { if(typeof(tab.empty) !== 'undefined') { var tempFL = new FeatureLayer(tab.url); on(tempFL, "load", lang.hitch(this, function() { this.tab.tabLayers = [tempFL]; this.processIncident(incident, distance, graphicsLayer); })); } else { this.processIncident(incident, distance, graphicsLayer); } })); }, // update for incident // for polygon: call it twice: first time: within the polygon, second time: within the buffer processIncident: function(incident, distance, graphicsLayer) { this.container.innerHTML = "Loading..."; var results = []; this.incident = incident; var unit = this.parent.config.distanceUnits; var unitCode = this.parent.config.distanceSettings[unit]; var bufferGeom = geometryEngine.buffer(incident.geometry, distance, unitCode); this.graphicsLayer = graphicsLayer; this.graphicsLayer.clear(); var tabLayers = this.tab.tabLayers; var defArray = []; for (var i = 0; i < tabLayers.length; i++) { var layer = tabLayers[i]; var query = new Query(); query.returnGeometry = true; query.geometry = bufferGeom; query.outFields = this._getFields(layer); defArray.push(layer.queryFeatures(query)); } var defList = new DeferredList(defArray); defList.then(lang.hitch(this, function(defResults) { for (var r = 0; r < defResults.length; r++) { var featureSet = defResults[r][1]; var layer = tabLayers[r]; var fields = this._getFields(layer); var graphics = featureSet.features; if (graphics.length > 0) { for (var g = 0; g < graphics.length; g++) { var gra = graphics[g]; var geom = gra.geometry; var dist = this._getDistance(incident.geometry, geom); var newAttr = { DISTANCE: dist }; for (var f = 0; f < fields.length; f++) { newAttr[fields[f]] = gra.attributes[fields[f]]; } gra.attributes = newAttr; } graphics.sort(this._compareDistance); results.push(graphics[0]); } } this._processResults(results); })); }, // process results _processResults: function(results) { this.container.innerHTML = ""; if (results.length === 0) { this.container.innerHTML = this.parent.nls.noFeaturesFound; } var tpc = domConstruct.create("div", { id: "tpc", style: "width:" + (results.length * 220) + "px;" }, this.container); domClass.add(tpc, "IMT_tabPanelContent"); var unit = this.parent.config.distanceUnits; var units = this.parent.nls[unit]; var prevFormat = ""; var dFormat = null; for (var i = 0; i < results.length; i++) { var num = i + 1; var gra = results[i]; var geom = gra.geometry; var loc = geom; if (geom.type !== "point") { loc = geom.getExtent().getCenter(); } var attr = gra.attributes; var dist = attr.DISTANCE; var distLbl = units + ": " + Math.round(dist * 100) / 100; var info = ""; var c = 0; for (var prop in attr) { if (prop !== "DISTANCE" && c < 3) { var newVal = attr[prop]; if (typeof(this.domainMap[prop]) !== 'undefined') { var d = this.domainMap[prop]; if (typeof (d.codedValues) !== 'undefined') { for (var iii = 0; iii < d.codedValues.length; iii++) { if (d.codedValues[iii].code === newVal) { newVal = d.codedValues[iii].name; } } } info += newVal + "<br/>"; } else { if (prop in this.dateFields) { if (this.dateFields[prop] !== prevFormat) { prevFormat = this.dateFields[prop]; dFormat = this._getDateFormat(this.dateFields[prop]); } newVal = new Date(attr[prop]).toLocaleDateString('en-US', dFormat); } info += newVal + "<br/>"; } c += 1; } } var div = domConstruct.create("div", { id: "Feature_" + num }, tpc); domClass.add(div, "IMTcolRec"); var div1 = domConstruct.create("div", {}, div); domClass.add(div1, "IMTcolRecBar"); var div2 = domConstruct.create("div", { innerHTML: num }, div1); domClass.add(div2, "IMTcolRecNum"); domStyle.set(div2, "backgroundColor", this.parent.config.color); on(div2, "click", lang.hitch(this, this._zoomToLocation, loc)); var div3 = domConstruct.create("div", { innerHTML: distLbl }, div1); domClass.add(div3, "IMTcolDistance"); if (this.parent.config.enableRouting) { var div4 = domConstruct.create("div", {}, div1); domClass.add(div4, "IMTcolDir"); on(div4, "click", lang.hitch(this, this._routeToIncident, loc)); } var div5 = domConstruct.create("div", { innerHTML: info }, div); domClass.add(div5, "IMTcolInfo"); var sls = new SimpleLineSymbol( SimpleLineSymbol.STYLE_SOLID, new Color.fromString(this.parent.config.color), 1); var sms = new SimpleMarkerSymbol( SimpleMarkerSymbol.STYLE_CIRCLE, 24, sls, new Color.fromString(this.parent.config.color)); var fnt = new Font(); fnt.family = "Arial"; fnt.size = "12px"; var symText = new TextSymbol(num, fnt, "#ffffff"); symText.setOffset(0, -4); if (attr.OUTSIDE_POLYGON === null) { var distSym = new SimpleLineSymbol( SimpleLineSymbol.STYLE_SOLID, new Color([0, 0, 0, 1]), 1); var distLine = new Polyline(loc.spatialReference); var distPt = this.incident.geometry; if (this.incident.geometry.type !== "point") { distPt = this.incident.geometry.getExtent().getCenter(); } distLine.addPath([loc, distPt]); this.graphicsLayer.add(new Graphic(distLine, distSym, {})); } this.graphicsLayer.add(new Graphic(loc, sms, attr)); this.graphicsLayer.add(new Graphic(loc, symText, attr)); } }, // getFields _getFields: function(layer) { var fields = []; if (layer.infoTemplate) { var fldInfos = layer.infoTemplate.info.fieldInfos; } else if (this.parent.map.itemInfo.itemData.operationalLayers.length > 0) { var mapLayers = this.parent.map.itemInfo.itemData.operationalLayers; var fldInfos = null; for (var i = 0; i < mapLayers.length; i++) { var lyr = mapLayers[i]; if (lyr.layerType === "ArcGISMapServiceLayer") { for (var ii = 0; ii < lyr.layers.length; ii++) { var sl = lyr.layers[ii]; if (sl.popupInfo) { if (sl.id === layer.layerId) { fldInfos = sl.popupInfo.fieldInfos; } } } } } if (!fldInfos) { fldInfos = layer.fields; } } else { var fldInfos = layer.fields; } var lyrFieldInfos = layer.fields; fieldInfoLoop: for (var i = 0; i < fldInfos.length; i++) { var fld = fldInfos[i]; if (typeof (fld.visible) !== 'undefined' ? fld.visible : true) { layerFieldLoop: for (var j = 0; j < lyrFieldInfos.length; j++) { var lyrFld = lyrFieldInfos[j]; if (typeof (fld.fieldName) !== 'undefined') { if (fld.fieldName === lyrFld.name) { break layerFieldLoop; } } else { if (fld.name === lyrFld.name) { break layerFieldLoop; } } } if (typeof (lyrFld.domain) !== 'undefined') { this.domainMap[lyrFld.name] = lyrFld.domain; } if (lyrFld.type === "esriFieldTypeDate") { if (layer.infoTemplate) { for (var key in layer.infoTemplate._fieldsMap) { if (typeof (layer.infoTemplate._fieldsMap[key].fieldName) !== 'undefined') { if (layer.infoTemplate._fieldsMap[key].fieldName === lyrFld.name) { if (typeof (layer.infoTemplate._fieldsMap[key].format.dateFormat) !== 'undefined') { this.dateFields[lyrFld.name] = layer.infoTemplate._fieldsMap[key].format.dateFormat; } } } else { //TODO should a default be set?? //this.dateFields[lyrFld.name] = ; } } } } fields.push(lyrFld.name); } } return fields; }, // get distance _getDistance: function(geom1, geom2) { var dist = 0; var units = this.parent.config.distanceUnits; dist = geometryEngine.distance(geom1, geom2, 9001); switch (units) { case "miles": dist *= 0.000621371; break; case "kilometers": dist *= 0.001; break; case "feet": dist *= 3.28084; break; case "yards": dist *= 1.09361; break; case "nauticalMiles": dist *= 0.000539957; break; } return dist; }, _getDateFormat: function (dFormat) { //default is Month Day Year var options = { month: '2-digit', day: '2-digit', year: 'numeric' }; switch (dFormat) { case "shortDate": //12/21/1997 options = { month: '2-digit', day: '2-digit', year: 'numeric' }; break; case "shortDateLE": //21/12/1997 options = { day: '2-digit', month: '2-digit', year: 'numeric' }; break; case "longMonthDayYear": //December 21,1997 options = { month: 'long', day: '2-digit', year: 'numeric' }; break; case "dayShortMonthYear": //21 Dec 1997 options = { day: '2-digit', month: 'short', year: 'numeric' }; break; case "longDate": //Sunday, December 21, 1997 options = { weekday: 'long', month: 'long', day: '2-digit', year: 'numeric' }; break; case "shortDateLongTime": //12/21/1997 6:00:00 PM options = { month: '2-digit', day: '2-digit', year: 'numeric', hour: 'numeric', minute: '2-digit', second: '2-digit', hour12: true }; break; case "shortDateLELongTime": //21/12/1997 6:00:00 PM options = { day: '2-digit', month: '2-digit', year: 'numeric', hour: 'numeric', minute: '2-digit', second: '2-digit', hour12: true }; break; case "shortDateShortTime": //12/21/1997 6:00 PM options = { month: '2-digit', day: '2-digit', year: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true }; break; case "shortDateLEShortTime": //21/12/1997 6:00 PM options = { day: '2-digit', month: '2-digit', year: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true }; break; case "shortDateShortTime24": //12/21/1997 18:00 options = { month: '2-digit', day: '2-digit', year: 'numeric', hour: 'numeric', minute: '2-digit', hour12: false }; break; case "shortDateLEShortTime24": //21/12/1997 18:00 options = { day: '2-digit', month: '2-digit', year: 'numeric', hour: 'numeric', minute: '2-digit', hour12: false }; break; case "longMonthYear": //December 1997 options = { month: 'long', year: 'numeric' }; break; case "shortMonthYear": //Dec 1997 options = { month: 'short', year: 'numeric' }; case "year": //1997 options = { year: 'numeric' }; break; } return options; }, // COMPARE DISTANCE _compareDistance: function(a, b) { if (a.attributes.DISTANCE < b.attributes.DISTANCE) { return -1; } if (a.attributes.DISTANCE > b.attributes.DISTANCE) { return 1; } return 0; }, // zoom to location _zoomToLocation: function(loc) { this.parent.zoomToLocation(loc); }, // route to incident _routeToIncident: function(loc) { this.parent.routeToIncident(loc); } }); return closestInfo; });
{ "content_hash": "7486125539b74bb520d80c76428c69a1", "timestamp": "", "source": "github", "line_count": 495, "max_line_length": 122, "avg_line_length": 32.86060606060606, "alnum_prop": 0.45659658182712404, "repo_name": "sjayashree01/solutions-webappbuilder-widgets", "id": "8e4350daa6b789d125e8c685809a5b5f859018c4", "size": "16266", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "IncidentAnalysis/js/ClosestInfo.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "251218" }, { "name": "HTML", "bytes": "161367" }, { "name": "JavaScript", "bytes": "2585337" }, { "name": "Python", "bytes": "2015" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>euclidean-geometry: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+1 / euclidean-geometry - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> euclidean-geometry <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-15 03:35:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-15 03:35:13 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/euclidean-geometry&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/EuclideanGeometry&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: plane geometry&quot; &quot;keyword: Euclid&quot; &quot;keyword: ruler and compass&quot; &quot;category: Mathematics/Geometry/General&quot; ] authors: [ &quot;Jean Duprat &lt;[email protected]&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/euclidean-geometry/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/euclidean-geometry.git&quot; synopsis: &quot;Basis of the Euclid&#39;s plane geometry&quot; description: &quot;&quot;&quot; This is a more recent version of the basis of Euclid&#39;s plane geometry, the previous version was the contribution intitled RulerCompassGeometry. The plane geometry is defined as a set of points, with two predicates : Clokwise for the orientation and Equidistant for the metric and three constructors, Ruler for the lines, Compass for the circles and Intersection for the points. For using it, we suggest to compile the files the name of which begin by a capital letter and a number from A1 to N7 in the lexicographic order and to keep modifiable the files of tacics (from Tactic1 to Tactic4) and the files of examples (Hilbert and Bolyai).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/euclidean-geometry/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=d1341193f9fd7a8aa5c1d87ceda9ed61&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-euclidean-geometry.8.8.0 coq.8.7.1+1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1). The following dependencies couldn&#39;t be met: - coq-euclidean-geometry -&gt; coq &gt;= 8.8 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-euclidean-geometry.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "6a013e7abedad67a91a578bf8351d34e", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 278, "avg_line_length": 45.220238095238095, "alnum_prop": 0.565618007108069, "repo_name": "coq-bench/coq-bench.github.io", "id": "2be5bc18bc59fd88fdb0c244647461ad1b9c49ce", "size": "7622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.7.1+1/euclidean-geometry/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Matsush. Mycol. Mem. 10: 94 (2003) #### Original name Tholomyces Matsush. ### Remarks null
{ "content_hash": "685d78d3175e79b654ced0163e23e319", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 13.76923076923077, "alnum_prop": 0.6983240223463687, "repo_name": "mdoering/backbone", "id": "4df1afe2ee5ee244e7f791916342f9d9f64dc607", "size": "220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Tholomyces/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module Collision.Helpers where import Graphics.UI.GLUT import Data.IORef import Control.Monad import Control.Parallel.Strategies import Data.Map import GameObjects.GameObject import GameObjects.Objects.Ball -- | Atomically modifies the contents of an IORef. -- Used instead ($~!) [GLUT] (^&) :: IORef a -> (a -> a) -> IO () (^&) ref fun = do atomicModifyIORef' ref (\r -> (fun r, ())) (#-) :: GameObject -> Map Int GameObject -> Map Int GameObject (#-) (GameObject object) dictionary = insert i (GameObject object) dictionary where i = getId object maxRealFloat :: RealFloat a => a -> a maxRealFloat x = encodeFloat b (e-1) `asTypeOf` x where b = floatRadix x - 1 (_, e) = floatRange x infinity :: RealFloat a => a infinity = if isInfinite inf then inf else maxRealFloat 1.0 where inf = 1/0
{ "content_hash": "b0fee350a42405e09dae394ce0cae871", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 62, "avg_line_length": 28.344827586206897, "alnum_prop": 0.681265206812652, "repo_name": "Zielon/Bounce", "id": "84738067d3868b5eb3605a821b333bd40055a917", "size": "822", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Collision/Helpers.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "47990" } ], "symlink_target": "" }
RELN_ROOT?= ${.CURDIR}/../.. .ifdef NO_LANGCODE_IN_DESTDIR DESTDIR?= ${DOCDIR}/readme .else DESTDIR?= ${DOCDIR}/en_US.ISO8859-1/readme .endif DOC?= article FORMATS?= html INSTALL_COMPRESSED?= gz INSTALL_ONLY_COMPRESSED?= # # SRCS lists the individual SGML files that make up the document. Changes # to any of these files will force a rebuild # # SGML content SRCS+= article.xml .include "${RELN_ROOT}/share/mk/doc.relnotes.mk" .include "${DOC_PREFIX}/share/mk/doc.project.mk"
{ "content_hash": "16d3e60bf3d5ea2a026e256af29ff3e1", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 73, "avg_line_length": 21.863636363636363, "alnum_prop": 0.7193347193347194, "repo_name": "jrobhoward/SCADAbase", "id": "35219fced674166823bf22da18aaf27fd61ac78e", "size": "494", "binary": false, "copies": "3", "ref": "refs/heads/SCADAbase", "path": "release/doc/en_US.ISO8859-1/readme/Makefile", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AGS Script", "bytes": "62471" }, { "name": "Assembly", "bytes": "4615704" }, { "name": "Awk", "bytes": "273794" }, { "name": "Batchfile", "bytes": "20333" }, { "name": "C", "bytes": "457666547" }, { "name": "C++", "bytes": "91495356" }, { "name": "CMake", "bytes": "17632" }, { "name": "CSS", "bytes": "104220" }, { "name": "ChucK", "bytes": "39" }, { "name": "D", "bytes": "6321" }, { "name": "DIGITAL Command Language", "bytes": "10638" }, { "name": "DTrace", "bytes": "1904158" }, { "name": "Emacs Lisp", "bytes": "32010" }, { "name": "EmberScript", "bytes": "286" }, { "name": "Forth", "bytes": "204603" }, { "name": "GAP", "bytes": "72078" }, { "name": "Groff", "bytes": "32376243" }, { "name": "HTML", "bytes": "5776268" }, { "name": "Haskell", "bytes": "2458" }, { "name": "IGOR Pro", "bytes": "6510" }, { "name": "Java", "bytes": "112547" }, { "name": "KRL", "bytes": "4950" }, { "name": "Lex", "bytes": "425858" }, { "name": "Limbo", "bytes": "4037" }, { "name": "Logos", "bytes": "179088" }, { "name": "Makefile", "bytes": "12750766" }, { "name": "Mathematica", "bytes": "21782" }, { "name": "Max", "bytes": "4105" }, { "name": "Module Management System", "bytes": "816" }, { "name": "Objective-C", "bytes": "1571960" }, { "name": "PHP", "bytes": "2471" }, { "name": "PLSQL", "bytes": "96552" }, { "name": "PLpgSQL", "bytes": "2212" }, { "name": "Perl", "bytes": "3947402" }, { "name": "Perl6", "bytes": "122803" }, { "name": "PostScript", "bytes": "152255" }, { "name": "Prolog", "bytes": "42792" }, { "name": "Protocol Buffer", "bytes": "54964" }, { "name": "Python", "bytes": "381066" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "Ruby", "bytes": "67015" }, { "name": "Scheme", "bytes": "5087" }, { "name": "Scilab", "bytes": "196" }, { "name": "Shell", "bytes": "10963470" }, { "name": "SourcePawn", "bytes": "2293" }, { "name": "SuperCollider", "bytes": "80208" }, { "name": "Tcl", "bytes": "7102" }, { "name": "TeX", "bytes": "720582" }, { "name": "VimL", "bytes": "19597" }, { "name": "XS", "bytes": "17496" }, { "name": "XSLT", "bytes": "4564" }, { "name": "Yacc", "bytes": "1881915" } ], "symlink_target": "" }
package org.apache.lucene.analysis; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.util.CloseableThreadLocal; import org.apache.lucene.util.Version; import java.io.Closeable; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; /** * An Analyzer builds TokenStreams, which analyze text. It thus represents a * policy for extracting index terms from text. * <p> * In order to define what analysis is done, subclasses must define their * {@link TokenStreamComponents TokenStreamComponents} in {@link #createComponents(String, Reader)}. * The components are then reused in each call to {@link #tokenStream(String, Reader)}. * <p> * Simple example: * <pre class="prettyprint"> * Analyzer analyzer = new Analyzer() { * {@literal @Override} * protected TokenStreamComponents createComponents(String fieldName, Reader reader) { * Tokenizer source = new FooTokenizer(reader); * TokenStream filter = new FooFilter(source); * filter = new BarFilter(filter); * return new TokenStreamComponents(source, filter); * } * }; * </pre> * For more examples, see the {@link org.apache.lucene.analysis Analysis package documentation}. * <p> * For some concrete implementations bundled with Lucene, look in the analysis modules: * <ul> * <li><a href="{@docRoot}/../analyzers-common/overview-summary.html">Common</a>: * Analyzers for indexing content in different languages and domains. * <li><a href="{@docRoot}/../analyzers-icu/overview-summary.html">ICU</a>: * Exposes functionality from ICU to Apache Lucene. * <li><a href="{@docRoot}/../analyzers-kuromoji/overview-summary.html">Kuromoji</a>: * Morphological analyzer for Japanese text. * <li><a href="{@docRoot}/../analyzers-morfologik/overview-summary.html">Morfologik</a>: * Dictionary-driven lemmatization for the Polish language. * <li><a href="{@docRoot}/../analyzers-phonetic/overview-summary.html">Phonetic</a>: * Analysis for indexing phonetic signatures (for sounds-alike search). * <li><a href="{@docRoot}/../analyzers-smartcn/overview-summary.html">Smart Chinese</a>: * Analyzer for Simplified Chinese, which indexes words. * <li><a href="{@docRoot}/../analyzers-stempel/overview-summary.html">Stempel</a>: * Algorithmic Stemmer for the Polish Language. * <li><a href="{@docRoot}/../analyzers-uima/overview-summary.html">UIMA</a>: * Analysis integration with Apache UIMA. * </ul> */ public abstract class Analyzer implements Closeable { private final ReuseStrategy reuseStrategy; private Version version = Version.LUCENE_CURRENT; // non final as it gets nulled if closed; pkg private for access by ReuseStrategy's final helper methods: CloseableThreadLocal<Object> storedValue = new CloseableThreadLocal<>(); /** * Create a new Analyzer, reusing the same set of components per-thread * across calls to {@link #tokenStream(String, Reader)}. */ public Analyzer() { this(GLOBAL_REUSE_STRATEGY); } /** * Expert: create a new Analyzer with a custom {@link ReuseStrategy}. * <p> * NOTE: if you just want to reuse on a per-field basis, its easier to * use a subclass of {@link AnalyzerWrapper} such as * <a href="{@docRoot}/../analyzers-common/org/apache/lucene/analysis/miscellaneous/PerFieldAnalyzerWrapper.html"> * PerFieldAnalyerWrapper</a> instead. */ public Analyzer(ReuseStrategy reuseStrategy) { this.reuseStrategy = reuseStrategy; } /** * Creates a new {@link TokenStreamComponents} instance for this analyzer. * * @param fieldName * the name of the fields content passed to the * {@link TokenStreamComponents} sink as a reader * @param reader * the reader passed to the {@link Tokenizer} constructor * @return the {@link TokenStreamComponents} for this analyzer. */ protected abstract TokenStreamComponents createComponents(String fieldName, Reader reader); /** * Returns a TokenStream suitable for <code>fieldName</code>, tokenizing * the contents of <code>reader</code>. * <p> * This method uses {@link #createComponents(String, Reader)} to obtain an * instance of {@link TokenStreamComponents}. It returns the sink of the * components and stores the components internally. Subsequent calls to this * method will reuse the previously stored components after resetting them * through {@link TokenStreamComponents#setReader(Reader)}. * <p> * <b>NOTE:</b> After calling this method, the consumer must follow the * workflow described in {@link TokenStream} to properly consume its contents. * See the {@link org.apache.lucene.analysis Analysis package documentation} for * some examples demonstrating this. * * <b>NOTE:</b> If your data is available as a {@code String}, use * {@link #tokenStream(String, String)} which reuses a {@code StringReader}-like * instance internally. * * @param fieldName the name of the field the created TokenStream is used for * @param reader the reader the streams source reads from * @return TokenStream for iterating the analyzed content of <code>reader</code> * @throws AlreadyClosedException if the Analyzer is closed. * @throws IOException if an i/o error occurs. * @see #tokenStream(String, String) */ public final TokenStream tokenStream(final String fieldName, final Reader reader) throws IOException { TokenStreamComponents components = reuseStrategy.getReusableComponents(this, fieldName); final Reader r = initReader(fieldName, reader); if (components == null) { components = createComponents(fieldName, r); reuseStrategy.setReusableComponents(this, fieldName, components); } else { components.setReader(r); } return components.getTokenStream(); } /** * Returns a TokenStream suitable for <code>fieldName</code>, tokenizing * the contents of <code>text</code>. * <p> * This method uses {@link #createComponents(String, Reader)} to obtain an * instance of {@link TokenStreamComponents}. It returns the sink of the * components and stores the components internally. Subsequent calls to this * method will reuse the previously stored components after resetting them * through {@link TokenStreamComponents#setReader(Reader)}. * <p> * <b>NOTE:</b> After calling this method, the consumer must follow the * workflow described in {@link TokenStream} to properly consume its contents. * See the {@link org.apache.lucene.analysis Analysis package documentation} for * some examples demonstrating this. * * @param fieldName the name of the field the created TokenStream is used for * @param text the String the streams source reads from * @return TokenStream for iterating the analyzed content of <code>reader</code> * @throws AlreadyClosedException if the Analyzer is closed. * @throws IOException if an i/o error occurs (may rarely happen for strings). * @see #tokenStream(String, Reader) */ public final TokenStream tokenStream(final String fieldName, final String text) throws IOException { TokenStreamComponents components = reuseStrategy.getReusableComponents(this, fieldName); @SuppressWarnings("resource") final ReusableStringReader strReader = (components == null || components.reusableStringReader == null) ? new ReusableStringReader() : components.reusableStringReader; strReader.setValue(text); final Reader r = initReader(fieldName, strReader); if (components == null) { components = createComponents(fieldName, r); reuseStrategy.setReusableComponents(this, fieldName, components); } else { components.setReader(r); } components.reusableStringReader = strReader; return components.getTokenStream(); } /** * Override this if you want to add a CharFilter chain. * <p> * The default implementation returns <code>reader</code> * unchanged. * * @param fieldName IndexableField name being indexed * @param reader original Reader * @return reader, optionally decorated with CharFilter(s) */ protected Reader initReader(String fieldName, Reader reader) { return reader; } /** * Invoked before indexing a IndexableField instance if * terms have already been added to that field. This allows custom * analyzers to place an automatic position increment gap between * IndexbleField instances using the same field name. The default value * position increment gap is 0. With a 0 position increment gap and * the typical default token position increment of 1, all terms in a field, * including across IndexableField instances, are in successive positions, allowing * exact PhraseQuery matches, for instance, across IndexableField instance boundaries. * * @param fieldName IndexableField name being indexed. * @return position increment gap, added to the next token emitted from {@link #tokenStream(String,Reader)}. * This value must be {@code >= 0}. */ public int getPositionIncrementGap(String fieldName) { return 0; } /** * Just like {@link #getPositionIncrementGap}, except for * Token offsets instead. By default this returns 1. * This method is only called if the field * produced at least one token for indexing. * * @param fieldName the field just indexed * @return offset gap, added to the next token emitted from {@link #tokenStream(String,Reader)}. * This value must be {@code >= 0}. */ public int getOffsetGap(String fieldName) { return 1; } /** * Returns the used {@link ReuseStrategy}. */ public final ReuseStrategy getReuseStrategy() { return reuseStrategy; } /** * Set the version of Lucene this analyzer should mimic the behavior for for analysis. */ public void setVersion(Version v) { version = v; // TODO: make write once? } /** * Return the version of Lucene this analyzer will mimic the behavior of for analysis. */ public Version getVersion() { return version; } /** Frees persistent resources used by this Analyzer */ @Override public void close() { if (storedValue != null) { storedValue.close(); storedValue = null; } } /** * This class encapsulates the outer components of a token stream. It provides * access to the source ({@link Tokenizer}) and the outer end (sink), an * instance of {@link TokenFilter} which also serves as the * {@link TokenStream} returned by * {@link Analyzer#tokenStream(String, Reader)}. */ public static class TokenStreamComponents { /** * Original source of the tokens. */ protected final Tokenizer source; /** * Sink tokenstream, such as the outer tokenfilter decorating * the chain. This can be the source if there are no filters. */ protected final TokenStream sink; /** Internal cache only used by {@link Analyzer#tokenStream(String, String)}. */ transient ReusableStringReader reusableStringReader; /** * Creates a new {@link TokenStreamComponents} instance. * * @param source * the analyzer's tokenizer * @param result * the analyzer's resulting token stream */ public TokenStreamComponents(final Tokenizer source, final TokenStream result) { this.source = source; this.sink = result; } /** * Creates a new {@link TokenStreamComponents} instance. * * @param source * the analyzer's tokenizer */ public TokenStreamComponents(final Tokenizer source) { this.source = source; this.sink = source; } /** * Resets the encapsulated components with the given reader. If the components * cannot be reset, an Exception should be thrown. * * @param reader * a reader to reset the source component * @throws IOException * if the component's reset method throws an {@link IOException} */ protected void setReader(final Reader reader) throws IOException { source.setReader(reader); } /** * Returns the sink {@link TokenStream} * * @return the sink {@link TokenStream} */ public TokenStream getTokenStream() { return sink; } /** * Returns the component's {@link Tokenizer} * * @return Component's {@link Tokenizer} */ public Tokenizer getTokenizer() { return source; } } /** * Strategy defining how TokenStreamComponents are reused per call to * {@link Analyzer#tokenStream(String, java.io.Reader)}. */ public static abstract class ReuseStrategy { /** Sole constructor. (For invocation by subclass constructors, typically implicit.) */ public ReuseStrategy() {} /** * Gets the reusable TokenStreamComponents for the field with the given name. * * @param analyzer Analyzer from which to get the reused components. Use * {@link #getStoredValue(Analyzer)} and {@link #setStoredValue(Analyzer, Object)} * to access the data on the Analyzer. * @param fieldName Name of the field whose reusable TokenStreamComponents * are to be retrieved * @return Reusable TokenStreamComponents for the field, or {@code null} * if there was no previous components for the field */ public abstract TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName); /** * Stores the given TokenStreamComponents as the reusable components for the * field with the give name. * * @param fieldName Name of the field whose TokenStreamComponents are being set * @param components TokenStreamComponents which are to be reused for the field */ public abstract void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components); /** * Returns the currently stored value. * * @return Currently stored value or {@code null} if no value is stored * @throws AlreadyClosedException if the Analyzer is closed. */ protected final Object getStoredValue(Analyzer analyzer) { if (analyzer.storedValue == null) { throw new AlreadyClosedException("this Analyzer is closed"); } return analyzer.storedValue.get(); } /** * Sets the stored value. * * @param storedValue Value to store * @throws AlreadyClosedException if the Analyzer is closed. */ protected final void setStoredValue(Analyzer analyzer, Object storedValue) { if (analyzer.storedValue == null) { throw new AlreadyClosedException("this Analyzer is closed"); } analyzer.storedValue.set(storedValue); } } /** * A predefined {@link ReuseStrategy} that reuses the same components for * every field. */ public static final ReuseStrategy GLOBAL_REUSE_STRATEGY = new GlobalReuseStrategy(); /** * Implementation of {@link ReuseStrategy} that reuses the same components for * every field. * @deprecated This implementation class will be hidden in Lucene 5.0. * Use {@link Analyzer#GLOBAL_REUSE_STRATEGY} instead! */ @Deprecated public final static class GlobalReuseStrategy extends ReuseStrategy { /** Sole constructor. (For invocation by subclass constructors, typically implicit.) * @deprecated Don't create instances of this class, use {@link Analyzer#GLOBAL_REUSE_STRATEGY} */ @Deprecated public GlobalReuseStrategy() {} @Override public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) { return (TokenStreamComponents) getStoredValue(analyzer); } @Override public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) { setStoredValue(analyzer, components); } } /** * A predefined {@link ReuseStrategy} that reuses components per-field by * maintaining a Map of TokenStreamComponent per field name. */ public static final ReuseStrategy PER_FIELD_REUSE_STRATEGY = new PerFieldReuseStrategy(); /** * Implementation of {@link ReuseStrategy} that reuses components per-field by * maintaining a Map of TokenStreamComponent per field name. * @deprecated This implementation class will be hidden in Lucene 5.0. * Use {@link Analyzer#PER_FIELD_REUSE_STRATEGY} instead! */ @Deprecated public static class PerFieldReuseStrategy extends ReuseStrategy { /** Sole constructor. (For invocation by subclass constructors, typically implicit.) * @deprecated Don't create instances of this class, use {@link Analyzer#PER_FIELD_REUSE_STRATEGY} */ @Deprecated public PerFieldReuseStrategy() {} @SuppressWarnings("unchecked") @Override public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) { Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer); return componentsPerField != null ? componentsPerField.get(fieldName) : null; } @SuppressWarnings("unchecked") @Override public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) { Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer); if (componentsPerField == null) { componentsPerField = new HashMap<>(); setStoredValue(analyzer, componentsPerField); } componentsPerField.put(fieldName, components); } } }
{ "content_hash": "d737b75b698b7aec8224420ddcdb012f", "timestamp": "", "source": "github", "line_count": 459, "max_line_length": 124, "avg_line_length": 38.78649237472767, "alnum_prop": 0.6975790597090378, "repo_name": "smartan/lucene", "id": "cf51745988c7c74e42d5b8611803a1b42429d6ce", "size": "18604", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/main/java/org/apache/lucene/analysis/Analyzer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "25382945" } ], "symlink_target": "" }
If your code is taking too long to run, you will need to either reduce the complexity of your chosen RNN architecture or switch to running your code on a GPU. If you'd like to use a GPU, you have two options: #### Build your Own Deep Learning Workstation If you have access to a GPU, you should follow the Keras instructions for [running Keras on GPU](https://keras.io/getting-started/faq/#how-can-i-run-keras-on-gpu). #### Amazon Web Services Instead of a local GPU, you could use Amazon Web Services to launch an EC2 GPU instance. (This costs money.) ## Rubric items #### Files Submitted | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Submission Files | The submission includes all required file RNN_project_student_version.ipynb All code must be written ONLY in the TODO sections and no previous code should be modified. | #### Documentation | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Comments | The submission includes comments that describe the functionality of the code. Every line of code is preceded by a meaningful comment. 1. describing input parameters to Keras module functions. 2. function calls 3. explaning thought process in common language | #### Step 1: Implement a function to window time series | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Window time series data. | The submission returns the proper windowed version of input time series of proper dimension listed in the notebook. | #### Step 2: Create a simple RNN model using keras to perform regression | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Build an RNN model to perform regression. | The submission constructs an RNN model in keras with LSTM module of dimension defined in the notebook. | #### Step 3: Clean up a large text corpus | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Find and remove all non-english or punctuation characters from input text data. The submission removes all non-english / non-punctuation characters. | #### Step 4: Implement a function to window a large text corpus | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Implement a function to window input text data| The submission returns the proper windowed version of input text of proper dimension listed in the notebook. | #### Step 5: Create a simple RNN model using keras to perform multiclass classification | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Build an RNN model to perform multiclass classification. | The submission constructs an RNN model in keras with LSTM module of dimension defined in the notebook. | #### Step 6: Generate text using a fully trained RNN model and a variety of input sequences | Criteria | Meets Specifications | |:---------------------:|:---------------------------------------------------------:| | Generate text using a trained RNN classifier. | The submission presents examples of generated text from a trained RNN module. The majority of this generated text should consist of real english words. |
{ "content_hash": "7edab793cf4f9199c8a5f53173a7e29d", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 286, "avg_line_length": 59.75, "alnum_prop": 0.5617154811715481, "repo_name": "nateGeorge/RNN_project", "id": "e4b212adfc1afd42d52cefffa5f8fa8722ddc093", "size": "3951", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "24527" }, { "name": "JavaScript", "bytes": "3449" }, { "name": "Jupyter Notebook", "bytes": "263747" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>C++ command line parameters parser: User&#39;s guide</title> <link href="own.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.6 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="main.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Data&nbsp;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> </div> <div class="contents"> <h1><a class="anchor" name="user_guide">User's guide </a></h1><b>Contents:</b><ul> <li><a class="el" href="user_guide.html#introduction">Introduction</a><ul> <li><a class="el" href="user_guide.html#value_or_not_value">Value or not value?</a></li><li><a class="el" href="user_guide.html#necessity">Necessity</a></li><li><a class="el" href="user_guide.html#default_val">Default value</a></li><li><a class="el" href="user_guide.html#error_reports">Error reports</a></li></ul> </li><li><a class="el" href="user_guide.html#common_usage">Common usage</a><ul> <li><a class="el" href="user_guide.html#preparing">Preparing</a></li><li><a class="el" href="user_guide.html#defining_parameter">Defining command line parameter</a></li><li><a class="el" href="user_guide.html#member_functions">Register of functions-members</a></li><li><a class="el" href="user_guide.html#parsing">Parsing</a></li><li><a class="el" href="user_guide.html#function_arg_types">Supported types of user's function argument</a></li></ul> </li><li><a class="el" href="user_guide.html#advanced_usage">Advanced usage</a><ul> <li><a class="el" href="user_guide.html#how_to_define_necessity">Define parameter's necessity</a></li><li><a class="el" href="user_guide.html#how_to_define_default_value">Define parameter's default value</a></li><li><a class="el" href="user_guide.html#how_to_define_type_check">Parameter's value type check</a></li><li><a class="el" href="user_guide.html#how_to_define_semantic_check">Parameter's value semantic check</a></li><li><a class="el" href="user_guide.html#combine_of_settings">Combine of settings</a></li><li><a class="el" href="user_guide.html#another_value_separator">Another 'name-value' separator</a></li><li><a class="el" href="user_guide.html#unnamed_params">Unnamed parameters</a></li></ul> </li></ul> <p> <hr/> <h2><a class="anchor" name="introduction"> Introduction</a></h2> Factually, using CLPP library add up to only two tasks: <ul> <li><b>registration</b> set of parameters, with definition all required checkings and characteristics, </li> <li><b>parsing</b> inputed parameter(s), with defined check(s) and calls of corresponding functions.</li> </ul> <br/> <h3><a class="anchor" name="value_or_not_value"> Value or not value?</a></h3> Command line parameter can be with or without value.<p> Example of parameter without value: <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program --help</span> </pre></div> Parameter <b>'--help'</b> is useful of its own accord, it not need any value.<p> Example of parameter with value: <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program --log-dir=/some/path</span> </pre></div> Parameter <b>'--log-dir'</b>, in contrast, useless without value.<p> <br/> <h3><a class="anchor" name="necessity"> Necessity</a></h3> Command line parameter can be necessary or optionally.<p> In examples above parameter <b>'--help'</b> is optionally, because it may missing (only in cases where user want to see help info, he input '--help').<p> But parameter <b>'--log-dir'</b> <em>may be</em> necessary, in this case user <em>must</em> input it.<p> <br/> <h3><a class="anchor" name="default_val"> Default value</a></h3> Command line parameter can have default value, in this case not required input it. This option can be useful for parameters with predefined default values.<p> In example above parameter <b>'--log-dir'</b> may have default value of path, so user can skip it.<p> <br/> <h3><a class="anchor" name="error_reports"> Error reports</a></h3> All reports about errors begins with <b>[CLPP]</b> prefix, for example:<p> <div class="fragment"><pre class="fragment"> [CLPP] You inputs 3 <a class="code" href="namespaceclpp.html#77404c52fd3d65003f78d8d171dd2a06">parameters</a>, but only 2 registered! </pre></div><p> <hr/> <h2><a class="anchor" name="common_usage"> Common usage</a></h2> This section describes common usage of CLPP.<p> <br/> <h3><a class="anchor" name="preparing"> Preparing</a></h3> Copy 'clpp' folder in some place where your compiler is looking for header files and add:<p> <div class="fragment"><pre class="fragment"><span class="preprocessor"> #include &lt;<a class="code" href="parser_8hpp.html">clpp/parser.hpp</a>&gt;</span> </pre></div><p> in your program.<p> For simplicity, you can also add:<p> <div class="fragment"><pre class="fragment"> <span class="keyword">using namespace </span>clpp; </pre></div><p> Note: In old versions of library used namespace <b>clp_parser</b>, but backward compatibility is maintained.<p> <br/> <h3><a class="anchor" name="defining_parameter"> Defining command line parameter</a></h3> Registration of new parameter included three tasks: <ul> <li>define parameter's name (short and full names, or single name), </li> <li>define function that will be called if corresponding parameter will be inputed, </li> <li>define checks and default value for parameter <em>(optionally)</em>.</li> </ul> Use <b><a class="el" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">clpp::command_line_parameters_parser::add_parameter()</a></b> function for it.<p> <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> help() { <span class="comment">/* some info */</span> } <span class="keywordtype">void</span> config() { <span class="comment">/* some config info */</span> } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; <span class="comment">// Register parameter with two names (in Unix-style) and 'help()' function.</span> parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-h"</span>, <span class="stringliteral">"--help"</span>, help ); <span class="comment">// Register parameter with single name and 'config()' function.</span> parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"--config"</span>, config ); <span class="comment">// ...</span> } </pre></div><p> <br/> <h3><a class="anchor" name="member_functions"> Register of functions-members</a></h3> You can register not only global functions, but also functions-members.<p> <div class="fragment"><pre class="fragment"> <span class="keyword">struct </span>some_parameters_storage { <span class="keywordtype">void</span> some_path( <span class="keyword">const</span> std::string&amp; <a class="code" href="namespaceclpp.html#efe328c81928312195ba91a74a5b020667dfceda428ebe0abead66453110238c">path</a> ) { <span class="comment">/* Some work with path... */</span> } <span class="keywordtype">void</span> some_num( <span class="keywordtype">double</span> number ) { <span class="comment">/* Some work with number... */</span> } } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { some_parameters_storage storage; <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-f"</span>, <span class="stringliteral">"--file"</span>, &amp;storage, &amp;some_parameters_storage::some_path ); parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-n"</span>, <span class="stringliteral">"--number"</span>, &amp;storage, &amp;some_parameters_storage::some_num ); <span class="comment">// ...</span> } </pre></div><p> <br/> <h3><a class="anchor" name="parsing"> Parsing</a></h3> For parsing use <b><a class="el" href="classclpp_1_1command__line__parameters__parser.html#462de12e0e0181036b8aa5a29bac070f">clpp::command_line_parameters_parser::parse()</a></b> function.<p> <div class="fragment"><pre class="fragment"> <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; <span class="comment">// ...</span> <span class="keywordflow">try</span> { parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#462de12e0e0181036b8aa5a29bac070f">parse</a>( argc, argv ); } <span class="keywordflow">catch</span> ( <span class="keyword">const</span> std::exception&amp; exc ) { std::cerr &lt;&lt; exc.what() &lt;&lt; std::endl; } <span class="comment">// ...</span> } </pre></div><p> This function parse all inputed command line parameters, checks correctness and calls corresponding functions.<p> <br/> <h3><a class="anchor" name="function_arg_types"> Supported types of user's function argument</a></h3> When you register parameter with value, you can use follow types of function's argument: <ul> <li>almost all standard C++-types (see below), </li> <li>std::string.</li> </ul> You CANNOT use <b>const char*</b> and <b>wchar_t</b> argument. But this limitation, in my humble opinion, is not the real problem.<p> You can pass argument by value, like this: <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> f( <span class="keywordtype">int</span> i ) { <span class="comment">/* some work... */</span> } </pre></div> or by const reference: <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> f( <span class="keyword">const</span> std::string&amp; <a class="code" href="namespaceclpp.html#efe328c81928312195ba91a74a5b020667dfceda428ebe0abead66453110238c">path</a> ) { <span class="comment">/* some work... */</span> } </pre></div><p> Passing by non-const reference is NOT supported (I think this is completely unnecessary).<p> <hr/> <h2><a class="anchor" name="advanced_usage"> Advanced usage</a></h2> This section describes advanced usage of CLPP.<p> <br/> <h3><a class="anchor" name="how_to_define_necessity"> Define parameter's necessity</a></h3> For define parameter's necessity use <b><a class="el" href="classclpp_1_1detail_1_1parameter.html#46ac6e04fb7a1c27574ff9607ab64fa7">clpp::parameter::necessary()</a></b> function: <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> config( <span class="keyword">const</span> std::string&amp; <a class="code" href="namespaceclpp.html#efe328c81928312195ba91a74a5b020667dfceda428ebe0abead66453110238c">path</a> ) { <span class="comment">/* some config info */</span> } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-c"</span>, <span class="stringliteral">"--config"</span>, config ) .necessary(); <span class="comment">// ...</span> } </pre></div> After that user <b>must</b> inputs this parameter in command line.<p> <br/> <h3><a class="anchor" name="how_to_define_default_value"> Define parameter's default value</a></h3> For set parameter's default value use <b><a class="el" href="classclpp_1_1detail_1_1parameter.html#a4bce9e31469578e0ccdd7fdaea1126d">clpp::parameter::default_value()</a></b> function: <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> config( <span class="keyword">const</span> std::string&amp; <a class="code" href="namespaceclpp.html#efe328c81928312195ba91a74a5b020667dfceda428ebe0abead66453110238c">path</a> ) { <span class="comment">/* some config info */</span> } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-c"</span>, <span class="stringliteral">"--config"</span>, config ) .default_value( <span class="stringliteral">"/some/default/path"</span> ); <span class="comment">// ...</span> } </pre></div> After that user <b>can skip</b> this parameter in command line.<p> <br/> <h3><a class="anchor" name="how_to_define_type_check"> Parameter's value type check</a></h3> Since <b>1.0rc</b> version value's type checks automatically. If you register callback function <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> some_num( <span class="keywordtype">double</span> num ) { <span class="comment">/* some work... */</span> } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-n"</span>, <span class="stringliteral">"--number"</span>, some_num ); <span class="comment">// ...</span> } </pre></div> so <code>number</code>'s value <b>must</b> be 'double' type.<p> Note: if you want use function with 'float' argument, like this:<p> <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> some_num( <span class="keywordtype">float</span> num ) { <span class="comment">/* some work... */</span> } </pre></div> AND use 'default_value()' function, you must indicate exactly 'float' type, like this:<p> <div class="fragment"><pre class="fragment"> <span class="comment">// ...</span> parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-n"</span>, <span class="stringliteral">"--number"</span>, some_num ) .default_value( 12.56f ) ; <span class="comment">// ...</span> </pre></div> or like this:<p> <div class="fragment"><pre class="fragment"> <span class="comment">// ...</span> parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-n"</span>, <span class="stringliteral">"--number"</span>, some_num ) .default_value( <span class="keywordtype">float</span>( 12.56 ) ) ; <span class="comment">// ...</span> </pre></div><p> <br/> <h3><a class="anchor" name="how_to_define_semantic_check"> Parameter's value semantic check</a></h3> Use <b><a class="el" href="classclpp_1_1detail_1_1parameter.html#b10f0ff8b02e32fe37e821ca4198ce75">clpp::parameter::check_semantic()</a></b> function.<p> <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> log_dir( <span class="keyword">const</span> std::string&amp; path_to_log ) { <span class="comment">/* some work... */</span> } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-l"</span>, <span class="stringliteral">"--log-dir"</span>, log_dir ) .check_semantic( <a class="code" href="namespaceclpp.html#efe328c81928312195ba91a74a5b020667dfceda428ebe0abead66453110238c">clpp::path</a> ); <span class="comment">// ...</span> } </pre></div><p> In this case, value of <b>'--log-dir'</b> <em>must</em> be valid path in current filesystem.<p> Supported value's semantic: <ul> <li><b>path</b> (check of path correctness, in current filesystem), </li> <li><b>ipv4</b> (check of IP-address validity, exactly IPv4), </li> <li><b>ipv6</b> (check of IP-address validity, exactly IPv6), </li> <li><b>ip</b> (check of IP-address validity, IPv4 or IPv6). </li> <li><b>email</b> (check of E-mail validity).</li> </ul> <br/> <h3><a class="anchor" name="combine_of_settings"> Combine of settings</a></h3> Of course, you can combine settings for one parameter, like this:<p> <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> log_dir( <span class="keyword">const</span> std::string&amp; path_to_log ) { <span class="comment">/* some work... */</span> } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-l"</span>, <span class="stringliteral">"--log-dir"</span>, log_dir ) .default_value( <span class="stringliteral">"/some/default/path"</span> ) .check_semantic( <a class="code" href="namespaceclpp.html#efe328c81928312195ba91a74a5b020667dfceda428ebe0abead66453110238c">clpp::path</a> ) ; <span class="comment">// ...</span> } </pre></div><p> <b>Note:</b> You cannot combine <em>contradictory</em> settings. For example, if you write like this:<p> <div class="fragment"><pre class="fragment"> <span class="keywordtype">void</span> log_dir( <span class="keyword">const</span> std::string&amp; path_to_log ) { <span class="comment">/* some work... */</span> } <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-l"</span>, <span class="stringliteral">"--log-dir"</span>, log_dir ) .default_value( <span class="stringliteral">"/some/default/path"</span> ) .check_semantic( <a class="code" href="namespaceclpp.html#efe328c81928312195ba91a74a5b020667dfceda428ebe0abead66453110238c">clpp::path</a> ) .necessary() <span class="comment">// Necessary parameter with defined default value?? Hmm...</span> ; <span class="comment">// ...</span> } </pre></div><p> exception will throw.<p> <br/> <h3><a class="anchor" name="another_value_separator"> Another 'name-value' separator</a></h3> You can define another 'name-value' separator, instead default <b>'='</b>.<p> Use <b><a class="el" href="classclpp_1_1command__line__parameters__parser.html#353d9c4f2f3b56afbdd540c6e49ed674">clpp::command_line_parameters_parser::set_value_separator()</a></b> function.<p> <div class="fragment"><pre class="fragment"> <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#353d9c4f2f3b56afbdd540c6e49ed674">set_value_separator</a>( <span class="charliteral">':'</span> ); <span class="comment">// ...</span> } </pre></div><p> In this case, parameters with value <b>must</b> be input in command line like this:<p> <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program --log-dir:/some/path</span> </pre></div><p> Note: You CANNOT use characters with ASCII-code less than 0x21. They are unsuitable candidates for the separator role. :-)<p> <br/> <h3><a class="anchor" name="unnamed_params"> Unnamed parameters</a></h3> Sometimes you may want to use some parameters without explicitly inputed names.<p> For example, if you develop network program with console-defined host and port, you can use it like this:<p> <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program --host=127.0.0.1 --port=80</span> </pre></div><p> but you probably want to use it easier:<p> <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program 127.0.0.1 80</span> </pre></div><p> Use <b><a class="el" href="classclpp_1_1detail_1_1parameter.html#205fbf87a98ee76d3fd64b35e13c07eb">clpp::parameter::order()</a></b> function.<p> This function sets order number for parameter, so in our example <b>'host'</b> has order number 1, and <b>'port'</b> has order number 2. Note that order number begins with 1, because it is not <em>index</em>, but exactly number.<p> Of course, order number cannot be negative.<p> So you must register these parameters like this:<p> <div class="fragment"><pre class="fragment"> <span class="keyword">struct </span>my_server { <span class="keywordtype">void</span> host( <span class="keyword">const</span> std::string&amp; address ) { <span class="comment">/* some work... */</span> } <span class="keywordtype">void</span> port( <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> some_port ) { <span class="comment">/* some work... */</span> } }; <span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] ) { my_server server; <a class="code" href="classclpp_1_1command__line__parameters__parser.html" title="Parser.">clpp::command_line_parameters_parser</a> parser; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-h"</span>, <span class="stringliteral">"--host"</span>, &amp;server, &amp;my_server::host ) .order( 1 ) ; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-p"</span>, <span class="stringliteral">"--port"</span>, &amp;server, &amp;my_server::port ) .order( 2 ) ; <span class="comment">// ...</span> } </pre></div><p> Now you can use it like this:<p> <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program 127.0.0.1 80</span> </pre></div><p> but <b>not</b> vice versa:<p> <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program 80 127.0.0.1</span> </pre></div><p> because in this case <b>my_server::port()</b> function get string-argument, and exception will throw.<p> Remember that order numbers must be unique:<p> <div class="fragment"><pre class="fragment"> <span class="comment">// ...</span> parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-h"</span>, <span class="stringliteral">"--host"</span>, &amp;server, &amp;my_server::host ) .order( 1 ) ; parser.<a class="code" href="classclpp_1_1command__line__parameters__parser.html#39b7fc25e289a0b46f4d777bee421b1e">add_parameter</a>( <span class="stringliteral">"-p"</span>, <span class="stringliteral">"--port"</span>, &amp;server, &amp;my_server::port ) .order( 1 ) <span class="comment">// You inputed already used order?? Hmm...</span> ; <span class="comment">// ...</span> </pre></div><p> Of course, you can use "ordered" parameters with names, in any combination:<p> <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program -h=127.0.0.1 --port=80</span> </pre></div> <div class="fragment"><pre class="fragment"><span class="preprocessor"> # ./program 127.0.0.1 -p=80</span> </pre></div> </div> <hr size="1"><address style="text-align: right;"><small>Generated on Thu Oct 28 17:45:49 2010 for C++ command line parameters parser by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address> </body> </html>
{ "content_hash": "e1bc211e8bfb66577f38a585bfba06e0", "timestamp": "", "source": "github", "line_count": 300, "max_line_length": 707, "avg_line_length": 86.54666666666667, "alnum_prop": 0.6923047296256355, "repo_name": "makerbot/clp-parser", "id": "7b3f14b155edb2fcffac82600b47c6f6c74054bf", "size": "25964", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/user_guide.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "131323" } ], "symlink_target": "" }
Turbolinks =========== [![Build Status](https://travis-ci.org/rails/turbolinks.svg?branch=master)](https://travis-ci.org/rails/turbolinks) Turbolinks makes following links in your web application faster. Instead of letting the browser recompile the JavaScript and CSS between each page change, it keeps the current page instance alive and replaces only the body (or parts of) and the title in the head. Think CGI vs persistent process. This is similar to [pjax](https://github.com/defunkt/jquery-pjax), but instead of worrying about what element on the page to replace and tailoring the server-side response to fit, we replace the entire body by default, and let you specify which elements to replace on an opt-in basis. This means that you get the bulk of the speed benefits from pjax (no recompiling of the JavaScript or CSS) without having to tailor the server-side response. It just works. Do note that this of course means that you'll have a long-running, persistent session with maintained state. That's what's making it so fast. But it also means that you may have to pay additional care not to leak memory or otherwise bloat that long-running state. That should rarely be a problem unless you're doing something really funky, but you do have to be aware of it. Your memory leaking sins will not be swept away automatically by the cleansing page change any more. How much faster is it really? ----------------------------- It depends. The more CSS and JavaScript you have, the bigger the benefit of not throwing away the browser instance and recompiling all of it for every page. Just like a CGI script that says "hello world" will be fast, but a CGI script loading Rails on every request will not. In any case, the benefit can be up to [twice as fast](https://github.com/steveklabnik/turbolinks_test/tree/all_the_assets) in apps with lots of JS and CSS. Of course, your mileage may vary, be dependent on your browser version, the moon cycle, and all other factors affecting performance testing. But at least it's a yardstick. The best way to find out just how fast it is? Try it on your own application. It hardly takes any effort at all. No jQuery or any other library -------------------------------- Turbolinks is designed to be as light-weight as possible (so you won't think twice about using it even for mobile stuff). It does not require jQuery or any other library to work. But it works great _with_ the jQuery or Prototype framework, or whatever else you have. Events ------ With Turbolinks pages will change without a full reload, so you can't rely on `DOMContentLoaded` or `jQuery.ready()` to trigger your code. Instead Turbolinks fires events on `document` to provide hooks into the lifecycle of the page. ***Load* a fresh version of a page from the server:** * `page:before-change` a Turbolinks-enabled link has been clicked *(see below for more details)* * `page:fetch` starting to fetch a new target page * `page:receive` the page has been fetched from the server, but not yet parsed * `page:before-unload` the page has been parsed and is about to be changed * `page:change` the page has been changed to the new version (and on DOMContentLoaded) * `page:update` is triggered alongside both page:change and jQuery's ajaxSuccess (if jQuery is available - otherwise you can manually trigger it when calling XMLHttpRequest in your own code) * `page:load` is fired at the end of the loading process. Handlers bound to the `page:before-change` event may return `false`, which will cancel the Turbolinks process. By default, Turbolinks caches 10 of these page loads. It listens to the [popstate](https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_popstate_event) event and attempts to restore page state from the cache when it's triggered. When `popstate` is fired the following process happens: ***Restore* a cached page from the client-side cache:** * `page:before-unload` page has been fetched from the cache and is about to be changed * `page:change` page has changed to the cached page. * `page:restore` is fired at the end of restore process. The number of pages Turbolinks caches can be configured to suit your application's needs: ```javascript // View the current cache size Turbolinks.pagesCached(); // Set the cache size Turbolinks.pagesCached(20); ``` If you need to make dynamic HTML updates in the current page and want it to be cached properly you can call: ```javascript Turbolinks.cacheCurrentPage(); ``` When a page is removed from the cache due to the cache reaching its size limit, the `page:expire` event is triggered. Listeners bound to this event can access the cached page object using `event.originalEvent.data`. Keys of note for this page cache object include `url`, `body`, and `title`. To implement a client-side spinner, you could listen for `page:fetch` to start it and `page:receive` to stop it. ```javascript // using jQuery for simplicity $(document).on("page:fetch", startSpinner); $(document).on("page:receive", stopSpinner); ``` DOM transformations that are idempotent are best. If you have transformations that are not, bind them to `page:load` (in addition to the initial page load) instead of `page:change` (as that would run them again on the cached pages): ```javascript // using jQuery for simplicity $(document).on("ready page:load", nonIdempotentFunction); ``` Transition Cache: A Speed Boost ------------------------------- Transition Cache, added in v2.2.0, makes loading cached pages instantaneous. Once a user has visited a page, returning later to the page results in an instant load. For example, if Page A is already cached by Turbolinks and you are on Page B, clicking a link to Page A will *immediately* display the cached copy of Page A. Turbolinks will then fetch Page A from the server and replace the cached page once the new copy is returned. To enable Transition Cache, include the following in your javascript: ```javascript Turbolinks.enableTransitionCache(); ``` The one drawback is that dramatic differences in appearance between a cached copy and new copy may lead to a jarring affect for the end-user. This will be especially true for pages that have many moving parts (expandable sections, sortable tables, infinite scrolling, etc.). If you find that a page is causing problems, you can have Turbolinks skip displaying the cached copy by adding `data-no-transition-cache` to any DOM element on the offending page. Progress Bar ------------ Because Turbolinks skips the traditional full page reload, browsers won't display their native progress bar when changing pages. To fill this void, Turbolinks offers an optional JavaScript-and-CSS-based progress bar to display page loading progress. As of Turbolinks 3.0, the progress bar is turned on by default. To disable (or re-enable) the progress bar, include one of the following in your JavaScript: ```javascript Turbolinks.ProgressBar.disable(); Turbolinks.ProgressBar.enable(); ``` The progress bar is implemented on the `<html>` element's pseudo `:before` element and can be **customized** by including CSS with higher specificity than the included styles. For example: ```css html.turbolinks-progress-bar::before { background-color: red !important; height: 5px !important; } ``` Control the progress bar manually using these methods: ```javascript Turbolinks.ProgressBar.start(); Turbolinks.ProgressBar.advanceTo(value); // where value is between 0-100 Turbolinks.ProgressBar.done(); ``` Initialization -------------- Turbolinks will be enabled **only** if the server has rendered a `GET` request. Some examples, given a standard RESTful resource: * `POST :create` => resource successfully created => redirect to `GET :show` * Turbolinks **ENABLED** * `POST :create` => resource creation failed => render `:new` * Turbolinks **DISABLED** **Why not all request types?** Some browsers track the request method of each page load, but triggering pushState methods don't change this value. This could lead to the situation where pressing the browser's reload button on a page that was fetched with Turbolinks would attempt a `POST` (or something other than `GET`) because the last full page load used that method. Opting out of Turbolinks ------------------------ By default, all internal HTML links will be funneled through Turbolinks, but you can opt out by marking links or their parent container with `data-no-turbolink`. For example, if you mark a div with `data-no-turbolink`, then all links inside of that div will be treated as regular links. If you mark the body, every link on that entire page will be treated as regular links. ```html <a href="/">Home (via Turbolinks)</a> <div id="some-div" data-no-turbolink> <a href="/">Home (without Turbolinks)</a> </div> ``` Note that internal links to files containing a file extension other than **.html** will automatically be opted out of Turbolinks. So links to /images/panda.gif will just work as expected. To whitelist additional file extensions to be processed by Turbolinks, use `Turbolinks.allowLinkExtensions()`. ```javascript Turbolinks.allowLinkExtensions(); // => ['html'] Turbolinks.allowLinkExtensions('md'); // => ['html', 'md'] Turbolinks.allowLinkExtensions('coffee', 'scss'); // => ['html', 'md', 'coffee', 'scss'] ``` Also, Turbolinks is installed as the last click handler for links. So if you install another handler that calls event.preventDefault(), Turbolinks will not run. This ensures that you can safely use Turbolinks with stuff like `data-method`, `data-remote`, or `data-confirm` from Rails. Note: in Turbolinks 3.0, the default behavior of `redirect_to` is to redirect via Turbolinks (`Turbolinks.visit` response) for XHR + non-GET requests. You can opt-out of this behavior by passing `turbolinks: false` to `redirect_to`. jquery.turbolinks ----------------- If you have a lot of existing JavaScript that binds elements on jQuery.ready(), you can pull the [jquery.turbolinks](https://github.com/kossnocorp/jquery.turbolinks) library into your project that will trigger ready() when Turbolinks triggers the `page:load` event. It may restore functionality of some libraries. Add the gem to your project, then add the following line to your JavaScript manifest file, after `jquery.js` but before `turbolinks.js`: ``` js //= require jquery.turbolinks ``` Additional details and configuration options can be found in the [jquery.turbolinks README](https://github.com/kossnocorp/jquery.turbolinks/blob/master/README.md). Asset change detection ---------------------- You can track certain assets, like application.js and application.css, that you want to ensure are always of the latest version inside a Turbolinks session. This is done by marking those asset links with data-turbolinks-track, like so: ```html <link href="/assets/application-9bd64a86adb3cd9ab3b16e9dca67a33a.css" rel="stylesheet" type="text/css" data-turbolinks-track> ``` If those assets change URLs (embed an md5 stamp to ensure this), the page will do a full reload instead of going through Turbolinks. This ensures that all Turbolinks sessions will always be running off your latest JavaScript and CSS. When this happens, you'll technically be requesting the same page twice. Once through Turbolinks to detect that the assets changed, and then again when we do a full redirect to that page. Evaluating script tags ---------------------- Turbolinks will evaluate any script tags in pages it visits, if those tags do not have a type or if the type is text/javascript. All other script tags will be ignored. As a rule of thumb when switching to Turbolinks, move all of your javascript tags inside the `head` and then work backwards, only moving javascript code back to the body if absolutely necessary. If you have any script tags in the body you do not want to be re-evaluated then you can set the `data-turbolinks-eval` attribute to `false`: ```html <script type="text/javascript" data-turbolinks-eval=false> console.log("I'm only run once on the initial page load"); </script> ``` Triggering a Turbolinks visit manually --------------------------------------- You can use `Turbolinks.visit(path)` to go to a URL through Turbolinks. You can also use `redirect_to path, turbolinks: true` in Rails to perform a redirect via Turbolinks. Partial replacements with Turbolinks (3.0+) ------------------------------------------- You can use either `Turbolinks.visit(path, options)` or `Turbolinks.replace(html, options)` to trigger partial replacement of nodes in your DOM instead of replacing the entire `body`. Turbolinks' partial replacement strategy relies on `id` attributes specified on individual nodes or a combination of `id` and `data-turbolinks-permanent` or `data-turbolinks-temporary` attributes. ```html <div id="comments"></div> <div id="nav" data-turbolinks-permanent></div> <div id="footer" data-turbolinks-temporary></div> ``` Any node with an `id` attribute can be partially replaced. If the `id` contains a colon, the key before the colon can also be targeted to replace many nodes with a similar prefix. ```html <div id="comments"></div> <div id="comments:123"></div> ``` `Turbolinks.visit` should be used when you want to perform an XHR request to fetch the latest content from the server and replace all or some of the nodes. `Turbolinks.replace` should be used when you already have a response body and want to replace the contents of the current page with it. This is needed for contextual responses like validation errors after a failed `create` attempt since fetching the page again would lose the validation errors. ```html+erb <body> <div id="sidebar" data-turbolinks-permanent> Sidebar, never changes after initial load. </div> <div id="flash" data-turbolinks-temporary> You have <%= @comments.count %> comments. </div> <section id="comments"> <%= @comments.each do |comment| %> <article id="comments:<%= comment.id %>"> <h1><%= comment.author %></h1> <p><%= comment.body %></p> </article> <% end %> </section> <%= form_for Comment.new, remote: true, id: 'new_comment' do |form| %> <%= form.text_area :content %> <%= form.submit %> <% end %> </body> <script> // Will change #flash, #comments, #comments:123 Turbolinks.visit(url, change: 'comments') // Will change #flash, #comment_123 Turbolinks.visit(url, change: 'comments:123') // Will only keep #sidebar Turbolinks.visit(url) // Will only keep #sidebar, #flash Turbolinks.visit(url, keep: 'flash') // Will keep nothing Turbolinks.visit(url, flush: true) // Same as visit() but takes a string or Document, allowing you to // do inline responses instead of issuing a new GET with Turbolinks.visit. // This is useful for things like form validation errors or other // contextualized responses. Turbolinks.replace(html, options) </script> ``` Partial replacement decisions can also be made server-side by using `redirect_to` or `render` with `change`, `keep`, or `flush` options. ```ruby class CommentsController < ActionController::Base def create @comment = Comment.new(comment_params) if @comment.save # This will change #flash, #comments redirect_to comments_url, change: 'comments' # => Turbolinks.visit('/comments', change: 'comments') else # Validation failure render :new, change: :new_comment # => Turbolinks.replace('<%=j render :new %>', change: 'new_comment') end end end ``` ```ruby # Redirect via Turbolinks when the request is XHR and not GET. # Will refresh any `data-turbolinks-temporary` nodes. redirect_to path # Force a redirect via Turbolinks. redirect_to path, turbolinks: true # Force a normal redirection. redirect_to path, turbolinks: false # Partially replace any `data-turbolinks-temporary` nodes and nodes with `id`s matching `comments` or `comments:*`. redirect_to path, change: 'comments' # Partially replace any `data-turbolinks-temoprary` nodes and nodes with `id` not matching `something` and `something:*`. redirect_to path, keep: 'something' # Replace the entire `body` of the document, including `data-turbolinks-permanent` nodes. redirect_to path, flush: true ``` ```ruby # Render with Turbolinks when the request is XHR and not GET. # Refresh any `data-turbolinks-temporary` nodes and nodes with `id` matching `new_comment`. render view, change: 'new_comment' # Refresh any `data-turbolinks-temporary` nodes and nodes with `id` not matching `something` and `something:*`. render view, keep: 'something' # Replace the entire `body` of the document, including `data-turbolinks-permanent` nodes. render view, flush: true # Force a render with Turbolinks. render view, turbolinks: true # Force a normal render. render view, turbolinks: false ``` XHR Request Caching (3.0+) -------------------------- To prevent browsers from caching Turbolinks requests: ```coffeescript # Globally Turbolinks.disableRequestCaching() # Per Request Turbolinks.visit url, cacheRequest: false ``` This works just like `jQuery.ajax(url, cache: false)`, appending `"_#{timestamp}"` to the GET parameters. Full speed for pushState browsers, graceful fallback for everything else ------------------------------------------------------------------------ Like pjax, this naturally only works with browsers capable of pushState. But of course we fall back gracefully to full page reloads for browsers that do not support it. Compatibility ------------- Turbolinks is designed to work with any browser that fully supports pushState and all the related APIs. This includes Safari 6.0+ (but not Safari 5.1.x!), IE10, and latest Chromes and Firefoxes. Do note that existing JavaScript libraries may not all be compatible with Turbolinks out of the box due to the change in instantiation cycle. You might very well have to modify them to work with Turbolinks' new set of events. For help with this, check out the [Turbolinks Compatibility](http://reed.github.io/turbolinks-compatibility) project. Turbolinks works with Rails 3.2 and newer. Installation ------------ 1. Add `gem 'turbolinks'` to your Gemfile. 1. Run `bundle install`. 1. Add `//= require turbolinks` to your Javascript manifest file (usually found at `app/assets/javascripts/application.js`). If your manifest requires both turbolinks and jQuery, make sure turbolinks is listed *after* jQuery. 1. Restart your server and you're now using turbolinks! Running the tests ----------------- Ruby: ``` rake test:all BUNDLE_GEMFILE=Gemfile.rails42 bundle BUNDLE_GEMFILE=Gemfile.rails42 rake test ``` JavaScript: ``` npm install cd test bundle bundle exec rackup open http://localhost:9292/javascript/index.html ``` Language Ports -------------- *These projects are not affiliated with or endorsed by the Rails Turbolinks team.* * [Flask Turbolinks](https://github.com/lepture/flask-turbolinks) (Python Flask) * [Django Turbolinks](https://github.com/dgladkov/django-turbolinks) (Python Django) * [ASP.NET MVC Turbolinks](https://github.com/kazimanzurrashid/aspnetmvcturbolinks) * [PHP Turbolinks Component](https://github.com/helthe/Turbolinks) (Symfony Component) * [PHP Turbolinks Package](https://github.com/frenzyapp/turbolinks) (Laravel Package) * [Grails Turbolinks](http://grails.org/plugin/turbolinks) (Grails Plugin) Credits ------- Thanks to Chris Wanstrath for his original work on Pjax. Thanks to Sam Stephenson and Josh Peek for their additional work on Pjax and Stacker and their help with getting Turbolinks released. Thanks to David Estes and Nick Reed for handling the lion's share of post-release issues and feature requests. And thanks to everyone else who's fixed or reported an issue!
{ "content_hash": "d7d6bbad76fe85e138df9a751dd04291", "timestamp": "", "source": "github", "line_count": 428, "max_line_length": 475, "avg_line_length": 46.16588785046729, "alnum_prop": 0.7418897717495825, "repo_name": "peterjm/turbolinks", "id": "7b436306094333141a8cde0a1de2853e7f30c791", "size": "19759", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "32148" }, { "name": "HTML", "bytes": "10185" }, { "name": "Ruby", "bytes": "28067" } ], "symlink_target": "" }
/* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F7xx_HAL_DMA2D_H #define __STM32F7xx_HAL_DMA2D_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f7xx_hal_def.h" /** @addtogroup STM32F7xx_HAL_Driver * @{ */ /** @defgroup DMA2D DMA2D * @brief DMA2D HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Types DMA2D Exported Types * @{ */ #define MAX_DMA2D_LAYER 2 /** * @brief DMA2D color Structure definition */ typedef struct { uint32_t Blue; /*!< Configures the blue value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Green; /*!< Configures the green value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ uint32_t Red; /*!< Configures the red value. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */ } DMA2D_ColorTypeDef; /** * @brief DMA2D CLUT Structure definition */ typedef struct { uint32_t *pCLUT; /*!< Configures the DMA2D CLUT memory address.*/ uint32_t CLUTColorMode; /*!< configures the DMA2D CLUT color mode. This parameter can be one value of @ref DMA2D_CLUT_CM */ uint32_t Size; /*!< configures the DMA2D CLUT size. This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF.*/ } DMA2D_CLUTCfgTypeDef; /** * @brief DMA2D Init structure definition */ typedef struct { uint32_t Mode; /*!< configures the DMA2D transfer mode. This parameter can be one value of @ref DMA2D_Mode */ uint32_t ColorMode; /*!< configures the color format of the output image. This parameter can be one value of @ref DMA2D_Color_Mode */ uint32_t OutputOffset; /*!< Specifies the Offset value. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x3FFF. */ } DMA2D_InitTypeDef; /** * @brief DMA2D Layer structure definition */ typedef struct { uint32_t InputOffset; /*!< configures the DMA2D foreground offset. This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x3FFF. */ uint32_t InputColorMode; /*!< configures the DMA2D foreground color mode . This parameter can be one value of @ref DMA2D_Input_Color_Mode */ uint32_t AlphaMode; /*!< configures the DMA2D foreground alpha mode. This parameter can be one value of @ref DMA2D_ALPHA_MODE */ uint32_t InputAlpha; /*!< Specifies the DMA2D foreground alpha value and color value in case of A8 or A4 color mode. This parameter must be a number between Min_Data = 0x00000000 and Max_Data = 0xFFFFFFFF in case of A8 or A4 color mode (ARGB). Otherwise, This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF.*/ } DMA2D_LayerCfgTypeDef; /** * @brief HAL DMA2D State structures definition */ typedef enum { HAL_DMA2D_STATE_RESET = 0x00, /*!< DMA2D not yet initialized or disabled */ HAL_DMA2D_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ HAL_DMA2D_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ HAL_DMA2D_STATE_TIMEOUT = 0x03, /*!< Timeout state */ HAL_DMA2D_STATE_ERROR = 0x04, /*!< DMA2D state error */ HAL_DMA2D_STATE_SUSPEND = 0x05 /*!< DMA2D process is suspended */ }HAL_DMA2D_StateTypeDef; /** * @brief DMA2D handle Structure definition */ typedef struct __DMA2D_HandleTypeDef { DMA2D_TypeDef *Instance; /*!< DMA2D Register base address */ DMA2D_InitTypeDef Init; /*!< DMA2D communication parameters */ void (* XferCpltCallback)(struct __DMA2D_HandleTypeDef * hdma2d); /*!< DMA2D transfer complete callback */ void (* XferErrorCallback)(struct __DMA2D_HandleTypeDef * hdma2d); /*!< DMA2D transfer error callback */ DMA2D_LayerCfgTypeDef LayerCfg[MAX_DMA2D_LAYER]; /*!< DMA2D Layers parameters */ HAL_LockTypeDef Lock; /*!< DMA2D Lock */ __IO HAL_DMA2D_StateTypeDef State; /*!< DMA2D transfer state */ __IO uint32_t ErrorCode; /*!< DMA2D Error code */ } DMA2D_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Constants DMA2D Exported Constants * @{ */ /** @defgroup DMA2D_Error_Code DMA2D Error Code * @{ */ #define HAL_DMA2D_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_DMA2D_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ #define HAL_DMA2D_ERROR_CE ((uint32_t)0x00000002) /*!< Configuration error */ #define HAL_DMA2D_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ /** * @} */ /** @defgroup DMA2D_Mode DMA2D Mode * @{ */ #define DMA2D_M2M ((uint32_t)0x00000000) /*!< DMA2D memory to memory transfer mode */ #define DMA2D_M2M_PFC ((uint32_t)0x00010000) /*!< DMA2D memory to memory with pixel format conversion transfer mode */ #define DMA2D_M2M_BLEND ((uint32_t)0x00020000) /*!< DMA2D memory to memory with blending transfer mode */ #define DMA2D_R2M ((uint32_t)0x00030000) /*!< DMA2D register to memory transfer mode */ /** * @} */ /** @defgroup DMA2D_Color_Mode DMA2D Color Mode * @{ */ #define DMA2D_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 DMA2D color mode */ #define DMA2D_RGB888 ((uint32_t)0x00000001) /*!< RGB888 DMA2D color mode */ #define DMA2D_RGB565 ((uint32_t)0x00000002) /*!< RGB565 DMA2D color mode */ #define DMA2D_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 DMA2D color mode */ #define DMA2D_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 DMA2D color mode */ /** * @} */ /** @defgroup DMA2D_COLOR_VALUE DMA2D COLOR VALUE * @{ */ #define COLOR_VALUE ((uint32_t)0x000000FF) /*!< color value mask */ /** * @} */ /** @defgroup DMA2D_SIZE DMA2D SIZE * @{ */ #define DMA2D_PIXEL (DMA2D_NLR_PL >> 16) /*!< DMA2D pixel per line */ #define DMA2D_LINE DMA2D_NLR_NL /*!< DMA2D number of line */ /** * @} */ /** @defgroup DMA2D_Offset DMA2D Offset * @{ */ #define DMA2D_OFFSET DMA2D_FGOR_LO /*!< Line Offset */ /** * @} */ /** @defgroup DMA2D_Input_Color_Mode DMA2D Input Color Mode * @{ */ #define CM_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 color mode */ #define CM_RGB888 ((uint32_t)0x00000001) /*!< RGB888 color mode */ #define CM_RGB565 ((uint32_t)0x00000002) /*!< RGB565 color mode */ #define CM_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 color mode */ #define CM_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 color mode */ #define CM_L8 ((uint32_t)0x00000005) /*!< L8 color mode */ #define CM_AL44 ((uint32_t)0x00000006) /*!< AL44 color mode */ #define CM_AL88 ((uint32_t)0x00000007) /*!< AL88 color mode */ #define CM_L4 ((uint32_t)0x00000008) /*!< L4 color mode */ #define CM_A8 ((uint32_t)0x00000009) /*!< A8 color mode */ #define CM_A4 ((uint32_t)0x0000000A) /*!< A4 color mode */ /** * @} */ /** @defgroup DMA2D_ALPHA_MODE DMA2D ALPHA MODE * @{ */ #define DMA2D_NO_MODIF_ALPHA ((uint32_t)0x00000000) /*!< No modification of the alpha channel value */ #define DMA2D_REPLACE_ALPHA ((uint32_t)0x00000001) /*!< Replace original alpha channel value by programmed alpha value */ #define DMA2D_COMBINE_ALPHA ((uint32_t)0x00000002) /*!< Replace original alpha channel value by programmed alpha value with original alpha channel value */ /** * @} */ /** @defgroup DMA2D_CLUT_CM DMA2D CLUT CM * @{ */ #define DMA2D_CCM_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 DMA2D C-LUT color mode */ #define DMA2D_CCM_RGB888 ((uint32_t)0x00000001) /*!< RGB888 DMA2D C-LUT color mode */ /** * @} */ /** @defgroup DMA2D_Size_Clut DMA2D Size Clut * @{ */ #define DMA2D_CLUT_SIZE (DMA2D_FGPFCCR_CS >> 8) /*!< DMA2D C-LUT size */ /** * @} */ /** @defgroup DMA2D_DeadTime DMA2D DeadTime * @{ */ #define LINE_WATERMARK DMA2D_LWR_LW /** * @} */ /** @defgroup DMA2D_Interrupts DMA2D Interrupts * @{ */ #define DMA2D_IT_CE DMA2D_CR_CEIE /*!< Configuration Error Interrupt */ #define DMA2D_IT_CTC DMA2D_CR_CTCIE /*!< C-LUT Transfer Complete Interrupt */ #define DMA2D_IT_CAE DMA2D_CR_CAEIE /*!< C-LUT Access Error Interrupt */ #define DMA2D_IT_TW DMA2D_CR_TWIE /*!< Transfer Watermark Interrupt */ #define DMA2D_IT_TC DMA2D_CR_TCIE /*!< Transfer Complete Interrupt */ #define DMA2D_IT_TE DMA2D_CR_TEIE /*!< Transfer Error Interrupt */ /** * @} */ /** @defgroup DMA2D_Flag DMA2D Flag * @{ */ #define DMA2D_FLAG_CE DMA2D_ISR_CEIF /*!< Configuration Error Interrupt Flag */ #define DMA2D_FLAG_CTC DMA2D_ISR_CTCIF /*!< C-LUT Transfer Complete Interrupt Flag */ #define DMA2D_FLAG_CAE DMA2D_ISR_CAEIF /*!< C-LUT Access Error Interrupt Flag */ #define DMA2D_FLAG_TW DMA2D_ISR_TWIF /*!< Transfer Watermark Interrupt Flag */ #define DMA2D_FLAG_TC DMA2D_ISR_TCIF /*!< Transfer Complete Interrupt Flag */ #define DMA2D_FLAG_TE DMA2D_ISR_TEIF /*!< Transfer Error Interrupt Flag */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Macros DMA2D Exported Macros * @{ */ /** @brief Reset DMA2D handle state * @param __HANDLE__: specifies the DMA2D handle. * @retval None */ #define __HAL_DMA2D_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA2D_STATE_RESET) /** * @brief Enable the DMA2D. * @param __HANDLE__: DMA2D handle * @retval None. */ #define __HAL_DMA2D_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DMA2D_CR_START) /** * @brief Disable the DMA2D. * @param __HANDLE__: DMA2D handle * @retval None. */ #define __HAL_DMA2D_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~DMA2D_CR_START) /* Interrupt & Flag management */ /** * @brief Get the DMA2D pending flags. * @param __HANDLE__: DMA2D handle * @param __FLAG__: Get the specified flag. * This parameter can be any combination of the following values: * @arg DMA2D_FLAG_CE: Configuration error flag * @arg DMA2D_FLAG_CTC: C-LUT transfer complete flag * @arg DMA2D_FLAG_CAE: C-LUT access error flag * @arg DMA2D_FLAG_TW: Transfer Watermark flag * @arg DMA2D_FLAG_TC: Transfer complete flag * @arg DMA2D_FLAG_TE: Transfer error flag * @retval The state of FLAG. */ #define __HAL_DMA2D_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR & (__FLAG__)) /** * @brief Clears the DMA2D pending flags. * @param __HANDLE__: DMA2D handle * @param __FLAG__: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg DMA2D_FLAG_CE: Configuration error flag * @arg DMA2D_FLAG_CTC: C-LUT transfer complete flag * @arg DMA2D_FLAG_CAE: C-LUT access error flag * @arg DMA2D_FLAG_TW: Transfer Watermark flag * @arg DMA2D_FLAG_TC: Transfer complete flag * @arg DMA2D_FLAG_TE: Transfer error flag * @retval None */ #define __HAL_DMA2D_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->IFCR = (__FLAG__)) /** * @brief Enables the specified DMA2D interrupts. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt sources to be enabled. * This parameter can be any combination of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA2D_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) /** * @brief Disables the specified DMA2D interrupts. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt sources to be disabled. * This parameter can be any combination of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval None */ #define __HAL_DMA2D_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) /** * @brief Checks whether the specified DMA2D interrupt has occurred or not. * @param __HANDLE__: DMA2D handle * @param __INTERRUPT__: specifies the DMA2D interrupt source to check. * This parameter can be one of the following values: * @arg DMA2D_IT_CE: Configuration error interrupt mask * @arg DMA2D_IT_CTC: C-LUT transfer complete interrupt mask * @arg DMA2D_IT_CAE: C-LUT access error interrupt mask * @arg DMA2D_IT_TW: Transfer Watermark interrupt mask * @arg DMA2D_IT_TC: Transfer complete interrupt mask * @arg DMA2D_IT_TE: Transfer error interrupt mask * @retval The state of INTERRUPT. */ #define __HAL_DMA2D_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR & (__INTERRUPT__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup DMA2D_Exported_Functions DMA2D Exported Functions * @{ */ /* Initialization and de-initialization functions *******************************/ HAL_StatusTypeDef HAL_DMA2D_Init(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_DeInit (DMA2D_HandleTypeDef *hdma2d); void HAL_DMA2D_MspInit(DMA2D_HandleTypeDef* hdma2d); void HAL_DMA2D_MspDeInit(DMA2D_HandleTypeDef* hdma2d); /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_DMA2D_Start(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_BlendingStart(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_Start_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t pdata, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_BlendingStart_IT(DMA2D_HandleTypeDef *hdma2d, uint32_t SrcAddress1, uint32_t SrcAddress2, uint32_t DstAddress, uint32_t Width, uint32_t Height); HAL_StatusTypeDef HAL_DMA2D_Suspend(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_Resume(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_Abort(DMA2D_HandleTypeDef *hdma2d); HAL_StatusTypeDef HAL_DMA2D_PollForTransfer(DMA2D_HandleTypeDef *hdma2d, uint32_t Timeout); void HAL_DMA2D_IRQHandler(DMA2D_HandleTypeDef *hdma2d); /* Peripheral Control functions *************************************************/ HAL_StatusTypeDef HAL_DMA2D_ConfigLayer(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_ConfigCLUT(DMA2D_HandleTypeDef *hdma2d, DMA2D_CLUTCfgTypeDef CLUTCfg, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_EnableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_DisableCLUT(DMA2D_HandleTypeDef *hdma2d, uint32_t LayerIdx); HAL_StatusTypeDef HAL_DMA2D_ProgramLineEvent(DMA2D_HandleTypeDef *hdma2d, uint32_t Line); /* Peripheral State functions ***************************************************/ HAL_DMA2D_StateTypeDef HAL_DMA2D_GetState(DMA2D_HandleTypeDef *hdma2d); uint32_t HAL_DMA2D_GetError(DMA2D_HandleTypeDef *hdma2d); /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Types DMA2D Private Types * @{ */ /** * @} */ /* Private defines -------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Defines DMA2D Private Defines * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Variables DMA2D Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Constants DMA2D Private Constants * @{ */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup DMA2D_Private_Macros DMA2D Private Macros * @{ */ #define IS_DMA2D_LAYER(LAYER) ((LAYER) <= MAX_DMA2D_LAYER) #define IS_DMA2D_MODE(MODE) (((MODE) == DMA2D_M2M) || ((MODE) == DMA2D_M2M_PFC) || \ ((MODE) == DMA2D_M2M_BLEND) || ((MODE) == DMA2D_R2M)) #define IS_DMA2D_CMODE(MODE_ARGB) (((MODE_ARGB) == DMA2D_ARGB8888) || ((MODE_ARGB) == DMA2D_RGB888) || \ ((MODE_ARGB) == DMA2D_RGB565) || ((MODE_ARGB) == DMA2D_ARGB1555) || \ ((MODE_ARGB) == DMA2D_ARGB4444)) #define IS_DMA2D_COLOR(COLOR) ((COLOR) <= COLOR_VALUE) #define IS_DMA2D_LINE(LINE) ((LINE) <= DMA2D_LINE) #define IS_DMA2D_PIXEL(PIXEL) ((PIXEL) <= DMA2D_PIXEL) #define IS_DMA2D_OFFSET(OOFFSET) ((OOFFSET) <= DMA2D_OFFSET) #define IS_DMA2D_INPUT_COLOR_MODE(INPUT_CM) (((INPUT_CM) == CM_ARGB8888) || ((INPUT_CM) == CM_RGB888) || \ ((INPUT_CM) == CM_RGB565) || ((INPUT_CM) == CM_ARGB1555) || \ ((INPUT_CM) == CM_ARGB4444) || ((INPUT_CM) == CM_L8) || \ ((INPUT_CM) == CM_AL44) || ((INPUT_CM) == CM_AL88) || \ ((INPUT_CM) == CM_L4) || ((INPUT_CM) == CM_A8) || \ ((INPUT_CM) == CM_A4)) #define IS_DMA2D_ALPHA_MODE(AlphaMode) (((AlphaMode) == DMA2D_NO_MODIF_ALPHA) || \ ((AlphaMode) == DMA2D_REPLACE_ALPHA) || \ ((AlphaMode) == DMA2D_COMBINE_ALPHA)) #define IS_DMA2D_CLUT_CM(CLUT_CM) (((CLUT_CM) == DMA2D_CCM_ARGB8888) || ((CLUT_CM) == DMA2D_CCM_RGB888)) #define IS_DMA2D_CLUT_SIZE(CLUT_SIZE) ((CLUT_SIZE) <= DMA2D_CLUT_SIZE) #define IS_DMA2D_LineWatermark(LineWatermark) ((LineWatermark) <= LINE_WATERMARK) #define IS_DMA2D_IT(IT) (((IT) == DMA2D_IT_CTC) || ((IT) == DMA2D_IT_CAE) || \ ((IT) == DMA2D_IT_TW) || ((IT) == DMA2D_IT_TC) || \ ((IT) == DMA2D_IT_TE) || ((IT) == DMA2D_IT_CE)) #define IS_DMA2D_GET_FLAG(FLAG) (((FLAG) == DMA2D_FLAG_CTC) || ((FLAG) == DMA2D_FLAG_CAE) || \ ((FLAG) == DMA2D_FLAG_TW) || ((FLAG) == DMA2D_FLAG_TC) || \ ((FLAG) == DMA2D_FLAG_TE) || ((FLAG) == DMA2D_FLAG_CE)) /** * @} */ /* Private functions prototypes ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Functions_Prototypes DMA2D Private Functions Prototypes * @{ */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup DMA2D_Private_Functions DMA2D Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F7xx_HAL_DMA2D_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "content_hash": "2b7ad3fe6332dc3203b3da9c3e26c573", "timestamp": "", "source": "github", "line_count": 524, "max_line_length": 172, "avg_line_length": 44.29770992366412, "alnum_prop": 0.5125797001550922, "repo_name": "PUCSIE-embedded-course/stm32f4-examples", "id": "68526825da70d96d27cc748355001c960b5d9190", "size": "25296", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "firmware/freertos/queue/lib/FreeRTOSV8.2.3/FreeRTOS/Demo/CORTEX_M7_STM32F7_STM32756G-EVAL_IAR_Keil/ST_Library/include/stm32f7xx_hal_dma2d.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "8079900" }, { "name": "Batchfile", "bytes": "321800" }, { "name": "C", "bytes": "397975006" }, { "name": "C++", "bytes": "23020398" }, { "name": "CSS", "bytes": "118382" }, { "name": "CartoCSS", "bytes": "41264" }, { "name": "Groff", "bytes": "140658" }, { "name": "HTML", "bytes": "6861248" }, { "name": "JavaScript", "bytes": "11012" }, { "name": "LSL", "bytes": "856" }, { "name": "Logos", "bytes": "17350" }, { "name": "M4", "bytes": "255202" }, { "name": "Makefile", "bytes": "1768370" }, { "name": "Objective-C", "bytes": "437644" }, { "name": "Opa", "bytes": "954" }, { "name": "Perl", "bytes": "149980" }, { "name": "Python", "bytes": "4534" }, { "name": "Shell", "bytes": "698336" }, { "name": "Standard ML", "bytes": "4208" }, { "name": "SuperCollider", "bytes": "75562" }, { "name": "Tcl", "bytes": "179850" }, { "name": "XSLT", "bytes": "4203792" } ], "symlink_target": "" }
namespace net { class CookieStore; class HttpTransactionFactory; class ProxyConfigService; class URLRequestContext; class URLRequestJobFactory; } namespace data_reduction_proxy { class DataReductionProxyConfigService; } using data_reduction_proxy::DataReductionProxyConfigService; namespace android_webview { class AwNetworkDelegate; class AwURLRequestContextGetter : public net::URLRequestContextGetter { public: AwURLRequestContextGetter(const base::FilePath& partition_path, net::CookieStore* cookie_store); void InitializeOnNetworkThread(); // net::URLRequestContextGetter implementation. virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE; virtual scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() const OVERRIDE; DataReductionProxyConfigService* proxy_config_service(); private: friend class AwBrowserContext; virtual ~AwURLRequestContextGetter(); // Prior to GetURLRequestContext() being called, this is called to hand over // the objects that GetURLRequestContext() will later install into // |job_factory_|. This ordering is enforced by having // AwBrowserContext::CreateRequestContext() call this method. // This method is necessary because the passed in objects are created // on the UI thread while |job_factory_| must be created on the IO thread. void SetHandlersAndInterceptors( content::ProtocolHandlerMap* protocol_handlers, content::URLRequestInterceptorScopedVector request_interceptors); void InitializeURLRequestContext(); const base::FilePath partition_path_; scoped_refptr<net::CookieStore> cookie_store_; scoped_ptr<net::URLRequestContext> url_request_context_; scoped_ptr<DataReductionProxyConfigService> proxy_config_service_; scoped_ptr<net::URLRequestJobFactory> job_factory_; scoped_ptr<net::HttpTransactionFactory> main_http_factory_; scoped_ptr<net::ServerBoundCertService> server_bound_cert_service_; // ProtocolHandlers and interceptors are stored here between // SetHandlersAndInterceptors() and the first GetURLRequestContext() call. content::ProtocolHandlerMap protocol_handlers_; content::URLRequestInterceptorScopedVector request_interceptors_; DISALLOW_COPY_AND_ASSIGN(AwURLRequestContextGetter); }; } // namespace android_webview #endif // ANDROID_WEBVIEW_BROWSER_NET_AW_URL_REQUEST_CONTEXT_GETTER_H_
{ "content_hash": "cca45c60c0e7fcdb7d3028ea1c28742e", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 78, "avg_line_length": 35.71641791044776, "alnum_prop": 0.7860426243209361, "repo_name": "andykimpe/chromium-test-npapi", "id": "8eedbc400b3d89ab07cc72abbca3d7338960636c", "size": "3096", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "android_webview/browser/net/aw_url_request_context_getter.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Assembly", "bytes": "24741" }, { "name": "Batchfile", "bytes": "6704" }, { "name": "C", "bytes": "3578395" }, { "name": "C++", "bytes": "197882186" }, { "name": "CSS", "bytes": "774304" }, { "name": "HTML", "bytes": "16781925" }, { "name": "Java", "bytes": "5176812" }, { "name": "JavaScript", "bytes": "9838003" }, { "name": "Makefile", "bytes": "36405" }, { "name": "Objective-C", "bytes": "1135377" }, { "name": "Objective-C++", "bytes": "7082902" }, { "name": "PLpgSQL", "bytes": "141320" }, { "name": "Perl", "bytes": "69392" }, { "name": "Protocol Buffer", "bytes": "360984" }, { "name": "Python", "bytes": "5577847" }, { "name": "Rebol", "bytes": "262" }, { "name": "Shell", "bytes": "434741" }, { "name": "Standard ML", "bytes": "1589" }, { "name": "nesC", "bytes": "15206" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> {% block head %} <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}"/> <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"/> <title>{% block title %}Code Pub{% endblock %} - SVN tools</title> {% endblock %} </head> <body> <div class="container"> <div id="navigator"> {% block navigator %} <div class="page-header"> <h3>Genscript 供应链代码发布系统 <small>v1.0.1 <p class="text-right" style="font-size:9pt">你好,{{ current_user.username }} <a href="#">登出</a></p></small> </h3> </div> <ul class="nav nav-tabs" role="tablist" id="menu"> <li class=""><a href="{{ url_for("dashboard.index") }}">首页</a></li> <li ><a href="{{ url_for("dashboard.show", system= "usorder") }}">US Order</a></li> <li class=""><a href="{{ url_for("dashboard.show", system= "cnorder") }}">CN Order</a></li> <li class=""><a href="{{ url_for("dashboard.show", system= "jporder") }}">JP Order</a></li> <li class=""><a href="{{ url_for("dashboard.show", system= "usshipping") }}">US/JP Shipping</a></li> <li class=""><a href="{{ url_for("dashboard.show", system="cnshipping") }}">CN Shipping</a></li> <li class=""><a href="{{ url_for("dashboard.show", system="manufacturing") }}">Manufacturing</a></li> <li class=""><a href="{{ url_for("dashboard.show", system="material") }}">Material</a></li> <li class=""><a href="{{ url_for("dashboard.show", system= "fedexClient") }}">Fedex client</a></li> </ul> </div> {% endblock %} <div class="row"> <div id="sitemenu"> {% block sitemenu %} {% endblock %} </div> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} <div class="col-md-12"> <h6 class="text-center">Created On 20161101 <small> @author: follow <a id=time></a></small> </h6> </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script> <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script> <script src="{{ url_for('static', filename='js/main.js') }}"></script> <script src="{{ url_for('static', filename='js/my_code_pub.js') }}"></script> {% endblock %} </div> </div> </div> </div> </body>
{ "content_hash": "e77fd65814359b36576c01a262bad9fe", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 117, "avg_line_length": 47.234375, "alnum_prop": 0.47568640423420444, "repo_name": "apen-yong/scm-manager", "id": "3178153400113ecdab6673b1331aa7b59f433673", "size": "3055", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/base.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "277" }, { "name": "HTML", "bytes": "27414" }, { "name": "JavaScript", "bytes": "8307" }, { "name": "Python", "bytes": "24894" } ], "symlink_target": "" }
#include <tommath.h> #ifdef BN_MP_DR_REDUCE_C /* LibTomMath, multiple-precision integer library -- Tom St Denis * * LibTomMath is a library that provides multiple-precision * integer arithmetic as well as number theoretic functionality. * * The library was designed directly after the MPI library by * Michael Fromberger but has been written from scratch with * additional optimizations in place. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, [email protected], http://libtom.org */ /* reduce "x" in place modulo "n" using the Diminished Radix algorithm. * * Based on algorithm from the paper * * "Generating Efficient Primes for Discrete Log Cryptosystems" * Chae Hoon Lim, Pil Joong Lee, * POSTECH Information Research Laboratories * * The modulus must be of a special format [see manual] * * Has been modified to use algorithm 7.10 from the LTM book instead * * Input x must be in the range 0 <= x <= (n-1)**2 */ int mp_dr_reduce (mp_int * x, mp_int * n, mp_digit k) { int err, i, m; mp_word r; mp_digit mu, *tmpx1, *tmpx2; /* m = digits in modulus */ m = n->used; /* ensure that "x" has at least 2m digits */ if (x->alloc < m + m) { if ((err = mp_grow (x, m + m)) != MP_OKAY) { return err; } } /* top of loop, this is where the code resumes if * another reduction pass is required. */ top: /* aliases for digits */ /* alias for lower half of x */ tmpx1 = x->dp; /* alias for upper half of x, or x/B**m */ tmpx2 = x->dp + m; /* set carry to zero */ mu = 0; /* compute (x mod B**m) + k * [x/B**m] inline and inplace */ for (i = 0; i < m; i++) { r = ((mp_word)*tmpx2++) * ((mp_word)k) + *tmpx1 + mu; *tmpx1++ = (mp_digit)(r & MP_MASK); mu = (mp_digit)(r >> ((mp_word)DIGIT_BIT)); } /* set final carry */ *tmpx1++ = mu; /* zero words above m */ for (i = m + 1; i < x->used; i++) { *tmpx1++ = 0; } /* clamp, sub and return */ mp_clamp (x); /* if x >= n then subtract and reduce again * Each successive "recursion" makes the input smaller and smaller. */ if (mp_cmp_mag (x, n) != MP_LT) { s_mp_sub(x, n, x); goto top; } return MP_OKAY; } #endif /* $Source: /cvs/libtom/libtommath/bn_mp_dr_reduce.c,v $ */ /* $Revision: 1.4 $ */ /* $Date: 2006/12/28 01:25:13 $ */
{ "content_hash": "8c8a56ed1534a7509e71aab3bd8b6475", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 71, "avg_line_length": 25.70212765957447, "alnum_prop": 0.5964403973509934, "repo_name": "chad/rubinius", "id": "e60b5784f1627ec5d423f4d4142f4aecfd4046a7", "size": "2416", "binary": false, "copies": "78", "ref": "refs/heads/master", "path": "shotgun/external_libs/libtommath/bn_mp_dr_reduce.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "1251" }, { "name": "Assembly", "bytes": "249639" }, { "name": "Bison", "bytes": "176541" }, { "name": "C", "bytes": "6175903" }, { "name": "C++", "bytes": "133193" }, { "name": "CSS", "bytes": "4426" }, { "name": "DTrace", "bytes": "1245" }, { "name": "Groff", "bytes": "134144" }, { "name": "HTML", "bytes": "109337" }, { "name": "JavaScript", "bytes": "570" }, { "name": "Makefile", "bytes": "42336" }, { "name": "Objective-C", "bytes": "550" }, { "name": "Perl", "bytes": "119523" }, { "name": "Perl6", "bytes": "2948" }, { "name": "Python", "bytes": "741" }, { "name": "R", "bytes": "32568" }, { "name": "Ragel in Ruby Host", "bytes": "9584" }, { "name": "Ruby", "bytes": "9447444" }, { "name": "Scheme", "bytes": "557" }, { "name": "Shell", "bytes": "1104487" }, { "name": "TeX", "bytes": "309354" } ], "symlink_target": "" }
@interface BaseCollectionView : UICollectionView - (void)config; - (void)createSubviews; - (void)loadData; @end
{ "content_hash": "ea7fee23b8de4c6f40bebdc266ccfc52", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 48, "avg_line_length": 16.285714285714285, "alnum_prop": 0.7543859649122807, "repo_name": "LeeYofu/ProjectTemplate", "id": "c828beb783563be94ff4850305308a4f11c88682", "size": "290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ProjectTemplate/Class/General/Base/View/BaseCollectionView.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "291" }, { "name": "Objective-C", "bytes": "204201" }, { "name": "Ruby", "bytes": "464" } ], "symlink_target": "" }
/* * Appirater.m * appirater * * Created by Arash Payan on 9/5/09. * http://arashpayan.com * Copyright 2010 Arash Payan. All rights reserved. */ #import "Appirater.h" #import <SystemConfiguration/SCNetworkReachability.h> #include <netinet/in.h> NSString *const kAppiraterFirstUseDate = @"kAppiraterFirstUseDate"; NSString *const kAppiraterUseCount = @"kAppiraterUseCount"; NSString *const kAppiraterSignificantEventCount = @"kAppiraterSignificantEventCount"; NSString *const kAppiraterCurrentVersion = @"kAppiraterCurrentVersion"; NSString *const kAppiraterRatedCurrentVersion = @"kAppiraterRatedCurrentVersion"; NSString *const kAppiraterDeclinedToRate = @"kAppiraterDeclinedToRate"; NSString *const kAppiraterReminderRequestDate = @"kAppiraterReminderRequestDate"; #ifdef __IPHONE_OS_VERSION_MAX_ALLOWED NSString *templateReviewURL = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=APP_ID&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software"; #else //annoyingly this seems to open in iTunes rather than the mac app store - couldn't find a way to deeplink to the mac app review panel //NSString *templateReviewURL = @"https://userpub.itunes.apple.com/WebObjects/MZUserPublishing.woa/wa/addUserReview?id=APP_ID&onlyLatestVersion=true&type=Purple+Software"; NSString *templateReviewURL = @"http://itunes.apple.com/us/app/rainbow-blocks/idAPP_ID?mt=12&ls=1"; #endif NSString *templateReviewURLIpad = @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=APP_ID"; @interface Appirater (hidden) - (BOOL)connectedToNetwork; + (Appirater*)sharedInstance; - (void)showRatingAlert; - (BOOL)ratingConditionsHaveBeenMet; - (void)incrementUseCount; @end @implementation Appirater (hidden) - (BOOL)connectedToNetwork { // Create zero addy struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; // Recover reachability flags SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); SCNetworkReachabilityFlags flags; BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); CFRelease(defaultRouteReachability); if (!didRetrieveFlags) { NSLog(@"Error. Could not recover network reachability flags"); return NO; } BOOL isReachable = flags & kSCNetworkFlagsReachable; BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection; NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"]; NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0]; NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self]; return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO; } + (Appirater*)sharedInstance { static Appirater *appirater = nil; if (appirater == nil) { @synchronized(self) { if (appirater == nil) appirater = [[Appirater alloc] init]; } } return appirater; } - (BOOL)ratingConditionsHaveBeenMet { if (APPIRATER_DEBUG) return YES; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSDate *dateOfFirstLaunch = [NSDate dateWithTimeIntervalSince1970:[userDefaults doubleForKey:kAppiraterFirstUseDate]]; NSTimeInterval timeSinceFirstLaunch = [[NSDate date] timeIntervalSinceDate:dateOfFirstLaunch]; NSTimeInterval timeUntilRate = 60 * 60 * 24 * APPIRATER_DAYS_UNTIL_PROMPT; if (timeSinceFirstLaunch < timeUntilRate) return NO; // check if the app has been used enough int useCount = [userDefaults integerForKey:kAppiraterUseCount]; if (useCount <= APPIRATER_USES_UNTIL_PROMPT) return NO; // check if the user has done enough significant events int sigEventCount = [userDefaults integerForKey:kAppiraterSignificantEventCount]; if (sigEventCount <= APPIRATER_SIG_EVENTS_UNTIL_PROMPT) return NO; // has the user previously declined to rate this version of the app? if ([userDefaults boolForKey:kAppiraterDeclinedToRate]) return NO; // has the user already rated the app? if ([userDefaults boolForKey:kAppiraterRatedCurrentVersion]) return NO; // if the user wanted to be reminded later, has enough time passed? NSDate *reminderRequestDate = [NSDate dateWithTimeIntervalSince1970:[userDefaults doubleForKey:kAppiraterReminderRequestDate]]; NSTimeInterval timeSinceReminderRequest = [[NSDate date] timeIntervalSinceDate:reminderRequestDate]; NSTimeInterval timeUntilReminder = 60 * 60 * 24 * APPIRATER_TIME_BEFORE_REMINDING; if (timeSinceReminderRequest < timeUntilReminder) return NO; return YES; } - (void)incrementUseCount { // get the app's version NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey]; // get the version number that we've been tracking NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *trackingVersion = [userDefaults stringForKey:kAppiraterCurrentVersion]; if (trackingVersion == nil) { trackingVersion = version; [userDefaults setObject:version forKey:kAppiraterCurrentVersion]; } if (APPIRATER_DEBUG) NSLog(@"APPIRATER Tracking version: %@", trackingVersion); if ([trackingVersion isEqualToString:version]) { // check if the first use date has been set. if not, set it. NSTimeInterval timeInterval = [userDefaults doubleForKey:kAppiraterFirstUseDate]; if (timeInterval == 0) { timeInterval = [[NSDate date] timeIntervalSince1970]; [userDefaults setDouble:timeInterval forKey:kAppiraterFirstUseDate]; } // increment the use count int useCount = [userDefaults integerForKey:kAppiraterUseCount]; useCount++; [userDefaults setInteger:useCount forKey:kAppiraterUseCount]; if (APPIRATER_DEBUG) NSLog(@"APPIRATER Use count: %d", useCount); } else { // it's a new version of the app, so restart tracking [userDefaults setObject:version forKey:kAppiraterCurrentVersion]; [userDefaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:kAppiraterFirstUseDate]; [userDefaults setInteger:1 forKey:kAppiraterUseCount]; [userDefaults setInteger:0 forKey:kAppiraterSignificantEventCount]; [userDefaults setBool:NO forKey:kAppiraterRatedCurrentVersion]; [userDefaults setBool:NO forKey:kAppiraterDeclinedToRate]; [userDefaults setDouble:0 forKey:kAppiraterReminderRequestDate]; } [userDefaults synchronize]; } - (void)incrementSignificantEventCount { // get the app's version NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey]; // get the version number that we've been tracking NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *trackingVersion = [userDefaults stringForKey:kAppiraterCurrentVersion]; if (trackingVersion == nil) { trackingVersion = version; [userDefaults setObject:version forKey:kAppiraterCurrentVersion]; } if (APPIRATER_DEBUG) NSLog(@"APPIRATER Tracking version: %@", trackingVersion); if ([trackingVersion isEqualToString:version]) { // check if the first use date has been set. if not, set it. NSTimeInterval timeInterval = [userDefaults doubleForKey:kAppiraterFirstUseDate]; if (timeInterval == 0) { timeInterval = [[NSDate date] timeIntervalSince1970]; [userDefaults setDouble:timeInterval forKey:kAppiraterFirstUseDate]; } // increment the significant event count int sigEventCount = [userDefaults integerForKey:kAppiraterSignificantEventCount]; sigEventCount++; [userDefaults setInteger:sigEventCount forKey:kAppiraterSignificantEventCount]; if (APPIRATER_DEBUG) NSLog(@"APPIRATER Significant event count: %d", sigEventCount); } else { // it's a new version of the app, so restart tracking [userDefaults setObject:version forKey:kAppiraterCurrentVersion]; [userDefaults setDouble:0 forKey:kAppiraterFirstUseDate]; [userDefaults setInteger:0 forKey:kAppiraterUseCount]; [userDefaults setInteger:1 forKey:kAppiraterSignificantEventCount]; [userDefaults setBool:NO forKey:kAppiraterRatedCurrentVersion]; [userDefaults setBool:NO forKey:kAppiraterDeclinedToRate]; [userDefaults setDouble:0 forKey:kAppiraterReminderRequestDate]; } [userDefaults synchronize]; } #ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - (void)showRatingAlert { UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:APPIRATER_MESSAGE_TITLE message:APPIRATER_MESSAGE delegate:self cancelButtonTitle:APPIRATER_CANCEL_BUTTON otherButtonTitles:APPIRATER_RATE_BUTTON, APPIRATER_RATE_LATER, nil] autorelease]; [alertView show]; } #else - (void)showRatingAlert { NSAlert *alert = [NSAlert alertWithMessageText:APPIRATER_MESSAGE_TITLE defaultButton:APPIRATER_RATE_BUTTON alternateButton:APPIRATER_CANCEL_BUTTON otherButton:APPIRATER_RATE_LATER informativeTextWithFormat:APPIRATER_MESSAGE]; [alert beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil]; } #endif @end @implementation Appirater - (void)incrementAndRate:(NSNumber*)_canPromptForRating { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self incrementUseCount]; if ([_canPromptForRating boolValue] == YES && [self ratingConditionsHaveBeenMet] && [self connectedToNetwork]) { [self performSelectorOnMainThread:@selector(showRatingAlert) withObject:nil waitUntilDone:NO]; } [pool release]; } - (void)incrementSignificantEventAndRate:(NSNumber*)_canPromptForRating { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self incrementSignificantEventCount]; if ([_canPromptForRating boolValue] == YES && [self ratingConditionsHaveBeenMet] && [self connectedToNetwork]) { [self performSelectorOnMainThread:@selector(showRatingAlert) withObject:nil waitUntilDone:NO]; } [pool release]; } + (void)appLaunched { [Appirater appLaunched:YES]; } + (void)appLaunched:(BOOL)canPromptForRating { /* We only count launches on non-multitasking devices, because multitasking devices also get a usage call when they come into the foreground and we don't want to count app launches as two uses on multitasking devices. */ #ifdef __IPHONE_OS_VERSION_MAX_ALLOWED UIDevice *device = [UIDevice currentDevice]; if ([device respondsToSelector:@selector(multitaskingSupported)] && [device multitaskingSupported]) { return; } #endif NSNumber *_canPromptForRating = [[NSNumber alloc] initWithBool:canPromptForRating]; [NSThread detachNewThreadSelector:@selector(incrementAndRate:) toTarget:[Appirater sharedInstance] withObject:_canPromptForRating]; [_canPromptForRating release]; } + (void)appEnteredForeground:(BOOL)canPromptForRating { NSNumber *_canPromptForRating = [[NSNumber alloc] initWithBool:canPromptForRating]; [NSThread detachNewThreadSelector:@selector(incrementAndRate:) toTarget:[Appirater sharedInstance] withObject:_canPromptForRating]; [_canPromptForRating release]; } + (void)userDidSignificantEvent:(BOOL)canPromptForRating { NSNumber *_canPromptForRating = [[NSNumber alloc] initWithBool:canPromptForRating]; [NSThread detachNewThreadSelector:@selector(incrementSignificantEventAndRate:) toTarget:[Appirater sharedInstance] withObject:_canPromptForRating]; [_canPromptForRating release]; } #ifdef __IPHONE_OS_VERSION_MAX_ALLOWED - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; switch (buttonIndex) { case 0: { // they don't want to rate it [userDefaults setBool:YES forKey:kAppiraterDeclinedToRate]; [userDefaults synchronize]; break; } case 1: { // they want to rate it NSString *reviewURL = nil; // figure out which URL to use. iPad only apps have to use a different app store URL NSDictionary *bundleDictionary = [[NSBundle mainBundle] infoDictionary]; if ([bundleDictionary objectForKey:@"UISupportedInterfaceOrientations"] != nil && [bundleDictionary objectForKey:@"UISupportedInterfaceOrientations~ipad"] == nil) { // it's an iPad only app, so use the iPad url reviewURL = [templateReviewURLIpad stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%d", APPIRATER_APP_ID]]; } else // iPhone or Universal app, so we can use the direct url reviewURL = [templateReviewURL stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%d", APPIRATER_APP_ID]]; [userDefaults setBool:YES forKey:kAppiraterRatedCurrentVersion]; [userDefaults synchronize]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:reviewURL]]; break; } case 2: // remind them later [userDefaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:kAppiraterReminderRequestDate]; [userDefaults synchronize]; break; default: break; } } #else - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; switch (returnCode) { case NSAlertAlternateReturn: { // they don't want to rate it [userDefaults setBool:YES forKey:kAppiraterDeclinedToRate]; break; } case NSAlertDefaultReturn: { // they want to rate it NSString *reviewURL = [templateReviewURL stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%d", APPIRATER_APP_ID]]; [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:reviewURL]]; [userDefaults setBool:YES forKey:kAppiraterRatedCurrentVersion]; break; } case NSAlertOtherReturn: // remind them later break; default: break; } [userDefaults synchronize]; [self release]; } #endif @end
{ "content_hash": "997f467491e8cafb493f70c3d0bef108", "timestamp": "", "source": "github", "line_count": 407, "max_line_length": 194, "avg_line_length": 35.058968058968055, "alnum_prop": 0.7645244936575794, "repo_name": "softboysxp/NowPlaying", "id": "b5171a6d0ddfd378ae3970eee2283f2598098df3", "size": "15410", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NowPlaying/Appirater.m", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Objective-C", "bytes": "46278" } ], "symlink_target": "" }
module Novaposhta class Base def self.class_attr_accessor(*names) names.each do |name| define_singleton_method("#{name.to_s}=".to_sym){ |attr| class_variable_set("@@#{name.to_s}", attr) } define_singleton_method(name.to_sym){ class_variable_get("@@#{name.to_s}") } end end class_attr_accessor :url, :api_key, :sender, :format def self.post_request(body) uri = URI( url.gsub(/\{format\}/, "#{format.to_s}") ) request = Net::HTTP::Post.new(uri) format_request!(request, body) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| http.request request end format_response(response) rescue nil end def self.make_body(model, method, options={}) { "modelName": model, "calledMethod": method, "methodProperties": options, "apiKey": api_key } end private def self.format_request!(request, body) if format.to_sym == :json request.content_type = 'application/json' request.body = body.to_json elsif format.to_sym == :xml request.content_type = 'text/xml' request.body = body.to_xml.gsub(/\n/, '').gsub(/>\s+</, '><') end end def self.format_response(response) if format.to_sym == :json JSON.parse(response.body) elsif format.to_sym == :xml Nokogiri::XML(response.body) end end end end
{ "content_hash": "6b0a703b183e2899ac447f827fdfbaa3", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 108, "avg_line_length": 28.735849056603772, "alnum_prop": 0.562048588312541, "repo_name": "woodcrust/novaposhta", "id": "fb4b333488be0ff12bcc602c4cc3597986a64d42", "size": "1523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/novaposhta/base.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "5162" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
class ProjectGithubWebhookCreation include Sidekiq::Worker sidekiq_options retry: false attr_reader :project def perform(project_id) @project = Project.find(project_id) GithubService.new(project.organization.admin_user.auth_token).create_webhook( project.github_repo, Rails.application.secrets.github_webhook_url, ['status'] ) rescue Octokit::UnprocessableEntity Rails.logger.error('Webhook already exists') end end
{ "content_hash": "ec7a0b5b4359cac15461b76fe0bfc962", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 83, "avg_line_length": 32.214285714285715, "alnum_prop": 0.7583148558758315, "repo_name": "Wolox/codestats", "id": "2727b459fbf99a31f64a0d98a4f91a992adb19d9", "size": "451", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/workers/project_github_webhook_creation.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12996" }, { "name": "CoffeeScript", "bytes": "6646" }, { "name": "HTML", "bytes": "45965" }, { "name": "Ruby", "bytes": "123700" }, { "name": "Shell", "bytes": "3322" } ], "symlink_target": "" }
<?php class Google_Service_Slides_UpdateLineCategoryRequest extends Google_Model { public $lineCategory; public $objectId; public function setLineCategory($lineCategory) { $this->lineCategory = $lineCategory; } public function getLineCategory() { return $this->lineCategory; } public function setObjectId($objectId) { $this->objectId = $objectId; } public function getObjectId() { return $this->objectId; } }
{ "content_hash": "9e315b72027288965387c2f3502bc090", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 74, "avg_line_length": 18.24, "alnum_prop": 0.6973684210526315, "repo_name": "bshaffer/google-api-php-client-services", "id": "7aad11d77516f111d8f7c3aeb78e31c8474284c8", "size": "1046", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "src/Google/Service/Slides/UpdateLineCategoryRequest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "9540154" } ], "symlink_target": "" }
#ifndef MOCK_DATAFACADE_HPP #define MOCK_DATAFACADE_HPP // implements all data storage when shared memory _IS_ used #include "contractor/query_edge.hpp" #include "extractor/guidance/turn_instruction.hpp" #include "extractor/guidance/turn_lane_types.hpp" #include "engine/algorithm.hpp" #include "engine/datafacade/algorithm_datafacade.hpp" #include "engine/datafacade/datafacade_base.hpp" #include "util/guidance/bearing_class.hpp" #include "util/guidance/entry_class.hpp" #include "util/guidance/turn_bearing.hpp" #include "util/typedefs.hpp" namespace osrm { namespace test { class MockBaseDataFacade : public engine::datafacade::BaseDataFacade { using StringView = util::StringView; public: util::Coordinate GetCoordinateOfNode(const NodeID /* id */) const override { return {util::FixedLongitude{0}, util::FixedLatitude{0}}; } OSMNodeID GetOSMNodeIDOfNode(const NodeID /* id */) const override { return OSMNodeID{0}; } bool EdgeIsCompressed(const EdgeID /* id */) const { return false; } GeometryID GetGeometryIndex(const NodeID /* id */) const override { return GeometryID{SPECIAL_GEOMETRYID, false}; } ComponentID GetComponentID(const NodeID /* id */) const override { return ComponentID{INVALID_COMPONENTID, false}; } TurnPenalty GetWeightPenaltyForEdgeID(const unsigned /* id */) const override final { return 0; } TurnPenalty GetDurationPenaltyForEdgeID(const unsigned /* id */) const override final { return 0; } std::vector<NodeID> GetUncompressedForwardGeometry(const EdgeID /* id */) const override { return {}; } std::vector<NodeID> GetUncompressedReverseGeometry(const EdgeID /* id */) const override { return {}; } std::vector<EdgeWeight> GetUncompressedForwardWeights(const EdgeID /* id */) const override { std::vector<EdgeWeight> result_weights; result_weights.resize(1); result_weights[0] = 1; return result_weights; } std::vector<EdgeWeight> GetUncompressedReverseWeights(const EdgeID id) const override { return GetUncompressedForwardWeights(id); } std::vector<EdgeWeight> GetUncompressedForwardDurations(const EdgeID id) const override { return GetUncompressedForwardWeights(id); } std::vector<EdgeWeight> GetUncompressedReverseDurations(const EdgeID id) const override { return GetUncompressedForwardWeights(id); } std::vector<DatasourceID> GetUncompressedForwardDatasources(const EdgeID /*id*/) const override { return {}; } std::vector<DatasourceID> GetUncompressedReverseDatasources(const EdgeID /*id*/) const override { return {}; } StringView GetDatasourceName(const DatasourceID) const override final { return {}; } extractor::guidance::TurnInstruction GetTurnInstructionForEdgeID(const EdgeID /* id */) const override { return extractor::guidance::TurnInstruction::NO_TURN(); } std::vector<RTreeLeaf> GetEdgesInBox(const util::Coordinate /* south_west */, const util::Coordinate /*north_east */) const override { return {}; } std::vector<engine::PhantomNodeWithDistance> NearestPhantomNodesInRange(const util::Coordinate /*input_coordinate*/, const float /*max_distance*/, const int /*bearing*/, const int /*bearing_range*/, const engine::Approach /*approach*/) const override { return {}; } std::vector<engine::PhantomNodeWithDistance> NearestPhantomNodesInRange(const util::Coordinate /*input_coordinate*/, const float /*max_distance*/, const engine::Approach /*approach*/) const override { return {}; } std::vector<engine::PhantomNodeWithDistance> NearestPhantomNodes(const util::Coordinate /*input_coordinate*/, const unsigned /*max_results*/, const double /*max_distance*/, const int /*bearing*/, const int /*bearing_range*/, const engine::Approach /*approach*/) const override { return {}; } std::vector<engine::PhantomNodeWithDistance> NearestPhantomNodes(const util::Coordinate /*input_coordinate*/, const unsigned /*max_results*/, const int /*bearing*/, const int /*bearing_range*/, const engine::Approach /*approach*/) const override { return {}; } std::vector<engine::PhantomNodeWithDistance> NearestPhantomNodes(const util::Coordinate /*input_coordinate*/, const unsigned /*max_results*/, const engine::Approach /*approach*/) const override { return {}; } std::vector<engine::PhantomNodeWithDistance> NearestPhantomNodes(const util::Coordinate /*input_coordinate*/, const unsigned /*max_results*/, const double /*max_distance*/, const engine::Approach /*approach*/) const override { return {}; } std::pair<engine::PhantomNode, engine::PhantomNode> NearestPhantomNodeWithAlternativeFromBigComponent( const util::Coordinate /*input_coordinate*/, const engine::Approach /*approach*/) const override { return {}; } std::pair<engine::PhantomNode, engine::PhantomNode> NearestPhantomNodeWithAlternativeFromBigComponent( const util::Coordinate /*input_coordinate*/, const double /*max_distance*/, const engine::Approach /*approach*/) const override { return {}; } std::pair<engine::PhantomNode, engine::PhantomNode> NearestPhantomNodeWithAlternativeFromBigComponent( const util::Coordinate /*input_coordinate*/, const double /*max_distance*/, const int /*bearing*/, const int /*bearing_range*/, const engine::Approach /*approach*/) const override { return {}; } std::pair<engine::PhantomNode, engine::PhantomNode> NearestPhantomNodeWithAlternativeFromBigComponent( const util::Coordinate /*input_coordinate*/, const int /*bearing*/, const int /*bearing_range*/, const engine::Approach /*approach*/) const override { return {}; } unsigned GetCheckSum() const override { return 0; } extractor::TravelMode GetTravelMode(const NodeID /* id */) const override { return TRAVEL_MODE_INACCESSIBLE; } NameID GetNameIndex(const NodeID /* id */) const override { return 0; } StringView GetNameForID(const NameID) const override final { return {}; } StringView GetRefForID(const NameID) const override final { return {}; } StringView GetPronunciationForID(const NameID) const override final { return {}; } StringView GetDestinationsForID(const NameID) const override final { return {}; } std::string GetTimestamp() const override { return ""; } bool GetContinueStraightDefault() const override { return true; } double GetMapMatchingMaxSpeed() const override { return 180 / 3.6; } const char *GetWeightName() const override final { return "duration"; } unsigned GetWeightPrecision() const override final { return 1; } double GetWeightMultiplier() const override final { return 10.; } BearingClassID GetBearingClassID(const NodeID /*id*/) const override { return 0; } EntryClassID GetEntryClassID(const EdgeID /*id*/) const override { return 0; } bool IsLeftHandDriving() const override { return false; } util::guidance::TurnBearing PreTurnBearing(const EdgeID /*eid*/) const override final { return util::guidance::TurnBearing{0.0}; } util::guidance::TurnBearing PostTurnBearing(const EdgeID /*eid*/) const override final { return util::guidance::TurnBearing{0.0}; } bool HasLaneData(const EdgeID /*id*/) const override final { return true; }; util::guidance::LaneTupleIdPair GetLaneData(const EdgeID /*id*/) const override final { return {{0, 0}, 0}; } extractor::guidance::TurnLaneDescription GetTurnDescription(const LaneDescriptionID /*lane_description_id*/) const override final { return {}; } util::guidance::BearingClass GetBearingClass(const BearingClassID /*bearing_class_id*/) const override { util::guidance::BearingClass result; result.add(0); result.add(90); result.add(180); result.add(270); return result; } util::guidance::EntryClass GetEntryClass(const EntryClassID /*entry_class_id*/) const override { util::guidance::EntryClass result; result.activate(1); result.activate(2); result.activate(3); return result; } }; template <typename AlgorithmT> class MockAlgorithmDataFacade; template <> class MockAlgorithmDataFacade<engine::datafacade::CH> : public engine::datafacade::AlgorithmDataFacade<engine::datafacade::CH> { private: EdgeData foo; public: unsigned GetNumberOfNodes() const override { return 0; } unsigned GetNumberOfEdges() const override { return 0; } unsigned GetOutDegree(const NodeID /* n */) const override { return 0; } NodeID GetTarget(const EdgeID /* e */) const override { return SPECIAL_NODEID; } const EdgeData &GetEdgeData(const EdgeID /* e */) const override { return foo; } EdgeID BeginEdges(const NodeID /* n */) const override { return SPECIAL_EDGEID; } EdgeID EndEdges(const NodeID /* n */) const override { return SPECIAL_EDGEID; } osrm::engine::datafacade::EdgeRange GetAdjacentEdgeRange(const NodeID /* node */) const override { return util::irange(static_cast<EdgeID>(0), static_cast<EdgeID>(0)); } EdgeID FindEdge(const NodeID /* from */, const NodeID /* to */) const override { return SPECIAL_EDGEID; } EdgeID FindEdgeInEitherDirection(const NodeID /* from */, const NodeID /* to */) const override { return SPECIAL_EDGEID; } EdgeID FindSmallestEdge(const NodeID /* from */, const NodeID /* to */, std::function<bool(EdgeData)> /* filter */) const override { return SPECIAL_EDGEID; } EdgeID FindEdgeIndicateIfReverse(const NodeID /* from */, const NodeID /* to */, bool & /* result */) const override { return SPECIAL_EDGEID; } }; template <> class MockAlgorithmDataFacade<engine::datafacade::CoreCH> : public engine::datafacade::AlgorithmDataFacade<engine::datafacade::CoreCH> { private: EdgeData foo; public: bool IsCoreNode(const NodeID /* id */) const override { return false; } }; template <typename AlgorithmT> class MockDataFacade final : public MockBaseDataFacade, public MockAlgorithmDataFacade<AlgorithmT> { }; template <> class MockDataFacade<engine::datafacade::CoreCH> final : public MockBaseDataFacade, public MockAlgorithmDataFacade<engine::datafacade::CH>, public MockAlgorithmDataFacade<engine::datafacade::CoreCH> { }; } // ns test } // ns osrm #endif // MOCK_DATAFACADE_HPP
{ "content_hash": "cf7cd7b1914bc79bf0cda8973f2f5fca", "timestamp": "", "source": "github", "line_count": 328, "max_line_length": 100, "avg_line_length": 35.21951219512195, "alnum_prop": 0.6417070637119113, "repo_name": "duizendnegen/osrm-backend", "id": "e4d9d4f9d0f92029a3da44db1090d2b7207d35d4", "size": "11552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unit_tests/mocks/mock_datafacade.hpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "6616" }, { "name": "C++", "bytes": "2961564" }, { "name": "CMake", "bytes": "99471" }, { "name": "Gherkin", "bytes": "1053654" }, { "name": "JavaScript", "bytes": "196416" }, { "name": "Lua", "bytes": "95749" }, { "name": "Makefile", "bytes": "3170" }, { "name": "Python", "bytes": "5717" }, { "name": "Shell", "bytes": "15158" } ], "symlink_target": "" }
package com.shubham.server.main; import java.util.HashMap; import java.util.Map; public class WsSessionList { public static Map<String, String> sessions = new HashMap<String, String>(); public static void addSession(String ip,String key){ sessions.put(ip, key); } public static void removeSession(String ip){ sessions.remove(ip); } public static boolean isExits(String ip,String key){ return sessions.get(ip) != null; } }
{ "content_hash": "4e16d221ee9e0d375171fad1620154ab", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 76, "avg_line_length": 20.318181818181817, "alnum_prop": 0.7248322147651006, "repo_name": "pentestershubham/Playstack", "id": "89c63a16f593211666f22e0799806b6d392a6064", "size": "447", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Playstack Android Application/Playstack/Server/com/shubham/server/main/WsSessionList.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "231863" }, { "name": "Go", "bytes": "8225" }, { "name": "HTML", "bytes": "45746" }, { "name": "Java", "bytes": "950945" }, { "name": "JavaScript", "bytes": "440557" } ], "symlink_target": "" }
<?php require_once (dirname(dirname(__FILE__)).'/create.class.php'); /** * Create a Template Variable. * * @param string $name The name of the TV * @param string $caption (optional) A short caption for the TV. * @param string $description (optional) A brief description. * @param integer $category (optional) The category to assign to. Defaults to no * category. * @param boolean $locked (optional) If true, can only be accessed by * administrators. Defaults to false. * @param string $els (optional) * @param integer $rank (optional) The rank of the TV * @param string $display (optional) The type of output render * @param string $display_params (optional) Any display rendering parameters * @param string $default_text (optional) The default value for the TV * @param json $templates (optional) Templates associated with the TV * @param json $resource_groups (optional) Resource Groups associated with the * TV. * @param json $propdata (optional) A json array of properties * * @package modx * @subpackage processors.element.tv */ class modTemplateVarCreateProcessor extends modElementCreateProcessor { public $classKey = 'modTemplateVar'; public $languageTopics = array('tv','category','element'); public $permission = 'new_tv'; public $objectType = 'tv'; public $beforeSaveEvent = 'OnBeforeTVFormSave'; public $afterSaveEvent = 'OnTVFormSave'; /** * Fire pre-save logic * {@inheritDoc} * @return boolean */ public function beforeSave() { $template = $this->getProperty('template'); if (empty($template)) { $this->setProperty('template',array()); } $caption = $this->getProperty('caption',''); if (empty($caption)) $this->setProperty('caption',$this->getProperty('name')); $this->setInputProperties(); $this->setOutputProperties(); $els = $this->getProperty('els',null); if ($els !== null) { $this->object->set('elements',$els); } $rank = $this->getProperty('rank',0); $this->object->set('rank',$rank); return parent::beforeSave(); } /** * Set the Output Options for the TV * @return array */ public function setOutputProperties() { $properties = $this->getProperties(); $outputProperties = array(); foreach ($properties as $key => $value) { $res = strstr($key,'prop_'); if ($res !== false) { $outputProperties[str_replace('prop_','',$key)] = $value; } } $this->object->set('output_properties',$outputProperties); return $outputProperties; } /** * Set the Input Options for the TV * @return array */ public function setInputProperties() { $properties = $this->getProperties(); $inputProperties = array(); foreach ($properties as $key => $value) { $res = strstr($key,'inopt_'); if ($res !== false) { $inputProperties[str_replace('inopt_','',$key)] = $value; } } $this->object->set('input_properties',$inputProperties); return $inputProperties; } /** * Add post-saving options to TVs * * {@inheritDoc} * @return boolean */ public function afterSave() { $this->setTemplateAccess(); $this->setResourceGroupAccess(); $this->setMediaSources(); return parent::afterSave(); } /** * Set the Template Access to the TV * @return void */ public function setTemplateAccess() { $templates = $this->getProperty('templates',null); if ($templates !== null) { $templates = is_array($templates) ? $templates : $this->modx->fromJSON($templates); foreach ($templates as $id => $template) { if ($template['access']) { /** @var modTemplateVarTemplate $templateVarTemplate */ $templateVarTemplate = $this->modx->getObject('modTemplateVarTemplate',array( 'tmplvarid' => $this->object->get('id'), 'templateid' => $template['id'], )); if (empty($templateVarTemplate)) { $templateVarTemplate = $this->modx->newObject('modTemplateVarTemplate'); } $templateVarTemplate->set('tmplvarid',$this->object->get('id')); $templateVarTemplate->set('templateid',$template['id']); $templateVarTemplate->set('rank',!empty($template['rank']) ? $template['rank'] : 0); $templateVarTemplate->save(); } else { $templateVarTemplate = $this->modx->getObject('modTemplateVarTemplate',array( 'tmplvarid' => $this->object->get('id'), 'templateid' => $template['id'], )); if (!empty($templateVarTemplate)) { $templateVarTemplate->remove(); } } } } } /** * Set Resource Groups access to TV * @return array|string */ public function setResourceGroupAccess() { $resourceGroups = $this->getProperty('resource_groups',null); if ($this->modx->hasPermission('tv_access_permissions') && $resourceGroups !== null) { $resourceGroups = is_array($resourceGroups) ? $resourceGroups : $this->modx->fromJSON($resourceGroups); if (is_array($resourceGroups)) { foreach ($resourceGroups as $id => $group) { if (!is_array($group)) continue; /** @var modTemplateVarResourceGroup $templateVarResourceGroup */ $templateVarResourceGroup = $this->modx->getObject('modTemplateVarResourceGroup',array( 'tmplvarid' => $this->object->get('id'), 'documentgroup' => $group['id'], )); if ($group['access'] == true) { if (!empty($templateVarResourceGroup)) continue; $templateVarResourceGroup = $this->modx->newObject('modTemplateVarResourceGroup'); $templateVarResourceGroup->set('tmplvarid',$this->object->get('id')); $templateVarResourceGroup->set('documentgroup',$group['id']); $templateVarResourceGroup->save(); } else { $templateVarResourceGroup->remove(); } } } } } /** * Set source-element maps * @return void */ public function setMediaSources() { $sources = $this->getProperty('sources',null); if ($sources !== null) { $sources = is_array($sources) ? $sources : $this->modx->fromJSON($sources); if (is_array($sources)) { foreach ($sources as $id => $source) { if (!is_array($source)) continue; /** @var modMediaSourceElement $sourceElement */ $sourceElement = $this->modx->getObject('sources.modMediaSourceElement',array( 'object' => $this->object->get('id'), 'object_class' => $this->object->_class, 'context_key' => $source['context_key'], )); if (!$sourceElement) { $sourceElement = $this->modx->newObject('sources.modMediaSourceElement'); $sourceElement->fromArray(array( 'object' => $this->object->get('id'), 'object_class' => $this->object->_class, 'context_key' => $source['context_key'], ),'',true,true); } $sourceElement->set('source',$source['source']); $sourceElement->save(); } } } } } return 'modTemplateVarCreateProcessor';
{ "content_hash": "62b9cf1fe619d1a387d3182ea87f62aa", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 115, "avg_line_length": 39.94146341463415, "alnum_prop": 0.5316316560820713, "repo_name": "timsvoice/great_green_sources", "id": "2adb133af14bdd320a02d97910fb47e357c4b21c", "size": "8188", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "core/model/modx/processors/element/tv/create.class.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "718852" }, { "name": "Java", "bytes": "11903" }, { "name": "JavaScript", "bytes": "1641637" }, { "name": "PHP", "bytes": "13315560" }, { "name": "Perl", "bytes": "25276" } ], "symlink_target": "" }
import { DatePicker as DatePickerDefinition } from '.'; import { View, CSSType } from '../core/view'; import { booleanConverter } from '../core/view-base'; import { Property } from '../core/properties'; const defaultDate = new Date(); const dateComparer = (x: Date, y: Date): boolean => x <= y && x >= y; @CSSType('DatePicker') export class DatePickerBase extends View implements DatePickerDefinition { public year: number; public month: number; public day: number; public hour: number; public minute: number; public second: number; public maxDate: Date; public minDate: Date; public date: Date; public iosPreferredDatePickerStyle: number; public showTime: boolean; } DatePickerBase.prototype.recycleNativeView = 'auto'; export const yearProperty = new Property<DatePickerBase, number>({ name: 'year', defaultValue: defaultDate.getFullYear(), valueConverter: (v) => parseInt(v), }); yearProperty.register(DatePickerBase); export const monthProperty = new Property<DatePickerBase, number>({ name: 'month', defaultValue: defaultDate.getMonth() + 1, valueConverter: (v) => parseInt(v), }); monthProperty.register(DatePickerBase); export const dayProperty = new Property<DatePickerBase, number>({ name: 'day', defaultValue: defaultDate.getDate(), valueConverter: (v) => parseInt(v), }); dayProperty.register(DatePickerBase); export const hourProperty = new Property<DatePickerBase, number>({ name: 'hour', defaultValue: defaultDate.getHours(), valueConverter: (v) => parseInt(v), }); hourProperty.register(DatePickerBase); export const minuteProperty = new Property<DatePickerBase, number>({ name: 'minute', defaultValue: defaultDate.getMinutes(), valueConverter: (v) => parseInt(v), }); minuteProperty.register(DatePickerBase); export const secondProperty = new Property<DatePickerBase, number>({ name: 'second', defaultValue: defaultDate.getSeconds(), valueConverter: (v) => parseInt(v), }); secondProperty.register(DatePickerBase); // TODO: Make CoercibleProperties export const maxDateProperty = new Property<DatePickerBase, Date>({ name: 'maxDate', equalityComparer: dateComparer, valueConverter: (v) => new Date(v), }); maxDateProperty.register(DatePickerBase); export const minDateProperty = new Property<DatePickerBase, Date>({ name: 'minDate', equalityComparer: dateComparer, valueConverter: (v) => new Date(v), }); minDateProperty.register(DatePickerBase); export const dateProperty = new Property<DatePickerBase, Date>({ name: 'date', defaultValue: defaultDate, equalityComparer: dateComparer, valueConverter: (v) => new Date(v), }); dateProperty.register(DatePickerBase); export const showTimeProperty = new Property<DatePickerBase, boolean>({ name: 'showTime', defaultValue: false, valueConverter: (v) => booleanConverter(v), }); showTimeProperty.register(DatePickerBase); export const iosPreferredDatePickerStyleProperty = new Property<DatePickerBase, number>({ name: 'iosPreferredDatePickerStyle', defaultValue: 0, valueConverter: (v) => parseInt(v), }); iosPreferredDatePickerStyleProperty.register(DatePickerBase);
{ "content_hash": "019063cd3e15c9de92433cd108440b4c", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 89, "avg_line_length": 29.980582524271846, "alnum_prop": 0.7529145077720207, "repo_name": "NativeScript/NativeScript", "id": "451b1ecc1701ea272386487f1b4ba5c5575ce3ce", "size": "3090", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "packages/core/ui/date-picker/date-picker-common.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34822" }, { "name": "HTML", "bytes": "1307" }, { "name": "Java", "bytes": "494925" }, { "name": "JavaScript", "bytes": "69009" }, { "name": "Objective-C", "bytes": "49167" }, { "name": "SCSS", "bytes": "65" }, { "name": "Shell", "bytes": "14663" }, { "name": "TypeScript", "bytes": "3946056" } ], "symlink_target": "" }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Z.Core.Test { [TestClass] public class System_String_IsEmpty { [TestMethod] public void IsEmpty() { // Type string @thisEmpty = ""; string @thisNotEmpty = "FizzBuzz"; // Exemples bool result1 = @thisEmpty.IsEmpty(); // return true; bool result2 = @thisNotEmpty.IsEmpty(); // return false; // Unit Test Assert.IsTrue(result1); Assert.IsFalse(result2); } } }
{ "content_hash": "e8d2a747b1ebc72c4d71157ce0cb53ac", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 68, "avg_line_length": 24.041666666666668, "alnum_prop": 0.5337954939341422, "repo_name": "zzzprojects/Z.ExtensionMethods", "id": "6a03767d262c7e23bc231e675cdf8058ad71bd64", "size": "1002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/Z.Core.Test/System.String/String.IsEmpty.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2614731" }, { "name": "Visual Basic", "bytes": "1411898" } ], "symlink_target": "" }
using namespace swift; SILGlobalVariable *SILGlobalVariable::create(SILModule &M, SILLinkage linkage, bool IsFragile, StringRef name, SILType loweredType, Optional<SILLocation> loc, VarDecl *Decl) { // Get a StringMapEntry for the variable. As a sop to error cases, // allow the name to have an empty string. llvm::StringMapEntry<SILGlobalVariable*> *entry = nullptr; if (!name.empty()) { entry = &*M.GlobalVariableMap.insert(std::make_pair(name, nullptr)).first; assert(!entry->getValue() && "global variable already exists"); name = entry->getKey(); } auto var = new (M) SILGlobalVariable(M, linkage, IsFragile, name, loweredType, loc, Decl); if (entry) entry->setValue(var); return var; } SILGlobalVariable::SILGlobalVariable(SILModule &Module, SILLinkage Linkage, bool IsFragile, StringRef Name, SILType LoweredType, Optional<SILLocation> Loc, VarDecl *Decl) : Module(Module), Name(Name), LoweredType(LoweredType), Location(Loc), Linkage(unsigned(Linkage)), Fragile(IsFragile), VDecl(Decl) { IsDeclaration = isAvailableExternally(Linkage); setLet(Decl ? Decl->isLet() : false); InitializerF = nullptr; Module.silGlobals.push_back(this); } void SILGlobalVariable::setInitializer(SILFunction *InitF) { if (InitializerF) InitializerF->decrementRefCount(); // Increment the ref count to make sure it will not be eliminated. InitF->incrementRefCount(); InitializerF = InitF; } SILGlobalVariable::~SILGlobalVariable() { getModule().GlobalVariableMap.erase(Name); } // FIXME static bool analyzeStaticInitializer(SILFunction *F, SILInstruction *&Val, SILGlobalVariable *&GVar) { Val = nullptr; GVar = nullptr; // We only handle a single SILBasicBlock for now. if (F->size() != 1) return false; SILBasicBlock *BB = &F->front(); GlobalAddrInst *SGA = nullptr; bool HasStore = false; for (auto &I : *BB) { // Make sure we have a single GlobalAddrInst and a single StoreInst. // And the StoreInst writes to the GlobalAddrInst. if (isa<AllocGlobalInst>(&I)) { continue; } else if (auto *sga = dyn_cast<GlobalAddrInst>(&I)) { if (SGA) return false; SGA = sga; GVar = SGA->getReferencedGlobal(); } else if (auto *SI = dyn_cast<StoreInst>(&I)) { if (HasStore || SI->getDest() != SGA) return false; HasStore = true; Val = dyn_cast<SILInstruction>(SI->getSrc()); // We only handle StructInst and TupleInst being stored to a // global variable for now. if (!isa<StructInst>(Val) && !isa<TupleInst>(Val)) return false; } else { if (auto *bi = dyn_cast<BuiltinInst>(&I)) { switch (bi->getBuiltinInfo().ID) { case BuiltinValueKind::FPTrunc: if (isa<LiteralInst>(bi->getArguments()[0])) continue; break; default: return false; } } // Objective-C selector string literals cannot be used in static // initializers. if (auto *stringLit = dyn_cast<StringLiteralInst>(&I)) { switch (stringLit->getEncoding()) { case StringLiteralInst::Encoding::UTF8: case StringLiteralInst::Encoding::UTF16: continue; case StringLiteralInst::Encoding::ObjCSelector: return false; } } if (I.getKind() != ValueKind::ReturnInst && I.getKind() != ValueKind::StructInst && I.getKind() != ValueKind::TupleInst && I.getKind() != ValueKind::DebugValueInst && I.getKind() != ValueKind::IntegerLiteralInst && I.getKind() != ValueKind::FloatLiteralInst) return false; } } return true; } bool SILGlobalVariable::canBeStaticInitializer(SILFunction *F) { SILInstruction *dummySI; SILGlobalVariable *dummyGV; return analyzeStaticInitializer(F, dummySI, dummyGV); } /// Check if a given SILFunction can be a static initializer. If yes, return /// the SILGlobalVariable that it writes to. SILGlobalVariable *SILGlobalVariable::getVariableOfStaticInitializer( SILFunction *F) { SILInstruction *dummySI; SILGlobalVariable *GV; if (analyzeStaticInitializer(F, dummySI, GV)) return GV; return nullptr; } /// Return the value that is written into the global variable. SILInstruction *SILGlobalVariable::getValueOfStaticInitializer() { if (!InitializerF) return nullptr; SILInstruction *SI; SILGlobalVariable *dummyGV; if (analyzeStaticInitializer(InitializerF, SI, dummyGV)) return SI; return nullptr; }
{ "content_hash": "1c1b5ac039d0c973fa61006b29776d45", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 78, "avg_line_length": 32.529411764705884, "alnum_prop": 0.6114124974884468, "repo_name": "therealbnut/swift", "id": "09f87b5047ea55758f06bc6530561197b5d05dfe", "size": "5572", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "lib/SIL/SILGlobalVariable.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2144" }, { "name": "C", "bytes": "49224" }, { "name": "C++", "bytes": "21531882" }, { "name": "CMake", "bytes": "330668" }, { "name": "DTrace", "bytes": "3545" }, { "name": "Emacs Lisp", "bytes": "54383" }, { "name": "LLVM", "bytes": "56821" }, { "name": "Makefile", "bytes": "1841" }, { "name": "Objective-C", "bytes": "227503" }, { "name": "Objective-C++", "bytes": "209373" }, { "name": "Perl", "bytes": "2211" }, { "name": "Python", "bytes": "687607" }, { "name": "Ruby", "bytes": "2091" }, { "name": "Shell", "bytes": "189237" }, { "name": "Swift", "bytes": "16355303" }, { "name": "VimL", "bytes": "13393" } ], "symlink_target": "" }
ACCEPTED #### According to Belgian Species List #### Published in null #### Original name null ### Remarks null
{ "content_hash": "d0e300b655a8cd6e0a850337d91a7105", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 20, "avg_line_length": 8.846153846153847, "alnum_prop": 0.6869565217391305, "repo_name": "mdoering/backbone", "id": "b96fa50221be3331651eef688ca8882c9fa3388e", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Thelebolales/Thelebolaceae/Pezizella/Pezizella alniella/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace CodeNav.Tests.Files { interface ITestInterface { int InterfaceMethod(); int InterfaceMethod(int input); int InterfaceProperty { get; } } public class ImplementingClass : ITestInterface { public int InterfaceMethod() { return 0; } public int InterfaceMethod(int input) { // Overloading within the same interface return input; } public int InterfaceMethod(int a, int b) { // Overloading outside the interface return a + b; } public void NonInterfaceMethod() { } public int InterfaceProperty { get; } } public class ImplementingClass2 : ITestInterface { #region ITestInterface implementation public int InterfaceMethod() { return 0; } public int InterfaceMethod(int input) { // Overloading within the same interface return input; } public int InterfaceProperty { get; } #endregion public int InterfaceMethod(int a, int b) { // Overloading outside the interface return a + b; } public void NonInterfaceMethod() { } } }
{ "content_hash": "5798f12817e5f6914b88ade1cb1b7597", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 52, "avg_line_length": 20.059701492537314, "alnum_prop": 0.5297619047619048, "repo_name": "sboulema/CodeNav", "id": "578826e79ecfc07c276646c0e7a3bf0c7430688d", "size": "1346", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "CodeNav.Tests/Files/TestInterface.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "332871" }, { "name": "JavaScript", "bytes": "602" }, { "name": "Visual Basic .NET", "bytes": "2658" } ], "symlink_target": "" }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911 // .1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.07.16 at 03:24:22 PM EEST // package org.ecloudmanager.tmrk.cloudapi.model; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * <p>Java class for ArrayOfOrganizationResourceType complex type. * <p/> * <p>The following schema fragment specifies the expected content contained within this class. * <p/> * <pre> * &lt;complexType name="ArrayOfOrganizationResourceType"> * &lt;complexContent> * &lt;extension base="{}ResourceType"> * &lt;sequence> * &lt;element name="Organization" type="{}OrganizationType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfOrganizationResourceType", propOrder = { "organization" }) @XmlSeeAlso({ OrganizationsType.class }) public class ArrayOfOrganizationResourceType extends ResourceType { @XmlElement(name = "Organization", nillable = true) protected List<OrganizationType> organization; /** * Gets the value of the organization property. * <p/> * <p/> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the organization property. * <p/> * <p/> * For example, to add a new item, do as follows: * <pre> * getOrganization().add(newItem); * </pre> * <p/> * <p/> * <p/> * Objects of the following type(s) are allowed in the list * {@link OrganizationType } */ public List<OrganizationType> getOrganization() { if (organization == null) { organization = new ArrayList<OrganizationType>(); } return this.organization; } }
{ "content_hash": "484439d298cca23d9e0dd3128f41197d", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 116, "avg_line_length": 30.5, "alnum_prop": 0.6610544971200709, "repo_name": "AltisourceLabs/ecloudmanager", "id": "a7ef376322cc43050cad26c6cf57e6e3002d06b0", "size": "2257", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/ArrayOfOrganizationResourceType.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "113696" }, { "name": "HTML", "bytes": "289852" }, { "name": "Java", "bytes": "3371074" }, { "name": "JavaScript", "bytes": "3673705" }, { "name": "SystemVerilog", "bytes": "855" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <testsuite xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd" name="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.27" tests="18" errors="0" skipped="0" failures="0"> <properties> <property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/> <property name="sun.boot.library.path" value="/usr/lib/jvm/java-8-oracle/jre/lib/i386"/> <property name="java.vm.version" value="25.144-b01"/> <property name="java.vm.vendor" value="Oracle Corporation"/> <property name="maven.multiModuleProjectDirectory" value="/var/www/html/podam-develop"/> <property name="java.vendor.url" value="http://java.oracle.com/"/> <property name="path.separator" value=":"/> <property name="guice.disable.misplaced.annotation.check" value="true"/> <property name="java.vm.name" value="Java HotSpot(TM) Server VM"/> <property name="file.encoding.pkg" value="sun.io"/> <property name="user.country" value="IN"/> <property name="sun.java.launcher" value="SUN_STANDARD"/> <property name="sun.os.patch.level" value="unknown"/> <property name="java.vm.specification.name" value="Java Virtual Machine Specification"/> <property name="user.dir" value="/var/www/html/podam-develop"/> <property name="java.runtime.version" value="1.8.0_144-b01"/> <property name="java.awt.graphicsenv" value="sun.awt.X11GraphicsEnvironment"/> <property name="java.endorsed.dirs" value="/usr/lib/jvm/java-8-oracle/jre/lib/endorsed"/> <property name="os.arch" value="i386"/> <property name="java.io.tmpdir" value="/tmp"/> <property name="line.separator" value="&#10;"/> <property name="java.vm.specification.vendor" value="Oracle Corporation"/> <property name="os.name" value="Linux"/> <property name="classworlds.conf" value="/usr/share/maven/bin/m2.conf"/> <property name="sun.jnu.encoding" value="UTF-8"/> <property name="java.library.path" value="/usr/java/packages/lib/i386:/lib:/usr/lib"/> <property name="java.specification.name" value="Java Platform API Specification"/> <property name="java.class.version" value="52.0"/> <property name="sun.management.compiler" value="HotSpot Tiered Compilers"/> <property name="os.version" value="4.10.0-35-generic"/> <property name="user.home" value="/root"/> <property name="user.timezone" value="Asia/Kolkata"/> <property name="java.awt.printerjob" value="sun.print.PSPrinterJob"/> <property name="file.encoding" value="UTF-8"/> <property name="java.specification.version" value="1.8"/> <property name="user.name" value="root"/> <property name="java.class.path" value="/usr/share/maven/boot/plexus-classworlds-2.x.jar"/> <property name="java.vm.specification.version" value="1.8"/> <property name="sun.arch.data.model" value="32"/> <property name="java.home" value="/usr/lib/jvm/java-8-oracle/jre"/> <property name="sun.java.command" value="org.codehaus.plexus.classworlds.launcher.Launcher integration-test"/> <property name="java.specification.vendor" value="Oracle Corporation"/> <property name="user.language" value="en"/> <property name="awt.toolkit" value="sun.awt.X11.XToolkit"/> <property name="java.vm.info" value="mixed mode"/> <property name="java.version" value="1.8.0_144"/> <property name="java.ext.dirs" value="/usr/lib/jvm/java-8-oracle/jre/lib/ext:/usr/java/packages/lib/ext"/> <property name="securerandom.source" value="file:/dev/./urandom"/> <property name="sun.boot.class.path" value="/usr/lib/jvm/java-8-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/sunrsasign.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-8-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-8-oracle/jre/classes"/> <property name="java.vendor" value="Oracle Corporation"/> <property name="maven.home" value="/usr/share/maven"/> <property name="file.separator" value="/"/> <property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/> <property name="sun.cpu.endian" value="little"/> <property name="sun.io.unicode.encoding" value="UnicodeLittle"/> <property name="sun.cpu.isalist" value=""/> </properties> <testcase name="testPdm3IndirectImplementingMapOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.005"/> <testcase name="testPdm3MapOfGenericPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.071"/> <testcase name="testPdm3ListOfGenericPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.062"/> <testcase name="testPdm3ExtendingMapOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.002"/> <testcase name="testPdm3ListOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.017"/> <testcase name="testPdm3IndirectImplementingListOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.003"/> <testcase name="testPdm3MapOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.018"/> <testcase name="testPdm3PojoConstructor" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.004"/> <testcase name="testPdm3ImplementingListOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.001"/> <testcase name="testPdm3WildcardPojo" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.051"/> <testcase name="testPdm3ImplementingMapOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0"/> <testcase name="testPdm3ExtendingImplementingMapOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.002"/> <testcase name="testPdm3Pojo" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.011"/> <testcase name="testPdm3ExtendingListOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.001"/> <testcase name="testPdm3ExtendingNonRawMapOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.001"/> <testcase name="testPdm3ExtendingImplementingListOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.002"/> <testcase name="testPdm3PojoGenericsConstructor" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.011"/> <testcase name="testPdm3ExtendingRawListOfPojos" classname="uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest" time="0.004"/> </testsuite>
{ "content_hash": "be2a7f5048a3dac00b7f416b76a93fe6", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 408, "avg_line_length": 85.25316455696202, "alnum_prop": 0.7317000742390497, "repo_name": "Vignesh4vi/podam", "id": "44a77be3125414ae3042ab08169d6c06a07cf3cd", "size": "6735", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target/failsafe-reports/TEST-uk.co.jemos.podam.test.unit.pdm3.Pdm3PojoUnitTest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "344038" }, { "name": "HTML", "bytes": "10310354" }, { "name": "Java", "bytes": "763389" }, { "name": "JavaScript", "bytes": "1732464" } ], "symlink_target": "" }
#ifndef HMLIB_ALGORITHM_NUMERIC_INC #define HMLIB_ALGORITHM_NUMERIC_INC 100 # #include<algorithm> #include"../utility.hpp" #include"../type_traits.hpp" namespace hmLib{ template<typename InputIterator, typename OutputIterator, typename T> T partial_accumulate(InputIterator first, InputIterator last, OutputIterator out, T init){ for(; first != last; ++first){ init += *first; *(out++) = init; } return init; } template<typename InputIterator, typename OutputIterator, typename T, typename Op> T partial_accumulate(InputIterator first, InputIterator last, OutputIterator out, T init, Op op){ for(; first != last; ++first){ init = op(init, *first); *(out++) = init; } return init; } template<typename Container, typename T = decltype(*std::begin(std::declval<Container>()) * *std::begin(std::declval<Container>())), typename std::enable_if<hmLib::is_range<Container>::value>::type*& = hmLib::utility::enabler> T norm2(const Container & c, T ini = 0) { auto end = std::end(c); for(auto itr = std::begin(c); itr != end; ++itr) { ini += (*itr) * (*itr); } return ini; } template<typename Container, typename T = decltype(std::sqrt(*std::begin(std::declval<Container>())* *std::begin(std::declval<Container>()))), typename std::enable_if<hmLib::is_range<Container>::value>::type*& = hmLib::utility::enabler> T norm(const Container& c, T ini = 0) { return std::sqrt(norm2(c,ini)); } } # #endif
{ "content_hash": "c124294eda299540876afa514f1da26c", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 237, "avg_line_length": 37.8421052631579, "alnum_prop": 0.6808066759388038, "repo_name": "hmito/hmLib", "id": "2948be30a4af1b5671e1e0518de54f46271d1a48", "size": "1440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "algorithm/numeric.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16639" }, { "name": "C++", "bytes": "1187907" } ], "symlink_target": "" }
Rcm I18n translation library and utilities ============================== #### Rcm Translate API #### Rcm Translate API - HTTP API for translations Calling the API: ``` https://example.com/api/rcm-translate-api/MY-TRANSLATION-NAMESPACE?1=term1&key2=term2 ``` The query param field is an arbitrary key (usually the same as the term) The query param value is the term (string) to translate I.E. ?queryField=queryValue equates to: someValue=translationString Result: ``` { "term1": "term1 translation", "term2": "term2 translation" } ```
{ "content_hash": "e63373e7e41f3321425cf85ec9cb28d3", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 89, "avg_line_length": 20.035714285714285, "alnum_prop": 0.6737967914438503, "repo_name": "bjanish/rcm-i18n", "id": "39a127cd007c4af69f49f7b8f6be4dadbb920b8e", "size": "561", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2330" }, { "name": "HTML", "bytes": "5520" }, { "name": "JavaScript", "bytes": "6753" }, { "name": "PHP", "bytes": "56803" } ], "symlink_target": "" }
<html> <head> <title>Docs For Class CF_Container</title> <link rel="stylesheet" type="text/css" href="../media/style.css"> </head> <body> <table border="0" cellspacing="0" cellpadding="0" height="48" width="100%"> <tr> <td class="header_top">php-cloudfiles</td> </tr> <tr><td class="header_line"><img src="../media/empty.png" width="1" height="1" border="0" alt="" /></td></tr> <tr> <td class="header_menu"> [ <a href="../classtrees_php-cloudfiles.html" class="menu">class tree: php-cloudfiles</a> ] [ <a href="../elementindex_php-cloudfiles.html" class="menu">index: php-cloudfiles</a> ] [ <a href="../elementindex.html" class="menu">all elements</a> ] </td> </tr> <tr><td class="header_line"><img src="../media/empty.png" width="1" height="1" border="0" alt="" /></td></tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="200" class="menu"> <div id="ric"> <p><a href="../ric_Changelog.html">Changelog</a></p> <p><a href="../ric_AUTHORS.html">AUTHORS</a></p> <p><a href="../ric_README.html">README</a></p> <p><a href="../ric_COPYING.html">COPYING</a></p> </div> <b>Packages:</b><br /> <a href="../li_php-cloudfiles.html">php-cloudfiles</a><br /> <a href="../li_php-cloudfiles-exceptions.html">php-cloudfiles-exceptions</a><br /> <a href="../li_php-cloudfiles-http.html">php-cloudfiles-http</a><br /> <br /><br /> <b>Files:</b><br /> <div class="package"> <a href="../php-cloudfiles/_cloudfiles.php.html"> cloudfiles.php </a><br> </div><br /> <b>Classes:</b><br /> <div class="package"> <a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a><br /> <a href="../php-cloudfiles/CF_Connection.html">CF_Connection</a><br /> <a href="../php-cloudfiles/CF_Container.html">CF_Container</a><br /> <a href="../php-cloudfiles/CF_Object.html">CF_Object</a><br /> </div> </td> <td> <table cellpadding="10" cellspacing="0" width="100%" border="0"><tr><td valign="top"> <h1>Class: CF_Container</h1> Source Location: /cloudfiles.php<br /><br /> <table width="100%" border="0"> <tr><td valign="top"> <h3><a href="#class_details">Class Overview</a></h3> <pre></pre><br /> <div class="description">Container operations</div><br /><br /> </td> <td valign="top"> <h3><a href="#class_vars">Variables</a></h3> <ul> <li><a href="../php-cloudfiles/CF_Container.html#var$bytes_used">$bytes_used</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cdn_acl_referrer">$cdn_acl_referrer</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cdn_acl_user_agent">$cdn_acl_user_agent</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cdn_enabled">$cdn_enabled</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cdn_log_retention">$cdn_log_retention</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cdn_ttl">$cdn_ttl</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cdn_uri">$cdn_uri</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cfs_auth">$cfs_auth</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$cfs_http">$cfs_http</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$name">$name</a></li> <li><a href="../php-cloudfiles/CF_Container.html#var$object_count">$object_count</a></li> </ul> </td> <td valign="top"> <h3><a href="#class_methods">Methods</a></h3> <ul> <li><a href="../php-cloudfiles/CF_Container.html#method__construct">__construct</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodacl_referrer">acl_referrer</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodacl_user_agent">acl_user_agent</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodcreate_object">create_object</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodcreate_paths">create_paths</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methoddelete_object">delete_object</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodget_object">get_object</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodget_objects">get_objects</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodis_public">is_public</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodlog_retention">log_retention</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodmake_private">make_private</a></li> <li><a href="../php-cloudfiles/CF_Container.html#methodmake_public">make_public</a></li> <li><a href="../php-cloudfiles/CF_Container.html#method__toString">__toString</a></li> </ul> </td> </tr></table> <hr /> <table width="100%" border="0"><tr> </tr></table> <hr /> <a name="class_details"></a> <h3>Class Details</h3> <div class="tags"> [line 907]<br /> Container operations<br /><br /><p>Containers are storage compartments where you put your data (objects). A container is similar to a directory or folder on a conventional filesystem with the exception that they exist in a flat namespace, you can not create containers inside of containers.</p><p>You also have the option of marking a Container as &quot;public&quot; so that the Objects stored in the Container are publicly available via the CDN.</p><br /></div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <hr /> <a name="class_vars"></a> <h3>Class Variables</h3> <div class="tags"> <a name="var$bytes_used"></a> <p></p> <h4>$bytes_used = <span class="value"></span></h4> <p>[line 913]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cdn_acl_referrer"></a> <p></p> <h4>$cdn_acl_referrer = <span class="value"></span></h4> <p>[line 920]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cdn_acl_user_agent"></a> <p></p> <h4>$cdn_acl_user_agent = <span class="value"></span></h4> <p>[line 919]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cdn_enabled"></a> <p></p> <h4>$cdn_enabled = <span class="value"></span></h4> <p>[line 915]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cdn_log_retention"></a> <p></p> <h4>$cdn_log_retention = <span class="value"></span></h4> <p>[line 918]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cdn_ttl"></a> <p></p> <h4>$cdn_ttl = <span class="value"></span></h4> <p>[line 917]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cdn_uri"></a> <p></p> <h4>$cdn_uri = <span class="value"></span></h4> <p>[line 916]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cfs_auth"></a> <p></p> <h4>$cfs_auth = <span class="value"></span></h4> <p>[line 909]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$cfs_http"></a> <p></p> <h4>$cfs_http = <span class="value"></span></h4> <p>[line 910]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$name"></a> <p></p> <h4>$name = <span class="value"></span></h4> <p>[line 911]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> <a name="var$object_count"></a> <p></p> <h4>$object_count = <span class="value"></span></h4> <p>[line 912]</p> <br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>access:</b>&nbsp;&nbsp;</td><td>public</td> </tr> </table> </div> <br /> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>Type:</b>&nbsp;&nbsp;</td> <td>mixed</td> </tr> </table> </div><br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div><br /> </div><br /> <hr /> <a name="class_methods"></a> <h3>Class Methods</h3> <div class="tags"> <hr /> <a name="method__construct"></a> <h3>constructor __construct <span class="smalllinenumber">[line 934]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>CF_Container __construct( &$cfs_auth, &$cfs_http, string $name, [int $count = 0], [int $bytes = 0], [ $docdn = True], obj $cfs_auth, obj $cfs_http)</code> </td></tr></table> </td></tr></table><br /> Class constructor<br /><br /><p>Constructor for Container</p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>SyntaxException invalid Container name</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">obj&nbsp;&nbsp;</td> <td><b>$cfs_auth</b>&nbsp;&nbsp;</td> <td>CF_Authentication instance</td> </tr> <tr> <td class="type">obj&nbsp;&nbsp;</td> <td><b>$cfs_http</b>&nbsp;&nbsp;</td> <td>HTTP connection manager</td> </tr> <tr> <td class="type">string&nbsp;&nbsp;</td> <td><b>$name</b>&nbsp;&nbsp;</td> <td>name of Container</td> </tr> <tr> <td class="type">int&nbsp;&nbsp;</td> <td><b>$count</b>&nbsp;&nbsp;</td> <td>number of Objects stored in this Container</td> </tr> <tr> <td class="type">int&nbsp;&nbsp;</td> <td><b>$bytes</b>&nbsp;&nbsp;</td> <td>number of bytes stored in this Container</td> </tr> <tr> <td class="type">&nbsp;&nbsp;</td> <td><b>&$cfs_auth</b>&nbsp;&nbsp;</td> <td></td> </tr> <tr> <td class="type">&nbsp;&nbsp;</td> <td><b>&$cfs_http</b>&nbsp;&nbsp;</td> <td></td> </tr> <tr> <td class="type">&nbsp;&nbsp;</td> <td><b>$docdn</b>&nbsp;&nbsp;</td> <td></td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodacl_referrer"></a> <h3>method acl_referrer <span class="smalllinenumber">[line 1122]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>boolean acl_referrer( [ $cdn_acl_referrer = &quot;&quot;])</code> </td></tr></table> </td></tr></table><br /> Enable ACL restriction by referer for this container.<br /><br /><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Enable&nbsp;Referrer</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodacl_referrer">acl_referrer</a><span class="src-sym">(</span><span class="src-str">&quot;http://www.example.com/gallery.php&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>True if successful</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>CDNNotEnabledException CDN functionality not returned during auth</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>AuthenticationException if auth token is not valid/expired</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">&nbsp;&nbsp;</td> <td><b>$cdn_acl_referrer</b>&nbsp;&nbsp;</td> <td></td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodacl_user_agent"></a> <h3>method acl_user_agent <span class="smalllinenumber">[line 1082]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>boolean acl_user_agent( [ $cdn_acl_user_agent = &quot;&quot;])</code> </td></tr></table> </td></tr></table><br /> Enable ACL restriction by User Agent for this container.<br /><br /><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Enable&nbsp;ACL&nbsp;by&nbsp;Referrer</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodacl_referrer">acl_referrer</a><span class="src-sym">(</span><span class="src-str">&quot;Mozilla&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>True if successful</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>CDNNotEnabledException CDN functionality not returned during auth</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>AuthenticationException if auth token is not valid/expired</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">&nbsp;&nbsp;</td> <td><b>$cdn_acl_user_agent</b>&nbsp;&nbsp;</td> <td></td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodcreate_object"></a> <h3>method create_object <span class="smalllinenumber">[line 1290]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>obj create_object( [string $obj_name = NULL])</code> </td></tr></table> </td></tr></table><br /> Create a new remote storage Object<br /><br /><p>Return a new Object instance. If the remote storage Object exists, the instance's attributes are populated.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;This&nbsp;creates&nbsp;a&nbsp;local&nbsp;instance&nbsp;of&nbsp;a&nbsp;storage&nbsp;object&nbsp;but&nbsp;only&nbsp;creates</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;it&nbsp;in&nbsp;the&nbsp;storage&nbsp;system&nbsp;when&nbsp;the&nbsp;object's&nbsp;write()&nbsp;method&nbsp;is&nbsp;called.</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$pic&nbsp;</span>=&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodcreate_object">create_object</a><span class="src-sym">(</span><span class="src-str">&quot;baby.jpg&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>CF_Object instance</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">string&nbsp;&nbsp;</td> <td><b>$obj_name</b>&nbsp;&nbsp;</td> <td>name of storage Object</td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodcreate_paths"></a> <h3>method create_paths <span class="smalllinenumber">[line 1516]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>void create_paths( $path_name)</code> </td></tr></table> </td></tr></table><br /> Helper function to create &quot;path&quot; elements for a given Object name<br /><br /><p>Given an Object whos name contains '/' path separators, this function will create the &quot;directory marker&quot; Objects of one byte with the Content-Type of &quot;application/folder&quot;.</p><p>It assumes the last element of the full path is the &quot;real&quot; Object and does NOT create a remote storage Object for that last element.</p><br /><br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">&nbsp;&nbsp;</td> <td><b>$path_name</b>&nbsp;&nbsp;</td> <td></td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methoddelete_object"></a> <h3>method delete_object <span class="smalllinenumber">[line 1476]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>boolean delete_object( obj $obj)</code> </td></tr></table> </td></tr></table><br /> Delete a remote storage Object<br /><br /><p>Given an Object instance or name, permanently remove the remote Object and all associated metadata.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$images&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;my&nbsp;photos&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Delete&nbsp;specific&nbsp;object</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methoddelete_object">delete_object</a><span class="src-sym">(</span><span class="src-str">&quot;disco_dancing.jpg&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td><kbd>True</kbd> if successfully removed</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>SyntaxException invalid Object name</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>NoSuchObjectException remote Object does not exist</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">obj&nbsp;&nbsp;</td> <td><b>$obj</b>&nbsp;&nbsp;</td> <td>name or instance of Object to delete</td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodget_object"></a> <h3>method get_object <span class="smalllinenumber">[line 1319]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>obj get_object( [string $obj_name = NULL])</code> </td></tr></table> </td></tr></table><br /> Return an Object instance for the remote storage Object<br /><br /><p>Given a name, return a Object instance representing the remote storage object.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;This&nbsp;call&nbsp;only&nbsp;fetches&nbsp;header&nbsp;information&nbsp;and&nbsp;not&nbsp;the&nbsp;content&nbsp;of</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;the&nbsp;storage&nbsp;object.&nbsp;&nbsp;Use&nbsp;the&nbsp;Object's&nbsp;read()&nbsp;or&nbsp;stream()&nbsp;methods</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;to&nbsp;obtain&nbsp;the&nbsp;object's&nbsp;data.</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$pic&nbsp;</span>=&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodget_object">get_object</a><span class="src-sym">(</span><span class="src-str">&quot;baby.jpg&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>CF_Object instance</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">string&nbsp;&nbsp;</td> <td><b>$obj_name</b>&nbsp;&nbsp;</td> <td>name of storage Object</td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodget_objects"></a> <h3>method get_objects <span class="smalllinenumber">[line 1427]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>array get_objects( [int $limit = 0], [int $marker = NULL], [string $prefix = NULL], [string $path = NULL])</code> </td></tr></table> </td></tr></table><br /> Return an array of Objects<br /><br /><p>Return an array of Object instances in this Container.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$images&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;my&nbsp;photos&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Grab&nbsp;the&nbsp;list&nbsp;of&nbsp;all&nbsp;storage&nbsp;objects</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$all_objects&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodget_objects">get_objects</a><span class="src-sym">(</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Grab&nbsp;subsets&nbsp;of&nbsp;all&nbsp;storage&nbsp;objects</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$first_ten&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodget_objects">get_objects</a><span class="src-sym">(</span><span class="src-num">10</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Note&nbsp;the&nbsp;use&nbsp;of&nbsp;the&nbsp;previous&nbsp;result's&nbsp;last&nbsp;object&nbsp;name&nbsp;being</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;used&nbsp;as&nbsp;the&nbsp;'marker'&nbsp;parameter&nbsp;to&nbsp;fetch&nbsp;the&nbsp;next&nbsp;10&nbsp;objects</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$next_ten&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a><span class="src-sym">(</span><span class="src-num">10</span><span class="src-sym">,&nbsp;</span><span class="src-var">$first_ten</span><span class="src-sym">[</span><a href="http://www.php.net/count">count</a><span class="src-sym">(</span><span class="src-var">$first_ten</span><span class="src-sym">)</span>-<span class="src-num">1</span><span class="src-sym">]</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Grab&nbsp;images&nbsp;starting&nbsp;with&nbsp;&quot;birthday_party&quot;&nbsp;and&nbsp;default&nbsp;limit/marker</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;to&nbsp;match&nbsp;all&nbsp;photos&nbsp;with&nbsp;that&nbsp;prefix</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$prefixed&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodget_objects">get_objects</a><span class="src-sym">(</span><span class="src-num">0</span><span class="src-sym">,&nbsp;</span><span class="src-id">NULL</span><span class="src-sym">,&nbsp;</span><span class="src-str">&quot;birthday&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Assuming&nbsp;you&nbsp;have&nbsp;created&nbsp;the&nbsp;appropriate&nbsp;directory&nbsp;marker&nbsp;Objects,</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;you&nbsp;can&nbsp;traverse&nbsp;your&nbsp;pseudo-hierarchical&nbsp;containers</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;with&nbsp;the&nbsp;&quot;path&quot;&nbsp;argument.</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$animals&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodget_objects">get_objects</a><span class="src-sym">(</span><span class="src-num">0</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-str">&quot;pictures/animals&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$dogs&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodget_objects">get_objects</a><span class="src-sym">(</span><span class="src-num">0</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-str">&quot;pictures/animals/dogs&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>array of strings</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">int&nbsp;&nbsp;</td> <td><b>$limit</b>&nbsp;&nbsp;</td> <td><em>optional</em> only return $limit names</td> </tr> <tr> <td class="type">int&nbsp;&nbsp;</td> <td><b>$marker</b>&nbsp;&nbsp;</td> <td><em>optional</em> subset of names starting at $marker</td> </tr> <tr> <td class="type">string&nbsp;&nbsp;</td> <td><b>$prefix</b>&nbsp;&nbsp;</td> <td><em>optional</em> Objects whose names begin with $prefix</td> </tr> <tr> <td class="type">string&nbsp;&nbsp;</td> <td><b>$path</b>&nbsp;&nbsp;</td> <td><em>optional</em> only return results under &quot;pathname&quot;</td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodis_public"></a> <h3>method is_public <span class="smalllinenumber">[line 1262]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>boolean is_public( )</code> </td></tr></table> </td></tr></table><br /> Check if this Container is being publicly served via CDN<br /><br /><p>Use this method to determine if the Container's content is currently available through the CDN.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Display&nbsp;CDN&nbsp;accessability</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodis_public">is_public</a><span class="src-sym">(</span><span class="src-sym">)&nbsp;</span>?&nbsp;print&nbsp;<span class="src-str">&quot;Yes&quot;&nbsp;</span>:&nbsp;print&nbsp;<span class="src-str">&quot;No&quot;</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>True if enabled, False otherwise</td> </tr> </table> </div> <br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodlist_objects"></a> <h3>method list_objects <span class="smalllinenumber">[line 1368]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>array list_objects( [int $limit = 0], [int $marker = NULL], [string $prefix = NULL], [string $path = NULL])</code> </td></tr></table> </td></tr></table><br /> Return a list of Objects<br /><br /><p>Return an array of strings listing the Object names in this Container.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$images&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;my&nbsp;photos&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Grab&nbsp;the&nbsp;list&nbsp;of&nbsp;all&nbsp;storage&nbsp;objects</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$all_objects&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a><span class="src-sym">(</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Grab&nbsp;subsets&nbsp;of&nbsp;all&nbsp;storage&nbsp;objects</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$first_ten&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a><span class="src-sym">(</span><span class="src-num">10</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Note&nbsp;the&nbsp;use&nbsp;of&nbsp;the&nbsp;previous&nbsp;result's&nbsp;last&nbsp;object&nbsp;name&nbsp;being</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;used&nbsp;as&nbsp;the&nbsp;'marker'&nbsp;parameter&nbsp;to&nbsp;fetch&nbsp;the&nbsp;next&nbsp;10&nbsp;objects</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$next_ten&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a><span class="src-sym">(</span><span class="src-num">10</span><span class="src-sym">,&nbsp;</span><span class="src-var">$first_ten</span><span class="src-sym">[</span><a href="http://www.php.net/count">count</a><span class="src-sym">(</span><span class="src-var">$first_ten</span><span class="src-sym">)</span>-<span class="src-num">1</span><span class="src-sym">]</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Grab&nbsp;images&nbsp;starting&nbsp;with&nbsp;&quot;birthday_party&quot;&nbsp;and&nbsp;default&nbsp;limit/marker</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;to&nbsp;match&nbsp;all&nbsp;photos&nbsp;with&nbsp;that&nbsp;prefix</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$prefixed&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a><span class="src-sym">(</span><span class="src-num">0</span><span class="src-sym">,&nbsp;</span><span class="src-id">NULL</span><span class="src-sym">,&nbsp;</span><span class="src-str">&quot;birthday&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Assuming&nbsp;you&nbsp;have&nbsp;created&nbsp;the&nbsp;appropriate&nbsp;directory&nbsp;marker&nbsp;Objects,</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;you&nbsp;can&nbsp;traverse&nbsp;your&nbsp;pseudo-hierarchical&nbsp;containers</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;with&nbsp;the&nbsp;&quot;path&quot;&nbsp;argument.</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$animals&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a><span class="src-sym">(</span><span class="src-num">0</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-str">&quot;pictures/animals&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$dogs&nbsp;</span>=&nbsp;<span class="src-var">$images</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlist_objects">list_objects</a><span class="src-sym">(</span><span class="src-num">0</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-id">NULL</span><span class="src-sym">,</span><span class="src-str">&quot;pictures/animals/dogs&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>array of strings</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">int&nbsp;&nbsp;</td> <td><b>$limit</b>&nbsp;&nbsp;</td> <td><em>optional</em> only return $limit names</td> </tr> <tr> <td class="type">int&nbsp;&nbsp;</td> <td><b>$marker</b>&nbsp;&nbsp;</td> <td><em>optional</em> subset of names starting at $marker</td> </tr> <tr> <td class="type">string&nbsp;&nbsp;</td> <td><b>$prefix</b>&nbsp;&nbsp;</td> <td><em>optional</em> Objects whose names begin with $prefix</td> </tr> <tr> <td class="type">string&nbsp;&nbsp;</td> <td><b>$path</b>&nbsp;&nbsp;</td> <td><em>optional</em> only return results under &quot;pathname&quot;</td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodlog_retention"></a> <h3>method log_retention <span class="smalllinenumber">[line 1168]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>boolean log_retention( [ $cdn_log_retention = False])</code> </td></tr></table> </td></tr></table><br /> Enable log retention for this CDN container.<br /><br /><p>Enable CDN log retention on the container. If enabled logs will be periodically (at unpredictable intervals) compressed and uploaded to a &quot;.CDN_ACCESS_LOGS&quot; container in the form of &quot;container_name.YYYYMMDDHH-XXXX.gz&quot;. Requires CDN be enabled on the account.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Enable&nbsp;logs&nbsp;retention.</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodlog_retention">log_retention</a><span class="src-sym">(</span><span class="src-id">True</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>True if successful</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>CDNNotEnabledException CDN functionality not returned during auth</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>AuthenticationException if auth token is not valid/expired</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">&nbsp;&nbsp;</td> <td><b>$cdn_log_retention</b>&nbsp;&nbsp;</td> <td></td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodmake_private"></a> <h3>method make_private <span class="smalllinenumber">[line 1218]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>boolean make_private( )</code> </td></tr></table> </td></tr></table><br /> Disable the CDN sharing for this container<br /><br /><p>Use this method to disallow distribution into the CDN of this Container's content.</p><p>NOTE: Any content already cached in the CDN will continue to be served from its cache until the TTL expiration transpires. The default TTL is typically one day, so &quot;privatizing&quot; the Container will take up to 24 hours before the content is purged from the CDN cache.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">get_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;Disable&nbsp;CDN&nbsp;accessability</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;still&nbsp;cached&nbsp;up&nbsp;to&nbsp;a&nbsp;month&nbsp;based&nbsp;on&nbsp;previous&nbsp;example</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodmake_private">make_private</a><span class="src-sym">(</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>True if successful</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>CDNNotEnabledException CDN functionality not returned during auth</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>AuthenticationException if auth token is not valid/expired</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="methodmake_public"></a> <h3>method make_public <span class="smalllinenumber">[line 1018]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>string make_public( [int $ttl = 86400])</code> </td></tr></table> </td></tr></table><br /> Enable Container content to be served via CDN or modify CDN attributes<br /><br /><p>Either enable this Container's content to be served via CDN or adjust its CDN attributes. This Container will always return the same CDN-enabled URI each time it is toggled public/private/public.</p><p>Example: <ol><li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;...&nbsp;authentication&nbsp;code&nbsp;excluded&nbsp;(see&nbsp;previous&nbsp;examples)&nbsp;...</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$conn&nbsp;</span>=&nbsp;<span class="src-key">new&nbsp;</span><span class="src-id"><a href="../php-cloudfiles/CF_Authentication.html">CF_Authentication</a></span><span class="src-sym">(</span><span class="src-var">$auth</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container&nbsp;</span>=&nbsp;<span class="src-var">$conn</span><span class="src-sym">-&gt;</span><span class="src-id">create_container</span><span class="src-sym">(</span><span class="src-str">&quot;public&quot;</span><span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line">&nbsp;</div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#&nbsp;CDN-enable&nbsp;the&nbsp;container&nbsp;and&nbsp;set&nbsp;it's&nbsp;TTL&nbsp;for&nbsp;a&nbsp;month</span></div></li> <li><div class="src-line">&nbsp;<span class="src-comm">#</span></div></li> <li><div class="src-line">&nbsp;<span class="src-var">$public_container</span><span class="src-sym">-&gt;</span><a href="../php-cloudfiles/CF_Container.html#methodmake_public">make_public</a><span class="src-sym">(</span><span class="src-num">86400</span>/<span class="src-num">2</span><span class="src-sym">)</span><span class="src-sym">;&nbsp;</span><span class="src-comm">#&nbsp;12&nbsp;hours&nbsp;(86400&nbsp;seconds/day)</span></div></li> </ol></p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>the CDN enabled Container's URI</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>CDNNotEnabledException CDN functionality not returned during auth</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>AuthenticationException if auth token is not valid/expired</td> </tr> <tr> <td><b>throws:</b>&nbsp;&nbsp;</td><td>InvalidResponseException unexpected response</td> </tr> </table> </div> <br /><br /> <h4>Parameters:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td class="type">int&nbsp;&nbsp;</td> <td><b>$ttl</b>&nbsp;&nbsp;</td> <td>the time in seconds content will be cached in the CDN</td> </tr> </table> </div><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> <hr /> <a name="method__toString"></a> <h3>method __toString <span class="smalllinenumber">[line 968]</span></h3> <div class="function"> <table width="90%" border="0" cellspacing="0" cellpadding="1"><tr><td class="code_border"> <table width="100%" border="0" cellspacing="0" cellpadding="2"><tr><td class="code"> <code>string __toString( )</code> </td></tr></table> </td></tr></table><br /> String representation of Container<br /><br /><p>Pretty print the Container instance.</p><br /><br /><br /> <h4>Tags:</h4> <div class="tags"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><b>return:</b>&nbsp;&nbsp;</td><td>Container details</td> </tr> </table> </div> <br /><br /> <div class="top">[ <a href="#top">Top</a> ]</div> </div> </div><br /> <div class="credit"> <hr /> Documentation generated on Fri, 26 Mar 2010 12:08:48 -0500 by <a href="http://www.phpdoc.org">phpDocumentor 1.4.3</a> </div> </td></tr></table> </td> </tr> </table> </body> </html>
{ "content_hash": "0f629d80644171618f8dcb8789698211", "timestamp": "", "source": "github", "line_count": 1160, "max_line_length": 675, "avg_line_length": 51.70775862068965, "alnum_prop": 0.6178289791767393, "repo_name": "spinolacastro/magento-scalable", "id": "fd857c6d72a9c5d09b404766398536f1abcb2fe5", "size": "59981", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "php/app/code/community/OnePica/ImageCdn/Model/Adapter/Rackspace/docs/php-cloudfiles/CF_Container.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "19946" }, { "name": "CSS", "bytes": "1009981" }, { "name": "Erlang", "bytes": "1423" }, { "name": "JavaScript", "bytes": "856031" }, { "name": "PHP", "bytes": "43566003" }, { "name": "Perl", "bytes": "549183" }, { "name": "Shell", "bytes": "5986" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/search" android:title="搜索" android:actionViewClass="android.widget.SearchView" android:orderInCategory="100" android:showAsAction="always" /> <item android:id="@+id/progress" android:actionLayout="@layout/clock" android:orderInCategory="100" android:showAsAction="always" android:title="模拟时钟" /> </menu>
{ "content_hash": "7bd2d7cde3f51612de5daaf859698e6e", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 65, "avg_line_length": 34.733333333333334, "alnum_prop": 0.6276391554702495, "repo_name": "jiyilanzhou/coolweather", "id": "65d45499bab91156fffe25213337ce46038c6c18", "size": "533", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/menu/menu_poppup_menu_demo.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "302143" } ], "symlink_target": "" }
package cmwell.web.ld.service /** * Created with IntelliJ IDEA. * User: gilad * Date: 7/22/13 * Time: 9:02 AM * To change this template use File | Settings | File Templates. */ object Conf { lazy val metaNsToken: String = { val is = Thread.currentThread.getContextClassLoader.getResourceAsStream("token-meta_ns.txt") scala.io.Source.fromInputStream(is).mkString } }
{ "content_hash": "9a94b0d5b1471e4c379352f60fe938c6", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 96, "avg_line_length": 24.5, "alnum_prop": 0.6964285714285714, "repo_name": "thomsonreuters/CM-Well", "id": "7b67bee8d8f2c65afc7e77b62375314abd8cf73e", "size": "1007", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "server/cmwell-ws/app/ld/service/Conf.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "53" }, { "name": "CSS", "bytes": "165222" }, { "name": "Dockerfile", "bytes": "3422" }, { "name": "Groovy", "bytes": "664" }, { "name": "HTML", "bytes": "125489" }, { "name": "Java", "bytes": "3557" }, { "name": "JavaScript", "bytes": "524530" }, { "name": "Scala", "bytes": "3870277" }, { "name": "Shell", "bytes": "41744" }, { "name": "XSLT", "bytes": "2451" } ], "symlink_target": "" }
MIT License Copyright (c) 2017 Steve Haroz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{ "content_hash": "c39f7a66f8e4bb788c86d57e12613967", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 78, "avg_line_length": 50.857142857142854, "alnum_prop": 0.8052434456928839, "repo_name": "steveharoz/open-access-vis", "id": "8b8e17b2af481d77325415304b2fe9879fabac4b", "size": "1068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".github/LICENSE.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "28381" }, { "name": "HTML", "bytes": "72065" }, { "name": "JavaScript", "bytes": "42974" }, { "name": "PHP", "bytes": "896" } ], "symlink_target": "" }
import { mount } from '@vue/test-utils'; import SearchSideBar from '../src/views/SearchSideBar'; import SampleSearchResults from './SampleSearchResults'; function createWrapper() { return mount(SearchSideBar, { propsData: { book: {}, }, }); } describe('Search side bar', () => { it('should mount', () => { const wrapper = createWrapper(); expect(wrapper.exists()).toBe(true); }); it('should allow parent to focus on input box', () => { const wrapper = createWrapper(); wrapper.vm.focusOnInput(); const elementThatIsFocused = document.activeElement; expect(elementThatIsFocused.classList.contains('search-input')).toBe(true); }); it('should highlight search terms', () => { const wrapper = createWrapper(); wrapper.vm.searchQuery = 'biology'; wrapper.vm.searchResults = SampleSearchResults; wrapper.vm.createMarks(wrapper.vm.searchQuery); expect.assertions(1); wrapper.vm.$nextTick(() => { const allMarks = wrapper.findAll('mark'); expect(allMarks.length).toBeGreaterThanOrEqual(wrapper.vm.searchResults.length); }); }); });
{ "content_hash": "78473c97532b1ccb188a459fe9628f84", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 86, "avg_line_length": 30.324324324324323, "alnum_prop": 0.6675579322638147, "repo_name": "DXCanas/kolibri", "id": "b6369f47c58553735588217e8af6177cbc0797e6", "size": "1122", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "kolibri/plugins/document_epub_render/assets/tests/SearchSideBar.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "864" }, { "name": "CSS", "bytes": "32872" }, { "name": "Dockerfile", "bytes": "4332" }, { "name": "Gherkin", "bytes": "115979" }, { "name": "HTML", "bytes": "14251" }, { "name": "JavaScript", "bytes": "890295" }, { "name": "Makefile", "bytes": "9885" }, { "name": "Python", "bytes": "1363204" }, { "name": "Shell", "bytes": "10407" }, { "name": "Vue", "bytes": "944905" } ], "symlink_target": "" }
<?php namespace Codeception\Test\Interfaces; use PHPUnit\Framework\SelfDescribing; interface Descriptive extends SelfDescribing { public function getFileName(): string; public function getSignature(): string; }
{ "content_hash": "817680b73d1f5197a241fc1353c074cb", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 44, "avg_line_length": 18.583333333333332, "alnum_prop": 0.7802690582959642, "repo_name": "Codeception/Codeception", "id": "a2833feb6c68b0778a18c01729d137a6233a6fdb", "size": "223", "binary": false, "copies": "1", "ref": "refs/heads/5.0", "path": "src/Codeception/Test/Interfaces/Descriptive.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "123" }, { "name": "Dockerfile", "bytes": "1525" }, { "name": "Gherkin", "bytes": "3638" }, { "name": "Hack", "bytes": "37209" }, { "name": "PHP", "bytes": "1106769" }, { "name": "Shell", "bytes": "19" } ], "symlink_target": "" }
using OpenSim.Framework.Servers.HttpServer; using System.Collections; using System.IO; namespace OpenSim.Framework.Capabilities { public class LLSDStreamhandler<TRequest, TResponse> : BaseStreamHandler where TRequest : new() { private LLSDMethod<TRequest, TResponse> m_method; public LLSDStreamhandler(string httpMethod, string path, LLSDMethod<TRequest, TResponse> method) : this(httpMethod, path, method, null, null) {} public LLSDStreamhandler( string httpMethod, string path, LLSDMethod<TRequest, TResponse> method, string name, string description) : base(httpMethod, path, name, description) { m_method = method; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { //Encoding encoding = Util.UTF8; //StreamReader streamReader = new StreamReader(request, false); //string requestBody = streamReader.ReadToEnd(); //streamReader.Close(); // OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap) // OpenMetaverse.StructuredData.LLSDParser.DeserializeXml(new XmlTextReader(request)); Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(request); TRequest llsdRequest = new TRequest(); LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest); TResponse response = m_method(llsdRequest); return Util.UTF8NoBomEncoding.GetBytes(LLSDHelpers.SerialiseLLSDReply(response)); } } }
{ "content_hash": "4d009c7adf30d0ec2d45097726666bd3", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 116, "avg_line_length": 37.51111111111111, "alnum_prop": 0.6575829383886256, "repo_name": "BogusCurry/arribasim-dev", "id": "46b8fa853e78c43f942bd91d15d6ef5dc905d1e4", "size": "3305", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "OpenSim/Capabilities/LLSDStreamHandler.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1255" }, { "name": "C#", "bytes": "16782866" }, { "name": "CSS", "bytes": "1683" }, { "name": "HTML", "bytes": "9537" }, { "name": "JavaScript", "bytes": "556" }, { "name": "LSL", "bytes": "36962" }, { "name": "Makefile", "bytes": "776" }, { "name": "PLpgSQL", "bytes": "599" }, { "name": "Python", "bytes": "5053" }, { "name": "Ruby", "bytes": "1111" }, { "name": "Shell", "bytes": "955" } ], "symlink_target": "" }
using System; using System.Collections.Generic; namespace Sokoban { class CommandManager { readonly Stack<Command> _undoStack = new Stack<Command>(); readonly Stack<Command> _redoStack = new Stack<Command>(); /// <summary> /// Undo 可能な状態かどうかを示します /// </summary> public bool CanUndo => _undoStack.Count > 0; /// <summary> /// Redo 可能な状態かどうかを示します /// </summary> public bool CanRedo => _redoStack.Count > 0; /// <summary> /// コマンドを実行します /// </summary> /// <param name="command"></param> public void Do(Command command) { command.Do(); _undoStack.Push(command); _redoStack.Clear(); } /// <summary> /// 履歴をクリアします /// </summary> public void Clear() { _undoStack.Clear(); _redoStack.Clear(); } /// <summary> /// Undo を実行します /// </summary> public void Undo() { if (!CanUndo) return; var command = _undoStack.Pop(); command.Undo(); _redoStack.Push(command); } /// <summary> /// Redo を実行します /// </summary> public void Redo() { if (!CanRedo) return; var command = _redoStack.Pop(); command.Do(); _undoStack.Push(command); } } class Command { Action _doAction; Action _undoAction; public Command(Action doAction, Action undoAction) { _doAction = doAction; _undoAction = undoAction; } public void Do() { _doAction(); } public void Undo() { _undoAction(); } } }
{ "content_hash": "39b61802ae099ae83962bb5322387031", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 66, "avg_line_length": 22.353658536585368, "alnum_prop": 0.46153846153846156, "repo_name": "setchi/Sokoban", "id": "587edd9c24eb623693dd05b78d93b8aa84d4b934", "size": "1953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sokoban/CommandManager.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "22399" } ], "symlink_target": "" }
[![Cookbook Version](http://img.shields.io/cookbook/v/geckodriver.svg?style=flat-square)][cookbook] [![linux](http://img.shields.io/travis/dhoer/chef-geckodriver/master.svg?label=linux&style=flat-square)][linux] [![osx](http://img.shields.io/travis/dhoer/chef-geckodriver/macosx.svg?label=macosx&style=flat-square)][osx] [![win](https://img.shields.io/appveyor/ci/dhoer/chef-geckodriver/master.svg?label=windows&style=flat-square)][win] [cookbook]: https://supermarket.chef.io/cookbooks/geckodriver [linux]: https://travis-ci.org/dhoer/chef-geckodriver [osx]: https://travis-ci.org/dhoer/chef-geckodriver/branches [win]: https://ci.appveyor.com/project/dhoer/chef-geckodriver Installs geckodriver (https://github.com/mozilla/geckodriver). ## Requirements - Chef 12.6+ - Mozilla Firefox (this cookbook does not install Mozilla Firefox) ### Platforms - CentOS, RedHat, Fedora - Mac OS X - Ubuntu, Debian - Windows ## Usage Include recipe in a run list or cookbook to install geckodriver. ### Attributes - `node['geckodriver']['version']` - Version to download. - `node['geckodriver']['url']` - URL download prefix. - `node['geckodriver']['windows']['home']` - Home directory for windows. - `node['geckodriver']['unix']['home']` - Home directory for both linux and macosx. #### Install selenium node with firefox capability ```ruby include_recipe 'mozilla_firefox' include_recipe 'geckodriver' node.override['selenium']['node']['capabilities'] = [ { browserName: 'firefox', maxInstances: 1, version: firefox_version, seleniumProtocol: 'WebDriver' } ] include_recipe 'selenium::node' ``` ## Getting Help - Ask specific questions on [Stack Overflow](http://stackoverflow.com/questions/tagged/marionette+driver). - Report bugs and discuss potential features in [Github issues](https://github.com/dhoer/chef-geckodriver/issues). ## Contributing Please refer to [CONTRIBUTING](https://github.com/dhoer/chef-geckodriver/graphs/contributors). ## License MIT - see the accompanying [LICENSE](https://github.com/dhoer/chef-geckodriver/blob/master/LICENSE.md) file for details.
{ "content_hash": "6a42f315c298255fae74bcd647652f4f", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 115, "avg_line_length": 32, "alnum_prop": 0.7372159090909091, "repo_name": "dhoer/chef-geckodriver", "id": "67b7393b631f9989282fe76ec3cb04b1ca771b82", "size": "2145", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "7949" } ], "symlink_target": "" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdlib.h> #ifdef _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include <ctype.h> #include "azure_c_shared_utility/gballoc.h" #include "iothub.h" #include "iothub_client.h" #include "iothubtransport.h" #include "iothubtransporthttp.h" #include "iothubtransportamqp.h" #include "iothubtransportmqtt.h" #include "iothub_message.h" #include "azure_c_shared_utility/vector.h" #include "azure_c_shared_utility/xlogging.h" #include "azure_c_shared_utility/strings.h" #include "messageproperties.h" #include "broker.h" #include <parson.h> typedef struct PERSONALITY_TAG { STRING_HANDLE deviceName; STRING_HANDLE deviceKey; IOTHUB_CLIENT_HANDLE iothubHandle; BROKER_HANDLE broker; MODULE_HANDLE module; }PERSONALITY; typedef PERSONALITY* PERSONALITY_PTR; typedef struct IOTHUB_HANDLE_DATA_TAG { VECTOR_HANDLE personalities; /*holds PERSONALITYs*/ STRING_HANDLE IoTHubName; STRING_HANDLE IoTHubSuffix; IOTHUB_CLIENT_TRANSPORT_PROVIDER transportProvider; TRANSPORT_HANDLE transportHandle; BROKER_HANDLE broker; }IOTHUB_HANDLE_DATA; #define SOURCE "source" #define MAPPING "mapping" #define DEVICENAME "deviceName" #define DEVICEKEY "deviceKey" #define SUFFIX "IoTHubSuffix" #define HUBNAME "IoTHubName" #define TRANSPORT "Transport" static int strcmp_i(const char* lhs, const char* rhs) { char lc, rc; int cmp; do { lc = *lhs++; rc = *rhs++; cmp = tolower(lc) - tolower(rc); } while (cmp == 0 && lc != 0 && rc != 0); return cmp; } static MODULE_HANDLE IotHub_Create(BROKER_HANDLE broker, const void* configuration) { IOTHUB_HANDLE_DATA *result; const IOTHUB_CONFIG* config = configuration; /*Codes_SRS_IOTHUBMODULE_02_001: [ If `broker` is `NULL` then `IotHub_Create` shall fail and return `NULL`. ]*/ /*Codes_SRS_IOTHUBMODULE_02_002: [ If `configuration` is `NULL` then `IotHub_Create` shall fail and return `NULL`. ]*/ /*Codes_SRS_IOTHUBMODULE_02_003: [ If `configuration->IoTHubName` is `NULL` then `IotHub_Create` shall and return `NULL`. ]*/ /*Codes_SRS_IOTHUBMODULE_02_004: [ If `configuration->IoTHubSuffix` is `NULL` then `IotHub_Create` shall fail and return `NULL`. ]*/ if ( (broker == NULL) || (configuration == NULL) ) { LogError("invalid arg broker=%p, configuration=%p", broker, configuration); result = NULL; } else if ( (config->IoTHubName == NULL) || (config->IoTHubSuffix == NULL) || (config->transportProvider == NULL) ) { LogError("invalid configuration IoTHubName=%s IoTHubSuffix=%s transportProvider=%p", (config != NULL) ? config->IoTHubName : "<null>", (config != NULL) ? config->IoTHubSuffix : "<null>", (config != NULL) ? config->transportProvider : 0); result = NULL; } else { result = malloc(sizeof(IOTHUB_HANDLE_DATA)); /*Codes_SRS_IOTHUBMODULE_02_027: [ When `IotHub_Create` encounters an internal failure it shall fail and return `NULL`. ]*/ if (result == NULL) { LogError("malloc returned NULL"); /*return as is*/ } else { /*Codes_SRS_IOTHUBMODULE_02_006: [ `IotHub_Create` shall create an empty `VECTOR` containing pointers to `PERSONALITY`s. ]*/ result->personalities = VECTOR_create(sizeof(PERSONALITY_PTR)); if (result->personalities == NULL) { /*Codes_SRS_IOTHUBMODULE_02_007: [ If creating the personality vector fails then `IotHub_Create` shall fail and return `NULL`. ]*/ free(result); result = NULL; LogError("VECTOR_create returned NULL"); } else { result->transportProvider = config->transportProvider; if (result->transportProvider == HTTP_Protocol) { /*Codes_SRS_IOTHUBMODULE_17_001: [ If `configuration->transportProvider` is `HTTP_Protocol`, `IotHub_Create` shall create a shared HTTP transport by calling `IoTHubTransport_Create`. ]*/ result->transportHandle = IoTHubTransport_Create(config->transportProvider, config->IoTHubName, config->IoTHubSuffix); if (result->transportHandle == NULL) { /*Codes_SRS_IOTHUBMODULE_17_002: [ If creating the shared transport fails, `IotHub_Create` shall fail and return `NULL`. ]*/ VECTOR_destroy(result->personalities); free(result); result = NULL; LogError("VECTOR_create returned NULL"); } } else { result->transportHandle = NULL; } if (result != NULL) { /*Codes_SRS_IOTHUBMODULE_02_028: [ `IotHub_Create` shall create a copy of `configuration->IoTHubName`. ]*/ /*Codes_SRS_IOTHUBMODULE_02_029: [ `IotHub_Create` shall create a copy of `configuration->IoTHubSuffix`. ]*/ if ((result->IoTHubName = STRING_construct(config->IoTHubName)) == NULL) { IoTHubTransport_Destroy(result->transportHandle); VECTOR_destroy(result->personalities); free(result); result = NULL; } else if ((result->IoTHubSuffix = STRING_construct(config->IoTHubSuffix)) == NULL) { STRING_delete(result->IoTHubName); IoTHubTransport_Destroy(result->transportHandle); VECTOR_destroy(result->personalities); free(result); result = NULL; } else { /*Codes_SRS_IOTHUBMODULE_17_004: [ `IotHub_Create` shall store the broker. ]*/ result->broker = broker; /*Codes_SRS_IOTHUBMODULE_02_008: [ Otherwise, `IotHub_Create` shall return a non-`NULL` handle. ]*/ } } } } } return result; } static MODULE_HANDLE IotHub_CreateFromJson(BROKER_HANDLE broker, const char* configuration) { MODULE_HANDLE result; if ((broker == NULL) || (configuration == NULL)) { /*Codes_SRS_IOTHUBMODULE_05_001: [If `broker` is NULL then `IotHub_CreateFromJson` shall fail and return NULL.]*/ /*Codes_SRS_IOTHUBMODULE_05_002: [ If `configuration` is NULL then `IotHub_CreateFromJson` shall fail and return NULL. ]*/ LogError("Invalid NULL parameter, broker=[%p] configuration=[%p]", broker, configuration); result = NULL; } else { /*Codes_SRS_IOTHUBMODULE_05_004: [ `IotHub_CreateFromJson` shall parse `configuration` as a JSON string. ]*/ JSON_Value* json = json_parse_string((const char*)configuration); if (json == NULL) { /*Codes_SRS_IOTHUBMODULE_05_003: [ If `configuration` is not a JSON string, then `IotHub_CreateFromJson` shall fail and return NULL. ]*/ LogError("Unable to parse json string"); result = NULL; } else { JSON_Object* obj = json_value_get_object(json); if (obj == NULL) { /*Codes_SRS_IOTHUBMODULE_05_005: [ If parsing of `configuration` fails, `IotHub_CreateFromJson` shall fail and return NULL. ]*/ LogError("Expected a JSON Object in configuration"); result = NULL; } else { const char * IoTHubName; const char * IoTHubSuffix; const char * transport; if ((IoTHubName = json_object_get_string(obj, HUBNAME)) == NULL) { /*Codes_SRS_IOTHUBMODULE_05_006: [ If the JSON object does not contain a value named "IoTHubName" then `IotHub_CreateFromJson` shall fail and return NULL. ]*/ LogError("Did not find expected %s configuration", HUBNAME); result = NULL; } else if ((IoTHubSuffix = json_object_get_string(obj, SUFFIX)) == NULL) { /*Codes_SRS_IOTHUBMODULE_05_007: [ If the JSON object does not contain a value named "IoTHubSuffix" then `IotHub_CreateFromJson` shall fail and return NULL. ]*/ LogError("Did not find expected %s configuration", SUFFIX); result = NULL; } else if ((transport = json_object_get_string(obj, TRANSPORT)) == NULL) { /*Codes_SRS_IOTHUBMODULE_05_011: [ If the JSON object does not contain a value named "Transport" then `IotHub_CreateFromJson` shall fail and return NULL. ]*/ LogError("Did not find expected %s configuration", TRANSPORT); result = NULL; } else { /*Codes_SRS_IOTHUBMODULE_05_012: [ If the value of "Transport" is not one of "HTTP", "AMQP", or "MQTT" (case-insensitive) then `IotHub_CreateFromJson` shall fail and return NULL. ]*/ /*Codes_SRS_IOTHUBMODULE_05_008: [ `IotHub_CreateFromJson` shall invoke the IotHub module's create function, using the broker, IotHubName, IoTHubSuffix, and Transport. ]*/ bool foundTransport = true; IOTHUB_CONFIG llConfiguration; llConfiguration.IoTHubName = IoTHubName; llConfiguration.IoTHubSuffix = IoTHubSuffix; if (strcmp_i(transport, "HTTP") == 0) { llConfiguration.transportProvider = HTTP_Protocol; } else if (strcmp_i(transport, "AMQP") == 0) { llConfiguration.transportProvider = AMQP_Protocol; } else if (strcmp_i(transport, "MQTT") == 0) { llConfiguration.transportProvider = MQTT_Protocol; } else { foundTransport = false; result = NULL; } if (foundTransport) { /*Codes_SRS_IOTHUBMODULE_05_009: [ When the lower layer IotHub module creation succeeds, `IotHub_CreateFromJson` shall succeed and return a non-NULL value. ]*/ /*Codes_SRS_IOTHUBMODULE_05_010: [ If the lower layer IotHub module creation fails, `IotHub_CreateFromJson` shall fail and return NULL. ]*/ result = IotHub_Create(broker, &llConfiguration); } } } json_value_free(json); } } return result; } static void IotHub_Destroy(MODULE_HANDLE moduleHandle) { /*Codes_SRS_IOTHUBMODULE_02_023: [ If `moduleHandle` is `NULL` then `IotHub_Destroy` shall return. ]*/ if (moduleHandle == NULL) { LogError("moduleHandle parameter was NULL"); } else { /*Codes_SRS_IOTHUBMODULE_02_024: [ Otherwise `IotHub_Destroy` shall free all used resources. ]*/ IOTHUB_HANDLE_DATA * handleData = moduleHandle; size_t vectorSize = VECTOR_size(handleData->personalities); for (size_t i = 0; i < vectorSize; i++) { PERSONALITY_PTR* personality = VECTOR_element(handleData->personalities, i); STRING_delete((*personality)->deviceKey); STRING_delete((*personality)->deviceName); IoTHubClient_Destroy((*personality)->iothubHandle); free(*personality); } IoTHubTransport_Destroy(handleData->transportHandle); VECTOR_destroy(handleData->personalities); STRING_delete(handleData->IoTHubName); STRING_delete(handleData->IoTHubSuffix); free(handleData); } } static bool lookup_DeviceName(const void* element, const void* value) { return (strcmp(STRING_c_str((*(PERSONALITY_PTR*)element)->deviceName), value) == 0); } static IOTHUBMESSAGE_DISPOSITION_RESULT IotHub_ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE msg, void* userContextCallback) { IOTHUBMESSAGE_DISPOSITION_RESULT result; if (userContextCallback == NULL) { /*Codes_SRS_IOTHUBMODULE_17_005: [ If `userContextCallback` is `NULL`, then `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_ABANDONED`. ]*/ LogError("No context to associate message"); result = IOTHUBMESSAGE_ABANDONED; } else { PERSONALITY_PTR personality = (PERSONALITY_PTR)userContextCallback; IOTHUBMESSAGE_CONTENT_TYPE msgContentType = IoTHubMessage_GetContentType(msg); if (msgContentType == IOTHUBMESSAGE_UNKNOWN) { /*Codes_SRS_IOTHUBMODULE_17_006: [ If Message Content type is `IOTHUBMESSAGE_UNKNOWN`, then `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_ABANDONED`. ]*/ LogError("Message content type is unknown"); result = IOTHUBMESSAGE_ABANDONED; } else { /* Handle message content */ MESSAGE_CONFIG newMessageConfig; IOTHUB_MESSAGE_RESULT msgResult; if (msgContentType == IOTHUBMESSAGE_STRING) { /*Codes_SRS_IOTHUBMODULE_17_014: [ If Message content type is `IOTHUBMESSAGE_STRING`, `IotHub_ReceiveMessageCallback` shall get the buffer from results of `IoTHubMessage_GetString`. ]*/ const char* sourceStr = IoTHubMessage_GetString(msg); newMessageConfig.source = (const unsigned char*)sourceStr; /*Codes_SRS_IOTHUBMODULE_17_015: [ If Message content type is `IOTHUBMESSAGE_STRING`, `IotHub_ReceiveMessageCallback` shall get the buffer size from the string length. ]*/ newMessageConfig.size = strlen(sourceStr); msgResult = IOTHUB_MESSAGE_OK; } else { /* content type is byte array */ /*Codes_SRS_IOTHUBMODULE_17_013: [ If Message content type is `IOTHUBMESSAGE_BYTEARRAY`, `IotHub_ReceiveMessageCallback` shall get the size and buffer from the results of `IoTHubMessage_GetByteArray`. ]*/ msgResult = IoTHubMessage_GetByteArray(msg, &(newMessageConfig.source), &(newMessageConfig.size)); } if (msgResult != IOTHUB_MESSAGE_OK) { /*Codes_SRS_IOTHUBMODULE_17_023: [ If `IoTHubMessage_GetByteArray` fails, `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_ABANDONED`. ]*/ LogError("Failed to get message content"); result = IOTHUBMESSAGE_ABANDONED; } else { /* Now, handle message properties. */ MAP_HANDLE newProperties; /*Codes_SRS_IOTHUBMODULE_17_007: [ `IotHub_ReceiveMessageCallback` shall get properties from message by calling `IoTHubMessage_Properties`. ]*/ newProperties = IoTHubMessage_Properties(msg); if (newProperties == NULL) { /*Codes_SRS_IOTHUBMODULE_17_008: [ If message properties are `NULL`, `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_ABANDONED`. ]*/ LogError("No Properties in IoTHub Message"); result = IOTHUBMESSAGE_ABANDONED; } else { /*Codes_SRS_IOTHUBMODULE_17_009: [ `IotHub_ReceiveMessageCallback` shall define a property "source" as "iothub". ]*/ /*Codes_SRS_IOTHUBMODULE_17_010: [ `IotHub_ReceiveMessageCallback` shall define a property "deviceName" as the `PERSONALITY`'s deviceName. ]*/ /*Codes_SRS_IOTHUBMODULE_17_011: [ `IotHub_ReceiveMessageCallback` shall combine message properties with the "source" and "deviceName" properties. ]*/ if (Map_Add(newProperties, GW_SOURCE_PROPERTY, GW_IOTHUB_MODULE) != MAP_OK) { /*Codes_SRS_IOTHUBMODULE_17_022: [ If message properties fail to combine, `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_ABANDONED`. ]*/ LogError("Property [%s] did not add properly", GW_SOURCE_PROPERTY); result = IOTHUBMESSAGE_ABANDONED; } else if (Map_Add(newProperties, GW_DEVICENAME_PROPERTY, STRING_c_str(personality->deviceName)) != MAP_OK) { /*Codes_SRS_IOTHUBMODULE_17_022: [ If message properties fail to combine, `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_ABANDONED`. ]*/ LogError("Property [%s] did not add properly", GW_DEVICENAME_PROPERTY); result = IOTHUBMESSAGE_ABANDONED; } else { /*Codes_SRS_IOTHUBMODULE_17_016: [ `IotHub_ReceiveMessageCallback` shall create a new message from combined properties, the size and buffer. ]*/ newMessageConfig.sourceProperties = newProperties; MESSAGE_HANDLE gatewayMsg = Message_Create(&newMessageConfig); if (gatewayMsg == NULL) { /*Codes_SRS_IOTHUBMODULE_17_017: [ If the message fails to create, `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_REJECTED`. ]*/ LogError("Failed to create gateway message"); result = IOTHUBMESSAGE_REJECTED; } else { /*Codes_SRS_IOTHUBMODULE_17_018: [ `IotHub_ReceiveMessageCallback` shall call `Broker_Publish` with the new message, this module's handle, and the `broker`. ]*/ if (Broker_Publish(personality->broker, personality->module, gatewayMsg) != BROKER_OK) { /*Codes_SRS_IOTHUBMODULE_17_019: [ If the message fails to publish, `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_REJECTED`. ]*/ LogError("Failed to publish gateway message"); result = IOTHUBMESSAGE_REJECTED; } else { /*Codes_SRS_IOTHUBMODULE_17_021: [ Upon success, `IotHub_ReceiveMessageCallback` shall return `IOTHUBMESSAGE_ACCEPTED`. ]*/ result = IOTHUBMESSAGE_ACCEPTED; } /*Codes_SRS_IOTHUBMODULE_17_020: [ `IotHub_ReceiveMessageCallback` shall destroy all resources it creates. ]*/ Message_Destroy(gatewayMsg); } } } } } } return result; } /*returns non-null if PERSONALITY has been properly populated*/ static PERSONALITY_PTR PERSONALITY_create(const char* deviceName, const char* deviceKey, IOTHUB_HANDLE_DATA* moduleHandleData) { PERSONALITY_PTR result = (PERSONALITY_PTR)malloc(sizeof(PERSONALITY)); if (result == NULL) { LogError("unable to allocate a personality for the device %s", deviceName); } else { if ((result->deviceName = STRING_construct(deviceName)) == NULL) { LogError("unable to STRING_construct"); free(result); result = NULL; } else if ((result->deviceKey = STRING_construct(deviceKey)) == NULL) { LogError("unable to STRING_construct"); STRING_delete(result->deviceName); free(result); result = NULL; } else { IOTHUB_CLIENT_CONFIG temp; temp.protocol = moduleHandleData->transportProvider; temp.deviceId = deviceName; temp.deviceKey = deviceKey; temp.deviceSasToken = NULL; temp.iotHubName = STRING_c_str(moduleHandleData->IoTHubName); temp.iotHubSuffix = STRING_c_str(moduleHandleData->IoTHubSuffix); temp.protocolGatewayHostName = NULL; /*Codes_SRS_IOTHUBMODULE_05_002: [ If a new personality is created and the module's transport has already been created (in `IotHub_Create`), an `IOTHUB_CLIENT_HANDLE` will be added to the personality by a call to `IoTHubClient_CreateWithTransport`. ]*/ /*Codes_SRS_IOTHUBMODULE_05_003: [ If a new personality is created and the module's transport has not already been created, an `IOTHUB_CLIENT_HANDLE` will be added to the personality by a call to `IoTHubClient_Create` with the corresponding transport provider. ]*/ result->iothubHandle = (moduleHandleData->transportHandle != NULL) ? IoTHubClient_CreateWithTransport(moduleHandleData->transportHandle, &temp) : IoTHubClient_Create(&temp); if (result->iothubHandle == NULL) { LogError("unable to create IoTHubClient"); STRING_delete(result->deviceName); STRING_delete(result->deviceKey); free(result); result = NULL; } else { /*Codes_SRS_IOTHUBMODULE_17_003: [ If a new personality is created, then the associated IoTHubClient will be set to receive messages by calling `IoTHubClient_SetMessageCallback` with callback function `IotHub_ReceiveMessageCallback`, and the personality as context. ]*/ if (IoTHubClient_SetMessageCallback(result->iothubHandle, IotHub_ReceiveMessageCallback, result) != IOTHUB_CLIENT_OK) { LogError("unable to IoTHubClient_SetMessageCallback"); IoTHubClient_Destroy(result->iothubHandle); STRING_delete(result->deviceName); STRING_delete(result->deviceKey); free(result); result = NULL; } else { /*it is all fine*/ result->broker = moduleHandleData->broker; result->module = moduleHandleData; } } } } return result; } static void PERSONALITY_destroy(PERSONALITY* personality) { STRING_delete(personality->deviceName); STRING_delete(personality->deviceKey); IoTHubClient_Destroy(personality->iothubHandle); } static PERSONALITY* PERSONALITY_find_or_create(IOTHUB_HANDLE_DATA* moduleHandleData, const char* deviceName, const char* deviceKey) { /*Codes_SRS_IOTHUBMODULE_02_017: [ Otherwise `IotHub_Receive` shall not create a new personality. ]*/ PERSONALITY* result; PERSONALITY_PTR* resultPtr = VECTOR_find_if(moduleHandleData->personalities, lookup_DeviceName, deviceName); if (resultPtr == NULL) { /*a new device has arrived!*/ PERSONALITY_PTR personality; if ((personality = PERSONALITY_create(deviceName, deviceKey, moduleHandleData)) == NULL) { LogError("unable to create a personality for the device %s", deviceName); result = NULL; } else { if ((VECTOR_push_back(moduleHandleData->personalities, &personality, 1)) != 0) { /*Codes_SRS_IOTHUBMODULE_02_016: [ If adding a new personality to the vector fails, then `IoTHub_Receive` shall return. ]*/ LogError("VECTOR_push_back failed"); PERSONALITY_destroy(personality); free(personality); result = NULL; } else { resultPtr = VECTOR_back(moduleHandleData->personalities); result = *resultPtr; } } } else { result = *resultPtr; } return result; } static IOTHUB_MESSAGE_HANDLE IoTHubMessage_CreateFromGWMessage(MESSAGE_HANDLE message) { IOTHUB_MESSAGE_HANDLE result; const CONSTBUFFER* content = Message_GetContent(message); /*Codes_SRS_IOTHUBMODULE_02_019: [ If creating the IOTHUB_MESSAGE_HANDLE fails, then `IotHub_Receive` shall return. ]*/ result = IoTHubMessage_CreateFromByteArray(content->buffer, content->size); if (result == NULL) { LogError("IoTHubMessage_CreateFromByteArray failed"); /*return as is*/ } else { MAP_HANDLE iothubMessageProperties = IoTHubMessage_Properties(result); CONSTMAP_HANDLE gwMessageProperties = Message_GetProperties(message); const char* const* keys; const char* const* values; size_t nProperties; if (ConstMap_GetInternals(gwMessageProperties, &keys, &values, &nProperties) != CONSTMAP_OK) { /*Codes_SRS_IOTHUBMODULE_02_019: [ If creating the IOTHUB_MESSAGE_HANDLE fails, then `IotHub_Receive` shall return. ]*/ LogError("unable to get properties of the GW message"); IoTHubMessage_Destroy(result); result = NULL; } else { size_t i; for (i = 0; i < nProperties; i++) { /*add all the properties of the GW message to the IOTHUB message*/ /*with the exception*/ /*Codes_SRS_IOTHUBMODULE_02_018: [ `IotHub_Receive` shall create a new IOTHUB_MESSAGE_HANDLE having the same content as `messageHandle`, and the same properties with the exception of `deviceName` and `deviceKey`. ]*/ if ( (strcmp(keys[i], "deviceName") != 0) && (strcmp(keys[i], "deviceKey") != 0) ) { if (Map_AddOrUpdate(iothubMessageProperties, keys[i], values[i]) != MAP_OK) { /*Codes_SRS_IOTHUBMODULE_02_019: [ If creating the IOTHUB_MESSAGE_HANDLE fails, then `IotHub_Receive` shall return. ]*/ LogError("unable to Map_AddOrUpdate"); break; } } } if (i == nProperties) { /*all is fine, return as is*/ } else { /*Codes_SRS_IOTHUBMODULE_02_019: [ If creating the IOTHUB_MESSAGE_HANDLE fails, then `IotHub_Receive` shall return. ]*/ IoTHubMessage_Destroy(result); result = NULL; } } ConstMap_Destroy(gwMessageProperties); } return result; } static void IotHub_Receive(MODULE_HANDLE moduleHandle, MESSAGE_HANDLE messageHandle) { /*Codes_SRS_IOTHUBMODULE_02_009: [ If `moduleHandle` or `messageHandle` is `NULL` then `IotHub_Receive` shall do nothing. ]*/ if ( (moduleHandle == NULL) || (messageHandle == NULL) ) { LogError("invalid arg moduleHandle=%p, messageHandle=%p", moduleHandle, messageHandle); /*do nothing*/ } else { CONSTMAP_HANDLE properties = Message_GetProperties(messageHandle); const char* source = ConstMap_GetValue(properties, SOURCE); /*properties is !=NULL by contract of Message*/ /*Codes_SRS_IOTHUBMODULE_02_010: [ If message properties do not contain a property called "source" having the value set to "mapping" then `IotHub_Receive` shall do nothing. ]*/ if ( (source == NULL) || (strcmp(source, MAPPING)!=0) ) { /*do nothing, the properties do not contain either "source" or "source":"mapping"*/ } else { /*Codes_SRS_IOTHUBMODULE_02_011: [ If message properties do not contain a property called "deviceName" having a non-`NULL` value then `IotHub_Receive` shall do nothing. ]*/ const char* deviceName = ConstMap_GetValue(properties, DEVICENAME); if (deviceName == NULL) { /*do nothing, not a message for this module*/ } else { /*Codes_SRS_IOTHUBMODULE_02_012: [ If message properties do not contain a property called "deviceKey" having a non-`NULL` value then `IotHub_Receive` shall do nothing. ]*/ const char* deviceKey = ConstMap_GetValue(properties, DEVICEKEY); if (deviceKey == NULL) { /*do nothing, missing device key*/ } else { IOTHUB_HANDLE_DATA* moduleHandleData = moduleHandle; /*Codes_SRS_IOTHUBMODULE_02_013: [ If no personality exists with a device ID equal to the value of the `deviceName` property of the message, then `IotHub_Receive` shall create a new `PERSONALITY` with the ID and key values from the message. ]*/ PERSONALITY* whereIsIt = PERSONALITY_find_or_create(moduleHandleData, deviceName, deviceKey); if (whereIsIt == NULL) { /*Codes_SRS_IOTHUBMODULE_02_014: [ If creating the personality fails then `IotHub_Receive` shall return. ]*/ /*do nothing, device was not added to the GW*/ LogError("unable to PERSONALITY_find_or_create"); } else { IOTHUB_MESSAGE_HANDLE iotHubMessage = IoTHubMessage_CreateFromGWMessage(messageHandle); if(iotHubMessage == NULL) { LogError("unable to IoTHubMessage_CreateFromGWMessage (internal)"); } else { /*Codes_SRS_IOTHUBMODULE_02_020: [ `IotHub_Receive` shall call IoTHubClient_SendEventAsync passing the IOTHUB_MESSAGE_HANDLE. ]*/ if (IoTHubClient_SendEventAsync(whereIsIt->iothubHandle, iotHubMessage, NULL, NULL) != IOTHUB_CLIENT_OK) { /*Codes_SRS_IOTHUBMODULE_02_021: [ If `IoTHubClient_SendEventAsync` fails then `IotHub_Receive` shall return. ]*/ LogError("unable to IoTHubClient_SendEventAsync"); } else { /*all is fine, message has been accepted for delivery*/ } IoTHubMessage_Destroy(iotHubMessage); } } } } } ConstMap_Destroy(properties); } /*Codes_SRS_IOTHUBMODULE_02_022: [ If `IoTHubClient_SendEventAsync` succeeds then `IotHub_Receive` shall return. ]*/ } static const MODULE_API_1 moduleInterface = { {MODULE_API_VERSION_1}, IotHub_CreateFromJson, IotHub_Create, IotHub_Destroy, IotHub_Receive, NULL }; /*Codes_SRS_IOTHUBMODULE_26_001: [ `Module_GetApi` shall return a pointer to a `MODULE_API` structure with the required function pointers. ]*/ #ifdef BUILD_MODULE_TYPE_STATIC MODULE_EXPORT const MODULE_API* MODULE_STATIC_GETAPI(IOTHUB_MODULE)(const MODULE_API_VERSION gateway_api_version) #else MODULE_EXPORT const MODULE_API* Module_GetApi(const MODULE_API_VERSION gateway_api_version) #endif { (void)gateway_api_version; return (const MODULE_API *)&moduleInterface; }
{ "content_hash": "89d4ca4ed5852fb138be979d93de8d30", "timestamp": "", "source": "github", "line_count": 690, "max_line_length": 285, "avg_line_length": 46.72463768115942, "alnum_prop": 0.5700062034739454, "repo_name": "yaweiw/azure-iot-gateway-sdk", "id": "ee97e835cfa303248557a1065a62de13348b6cf0", "size": "32240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/iothub/src/iothub.c", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1483" }, { "name": "C", "bytes": "1435321" }, { "name": "C#", "bytes": "118865" }, { "name": "C++", "bytes": "1874229" }, { "name": "CMake", "bytes": "58382" }, { "name": "Java", "bytes": "29470" }, { "name": "Objective-C", "bytes": "1121" }, { "name": "Shell", "bytes": "1248" } ], "symlink_target": "" }
<?php namespace Nelmio\Alice\Instances\Instantiator\DummyClasses; class DummyWithExplicitDefaultConstructor { public function __construct() { } }
{ "content_hash": "e203523be167ae79358cbca51f2ffd64", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 59, "avg_line_length": 13.5, "alnum_prop": 0.7345679012345679, "repo_name": "rainlike/justshop", "id": "fbf243d468820e95251d704a9517c318f1cdb570", "size": "377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/nelmio/alice/tests/Nelmio/Alice/Instances/Instantiator/DummyClasses/DummyWithExplicitDefaultConstructor.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1153" }, { "name": "CSS", "bytes": "821" }, { "name": "HTML", "bytes": "17134" }, { "name": "JavaScript", "bytes": "1135" }, { "name": "PHP", "bytes": "110346" }, { "name": "Shell", "bytes": "400" } ], "symlink_target": "" }
using System; using Premotion.Mansion.Core.Scripting.ExpressionScript; namespace Premotion.Mansion.Core.ScriptFunctions.Date { /// <summary> /// Returns the /// </summary> [ScriptFunction("DateDiff")] public class DateDiff : FunctionExpression { /// <summary> /// </summary> /// <param name="context"></param> /// <returns></returns> /// <param name="one"></param> /// <param name="other"></param> public TimeSpan Evaluate(IMansionContext context, DateTime one, DateTime other) { // validate arguments if (context == null) throw new ArgumentNullException("context"); if (one == DateTime.MinValue) return TimeSpan.MinValue; if (other == DateTime.MinValue) return TimeSpan.MinValue; return one - other; } } }
{ "content_hash": "0c1ee8df2a302661d6d0c714073381e3", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 81, "avg_line_length": 24.580645161290324, "alnum_prop": 0.6732283464566929, "repo_name": "devatwork/Premotion-Mansion", "id": "6e922f9ccb38f35d3c6b5e4e34a4b78db2eace84", "size": "764", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Premotion.Mansion.Core/ScriptFunctions/Date/DateDiff.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "768" }, { "name": "Batchfile", "bytes": "3262" }, { "name": "C#", "bytes": "2762697" }, { "name": "CSS", "bytes": "158664" }, { "name": "HTML", "bytes": "61257" }, { "name": "JavaScript", "bytes": "1100387" }, { "name": "PHP", "bytes": "20246" }, { "name": "Pascal", "bytes": "3805" }, { "name": "Smarty", "bytes": "52063" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60-ea) on Tue Aug 16 17:15:34 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.jgroups.stack.transport.DefaultThreadPool (Public javadocs 2016.8.1 API)</title> <meta name="date" content="2016-08-16"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.config.jgroups.stack.transport.DefaultThreadPool (Public javadocs 2016.8.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2016.8.1</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/jgroups/stack/transport/class-use/DefaultThreadPool.html" target="_top">Frames</a></li> <li><a href="DefaultThreadPool.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.jgroups.stack.transport.DefaultThreadPool" class="title">Uses of Class<br>org.wildfly.swarm.config.jgroups.stack.transport.DefaultThreadPool</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.jgroups.stack">org.wildfly.swarm.config.jgroups.stack</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.jgroups.stack.transport">org.wildfly.swarm.config.jgroups.stack.transport</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.jgroups.stack"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a> in <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/package-summary.html">org.wildfly.swarm.config.jgroups.stack</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/package-summary.html">org.wildfly.swarm.config.jgroups.stack</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a></code></td> <td class="colLast"><span class="typeNameLabel">Transport.TransportResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/Transport.TransportResources.html#defaultThreadPool--">defaultThreadPool</a></span>()</code> <div class="block">A thread pool executor</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/package-summary.html">org.wildfly.swarm.config.jgroups.stack</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/Transport.html" title="type parameter in Transport">T</a></code></td> <td class="colLast"><span class="typeNameLabel">Transport.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/Transport.html#defaultThreadPool-org.wildfly.swarm.config.jgroups.stack.transport.DefaultThreadPool-">defaultThreadPool</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a>&nbsp;value)</code> <div class="block">A thread pool executor</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.wildfly.swarm.config.jgroups.stack.transport"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a> in <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/package-summary.html">org.wildfly.swarm.config.jgroups.stack.transport</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/package-summary.html">org.wildfly.swarm.config.jgroups.stack.transport</a> with type parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a>&lt;T&gt;&gt;</span></code> <div class="block">A thread pool executor</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPoolConsumer.html" title="interface in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPoolConsumer</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a>&lt;T&gt;&gt;</span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPoolSupplier.html" title="interface in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPoolSupplier</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a>&gt;</span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/package-summary.html">org.wildfly.swarm.config.jgroups.stack.transport</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">DefaultThreadPool</a></code></td> <td class="colLast"><span class="typeNameLabel">DefaultThreadPoolSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPoolSupplier.html#get--">get</a></span>()</code> <div class="block">Constructed instance of DefaultThreadPool resource</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../org/wildfly/swarm/config/jgroups/stack/transport/DefaultThreadPool.html" title="class in org.wildfly.swarm.config.jgroups.stack.transport">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2016.8.1</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/jgroups/stack/transport/class-use/DefaultThreadPool.html" target="_top">Frames</a></li> <li><a href="DefaultThreadPool.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "0f3940a2412de81d294413111f8a6c1e", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 515, "avg_line_length": 59.38793103448276, "alnum_prop": 0.6692553345913775, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "e4cbbfe84b3a4fae548f9cb4152b837bbd3f3424", "size": "13778", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2016.8.1/apidocs/org/wildfly/swarm/config/jgroups/stack/transport/class-use/DefaultThreadPool.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#pragma once #ifndef _TEST_HTTP_H_ #define _TEST_HTTP_H_ #include <iostream> #include <vector> #include <map> #include <set> #include <list> #include <deque> #include <queue> #include <typeinfo> #include "../proto4z.h" using namespace std; using namespace zsummer::proto4z; const int MAX_HTTP_LEN = 1000; class TestHTTP { public: bool Test(WriteHTTP &wh) { HTTPHeadMap head; std::string body; unsigned int usedLen = 0; if (CheckHTTPBuffIntegrity(wh.GetStream(), wh.GetStreamLen(), 1024, head, body, usedLen) == IRT_SUCCESS) { if (head.find("Host") != head.end() && ( head.find("GET") != head.end() || head.find("POST") != head.end() || head.find("RESPONSE") != head.end())) { cout << "Check CheckHTTPBuffIntegrity Success" << endl; } else { cout << "Check CheckHTTPBuffIntegrity Data error" << endl; return false; } } else { cout << "Check CheckHTTPBuffIntegrity unpack error. ret =" << (IRT_SHORTAGE ? "IRT_SHORTAGE":"IRT_CORRUPTION") << endl; return false; } if (CheckHTTPBuffIntegrity(wh.GetStream(), wh.GetStreamLen()-1, 1024, head, body, usedLen) != IRT_SHORTAGE) { cout << "Check CheckHTTPBuffIntegrity IRT_SHORTAGE error" << endl; return false; } if (CheckHTTPBuffIntegrity(wh.GetStream(), wh.GetStreamLen(), wh.GetStreamLen() - 1, head, body, usedLen) != IRT_CORRUPTION) { cout << "Check CheckHTTPBuffIntegrity IRT_CORRUPTION error" << endl; return false; } return true; } protected: private: }; #endif
{ "content_hash": "9036a2c3f5dc864785c090078f7f259d", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 126, "avg_line_length": 22.441176470588236, "alnum_prop": 0.6507208387942333, "repo_name": "darongE/zsummerX", "id": "5fac830a25147ef466404624084e26b0dc1d7920", "size": "1528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "depends/proto4z/test/TestHTTP.h", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#ifndef EDDA_CURVILINEAR_GRID_H #define EDDA_CURVILINEAR_GRID_H #include "grid.h" #include <vector> namespace edda{ #define DIR_I 0 #define DIR_J 1 #define DIR_K 2 #if 0 ////////////// This CellTopoType is used in OSUFlow. In OSUFlow CVertex is defined in Grid.h. can be placed at another file for more organized code //////////////// // define the cell type enum CellTopoType { T0_CELL, // vertex T1_CELL, // edge T2_CELL, // triangle, quarilateral T3_CELL, // tetrahedra, cube T4_CELL // hetrahedra, added by lijie }; #endif typedef struct { int dir; int tetra; int face; } Tetra_step; #define CELL_TETRAHEDRON 1 #define CELL_HEXAHEDRON 2 typedef struct { int type; VECTOR3 ijk; int subid; } Cell; /* phys_to_cell | ---| | locate | | | ---locate_close_vertex_cell | | | | | ---adaptive_vertex_cell_walk | | | ---tetrahedral_walk_locate | | | ---hexahedral_walk_locate | | ----phys_to_comp_coords */ class EDDA_EXPORT CurvilinearGrid : public CartesianGrid { private: VECTOR3 xyz_o, xyz_r, xyz_s, xyz_t, xyz_rs, xyz_rt, xyz_st, xyz_rst; VECTOR3* initial_location; VECTOR3* m_pVertex; bool left_handed_cells; public: CurvilinearGrid(int xdim, int ydim, int zdim); CurvilinearGrid(int* dim, VECTOR3* pVertexGeom); //from OSUFlow. maybe can delete CurvilinearGrid(int* dim, float* point_ary); CurvilinearGrid(); ~CurvilinearGrid(); void Reset(); // physical coordinate of vertex verIdx ReturnStatus at_vertex(int verIdx, VECTOR3& pos); // whether the physical point is on the boundary bool at_phys(VECTOR3& pos); // get vertex list of a cell ReturnStatus getCellVertices(int cellId, std::vector<size_t>& vVertices); // get the cell id and also interpolating coefficients for the given physical position ReturnStatus phys_to_cell(PointInfo& pInfo); // the volume of cell double cellVolume(int cellId); // cell type CellType getCellType() { return CUBE; } // set bounding box void setBoundary(VECTOR3& minB, VECTOR3& maxB); void setRealBoundary(VECTOR4& minB, VECTOR4& maxB); // get min and maximal boundary void boundary(VECTOR3& minB, VECTOR3& maxB); bool isInBBox(VECTOR3& pos); bool isInRealBBox(VECTOR3& pos); bool isInRealBBox(VECTOR3& pos, float t); void computeBBox(); // boundary intersection void boundaryIntersection(VECTOR3&, VECTOR3&, VECTOR3&, float*, float){};//not implemented in OSUFlow. will do in the future // whether in a cell bool isInCell(PointInfo& pInfo, const int cellId){ return true; };//the implementation in OSUFlow is not correct. will do in the future // get grid spacing in x,y,z dimensions void getGridSpacing(int cellId, float& xspace, float& yspace, float& zspace) { xspace = 0; yspace = 0; zspace = 0; };//grid spacing is not meaningful for curvilinear grid. need this function to override the abstract method in the parent classes int get_ijk_of_vertex(int vertexId, VECTOR3& ijk); int get_ijk_of_cell(int cellId, VECTOR3& ijk); /**********************************/ //re-implemented functions int central_difference_neighbors(VECTOR3& vc, int dir); //interpolate int phys_to_comp_coords(const VECTOR3 p, double& r, double& s, double& t); // int get_ijk_of_vertex(int vertexId, VECTOR3& ijk); int init_jacobian_vectors(VECTOR3* dp); // int jacobian_at_vertex(VECTOR3, MATRIX3*);//not used // int jacobian_at_vertex_id(int verIdx, MATRIX3& jacobian);//not used //int inverse_jacobian(MATRIX3& mi, double r, double s, double t); int inverse_jacobian_t(MATRIX3& mi, double r, double s, double t); //point location void locate_initialization(); int locate_close_vertex_cell(VECTOR3 pp, VECTOR3& vc); int adaptive_vertex_cell_walk(VECTOR3& pp, VECTOR3& start_v, VECTOR3* v); int tetrahedral_walk_locate(VECTOR3, Cell, Cell&); int hexahedral_walk_locate(VECTOR3, Cell, Cell&); ReturnStatus locate(VECTOR3, Cell&); ReturnStatus locate(VECTOR3 pp, Cell& prev_cell, Cell& cell); // int locate(VECTOR3&, VECTOR3&, VECTOR3*) const; //auxiliary int coordinates_at_cell(VECTOR3 cell, VECTOR3* v);//return 8 velocity value int coordinates_at_vertex(VECTOR3 pos, VECTOR3* v); //return 1 velocity value int walk_on_x_boundary(VECTOR3 pp, int plane_pos, float& min_d2, VECTOR3& min_v); int walk_on_y_boundary(VECTOR3 pp, int plane_pos, float& min_d2, VECTOR3& min_v); int walk_on_z_boundary(VECTOR3 pp, int plane_pos, float& min_d2, VECTOR3& min_v); int simplicial_decomposition_odd(VECTOR3& ijk); int up_cells(VECTOR3 input_ijk, Cell& cell, int decompose = 1); static const int hexa_face[2][6][4]; static const int subtetra_vertex[10][4]; static const int subtetra_face[10][4][3]; static const int quadrilateral_vertex[3][4]; static const int subtriangle_vertex[20][3]; static const int edge_vertex[21][2]; static const Tetra_step tetra_step[10][4]; int n_initial_locations; }; #define FEL_DIR_0 0 #define FEL_DIR_NEG_I 1 #define FEL_DIR_POS_I 2 #define FEL_DIR_NEG_J 3 #define FEL_DIR_POS_J 4 #define FEL_DIR_NEG_K 5 #define FEL_DIR_POS_K 6 #define FEL_DIR_I 7 #define FEL_DIR_J 8 #define FEL_DIR_K 9 // The canonical vertex numbering for a structured hexahedron. // The vertex indices in the tables below are in terms of this // hexahedron numbering. // // 6________7 // /| /| ^ // / | / | | // 4/_______5/ | k // | 2|___ |___|3 // | / | / ^ // | / | / / // |/_______|/ j // 0 1 // i -> } #endif
{ "content_hash": "c1d96ff6605403ba9183c260f1efb0e4", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 165, "avg_line_length": 29.73821989528796, "alnum_prop": 0.6566901408450704, "repo_name": "GRAVITYLab/edda", "id": "50c3943f7b4963f684d4429cfb562a143db19ef3", "size": "5680", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/dataset/curvilinear_grid.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "41880" }, { "name": "C++", "bytes": "3350154" }, { "name": "CMake", "bytes": "19449" }, { "name": "CSS", "bytes": "30865" }, { "name": "Cuda", "bytes": "6886" }, { "name": "HTML", "bytes": "6354910" }, { "name": "JavaScript", "bytes": "90574" }, { "name": "Python", "bytes": "6388" } ], "symlink_target": "" }
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Algorithms { public static class Sha512Tests { private const string s_hashOfEmpty = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; #region Properties [Fact] public static void Properties() { var a = new Sha512(); Assert.Equal(32, Sha512.MinHashSize); Assert.Equal(64, Sha512.MaxHashSize); Assert.Equal(64, a.HashSize); Assert.Equal(32, HashAlgorithm.Sha512_256.HashSize); Assert.Equal(64, HashAlgorithm.Sha512.HashSize); } #endregion #region Hash #1 [Fact] public static void HashEmpty() { var a = HashAlgorithm.Sha512; var expected = s_hashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan<byte>.Empty); Assert.Equal(a.HashSize, actual.Length); Assert.Equal(expected, actual); } #endregion #region Hash #3 [Fact] public static void HashEmptyWithSpan() { var a = HashAlgorithm.Sha512; var expected = s_hashOfEmpty.DecodeHex(); var actual = new byte[expected.Length]; a.Hash(ReadOnlySpan<byte>.Empty, actual); Assert.Equal(expected, actual); } #endregion } }
{ "content_hash": "7e14cb9512eaa6e71f8c10b499410829", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 176, "avg_line_length": 24.096774193548388, "alnum_prop": 0.5917001338688086, "repo_name": "ektrah/nsec", "id": "9a5414e14b37f87dc19936d2f982a1bed1b42372", "size": "1494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Algorithms/Sha512Tests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "808333" } ], "symlink_target": "" }
package org.apache.vxquery.runtime.functions.node; import org.apache.vxquery.runtime.functions.base.AbstractTaggedValueArgumentScalarEvaluatorFactory; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator; import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory; import org.apache.hyracks.api.context.IHyracksTaskContext; public class OpNodeBeforeEvaluatorFactory extends AbstractTaggedValueArgumentScalarEvaluatorFactory { private static final long serialVersionUID = 1L; public OpNodeBeforeEvaluatorFactory(IScalarEvaluatorFactory[] args) { super(args); } @Override protected IScalarEvaluator createEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) throws AlgebricksException { return new OpNodeBeforeEvaluator(args); } }
{ "content_hash": "1570d45bc21dce231e47734e0a508ebd", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 101, "avg_line_length": 34.69230769230769, "alnum_prop": 0.8104212860310421, "repo_name": "sjaco002/vxquery", "id": "0205a50d280bf18000674b68023fd8ee732501c1", "size": "1703", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/node/OpNodeBeforeEvaluatorFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2806058" }, { "name": "Python", "bytes": "120934" }, { "name": "Shell", "bytes": "39923" }, { "name": "XQuery", "bytes": "464264" }, { "name": "XSLT", "bytes": "17897" } ], "symlink_target": "" }
package etcd import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "strings" "time" "github.com/m3db/m3cluster/client" etcdclient "github.com/m3db/m3cluster/client/etcd" "github.com/m3db/m3cluster/services" xclock "github.com/m3db/m3x/clock" "github.com/m3db/m3x/errors" "github.com/coreos/etcd/embed" ) type embeddedKV struct { etcd *embed.Etcd opts Options dir string } // New creates a new EmbeddedKV func New(opts Options) (EmbeddedKV, error) { dir, err := ioutil.TempDir("", opts.Dir()) if err != nil { return nil, err } cfg := embed.NewConfig() cfg.Dir = dir e, err := embed.StartEtcd(cfg) if err != nil { return nil, fmt.Errorf("unable to start etcd, err: %v", err) } return &embeddedKV{ etcd: e, opts: opts, dir: dir, }, nil } func (e *embeddedKV) Close() error { var multi errors.MultiError // see if there's any errors select { case err := <-e.etcd.Err(): multi = multi.Add(err) default: } // shutdown and release e.etcd.Server.Stop() e.etcd.Close() multi = multi.Add(os.RemoveAll(e.dir)) return multi.FinalError() } func (e *embeddedKV) Start() error { timeout := e.opts.InitTimeout() select { case <-e.etcd.Server.ReadyNotify(): break case <-time.After(timeout): return fmt.Errorf("etcd server took too long to start") } // ensure v3 api endpoints are available, https://github.com/coreos/etcd/pull/7075 apiVersionEndpoint := fmt.Sprintf("%s/version", embed.DefaultListenClientURLs) fn := func() bool { return version3Available(apiVersionEndpoint) } ok := xclock.WaitUntil(fn, timeout) if !ok { return fmt.Errorf("api version 3 not available") } return nil } type versionResponse struct { Version string `json:"etcdcluster"` } func version3Available(endpoint string) bool { resp, err := http.Get(endpoint) if err != nil { return false } if resp.StatusCode != 200 { return false } defer resp.Body.Close() decoder := json.NewDecoder(resp.Body) var data versionResponse err = decoder.Decode(&data) if err != nil { return false } return strings.Index(data.Version, "3.") == 0 } func (e *embeddedKV) Endpoints() []string { addresses := make([]string, 0, len(e.etcd.Clients)) for _, c := range e.etcd.Clients { addresses = append(addresses, c.Addr().String()) } return addresses } func (e *embeddedKV) ConfigServiceClient(fns ...ClientOptFn) (client.Client, error) { eopts := etcdclient.NewOptions(). SetInstrumentOptions(e.opts.InstrumentOptions()). SetServicesOptions(services.NewOptions().SetInitTimeout(e.opts.InitTimeout())). SetClusters([]etcdclient.Cluster{ etcdclient.NewCluster().SetZone(e.opts.Zone()).SetEndpoints(e.Endpoints()), }). SetService(e.opts.ServiceID()). SetEnv(e.opts.Environment()). SetZone(e.opts.Zone()) for _, fn := range fns { eopts = fn(eopts) } return etcdclient.NewConfigServiceClient(eopts) }
{ "content_hash": "1055c7d04f318b6260b4c31442b3cd8d", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 85, "avg_line_length": 22.084615384615386, "alnum_prop": 0.6913967258794845, "repo_name": "m3db/m3cluster", "id": "0ab5189f6f6a0b20850bbc51e02c35154266c5a8", "size": "3993", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integration/etcd/etcd.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1110931" }, { "name": "Makefile", "bytes": "3474" }, { "name": "Shell", "bytes": "548" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_72) on Wed Nov 05 20:55:56 EST 2014 --> <title>Uses of Class org.apache.cassandra.thrift.Cassandra.system_update_column_family_result._Fields (apache-cassandra API)</title> <meta name="date" content="2014-11-05"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.cassandra.thrift.Cassandra.system_update_column_family_result._Fields (apache-cassandra API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.system_update_column_family_result._Fields.html" target="_top">Frames</a></li> <li><a href="Cassandra.system_update_column_family_result._Fields.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.cassandra.thrift.Cassandra.system_update_column_family_result._Fields" class="title">Uses of Class<br>org.apache.cassandra.thrift.Cassandra.system_update_column_family_result._Fields</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.cassandra.thrift">org.apache.cassandra.thrift</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.cassandra.thrift"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a> in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a> with type parameters of type <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static java.util.Map&lt;<a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a>,org.apache.thrift.meta_data.FieldMetaData&gt;</code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result.html#metaDataMap">metaDataMap</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a> that return <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result.html#fieldForId(int)">fieldForId</a></strong>(int&nbsp;fieldId)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html#findByName(java.lang.String)">findByName</a></strong>(java.lang.String&nbsp;name)</code> <div class="block">Find the _Fields constant that matches name, or null if its not found.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html#findByThriftId(int)">findByThriftId</a></strong>(int&nbsp;fieldId)</code> <div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html#findByThriftIdOrThrow(int)">findByThriftIdOrThrow</a></strong>(int&nbsp;fieldId)</code> <div class="block">Find the _Fields constant that matches fieldId, throwing an exception if it is not found.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a>[]</code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result._Fields.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html#values()">values</a></strong>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/apache/cassandra/thrift/package-summary.html">org.apache.cassandra.thrift</a> with parameters of type <a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>java.lang.Object</code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result.html#getFieldValue(org.apache.cassandra.thrift.Cassandra.system_update_column_family_result._Fields)">getFieldValue</a></strong>(<a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a>&nbsp;field)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result.html#isSet(org.apache.cassandra.thrift.Cassandra.system_update_column_family_result._Fields)">isSet</a></strong>(<a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a>&nbsp;field)</code> <div class="block">Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">Cassandra.system_update_column_family_result.</span><code><strong><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result.html#setFieldValue(org.apache.cassandra.thrift.Cassandra.system_update_column_family_result._Fields,%20java.lang.Object)">setFieldValue</a></strong>(<a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.system_update_column_family_result._Fields</a>&nbsp;field, java.lang.Object&nbsp;value)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/cassandra/thrift/Cassandra.system_update_column_family_result._Fields.html" title="enum in org.apache.cassandra.thrift">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/cassandra/thrift/class-use/Cassandra.system_update_column_family_result._Fields.html" target="_top">Frames</a></li> <li><a href="Cassandra.system_update_column_family_result._Fields.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2014 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "9291c1acd32f2c318703507eae5711ad", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 576, "avg_line_length": 65.41777777777777, "alnum_prop": 0.6959032542971669, "repo_name": "anuragkapur/cassandra-2.1.2-ak-skynet", "id": "cc1fd536c3f1162f64b821442c6a6253a2f740c8", "size": "14719", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apache-cassandra-2.1.2/javadoc/org/apache/cassandra/thrift/class-use/Cassandra.system_update_column_family_result._Fields.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "59670" }, { "name": "PowerShell", "bytes": "37758" }, { "name": "Python", "bytes": "622552" }, { "name": "Shell", "bytes": "100474" }, { "name": "Thrift", "bytes": "78926" } ], "symlink_target": "" }
<?php namespace Ems\Core; use Closure; use Ems\Contracts\Core\Stringable; use Ems\Contracts\Core\StringableTrait; use Ems\Contracts\Core\Type; use Ems\Core\Exceptions\KeyNotFoundException; use Ems\Core\Exceptions\UnsupportedParameterException; use LogicException; use ReflectionException; use ReflectionFunction; use ReflectionFunctionAbstract; use ReflectionMethod; use UnexpectedValueException; use function array_merge; use function call_user_func; use function class_exists; use function explode; use function func_get_args; use function function_exists; use function is_array; use function is_callable; use function is_object; use function is_string; use function method_exists; use function spl_object_hash; use function strpos; /** * This class is a helper class to allow inline evaluation of * parameters in dynamic calls like Container::call * * It also allows you to add additional parameters to your * callable which you don't know when registering them. * * The best way to understand how it is used look into its unit test. **/ class Lambda implements Stringable { use StringableTrait; /** * @var string|array|callable **/ protected $call; /** * @var callable */ protected $callable; /** * @var string */ protected $callClass; /** * @var object */ protected $callInstance = false; /** * @var string */ protected $callMethod; /** * @var bool */ protected $isStaticMethod; /** * @var bool */ protected $isFunction; /** * @var bool */ protected $isClosure; /** * @var callable */ protected $instanceResolver; /** * @var array **/ protected $additionalArgs = []; /** * @var array **/ protected $injections = []; /** * @var array */ protected $bindings = []; /** * @var bool */ protected $autoInject = false; /** * @var bool */ protected $wasAutoInjected = false; /** * @var array **/ protected static $reflectionCache = []; /** * @var array */ protected static $methodSeparators = ['::', '->', '@']; /** * Create a new Lambda object. Pass something what can be parsed by this * class. To resolve classes from class based calls inject a callable to * resolve this classes. (An IOCContainer or something similar) * * @param array|string|callable $call * @param callable $instanceResolver (optional) * @param bool $autoInject (default:false) * * @throws ReflectionException */ public function __construct($call, callable $instanceResolver=null, $autoInject=false) { if ($call instanceof self) { throw new UnexpectedValueException("You cannot make a lambda to forward a lambda."); } $this->call = $call; $this->instanceResolver = $instanceResolver; $this->autoInject($autoInject); } /** * Run the lambda code * * @return mixed * * @throws ReflectionException **/ public function __invoke() { $callable = $this->getCallable(); if ($this->autoInject) { return static::callFast([$this, 'trigger'], func_get_args()); } if ($this->injections) { return static::callNamed($callable, $this->injections, func_get_args()); } $args = array_merge(func_get_args(), $this->additionalArgs); return static::call($callable, $args); } /** * Same as __invoke but prefer to insert the passed arguments at positions * were no (auto) injected arguments are. * * @see self::mergeArguments() * * @return mixed * * @throws ReflectionException */ public function trigger() { $callable = $this->getCallable(); $args = array_merge(func_get_args(), $this->additionalArgs); if ($this->autoInject && !$this->wasAutoInjected) { $this->performAutoInjection(); } if (!$this->injections) { return static::call($callable, $args); } $allArgs = Lambda::mergeArguments($callable, $this->injections, $args); return static::callFast($callable, $allArgs); } /** * Append some parameters to the passed parameters. They will be injected * when the assigned callable is called. * Append parameters may also contain Lambdas. * * @param mixed $parameters * * @return self **/ public function append($parameters) { $this->additionalArgs = is_array($parameters) ? $parameters : func_get_args(); return $this; } /** * Same as append, but replace all callable values with lambdas. * * @param mixed $parameters * * @return self * * @throws ReflectionException * * @see self::append() * */ public function curry($parameters) { $parameters = is_array($parameters) ? $parameters : func_get_args(); return $this->append(static::currify($parameters)); } /** * Assign an associative array with a value for each parameter of the callable. * The parameters will then be passed to it. (And merged with the normal ones) * * @param array $injections * * @return self **/ public function inject(array $injections) { $this->injections = $injections; return $this; } /** * @return array */ public function getInjections() { return $this->injections; } /** * This method does allow to skip resolving a type by the assigned factory. * It forces to use the assigned object to be passed to the callable. * * @param string $abstract an interface or class name. * @param object $instance The actual instance (not closure or factory) * * @return $this */ public function bind($abstract, $instance) { $this->bindings[$abstract] = $instance; return $this; } /** * Auto inject the parameters. If false is passed disable the auto * injection. If $now is true perform the type resolution now and write it * into the $injections array. * * @param bool $autoInject (default:true) * @param bool $now (default:false) * * @return $this * * @throws ReflectionException */ public function autoInject($autoInject=true, $now=false) { $this->autoInject = $autoInject; if (!$this->autoInject) { return $this; } if (!$this->instanceResolver) { throw new LogicException('You have to assign a instance resolver to support auto injection'); } if ($now) { $this->performAutoInjection(); } return $this; } /** * Return true if the parameters should be automatically injected. * * @return bool */ public function shouldAutoInject() { return $this->autoInject; } /** * Get the class of the callable. (if there is one) * * @return string * * @throws ReflectionException */ public function getCallClass() { if ($this->callClass === null) { $this->parseCall(); } return $this->callClass; } /** * Get the method|function of the callable (if there is one) * * @return string * * @throws ReflectionException */ public function getCallMethod() { if ($this->callMethod === null) { $this->parseCall(); } return $this->callMethod; } /** * @return null|object * * @throws ReflectionException */ public function getCallInstance() { if ($this->callInstance !== false) { return $this->callInstance; } if (is_array($this->call) && isset($this->call[0]) && is_object($this->call[0])) { $this->callInstance = $this->call[0]; return $this->callInstance; } if (is_object($this->call) && method_exists($this->call, '__invoke')){ $this->callInstance = $this->call; return $this->callInstance; } if ($this->isFunction() || $this->isStaticMethod()) { $this->callInstance = null; return $this->callInstance; } $this->callInstance = $this->resolveCallInstance($this->getCallClass()); return $this->callInstance; } /** * Return true if the callable is an instance method. This is true if the * there is a class and the method is not static. Also true on __invoke. * * @return bool * * @throws ReflectionException */ public function isInstanceMethod() { return $this->getCallClass() && !$this->isClosure() && !$this->isStaticMethod(); } /** * Return true if the callable is a method call and the reflection says it * is static. * * @return bool * * @throws ReflectionException */ public function isStaticMethod() { if ($this->isStaticMethod === null) { $this->parseCall(); } return $this->isStaticMethod; } /** * Return true if the callable is just a plain function. * * @return bool * * @throws ReflectionException */ public function isFunction() { if ($this->isFunction === null) { $this->parseCall(); } return $this->isFunction; } /** * Return true if the callable is a Closure. * * @return bool * * @throws ReflectionException */ public function isClosure() { if ($this->isClosure === null) { $this->parseCall(); } return $this->isClosure; } /** * Return the factory to create instances of class names. * * @return callable|null */ public function getInstanceResolver() { return $this->instanceResolver; } /** * Set the factory that makes the instance out of a class name. * * @param callable $instanceResolver * * @return Lambda */ public function setInstanceResolver(callable $instanceResolver) { $this->instanceResolver = $instanceResolver; return $this; } /** * {@inheritdoc} * * This is used to serialize and deserialize the callable of a lambda. * It will complain if it is not possible to serialize it. * Filled arguments are not concerned! * * @return string * * @throws LogicException * @throws ReflectionException **/ public function toString() { if ($this->isClosure()) { throw new LogicException('You cannot serialize a closure.'); } if ($this->isFunction()) { return $this->getCallMethod(); } $separator = $this->isStaticMethod() ? '::' : '->'; return $this->getCallClass() . $separator . $this->getCallMethod(); } /** * Just call a callable without parsing any lambdas * * @param callable $callable * @param mixed $args (optional) * * @return mixed **/ public static function callFast(callable $callable, $args=null) { return call_user_func($callable, ...(array)$args); } /** * Call a callable and parse its lambdas * * @param callable $callable * @param mixed $args (optional) * * @return mixed **/ public static function call(callable $callable, $args=null) { if (!is_array($args)) { $args = $args === null ? [] : [$args]; } return static::callFast($callable, static::evaluateArgs($args)); } /** * Calls the passed callable with an array of named parameter * ($parameterName=>$value). * If you want to pass original parameters to overwrite the injected ones * pass them as the third parameter. * * @see self::toArguments() * * @param callable $callable * @param array $inject * @param array $callArgs (optional) * * @return array * * @throws ReflectionException **/ public static function callNamed(callable $callable, array $inject, array $callArgs=[]) { return static::call($callable, static::toArguments($callable, $inject, $callArgs)); } /** * Calls the passed callable with an array of named parameter * ($parameterName=>$value). * If you want to pass additional parameters which gets inserted in every * position where an inject key is missing, pass them as the third parameter. * * @see self::mergeArguments() * * @param callable $callable * @param array $inject * @param array $callArgs (optional) * * @return array * * @throws ReflectionException **/ public static function callMerged(callable $callable, array $inject, array $callArgs=[]) { return static::call($callable, static::mergeArguments($callable, $inject, $callArgs)); } /** * Run all Lambdas in arguments anf return the "parsed" * * @param array * * @return array **/ public static function evaluateArgs(array $args) { $parsedArgs = []; foreach ($args as $key=>$value) { if ($value instanceof self) { $parsedArgs[$key] = static::callFast($value); continue; } $parsedArgs[$key] = $args[$key]; } return $parsedArgs; } /** * Replace all callable values in an array with lambdas * * @param array $args * * @return array * * @throws ReflectionException */ public static function currify(array $args) { $curried = []; foreach ($args as $key=>$value) { if (is_callable($value)) { $curried[$key] = new static($value); continue; } $curried[$key] = $value; } return $curried; } /** * Static constructor for shorter instance creation * * @param string|array|callable $callable * @param callable $instanceResolver (optional) * * @return self * * @throws ReflectionException */ public static function f($callable, callable $instanceResolver=null) { return new static($callable, $instanceResolver); } /** * Return an array of argument information about $callable. * The array is indexed by the name and every value is an array * containing information about if its optional and which type * it should have.The callable typehint is removed to support * protected methods. * * @param callable|array $callable * * @return array * * @throws ReflectionException **/ public static function reflect($callable) { $cacheId = static::cacheId($callable); if ($reflectArray = static::getFromCache($cacheId)) { return $reflectArray; } $parameters = []; foreach(static::getReflection($callable)->getParameters() as $parameter) { $type = null; if ($classReflection = $parameter->getClass()) { $type = $classReflection->getName(); } $parameters[$parameter->getName()] = [ 'optional' => $parameter->isOptional(), 'type' => $type ]; } return static::putIntoCacheAndReturn($cacheId, $parameters); } /** * Reads all parameter names from the callable and builds an parameter array * you can use to call the callable. * The second parameter is an associative array with data for each parameter. * The third parameter is what you "normally" would pass to the callable. * (A numeric array containing parameters) * The numeric parameters do overwrite the assoc one. The callable * typehint is removed to support protected methods. * * @param callable|array $callable * @param array $inject * @param array $callArgs (optional) * * @return array * * @throws ReflectionException **/ public static function toArguments($callable, array $inject, array $callArgs=[]) { $i = -1; $arguments = []; foreach(static::reflect($callable) as $name=>$data) { $i++; // isset() does not work with null, so it would not be possible to // overwrite values with null, so instead use array_key_exists if (array_key_exists($i, $callArgs)) { $arguments[$i] = $callArgs[$i]; continue; } if (array_key_exists($name, $inject)) { $arguments[$i] = $inject[$name]; continue; } if (!$data['optional']) { $cacheId = static::cacheId($callable); throw new KeyNotFoundException("The parameter $name is required by '$cacheId'. Pass it via inject or the normal parameters."); } } return $arguments; } /** * Same as self::toArguments. But instead of overwriting the $inject * parameters with the callArgs they are inserted on any position where * a injected value is missing. * The typehint is removed to support protected methods. * * You can pass an assoc array as the first parameter instead of a callable * to pass already built reflected parameters. * * @param callable|array $callable * @param array $inject * @param array $callArgs (optional) * * @return array * * @throws ReflectionException **/ public static function mergeArguments($callable, array $inject, array $callArgs=[]) { $arguments = []; $reflection = is_array($callable) && !isset($callable[0]) ? $callable : static::reflect($callable); foreach ($reflection as $paramName=>$methodData) { if (isset($inject[$paramName])) { $arguments[] = $inject[$paramName]; continue; } $arguments[] = array_shift($callArgs); } return $arguments; } /** * This method builds the arguments to call a method with its dependencies. * You have to built the array with static::reflect($callable) to call this * method. * Pass the third argument to force a distinct object to be used for a * type. For example [CacheInterface::class => $myCustomCache] would lead to * not asking the instance resolver and using $myCustomCache. * * @param array $reflectedArgs * @param callable $instanceResolver (optional) * @param array $customBindings (optional) * * @return array */ public static function buildHintedArguments(array $reflectedArgs, callable $instanceResolver=null, $customBindings=[]) { $args = []; $instanceResolver = $instanceResolver ?: function ($class) { return new $class(); }; foreach ($reflectedArgs as $name=>$info) { if (!$info['type']) { continue; } if (!Type::isCustom($info['type'])) { continue; } if (isset($customBindings[$info['type']])) { $args[$name] = $customBindings[$info['type']]; continue; } $args[$name] = $instanceResolver($info['type']); } return $args; } /** * Return all method separators. These are used to split class * and method out of a string. * * @return array */ public static function methodSeparators() { return static::$methodSeparators; } /** * Add another supported method separator. * * @param string $separator */ public static function addMethodSeparator($separator) { static::$methodSeparators[] = $separator; } /** * Get the real callable to pass it to call_user_func. * * @return callable * * @throws ReflectionException */ public function getCallable() { if (!$this->callable) { $this->callable = $this->makeCallable(); } return $this->callable; } /** * Return a cache id for the passed callable * * @param callable|array $callable * * @return string * * @throws ReflectionException **/ public static function cacheId($callable) { if (is_array($callable)) { $class = is_string($callable[0]) ? $callable[0] : get_class($callable[0]); return "$class::" . $callable[1]; } if (is_string($callable)) { return $callable; } if (!$callable instanceof Closure) { return get_class($callable); } $r = new ReflectionFunction($callable); return 'Closure:' . $r->getFileName() . ':' . $r->getStartLine() . ':' . $r->getEndLine(); } /** * This is a small helper to ensure a listener is called only once. So as an * example in $app->onAfter() instead of this: * * $app->onAfter(Repository::class, function (Repository $repository) { * $repository->configure(); * }); * * You can write: * $app->onAfter(Repository::class, Lambda::once(function (Repository $repository) { * $repository->configure(); * })); * * @param callable $call * @return Closure */ public static function once(callable $call) : Closure { $received = []; return function (...$args) use ($call, &$received) { $hash = spl_object_hash($args[0]); if (isset($received[$hash])) { return; } $received[$hash] = true; $call(...$args); }; } /** * Make the (eventually not) callable base arg of this class callable. * * @return callable * * @throws ReflectionException */ protected function makeCallable() { if ($this->call instanceof Closure || $this->isFunction()) { return $this->call; } if ($this->isStaticMethod()) { return [$this->getCallClass(), $this->getCallMethod()]; } return [$this->getCallInstance(), $this->getCallMethod()]; } /** * Parse the call to make it callable and know a few things about it. * * @throws ReflectionException * @throws LogicException */ protected function parseCall() { if ($this->call instanceof Closure) { $this->callClass = Closure::class; $this->callMethod = ''; $this->isStaticMethod = false; $this->isFunction = false; $this->isClosure = true; return; } list($class, $method) = $this->toClassAndMethod($this->call); if ($class === '') { $this->callClass = ''; $this->callMethod = $method; $this->isStaticMethod = false; $this->isFunction = true; $this->isClosure = false; return; } $this->callClass = $class; $this->callMethod = $method; $this->isFunction = false; $this->isClosure = false; $reflection = new ReflectionMethod($class, $method); $this->isStaticMethod = $reflection->isStatic(); if (!$reflection->isPublic()) { throw new LogicException("Method '$method' of $class is not public and therefore not callable."); } return; } /** * @param string|array $call * * @return array */ protected function toClassAndMethod($call) { if (is_array($call)) { return is_object($call[0]) ? [get_class($call[0]), $call[1]] : $call; } if (is_object($call) && method_exists($call, '__invoke')) { return [get_class($call), '__invoke']; } if (function_exists($call)) { return ['', $call]; } if (class_exists($call) && method_exists($call, '__invoke')) { return [$call, '__invoke']; } if($separator = static::findMethodSeparator($call)) { return static::listClassAndMethod($call, $separator); } throw new UnsupportedParameterException("Cannot parse '$call'."); } /** * Resolve the class of a callable. * * @param string $class * * @return object */ protected function resolveCallInstance($class) { if (!$this->instanceResolver) { return new $class(); } return call_user_func($this->instanceResolver, $class); } /** * Automatically calculate the injections * * @throws ReflectionException */ protected function performAutoInjection() { if ($this->wasAutoInjected) { return; } $argumentTypes = static::reflect($this->getCallable()); $injections = Lambda::buildHintedArguments($argumentTypes, $this->instanceResolver, $this->bindings); $this->inject($injections); $this->wasAutoInjected = true; } /** * Try to load a reflection from cache. * * @param string $cacheId * * @return mixed **/ protected static function getFromCache($cacheId) { return isset(static::$reflectionCache[$cacheId]) ? static::$reflectionCache[$cacheId] : null; } /** * Store the reflected information about $cacheId and return it * * @param string $cacheId * @param array $reflection * * @return array **/ protected static function putIntoCacheAndReturn($cacheId, array $reflection) { static::$reflectionCache[$cacheId] = $reflection; return $reflection; } /** * Get a reflection object for the passed callable. The callable * typehint is removed to support protected methods. * * @param callable|array $callable * * @return ReflectionFunctionAbstract * * @throws ReflectionException **/ protected static function getReflection($callable) { if (is_array($callable)) { return new ReflectionMethod($callable[0], $callable[1]); } if ($callable instanceof Closure) { return new ReflectionFunction($callable); } if (is_object($callable)) { return new ReflectionMethod($callable, '__invoke'); } // Should be a string until here if ($separator = static::findMethodSeparator($callable)) { list($class, $method) = explode($separator, $callable); return new ReflectionMethod($class, $method); } return new ReflectionFunction($callable); } /** * Find the used method separator in $methodString * * @param string $methodString * * @return string */ protected static function findMethodSeparator($methodString) { foreach (static::$methodSeparators as $separator) { if (strpos($methodString, $separator)) { return $separator; } } return ''; } /** * Return the class and method in 2 array values. If you don't know the * separator let it guess it. * * @param string $methodString * @param string $separator (optional) * * @return array */ protected static function listClassAndMethod($methodString, $separator='') { $separator = $separator ?: static::findMethodSeparator($methodString); return explode($separator, $methodString, 2); } }
{ "content_hash": "abe30b41a874cbace42b2dd8a230c9dc", "timestamp": "", "source": "github", "line_count": 1098, "max_line_length": 142, "avg_line_length": 25.729508196721312, "alnum_prop": 0.5609358960744752, "repo_name": "mtils/php-ems", "id": "20f7f15719bdff4dc70d0394dcd1f3f967f6d8c9", "size": "28251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Ems/Core/Lambda.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "4490502" }, { "name": "Shell", "bytes": "1138" } ], "symlink_target": "" }
<h1>Characters</h1> <ul> <li *ngFor="let character of characters">{{character}}</li> </ul>
{ "content_hash": "cbb177a5c6b285f752b7d5cf68efc06e", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 63, "avg_line_length": 24, "alnum_prop": 0.625, "repo_name": "sgbj/generator-aspnetcore-angular2", "id": "389dd5f22bde4ec1a2264cdaa44ee3f9ce4c4827", "size": "98", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generators/app/templates/advanced/src/WebApp/wwwroot/src/app/characters/character-list.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "10267" }, { "name": "CSS", "bytes": "580" }, { "name": "HTML", "bytes": "2817" }, { "name": "JavaScript", "bytes": "16630" }, { "name": "TypeScript", "bytes": "10177" } ], "symlink_target": "" }
using Should; namespace SpecEasy.Specs.ExceptionReporting.SupportingExamples { [SupportingExample] internal class BrokenClassSpec : Spec<BrokenClass> { private bool input; private bool result; public void RunSpec() { When("inverting a boolean value", () => result = SUT.InvertThatThrowsArgumentOutOfRangeException(input)); Given("a false input", () => input = false).Verify(() => Then("the result is true", () => result.ShouldBeTrue())); Given("a true input", () => input = true).Verify(() => Then("the result is false", () => result.ShouldBeFalse())); } } }
{ "content_hash": "b08870841cb63842762cfd19dc4fed43", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 117, "avg_line_length": 31.181818181818183, "alnum_prop": 0.5830903790087464, "repo_name": "trackabout/speceasy", "id": "c3b403ee370b12305bcb26ad40fb0a758d0c5720", "size": "686", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "SpecEasy.Specs/ExceptionReporting/SupportingExamples/BrokenClassSpec.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "325" }, { "name": "C#", "bytes": "224930" } ], "symlink_target": "" }
import { Component, OnInit } from "@angular/core"; import { FormBuilder, FormGroup, Validators } from "@angular/forms"; import { Router } from "@angular/router"; import { TableletService } from "../../service"; import { API } from "../../http"; const compareDates = (startDateKey: string, endDateKey: string) => { return (group: FormGroup): { [key: string]: any } => { let startDate = group.controls[startDateKey]; let endDate = group.controls[endDateKey]; if (null === startDate.value || null === endDate.value) { return {}; } if (new Date(startDate.value).getTime() > new Date(endDate.value).getTime()) { return { compared: true }; } } } @Component({ selector: 'diary-newpage', templateUrl: './newpage.component.html', styleUrls: ['./newpage.component.css'] }) export class NewPageComponent implements OnInit { titleFocused: boolean; startDateFocused: boolean; endDateFocused: boolean; typeFocused: boolean; locationFocused: boolean; relatedFocused: boolean; pageModel: any = { 'DiaryPageType': '学习' }; relations: Array<string> = []; contents: Array<any> = [{ 'text': "" }]; pageForm: FormGroup; pageDateError: string; relatedError: string; contentsError: string; pageFormErrors = { 'DiaryPageTitle': '', 'DiaryPageStartDate': '', 'DiaryPageEndDate': '', 'DiaryPageType': '', 'DiaryPageLocation': '' }; pageFormValidationMessages = { 'pageDateError': { 'compared': '开始日期应该早于结束日期.' }, 'relatedError': { 'maxLength': '相关人过多,请进行删减后再保存.' }, 'contentsError': { 'required': '内容是必填项.', 'maxLength': '内容过长,请进行删减后再保存.' }, 'DiaryPageTitle': { 'required': '标题是必填项.', 'minlength': '标题最短1个字符.', 'maxlength': '标题最长255个字符.', }, 'DiaryPageStartDate': { 'required': '开始日期是必填项.' }, 'DiaryPageEndDate': { 'required': '结束日期是必填项.' }, 'DiaryPageType': { 'required': '类型是必填项.' }, 'DiaryPageLocation': { 'required': '地点是必填项.', 'minlength': '地点最短1个字符.', 'maxlength': '地点最长255个字符.', } }; constructor(private fb: FormBuilder, private router: Router, private tablelet: TableletService) { } ngOnInit() { let datum = this.tablelet.getHandlingData(TableletService.PAGEs); if (datum) { this.pageModel = Object.assign(datum, { DiaryPageStartDate: datum.DiaryPageStartDate.substring(0, 10), DiaryPageEndDate: datum.DiaryPageEndDate.substring(0, 10) }); this.relations = datum.DiaryPageRelated.split('|').filter(r => !!r); this.contents = datum.DiaryPageContent.split('</p><p>').filter(c => !!c).map(text => ({ text })); } this.buildPageForm(); } buildPageForm(): void { this.pageForm = this.fb.group({ 'DiaryPageTitle': [this.pageModel.DiaryPageTitle, [ Validators.required, Validators.minLength(1), Validators.maxLength(255) ]], 'DiaryPageStartDate': [this.pageModel.DiaryPageStartDate, [ Validators.required ]], 'DiaryPageEndDate': [this.pageModel.DiaryPageEndDate, [ Validators.required ]], 'DiaryPageLocation': [this.pageModel.DiaryPageLocation, [ Validators.required, Validators.minLength(1), Validators.maxLength(255) ]], 'DiaryPageType': [this.pageModel.DiaryPageType, [ Validators.required ]] }, { validator: compareDates('DiaryPageStartDate', 'DiaryPageEndDate') }); this.pageForm.valueChanges .subscribe(data => this.onValueChanged(this.pageForm, this.pageFormErrors, this.pageFormValidationMessages)); this.onValueChanged(this.pageForm, this.pageFormErrors, this.pageFormValidationMessages); // (re)set validation messages now } onValueChanged(form: FormGroup, formErrors: any, validationMessages: any, show?: boolean) { if (!form) { return; } this.pageDateError = ''; if ((show || form.dirty) && !form.valid) { for (const key in form.errors) { this.pageDateError += this.pageFormValidationMessages['pageDateError'][key] + ' '; } } for (const field in formErrors) { // clear previous error message (if any) formErrors[field] = ''; const control = form.get(field); if (control && (show || control.dirty) && !control.valid) { const messages = validationMessages[field]; for (const key in control.errors) { formErrors[field] += messages[key] + ' '; } } } } addRelated(e) { if (!e.target.value) { return; } if (e.target.value.indexOf('|') !== -1) { alert('含有非法字符"|"'); return; } this.relations.push(e.target.value.trim()); e.target.value = ''; let filteredRelations = []; this.relations.forEach(related => { if (!filteredRelations.some(fR => fR === related)) { filteredRelations.push(related); } }); this.relations = filteredRelations; } removeRelated(toRemove) { this.relations = this.relations.filter(related => related !== toRemove); } addInputBlock(e, i) { this.contents = [...this.contents.slice(0, i + 1), { text: "" }, ...this.contents.slice(i + 1, this.contents.length)]; } removeInputBlock(e, i) { this.contents = [...this.contents.slice(0, i), ...this.contents.slice(i + 1, this.contents.length)]; } savePage() { console.log(this.pageForm); if (!this.pageForm.valid) { this.onValueChanged(this.pageForm, this.pageFormErrors, this.pageFormValidationMessages, true); return; } let DiaryPageRelated = this.validRelations(); console.log(DiaryPageRelated); if (false === DiaryPageRelated) { return; } let DiaryPageContent = this.validContents(); console.log(DiaryPageContent); if (!DiaryPageContent) { return; } const self = this; this.tablelet.addDataByAPI(TableletService.PAGEs, API.getAPI("page/save"), Object.assign(this.pageForm.value, { DiaryPageId: self.pageModel.DiaryPageId, DiaryPageContent, DiaryPageRelated, DiaryPageStartDate: this.pageForm.value.DiaryPageStartDate + ' 00:00:00', DiaryPageEndDate: this.pageForm.value.DiaryPageEndDate + ' 00:00:00' }), this.tablelet.getHandlingIdx(TableletService.PAGEs), () => { self.router.navigate(['/page']); }); } private validContents() { let wholeContent = this.contents.reduce((pv, cv, ci, array) => { if (ci !== array.length - 1) { return pv + cv.text.trim() + '</p><p>'; } return pv + cv.text.trim(); }, ''); this.contentsError = ''; if (wholeContent.length > 102400) { this.contentsError += this.pageFormValidationMessages.contentsError.maxLength; return false; } if (wholeContent.length === 0) { this.contentsError += this.pageFormValidationMessages.contentsError.required; return false; } return wholeContent; } private validRelations() { let related = this.relations.join("|"); this.relatedError = ''; if (related.length > 255) { this.relatedError += this.pageFormValidationMessages.relatedError.maxLength; return false; } return related; } }
{ "content_hash": "95c1dd0715d85c636d5cfab3a3904efe", "timestamp": "", "source": "github", "line_count": 256, "max_line_length": 128, "avg_line_length": 28.42578125, "alnum_prop": 0.6231963721313728, "repo_name": "CaoYouXin/serveV2", "id": "ce453201eda3bde1eba4835de98aa7113f1d6ed9", "size": "7511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/diaryConsole/src/diary/newpage/newpage.component.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "50686" }, { "name": "HTML", "bytes": "73174" }, { "name": "Java", "bytes": "496023" }, { "name": "JavaScript", "bytes": "12070" }, { "name": "Shell", "bytes": "1422" }, { "name": "TypeScript", "bytes": "289481" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:adjustViewBounds="false" android:focusable="true" android:scaleType="centerCrop" android:background="@drawable/guidebg_8" /> <com.hanchu.lufthansa.typetextview.TypeTextView android:id="@+id/typeTx_8" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="400dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:textColor="#14b356" android:textSize="18sp" /> <ImageView android:id="@+id/g7_next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="40dp" android:src="@drawable/tutorial_next" /> </RelativeLayout>
{ "content_hash": "40e2c502218f1211c99a2c6b70e5cfda", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 74, "avg_line_length": 36.82857142857143, "alnum_prop": 0.682699767261443, "repo_name": "tigline/lufthansa", "id": "d706c97fe29f3553a743094635e1856e7185dc16", "size": "1289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/layout/guide_eight.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "180182" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TilandisGUI.Properties { /// <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()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TilandisGUI.Properties.Resources", typeof(Resources).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)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
{ "content_hash": "cf355e10463eddd354d4182d001529b8", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 177, "avg_line_length": 43.53225806451613, "alnum_prop": 0.6209707298999629, "repo_name": "lavacano201014/tilandis", "id": "f929dbeff93efac57eb960249f23dbbaf2d5692b", "size": "2701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TilandisGUI/Properties/Resources.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "27021" }, { "name": "C++", "bytes": "445146" } ], "symlink_target": "" }
class EventBase(object): """ The base of all event classes. A Ryu application can define its own event type by creating a subclass. """ def __init__(self): super(EventBase, self).__init__() class EventRequestBase(EventBase): """ The base class for synchronous request for RyuApp.send_request. """ def __init__(self): super(EventRequestBase, self).__init__() self.dst = None # app.name of provide the event. self.src = None self.sync = False self.reply_q = None class EventReplyBase(EventBase): """ The base class for synchronous request reply for RyuApp.send_reply. """ def __init__(self, dst): super(EventReplyBase, self).__init__() self.dst = dst
{ "content_hash": "799fe28d151d8bd93e98e1104200b6fb", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 75, "avg_line_length": 24.1875, "alnum_prop": 0.6020671834625323, "repo_name": "fujita/ryu", "id": "3f5c3dbf85f0fcbeebde13d7e944356267771d78", "size": "1452", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ryu/controller/event.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "28540" }, { "name": "CSS", "bytes": "306" }, { "name": "Erlang", "bytes": "874721" }, { "name": "Gnuplot", "bytes": "1094" }, { "name": "HTML", "bytes": "306" }, { "name": "JavaScript", "bytes": "8436" }, { "name": "Makefile", "bytes": "88" }, { "name": "Python", "bytes": "6135247" }, { "name": "Shell", "bytes": "17573" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec upgrade-insecure-requests/` --> <html> <head> <meta charset="utf-8"> <meta name="timeout" content="long"> <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/security-features/resources/common.sub.js"></script> <script src="../../../generic/test-case.sub.js"></script> </head> <body> <script> TestCase( [ { "expectation": "allowed", "origin": "cross-http-downgrade", "redirection": "downgrade", "source_context_list": [ { "policyDeliveries": [], "sourceContextType": "iframe-blank" } ], "source_scheme": "https", "subresource": "iframe-tag", "subresource_policy_deliveries": [], "test_description": "Upgrade-Insecure-Requests: Expects allowed for iframe-tag to cross-http-downgrade origin and downgrade redirection from https context." }, { "expectation": "allowed", "origin": "cross-http-downgrade", "redirection": "no-redirect", "source_context_list": [ { "policyDeliveries": [], "sourceContextType": "iframe-blank" } ], "source_scheme": "https", "subresource": "iframe-tag", "subresource_policy_deliveries": [], "test_description": "Upgrade-Insecure-Requests: Expects allowed for iframe-tag to cross-http-downgrade origin and no-redirect redirection from https context." }, { "expectation": "allowed", "origin": "cross-https", "redirection": "downgrade", "source_context_list": [ { "policyDeliveries": [], "sourceContextType": "iframe-blank" } ], "source_scheme": "https", "subresource": "iframe-tag", "subresource_policy_deliveries": [], "test_description": "Upgrade-Insecure-Requests: Expects allowed for iframe-tag to cross-https origin and downgrade redirection from https context." }, { "expectation": "allowed", "origin": "same-http-downgrade", "redirection": "downgrade", "source_context_list": [ { "policyDeliveries": [], "sourceContextType": "iframe-blank" } ], "source_scheme": "https", "subresource": "iframe-tag", "subresource_policy_deliveries": [], "test_description": "Upgrade-Insecure-Requests: Expects allowed for iframe-tag to same-http-downgrade origin and downgrade redirection from https context." }, { "expectation": "allowed", "origin": "same-http-downgrade", "redirection": "no-redirect", "source_context_list": [ { "policyDeliveries": [], "sourceContextType": "iframe-blank" } ], "source_scheme": "https", "subresource": "iframe-tag", "subresource_policy_deliveries": [], "test_description": "Upgrade-Insecure-Requests: Expects allowed for iframe-tag to same-http-downgrade origin and no-redirect redirection from https context." }, { "expectation": "allowed", "origin": "same-https", "redirection": "downgrade", "source_context_list": [ { "policyDeliveries": [], "sourceContextType": "iframe-blank" } ], "source_scheme": "https", "subresource": "iframe-tag", "subresource_policy_deliveries": [], "test_description": "Upgrade-Insecure-Requests: Expects allowed for iframe-tag to same-https origin and downgrade redirection from https context." } ], new SanityChecker() ).start(); </script> <div id="log"></div> </body> </html>
{ "content_hash": "12c71dff394c608e38f5dd8ce13e4e17", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 170, "avg_line_length": 39.11504424778761, "alnum_prop": 0.5226244343891403, "repo_name": "ric2b/Vivaldi-browser", "id": "57fec0607ed54cee338fee7e31ce2c8b06655658", "size": "4420", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "chromium/third_party/blink/web_tests/external/wpt/upgrade-insecure-requests/gen/iframe-blank-inherit.meta/upgrade/iframe-tag.https.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package binary_coverage_test import ( "testing" "github.com/bazelbuild/rules_go/go/tools/bazel_testing" ) func TestMain(m *testing.M) { bazel_testing.TestMain(m, bazel_testing.Args{ Main: ` -- BUILD.bazel -- load("@io_bazel_rules_go//go:def.bzl", "go_binary") go_binary( name = "hello", srcs = ["hello.go"], out = "hello", ) -- hello.go -- package main import "fmt" func main() { fmt.Println(A()) } func A() int { return 12 } func B() int { return 34 } `, }) } func Test(t *testing.T) { // Check that we can build a binary with coverage instrumentation enabled. args := []string{ "build", "--collect_code_coverage", "--instrumentation_filter=.*", "//:hello", } if err := bazel_testing.RunBazel(args...); err != nil { t.Fatal(err) } // Check that we can build with `bazel coverage`. It will fail because // there are no tests. args = []string{ "coverage", "//:hello", } if err := bazel_testing.RunBazel(args...); err == nil { t.Fatal("got success; want failure") } else if bErr, ok := err.(*bazel_testing.StderrExitError); !ok { t.Fatalf("got %v; want StderrExitError", err) } else if code := bErr.Err.ExitCode(); code != 4 { t.Fatalf("got code %d; want code 4 (no tests found)", code) } }
{ "content_hash": "44f33b944b13c2c6cf576799611611fe", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 75, "avg_line_length": 20.508196721311474, "alnum_prop": 0.6266986410871302, "repo_name": "bazelbuild/rules_go", "id": "724528be71bb8fbbe84fdd01a3a653699daf9759", "size": "1867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/core/coverage/binary_coverage_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2529" }, { "name": "C", "bytes": "5193" }, { "name": "C++", "bytes": "2348" }, { "name": "Go", "bytes": "623091" }, { "name": "Objective-C", "bytes": "1025" }, { "name": "Objective-C++", "bytes": "408" }, { "name": "Python", "bytes": "20444" }, { "name": "Shell", "bytes": "3421" }, { "name": "Smarty", "bytes": "197" }, { "name": "Starlark", "bytes": "502012" } ], "symlink_target": "" }
package com.vk.api.sdk.queries.friends; import com.vk.api.sdk.queries.EnumParam; /** * Created by Anton Tsivarev on 22.09.16. */ public enum FriendsGetOnlineOrder implements EnumParam { RANDOM("random"), HINTS("hints"); private final String value; FriendsGetOnlineOrder(String value) { this.value = value; } @Override public String getValue() { return value; } }
{ "content_hash": "f12d86c3b133ed6b06af23ad807fff4a", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 56, "avg_line_length": 18.217391304347824, "alnum_prop": 0.6563245823389021, "repo_name": "kokorin/vk-java-sdk", "id": "950970798165bf4695b5d7de0108b7c52084e63e", "size": "419", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "sdk/src/main/java/com/vk/api/sdk/queries/friends/FriendsGetOnlineOrder.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2634022" } ], "symlink_target": "" }
Creates and manages Redis instances on the Google Cloud Platform. This page contains information about getting started with the Google Cloud Memorystore for Redis API using the Google API Client Library for Java. In addition, you may be interested in the following documentation: * Browse the [Javadoc reference for the Google Cloud Memorystore for Redis API][javadoc] * Read the [Developer's Guide for the Google API Client Library for Java][google-api-client]. * Interact with this API in your browser using the [APIs Explorer for the Google Cloud Memorystore for Redis API][api-explorer] ## Installation ### Maven Add the following lines to your `pom.xml` file: ```xml <project> <dependencies> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-redis</artifactId> <version>v1-rev20201110-1.30.10</version> </dependency> </dependencies> </project> ``` ### Gradle ```gradle repositories { mavenCentral() } dependencies { compile 'com.google.apis:google-api-services-redis:v1-rev20201110-1.30.10' } ``` [javadoc]: https://googleapis.dev/java/google-api-services-redis/latest/index.html [google-api-client]: https://github.com/googleapis/google-api-java-client/ [api-explorer]: https://developers.google.com/apis-explorer/#p/redis/v1/
{ "content_hash": "e73ddd93c51ba95a6b664f848b54b309", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 127, "avg_line_length": 31.095238095238095, "alnum_prop": 0.7503828483920367, "repo_name": "googleapis/google-api-java-client-services", "id": "f95eaf4586abcc61e798ff2fefc5912ce7ef39a1", "size": "1372", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "clients/google-api-services-redis/v1/1.30.1/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
export default { baseSrc: './src', baseDist: './static', src: { styles: './src/sass', scripts: './src/blocks', images: './src/images', fonts: './src/fonts' }, dist: { styles: './static/css', scripts: './static/scripts', images: './static/images', fonts: './static/fonts' } };
{ "content_hash": "33ab1dd03680417bf3bbd2036fb4ca99", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 36, "avg_line_length": 20.333333333333332, "alnum_prop": 0.4644808743169399, "repo_name": "dim2k2006/geekon-main", "id": "b13e8624c0dd8edc954606d5f3ae27385bb9c51d", "size": "366", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gulp/settings.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22600" }, { "name": "HTML", "bytes": "19324" }, { "name": "JavaScript", "bytes": "7698" } ], "symlink_target": "" }
package responses import "github.com/etcinit/gonduit/entities" // PHIDQueryResponse is the result of phid.query operations. type PHIDQueryResponse map[string]*entities.PHIDResult
{ "content_hash": "2f13b6b99775160df856d93847d0b458", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 60, "avg_line_length": 30.166666666666668, "alnum_prop": 0.8287292817679558, "repo_name": "etcinit/phabricator-slack-feed", "id": "24d2417244782ea79444d8c1a4215b3da765ef3e", "size": "181", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/github.com/etcinit/gonduit/responses/phid_query.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "26161" }, { "name": "Makefile", "bytes": "119" } ], "symlink_target": "" }
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(false); ui->stealthCB->setEnabled(true); ui->stealthCB->setVisible(true); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); ui->stealthCB->setVisible(false); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(true); ui->stealthCB->setEnabled(false); ui->stealthCB->setVisible(true); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); ui->stealthCB->setVisible(false); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); mapper->addMapping(ui->stealthCB, AddressTableModel::Type); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: { int typeInd = ui->stealthCB->isChecked() ? AddressTableModel::AT_Stealth : AddressTableModel::AT_Normal; address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text(), typeInd); } break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Graviton address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
{ "content_hash": "67be54cc1ff65a8cba6304e99e89148e", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 113, "avg_line_length": 29.113475177304963, "alnum_prop": 0.6133982947624848, "repo_name": "gravitondev/graviton", "id": "810e9f8309abea2882d47c8e9579e0059ea1d570", "size": "4277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/editaddressdialog.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "104261" }, { "name": "C++", "bytes": "4361931" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "11748" }, { "name": "NSIS", "bytes": "6077" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "3517" }, { "name": "Python", "bytes": "54355" }, { "name": "QMake", "bytes": "16023" }, { "name": "Shell", "bytes": "8509" } ], "symlink_target": "" }
using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.ComponentModel; namespace BankApp_V2_MVC { public class Kredyt { public int nr_uzytkownika { get { throw new System.NotImplementedException(); } set { } } public int oprocentowanie { get { throw new System.NotImplementedException(); } set { } } public int rata_miesieczna { get { throw new System.NotImplementedException(); } set { } } public int kwota { get { throw new System.NotImplementedException(); } set { } } public int status_kredytu { get { throw new System.NotImplementedException(); } set { } } public int Kredyt_ID { get { throw new System.NotImplementedException(); } set { } } public void dodajKredyt() { throw new System.NotImplementedException(); } public void usunKredyt() { throw new System.NotImplementedException(); } public void wyswietl() { throw new System.NotImplementedException(); } } }
{ "content_hash": "4a01438dce3ec3f0baa08943f05d63fe", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 59, "avg_line_length": 18.559139784946236, "alnum_prop": 0.39976825028968715, "repo_name": "moradewicz/SuperBank", "id": "6ba608babab4484af51e30dd48e66c8a03bb80d3", "size": "1728", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Kredyt.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "210" }, { "name": "C#", "bytes": "227083" }, { "name": "CSS", "bytes": "1026" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "21428" } ], "symlink_target": "" }
@interface AccountDetailsViewController : UIViewController @property (nonatomic, strong) Account *account; @end
{ "content_hash": "c467f3666bf2a4ea0060f946d5d79d7d", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 58, "avg_line_length": 28.25, "alnum_prop": 0.8230088495575221, "repo_name": "JinlianWang/AdaptiveDesign", "id": "82a3f290998b161e15d2b9ca42631963f0f73569", "size": "322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "POC_AdaptiveDesign/Controllers/AccountDetailsViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "27162" } ], "symlink_target": "" }
import collections from supriya.ugens.PV_MagSquared import PV_MagSquared class PV_MagNoise(PV_MagSquared): """ Multiplies magnitudes by noise. :: >>> pv_chain = supriya.ugens.FFT( ... source=supriya.ugens.WhiteNoise.ar(), ... ) >>> pv_mag_noise = supriya.ugens.PV_MagNoise.new( ... pv_chain=pv_chain, ... ) >>> pv_mag_noise PV_MagNoise.kr() """ ### CLASS VARIABLES ### _ordered_input_names = collections.OrderedDict([("pv_chain", None)])
{ "content_hash": "315b9f1b59e3af61cf70e175c42e6bf7", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 22, "alnum_prop": 0.5527272727272727, "repo_name": "Pulgama/supriya", "id": "ecaa0ca5064dcf587b15d4d42ff500a5eb243506", "size": "550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "supriya/ugens/PV_MagNoise.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6712" }, { "name": "CSS", "bytes": "446" }, { "name": "HTML", "bytes": "1083" }, { "name": "JavaScript", "bytes": "6163" }, { "name": "Makefile", "bytes": "6775" }, { "name": "Python", "bytes": "2790612" }, { "name": "Shell", "bytes": "569" } ], "symlink_target": "" }
from __future__ import division from __future__ import print_function from __future__ import absolute_import from builtins import range from past.builtins import basestring from past.utils import old_div from builtins import object import zipfile import numpy as np import matplotlib.pyplot as plt from osgeo import gdal, gdal_array from osgeo.gdalconst import GA_ReadOnly, GA_Update from girs.geom.envelope import merge_envelopes from . import parameter # ===================== use Python Exceptions ================================= gdal.UseExceptions() # ============================================================================= def driver_dictionary(): """Return the driver dictionary The driver dictionary: - key: source extension - value: driver short name :return: driver dictionary :rtype: dict """ drivers_dict = {} for i in range(gdal.GetDriverCount()): drv = gdal.GetDriver(i) if drv.GetMetadataItem(gdal.DCAP_RASTER): extensions = drv.GetMetadataItem(gdal.DMD_EXTENSIONS) extensions = extensions.split() if extensions else [None] for ext in extensions: if ext: if ext.startswith('.'): ext = ext[1:] ext = ext.lower() for ext1 in [e for e in ext.split('/')]: if ext1 not in drivers_dict: drivers_dict[ext1] = [] drivers_dict[ext1].append(drv.ShortName) else: if None not in drivers_dict: drivers_dict[None] = [] drivers_dict[None].append(drv.ShortName) return drivers_dict def get_driver(filename=None, driver_short_name=None): """Return a driver. If driver_short_name is given, return the corresponding driver. filename can be 'MEM' or a file name. If a file name is given, guess the driver, returning it only when the correspondence is one to one, else return None. Filename suffixes, which should work: ace2: ACE2, asc: AAIGrid, bin: NGSGEOID, blx: BLX, bmp: BMP, bt: BT, cal: CALS, ct1: CALS, dat: ZMap, ddf: SDTS, dem: USGSDEM, dt0: DTED, dt1: DTED, dt2: DTED, e00: E00GRID, gen: ADRG, gff: GFF, grb: GRIB, grc: NWT_GRC, gsb: NTv2, gtx: GTX, gxf: GXF, hdf: HDF4, hdf5: HDF5, hf2: HF2, hgt: SRTMHGT, jpeg: JPEG, jpg: JPEG, kea: KEA, kro: KRO, lcp: LCP, map: PCRaster, mem: JDEM, mpl: ILWIS, n1: ESAT, nat: MSGN, ntf: NITF, pix: PCIDSK, png: PNG, pnm: PNM, ppi: IRIS, rda: R, rgb: SGI, rik: RIK, rst: RST, rsw: RMF, sdat: SAGA, tif: GTiff, tiff: GTiff, toc: RPFTOC, vrt: VRT, xml: ECRGTOC, xpm: XPM, xyz: XYZ, Filenames with ambiguous suffixes: gif: GIF, BIGGIF grd: GSAG, GSBG, GS7BG, NWT_GRD hdr: COASP, MFF, SNODAS img: HFA, SRP nc: GMT, netCDF ter: Leveller, Terragen Without suffix: SAR_CEOS, CEOS, JAXAPALSAR, ELAS, AIG, GRASSASCIIGrid, MEM, BSB, DIMAP, AirSAR, RS2, SAFE, HDF4Image, ISIS3, ISIS2, PDS, VICAR, TIL, ERS, L1B, FIT, INGR, COSAR, TSX, MAP, KMLSUPEROVERLAY, SENTINEL2, MRF, DOQ1, DOQ2, GenBin, PAux, MFF2, FujiBAS, GSC, FAST, LAN, CPG, IDA, NDF, EIR, DIPEx, LOSLAS, CTable2, ROI_PAC, ENVI, EHdr, ISCE, ARG, BAG, HDF5Image, OZI, CTG, DB2ODBC, NUMPY :param filename: :param driver_short_name: :return: """ if driver_short_name: driver = gdal.GetDriverByName(driver_short_name) if not driver: raise ValueError('Could not find driver for short name {}'.format(driver_short_name)) elif not filename: driver = gdal.GetDriverByName('MEM') else: try: driver = gdal.IdentifyDriver(filename) except RuntimeError: driver = None if not driver: drivers_dict = driver_dictionary() try: driver_short_name = drivers_dict[filename.split('.')[-1]] if len(driver_short_name) == 1: driver = gdal.GetDriverByName(driver_short_name[0]) else: raise ValueError('Ambiguous file name {} with possible drivers: {}'.format( filename, ', '.join(driver_short_name))) except KeyError: raise ValueError('Could not find driver for file {}'.format(filename)) return driver # ============================================================================= class RasterFilename(object): def __init__(self, filename): self.filename = filename def get_filename(self): return self.filename def get_member(self): return self.filename def is_compressed(self): return False class RasterGzipFilename(RasterFilename): def __init__(self, filename): super(RasterGzipFilename, self).__init__(filename) def get_member(self): return self.filename[:-3] def is_compressed(self): return True class RasterZipFilename(RasterFilename): def __init__(self, filename, member): super(RasterZipFilename, self).__init__(filename) if not member: with zipfile.ZipFile(filename) as zf: members = zf.namelist() assert len(members) == 1 member = members[0] self.member = member def get_member(self): return self.member def is_compressed(self): return True # ============================================================================= # Raster # ============================================================================= class Raster(object): def __init__(self, filename, member=None): """ :param filename: :param member: """ self.dataset = None if filename is None: filename = '' fnl = filename.lower() if fnl.endswith('.zip'): self.filename = RasterZipFilename(filename, member) elif fnl.endswith('.gz'): self.filename = RasterGzipFilename(filename) else: self.filename = RasterFilename(filename) def __repr__(self): return self.get_filename() + ' ' + self.get_parameters().__repr__() def info(self, **kwargs): """Return information on a dataset :: return gdal.Info(self.dataset, **kwargs) :param kwargs: see gdal.Info :return: information on a dataset :rtype: str """ return gdal.Info(self.dataset, **kwargs) def show(self, band_number=1, mask=True, scale=False, plot=True): """ :param band_number: :param mask: :param scale: :return: """ array = self.get_array(band_number, mask=mask, scale=scale) if np.ma.all(array) is np.ma.masked: print('Empty array: nothing to show') else: plt.imshow(array) if plot: plt.show() def plot(self, axes_dict=None, mask=True, scale=False, plot=True): """ :param axes_dict: dictionary with ax as key and list of bands as plot :param mask: :param scale: :param plot: :return: """ for ax, band_number in list(axes_dict.items()): if isinstance(band_number, int): array = self.get_array(band_number, mask=mask, scale=scale) else: array = self.get_arrays(band_number, mask=mask, scale=scale) ax.imshow(array) if plot: plt.show() def is_compressed(self): """Return True is the file is compressed Valid compressions are gzip (.gz) and zip (.zip) :return: True is the file is compressed """ return self.filename.is_compressed() def get_filename(self): """Return the file name :return: file name :rtype: str """ return self.filename.get_filename() def get_rastername(self): """Return the raster name Raster name may be different of file name in case of zipped files :return: file name :rtype: str """ return self.filename.get_member() def get_parameters(self): """Return the raster parameters defined in the dataset :return: raster parameters :rtype: RasterParameters """ return parameter.get_parameters(self.dataset) def get_raster_size(self): """Return (number of columns, number of rows) Return the x- and y-sizes as tuple (number of columns, number of rows) :return: number of columns and rows :rtype: (int, int) """ return self.dataset.RasterXSize, self.dataset.RasterYSize def get_nodata(self, band_number=1): """Return nodata or list of nodata If band_number is 'all' or a list of band numbers, return a list with one nodata for each band. If band_number is a number, return the nodata value :param band_number: 'all', band number or list of band numbers :type band_number: int or list of int :return: nodata or list of nodata :rtype: raster type or list of raster types """ if band_number == 'all': band_number = list(range(1, self.get_band_count() + 1)) try: return [self.dataset.GetRasterBand(i).GetNoDataValue() for i in band_number] except TypeError: return self.dataset.GetRasterBand(band_number).GetNoDataValue() def get_extent(self, scale=0.0): """Return the raster extent in world coordinates. :return: (x_min, x_max, y_min, y_max) :rtype: """ xmin, xmax, ymin, ymax = extent_pixel_to_world(self.get_geotransform(), self.dataset.RasterXSize, self.dataset.RasterYSize) if scale and scale != 0.0: dx, dy = xmax - xmin, ymax - ymin xmin -= dx * scale xmax += dx * scale ymin -= dy * scale ymax += dy * scale return xmin, xmax, ymin, ymax def copy(self, name='', driver_short_name=None): """Return a copy of this raster Creates a new RasterUpdate instance using the parameters of this raster :param name: :param driver_short_name: :return: """ return copy(self, name, driver_short_name) def get_band_count(self): """Return the number of bands :return: number of bands :rtype: int """ return self.dataset.RasterCount def get_band_data_type(self, band_number=1): """Return data type or list of data types If band_number is 'all' or a list of band numbers, return a list with one data type for each band. If band_number is a number, return the data type :param band_number: 'all', band number or list of band numbers :type band_number: int or list of int :return: data type or list of data types :rtype: int or list of int """ if band_number == 'all': band_number = list(range(1, len(band_number) + 1)) try: return [self.dataset.GetRasterBand(i).DataType for i in band_number] except TypeError: return self.dataset.GetRasterBand(band_number).DataType def get_band(self, band_number=1): """Return a raster band :param band_number: band number. Default band_number=1 :return: raster band :rtype: gdal.Band """ return self.dataset.GetRasterBand(band_number) def array_block(self, band_number=1): """Loop through an array and yields i_row, i_col, n_rows, n_cols, array block It is 5x slower than get_array :return: i_row, i_col, n_rows, n_cols, block """ band = self.dataset.GetRasterBand(band_number) row_size, col_size = band.YSize, band.XSize block_sizes = band.GetBlockSize() row_block_size, col_block_size = block_sizes[1], block_sizes[0] col_range = list(range(0, col_size, col_block_size)) for i_row in range(0, row_size, row_block_size): n_rows = row_block_size if i_row + row_block_size < row_size else row_size - i_row for i_col in col_range: n_cols = col_block_size if i_col + col_block_size < col_size else col_size - i_col yield i_row, i_col, n_rows, n_cols, band.ReadAsArray(i_col, i_row, n_cols, n_rows) def get_array(self, band_number=1, col0=0, row0=0, n_cols=None, n_rows=None, mask=False, scale=False): """Return the raster band array If band number is a number, return a 2D-array, else if band number is a list/tuple of numbers, return a 3D-array If mask is True, returned a numpy masked array If scale is True, scale the raster: (array - min)/(max - min) :param band_number: band number. Default band_number=1 :param col0: starting x pixel :type col0: int :param row0: starting y pixel :type row0: int :param n_cols: number of x-pixels :type n_cols: int :param n_rows: number of y-pixels :type n_rows: int :return: 2D- or 3D-array :rtype: numpy.ndarray """ if not n_cols: n_cols = self.dataset.RasterXSize if not n_rows: n_rows = self.dataset.RasterYSize if band_number == 'all': band_number = list(range(1, self.get_band_count() + 1)) try: arrays = np.empty((len(band_number), n_rows, n_cols)) for i, bn in enumerate(band_number): arrays[i] = self.get_array(bn, col0=col0, row0=row0, n_cols=n_cols, n_rows=n_rows, mask=mask, scale=scale) return arrays except TypeError: array = self.dataset.GetRasterBand(band_number).ReadAsArray(col0, row0, n_cols, n_rows) if mask: nodata = self.get_nodata(band_number=band_number) array = np.ma.array(array, mask=(array == nodata)) if scale: array = scale_array(array) return array def get_array_full(self, value=0, **kwargs): """ :param value: :type value: int or list :param kwargs: :key dtype: numpy dtype, default raster type converted into dtype :return: array """ n_cols, n_rows = self.get_raster_size() dtype = kwargs.pop('dtype', gdal_array.GDALTypeCodeToNumericTypeCode(self.get_band_data_type())) if isinstance(value, (list, tuple)): n_bands = len(value) if value.count(0) == len(value): return np.zeros((n_bands, n_rows, n_cols), dtype) elif value.count(None) == len(value): return np.empty((n_bands, n_rows, n_cols), dtype) else: array = np.empty((n_bands, n_rows, n_cols), dtype) for i in range(n_bands): array[i] = np.full((n_rows, n_cols), value[i], dtype) return array else: if value == 0: return np.zeros((n_rows, n_cols), dtype) elif value is None: return np.empty((n_rows, n_cols), dtype) else: return np.full((n_rows, n_cols), value, dtype) def get_geotransform(self): """Return geo transform. :return: """ return self.dataset.GetGeoTransform() def transform(self, **kwargs): """Return a raster in the given coordinate system Create an instance of RasterUpdate in 'MEM': - If filename and driver are unset - If driver is 'MEM' :param kwargs: :key epsg: (str) :key proj4: (str) :key wkt: (str) :key output_raster: full path file name, any string if drivername='mem', or None :key drivername: short driver name :return: """ output_raster = kwargs.pop('output_raster', 'MEM') drivername = kwargs.pop('drivername', 'Memory') if output_raster: target = output_raster else: target = drivername srs = kwargs.pop('wkt', kwargs.pop('proj4', None)) if not srs: srs = 'epsg:{}'.format(kwargs.pop('epsg', None)) return RasterUpdate(gdal.Warp(destNameOrDestDS=target, srcDSOrSrcDSTab=self.dataset, dstSRS=srs, **kwargs)) def get_coordinate_system(self): """Return the coordinate system :return: """ return self.dataset.GetProjection() def get_pixel_size(self): """Return pixel sizes (x, y): (column width, row height) :return: pixel sizes (x, y): (column width, row height) :rtype: tuple """ return pixel_size(self.get_geotransform()) def world_to_pixel(self, x, y): """Transform world to pixel coordinates :param x: :param y: :return: pixel coordinates of (x, y) :rtype: list of int """ return world_to_pixel(self.get_geotransform(), x, y) def extent_world_to_pixel(self, min_x, max_x, min_y, max_y): """Return extent in pixel coordinates :param min_x: minimum x (minimum longitude) :type min_x: float :param max_x: maximum x (maximum longitude) :type max_x: float :param min_y: minimum x (minimum latitude) :type min_y: float :param max_y: maximum x (maximum latitude) :type max_y: float :return: (u_min, u_max, v_min, v_max) :rtype: tuple """ return extent_world_to_pixel(self.get_geotransform(), min_x, max_x, min_y, max_y) def pixel_to_world(self, x, y): """Return the top-left world coordinate of the pixel :param x: :param y: :return: """ return pixel_to_world(self.get_geotransform(), x, y) def get_pixel_centroid_coordinates(self): """ :return: """ dx, dy = self.get_pixel_size() dy = -dy nc, nr = self.get_raster_size() tr = self.get_geotransform() arr = np.concatenate([x.reshape(nr, nc, 1) for x in np.indices((nr, nc))][::-1], 2).astype(np.float) arr[:][:] *= np.array([dx, dy]) arr[:][:] += np.array([tr[0], tr[3]]) arr[:][:] += np.array([dx / 2.0, dy / 2.0]) return arr def get_centroid_world_coordinates(self): """Return the raster centroid in world coordinates :return: """ x_size, y_size = self.get_pixel_size() return get_centroid_world_coordinates(self.get_geotransform(), self.dataset.RasterXSize, self.dataset.RasterYSize, x_size, y_size) def resample(self, pixel_sizes, resample_alg=gdal.GRA_NearestNeighbour, **kwargs): """Resample the raster :param pixel_sizes: :param resample_alg: :param kwargs: :return: """ from girs.rast.proc import resample return resample(self, pixel_sizes, resample_alg, **kwargs) def strip(self): from girs.rast.proc import strip return strip(self) # ============================================================================= # RasterReader # ============================================================================= class RasterReader(Raster): def __init__(self, filename, member=''): """Filename, also als .zip or .gz. In case of zip-files, a member name can be also be given in case there are more then one raster files in the zip file :param filename: :param member: """ super(RasterReader, self).__init__(filename, member=member) fnl = filename.lower() if fnl.endswith('.zip'): # /vsizip/path/to/the/file.zip/path/inside/the/zip/file filename = '/vsizip/' + filename + '/' + member elif fnl.endswith('.gz'): # /vsigzip/path/to/the/file.gz filename = '/vsigzip/' + filename self.dataset = gdal.Open(filename, GA_ReadOnly) class RasterEditor(Raster): def __init__(self, filename): super(RasterEditor, self).__init__(filename) def set_nodata(self, nodata, band_number=1): """Set nodata :param nodata: :param band_number: :return: """ if isinstance(nodata, basestring): nodata = [nodata] else: try: len(nodata) except TypeError: nodata = [nodata] try: band_number_nodata = {bn: nodata[i] for i, bn in enumerate(band_number)} except TypeError: band_number = [band_number] band_number_nodata = {bn: nodata[i] for i, bn in enumerate(band_number)} for bn in band_number: self.dataset.GetRasterBand(bn).SetNoDataValue(band_number_nodata[bn]) self.dataset.FlushCache() def set_array(self, array, band_number=1): """Set array :param array: :param band_number: :return: """ result = self.dataset.GetRasterBand(band_number).WriteArray(array) self.dataset.FlushCache() return result def set_projection(self, srs): """Set projection :param srs: :return: """ result = self.dataset.SetProjection(srs) self.dataset.FlushCache() return result def set_geotransform(self, x_min=0.0, x_pixel_size=1.0, x_rot=0.0, y_max=0.0, y_rot=0.0, y_pixel_size=1.0): """ :param x_min: x location of East corner of the raster :param x_pixel_size: pixel width :param x_rot: x pixel rotation, usually zero :param y_max: y location of North corner of the raster :param y_rot: x pixel rotation, usually zero :param y_pixel_size: negative value of pixel height :return: True if setting was successful else gdal.CE_Failure """ result = self.dataset.SetGeoTransform(x_min, x_pixel_size, x_rot, y_max, y_rot, y_pixel_size) self.dataset.FlushCache() return True if result == gdal.CE_None else gdal.CE_Failure class RasterUpdate(RasterEditor): def __init__(self, source, drivername=None): """ If source is another Raster or a raster dataset, create a copy of the dataset in 'MEM' If source is a filename, open the file in update modus :param source: raster filename, Raster, or raster dataset """ try: super(RasterUpdate, self).__init__(source) # No support for zip-files if source.lower().endswith('.gz'): # /vsigzip/path/to/the/file.gz source = '/vsigzip/' + source if not drivername or drivername == 'MEM': drv = gdal.GetDriverByName('MEM') drv else: raise ValueError('No filename defined') self.dataset = gdal.Open(source, GA_Update) except AttributeError: super(RasterUpdate, self).__init__('') try: self.dataset = gdal.GetDriverByName('MEM').CreateCopy('', source.dataset) except AttributeError: self.dataset = gdal.GetDriverByName('MEM').CreateCopy('', source) self.filename = '' class RasterWriter(RasterEditor): def __init__(self, raster_parameters, source=None, drivername=None): """Create an instance of RasterWriter in 'MEM': - If source and driver are not given - If drivername is 'MEM' :param raster_parameters: :param source: :param drivername: gdal driver short name or an instance of gdal.Driver """ super(RasterWriter, self).__init__(source) drv = None if not source: if not drivername or drivername == 'MEM': drv = gdal.GetDriverByName('MEM') else: raise ValueError('No filename defined') elif source: if not drivername: drv = get_driver(source) else: try: drv = gdal.GetDriverByName(drivername) except TypeError as e: if not isinstance(drivername, gdal.Driver): raise e drv = drivername n_bands = raster_parameters.number_of_bands try: dt = raster_parameters.data_types[0] except TypeError: dt = raster_parameters.data_types try: filename = self.get_filename() self.dataset = drv.Create(filename, raster_parameters.RasterXSize, raster_parameters.RasterYSize, n_bands, dt) except RuntimeError as e: msg = '{} or raster {} is being eventually used (locked)'.format(e.message, self.filename) raise RuntimeError(msg) self.dataset.SetGeoTransform(raster_parameters.geo_trans) self.dataset.SetProjection(raster_parameters.srs) raster_parameters.set_nodata(raster_parameters.nodata) for i in range(n_bands): if raster_parameters.nodata[i] is not None: rb_out = self.dataset.GetRasterBand(i+1) rb_out.SetNoDataValue(raster_parameters.nodata[i]) rb_out.FlushCache() # ============================================================================= # Functions # ============================================================================= def info(raster, **kwargs): """Return raster information :param raster: :param kwargs: :return: """ try: raster = RasterReader(raster) dataset = raster.dataset except AttributeError: try: dataset = raster.dataset except AttributeError: dataset = raster return gdal.Info(dataset, **kwargs) def create_gifs(output_filename, *args, **kwargs): """ :param self: :param output_filename: :param args: :param kwargs: :key mask: default True :key scale: default False :key band_number: :key nodata: :key cmap_name: default Blues :key cmap: default Blues :key resize: default 1 :return: """ from PIL import Image import matplotlib as mpl resize = kwargs.pop('resize', 1) cm = kwargs.pop('cmap', mpl.cm.get_cmap(kwargs.pop('cmap_name', 'plasma_r'))) images = list() a_max, a_min = None, None for i, arg in enumerate(args): try: r = RasterReader(arg) except AttributeError: r = arg array = r.get_array(mask=True, scale=False) a_min = array.min() if a_min is None else min(a_min, array.min()) a_max = array.max() if a_max is None else max(a_max, array.max()) for i, arg in enumerate(args): try: r = RasterReader(arg) except AttributeError: r = arg array = r.get_array(mask=True, scale=False) array = old_div((array - a_min), (a_max - a_min)) array = cm(array) img = Image.fromarray((array * 255).astype('uint8')) img = img.resize((img.size[0] * resize, img.size[1] * resize)) images.append(img) images[0].save(output_filename, 'GIF', duration=1000, save_all=True, optimize=False, append_images=images[1:]) # def create_gifs(output_filename, *args, **kwargs): # """ # # :param self: # :param output_filename: # :param args: # :param kwargs: # :key mask: default True # :key scale: default False # :key band_number: # :return: # """ # from PIL import Image # import matplotlib as mpl # cm_hot = mpl.cm.get_cmap('hot') # images = list() # for i, arg in enumerate(args): # try: # r = RasterReader(arg) # except AttributeError: # r = arg # # p = r.get_parameters() # nodata = p.nodata # array = r.get_array(mask=False, scale=False) # array[array == nodata] = 0 # array *= 255.0 / array.max() # array = array.astype(np.uint8) # array = cm_hot(array) # array *= 255 # array = array.astype('uint8') # print array # # data = img.getdata() # # max_d = max(data) * 1.2 # # img.putdata([item if item != nodata else 0 for item in data]) # img = Image.fromarray(array) # img = img.resize((img.size[0] * 50, img.size[1] * 50)) # images.append(img) # images[0].save(output_filename, 'GIF', duration=2000, save_all=True, optimize=False, append_images=images[1:]) # def create_gifs(output_filename, *args, **kwargs): # """ # # :param self: # :param output_filename: # :param args: # :param kwargs: # :key mask: default True # :key scale: default False # :key band_number: # :return: # """ # from PIL import Image # import imageio as io # images = list() # # for i, arg in enumerate(args): # try: # r = RasterReader(arg) # except AttributeError: # r = arg # array = r.get_array(mask=False, scale=False) # images = [io.imread(os.path.join(input_dir, f1)) for f1 in filenames] # io.mimsave(output_gif, jpeg_images, duration=0.5) def get_parameters(raster): """Return the raster parameters defined in this raster :param raster: dataset or filename :type raster: gdal.Dataset :return: raster parameters :rtype: RasterParameters """ return parameter.get_parameters(raster) def copy(raster, dst_filename='', driver_short_name=None): """Return a copy of given raster Creates a new RasterUpdate instance using the parameters of this raster :param raster: :param dst_filename: :param driver_short_name: :return: copy of this raster :rtype: RasterUpdate """ try: raster = RasterReader(raster) except AttributeError: raster = raster drv = get_driver(dst_filename, driver_short_name) dataset = drv.CreateCopy(dst_filename, raster.dataset) return RasterUpdate(dataset) def scale_array(array): def scale(a): array_min = np.amin(a) array_max = np.amax(a) return old_div((a - array_min), (array_max - array_min)) if len(array.shape) > 2: # ndim does not work for masked arrays for i in range(len(array)): array[i, :, :] = scale(array[i, :, :]) else: array = scale(array) return array def pixel_size(geo_trans): """Return pixel sizes :param geo_trans: geo transformation :type geo_trans: tuple with six values :return: pixel sizes (x, y): (column width, row height) :rtype: tuple """ return geo_trans[1], -geo_trans[5] def world_to_pixel(geo_trans, x, y, np_func=np.trunc): """Transform world into pixel coordinates :param geo_trans: geo transformation :type geo_trans: tuple with six values :param x: :param y: :param np_func: :return: pixel coordinates of (x, y) :rtype: list of int """ # print geo_trans, x, y # xOffset = int((x - geo_trans[0]) / geo_trans[1]) # yOffset = int((y - geo_trans[3]) / geo_trans[5]) # print xOffset, yOffset, xOffset = np_func(np.divide(x - geo_trans[0], geo_trans[1])).astype(np.int) yOffset = np_func(np.divide(y - geo_trans[3], geo_trans[5])).astype(np.int) # print xOffset, yOffset return xOffset, yOffset def pixel_to_world(geo_trans, x, y): """Return the top-left world coordinate of the pixel :param geo_trans: geo transformation :type geo_trans: tuple with six values :param x: :param y: :return: """ return geo_trans[0] + (x * geo_trans[1]), geo_trans[3] + (y * geo_trans[5]) def extent_pixel_to_world(geo_trans, raster_x_size, raster_y_size): """Return extent in world coordinates. Transform the given pixel coordinates `raster_x_size` (number of columns) and `raster_y_size` (number of rows) into world coordinates. :param geo_trans: geo transformation :type geo_trans: tuple with six values :param raster_x_size: number of columns :type raster_x_size: int :param raster_y_size: number of rows :return: (x_min, x_max, y_min, y_max) :rtype: tuple """ x_min0, y_max0 = pixel_to_world(geo_trans, 0, 0) x_max0, y_min0 = pixel_to_world(geo_trans, raster_x_size, raster_y_size) return x_min0, x_max0, y_min0, y_max0 def extent_world_to_pixel(geo_trans, min_x, max_x, min_y, max_y): """Return extent in pixel coordinates :param geo_trans: geo transformation :type geo_trans: tuple with six values :param min_x: minimum x (minimum longitude) :type min_x: float :param max_x: maximum x (maximum longitude) :type max_x: float :param min_y: minimum x (minimum latitude) :type min_y: float :param max_y: maximum x (maximum latitude) :type max_y: float :return: (u_min, u_max, v_min, v_max) :rtype: tuple """ geo_trans = list(geo_trans) u_min, v_min = world_to_pixel(geo_trans, min_x, max_y) u_max, v_max = world_to_pixel(geo_trans, max_x, min_y) geo_trans[0], geo_trans[3] = pixel_to_world(geo_trans, u_min, v_min) return (u_min, u_max, v_min, v_max), geo_trans def get_centroid_world_coordinates(geo_trans, raster_x_size, raster_y_size, x_pixel_size, y_pixel_size): """Return the raster centroid in world coordinates :param geo_trans: geo transformation :type geo_trans: tuple with six values :param raster_x_size: number of columns :type raster_x_size: int :param raster_y_size: number of rows :param x_pixel_size: pixel size in x direction :type: x_pixel_size: float :param y_pixel_size: pixel size in y direction :type y_pixel_size: float :return: """ x0, y0 = pixel_to_world(geo_trans, 0, 0) x1, y1 = pixel_to_world(geo_trans, raster_x_size-1, raster_y_size-1) x1 += x_pixel_size y1 -= y_pixel_size return (x0 + x1) * 0.5, (y0 + y1) * 0.5 def get_default_values(number_of_bands, values): """Return values for bands Utility function to get values (e.g., nodata) for bands. For n = number_of_bands: - If values is a single value, transform it into a list with n elements - If values is a list with size lower than n, extend the list to size n by repeating the last value (n=4, values=[1, 2], result=[1, 2, 2, 2] - If values is a list with size greater than n, slice values to values[:n] :param number_of_bands: number of bands :type number_of_bands: int :param values: value or list of values :type values: same as raster type :return: values :rtype: same as input values """ try: if number_of_bands < len(values): values = values[:number_of_bands] elif number_of_bands > len(values): values = values[-1] * (number_of_bands - len(values)) except TypeError: values = [values] * number_of_bands except: raise return values def rasters_get_extent(rasters, extent_type='intersection'): """Return the extent of a list of rasters. Return the extent of the union or intersection of a list of rasters :param rasters: list of rasters or raster filenames (also mixed) :param extent_type: intersection or union :return: (xmin, xmax, ymin, ymax) in world coordinates """ # Get get common extent # Get the rasters rasters = [RasterReader(ir) if isinstance(ir, basestring) else ir for ir in rasters] return merge_envelopes([r.get_extent() for r in rasters]) def rasters_get_pixel_size(rasters, minmax='max'): """Return union or intersection of pixel sizes - If minmax='min', return the intersection of the pixel sizes defined in the list of rasters. This corresponds to the smallest pixel size among all rasters. - If minmax='max', return the union of the pixel sizes defined in the list of rasters. This corresponds to the largest pixel size among all rasters. :param rasters: list of rasters :type rasters: list of raster file names or list of Raster instances, also both types in the same list :param minmax: 'min' for intersection and 'max' for union :type minmax: str :return: pixel sizes (x, y): (number of columns, number of rows) :rtype: tuple """ rasters = [RasterReader(ir) if isinstance(ir, basestring) else ir for ir in rasters] xs, ys = rasters[0].get_pixel_size() if minmax == 'max': for r in rasters: xs0, ys0 = r.get_pixel_size() xs = max(xs, xs0) ys = max(ys, ys0) elif minmax == 'min': for r in rasters: xs0, ys0 = r.get_pixel_size() xs = min(xs, xs0) ys = min(ys, ys0) return xs, ys
{ "content_hash": "6ddc50f722c1ac0f7bc8bd707e9df65e", "timestamp": "", "source": "github", "line_count": 1090, "max_line_length": 164, "avg_line_length": 34.15321100917431, "alnum_prop": 0.5718967416122707, "repo_name": "JRoehrig/GIRS", "id": "c501406da022256c6e274e5a821773aca7cdbe7c", "size": "37227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "girs/rast/raster.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "258726" } ], "symlink_target": "" }
<?php namespace Composer\Test\Downloader; use Composer\Test\TestCase; class ArchiveDownloaderTest extends TestCase { /** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */ protected $config; public function testGetFileName() { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) ->method('getDistUrl') ->will($this->returnValue('http://example.com/script.js')) ; $downloader = $this->getArchiveDownloaderMock(); $method = new \ReflectionMethod($downloader, 'getFileName'); $method->setAccessible(true); $this->config->expects($this->any()) ->method('get') ->with('vendor-dir') ->will($this->returnValue('/vendor')); $first = $method->invoke($downloader, $packageMock, '/path'); $this->assertMatchesRegularExpression('#/vendor/composer/tmp-[a-z0-9]+\.js#', $first); $this->assertSame($first, $method->invoke($downloader, $packageMock, '/path')); } public function testProcessUrl() { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); } $downloader = $this->getArchiveDownloaderMock(); $method = new \ReflectionMethod($downloader, 'processUrl'); $method->setAccessible(true); $expected = 'https://github.com/composer/composer/zipball/master'; $url = $method->invoke($downloader, $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(), $expected); $this->assertEquals($expected, $url); } public function testProcessUrl2() { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); } $downloader = $this->getArchiveDownloaderMock(); $method = new \ReflectionMethod($downloader, 'processUrl'); $method->setAccessible(true); $expected = 'https://github.com/composer/composer/archive/master.tar.gz'; $url = $method->invoke($downloader, $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(), $expected); $this->assertEquals($expected, $url); } public function testProcessUrl3() { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); } $downloader = $this->getArchiveDownloaderMock(); $method = new \ReflectionMethod($downloader, 'processUrl'); $method->setAccessible(true); $expected = 'https://api.github.com/repos/composer/composer/zipball/master'; $url = $method->invoke($downloader, $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(), $expected); $this->assertEquals($expected, $url); } /** * @dataProvider provideUrls * @param string $url */ public function testProcessUrlRewriteDist($url) { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); } $downloader = $this->getArchiveDownloaderMock(); $method = new \ReflectionMethod($downloader, 'processUrl'); $method->setAccessible(true); $type = strpos($url, 'tar') ? 'tar' : 'zip'; $expected = 'https://api.github.com/repos/composer/composer/'.$type.'ball/ref'; $package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $package->expects($this->any()) ->method('getDistReference') ->will($this->returnValue('ref')); $url = $method->invoke($downloader, $package, $url); $this->assertEquals($expected, $url); } public function provideUrls() { return array( array('https://api.github.com/repos/composer/composer/zipball/master'), array('https://api.github.com/repos/composer/composer/tarball/master'), array('https://github.com/composer/composer/zipball/master'), array('https://www.github.com/composer/composer/tarball/master'), array('https://github.com/composer/composer/archive/master.zip'), array('https://github.com/composer/composer/archive/master.tar.gz'), ); } /** * @dataProvider provideBitbucketUrls * @param string $url * @param string $extension */ public function testProcessUrlRewriteBitbucketDist($url, $extension) { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); } $downloader = $this->getArchiveDownloaderMock(); $method = new \ReflectionMethod($downloader, 'processUrl'); $method->setAccessible(true); $url .= '.' . $extension; $expected = 'https://bitbucket.org/davereid/drush-virtualhost/get/ref.' . $extension; $package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $package->expects($this->any()) ->method('getDistReference') ->will($this->returnValue('ref')); $url = $method->invoke($downloader, $package, $url); $this->assertEquals($expected, $url); } public function provideBitbucketUrls() { return array( array('https://bitbucket.org/davereid/drush-virtualhost/get/77ca490c26ac818e024d1138aa8bd3677d1ef21f', 'zip'), array('https://bitbucket.org/davereid/drush-virtualhost/get/master', 'tar.gz'), array('https://bitbucket.org/davereid/drush-virtualhost/get/v1.0', 'tar.bz2'), ); } /** * @return \Composer\Downloader\ArchiveDownloader&\PHPUnit\Framework\MockObject\MockObject */ private function getArchiveDownloaderMock() { return $this->getMockForAbstractClass( 'Composer\Downloader\ArchiveDownloader', array( $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->config = $this->getMockBuilder('Composer\Config')->getMock(), new \Composer\Util\HttpDownloader($io, $this->config), ) ); } }
{ "content_hash": "e3dd4b0a5dc524f6fae8bfda20886c51", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 126, "avg_line_length": 35.86046511627907, "alnum_prop": 0.6120298313878081, "repo_name": "nicolas-grekas/composer", "id": "9537e462a19fb23409cd604f7fe52f4340b3467c", "size": "6428", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "tests/Composer/Test/Downloader/ArchiveDownloaderTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "Hack", "bytes": "154" }, { "name": "PHP", "bytes": "6114023" } ], "symlink_target": "" }
package lee; import org.crazyit.app.domain.News; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class NewsManager { public static void main(String[] args) throws Exception { //ʵÀý»¯Configuration£¬ Configuration conf = new Configuration() //ÏÂÃæ·½·¨Ä¬ÈϼÓÔØhibernate.cfg.xmlÎļþ .configure(); //ÒÔConfiguration´´½¨SessionFactory SessionFactory sf = conf.buildSessionFactory(); //´´½¨Session Session sess = sf.openSession(); //¿ªÊ¼ÊÂÎñ Transaction tx = sess.beginTransaction(); //´´½¨ÏûϢʵÀý News n = new News(); //ÉèÖÃÏûÏ¢±êÌâºÍÏûÏ¢ÄÚÈÝ n.setTitle("·è¿ñJavaÁªÃ˳ÉÁ¢ÁË"); n.setContent("·è¿ñJavaÁªÃ˳ÉÁ¢ÁË£¬" + "ÍøÕ¾µØÖ·http://www.crazyit.org"); //±£´æÏûÏ¢ sess.save(n); //Ìá½»ÊÂÎñ tx.commit(); //¹Ø±ÕSession sess.close(); sf.close(); } }
{ "content_hash": "f5c27efc3912263590c021be3b22fc7b", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 49, "avg_line_length": 24.18918918918919, "alnum_prop": 0.6972067039106146, "repo_name": "runnerfish/ssh2_code_learn", "id": "38a2d18c2524dae1b5be5975407ae2ba15a4a7ca", "size": "895", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SSH2 Code Kit/05/5.2/HibernateDemo/src/lee/NewsManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3886" }, { "name": "Java", "bytes": "937888" } ], "symlink_target": "" }
import * as React from 'react'; import TopLayoutBlog from 'docs/src/modules/components/TopLayoutBlog'; import { docs } from './premium-plan-release.md?@mui/markdown'; export default function Page() { return <TopLayoutBlog docs={docs} />; }
{ "content_hash": "c776c03e314ec2f31b37b27aab9381fa", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 70, "avg_line_length": 34.714285714285715, "alnum_prop": 0.7366255144032922, "repo_name": "rscnt/material-ui", "id": "8ab4e78e9edf0767e255e6c71c10a6d31f6523fb", "size": "243", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/pages/blog/premium-plan-release.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2126" }, { "name": "JavaScript", "bytes": "3967457" }, { "name": "TypeScript", "bytes": "2468380" } ], "symlink_target": "" }
using System.IO; namespace Lucene.Net.Search.Payloads { using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using Similarity = Lucene.Net.Search.Similarities.Similarity; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; using SpanScorer = Lucene.Net.Search.Spans.SpanScorer; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using SpanWeight = Lucene.Net.Search.Spans.SpanWeight; using Term = Lucene.Net.Index.Term; using TermSpans = Lucene.Net.Search.Spans.TermSpans; /// <summary> /// This class is very similar to /// <see cref="Lucene.Net.Search.Spans.SpanTermQuery"/> except that it factors /// in the value of the payload located at each of the positions where the /// <see cref="Lucene.Net.Index.Term"/> occurs. /// <para/> /// NOTE: In order to take advantage of this with the default scoring implementation /// (<see cref="Similarities.DefaultSimilarity"/>), you must override <see cref="Similarities.DefaultSimilarity.ScorePayload(int, int, int, BytesRef)"/>, /// which returns 1 by default. /// <para/> /// Payload scores are aggregated using a pluggable <see cref="PayloadFunction"/>. </summary> /// <seealso cref="Lucene.Net.Search.Similarities.Similarity.SimScorer.ComputePayloadFactor(int, int, int, BytesRef)"/> public class PayloadTermQuery : SpanTermQuery { protected PayloadFunction m_function; private bool includeSpanScore; public PayloadTermQuery(Term term, PayloadFunction function) : this(term, function, true) { } public PayloadTermQuery(Term term, PayloadFunction function, bool includeSpanScore) : base(term) { this.m_function = function; this.includeSpanScore = includeSpanScore; } public override Weight CreateWeight(IndexSearcher searcher) { return new PayloadTermWeight(this, this, searcher); } protected class PayloadTermWeight : SpanWeight { private readonly PayloadTermQuery outerInstance; public PayloadTermWeight(PayloadTermQuery outerInstance, PayloadTermQuery query, IndexSearcher searcher) : base(query, searcher) { this.outerInstance = outerInstance; } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { return new PayloadTermSpanScorer(this, (TermSpans)m_query.GetSpans(context, acceptDocs, m_termContexts), this, m_similarity.GetSimScorer(m_stats, context)); } protected class PayloadTermSpanScorer : SpanScorer { private readonly PayloadTermQuery.PayloadTermWeight outerInstance; protected BytesRef m_payload; protected internal float m_payloadScore; protected internal int m_payloadsSeen; internal readonly TermSpans termSpans; public PayloadTermSpanScorer(PayloadTermQuery.PayloadTermWeight outerInstance, TermSpans spans, Weight weight, Similarity.SimScorer docScorer) : base(spans, weight, docScorer) { this.outerInstance = outerInstance; termSpans = spans; } protected override bool SetFreqCurrentDoc() { if (!m_more) { return false; } m_doc = m_spans.Doc; m_freq = 0.0f; m_numMatches = 0; m_payloadScore = 0; m_payloadsSeen = 0; while (m_more && m_doc == m_spans.Doc) { int matchLength = m_spans.End - m_spans.Start; m_freq += m_docScorer.ComputeSlopFactor(matchLength); m_numMatches++; ProcessPayload(outerInstance.m_similarity); m_more = m_spans.Next(); // this moves positions to the next match in this // document } return m_more || (m_freq != 0); } protected internal virtual void ProcessPayload(Similarity similarity) { if (termSpans.IsPayloadAvailable) { DocsAndPositionsEnum postings = termSpans.Postings; m_payload = postings.GetPayload(); if (m_payload != null) { m_payloadScore = outerInstance.outerInstance.m_function.CurrentScore(m_doc, outerInstance.outerInstance.Term.Field, m_spans.Start, m_spans.End, m_payloadsSeen, m_payloadScore, m_docScorer.ComputePayloadFactor(m_doc, m_spans.Start, m_spans.End, m_payload)); } else { m_payloadScore = outerInstance.outerInstance.m_function.CurrentScore(m_doc, outerInstance.outerInstance.Term.Field, m_spans.Start, m_spans.End, m_payloadsSeen, m_payloadScore, 1F); } m_payloadsSeen++; } else { // zero out the payload? } } /// /// <returns> <see cref="GetSpanScore()"/> * <see cref="GetPayloadScore()"/> </returns> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public override float GetScore() { return outerInstance.outerInstance.includeSpanScore ? GetSpanScore() * GetPayloadScore() : GetPayloadScore(); } /// <summary> /// Returns the <see cref="SpanScorer"/> score only. /// <para/> /// Should not be overridden without good cause! /// </summary> /// <returns> the score for just the Span part w/o the payload </returns> /// <exception cref="IOException"> if there is a low-level I/O error /// </exception> /// <seealso cref="GetScore()"/> protected internal virtual float GetSpanScore() { return base.GetScore(); } /// <summary> /// The score for the payload /// </summary> /// <returns> The score, as calculated by /// <see cref="PayloadFunction.DocScore(int, string, int, float)"/> </returns> protected internal virtual float GetPayloadScore() { return outerInstance.outerInstance.m_function.DocScore(m_doc, outerInstance.outerInstance.Term.Field, m_payloadsSeen, m_payloadScore); } } public override Explanation Explain(AtomicReaderContext context, int doc) { PayloadTermSpanScorer scorer = (PayloadTermSpanScorer)GetScorer(context, (context.AtomicReader).LiveDocs); if (scorer != null) { int newDoc = scorer.Advance(doc); if (newDoc == doc) { float freq = scorer.SloppyFreq; Similarity.SimScorer docScorer = m_similarity.GetSimScorer(m_stats, context); Explanation expl = new Explanation(); expl.Description = "weight(" + Query + " in " + doc + ") [" + m_similarity.GetType().Name + "], result of:"; Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "phraseFreq=" + freq)); expl.AddDetail(scoreExplanation); expl.Value = scoreExplanation.Value; // now the payloads part // QUESTION: Is there a way to avoid this skipTo call? We need to know // whether to load the payload or not // GSI: I suppose we could toString the payload, but I don't think that // would be a good idea string field = ((SpanQuery)Query).Field; Explanation payloadExpl = outerInstance.m_function.Explain(doc, field, scorer.m_payloadsSeen, scorer.m_payloadScore); payloadExpl.Value = scorer.GetPayloadScore(); // combined ComplexExplanation result = new ComplexExplanation(); if (outerInstance.includeSpanScore) { result.AddDetail(expl); result.AddDetail(payloadExpl); result.Value = expl.Value * payloadExpl.Value; result.Description = "btq, product of:"; } else { result.AddDetail(payloadExpl); result.Value = payloadExpl.Value; result.Description = "btq(includeSpanScore=false), result of:"; } result.Match = true; // LUCENE-1303 return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } public override int GetHashCode() { const int prime = 31; int result = base.GetHashCode(); result = prime * result + ((m_function == null) ? 0 : m_function.GetHashCode()); result = prime * result + (includeSpanScore ? 1231 : 1237); return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (!base.Equals(obj)) { return false; } if (this.GetType() != obj.GetType()) { return false; } PayloadTermQuery other = (PayloadTermQuery)obj; if (m_function == null) { if (other.m_function != null) { return false; } } else if (!m_function.Equals(other.m_function)) { return false; } if (includeSpanScore != other.includeSpanScore) { return false; } return true; } } }
{ "content_hash": "0c07e820cb054c00accd49c52cd9fc32", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 284, "avg_line_length": 43.948616600790515, "alnum_prop": 0.5170428995413257, "repo_name": "Ref12/Codex", "id": "8bab46e54986d34fd3bf80bb86bbffa254c31100", "size": "11980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lucenenet/src/Lucene.Net/Search/Payloads/PayloadTermQuery.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "191" }, { "name": "Batchfile", "bytes": "6492" }, { "name": "C#", "bytes": "27195570" }, { "name": "CSS", "bytes": "149021" }, { "name": "Dockerfile", "bytes": "4544" }, { "name": "Gnuplot", "bytes": "2444" }, { "name": "HTML", "bytes": "92908" }, { "name": "Java", "bytes": "1891" }, { "name": "JavaScript", "bytes": "163538" }, { "name": "PowerShell", "bytes": "77482" }, { "name": "Shell", "bytes": "3436" }, { "name": "TypeScript", "bytes": "102306" } ], "symlink_target": "" }
.. index:: intermediate object-oriented development object-oriented development COMP 413: Intermediate Object-Oriented Development ======================================================= Credit Hours ----------------------------------- 3 Prerequisites ---------------------------- :doc:`comp271` (strictly enforced) Description ---------------------------- Object-orientation continues to be a dominant approach to software development. This intermediate programming-intensive course studies the use of classes and objects with an emphasis on collaboration among objects. **Overall Series of Object-Oriented Courses** - :doc:`comp170` (CS1) - simple objects representing scalars - :doc:`comp271` (CS2) - collections of simple objects - :doc:`comp313` / :doc:`comp413` - complex, interacting objects; basic design patterns - :doc:`comp373` / :doc:`comp473` - advanced design patterns and topics such as AOP(Aspect-Oriented programming) :doc:`comp313` / :doc:`comp413` is also a prerequisite for other advanced software courses. Students interested in advanced software courses are encouraged to take :doc:`comp313` / :doc:`comp413` as soon as they have completed :doc:`comp271` so as to be eligible for these further courses. **Course Topics** - Data Structures of various types – linear vs. nonlinear, indexing vs. non-indexing, position vs. value-oriented - Advanced Java, e.g. interfaces, annotations, exceptions, generics, collections, boxing/unboxing, array objects - Object Modeling – UML, use cases and activity diagrams, class diagrams, archetypes, interaction diagrams - Design by contract, interfaces, refactoring & generalization, design patterns (Adapter, Decorator, Composite, Strategy, Iterator, Abstract Factory, Visitor, …) - Agile Development Process – evolutionary design, test-driven development, refactoring, … - Tools – Eclipse, Subversion, JUnit, JMock, Ant, … - Techniques – object pooling, garbage collection, performance profiling (NetBeans) Outcome --------- A thorough understanding of the principles of object-orientation: abstraction, delegation, inheritance, and polymorphism; exposure to basic design patterns; programming experience in mainstream object-oriented languages such as C++ and Java. You will take your software development abilities to the next level by building on your knowledge of data structures. You will learn to design and implement more complex programs using good software engineering practices, including: - Designing with interfaces and composition - Design patterns - Refactoring - Test-driven development (TDD) Syllabi ------------- .. csv-table:: :header: "Semester/Year", "Instructor", "URL" :widths: 15, 25, 50 "Spring 2014", "Dr. Yacobellis", "https://luc.box.com/s/m24hdedq5ghw8ecgr7gjtdtkg71juvhy" "Fall 2013", "Dr. Läufer", "https://luc.box.com/s/m24hdedq5ghw8ecgr7gjtdtkg71juvhy"
{ "content_hash": "20e35aed7971fe2f913ed50137b4b2aa", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 289, "avg_line_length": 41.6, "alnum_prop": 0.7249313186813187, "repo_name": "tombiju/coursedescriptions", "id": "e8a4ef488780d88c3bf243886ae38a4e632019a5", "size": "2929", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/comp413.rst", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "65852" }, { "name": "Batchfile", "bytes": "5109" }, { "name": "C++", "bytes": "64557" }, { "name": "HTML", "bytes": "1124" }, { "name": "Makefile", "bytes": "5581" }, { "name": "Pascal", "bytes": "21633" }, { "name": "Python", "bytes": "66796" }, { "name": "Shell", "bytes": "1364" } ], "symlink_target": "" }
import { Incident } from "incident"; import util from "util"; import * as httpIo from "../interfaces/http-io"; export namespace UnexpectedHttpStatusError { export type Name = "UnexpectedHttpStatus"; export const name: Name = "UnexpectedHttpStatus"; export interface Data { response: httpIo.Response; expected: Set<number>; request?: httpIo.GetOptions | httpIo.PostOptions | httpIo.PutOptions; } export type Cause = undefined; } export type UnexpectedHttpStatusError = Incident<UnexpectedHttpStatusError.Data, UnexpectedHttpStatusError.Name, UnexpectedHttpStatusError.Cause>; export namespace UnexpectedHttpStatusError { export type Type = UnexpectedHttpStatusError; export function format({expected, response, request}: Data) { const msg: string = `Received response with the HTTP status code \`${response.statusCode}\`` + ` but expected one of ${util.inspect(expected)}.`; if (request === undefined) { return `${msg} Response: ${util.inspect(response)}`; } else { return `${msg} Request: ${util.inspect(request)}, Response: ${util.inspect(response)}`; } } export function create( response: httpIo.Response, expected: Set<number>, request?: httpIo.GetOptions | httpIo.PostOptions | httpIo.PutOptions, ): UnexpectedHttpStatusError { return new Incident(name, {response, expected, request}, format); } } export namespace MissingHeaderError { export type Name = "MissingHeader"; export const name: Name = "MissingHeader"; export interface Data { response: httpIo.Response; headerName: string; request?: httpIo.GetOptions | httpIo.PostOptions | httpIo.PutOptions; } export type Cause = undefined; } export type MissingHeaderError = Incident<MissingHeaderError.Data, MissingHeaderError.Name, MissingHeaderError.Cause>; export namespace MissingHeaderError { export type Type = MissingHeaderError; export function format({headerName, response, request}: Data) { const msg: string = `Received response with headers \`${util.inspect(response.headers)}\`` + ` where the expected header ${util.inspect(headerName)} is missing.`; if (request === undefined) { return `${msg} Response: ${util.inspect(response)}`; } else { return `${msg} Request: ${util.inspect(request)}, Response: ${util.inspect(response)}`; } } export function create( response: httpIo.Response, headerName: string, request?: httpIo.GetOptions | httpIo.PostOptions | httpIo.PutOptions, ): MissingHeaderError { return new Incident(name, {response, headerName, request}, format); } } export namespace RequestError { export type Name = "Request"; export const name: Name = "Request"; export interface Data { request: httpIo.GetOptions | httpIo.PostOptions | httpIo.PutOptions; } export type Cause = Error; } export type RequestError = Incident<RequestError.Data, RequestError.Name, RequestError.Cause>; export namespace RequestError { export type Type = RequestError; export function format({request}: Data) { return `The following HTTP request failed: "${JSON.stringify(request)}"`; } export function create( cause: Error, request: httpIo.GetOptions | httpIo.PostOptions | httpIo.PutOptions, ): RequestError { return new Incident(cause, name, {request}, format); } }
{ "content_hash": "909ff03ddf768f1caa99a6b3f0172267", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 96, "avg_line_length": 30.825688073394495, "alnum_prop": 0.7116071428571429, "repo_name": "ocilo/skype-http", "id": "c2329bde89a752670f364f70fd0163831ab7e4a8", "size": "3360", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/lib/errors/http.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "200242" }, { "name": "JavaScript", "bytes": "386" }, { "name": "Shell", "bytes": "7407" }, { "name": "TypeScript", "bytes": "197261" } ], "symlink_target": "" }
<div class="container"> <div class="row" > <div class="col-xs-12" ng-if="!showOffer"> <h3>{{message}}</h3> </div> <div class="row pull-right"> <a ng-show="currentUser.id" ui-sref="app.offer" class = "btn btn-info"> Add your offer</a> </div> <div class="col-xs-12" ng-if="showOffer"> <div class="row"> <div class="products-row"> <div class="col-md-3 product-grids" ng-repeat="offer in offers | filter: {mychannel:'sell'} | filter: global.search"> <div class="agile-products"> <div ng-show="offer.label" class="new-tag"><h6>{{offer.label}}</h6></div> <a ui-sref="app.offerdetails({id: offer.id})" class="img-responsive"> <img ng-src="{{offer.images[0]}}" alt="{{offer.name}}" style="width:200px;height:200px"> </a> <div class="agile-product-text"> <h5><a ui-sref="app.offerdetails({id: offer.id})">{{offer.name}}</a></h5> <h6><del>{{offer.bprice | currency}}</del>{{offer.price | currency}}</h6> <div class="pw3ls-cart"> <ngcart-addtocart id="{{ offer.id }}" name="{{offer.name }}" price="{{offer.price }}" quantity="1" quantity-max="10"><i class="fa fa-cart-plus" aria-hidden="true"></i>Add to Cart</ngcart-addtocart></div> </div> </div></div> </div> </div> </div></div></div>
{ "content_hash": "d66652cddb47827127d2925444ef39c9", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 228, "avg_line_length": 53.172413793103445, "alnum_prop": 0.49546044098573283, "repo_name": "tahdy/am-store", "id": "057a6b9b8aa46ac7772a793c7f0c86d9d3baacc8", "size": "1542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/views/sell.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "85659" }, { "name": "JavaScript", "bytes": "450386" } ], "symlink_target": "" }
package io.github.astrapi69.mystic.crypt.processor.bruteforce; import java.util.Arrays; /** * The class {@link BruteForceProcessor} can process a brute force for find a password. For an * example see the unit test. * * @version 1.0 * @author Asterios Raptis */ public class BruteForceProcessor { /** The possibles characters. */ private final char[] possiblesCharacters; /** The current attempt. */ private char[] currentAttempt; /** * Instantiates a new {@link BruteForceProcessor} object. * * @param possiblesCharacters * the possibles characters * @param attemptLength * the attempt length */ public BruteForceProcessor(final char[] possiblesCharacters, final int attemptLength) { this.possiblesCharacters = possiblesCharacters; this.currentAttempt = new char[attemptLength]; Arrays.fill(currentAttempt, possiblesCharacters[0]); } /** * Gets the current attempt. * * @return the current attempt */ public String getCurrentAttempt() { return new String(currentAttempt); } /** * Increment. */ public void increment() { int index = currentAttempt.length - 1; while (0 <= index) { if (currentAttempt[index] == possiblesCharacters[possiblesCharacters.length - 1]) { if (index == 0) { currentAttempt = new char[currentAttempt.length + 1]; Arrays.fill(currentAttempt, possiblesCharacters[0]); break; } else { currentAttempt[index] = possiblesCharacters[0]; index--; } } else { currentAttempt[index] = possiblesCharacters[Arrays.binarySearch(possiblesCharacters, currentAttempt[index]) + 1]; break; } } } }
{ "content_hash": "7c40c79f0266dcd8e8d2c4149921421f", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 94, "avg_line_length": 22.039473684210527, "alnum_prop": 0.6782089552238806, "repo_name": "astrapi69/mystic-crypt", "id": "172e244ed809bcbf3b9bccc41d64fd3a1c191b10", "size": "2820", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/io/github/astrapi69/mystic/crypt/processor/bruteforce/BruteForceProcessor.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "5084" }, { "name": "Java", "bytes": "554243" } ], "symlink_target": "" }
require 'spec_helper' describe "Connection" do before(:all) do @raw_conn = get_connection @conn = PLSQL::Connection.create( @raw_conn ) end after(:all) do unless defined?(JRuby) @raw_conn.logoff rescue nil else @raw_conn.close rescue nil end end describe "create and destroy" do before(:all) do @raw_conn1 = get_connection end before(:each) do @conn1 = PLSQL::Connection.create( @raw_conn1 ) end it "should create connection" do expect(@conn1.raw_connection).to eq @raw_conn1 end unless defined?(JRuby) it "should be oci connection" do expect(@conn1).to be_oci expect(@conn1.raw_driver).to eq :oci end else it "should be jdbc connection" do expect(@conn1).to be_jdbc expect(@conn1.raw_driver).to eq :jdbc end end it "should logoff connection" do expect(@conn1.logoff).to be true end end # Ruby 1.8 and 1.9 unless defined?(JRuby) describe "OCI data type conversions" do it "should translate PL/SQL VARCHAR to Ruby String" do expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => 100)).to eq [String, 100] expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => nil)).to eq [String, 32767] end it "should translate PL/SQL VARCHAR2 to Ruby String" do expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => 100)).to eq [String, 100] expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => nil)).to eq [String, 32767] end it "should translate PL/SQL CLOB to Ruby String" do expect(@conn.plsql_to_ruby_data_type(:data_type => "CLOB", :data_length => 100_000)).to eq [OCI8::CLOB, nil] expect(@conn.plsql_to_ruby_data_type(:data_type => "CLOB", :data_length => nil)).to eq [OCI8::CLOB, nil] end it "should translate PL/SQL NUMBER to Ruby OraNumber" do expect(@conn.plsql_to_ruby_data_type(:data_type => "NUMBER", :data_length => 15)).to eq [OraNumber, nil] end it "should translate PL/SQL DATE to Ruby DateTime" do expect(@conn.plsql_to_ruby_data_type(:data_type => "DATE", :data_length => nil)).to eq [DateTime, nil] end it "should translate PL/SQL TIMESTAMP to Ruby Time" do expect(@conn.plsql_to_ruby_data_type(:data_type => "TIMESTAMP", :data_length => nil)).to eq [Time, nil] end it "should not translate Ruby Fixnum when OraNumber type specified" do expect(@conn.ruby_value_to_ora_value(100, OraNumber)).to eql(100) end it "should translate Ruby Bignum value to OraNumber when OraNumber type specified" do ora_number = @conn.ruby_value_to_ora_value(12345678901234567890, OraNumber) expect(ora_number.class).to eq OraNumber expect(ora_number.to_s).to eq "12345678901234567890" # OraNumber has more numeric comparison methods in ruby-oci8 2.0 expect(ora_number).to eq OraNumber.new("12345678901234567890") if OCI8::VERSION >= '2.0.0' end it "should translate Ruby String value to OCI8::CLOB when OCI8::CLOB type specified" do large_text = "x" * 100_000 ora_value = @conn.ruby_value_to_ora_value(large_text, OCI8::CLOB) expect(ora_value.class).to eq OCI8::CLOB expect(ora_value.size).to eq 100_000 ora_value.rewind expect(ora_value.read).to eq large_text end it "should translate Oracle OraNumber integer value to Fixnum" do expect(@conn.ora_value_to_ruby_value(OraNumber.new(100))).to eql(100) end it "should translate Oracle OraNumber float value to BigDecimal" do expect(@conn.ora_value_to_ruby_value(OraNumber.new(100.11))).to eql(BigDecimal("100.11")) end # ruby-oci8 2.0 returns DATE as Time or DateTime if OCI8::VERSION < '2.0.0' it "should translate Oracle OraDate value to Time" do now = OraDate.now expect(@conn.ora_value_to_ruby_value(now)).to eql(now.to_time) end end it "should translate Oracle CLOB value to String" do large_text = "x" * 100_000 clob = OCI8::CLOB.new(@raw_conn, large_text) expect(@conn.ora_value_to_ruby_value(clob)).to eq large_text end end # JRuby else describe "JDBC data type conversions" do it "should translate PL/SQL VARCHAR to Ruby String" do expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => 100)).to eq [String, 100] expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR", :data_length => nil)).to eq [String, 32767] end it "should translate PL/SQL VARCHAR2 to Ruby String" do expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => 100)).to eq [String, 100] expect(@conn.plsql_to_ruby_data_type(:data_type => "VARCHAR2", :data_length => nil)).to eq [String, 32767] end it "should translate PL/SQL NUMBER to Ruby BigDecimal" do expect(@conn.plsql_to_ruby_data_type(:data_type => "NUMBER", :data_length => 15)).to eq [BigDecimal, nil] end it "should translate PL/SQL DATE to Ruby DateTime" do expect(@conn.plsql_to_ruby_data_type(:data_type => "DATE", :data_length => nil)).to eq [DateTime, nil] end it "should translate PL/SQL TIMESTAMP to Ruby Time" do expect(@conn.plsql_to_ruby_data_type(:data_type => "TIMESTAMP", :data_length => nil)).to eq [Time, nil] end it "should not translate Ruby Fixnum when BigDecimal type specified" do expect(@conn.ruby_value_to_ora_value(100, BigDecimal)).to eq java.math.BigDecimal.new(100) end it "should translate Ruby String to string value" do expect(@conn.ruby_value_to_ora_value(1.1, String)).to eq '1.1' end it "should translate Ruby Bignum value to BigDecimal when BigDecimal type specified" do big_decimal = @conn.ruby_value_to_ora_value(12345678901234567890, BigDecimal) expect(big_decimal).to eq java.math.BigDecimal.new("12345678901234567890") end it "should translate Ruby String value to Java::OracleSql::CLOB when Java::OracleSql::CLOB type specified" do large_text = "x" * 100_000 ora_value = @conn.ruby_value_to_ora_value(large_text, Java::OracleSql::CLOB) expect(ora_value.class).to eq Java::OracleSql::CLOB expect(ora_value.length).to eq 100_000 expect(ora_value.getSubString(1, ora_value.length)).to eq large_text ora_value.freeTemporary end it "should translate Ruby nil value to nil when Java::OracleSql::CLOB type specified" do ora_value = @conn.ruby_value_to_ora_value(nil, Java::OracleSql::CLOB) expect(ora_value).to be_nil end it "should translate Oracle BigDecimal integer value to Fixnum" do expect(@conn.ora_value_to_ruby_value(BigDecimal("100"))).to eql(100) end it "should translate Oracle BigDecimal float value to BigDecimal" do expect(@conn.ora_value_to_ruby_value(BigDecimal("100.11"))).to eql(BigDecimal("100.11")) end it "should translate Oracle CLOB value to String" do large_text = "āčē" * 100_000 clob = @conn.ruby_value_to_ora_value(large_text, Java::OracleSql::CLOB) expect(@conn.ora_value_to_ruby_value(clob)).to eq large_text clob.freeTemporary end it "should translate empty Oracle CLOB value to nil" do clob = @conn.ruby_value_to_ora_value(nil, Java::OracleSql::CLOB) expect(@conn.ora_value_to_ruby_value(clob)).to be_nil end end end describe "SQL SELECT statements" do it "should execute SQL statement and return first result" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_first("SELECT 'abc',123,123.456, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') FROM dual")).to eq ["abc",123,123.456,@now] end it "should execute SQL statement and return first result as hash" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_hash_first("SELECT 'abc' a, 123 b, 123.456 c, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}', 'YYYY-MM-DD HH24:MI:SS') d FROM dual")).to eq({:a => "abc", :b => 123, :c => 123.456, :d => @now}) end it "should execute SQL statement with bind parameters and return first result" do @today = Date.parse("2008-05-31") @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_first("SELECT :1,:2,:3,:4,:5 FROM dual", 'abc',123,123.456,@now,@today)).to eq ["abc",123,123.456,@now,Time.parse(@today.to_s)] end it "should execute SQL statement with NULL values and return first result" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_first("SELECT NULL,123,123.456, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') FROM dual")).to eq [nil,123,123.456,@now] end if defined?(JRuby) it "should execute SQL statement with NULL values as bind parameters and return first result" do @today = Date.parse("2008-05-31") @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_first("SELECT :1,:2,:3,:4,:5 FROM dual", nil,123,123.456,@now,@today)).to eq [nil,123,123.456,@now,Time.parse(@today.to_s)] end end it "should execute SQL statement and return all results" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_all("SELECT 'abc',123,123.456, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') FROM dual UNION ALL SELECT 'abc',123,123.456, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') FROM dual")).to eq [["abc",123,123.456,@now],["abc",123,123.456,@now]] end it "should execute SQL statement and return all results as hash" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_hash_all("SELECT 'abc' a, 123 b, 123.456 c, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') d FROM dual UNION ALL SELECT 'def' a, 123 b, 123.456 c, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') d FROM dual")).to eq [{:a=>"abc",:b=>123,:c=>123.456,:d=>@now},{:a=>"def",:b=>123,:c=>123.456,:d=>@now}] end it "should execute SQL statement with bind parameters and return all results" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_all("SELECT :1,:2,:3,:4 FROM dual UNION ALL SELECT :1,:2,:3,:4 FROM dual", 'abc',123,123.456,@now,'abc',123,123.456,@now)).to eq [["abc",123,123.456,@now],["abc",123,123.456,@now]] end it "should execute SQL statement and yield all results in block" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_all("SELECT 'abc',123,123.456, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') FROM dual UNION ALL SELECT 'abc',123,123.456, TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') FROM dual") do |r| expect(r).to eq ["abc",123,123.456,@now] end).to eq 2 end it "should execute SQL statement with bind parameters and yield all results in block" do @now = Time.local(2008,05,31,23,22,11) expect(@conn.select_all("SELECT :1,:2,:3,:4 FROM dual UNION ALL SELECT :1,:2,:3,:4 FROM dual", 'abc',123,123.456,@now,'abc',123,123.456,@now) do |r| expect(r).to eq ["abc",123,123.456,@now] end).to eq 2 end end describe "PL/SQL procedures" do before(:all) do @random = rand(1000) @now = Time.local(2008,05,31,23,22,11) sql = <<-SQL CREATE OR REPLACE FUNCTION test_add_random (p_number NUMBER, p_varchar IN OUT VARCHAR2, p_date IN OUT DATE) RETURN NUMBER IS BEGIN RETURN p_number + #{@random}; END test_add_random; SQL expect(@conn.exec(sql)).to be true end after(:all) do @conn.exec "DROP FUNCTION test_add_random" end it "should parse PL/SQL procedure call and bind parameters and exec and get bind parameter value" do sql = <<-SQL BEGIN :result := test_add_random (:p_number, :p_varchar, :p_date); END; SQL cursor = @conn.parse(sql) cursor.bind_param(":result", nil, :data_type => 'NUMBER', :in_out => 'OUT') cursor.bind_param(":p_number", 100, :data_type => 'NUMBER', :in_out => 'IN') cursor.bind_param(":p_varchar", "abc", :data_type => 'VARCHAR2', :in_out => 'IN/OUT') cursor.bind_param(":p_date", @now, :data_type => 'DATE', :in_out => 'IN/OUT') cursor.exec expect(cursor[":result"]).to eq @random + 100 expect(cursor[":p_varchar"]).to eq "abc" expect(cursor[":p_date"]).to eq @now expect(cursor.close).to be_nil end end describe "commit and rollback" do before(:all) do expect(@conn.exec("CREATE TABLE test_commit (dummy VARCHAR2(100))")).to be true @conn.autocommit = false expect(@conn).not_to be_autocommit end after(:all) do @conn.exec "DROP TABLE test_commit" end after(:each) do @conn.exec "DELETE FROM test_commit" @conn.commit end it "should do commit" do @conn.exec("INSERT INTO test_commit VALUES ('test')") @conn.commit expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 1 end it "should do rollback" do @conn.exec("INSERT INTO test_commit VALUES ('test')") @conn.rollback expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 0 end it "should do commit and rollback should not undo commited transaction" do @conn.exec("INSERT INTO test_commit VALUES ('test')") @conn.commit @conn.rollback expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 1 end end describe "prefetch rows" do after(:each) do @conn.prefetch_rows = 1 # set back to default end it "should set prefetch rows for connection" do sql = "SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual" @conn.prefetch_rows = 2 expect { @conn.cursor_from_query(sql) }.to raise_error(/divisor is equal to zero/) @conn.prefetch_rows = 1 expect { @conn.cursor_from_query(sql) }.not_to raise_error end it "should fetch just one row when using select_first" do sql = "SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual" @conn.prefetch_rows = 2 expect { @conn.select_first(sql) }.not_to raise_error end end describe "describe synonym" do before(:all) do @conn.exec "CREATE SYNONYM hr.synonym_for_dual FOR sys.dual" end after(:all) do @conn.exec "DROP SYNONYM hr.synonym_for_dual" end it "should describe local synonym" do expect(@conn.describe_synonym('HR','SYNONYM_FOR_DUAL')).to eq ['SYS', 'DUAL'] expect(@conn.describe_synonym('hr','synonym_for_dual')).to eq ['SYS', 'DUAL'] expect(@conn.describe_synonym(:hr,:synonym_for_dual)).to eq ['SYS', 'DUAL'] end it "should return nil on non-existing synonym" do expect(@conn.describe_synonym('HR','SYNONYM_FOR_XXX')).to be_nil expect(@conn.describe_synonym('hr','synonym_for_xxx')).to be_nil expect(@conn.describe_synonym(:hr,:synonym_for_xxx)).to be_nil end it "should describe public synonym" do expect(@conn.describe_synonym('PUBLIC','DUAL')).to eq ['SYS', 'DUAL'] expect(@conn.describe_synonym('PUBLIC','dual')).to eq ['SYS', 'DUAL'] expect(@conn.describe_synonym('PUBLIC',:dual)).to eq ['SYS', 'DUAL'] end end describe "session information" do it "should get database version" do # using Oracle version 10.2.0.4 for unit tests expect(@conn.database_version).to eq DATABASE_VERSION.split('.').map{|n| n.to_i} end it "should get session ID" do expect(@conn.session_id).to eq @conn.select_first("SELECT USERENV('SESSIONID') FROM dual")[0].to_i end end describe "drop ruby temporary tables" do after(:all) do @conn.drop_all_ruby_temporary_tables end it "should drop all ruby temporary tables" do tmp_table = "ruby_111_222_333" @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))" expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error @conn.drop_all_ruby_temporary_tables expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/) end it "should drop current session ruby temporary tables" do tmp_table = "ruby_#{@conn.session_id}_222_333" @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))" expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error @conn.drop_session_ruby_temporary_tables expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/) end it "should not drop other session ruby temporary tables" do tmp_table = "ruby_#{@conn.session_id+1}_222_333" @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))" expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error @conn.drop_session_ruby_temporary_tables expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error end end describe "logoff" do before(:each) do # restore connection before each test reconnect_connection end after(:all) do @conn.exec "DROP TABLE test_dummy_table" rescue nil end def reconnect_connection @raw_conn = get_connection @conn = PLSQL::Connection.create( @raw_conn ) end it "should drop current session ruby temporary tables" do tmp_table = "ruby_#{@conn.session_id}_222_333" @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))" expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error @conn.logoff reconnect_connection expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/) end it "should rollback any uncommited transactions" do tmp_table = "ruby_#{@conn.session_id}_222_333" old_autocommit = @conn.autocommit? @conn.autocommit = false @conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))" @conn.exec "CREATE TABLE test_dummy_table (dummy CHAR(1))" @conn.exec "INSERT INTO test_dummy_table VALUES ('1')" # logoff will drop ruby temporary tables, it should do rollback before drop table @conn.logoff reconnect_connection expect(@conn.select_first("SELECT * FROM test_dummy_table")).to eq nil @conn.autocommit = old_autocommit end end end
{ "content_hash": "443ac93e4435c2f92a72c9f501ac766e", "timestamp": "", "source": "github", "line_count": 503, "max_line_length": 116, "avg_line_length": 38.17097415506958, "alnum_prop": 0.6245833333333334, "repo_name": "jgebal/ruby-plsql", "id": "dc74007a6c2f4a1b79e59103bdf2b5c34fc4c87a", "size": "19222", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/plsql/connection_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3524" }, { "name": "Ruby", "bytes": "301087" }, { "name": "Shell", "bytes": "2056" } ], "symlink_target": "" }