hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
8dd06b5f537a0ef25958d71cdf0307d9c122f74f
2,957
js
JavaScript
lib/core/shared/sdk/funnelProtocol.js
Richard-DEPIERRE/kuzzle
67a6d403dff827ba0f9d32f5e82140ca00fcabf9
[ "Apache-2.0" ]
1,280
2015-08-25T07:49:06.000Z
2022-03-26T06:07:15.000Z
lib/core/shared/sdk/funnelProtocol.js
Richard-DEPIERRE/kuzzle
67a6d403dff827ba0f9d32f5e82140ca00fcabf9
[ "Apache-2.0" ]
2,214
2015-08-26T13:38:45.000Z
2022-03-31T17:14:56.000Z
lib/core/shared/sdk/funnelProtocol.js
Richard-DEPIERRE/kuzzle
67a6d403dff827ba0f9d32f5e82140ca00fcabf9
[ "Apache-2.0" ]
141
2015-09-17T09:53:23.000Z
2022-03-16T07:32:30.000Z
/* * Kuzzle, a backend software, self-hostable and ready to use * to power modern apps * * Copyright 2015-2020 Kuzzle * mailto: support AT kuzzle.io * website: http://kuzzle.io * * 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 * * https://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. */ 'use strict'; const { KuzzleEventEmitter } = require('kuzzle-sdk'); const { Request } = require('../../../api/request'); const kerror = require('../../../kerror'); const { hilightUserCode } = require('../../../util/stackTrace'); class FunnelProtocol extends KuzzleEventEmitter { constructor() { super(); this.id = 'funnel'; this.connectionId = null; /** * Realtime notifications are sent by the InternalProtocol * through the internal event system. */ global.kuzzle.on('core:network:internal:message', message => { // Send the notifications to the SDK for the internal Room mechanism this.emit(message.room, message); }); } isReady () { return true; } /** * Hydrate the user and execute SDK query */ async query (request) { if (! this.connectionId) { this.connectionId = await global.kuzzle.ask('core:network:internal:connectionId:get'); } const requestOptions = { connection: { id: this.connectionId, protocol: this.id }, user: null, }; // Validate and use the provided request.kuid if (request.__kuid__) { if (typeof request.__kuid__ !== 'string') { throw kerror.get('plugin', 'context', 'invalid_user'); } // Get the user and store it in this context to prevent any possible race conditions requestOptions.user = await global.kuzzle.ask('core:security:user:get', request.__kuid__); } const kuzzleRequest = new Request(request, requestOptions); try { if (requestOptions.user && request.__checkRights__ && ! await requestOptions.user.isActionAllowed(kuzzleRequest) ) { throw kerror.get( 'security', 'rights', 'forbidden', kuzzleRequest.input.controller, kuzzleRequest.input.action, requestOptions.user._id); } const result = await global.kuzzle.funnel.executePluginRequest(kuzzleRequest); return { result }; } catch (error) { if (error.stack) { error.stack = error.stack.split('\n').map(hilightUserCode).join('\n'); } throw error; } } } module.exports = FunnelProtocol;
27.896226
96
0.646263
1bed020c34bc3496a49b5f6d0d8f7eb5ce66e12b
890
rb
Ruby
lib/mail/gpg/rails/action_mailer_base_patch.rb
duckdalbe/mail-gpg
b21083369d46e9ad8e43aa6d561504c3a4179425
[ "MIT" ]
53
2015-01-07T03:06:52.000Z
2021-12-16T11:21:25.000Z
lib/mail/gpg/rails/action_mailer_base_patch.rb
duckdalbe/mail-gpg
b21083369d46e9ad8e43aa6d561504c3a4179425
[ "MIT" ]
42
2015-04-25T13:46:52.000Z
2021-07-02T20:35:03.000Z
lib/mail/gpg/rails/action_mailer_base_patch.rb
duckdalbe/mail-gpg
b21083369d46e9ad8e43aa6d561504c3a4179425
[ "MIT" ]
22
2015-05-25T12:35:41.000Z
2021-04-13T15:54:40.000Z
require 'action_mailer/base' module Mail module Gpg module Rails module ActionMailerPatch def self.apply unless ActionMailer::Base < InstanceMethods ActionMailer::Base.prepend InstanceMethods ActionMailer::Base.singleton_class.prepend ClassMethods end end module InstanceMethods def mail(headers = {}, &block) headers = headers.dup gpg_options = headers.delete :gpg super(headers, &block).tap do |m| if gpg_options m.gpg gpg_options end end end end module ClassMethods def deliver_mail(mail, &block) super(mail) do Mail::Gpg::DeliveryHandler.deliver_mail mail, &block end end end end end end end
21.190476
67
0.54382
85197502ca6341e00d70de58b8f2cbacc989e035
31,041
cs
C#
Rias/Migrations/20210530111302_UpdatedAt.Designer.cs
FenikkusuKoneko/RiasBot
89d8d60b3107a363c4692bc04fc3a0a76409b0ff
[ "MIT" ]
12
2020-05-04T05:46:18.000Z
2021-07-26T08:32:53.000Z
Rias/Migrations/20210530111302_UpdatedAt.Designer.cs
FenikkusuNeko/RiasBot
b00d96800ca3e99b0d795392650984b4e632e735
[ "MIT" ]
null
null
null
Rias/Migrations/20210530111302_UpdatedAt.Designer.cs
FenikkusuNeko/RiasBot
b00d96800ca3e99b0d795392650984b4e632e735
[ "MIT" ]
6
2018-04-23T21:57:36.000Z
2019-08-12T16:26:47.000Z
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using Rias.Database; using Rias.Models; namespace Rias.Migrations { [DbContext(typeof(RiasDbContext))] [Migration("20210530111302_UpdatedAt")] partial class UpdatedAt { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasPostgresEnum(null, "last_charge_status", new[] { "paid", "declined", "pending", "refunded", "fraud", "other" }) .HasPostgresEnum(null, "patron_status", new[] { "active_patron", "declined_patron", "former_patron" }) .HasAnnotation("Relational:MaxIdentifierLength", 63) .HasAnnotation("ProductVersion", "5.0.5") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); modelBuilder.Entity("Rias.Database.Entities.CharacterEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("CharacterId") .HasColumnType("integer") .HasColumnName("character_id"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<string>("ImageUrl") .HasColumnType("text") .HasColumnName("image_url"); b.Property<string>("Name") .HasColumnType("text") .HasColumnName("name"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<string>("Url") .HasColumnType("text") .HasColumnName("url"); b.HasKey("Id") .HasName("pk_characters"); b.HasAlternateKey("CharacterId") .HasName("ak_characters_character_id"); b.HasIndex("CharacterId") .IsUnique() .HasDatabaseName("ix_characters_character_id"); b.ToTable("characters"); }); modelBuilder.Entity("Rias.Database.Entities.CustomCharacterEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("CharacterId") .HasColumnType("integer") .HasColumnName("character_id"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<string>("Description") .HasColumnType("text") .HasColumnName("description"); b.Property<string>("ImageUrl") .HasColumnType("text") .HasColumnName("image_url"); b.Property<string>("Name") .HasColumnType("text") .HasColumnName("name"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.HasKey("Id") .HasName("pk_custom_characters"); b.HasAlternateKey("CharacterId") .HasName("ak_custom_characters_character_id"); b.HasIndex("CharacterId") .IsUnique() .HasDatabaseName("ix_custom_characters_character_id"); b.ToTable("custom_characters"); }); modelBuilder.Entity("Rias.Database.Entities.CustomWaifuEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<string>("ImageUrl") .HasColumnType("text") .HasColumnName("image_url"); b.Property<bool>("IsSpecial") .HasColumnType("boolean") .HasColumnName("is_special"); b.Property<string>("Name") .HasColumnType("text") .HasColumnName("name"); b.Property<int>("Position") .HasColumnType("integer") .HasColumnName("position"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_custom_waifus"); b.ToTable("custom_waifus"); }); modelBuilder.Entity("Rias.Database.Entities.GuildEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<decimal>("AutoAssignableRoleId") .HasColumnType("numeric(20,0)") .HasColumnName("auto_assignable_role_id"); b.Property<string>("ByeMessage") .HasColumnType("text") .HasColumnName("bye_message"); b.Property<bool>("ByeNotification") .HasColumnType("boolean") .HasColumnName("bye_notification"); b.Property<decimal>("ByeWebhookId") .HasColumnType("numeric(20,0)") .HasColumnName("bye_webhook_id"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<bool>("DeleteCommandMessage") .HasColumnType("boolean") .HasColumnName("delete_command_message"); b.Property<string>("GreetMessage") .HasColumnType("text") .HasColumnName("greet_message"); b.Property<bool>("GreetNotification") .HasColumnType("boolean") .HasColumnName("greet_notification"); b.Property<decimal>("GreetWebhookId") .HasColumnType("numeric(20,0)") .HasColumnName("greet_webhook_id"); b.Property<decimal>("GuildId") .HasColumnType("numeric(20,0)") .HasColumnName("guild_id"); b.Property<string>("Locale") .HasColumnType("text") .HasColumnName("locale"); b.Property<decimal>("ModLogChannelId") .HasColumnType("numeric(20,0)") .HasColumnName("mod_log_channel_id"); b.Property<decimal>("MuteRoleId") .HasColumnType("numeric(20,0)") .HasColumnName("mute_role_id"); b.Property<string>("Prefix") .HasColumnType("text") .HasColumnName("prefix"); b.Property<int>("PunishmentWarningsRequired") .HasColumnType("integer") .HasColumnName("punishment_warnings_required"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<string>("WarningPunishment") .HasColumnType("text") .HasColumnName("warning_punishment"); b.Property<decimal[]>("XpIgnoredChannels") .HasColumnType("numeric[]") .HasColumnName("xp_ignored_channels"); b.Property<decimal>("XpIgnoredRoleId") .HasColumnType("numeric(20,0)") .HasColumnName("xp_ignored_role_id"); b.Property<string>("XpLevelUpMessage") .HasColumnType("text") .HasColumnName("xp_level_up_message"); b.Property<string>("XpLevelUpRoleRewardMessage") .HasColumnType("text") .HasColumnName("xp_level_up_role_reward_message"); b.Property<bool>("XpNotification") .HasColumnType("boolean") .HasColumnName("xp_notification"); b.Property<decimal>("XpWebhookId") .HasColumnType("numeric(20,0)") .HasColumnName("xp_webhook_id"); b.HasKey("Id") .HasName("pk_guilds"); b.HasIndex("GuildId") .IsUnique() .HasDatabaseName("ix_guilds_guild_id"); b.ToTable("guilds"); }); modelBuilder.Entity("Rias.Database.Entities.GuildXpRoleEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<decimal>("GuildId") .HasColumnType("numeric(20,0)") .HasColumnName("guild_id"); b.Property<int>("Level") .HasColumnType("integer") .HasColumnName("level"); b.Property<decimal>("RoleId") .HasColumnType("numeric(20,0)") .HasColumnName("role_id"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.HasKey("Id") .HasName("pk_guild_xp_roles"); b.HasIndex("GuildId", "RoleId") .IsUnique() .HasDatabaseName("ix_guild_xp_roles_guild_id_role_id"); b.ToTable("guild_xp_roles"); }); modelBuilder.Entity("Rias.Database.Entities.MembersEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<decimal>("GuildId") .HasColumnType("numeric(20,0)") .HasColumnName("guild_id"); b.Property<bool>("IsMuted") .HasColumnType("boolean") .HasColumnName("is_muted"); b.Property<bool>("IsXpIgnored") .HasColumnType("boolean") .HasColumnName("is_xp_ignored"); b.Property<DateTime>("LastMessageDate") .HasColumnType("timestamp without time zone") .HasColumnName("last_message_date"); b.Property<decimal>("MemberId") .HasColumnType("numeric(20,0)") .HasColumnName("member_id"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<int>("Xp") .HasColumnType("integer") .HasColumnName("xp"); b.HasKey("Id") .HasName("pk_members"); b.HasIndex("GuildId", "MemberId") .IsUnique() .HasDatabaseName("ix_members_guild_id_member_id"); b.ToTable("members"); }); modelBuilder.Entity("Rias.Database.Entities.MuteTimerEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<DateTime>("Expiration") .HasColumnType("timestamp without time zone") .HasColumnName("expiration"); b.Property<decimal>("GuildId") .HasColumnType("numeric(20,0)") .HasColumnName("guild_id"); b.Property<decimal>("ModeratorId") .HasColumnType("numeric(20,0)") .HasColumnName("moderator_id"); b.Property<decimal>("MuteChannelSourceId") .HasColumnType("numeric(20,0)") .HasColumnName("mute_channel_source_id"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_mute_timers"); b.HasIndex("GuildId", "UserId") .IsUnique() .HasDatabaseName("ix_mute_timers_guild_id_user_id"); b.ToTable("mute_timers"); }); modelBuilder.Entity("Rias.Database.Entities.PatreonEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("AmountCents") .HasColumnType("integer") .HasColumnName("amount_cents"); b.Property<bool>("Checked") .HasColumnType("boolean") .HasColumnName("checked"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<DateTimeOffset?>("LastChargeDate") .HasColumnType("timestamp with time zone") .HasColumnName("last_charge_date"); b.Property<LastChargeStatus?>("LastChargeStatus") .HasColumnType("last_charge_status") .HasColumnName("last_charge_status"); b.Property<int>("PatreonUserId") .HasColumnType("integer") .HasColumnName("patreon_user_id"); b.Property<string>("PatreonUserName") .HasColumnType("text") .HasColumnName("patreon_user_name"); b.Property<PatronStatus?>("PatronStatus") .HasColumnType("patron_status") .HasColumnName("patron_status"); b.Property<int>("Tier") .HasColumnType("integer") .HasColumnName("tier"); b.Property<int>("TierAmountCents") .HasColumnType("integer") .HasColumnName("tier_amount_cents"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_patreon"); b.ToTable("patreon"); }); modelBuilder.Entity("Rias.Database.Entities.ProfileEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("BackgroundDim") .HasColumnType("integer") .HasColumnName("background_dim"); b.Property<string>("BackgroundUrl") .HasColumnType("text") .HasColumnName("background_url"); b.Property<string[]>("Badges") .HasColumnType("text[]") .HasColumnName("badges"); b.Property<string>("Biography") .HasColumnType("text") .HasColumnName("biography"); b.Property<string>("Color") .HasColumnType("text") .HasColumnName("color"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_profile"); b.HasIndex("UserId") .IsUnique() .HasDatabaseName("ix_profile_user_id"); b.ToTable("profile"); }); modelBuilder.Entity("Rias.Database.Entities.SelfAssignableRoleEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<decimal>("GuildId") .HasColumnType("numeric(20,0)") .HasColumnName("guild_id"); b.Property<decimal>("RoleId") .HasColumnType("numeric(20,0)") .HasColumnName("role_id"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.HasKey("Id") .HasName("pk_self_assignable_roles"); b.HasIndex("GuildId", "RoleId") .IsUnique() .HasDatabaseName("ix_self_assignable_roles_guild_id_role_id"); b.ToTable("self_assignable_roles"); }); modelBuilder.Entity("Rias.Database.Entities.UserEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<int>("Currency") .HasColumnType("integer") .HasColumnName("currency"); b.Property<DateTime>("DailyTaken") .HasColumnType("timestamp without time zone") .HasColumnName("daily_taken"); b.Property<bool>("IsBanned") .HasColumnType("boolean") .HasColumnName("is_banned"); b.Property<DateTime>("LastMessageDate") .HasColumnType("timestamp without time zone") .HasColumnName("last_message_date"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.Property<int>("Xp") .HasColumnType("integer") .HasColumnName("xp"); b.HasKey("Id") .HasName("pk_users"); b.HasIndex("UserId") .IsUnique() .HasDatabaseName("ix_users_user_id"); b.ToTable("users"); }); modelBuilder.Entity("Rias.Database.Entities.VoteEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<bool>("Checked") .HasColumnType("boolean") .HasColumnName("checked"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<bool>("IsWeekend") .HasColumnType("boolean") .HasColumnName("is_weekend"); b.Property<string>("Query") .HasColumnType("text") .HasColumnName("query"); b.Property<string>("Type") .HasColumnType("text") .HasColumnName("type"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_votes"); b.ToTable("votes"); }); modelBuilder.Entity("Rias.Database.Entities.WaifuEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int?>("CharacterId") .HasColumnType("integer") .HasColumnName("character_id"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<int?>("CustomCharacterId") .HasColumnType("integer") .HasColumnName("custom_character_id"); b.Property<string>("CustomImageUrl") .HasColumnType("text") .HasColumnName("custom_image_url"); b.Property<bool>("IsSpecial") .HasColumnType("boolean") .HasColumnName("is_special"); b.Property<int>("Position") .HasColumnType("integer") .HasColumnName("position"); b.Property<int>("Price") .HasColumnType("integer") .HasColumnName("price"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_waifus"); b.HasIndex("CharacterId") .HasDatabaseName("ix_waifus_character_id"); b.HasIndex("CustomCharacterId") .HasDatabaseName("ix_waifus_custom_character_id"); b.ToTable("waifus"); }); modelBuilder.Entity("Rias.Database.Entities.WarningEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasColumnName("id") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("created_at"); b.Property<decimal>("GuildId") .HasColumnType("numeric(20,0)") .HasColumnName("guild_id"); b.Property<decimal>("ModeratorId") .HasColumnType("numeric(20,0)") .HasColumnName("moderator_id"); b.Property<string>("Reason") .HasColumnType("text") .HasColumnName("reason"); b.Property<DateTime>("UpdatedAt") .HasColumnType("timestamp without time zone") .HasColumnName("updated_at"); b.Property<decimal>("UserId") .HasColumnType("numeric(20,0)") .HasColumnName("user_id"); b.HasKey("Id") .HasName("pk_warnings"); b.ToTable("warnings"); }); modelBuilder.Entity("Rias.Database.Entities.WaifuEntity", b => { b.HasOne("Rias.Database.Entities.CharacterEntity", "Character") .WithMany() .HasForeignKey("CharacterId") .HasConstraintName("fk_waifus_characters_character_id") .HasPrincipalKey("CharacterId"); b.HasOne("Rias.Database.Entities.CustomCharacterEntity", "CustomCharacter") .WithMany() .HasForeignKey("CustomCharacterId") .HasConstraintName("fk_waifus_custom_characters_custom_character_id") .HasPrincipalKey("CharacterId"); b.Navigation("Character"); b.Navigation("CustomCharacter"); }); #pragma warning restore 612, 618 } } }
41.005284
131
0.464257
7282e6997e080b739a0029e4befc8a2002a41fb3
3,939
h
C
include/dark/polyfill.h
darkoverlordofdata/wrengame
58a85b1fc4cacafb51780cadb694aa2b71382ec0
[ "MIT" ]
null
null
null
include/dark/polyfill.h
darkoverlordofdata/wrengame
58a85b1fc4cacafb51780cadb694aa2b71382ec0
[ "MIT" ]
null
null
null
include/dark/polyfill.h
darkoverlordofdata/wrengame
58a85b1fc4cacafb51780cadb694aa2b71382ec0
[ "MIT" ]
null
null
null
/******************************************************************* ** This code is part of the Dark Framework. ** MIT License Copyright (c) 2018 Dark Overlord of Data 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. ******************************************************************/ #pragma once // some string related functions that should be in the stdlib /** * strrstr - Returns a pointer to the first occurrence of str2 * in str1, or a null pointer if str2 is not part of str1. * * @param str string to search in * @param str2 string to search for * @return ptr to the substring */ #ifndef strrstr proc char * strrstr(char *str1, char *str2) { size_t slen = strlen(str1); size_t flen = strlen(str2); if (flen > slen) return nullptr; for (char* result = str1 + slen - flen; result >= str1; result--) { if (strncmp(result, str2, flen) == 0) return result; } return nullptr; } #endif /** * strndup - Returns a pointer to a null-terminated byte string, which * is a duplicate of the string pointed to by str1. The returned pointer * must be passed to free to avoid a memory leak. * * @param str string to duplicate * @param size of the new string * @return ptr to the new string */ #ifndef strdup proc char* strdup(const char* s) { size_t len = strlen(s)+1; void* new = malloc(len); if (new == nullptr) return nullptr; return (char*)memcpy(new, s, len); } #endif /** * join strings * * @param count of strings * @param ... list of char*'s * @returns all strings concantenated together. */ proc char* STR_JOIN(int count, ...) { int size = 0; va_list args1; va_start(args1, count); va_list args2; va_copy(args2, args1); /** * Caclulate length of the result string */ for (int i = 0; i < count; ++i) { char* str = va_arg(args1, char*); size += strlen(str); } va_end(args1); char* result = calloc((size+1), sizeof(char)); /** * Now build the result string */ for (int i = 0; i < count; ++i) { char* str = va_arg(args2, char*); strcat(result, str); } va_end(args2); return result; } /** * ReadTextFile * * @param path path to file * @returns string with file contents * */ proc char* ReadTextFile(FILE* f) { fseek(f, 0L, SEEK_END); long s = ftell(f); rewind(f); char* buf = calloc(1, s+1); buf[s] = '\0'; if (buf != nullptr) { fread(buf, s, 1, f); return buf; } return buf; } /** * println * * Writes output to stderr, with end of line. */ __attribute__((__format__ (__printf__, 1, 2))) static inline void println (char* format, ...) { va_list args; va_start(args, format); vfprintf(stdout, format, args); va_end(args); fprintf(stdout, "\n"); } // type (Object) // { // Object* Isa; // }; /** * Length of string */ method int Length(char* s) { return strlen(s); }
24.61875
78
0.632394
f1fdeddaa3c0d0059438456aa011d40174182efb
508
rb
Ruby
lib/encryption.rb
NUBIC/nucore-open
6fd4a8f9a380fec52b3a1c2cf147f7090a343c2d
[ "MIT" ]
null
null
null
lib/encryption.rb
NUBIC/nucore-open
6fd4a8f9a380fec52b3a1c2cf147f7090a343c2d
[ "MIT" ]
null
null
null
lib/encryption.rb
NUBIC/nucore-open
6fd4a8f9a380fec52b3a1c2cf147f7090a343c2d
[ "MIT" ]
null
null
null
require 'fast-aes' require 'active_support/secure_random' require 'base64' module Encryption #Basic AES symmetric encryption functions #based on http://snippets.dzone.com/posts/show/4975 def self.encrypt(text) aes = FastAES.new(Settings.aes_crypt_key) salt = SecureRandom.base64(16) Base64.encode64(aes.encrypt(salt + text)) end def self.decrypt(data) aes = FastAES.new(Settings.aes_crypt_key) output = aes.decrypt(Base64.decode64(data)) text = output[24..-1] end end
25.4
53
0.726378
1a84a1e199372b71944d65a7418368b247308d16
1,539
py
Python
requests_spider/rule.py
jayvdb/requests_spider
f4aa1f21880bd49b05e7cdbfcefa5a41a082e96c
[ "MIT" ]
5
2019-01-11T01:43:53.000Z
2019-08-04T16:05:40.000Z
requests_spider/rule.py
jayvdb/requests_spider
f4aa1f21880bd49b05e7cdbfcefa5a41a082e96c
[ "MIT" ]
1
2020-01-31T03:57:59.000Z
2020-02-02T07:15:59.000Z
requests_spider/rule.py
jayvdb/requests_spider
f4aa1f21880bd49b05e7cdbfcefa5a41a082e96c
[ "MIT" ]
2
2019-08-04T16:05:39.000Z
2020-01-31T03:06:22.000Z
import re from lxml.etree import ParserError from requests_spider.request import Request from requests_spider.const import mk_link from requests_spider.response import Response class Rule(Request): def __init__(self, rule, **kwargs): super().__init__(url=None, **kwargs) self.rule = rule def replace(self, url): return Request(url, method=self.method, callback=self.callback, meta=self.meta, form_filter=self.form_filter, not_filter=self.not_filter, **self.info) def make_next(self, links, response): return [self.replace(mk_link(link, response.url)) for link in links] def search(self, response: Response): pass class XRule(Rule): def search(self, response: Response): try: links = response.html.xpath(self.rule) except (ParserError, UnicodeDecodeError): links = [] return self.make_next(links, response) class RRule(Rule): def search(self, response: Response): links = re.findall(self.url, response.text) return self.make_next(links, response) class CRule(Rule): def __init__(self, rule, attr='href', **kwargs): super().__init__(rule, **kwargs) self.attr = attr def search(self, response: Response): try: links = response.html.find(self.url) links = [link.attrs.get(self.attr) for link in links] except (ParserError, UnicodeDecodeError): links = [] return self.make_next(links, response)
29.037736
93
0.647823
c6e4bb86615aaa97f8c7ad9c74a964755861c182
100
css
CSS
resources/styles.css
scott-morris/fitbit-obs-switcher
c78acdd6dba3cebfc8399a8b89f0bce12225d827
[ "Apache-2.0" ]
null
null
null
resources/styles.css
scott-morris/fitbit-obs-switcher
c78acdd6dba3cebfc8399a8b89f0bce12225d827
[ "Apache-2.0" ]
2
2022-01-22T13:06:51.000Z
2022-02-13T17:46:44.000Z
resources/styles.css
scott-morris/fitbit-obs-switcher
c78acdd6dba3cebfc8399a8b89f0bce12225d827
[ "Apache-2.0" ]
null
null
null
.background { viewport-fill: black; } .medium-copy-bold { fill: white; text-anchor: middle; }
12.5
23
0.66
05a137a8fd209e4387eaca7b5418642531cea440
2,832
py
Python
data/excape/make.py
ExaScience/smurff
29c3859badca49275833024cd77f8ca7fa6f76be
[ "MIT" ]
65
2017-06-23T14:01:58.000Z
2022-03-10T16:13:48.000Z
data/excape/make.py
ExaScience/smurff
29c3859badca49275833024cd77f8ca7fa6f76be
[ "MIT" ]
143
2017-08-11T10:43:52.000Z
2021-09-23T17:07:51.000Z
data/excape/make.py
ExaScience/smurff
29c3859badca49275833024cd77f8ca7fa6f76be
[ "MIT" ]
14
2018-05-17T18:33:28.000Z
2021-12-23T20:41:32.000Z
import requests import os from hashlib import sha256 def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" trainSession = requests.TrainSession() response = trainSession.get(URL, params = { 'id' : id }, stream = True) token = get_confirm_token(response) if token: params = { 'id' : id, 'confirm' : token } response = trainSession.get(URL, params = params, stream = True) save_response_content(response, destination) trainSession.close() def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, "wb") as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: # filter out keep-alive new chunks f.write(chunk) def sha256_from(filename): with open(filename, "rb") as f: sha = sha256(f.read()).hexdigest() return sha def download(): urls = [ ( "1MI2gXqc0-PM77qxReYQrmO1QyAITMBZ0", "f49c480076ee43f5635bd957a07c44a8a06133d10985c683b9260930831eb163", "side_c2v.ddm", ), ( "1UA1gQrnintr4BCWuIgg5LFda7Sx4fSAe", "8212af437e66ac4db2c48a7b0be63c8822ae803ceee7d080d03d8310d94b5849", "side_ecfp6_counts_var005.sdm", ), ( "15QG_g9h7d5lqbnybOilb7UX08FFiHN9l", "7326d97c8546fb09eb4a4a6b54758046ff04e7402cf857484d8263006e119a56", "side_ecfp6_folded_dense.ddm", ), ( "1OpvOLh0fwFQQRDyp8vYdAGU_CIy9WNCP", "9b8e458612a72d7051463d761248c54edfcb8bbfc73266536a5791fa5b047da2", "test.sdm", ), ( "1TGq9qSkKa7fvnwdJ2g5drTTaNTwlnOYF", "f6d9315f2c905146275caa1e1b03e380d870c33166caec81c2bdb35a7efe77ef", "train.sdm", ), ] for id, expected_sha, output in urls: if os.path.isfile(output): actual_sha = sha256_from(output) if (expected_sha == actual_sha): print("already have %s" % output) continue print("download %s" % output) download_file_from_google_drive(id, output) actual_sha = sha256_from(output) assert (expected_sha == actual_sha) if __name__ == "__main__": download() # shapes: # side_c2v.ddm : (46738, 469) # side_ecfp6_counts_var005.sdm : (46738, 13132) nnz: 1663083 (0.27%) # side_ecfp6_folded_dense.ddm : (46738, 1024) # test.sdm : (46738, 114) 21740 # train.sdm : (46738, 114) 37640
30.782609
83
0.609463
8511387adf40248bb856f1e7773980b4df1ea99e
1,114
cs
C#
source/Tools/TeachAppMaker/Commands/EditCommands.cs
LigangSun/AppCenter
b3f81e836ab2f4276cae33e5a2367752f3c3b050
[ "MIT" ]
null
null
null
source/Tools/TeachAppMaker/Commands/EditCommands.cs
LigangSun/AppCenter
b3f81e836ab2f4276cae33e5a2367752f3c3b050
[ "MIT" ]
null
null
null
source/Tools/TeachAppMaker/Commands/EditCommands.cs
LigangSun/AppCenter
b3f81e836ab2f4276cae33e5a2367752f3c3b050
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SoonLearning.TeachAppMaker.Commands { public class EditCommands { public static readonly AddQuestionCommand AddQuestionCommand; public static readonly AddSubQuestionCommand AddSubQuestionCommand; public static readonly EditQuestionCommand EditQuestionCommand; public static readonly EditKnowledgeCommand EditKnowledgeCommand; public static readonly DeleteCommand DeleteCommand; public static readonly DuplicateCommand DuplicateCommand; public static readonly EditAppCommand EditAppCommand; static EditCommands() { AddQuestionCommand = new AddQuestionCommand(); AddSubQuestionCommand = new AddSubQuestionCommand(); EditQuestionCommand = new EditQuestionCommand(); EditKnowledgeCommand = new EditKnowledgeCommand(); DeleteCommand = new DeleteCommand(); DuplicateCommand = new DuplicateCommand(); EditAppCommand = new EditAppCommand(); } } }
37.133333
75
0.716338
a9f29c82d01c77278f50c8181c2195d68235ca3d
16,834
php
PHP
admin/functions/functions.options.php
rodrigosady/redemindfulness
1b21ef91822be43471d1285ffc7919efbaa64fb8
[ "CC0-1.0" ]
null
null
null
admin/functions/functions.options.php
rodrigosady/redemindfulness
1b21ef91822be43471d1285ffc7919efbaa64fb8
[ "CC0-1.0" ]
null
null
null
admin/functions/functions.options.php
rodrigosady/redemindfulness
1b21ef91822be43471d1285ffc7919efbaa64fb8
[ "CC0-1.0" ]
null
null
null
<?php add_action('init','of_options'); if (!function_exists('of_options')) { function of_options() { //Access the WordPress Categories via an Array $of_categories = array(); $of_categories_obj = get_categories('hide_empty=0'); foreach ($of_categories_obj as $of_cat) { $of_categories[$of_cat->cat_ID] = $of_cat->cat_name;} $categories_tmp = array_unshift($of_categories, "Select a category:"); //Access the WordPress Pages via an Array $of_pages = array(); $of_pages_obj = get_pages('sort_column=post_parent,menu_order'); foreach ($of_pages_obj as $of_page) { $of_pages[$of_page->ID] = $of_page->post_name; } $of_pages_tmp = array_unshift($of_pages, "Select a page:"); //Testing $of_options_select = array("one","two","three","four","five"); $of_options_radio = array("one" => "One","two" => "Two","three" => "Three","four" => "Four","five" => "Five"); /*-----------------------------------------------------------------------------------*/ /* TO DO: Add options/functions that use these */ /*-----------------------------------------------------------------------------------*/ //More Options $uploads_arr = wp_upload_dir(); $all_uploads_path = $uploads_arr['path']; $all_uploads = get_option('of_uploads'); $other_entries = array("Select a number:","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"); $body_repeat = array("no-repeat","repeat-x","repeat-y","repeat"); $body_pos = array("top left","top center","top right","center left","center center","center right","bottom left","bottom center","bottom right"); // Image Alignment radio box $of_options_thumb_align = array("alignleft" => "Left","alignright" => "Right","aligncenter" => "Center"); // Image Links to Options $of_options_image_link_to = array("image" => "The Image","post" => "The Post"); /*-----------------------------------------------------------------------------------*/ /* The Options Array */ /*-----------------------------------------------------------------------------------*/ // Set the Options Array global $of_options; $of_options = array(); $of_options[] = array( "name" => "General Settings", "type" => "heading" ); $url = ADMIN_DIR . 'assets/images/'; $of_options[] = array( "name" => "Main Layout", "desc" => "Select main content and sidebar alignment. Choose between no sidebar, right sidebar or left sidebar layout.", "id" => "sidebar_position", "std" => "right", "type" => "images", "options" => array( 'none' => $url . '1col.png', 'right' => $url . '2cr.png', 'left' => $url . '2cl.png' ) ); $of_options[] = array( "name" => "Display search in main menu", "desc" => "Tick to display", "id" => "main_menu_search", "std" => 1, "type" => "checkbox" ); $of_options[] = array( "name" => "Logo", "desc" => "Upload a logo", "id" => "logo_image", "std" => "", "type" => "media" ); $of_options[] = array( "name" => "Logo Text Dark", "desc" => "e.g. Park", "id" => "logo_text_dark", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Logo Text Light", "desc" => "e.g. College", "id" => "logo_text_light", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Default Header Image URL", "desc" => "Displayed on all inner pages, e.g. http://website.com/image.jpg", "id" => "default_header_url", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Custom Favicon", "desc" => "Upload a 16px x 16px Png/Gif image that will represent your website's favicon.", "id" => "custom_favicon", "std" => "", "type" => "upload" ); $of_options[] = array( "name" => "Tracking Code", "desc" => "Paste your Google Analytics (or other) tracking code here. This will be added into the footer template of your theme.", "id" => "google_analytics", "std" => "", "type" => "textarea" ); $of_options[] = array( "name" => "Footer Text", "desc" => "Displayed in the footer area", "id" => "footer_text", "std" => '&copy; Copyright - <a href="#">ParkCollege</a> by <a href="#">Quite Nice Stuff</a>', "type" => "textarea" ); $of_options[] = array( "name" => "Home Settings", "type" => "heading" ); $of_options[] = array( "name" => "Display Homepage Blocks", "desc" => "Tick to display", "id" => "display_homepage_blocks", "std" => 0, "type" => "checkbox" ); $of_options[] = array( "name" => "Number of Homepage Coloured Blocks", "desc" => "", "id" => "homepage_coloured_blocks_number", "std" => "5", "type" => "select", "options" => array( '3' => 'Three', '4' => 'Four', '5' => 'Five',) ); $of_options[] = array( "name" => "Homepage Coloured Blocks", "desc" => "", "id" => "homepage_coloured_blocks", "std" => "", "type" => "custom_blocks" ); $of_options[] = array( "name" => "Homepage Slideshow", "desc" => "Add the description/caption like so:<br /><br />&lt;p&gt;First line text&lt;/p&gt;<br /> &lt;div class=\"clearboth\"&gt;&lt;/div&gt;<br /> &lt;p&gt;Second line text&lt;/p&gt;", "id" => "homepage_slider", "std" => "", "type" => "slider" ); $of_options[] = array( "name" => "Slideshow Boxed Layout", "desc" => "Tick if your slideshow images are the same width as your content", "id" => "slideshow_boxed", "std" => 0, "type" => "checkbox" ); $of_options[] = array( "name" => "Slideshow Height in px", "desc" => "Enter a numerical value e.g. \"450\", do NOT add px or %", "id" => "slideshow_height", "std" => "450", "type" => "text" ); $of_options[] = array( "name" => "Do not overlay header on slideshow", "desc" => "Tick this option if you do not wish to overlay the header on your slideshow", "id" => "slideshow_header_overlay", "std" => 0, "type" => "checkbox" ); $of_options[] = array( "name" => "Styling Options", "type" => "heading" ); $of_options[] = array( "name" => "Body Background Colour", "desc" => "", "id" => "body_background", "std" => "", "type" => "color" ); $of_options[] = array( "name" => "Background Image", "desc" => "Upload a background image", "id" => "body_background_image", "std" => "", "type" => "media" ); $of_options[] = array( "name" => "Background Repeat", "desc" => "Choose how to repeat the background image", "id" => "background_repeat", "std" => "repeat", "type" => "select", "options" => array( 'repeat' => 'Repeat', 'repeat-y' => 'Repeat-y', 'repeat-x' => 'Repeat-x', 'no-repeat' => 'No-repeat',) ); $of_options[] = array( "name" => "Main Colour", "desc" => "", "id" => "main_colour", "std" => "", "type" => "color" ); $of_options[] = array( "name" => "Footer Background Colour", "desc" => "", "id" => "footer_background_colour", "std" => "", "type" => "color" ); $of_options[] = array( "name" => "Footer Highlight Colour", "desc" => "", "id" => "footer_highlight_colour", "std" => "", "type" => "color" ); $of_options[] = array( "name" => "Footer Text Link Colour", "desc" => "", "id" => "footer_link_colour", "std" => "", "type" => "color" ); $of_options[] = array( "name" => "Top Bar Text Hover Colour", "desc" => "", "id" => "top_bar_hover_colour", "std" => "", "type" => "color" ); $of_options[] = array( "name" => "Slideshow Caption Background Colour (RGBA format)", "desc" => "Use http://hex2rgba.devoth.com/ e.g. rgba(28, 28, 28, 0.7)", "id" => "main_colorrgba", "std" => "", "type" => "text"); $of_options[] = array( "name" => "Custom CSS", "desc" => "Quickly add some CSS to your theme by adding it to this block.", "id" => "custom_css", "std" => "", "type" => "textarea" ); $of_options[] = array( "name" => "Google Font", "desc" => "Add Google Font Code Here, e.g. <br /><br /> &#60;link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,700,900' rel='stylesheet' type='text/css'&#62;", "id" => "custom_font_code", "std" => "<link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,700,900' rel='stylesheet' type='text/css'>", "type" => "textarea" ); $of_options[] = array( "name" => "Google Font Name", "desc" => "Enter the Google Font name / family here without 'font-family', e.g. <br /><br /> 'Merriweather', serif", "id" => "custom_font", "std" => "'Merriweather', serif", "type" => "text" ); $of_options[] = array( "name" => "Portfolio Settings", "type" => "heading" ); $of_options[] = array( "name" => "Portfolio Columns", "desc" => "Choose how many columns to display on the portfolio listing page", "id" => "portfolio_columns", "std" => "two", "type" => "select", "options" => array( 'two' => 'Two', 'three' => 'Three', 'four' => 'Four',) ); $of_options[] = array( "name" => "Items Per Page", "desc" => "The number of portfolio items to be displayed on each page, add a numerical value e.g. \"10\"", "id" => "portfolio_items_pp", "std" => "10", "type" => "text" ); $of_options[] = array( "name" => "Portfolio Page URL", "desc" => "To be used on the portfolio single page breadcrumbs, enter your portfolio page slug e.g. \"portfolio\"", "id" => "portfolio_page_url", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Course Settings", "type" => "heading" ); $of_options[] = array( "name" => "Items Per Page", "desc" => "The number of course items to be displayed on each page, add a numerical value e.g. \"10\"", "id" => "course_items_pp", "std" => "10", "type" => "text" ); $of_options[] = array( "name" => "Course Order", "desc" => "Choose the order courses are displayed in on the course page", "id" => "course_order", "std" => "ASC", "type" => "select", "options" => array( 'DESC' => 'Oldest First', 'ASC' => 'Newest First',) ); $of_options[] = array( "name" => "Course Page URL", "desc" => "To be used on the course single page breadcrumbs, enter your course page slug e.g. \"courses\"", "id" => "course_page_url", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Teacher Settings", "type" => "heading" ); $of_options[] = array( "name" => "Items Per Page", "desc" => "The number of teachers to be displayed on each page, add a numerical value e.g. \"10\"", "id" => "teacher_items_pp", "std" => "10", "type" => "text" ); $of_options[] = array( "name" => "Link to Teacher Single Page", "desc" => "Tick to switch link on", "id" => "teacher_single_link", "std" => 0, "type" => "checkbox" ); $of_options[] = array( "name" => "Teacher Single Page Style", "desc" => "", "id" => "teacher_single_style", "std" => "style_one", "type" => "select", "options" => array( 'style_one' => 'Style One', 'style_two' => 'Style Two',) ); $of_options[] = array( "name" => "Teacher Page URL", "desc" => "To be used on the teacher single page breadcrumbs, enter your teacher page slug e.g. \"teachers\"", "id" => "teacher_page_url", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Event Settings", "type" => "heading" ); $of_options[] = array( "name" => "Items Per Page", "desc" => "The number of events to be displayed on each page, add a numerical value e.g. \"10\"", "id" => "event_items_pp", "std" => "10", "type" => "text" ); $of_options[] = array( "name" => "Event Page URL", "desc" => "To be used on the event single page breadcrumbs, enter your event page slug e.g. \"events\"", "id" => "event_page_url", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Show Past Events", "desc" => "Check to show past events", "id" => "event_show_past", "std" => 1, "type" => "checkbox" ); $of_options[] = array( "name" => "Order By", "desc" => "Choose the order events are displayed", "id" => "event_order", "std" => "Oldest First", "type" => "select", "options" => array('Oldest First', 'Newest First') ); $of_options[] = array( "name" => "Contact Settings", "type" => "heading" ); $of_options[] = array( "name" => "Email Address", "desc" => "e.g. email@website.com", "id" => "email_address", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Phone Number", "desc" => "e.g. 1800-562-3764", "id" => "phone_number", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Social Settings", "type" => "heading" ); $of_options[] = array( "name" => "Twitter URL", "desc" => "e.g. http://website.com/user", "id" => "social_twitter", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Facebook URL", "desc" => "e.g. http://website.com/user", "id" => "social_facebook", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Google+ URL", "desc" => "e.g. http://website.com/user", "id" => "social_googleplus", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Pinterest URL", "desc" => "e.g. http://website.com/user", "id" => "social_pinterest", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Flickr URL", "desc" => "e.g. http://website.com/user", "id" => "social_flickr", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Youtube URL", "desc" => "e.g. http://website.com/user", "id" => "social_youtube", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Vimeo URL", "desc" => "e.g. http://website.com/user", "id" => "social_vimeo", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "Skype URL", "desc" => "e.g. http://website.com/user", "id" => "social_skype", "std" => "", "type" => "text" ); $of_options[] = array( "name" => "RSS URL", "desc" => "e.g. http://website.com/user", "id" => "social_rss", "std" => "", "type" => "text" ); // Backup Options $of_options[] = array( "name" => "Backup Options", "type" => "heading" ); $of_options[] = array( "name" => "Backup and Restore Options", "id" => "of_backup", "std" => "", "type" => "backup", "desc" => 'You can use the two buttons below to backup your current options, and then restore it back at a later time. This is useful if you want to experiment on the options but would like to keep the old settings in case you need it back.', ); $of_options[] = array( "name" => "Transfer Theme Options Data", "id" => "of_transfer", "std" => "", "type" => "transfer", "desc" => 'You can tranfer the saved options data between different installs by copying the text inside the text box. To import data from another install, replace the data in the text box with the one from another install and click "Import Options".', ); } } ?>
33.007843
259
0.488892
6c8ca32c26f0491266fb492168f1be9d696d0565
660
asm
Assembly
oeis/100/A100070.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/100/A100070.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/100/A100070.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A100070: Number a(n) of forests with two components in the complete bipartite graph K_{n,n}. ; Submitted by Christian Krause ; 6,117,5632,515625,77262336,17230990189,5360119185408,2219048868131217,1180000000000000000,783948341202404638821,636404158746280870281216,619884903445287035295372217,713552333492738487958741450752,958281836758907139301300048828125,1484996901540960701759721950156947456,2630102497986539743653834330242302250529,5279626377239924254549224564563169937195008,11923752124059209915118500893164751193536753237,30099130810368000000000000000000000000000000000000 mov $1,$0 mov $2,2 add $2,$0 add $0,$2 pow $2,2 add $0,$2 pow $2,$1 mul $0,$2
50.769231
453
0.865152
6dffe7ab5ca88db5d18c187d3f0b9f63f59fe2ec
559
tsx
TypeScript
src/containers/Stage/index.tsx
laihaibo/vite-react-starter-kit
f06e3e7220e598c43f425292a6d1366f71c38420
[ "MIT" ]
null
null
null
src/containers/Stage/index.tsx
laihaibo/vite-react-starter-kit
f06e3e7220e598c43f425292a6d1366f71c38420
[ "MIT" ]
null
null
null
src/containers/Stage/index.tsx
laihaibo/vite-react-starter-kit
f06e3e7220e598c43f425292a6d1366f71c38420
[ "MIT" ]
null
null
null
// eslint-disable-next-line no-use-before-define import React from "react"; import { useLocalStore, observer } from "mobx-react"; import { Button } from "zarm"; import uiStore from "../../stores/uiStore"; import styles from "./index.module.css"; // 使用uselocalstore function Index() { const store = useLocalStore(() => uiStore); return ( <div className={styles.Index}> <Button theme="primary" onClick={() => store.increment()}> Plus 1 </Button> <div>{uiStore.price}</div> </div> ); } export default observer(Index);
23.291667
64
0.647585
9b119b8de4f4a48a717d49b852679e7ae700423a
2,355
sql
SQL
imgUploader.sql
6i9er/imgUploader
97d82bd1c0c3ed555cd17477fe99bd6ce6c77e20
[ "MIT" ]
null
null
null
imgUploader.sql
6i9er/imgUploader
97d82bd1c0c3ed555cd17477fe99bd6ce6c77e20
[ "MIT" ]
null
null
null
imgUploader.sql
6i9er/imgUploader
97d82bd1c0c3ed555cd17477fe99bd6ce6c77e20
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.0.10deb1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 08, 2016 at 07:09 PM -- Server version: 5.5.49-0ubuntu0.14.04.1 -- PHP Version: 5.5.9-1ubuntu4.17 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `imgUploader` -- -- -------------------------------------------------------- -- -- Table structure for table `images` -- CREATE TABLE IF NOT EXISTS `images` ( `image_id` int(11) NOT NULL AUTO_INCREMENT, `path` varchar(255) NOT NULL, `image_order` int(11) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`image_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ; -- -- Dumping data for table `images` -- INSERT INTO `images` (`image_id`, `path`, `image_order`, `created_at`, `updated_at`) VALUES (1, 'Screenshot from 2016-02-02 04:52:55_1465244589.png', 1, '2016-06-08 16:07:11', '2016-06-06 18:23:09'), (2, 'Screenshot from 2016-04-25 10:47:43_1465244589.png', 15, '2016-06-08 16:07:12', '2016-06-06 18:23:09'), (4, 'Screenshot from 2016-02-02 04:52:55_1465305605.png', 13, '2016-06-08 16:07:12', '2016-06-07 11:20:05'), (5, 'Screenshot from 2016-04-25 10:47:43_1465305605.png', 14, '2016-06-08 16:07:12', '2016-06-07 11:20:05'), (6, 'Screenshot from 2016-06-05 14:44:15_1465305605.png', 11, '2016-06-08 16:07:12', '2016-06-07 11:20:05'), (8, 'Screenshot from 2016-06-05 14:44:15_1465393620.png', 12, '2016-06-08 16:07:12', '2016-06-08 11:47:00'), (10, 'Screenshot from 2016-06-05 14:44:15_1465394024.png', 8, '2016-06-08 16:07:12', '2016-06-08 11:53:44'), (15, 'Screenshot from 2016-04-25 10:47:43_1465401997.png', 4, '2016-06-08 16:07:11', '0000-00-00 00:00:00'), (18, 'Screenshot from 2016-04-25 10:47:43_1465402071.png', 0, '2016-06-08 16:07:51', '0000-00-00 00:00:00'); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
42.053571
108
0.685775
15ddc700dde5759ab9011cb9225d957441d12d45
653
sql
SQL
microservices-2/tracks3.sql
beaubadilla/cpsc449_backend_engineering
0edf216d76bb46482a90fcce58b921a2aaa9e26c
[ "CNRI-Python", "RSA-MD", "Xnet", "blessing", "X11" ]
null
null
null
microservices-2/tracks3.sql
beaubadilla/cpsc449_backend_engineering
0edf216d76bb46482a90fcce58b921a2aaa9e26c
[ "CNRI-Python", "RSA-MD", "Xnet", "blessing", "X11" ]
null
null
null
microservices-2/tracks3.sql
beaubadilla/cpsc449_backend_engineering
0edf216d76bb46482a90fcce58b921a2aaa9e26c
[ "CNRI-Python", "RSA-MD", "Xnet", "blessing", "X11" ]
null
null
null
-- $ sqlite3 tracks3.db < sqlite.sql BEGIN TRANSACTION; DROP TABLE IF EXISTS "Track"; CREATE TABLE "Track" ( "TrackId" GUID, "TrackName" NVARCHAR(200) NOT NULL, "Album" NVARCHAR(220) NOT NULL, "Artist" NVARCHAR(220), "Length" INTEGER NOT NULL, "Url" TEXT NOT NULL, "Art" TEXT, CONSTRAINT "PK_Track" PRIMARY KEY("TrackId"), UNIQUE("TrackName","Album") ); INSERT INTO Track(TrackName, Album, Artist, Length, Url, Art) VALUES('Princess of the Dawn', 'Restless and Wild','Deaffy & R.A. Smith-Diesel', 343719, "file://somewhere.mp3","Example.jpg"); COMMIT;
31.095238
189
0.6049
1e413e65535e5b6b56ed600d35f06cc628e89ad7
14
lua
Lua
resources/words/vve.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
resources/words/vve.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
resources/words/vve.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
return {'vve'}
14
14
0.642857
e7a86829fad01956fcbeddc9a40b2163974c58bb
569
css
CSS
assets/css/style.css
klwidmer/Crystal-Game
c4ec09ca532638a194c03c2d848859d5123838d5
[ "MIT" ]
null
null
null
assets/css/style.css
klwidmer/Crystal-Game
c4ec09ca532638a194c03c2d848859d5123838d5
[ "MIT" ]
null
null
null
assets/css/style.css
klwidmer/Crystal-Game
c4ec09ca532638a194c03c2d848859d5123838d5
[ "MIT" ]
null
null
null
/* @media (max-width : 768,980,1024px) { } */ .jumbotron { block-size: 15em; } ul { text-align: left; margin-left: auto; } h1 { text-align: center; font: bold; } body { margin-left: 2em; margin-right: 2em; background: url(assets\images\crystalThree.jpg); } #border { background-color: rgb(255, 255, 255); border: 10px solid #128494; margin: 10px; padding: 5px; } #bordertwo{ background-color: rgb(255, 255, 255); border: 10px solid #128494; margin: 10px; padding: 5px; float: right; }
13.878049
52
0.585237
3bc8aeb0eda99ea7388200c3b19d32c7335b1b8c
15,698
sql
SQL
sql/Financeiro/MENU.sql
crosiersource/crosierapp-radx
252114671fa33a6742e29b6631528a988b606b1a
[ "MIT" ]
null
null
null
sql/Financeiro/MENU.sql
crosiersource/crosierapp-radx
252114671fa33a6742e29b6631528a988b606b1a
[ "MIT" ]
10
2020-05-08T03:13:54.000Z
2022-03-24T13:18:47.000Z
sql/Financeiro/MENU.sql
crosiersource/crosierapp-radx
252114671fa33a6742e29b6631528a988b606b1a
[ "MIT" ]
null
null
null
START TRANSACTION; SET FOREIGN_KEY_CHECKS = 0; -- -- -- Entrada no menu do crosier-core DELETE FROM cfg_entmenu WHERE uuid = '189dd86e-f806-4f96-8d5e-2a3e388c6976'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('189dd86e-f806-4f96-8d5e-2a3e388c6976', 'Financeiro', 'fas fa-dollar-sign', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin', '', '71d1456b-3a9f-4589-8f71-42bbf6c91a3e', 100, 'background-color: darkslateblue;', now(), now(), 1, 1, 1); -- -- -- Entrada do meu PAI (NÃO É EXIBIDO) DELETE FROM cfg_entmenu WHERE uuid = 'b7a5f134-ea80-40e4-822e-e04cdac70258'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('b7a5f134-ea80-40e4-822e-e04cdac70258', 'Financeiro (Menu Raíz)', '', 'PAI', '9121ea11-dc5d-4a22-9596-187f5452f95a', '', '', null, 0, null, now(), now(), 1, 1, 1); -- Menu "Lançamentos" DELETE FROM cfg_entmenu WHERE uuid = '3984a4f5-cd55-4525-87b9-01212fb1952c'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('3984a4f5-cd55-4525-87b9-01212fb1952c', 'Lançamentos', 'fas fa-sign-out-alt', 'DROPDOWN', '9121ea11-dc5d-4a22-9596-187f5452f95a', null, '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 1, null, now(), now(), 1, 1, 1); DELETE FROM cfg_entmenu WHERE pai_uuid = '3984a4f5-cd55-4525-87b9-01212fb1952c'; INSERT INTO `cfg_entmenu` (`id`, `uuid`, `label`, `icon`, `tipo`, `pai_uuid`, `ordem`, `css_style`, `inserted`, `updated`, `estabelecimento_id`, `user_inserted_id`, `user_updated_id`, `url`, `app_uuid`, `roles`) VALUES (NULL, '52b3799e-f70e-4adf-8052-88f41ec1834e', 'Conta a Pagar', 'fas fa-file-invoice-dollar', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 2, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/aPagarReceber/', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, '9badfa49-3e39-44a8-b6cc-667d87cbc167', 'Conta a Pagar (Parcelamento)', 'fas fa-file-invoice-dollar', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 3, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/aPagarReceber/?parcelamento=true', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, 'aaa28528-43b5-4066-9ccc-9a083cd88a1a', 'Cheque Próprio', 'fas fa-money-check', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 4, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/chequeProprio/', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, '4b847e88-f16c-4b78-8d8a-10d1cfbbb0b1', 'Cheque Terceiros', 'fas fa-money-check', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 6, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/chequeTerceiros/', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, 'fadc7b3e-f2f3-42cd-9ebc-0652cdade206', 'Transf entre Carteiras', 'fas fa-exchange-alt', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 8, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/transferenciaEntreCarteiras/', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, '88281506-754e-4d54-bd68-299593918e03', 'Em Grupo', 'far fa-object-group', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 9, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/grupo/', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, '1e5d6a55-a507-401a-aa02-91602081bae1', 'Estorno', 'fas fa-eraser', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 10, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/estorno/', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, '0558f998-b936-415b-a1b9-5f1ed6b54395', 'Recorrente', 'fas fa-redo-alt', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 11, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/recorrente/', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, 'b5adceda-84db-46ec-aee6-43df24e4ce42', 'Cheque Terceiros (Parcelamento)', 'fas fa-money-check', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 7, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/chequeTerceiros/?parcelamento=true', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''), (NULL, '4a3625d7-92ef-4a26-aeaf-f9c5d16b615c', 'Cheque Próprio (Parcelamento)', 'fas fa-money-check', 'ENT', '3984a4f5-cd55-4525-87b9-01212fb1952c', 5, NULL, now(), now(), 1, 1, 1, '/fin/movimentacao/form/chequeProprio/?parcelamento=true', '9121ea11-dc5d-4a22-9596-187f5452f95a', ''); -- Extrato de Contas a Pagar/Receber DELETE FROM cfg_entmenu WHERE uuid = 'e8d385b5-5fe2-41f0-b8e2-f1d1ad7bd097'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('e8d385b5-5fe2-41f0-b8e2-f1d1ad7bd097', 'A Pagar/Receber', 'fas fa-file-invoice-dollar', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/aPagarReceber/list', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 2, null, now(), now(), 1, 1, 1); -- Pesquisa de Movimentações DELETE FROM cfg_entmenu WHERE uuid = '61d20df0-d26b-4e29-a304-9c56121d7fd0'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('61d20df0-d26b-4e29-a304-9c56121d7fd0', 'Pesquisar', 'fas fa-search-dollar', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/movimentacao/list', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 3, null, now(), now(), 1, 1, 1); -- Extrato de Movimentações DELETE FROM cfg_entmenu WHERE uuid = '0bc57722-bd1c-44fe-911e-2657d49c2965'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('0bc57722-bd1c-44fe-911e-2657d49c2965', 'Extrato', 'fas fa-list-ol', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/movimentacao/extrato', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 4, null, now(), now(), 1, 1, 1); -- Importação de Movimentações DELETE FROM cfg_entmenu WHERE uuid = 'fdabfbb2-197f-4cd4-87dd-f3ea02ef7a06'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('fdabfbb2-197f-4cd4-87dd-f3ea02ef7a06', 'Importação', 'fas fa-file-import', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/movimentacao/import', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 5, null, now(), now(), 1, 1, 1); -- Lançamento de caixa DELETE FROM cfg_entmenu WHERE uuid = '79c10300-39f8-4192-ac45-af4113d97ea7'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('79c10300-39f8-4192-ac45-af4113d97ea7', 'Caixas', 'fas fa-hand-holding-usd', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/movimentacao/caixa', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 6, null, now(), now(), 1, 1, 1); -- Abertura e Fechamento de Caixa DELETE FROM cfg_entmenu WHERE uuid = 'e31a61ee-22f6-11ec-b802-2f8810a1181b'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('e31a61ee-22f6-11ec-b802-2f8810a1181b', 'Abertura e Fechamento de Caixa', 'fas fa-book-open', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/carteira/caixaOperacaoForm', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 6, null, now(), now(), 1, 1, 1); -- Recorrentes DELETE FROM cfg_entmenu WHERE uuid = '31b009a5-758b-4ee4-b47c-f42df678868d'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('31b009a5-758b-4ee4-b47c-f42df678868d', 'Recorrentes', 'fas fa-undo', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/movimentacaoRecorrente/list', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 7, null, now(), now(), 1, 1, 1); -- Agrupadas DELETE FROM cfg_entmenu WHERE uuid = 'd75b1eb9-3f15-4eb9-a87d-d1ebb33172ff'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('d75b1eb9-3f15-4eb9-a87d-d1ebb33172ff', 'Agrupadas', 'fas fa-layer-group', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/grupoItem/listMovs/', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 8, null, now(), now(), 1, 1, 1); -- Cadastros DELETE FROM cfg_entmenu WHERE uuid = 'a2f6c378-71c8-426b-8974-804187e8776a'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('a2f6c378-71c8-426b-8974-804187e8776a', 'Cadastros', 'fas fa-clipboard-list', 'DROPDOWN', '9121ea11-dc5d-4a22-9596-187f5452f95a', '', '', 'b7a5f134-ea80-40e4-822e-e04cdac70258', 99, 'background-color: #0f2944;', now(), now(), 1, 1, 1); -- Carteiras DELETE FROM cfg_entmenu WHERE uuid = '8b1a74a8-fb70-4a05-a1e1-150e2561ce70'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('8b1a74a8-fb70-4a05-a1e1-150e2561ce70', 'Carteiras', 'fas fa-piggy-bank', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/carteira/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 1, null, now(), now(), 1, 1, 1); -- Categorias DELETE FROM cfg_entmenu WHERE uuid = 'b41a78d8-14ec-4ba4-8ec6-453240719321'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('b41a78d8-14ec-4ba4-8ec6-453240719321', 'Categorias', 'fas fa-stream', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/categoria/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 2, null, now(), now(), 1, 1, 1); -- Centros de Custos DELETE FROM cfg_entmenu WHERE uuid = '6f68649c-516c-4b1f-a735-040d9f7125a9'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('6f68649c-516c-4b1f-a735-040d9f7125a9', 'Centros de Custos', 'fas fa-location-arrow', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/centroCusto/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 3, null, now(), now(), 1, 1, 1); -- Grupos DELETE FROM cfg_entmenu WHERE uuid = 'db8eea41-44c2-49dc-b850-fb0b0a8631bd'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('db8eea41-44c2-49dc-b850-fb0b0a8631bd', 'Grupos', 'fas fa-sitemap', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/grupo/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 4, null, now(), now(), 1, 1, 1); -- Modos de Movimentação DELETE FROM cfg_entmenu WHERE uuid = 'b1dcae54-08ce-4b25-b38b-a8f7d56218e8'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('b1dcae54-08ce-4b25-b38b-a8f7d56218e8', 'Modos', 'fas fa-sitemap', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/modo/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 5, null, now(), now(), 1, 1, 1); -- Operadoras de Cartão DELETE FROM cfg_entmenu WHERE uuid = '5fe09111-9fce-4eaf-b65a-060a09d2f8e7'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('5fe09111-9fce-4eaf-b65a-060a09d2f8e7', 'Operadoras de Cartão', 'fas fa-building', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/operadoraCartao/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 6, null, now(), now(), 1, 1, 1); -- Bandeiras de Cartão DELETE FROM cfg_entmenu WHERE uuid = 'ced83376-84a7-4c89-a185-e252a9ae3936'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('ced83376-84a7-4c89-a185-e252a9ae3936', 'Bandeiras de Cartão', 'fab fa-cc-visa', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/bandeiraCartao/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 7, null, now(), now(), 1, 1, 1); -- Regras de Importação DELETE FROM cfg_entmenu WHERE uuid = 'cb7e4d97-59fe-4666-880f-6f8eecd806f3'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('cb7e4d97-59fe-4666-880f-6f8eecd806f3', 'Regras de Importação', 'fas fa-file-excel', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/regraImportacaoLinha/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 8, null, now(), now(), 1, 1, 1); -- Registros para Conferências DELETE FROM cfg_entmenu WHERE uuid = 'e2ffd6b9-81d6-4ff1-84ab-ada9670484ce'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('e2ffd6b9-81d6-4ff1-84ab-ada9670484ce', 'Registros para Conferências', 'fas fa-check-circle', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/registroConferencia/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 9, null, now(), now(), 1, 1, 1); -- Bancos DELETE FROM cfg_entmenu WHERE uuid = '5cf74ef9-4d4d-4283-98d0-120d4617a7ea'; INSERT INTO cfg_entmenu(uuid, label, icon, tipo, app_uuid, url, roles, pai_uuid, ordem, css_style, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('5cf74ef9-4d4d-4283-98d0-120d4617a7ea', 'Bancos', 'fas fa-university', 'ENT', '9121ea11-dc5d-4a22-9596-187f5452f95a', '/fin/banco/list', '', 'a2f6c378-71c8-426b-8974-804187e8776a', 10, null, now(), now(), 1, 1, 1); -- -- -- -- -- -- -- -- cfg_entmenu_locator -- DELETE FROM cfg_entmenu_locator WHERE menu_uuid = 'b7a5f134-ea80-40e4-822e-e04cdac70258'; INSERT INTO cfg_entmenu_locator(menu_uuid, url_regexp, quem, inserted, updated, estabelecimento_id, user_inserted_id, user_updated_id) VALUES ('b7a5f134-ea80-40e4-822e-e04cdac70258', '^https://radx\.(.)*/fin/(.)*', '*', now(), now(), 1, 1, 1); COMMIT;
48.903427
202
0.68754
4d5ca4dd9b60a07d30bf7380209d56a5c766799f
628
cs
C#
src/AdoNet/Orleans.Persistence.AdoNet/Storage/Provider/OrleansDefaultHasher.cs
JohnDebono/orleans
0c90d286f92a0e26b2b85b5da34350ef1dc79def
[ "MIT" ]
9,108
2015-01-23T18:24:16.000Z
2022-03-31T15:40:52.000Z
src/AdoNet/Orleans.Persistence.AdoNet/Storage/Provider/OrleansDefaultHasher.cs
JohnDebono/orleans
0c90d286f92a0e26b2b85b5da34350ef1dc79def
[ "MIT" ]
5,728
2015-01-24T01:18:32.000Z
2022-03-31T23:56:27.000Z
src/AdoNet/Orleans.Persistence.AdoNet/Storage/Provider/OrleansDefaultHasher.cs
JohnDebono/orleans
0c90d286f92a0e26b2b85b5da34350ef1dc79def
[ "MIT" ]
2,491
2015-01-23T18:33:35.000Z
2022-03-30T16:42:55.000Z
namespace Orleans.Storage { /// <summary> /// A default implementation uses the same hash as Orleans in grains placement. /// </summary> public class OrleansDefaultHasher: IHasher { /// <summary> /// <see cref="IHasher.Description"/> /// </summary> public string Description { get; } = $"The default Orleans hash function ({nameof(JenkinsHash)})."; /// <summary> /// <see cref="IHasher.Hash(byte[])"/>. /// </summary> public int Hash(byte[] data) { return unchecked((int)JenkinsHash.ComputeHash(data)); } } }
27.304348
107
0.557325
f4811ec3f619aeecfea197bb48ec306250a24a71
132
ts
TypeScript
src/components/index.ts
wyze/matching-game
c7181ab8fd1e9dc7bd87313155533e22bd5e6828
[ "MIT" ]
1
2020-11-29T19:11:21.000Z
2020-11-29T19:11:21.000Z
src/components/index.ts
wyze/matching-game
c7181ab8fd1e9dc7bd87313155533e22bd5e6828
[ "MIT" ]
null
null
null
src/components/index.ts
wyze/matching-game
c7181ab8fd1e9dc7bd87313155533e22bd5e6828
[ "MIT" ]
null
null
null
export * from './Button' export * from './DifficultyToggle' export * from './Card' export * from './Runtime' export * from './Text'
22
34
0.659091
b324c79cd98921c815f04a727084794ebb033708
2,147
py
Python
kafka-twitter-producer.py
coti92/spark-streaming-twitter-kafka-master
007b6da6dc2a3a515c57b20fe6d3c63096540321
[ "MIT" ]
null
null
null
kafka-twitter-producer.py
coti92/spark-streaming-twitter-kafka-master
007b6da6dc2a3a515c57b20fe6d3c63096540321
[ "MIT" ]
null
null
null
kafka-twitter-producer.py
coti92/spark-streaming-twitter-kafka-master
007b6da6dc2a3a515c57b20fe6d3c63096540321
[ "MIT" ]
null
null
null
#!/usr/bin/env python # import required libraries from kafka import SimpleProducer, KafkaClient from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream # Twitter keys consumer_key = 'HxTwHU4NS9ozBy5umXh5Y0VYv' consumer_secret = 'gnlrkkoYNUNZT2B2sshoVIvfkjvRRosI7DWcLNlZ89Ubwrkqbt' access_token = '741468980-hirgAI1iuJr8RyLlWS4zX86YsFVTsvnH84cNw4ND' access_token_secret = 'FcUyRls8TBRQkloHTiWMqxzt1kboBnKXe7zDA8KEIZIjJ' # Kafka settings topic = b'twitter-stream' # setting up Kafka producer kafka = KafkaClient('localhost:9092') producer = SimpleProducer(kafka) #This is a basic listener that just put received tweets to kafka cluster. class StdOutListener(StreamListener): def on_data(self, data): producer.send_messages(topic, data.encode('utf-8')) print (data) return True def on_error(self, status): print (status) WORDS_TO_TRACK = "the to and is in it you of for on my that at with me do have just this be so are not was but out up what now new from your like good no get all about we if time as day will one how can some an am by going they go or has know today there love more work too got he back think did when see really had great off would need here thanks been still people who night want why home should well much then right make last over way does getting watching its only her post his morning very she them could first than better after tonight our again down news man looking us tomorrow best into any hope week nice show yes where take check come fun say next watch never bad free life".split() if __name__ == '__main__': print ('running the twitter-stream python code') #This handles Twitter authetification and the connection to Twitter Streaming API l = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, l) # Goal is to keep this process always going while True: try: stream.sample() stream.filter(languages=["en"], track=WORDS_TO_TRACK) except: pass
43.816327
693
0.755939
aac7edb2dd0f4da3ad6a76d0d125d105d3e9b8a7
3,338
lua
Lua
Lua/Menu/MainMenu/mainMenuStyle.lua
andeandr100/Crumbled-World
e5dc7a3bb0f1b75045171998f1771c58d80d65f3
[ "MIT" ]
5
2017-03-13T12:22:23.000Z
2017-07-23T14:23:20.000Z
Lua/Menu/MainMenu/mainMenuStyle.lua
andeandr100/Crumbled-World
e5dc7a3bb0f1b75045171998f1771c58d80d65f3
[ "MIT" ]
null
null
null
Lua/Menu/MainMenu/mainMenuStyle.lua
andeandr100/Crumbled-World
e5dc7a3bb0f1b75045171998f1771c58d80d65f3
[ "MIT" ]
null
null
null
--this = SceneNode() MainMenuStyle = {} MainMenuStyle.borderColor = Vec4(Vec3(0.45), 1.0) MainMenuStyle.borderSize = 0.00135 MainMenuStyle.backgroundTopColor = Vec4(0,0,0,0.7) MainMenuStyle.backgroundDownColor = Vec4(0,0,0,0.5) MainMenuStyle.textColor = Vec3(0.7) MainMenuStyle.textColorHighLighted = Vec3(0.92) language = Language() function MainMenuStyle.createPagePanel(panel) panel:add(Panel(PanelSize(Vec2()))) end --Create main menu -- Panel = parrent panel -- panelSize = Panelsize() function MainMenuStyle.createTopMenu(panel, panelSize) local topPanel = panel:add(Panel(panelSize)) topPanel:setBackground(Gradient(MainMenuStyle.backgroundTopColor, MainMenuStyle.backgroundDownColor)) topPanel:setLayout(FlowLayout(Alignment.TOP_LEFT)) local border = panel:add(Panel(PanelSize(Vec2(-1,2),PanelSizeType.Pixel))) border:setBackground(Sprite(MainMenuStyle.borderColor)) return topPanel end function MainMenuStyle.addTopMenuButton(panel, scale, text) return panel:add(MainMenuStyle.createMenuButton( Vec2(-1), scale, text)) end function MainMenuStyle.createMenuButton(size, scale, text) local button = Button((scale and PanelSize(size, scale) or PanelSize(size)), text, ButtonStyle.RADIENT) button:setTextColor(Vec3(0.7)) button:setTextHoverColor(Vec3(0.92)) button:setTextDownColor(Vec3(1)) button:setEdgeColor(Vec4(0), Vec4(0)) button:setEdgeHoverColor(Vec4(0), Vec4(0)) button:setEdgeDownColor(Vec4(0), Vec4(0)) button:setInnerColor(Vec4(0), Vec4(0), Vec4(0)) button:setInnerHoverColor(Vec4(0), Vec4(1,1,1,0.4), Vec4(0)) button:setInnerDownColor(Vec4(0), Vec4(1,1,1,0.3), Vec4(0)) return button end function MainMenuStyle.createButton(size, scale, text) local button = Button(PanelSize(size, scale), text, ButtonStyle.SQUARE_LIGHT) button:setEdgeColor(MainMenuStyle.borderColor) button:setEdgeHoverColor(MainMenuStyle.borderColor) button:setEdgeDownColor(Vec4(MainMenuStyle.borderColor:toVec3() * 0.8, MainMenuStyle.borderColor.w)) button:setInnerColor(Vec4(0.18,0.18,0.18,1),Vec4(),Vec4(0,0,0,1)) button:setInnerHoverColor(Vec4(0.08,0.08,0.08,1),Vec4(0.5,0.5,0.5,1),Vec4(0,0,0,1)) button:setInnerDownColor(Vec4(0.08,0.08,0.08,1),Vec4(0.4,0.4,0.4,1),Vec4(0,0,0,1)) button:setTextColor(MainMenuStyle.textColor) button:setTextHoverColor(Vec4(1)) button:setTextDownColor(Vec4(1)) -- button:setTextColor(Vec3(0.7)) -- button:setTextHoverColor(Vec3(0.92)) -- button:setTextDownColor(Vec3(1)) -- -- button:setEdgeColor(MainMenuStyle.borderColor) -- button:setEdgeHoverColor(MainMenuStyle.borderColor) -- button:setEdgeDownColor(MainMenuStyle.borderColor) -- -- button:setInnerColor(Vec4(0)) -- button:setInnerHoverColor(Vec4(1,1,1,0.2)) -- button:setInnerDownColor(Vec4(1,1,1,0.1)) return button end function MainMenuStyle.createTextField(size, scale, text) local textField = TextField(PanelSize(size, scale), text) textField:setTextColor(MainMenuStyle.textColorHighLighted) textField:setBackgroundColor(Vec4(0,0,0,0.8)) textField:setBorderBottomInternalColor(Vec4(0,0,0,0.9)) textField:setBorderBottomEdgeColor(MainMenuStyle.borderColor) return textField end function MainMenuStyle.createBreakLine(panel,length) local breakLinePanel = panel:add(Panel(PanelSize(Vec2(length or -0.9,0.002)))) breakLinePanel:setBackground(Sprite(MainMenuStyle.borderColor)) end
34.061224
104
0.776213
8da7d242270ff1bfc4db46ae5ac0228556310030
1,867
js
JavaScript
__tests__/flatten.js
alextoudic/conductor
5fd7078ba9722a788470e6d9a0c10368d3b89c49
[ "MIT" ]
56
2018-02-26T09:31:30.000Z
2020-01-15T09:17:56.000Z
__tests__/flatten.js
alextoudic/conductor
5fd7078ba9722a788470e6d9a0c10368d3b89c49
[ "MIT" ]
102
2018-03-08T20:06:03.000Z
2021-06-29T05:46:49.000Z
__tests__/flatten.js
alextoudic/conductor
5fd7078ba9722a788470e6d9a0c10368d3b89c49
[ "MIT" ]
7
2018-03-10T12:29:32.000Z
2019-08-08T19:45:27.000Z
const flatten = require('../src/flatten') const array = [1, 2, 3] const nestedArray = [1, [2, 3]] const deepNestedArray = [1, [2, [3]]] const object = { a: 1, b: 2, c: 3 } const nestedObject = { a: { b: 2, c: 3 } } const deepNestedObject = { a: { b: { c: 3 } } } const set = new Set(array) const nestedSet = new Set([1, new Set([2, 3])]) const deepNestedSet = new Set([1, new Set([2, new Set([3])])]) const map = new Map(Object.entries(object)) const nestedMap = new Map([['a', new Map(Object.entries(nestedObject.a))]]) const deepNestedMap = new Map([['a', new Map([['b', new Map([['c', 3]])]])]]) describe('flatten', () => { it('should flatten an array', () => { expect(flatten(array)).toEqual(array) }) it('should flatten a nested array', () => { expect(flatten(nestedArray)).toEqual(array) }) it('should flatten a deep nested array', () => { expect(flatten(deepNestedArray)).toEqual(array) }) it('should flatten an object', () => { expect(flatten(object)).toEqual(object) }) it('should flatten a nested object', () => { expect(flatten(nestedObject)).toEqual({ 'a.b': 2, 'a.c': 3 }) }) it('should flatten a deep nested object', () => { expect(flatten(deepNestedObject)).toEqual({ 'a.b.c': 3 }) }) it('should flatten a set', () => { expect(flatten(set)).toEqual(set) }) it('should flatten a nested set', () => { expect(flatten(nestedSet)).toEqual(set) }) it('should flatten a deep nested set', () => { expect(flatten(deepNestedSet)).toEqual(set) }) it('should flatten a map', () => { expect(flatten(map)).toEqual(map) }) it('should flatten a nested map', () => { expect(flatten(nestedMap)).toEqual(new Map([['a.b', 2], ['a.c', 3]])) }) it('should flatten a deep nested map', () => { expect(flatten(deepNestedMap)).toEqual(new Map([['a.b.c', 3]])) }) })
27.455882
77
0.591859
980a72fccef645cb19598fdd874c51d1fe85d79a
7,654
py
Python
step84_data/POD_imports.py
acse-hg2917/DDGAN_buildings
91a6fbc74819e94f7b31a2d6b3fdbb3fa4959eba
[ "MIT" ]
null
null
null
step84_data/POD_imports.py
acse-hg2917/DDGAN_buildings
91a6fbc74819e94f7b31a2d6b3fdbb3fa4959eba
[ "MIT" ]
null
null
null
step84_data/POD_imports.py
acse-hg2917/DDGAN_buildings
91a6fbc74819e94f7b31a2d6b3fdbb3fa4959eba
[ "MIT" ]
null
null
null
#%% import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error # from nirom_dd_orig import plot_starshape save_bf = False snapshots_matrix_1 = np.load('snapshots/snapshots_pod_0709.npy') snapshots_matrix_2 = np.load('snapshots/snapshots_pod.npy') snapshots_matrix = np.concatenate((snapshots_matrix_1, snapshots_matrix_2), axis = 1) print("Number of snapshots = ",snapshots_matrix.shape[1]) xlength = 3.0 ylength = 3.0 grid_width = [0.48,0.48] # spacing inside small grid # %% snapshots_matrix_vel = snapshots_matrix[:nx*ny*2,:] snapshots_matrix_b = snapshots_matrix[nx*ny*2:nx*ny*3,:] # %% nx = int(grid_width[0]*100) ny = nx nz = 1 ddx = np.array((0.01,0.01)) nloc = 3 nScalar = 1 #because I calculate u and v separately nDim = 2 # dimension of problem (no need to interpolate in the third dimension) #%% # cumulative_tol = 0.95 # nPOD = [nTime] # len(nPOD) = nFields # nPOD = [-2] nPOD = [-1] nPOD = [100] # 100 50 10 bases = [] singular_values = [] #snapshots matrix done! nrows, ncols = snapshots_matrix.shape if nrows > ncols: SSmatrix = np.dot(snapshots_matrix.T, snapshots_matrix) else: SSmatrix = np.dot(snapshots_matrix, snapshots_matrix.T) print('WARNING - CHECK HOW THE BASIS FUNCTIONS ARE CALCULATED WITH THIS METHOD') # print('SSmatrix', SSmatrix.shape) eigvalues, v = np.linalg.eigh(SSmatrix) # print('eigenvalues', eigvalues) # print('normalized eigenvector ([:j]) v = ', v) eigvalues = eigvalues[::-1] # get rid of small negative eigenvalues (there shouldn't be any as the eigenvalues of a real, symmetric # matrix are non-negative, but sometimes very small negative values do appear) eigvalues[eigvalues<0] = 0 s_values = np.sqrt(eigvalues) # print('s values', s_values[0:20]) singular_values.append(s_values) cumulative_info = np.zeros(len(eigvalues)) for j in range(len(eigvalues)): if j==0: cumulative_info[j] = eigvalues[j] else: cumulative_info[j] = cumulative_info[j-1] + eigvalues[j] cumulative_info = cumulative_info / cumulative_info[-1] nAll = len(eigvalues) # Apply POD #if nPOD = -1, use cumulative tolerance #if nPOD = -2 use all coefficients (or set nPOD = nTime) #if nPOD > 0 use nPOD coefficients as defined by the user if nPOD[0] == -1: # SVD truncation - percentage of information captured or number # cumulative_tol = nirom_options.compression.cumulative_tol[iField] nPOD_iField = sum(cumulative_info <= cumulative_tol) #tolerance nPOD[0] = nPOD_iField elif nPOD[0] == -2: nPOD_iField = nAll nPOD[0] = nPOD_iField else: nPOD_iField = nPOD[0] print("retaining", nPOD_iField, "basis functions of a possible", len(eigvalues)) basis_functions = np.zeros((nx*ny*nz*(nDim+1),nPOD_iField)) # nDim should be nScalar? for j in reversed(range(nAll-nPOD_iField,nAll)): Av = np.dot(snapshots_matrix,v[:,j]) basis_functions[:,nAll-j-1] = Av/np.linalg.norm(Av) # %% plt.plot(range(len(singular_values[0])), np.log(singular_values[0]), 'k.-') plt.xlabel("Log of singular values") plt.ylabel("Index of basis function") plt.grid(':') # plt.savefig("singular_plot.png") plt.show() # %% plt.plot(range(len(cumulative_info)), cumulative_info, 'g.-') plt.xlabel("Log of singular values") plt.ylabel("Index of basis function") plt.grid(':') # plt.savefig("cumulative_info.png") plt.show() #%% """ Compress and reconstruct the snapshots and graph the MSE reconstruction error R- basis_functions alpha - pod coeff phi - reconstruction """ alphas = np.zeros((snapshots_matrix.shape[1], nPOD_iField)) #array that stores compressions for i in range(snapshots_matrix.shape[1]): alphas[i] = basis_functions.T @ snapshots_matrix[:,i] #reconstruct reconstructions = np.zeros(snapshots_matrix.shape) mse_errors = [] for i in range(snapshots_matrix.shape[1]): reconstructions[:,i] = basis_functions @ alphas[i] mse_errors.append(mean_squared_error(snapshots_matrix[:,i], reconstructions[:,i])) #%% # with 278 basis functions, np.mean(mse_errors) = 0.0024700645895766376 #save basis functions if save_bf: np.save("basis_functions.npy", basis_functions) # %% """ Import the starshape grid and compress that information """ starshape = np.load("starshape_pod.npy") alphas_s = np.zeros((starshape.shape[1], nPOD_iField)) #array that stores compressions for i in range(starshape.shape[1]): alphas_s[i] = basis_functions.T @ starshape[:,i] # reconstruct reconstructions_s = np.zeros(starshape.shape) mse_errors_s = [] for i in range(starshape.shape[1]): reconstructions_s[:,i] = basis_functions @ alphas_s[i] mse_errors_s.append(mean_squared_error(starshape[:,i], reconstructions_s[:,i])) # Export the compressions np.save("ss_pod_coeffs.npy",alphas_s) # %% def create_basis_func(snapshot_matrix, nPOD): nrows, ncols = snapshot_matrix.shape # if nrows > ncols: # SSmatrix = np.dot(snapshot_matrix.T, snapshot_matrix) # else: # SSmatrix = np.dot(snapshot_matrix, snapshot_matrix.T) # print('WARNING - CHECK HOW THE BASIS FUNCTIONS ARE CALCULATED WITH THIS METHOD') SSmatrix = np.dot(snapshot_matrix.T, snapshot_matrix) # print('SSmatrix', SSmatrix.shape) eigvalues, v = np.linalg.eigh(SSmatrix) # print('eigenvalues', eigvalues) # print('normalized eigenvector ([:j]) v = ', v) eigvalues = eigvalues[::-1] # get rid of small negative eigenvalues (there shouldn't be any as the eigenvalues of a real, symmetric # matrix are non-negative, but sometimes very small negative values do appear) eigvalues[eigvalues<0] = 0 # s_values = np.sqrt(eigvalues) # singular_values.append(s_values) cumulative_info = np.zeros(len(eigvalues)) for j in range(len(eigvalues)): if j==0: cumulative_info[j] = eigvalues[j] else: cumulative_info[j] = cumulative_info[j-1] + eigvalues[j] cumulative_info = cumulative_info / cumulative_info[-1] nAll = len(eigvalues) # Apply POD #if nPOD = -1, use cumulative tolerance #if nPOD = -2 use all coefficients (or set nPOD = nTime) #if nPOD > 0 use nPOD coefficients as defined by the user # if nPOD[0] == -1: # # SVD truncation - percentage of information captured or number # # cumulative_tol = nirom_options.compression.cumulative_tol[iField] # nPOD_iField = sum(cumulative_info <= cumulative_tol) #tolerance # nPOD[0] = nPOD_iField # elif nPOD[0] == -2: # nPOD_iField = nAll # nPOD[0] = nPOD_iField # else: # nPOD_iField = nPOD[0] print("retaining", nPOD, "basis functions of a possible", len(eigvalues)) basis = np.zeros((snapshot_matrix.shape[0],nPOD)) # nDim should be nScalar? for j in reversed(range(nAll-nPOD,nAll)): Av = np.dot(snapshot_matrix,v[:,j]) basis[:,nAll-j-1] = Av/np.linalg.norm(Av) return basis #%% def extract_POD(basis_func, starshape_sm): nPOD = basis_func.shape[1] alpha_s = np.zeros((starshape_sm.shape[1], nPOD)) #array that stores compressions for i in range(starshape.shape[1]): alpha_s[i] = basis_func.T @ starshape_sm[:,i] return alpha_s # %% basis_vel = create_basis_func(snapshots_matrix_vel, 20) basis_buildings = create_basis_func(snapshots_matrix_b, 10) starshape_vel = starshape[:nx*ny*2,:] starshape_b = starshape[nx*ny*2:nx*ny*3,:] # %% ss_pod_vel = extract_POD(basis_vel, starshape_vel) ss_pod_buildings = extract_POD(basis_buildings, starshape_b) np.save("ss_pod_vel_3000.npy", ss_pod_vel) np.save("ss_pod_b_3000.npy", ss_pod_buildings) np.save("basis_b_3000.npy", basis_buildings) np.save("basis_vel_3000.npy", basis_vel)
33.134199
107
0.70682
c4f71328bc68fc79f731aa6cb23abc7869f33e4d
400
cpp
C++
practice/algorithms/birthday-cake-candles.cpp
geezardo/hackerrank
c3dd829ba803bd21ec3f432f419e40415cf6a6a8
[ "MIT" ]
null
null
null
practice/algorithms/birthday-cake-candles.cpp
geezardo/hackerrank
c3dd829ba803bd21ec3f432f419e40415cf6a6a8
[ "MIT" ]
null
null
null
practice/algorithms/birthday-cake-candles.cpp
geezardo/hackerrank
c3dd829ba803bd21ec3f432f419e40415cf6a6a8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define endl '\n' int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> a (n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); auto lb = lower_bound(a.begin(), a.end(), a[n - 1]); int sum = 0; for (auto it = lb; it != a.end(); it++) sum++; cout << sum << endl; return 0; }
14.814815
54
0.5175
c4c4e01696c18cdeaa7407ac894763a2ce5802da
3,552
hpp
C++
apps/Cocles/old_src/ledger/internal/Database.hpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
1
2022-02-11T21:25:53.000Z
2022-02-11T21:25:53.000Z
apps/Cocles/old_src/ledger/internal/Database.hpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
15
2021-08-21T13:41:29.000Z
2022-03-08T14:13:43.000Z
apps/Cocles/old_src/ledger/internal/Database.hpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
null
null
null
// License: The Unlicense (https://unlicense.org) #ifndef COCLES_LEDGER_INTERNAL_DATABASE_HPP #define COCLES_LEDGER_INTERNAL_DATABASE_HPP #include "AccountEntry.hpp" #include "AccountTypeEntry.hpp" #include "AdjustmentEntry.hpp" #include "FilteredTableView.hpp" #include "RecordKeeper.hpp" #include "TransactionEntry.hpp" template <typename TYPE> struct TableView; struct Database { Database(); // Methods for querying AccountTypes TableView<AccountType> get_account_type_table() const; const std::string& get_name(AccountTypeEntry record) const; AccountTypeEntry find_account_type_by_name(const std::string& name) const; // Methods for interacting with Accounts TableView<Account> get_account_table() const; AccountEntry new_account(); AccountEntry new_account(const std::string& name, AccountTypeEntry type); void clear_account_table(); void delete_account(AccountEntry record); const std::string& get_name(AccountEntry record) const; void set_name(AccountEntry record, const std::string& name); AccountEntry find_account_by_name(const std::string& name) const; AccountTypeEntry get_type(AccountEntry record) const; void set_type(AccountEntry record, AccountTypeEntry type); // TODO(tybl): find_account_by_type should be able to return many AccountEntrys FilteredTableView<Account> find_account_by_type(AccountTypeEntry type) const; // Methods for interacting with Transactions TableView<Transaction> get_transaction_table() const; TransactionEntry new_transaction(); TransactionEntry new_transaction(const date::year_month_day& date, const std::string& memo); void clear_transaction_table(); void delete_transaction(TransactionEntry record); const date::year_month_day get_date(TransactionEntry record) const; void set_date(TransactionEntry record, const date::year_month_day& date); // TODO(tybl): find_transaction_by_date should be able to return many TransactionEntrys FilteredTableView<Transaction> find_transaction_by_date(const date::year_month_day& date) const; const std::string& get_memo(TransactionEntry record) const; void set_memo(TransactionEntry record, const std::string& memo); TransactionEntry find_transaction_by_memo(const std::string& memo) const; // Methods for interacting with Adjustments TableView<Adjustment> get_adjustment_table() const; AdjustmentEntry new_adjustment(); AdjustmentEntry new_adjustment(AccountEntry account, TransactionEntry transaction); void clear_adjustment_table(); void delete_adjustment(AdjustmentEntry record); AccountEntry get_account(AdjustmentEntry record) const; void set_account(AdjustmentEntry record, AccountEntry account); // TODO(tybl): find_adjustment_by_account shoule be able to return many AdjustmentEntrys AdjustmentEntry find_adjustment_by_account(AccountEntry account) const; TransactionEntry get_transaction(AdjustmentEntry record) const; void set_transaction(AdjustmentEntry record, TransactionEntry transaction); // TODO(tybl): find_adjustment_by_transaction should be able to return many AdjustmentEntrys AdjustmentEntry find_adjustment_by_transaction(TransactionEntry transaction) const; private: ledger::internal::RecordKeeper<Account> account_table; ledger::internal::RecordKeeper<AccountType> account_type_table; ledger::internal::RecordKeeper<Adjustment> adjustment_table; ledger::internal::RecordKeeper<Transaction> transaction_table; }; #endif // COCLES_LEDGER_INTERNAL_DATABASE_HPP
33.509434
99
0.798142
df5ec6bf287d829339eb7b6c87ec00114b1a187f
894
cs
C#
Swindom/Swindom/Source/Settings/HotkeyInformation.cs
FreeEcho1/Swindom
54627a8e12e6a793546a1e712ba16777ef0b653f
[ "MIT" ]
null
null
null
Swindom/Swindom/Source/Settings/HotkeyInformation.cs
FreeEcho1/Swindom
54627a8e12e6a793546a1e712ba16777ef0b653f
[ "MIT" ]
null
null
null
Swindom/Swindom/Source/Settings/HotkeyInformation.cs
FreeEcho1/Swindom
54627a8e12e6a793546a1e712ba16777ef0b653f
[ "MIT" ]
null
null
null
namespace Swindom.Source.Settings { /// <summary> /// 「ホットキー」機能の情報 /// </summary> public class HotkeyInformation { /// <summary> /// 処理状態 (無効「false」/有効「true」) /// </summary> public bool Enabled = false; /// <summary> /// 画面外に出る場合は位置やサイズを変更しない (無効「false」/有効「true」) /// </summary> public bool DoNotChangeOutOfScreen = true; /// <summary> /// 全画面ウィンドウがある場合は処理停止 (無効「false」/有効「true」) /// </summary> public bool StopProcessingFullScreen = false; /// <summary> /// ホットキーの追加/修正ウィンドウのサイズ /// </summary> public System.Drawing.Size AddModifyWindowSize = new(); /// <summary> /// 「ホットキー」機能の項目情報 /// </summary> public System.Collections.Generic.List<HotkeyItemInformation> Items = new(); } }
29.8
85
0.525727
32670496faff12569f9b70e81b7e89c83683d658
4,304
kt
Kotlin
app/src/main/java/io/exzocoin/wallet/modules/market/home/MarketHomeFragment.kt
rexdev0211/exzo-android-wallet-main
1ed5d80490ecf1574499cafa5aad922c4ea9a362
[ "MIT" ]
null
null
null
app/src/main/java/io/exzocoin/wallet/modules/market/home/MarketHomeFragment.kt
rexdev0211/exzo-android-wallet-main
1ed5d80490ecf1574499cafa5aad922c4ea9a362
[ "MIT" ]
null
null
null
app/src/main/java/io/exzocoin/wallet/modules/market/home/MarketHomeFragment.kt
rexdev0211/exzo-android-wallet-main
1ed5d80490ecf1574499cafa5aad922c4ea9a362
[ "MIT" ]
null
null
null
package io.exzocoin.wallet.modules.market.home import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.recyclerview.widget.ConcatAdapter import io.exzocoin.wallet.R import io.exzocoin.wallet.core.BaseFragment import io.exzocoin.wallet.modules.market.* import io.exzocoin.wallet.modules.market.list.MarketListViewModel import io.exzocoin.wallet.modules.coin.CoinFragment import io.exzocoin.core.findNavController import io.exzocoin.core.helpers.HudHelper import io.exzocoin.wallet.core.managers.ProjectManager import io.exzocoin.wallet.modules.transactions.FilterAdapter import kotlinx.android.synthetic.main.fragment_market_discovery.coinRatesRecyclerView import kotlinx.android.synthetic.main.fragment_market_home.* import kotlinx.android.synthetic.main.fragment_market_home.tabLayout class MarketHomeFragment : BaseFragment(), ViewHolderMarketItem.Listener, FilterAdapter.Listener { private val vmFactory = MarketHomeDiscoveryModule.Factory() private val marketDiscoveryViewModel by viewModels<MarketHomeViewModel> { vmFactory } private val marketListViewModel by viewModels<MarketListViewModel> { vmFactory } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_market_home, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val marketItemsAdapter = MarketItemsAdapter( this, marketListViewModel.marketViewItemsLiveData, marketListViewModel.loadingLiveData, marketListViewModel.errorLiveData, viewLifecycleOwner ) val marketLoadingAdapter = MarketLoadingAdapter( marketListViewModel.loadingLiveData, marketListViewModel.errorLiveData, marketListViewModel::onErrorClick, viewLifecycleOwner ) val filterAdapter = FilterAdapter(this) recyclerTags.adapter = filterAdapter filterAdapter.setFilters(marketListViewModel.sortingFields.map { FilterAdapter.FilterItem(getString(it.titleResId)) }, FilterAdapter.FilterItem(getString(marketListViewModel.sortingField.titleResId))) coinRatesRecyclerView.adapter = ConcatAdapter(marketLoadingAdapter, marketItemsAdapter) coinRatesRecyclerView.itemAnimator = null /*pullToRefresh.setOnRefreshListener { marketListViewModel.refresh() pullToRefresh.isRefreshing = false }*/ marketListViewModel.networkNotAvailable.observe(viewLifecycleOwner, { HudHelper.showErrorMessage(requireView(), R.string.Hud_Text_NoInternet) }) ProjectManager.getFeaturedProjects() .subscribe({ val size = it.size Log.d("Test", size.toString()) val marketCategoriesAdapter = MarketFeaturedProjectAdapter(requireContext(), tabLayout, it) }, { Log.d("Error", it.message.toString()) }) ProjectManager.getAds() .subscribe({ val size = it.size Log.d("Test", size.toString()) val marketAdsAdapter = MarketAdsAdapter(requireContext()) marketAdsAdapter.setItems(it) adsSlider.setSliderAdapter(marketAdsAdapter) }, { Log.d("Error", it.message.toString()) }) } override fun onItemClick(marketViewItem: MarketViewItem) { val arguments = CoinFragment.prepareParams(marketViewItem.coinType, marketViewItem.coinCode, marketViewItem.coinName) findNavController().navigate(R.id.coinFragment, arguments, navOptions()) } override fun onFilterItemClick( item: FilterAdapter.FilterItem?, itemPosition: Int, itemWidth: Int ) { //TODO("Not yet implemented") val selectedSortingField = marketListViewModel.sortingFields[itemPosition] marketListViewModel.update(sortingField = selectedSortingField) } }
40.603774
125
0.709572
a47a40e468881341ec4b48e8d8f1fd3a55334b63
979
php
PHP
Helpers/NavItem.php
pennline/html
b7e3fefa335335858882dd69a4ee728a4c8e5a98
[ "MIT" ]
null
null
null
Helpers/NavItem.php
pennline/html
b7e3fefa335335858882dd69a4ee728a4c8e5a98
[ "MIT" ]
null
null
null
Helpers/NavItem.php
pennline/html
b7e3fefa335335858882dd69a4ee728a4c8e5a98
[ "MIT" ]
null
null
null
<?php namespace Pennline\Html\Helpers; class NavItem { /** * @var string */ public $href; /** * @var string */ public $page; /** * @var string */ public $title; /** * @param array $item */ public function __construct( $item = array() ) { $this->init(); $this->populate( $item ); } protected function init() { $this->href = ''; $this->page = ''; $this->title = ''; } /** * @param array $item */ public function populate( $item = array() ) { if ( !is_array( $item ) ) { error_log( __METHOD__ . '() $item provided is not an array' ); throw new Exception( 'parameter type error', 1 ); } if ( isset( $item['href'] ) ) { $this->href = filter_var( $item['href'], FILTER_SANITIZE_STRING ); } if ( isset( $item['page'] ) ) { $this->page = filter_var( $item['page'], FILTER_SANITIZE_STRING ); } if ( isset ( $item['title'] ) ) { $this->title = filter_var( $item['title'], FILTER_SANITIZE_STRING ); } } }
17.175439
71
0.560776
c6c2fcceff553d17c4d0292f5512365bcfb675c5
212
css
CSS
src/main/webapp/css/housing.css
juliepwchen/PACT
decb30fdc379cc1218a6de4d9a58dffb758bb6be
[ "MIT" ]
1
2020-03-05T20:25:38.000Z
2020-03-05T20:25:38.000Z
src/main/webapp/css/housing.css
juliepwchen/PACT
decb30fdc379cc1218a6de4d9a58dffb758bb6be
[ "MIT" ]
null
null
null
src/main/webapp/css/housing.css
juliepwchen/PACT
decb30fdc379cc1218a6de4d9a58dffb758bb6be
[ "MIT" ]
null
null
null
.nav, .pagination, .carousel, .panel-title a { cursor: pointer; } .panel-default > .panel-heading { background-color: #7FE5CC; text-align: center; font-size: 12px; } ul.u { list-style-type: none; }
15.142857
46
0.646226
c3f000e008ecf2075a366084fa316df79c113454
1,271
cs
C#
src/NnCase.CodeGen/Operators/StridedSlice.cs
dotnetGame/nncase
09d40c6a9194542bb5a5fc2b8c74e0e8ed193486
[ "Apache-2.0" ]
11
2018-04-04T17:03:46.000Z
2020-11-26T08:54:58.000Z
src/NnCase.CodeGen/Operators/StridedSlice.cs
dotnetGame/nncase
09d40c6a9194542bb5a5fc2b8c74e0e8ed193486
[ "Apache-2.0" ]
null
null
null
src/NnCase.CodeGen/Operators/StridedSlice.cs
dotnetGame/nncase
09d40c6a9194542bb5a5fc2b8c74e0e8ed193486
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Text; using NnCase.Evaluation; using NnCase.Evaluation.Operators; using NnCase.IR; using NnCase.IR.Operators; using NnCase.Runtime.Operators; namespace NnCase.CodeGen.Operators { internal static partial class DefaultEmitters { private static void RegisterStridedSlice(CodeGenRegistry registry) { registry.Add<StridedSlice>((n, g) => { return new StridedSliceOptionsBody { Options = new StridedSliceOptions { Input = g.MemoryRange(n.Input), Output = g.MemoryRange(n.Output), InputShape = OpUtility.To(n.Input.Shape), Begin = OpUtility.To(n.Begin), End = OpUtility.To(n.End), Strides = OpUtility.To(n.Strides), BeginMask = n.BeginMask, EndMask = n.EndMask, EllipsisMask = n.EllipsisMask, NewAxisMask = n.NewAxisMask, ShrinkAxisMask = n.ShrinkAxisMask } }; }); } } }
32.589744
74
0.505901
7af468b3b84a22b573f1dc5d31d5b5d06225788c
1,598
cs
C#
src/VendingMachine/DataAccess/Queries/ShowVendingMachineQuery.cs
DrunkyBard/VendingMachine
0c48a3df9ecdf90ab4efcad4972c9ae8156c76b1
[ "MIT" ]
null
null
null
src/VendingMachine/DataAccess/Queries/ShowVendingMachineQuery.cs
DrunkyBard/VendingMachine
0c48a3df9ecdf90ab4efcad4972c9ae8156c76b1
[ "MIT" ]
null
null
null
src/VendingMachine/DataAccess/Queries/ShowVendingMachineQuery.cs
DrunkyBard/VendingMachine
0c48a3df9ecdf90ab4efcad4972c9ae8156c76b1
[ "MIT" ]
null
null
null
using System.Linq; using VendingMachineApp.DataAccess.EF; using VendingMachineApp.DataAccess.Entities; using VendingMachineApp.Models; namespace VendingMachineApp.DataAccess.Queries { public sealed class ShowVendingMachineQuery { public VendingMachineViewModel Ask() { using (var dbContext = new VendingMachineDbContext()) { var vMachine = dbContext.Set<VendingMachineEntity>().Single(); var buyer = dbContext.Set<UserEntity>().Single(); var vMachineWallet = vMachine.Coins .Select(c => new CoinViewModel { ParValue = c.FaceValue, Count = c.Count }).ToList(); var buyerWallet = buyer.Coins .Select(c => new CoinViewModel { ParValue = c.FaceValue, Count = c.Count }).ToList(); var availableGoods = vMachine.Goods .Select(g => new GoodsViewModel { Identity = g.Id, Name = g.Name, Price = g.Price, Count = g.Count }).ToList(); return new VendingMachineViewModel { AvailableGoods = availableGoods, BuyerWallet = buyerWallet, MachineWallet = vMachineWallet }; } } } }
34
78
0.463705
b1006b6718db945a22535933aaea8a2aa65f4eb2
961
sql
SQL
fuel/app/databases/ddl/20180511191300_LASHIC-34.sql
binh-lashic/lashic-care-web
6c8d50c371eabdd3980318eb0b66fbe9cb525f43
[ "MIT" ]
null
null
null
fuel/app/databases/ddl/20180511191300_LASHIC-34.sql
binh-lashic/lashic-care-web
6c8d50c371eabdd3980318eb0b66fbe9cb525f43
[ "MIT" ]
null
null
null
fuel/app/databases/ddl/20180511191300_LASHIC-34.sql
binh-lashic/lashic-care-web
6c8d50c371eabdd3980318eb0b66fbe9cb525f43
[ "MIT" ]
null
null
null
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[nurse_call_data_daily]( [id] [int] IDENTITY (1, 1) NOT NULL, [sensor_name] [nvarchar](255) NOT NULL, [status] [int] NOT NULL, [measurement_time] [datetime] NOT NULL, [created_at] [datetime] NOT NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[nurse_call_data_daily] ADD PRIMARY KEY CLUSTERED ( [id] ASC )WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY] GO SET ANSI_PADDING ON GO CREATE NONCLUSTERED INDEX [idx_nurse_call_data_daily_001] ON [dbo].[nurse_call_data_daily] ( [sensor_name] ASC, [measurement_time] ASC )WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY] GO SET ANSI_PADDING ON GO ALTER TABLE [dbo].[nurse_call_data_daily] ADD DEFAULT (NEXT VALUE FOR [nurse_call_data_daily_id_counter]) FOR [id] GO ALTER TABLE [dbo].[nurse_call_data_daily] ADD DEFAULT (dateadd(hour,(9),getutcdate())) FOR [created_at] GO
28.264706
115
0.756504
f449997000fd0a3e7dbf3c70e9350139b71da7a0
2,202
ts
TypeScript
packages/server/src/service/contact/search.ts
ccardozov/mail-my-ballot
d5e8d62e30ffcfb04ba27464dd3c300a3756c972
[ "Apache-2.0" ]
null
null
null
packages/server/src/service/contact/search.ts
ccardozov/mail-my-ballot
d5e8d62e30ffcfb04ba27464dd3c300a3756c972
[ "Apache-2.0" ]
6
2020-05-26T23:46:25.000Z
2020-05-27T04:54:19.000Z
packages/server/src/service/contact/search.ts
ythecombinator/mail-my-ballot
5efbd96a21301a990d7b0850cf171cfd59c29f7e
[ "Apache-2.0" ]
null
null
null
import { Locale, AvailableState } from "../../common" import { normalizeLocale } from "./normalize" const citySuffixes = (suffixes: string[], city: string): string[] => { if (suffixes.some(suffix => city.endsWith(suffix))) { return [city] } return [city, ...suffixes.map(suffix => city + suffix)] } /* add in possible prefixes, assuming larger entities are most likely to have prefix dropped */ const possibleBeginnings = [ 'City of ', 'Town of ', 'Village of ', ] const wisconsinCities = (city: string): string[] => { if (possibleBeginnings.some(beginning => city.startsWith(beginning))) { return [city] } return [city, ...possibleBeginnings.map(beginning => beginning + city)] } /* cities that span multiple counties are listed without a county */ const wisconsinCounties = (county: string): string[] => { return [county, ''] } /** States that have cities independent of counties. These are usually for large cities * So just try matching on cities first and then county if city doesn't match */ const keysCityState = (locale: Locale<AvailableState>): string[] => { const cityLocales = citySuffixes([' City'], locale.city) .map(city => normalizeLocale({...locale, city})) const countyLocales = normalizeLocale({...locale, city: ''}) return cityLocales.concat([countyLocales]) } /* list of keys to try (in order) */ export const keys = ( locale: Locale<AvailableState>, ): string[] => { switch(locale.state) { case 'Arizona': case 'Florida': case 'Georgia': case 'Maine': case 'Minnesota': case 'Nebraska': case 'New York': { return [normalizeLocale(locale)] } case 'Michigan': { return citySuffixes([ ' City', ' Township', ' Charter Township', ], locale.city).map(city => normalizeLocale({...locale, city})) } case 'Wisconsin': { if (!locale.county) return [] return wisconsinCounties(locale.county).flatMap(county => wisconsinCities(locale.city).map(city => normalizeLocale({...locale, city, county}) ) ) } case 'Maryland': case 'Virginia': case 'Nevada': { return keysCityState(locale) } } }
29.756757
95
0.638965
24bfb64b49a7718dadbfdba353dead018489d4bc
4,625
php
PHP
www/lib/FileLog.class.php
hyeonseok/pajet
6d7be444bbc086c031bfc4d09207beadb2bf343c
[ "MIT" ]
2
2017-09-06T05:30:35.000Z
2021-03-24T05:44:38.000Z
www/lib/FileLog.class.php
hyeonseok/pajet
6d7be444bbc086c031bfc4d09207beadb2bf343c
[ "MIT" ]
1
2018-07-03T02:49:57.000Z
2018-07-03T02:49:57.000Z
www/lib/FileLog.class.php
hyeonseok/pajet
6d7be444bbc086c031bfc4d09207beadb2bf343c
[ "MIT" ]
1
2017-06-28T13:40:30.000Z
2017-06-28T13:40:30.000Z
<?php /** * Stores array data in simple tsv like file format. * Retrives data by range, date, keyword search. */ class FileLog { private $structure; private $file_name; public function __construct($file_name, $structure = null, $overwrite = false) { date_default_timezone_set('Asia/Seoul'); $this->file_name = $file_name; if (!file_exists($this->file_name) && ($structure == null || is_array($structure) === false)) { $this->trace('You must specify file structure.' . "\n"); } if (!file_exists($this->file_name) || $overwrite == true) { fwrite(fopen($this->file_name, 'w'), implode("\t", $structure) . "\n"); } if ($structure == null) { $structure_string = fgets(fopen($this->file_name, 'r')); $this->structure = explode("\t", trim($structure_string)); } else { $this->structure = $structure; } } private function trace($message) { echo($message . "\n"); exit(); } private function format_row($row) { $split = explode("\t", trim($row)); $row_data = array(); foreach ($this->structure as $key => $field) { $row_data[$field] = $this->decode_string($split[$key]); } return $row_data; } private function encode_string($str) { $str = str_replace("\\", "\\\\", $str); $str = str_replace("\t", "\\t", $str); $str = str_replace("\r", "\\r", $str); $str = str_replace("\n", "\\n", $str); return $str; } private function decode_string($str) { $decoded_string = ''; while (($slash_position = strpos($str, "\\")) !== false ) { $former_string = substr($str, 0, $slash_position); $next_character = substr($str, $slash_position + 1, 1); $latter_string = substr($str, $slash_position + 2); if ($next_character == "\\") { $replace_character = "\\"; } else if ($next_character == "t") { $replace_character = "\t"; } else if ($next_character == "r") { $replace_character = "\r"; } else if ($next_character == "n") { $replace_character = "\n"; } $decoded_string .= $former_string . $replace_character; $str = $latter_string; } return $decoded_string . $str; } public function save($data) { $fp = fopen($this->file_name, 'a'); if (count($this->structure) != count($data)) { $this->trace('Data length mismatched. ' . count($this->structure) . ' vs. ' . count($data)); } foreach ($data as $item) { $str .= $this->encode_string($item) . "\t"; } $str .= "\n"; $str = str_replace("\t\n", "\n", $str); fwrite($fp, $str); fclose($fp); } public function load($offset = false, $length = false) { $data = array(); $count = 0; $fp = fopen($this->file_name, 'r'); while (($buffer = fgets($fp)) !== false) { if ($count == 0) { $count = 1; continue; } $count++; if (strlen(trim($buffer)) < 1) { continue; } if ($offset !== false && $length !== false && $count - 1 < $offset + 1) { continue; } if ($offset !== false && $length !== false && $count - 1 > $offset + $length) { break; } array_push($data, $formatted_row = $this->format_row($buffer)); if ($offset !== false && $length === false && $offset < 0 && count($data) > $offset * -1) { array_shift($data); } } fclose($fp); return $data; } public function load_by_date($start_date, $end_date, $field_name) { $data = array(); $fp = fopen($this->file_name, 'r'); while (($buffer = fgets($fp)) !== false) { if (strlen(trim($buffer)) < 1) { continue; } $formatted_row = $this->format_row($buffer); if (!(strtotime($start_date) <= $formatted_row[$field_name] && strtotime($end_date) >= $formatted_row[$field_name])) { continue; } array_push($data, $formatted_row); } fclose($fp); return $data; } public function load_by_match($keyword, $field_name = null, $unique = false) { $data = array(); $fp = fopen($this->file_name, 'r'); while (($buffer = fgets($fp)) !== false) { if (strlen(trim($buffer)) < 1) { continue; } $formatted_row = $this->format_row($buffer); if ($formatted_row[$field_name] != $keyword) { continue; } array_push($data, $formatted_row); } fclose($fp); if ($unique) { $data = $data[count($data) - 1]; } return $data; } public function load_by_search($keyword, $field_name = null) { $data = array(); $fp = fopen($this->file_name, 'r'); while (($buffer = fgets($fp)) !== false) { if (strlen(trim($buffer)) < 1) { continue; } $formatted_row = $this->format_row($buffer); if (strpos($formatted_row[$field_name], $keyword) === false) { continue; } array_push($data, $formatted_row); } fclose($fp); return $data; } } ?>
25.412088
121
0.583351
ed0cedf0de41fa9592ce0a32807c986f8c4fd845
2,087
h
C
src/include/RingBufferWriter.h
nemo110110/RingBuffers
9c4906a892314bcfeddd8fc6e847031f039fa995
[ "MIT" ]
null
null
null
src/include/RingBufferWriter.h
nemo110110/RingBuffers
9c4906a892314bcfeddd8fc6e847031f039fa995
[ "MIT" ]
null
null
null
src/include/RingBufferWriter.h
nemo110110/RingBuffers
9c4906a892314bcfeddd8fc6e847031f039fa995
[ "MIT" ]
1
2021-11-20T11:07:12.000Z
2021-11-20T11:07:12.000Z
#ifndef RINGBUFFERWRITER_H #define RINGBUFFERWRITER_H #include "ARingBufferWriter.h" template<class T> class RingBuffer; template<class T> class RingBufferReader; template<class T> class RingBufferWriter : public ARingBufferWriter<T> { friend class RingBuffer<T>; friend class RingBufferReader<T>; private: RingBufferWriter<T>(RingBuffer<T> *rb); int available() const override; protected: // TODO Replace with simple ARingBuffer<T>* data member? inline RingBuffer<T> *ringBuffer() const override { return rb; } void acquireResources(int count) override; void releaseResources(int count) override; private: RingBuffer<T> * const rb; }; #include "RingBuffer.h" #include "RingBufferReader.h" #include <stdexcept> #include <list> template<class T> RingBufferWriter<T>::RingBufferWriter(RingBuffer<T> *rb) : ARingBufferWriter<T>(), rb(rb) { } template<class T> int RingBufferWriter<T>::available() const { std::list<ARingBufferReader<T>*> *readers = &rb->readers; int min = this->ringBuffer()->capacity; int current; for (typename std::list<ARingBufferReader<T>*>::const_iterator it = readers->begin(); it != readers->end(); ++it) { current = rb->capacity - static_cast<RingBufferReader<T>*>(*it)->ahead; if (current < min) { min = current; } } return min; } template<class T> void RingBufferWriter<T>::acquireResources(int count) { std::list<ARingBufferReader<T>*> *readers = &rb->readers; RingBufferReader<T> *reader; for (typename std::list<ARingBufferReader<T>*>::iterator it = readers->begin(); it != readers->end(); ++it) { reader = static_cast<RingBufferReader<T>*>(*it); if (rb->capacity - reader->ahead < count) { throw std::runtime_error("Insufficient available space in RingBuffer for RingBufferWriter resource acquisition"); } reader->ahead += count; } } template<class T> void RingBufferWriter<T>::releaseResources(int count) { } #endif // RINGBUFFERWRITER_H
26.0875
125
0.669861
3c00898793b1874268eaec1eabf198a9dc7c30e8
514
lua
Lua
gamemode/player_class/player_spectator.lua
MattJeanes/ObjHunt
0c98cdfa3bd519d84ba6b4c3fab1dc747958e896
[ "Apache-2.0" ]
16
2015-03-23T04:34:07.000Z
2021-08-16T01:18:12.000Z
gamemode/player_class/player_spectator.lua
MattJeanes/ObjHunt
0c98cdfa3bd519d84ba6b4c3fab1dc747958e896
[ "Apache-2.0" ]
33
2015-03-10T21:40:03.000Z
2020-03-22T07:09:40.000Z
gamemode/player_class/player_spectator.lua
MattJeanes/ObjHunt
0c98cdfa3bd519d84ba6b4c3fab1dc747958e896
[ "Apache-2.0" ]
18
2015-01-11T00:07:59.000Z
2021-09-06T12:33:48.000Z
DEFINE_BASECLASS( "player_default" ) local PLAYER = {} -- -- See gamemodes/base/player_class/player_default.lua for all overridable variables -- PLAYER.DisplayName = "Spectator" PLAYER.SetObserverMode = 6 PLAYER.CanUseFlashlight = false PLAYER.AvoidPlayers = false PLAYER.lastTaunt = 0.0 function PLAYER:Spawn() self.Player:Spectate( OBS_MODE_ROAMING ) end function PLAYER:Loadout() self.Player:RemoveAllAmmo() end player_manager.RegisterClass( "player_spectator", PLAYER, "player_default" )
22.347826
83
0.764591
0a52ffc56e048d37aae59bdd20ee65a57cc29015
3,539
cs
C#
Xal/Extensions/RandomExtensions.cs
alexandretperez/Xal
c72ef1994ff60d245d017a3ab081e41d7c94747e
[ "MIT" ]
2
2019-04-01T15:00:17.000Z
2022-03-01T20:36:37.000Z
Xal/Extensions/RandomExtensions.cs
alexandretperez/Xal
c72ef1994ff60d245d017a3ab081e41d7c94747e
[ "MIT" ]
null
null
null
Xal/Extensions/RandomExtensions.cs
alexandretperez/Xal
c72ef1994ff60d245d017a3ab081e41d7c94747e
[ "MIT" ]
1
2020-06-25T12:22:02.000Z
2020-06-25T12:22:02.000Z
using System; using System.Collections.Generic; namespace Xal.Extensions { /// <summary> /// Provides extension methods for <see cref="Random"/> objects. /// </summary> public static class RandomExtensions { /// <summary> /// Generates a random string with the specified <paramref name="length"/> based on the <paramref name="chars"/>. /// </summary> /// <param name="random">The Random instance.</param> /// <param name="length">The length of the string.</param> /// <param name="chars">The desired chars to randomize.</param> /// <exception cref="OverflowException"><paramref name="length"/> exceeds matrix dimensions.</exception> /// <returns>A randomized string</returns> public static string NextString(this Random random, int length, string chars) { var buffer = new char[length]; var maxLen = chars.Length; for (int i = 0, j = length; i < j; i++) { var index = random.Next(maxLen); buffer[i] = chars[index]; } return new string(buffer); } /// <summary> /// Generates a random string with the specified <paramref name="length"/>. /// </summary> /// <param name="random">The Random instance.</param> /// <param name="length">The length of the string.</param> /// <exception cref="OverflowException"><paramref name="length"/> exceeds matrix dimensions.</exception> /// <returns>A randomized string</returns> public static string NextString(this Random random, int length) { return NextString(random, length, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789"); } /// <summary> /// Generates a sequence of a random values based on the <paramref name="generator"/>. /// </summary> /// <typeparam name="T">The type of the elements in the sequence.</typeparam> /// <param name="_">The Random instance.</param> /// <param name="generator">The value generator.</param> /// <param name="size">The number of items to generate in the sequence.</param> /// <returns>A sequence of <typeparamref name="T"/></returns> public static IEnumerable<T> NextSequence<T>(this Random _, Func<int, T> generator, int size) { for (int i = 0; i < size; i++) yield return generator(i); } /// <summary> /// Generates a sequence of a random values based on the <paramref name="generator"/>. The size vary between 1 and 100 elements. /// </summary> /// <typeparam name="T">The type of the elements in the sequence.</typeparam> /// <param name="random">The Random instance.</param> /// <param name="generator">The value generator.</param> /// <returns>A sequence of <typeparamref name="T"/></returns> public static IEnumerable<T> NextSequence<T>(this Random random, Func<int, T> generator) { return NextSequence(random, generator, random.Next(1, 101)); } /// <summary> /// Generates a boolean value <c>true</c> or <c>false</c>. /// </summary> /// <param name="random">The Random instance.</param> /// <returns>A boolean value <c>true</c> or <c>false</c></returns> public static bool NextBoolean(this Random random) { return random.Next(0, 2) == 1; } } }
44.2375
136
0.587737
54eb79b71335eed178a2c984e87ee4b527d44c31
6,292
cc
C++
chromium/chrome/browser/external_extension_browsertest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/external_extension_browsertest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/external_extension_browsertest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "base/command_line.h" #include "base/macros.h" #include "base/prefs/pref_service.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/google/core/browser/google_switches.h" #include "components/search_engines/search_engines_pref_names.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" namespace { struct IsSearchProviderTestData { IsSearchProviderTestData() : tab(NULL) {} IsSearchProviderTestData(content::WebContents* t, const std::string& h, GURL url) : tab(t), host(h), test_url(url) {} content::WebContents* tab; std::string host; GURL test_url; }; } // namespace class SearchProviderTest : public InProcessBrowserTest { protected: SearchProviderTest() {} void SetUpCommandLine(base::CommandLine* command_line) override { ASSERT_TRUE(embedded_test_server()->Start()); // Map all hosts to our local server. std::string host_rule("MAP * " + embedded_test_server()->host_port_pair().ToString()); command_line->AppendSwitchASCII(switches::kHostRules, host_rule); // Use no proxy or otherwise this test will fail on a machine that has a // proxy configured. command_line->AppendSwitch(switches::kNoProxyServer); // Always point google search to a known, non-secure URL. Normally, this // varies based on locale and is a HTTPS host. command_line->AppendSwitchASCII( switches::kGoogleBaseURL, "http://www.google.com"); // Get the url for the test page. search_provider_test_url_ = embedded_test_server()->GetURL("/is_search_provider_installed.html"); } void SetUpOnMainThread() override { // Force the country to Canada, which has an installed search provider // that's HTTP. browser()->profile()->GetPrefs()->SetInteger( prefs::kCountryIDAtInstall, ('C' << 8) | 'A'); } IsSearchProviderTestData StartIsSearchProviderInstalledTest( Browser* browser, const char* host, const char* expected_result) { GURL test_url(std::string("http://") + host + search_provider_test_url_.path() + "#" + expected_result); ui_test_utils::NavigateToURLWithDisposition( browser, test_url, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Bundle up information needed to verify the result. content::WebContents* tab = browser->tab_strip_model()->GetActiveWebContents(); return IsSearchProviderTestData(tab, host, test_url); } void FinishIsSearchProviderInstalledTest( const IsSearchProviderTestData& data) { base::string16 title = data.tab->GetTitle(); if (title.empty()) { content::TitleWatcher title_watcher(data.tab, base::ASCIIToUTF16("OK")); title_watcher.AlsoWaitForTitle(base::ASCIIToUTF16("FAIL")); title = title_watcher.WaitAndGetTitle(); } EXPECT_EQ(base::ASCIIToUTF16("OK"), title); } GURL search_provider_test_url_; private: DISALLOW_COPY_AND_ASSIGN(SearchProviderTest); }; #if defined(OS_WIN) // This is flaking on XP. See http://crbug.com/159530 #define MAYBE_TestIsSearchProviderInstalled \ DISABLED_TestIsSearchProviderInstalled #else #define MAYBE_TestIsSearchProviderInstalled TestIsSearchProviderInstalled #endif IN_PROC_BROWSER_TEST_F(SearchProviderTest, MAYBE_TestIsSearchProviderInstalled) { // Use the default search provider, other installed search provider, and // one not installed as well. Note, Ask is used here because it's a HTTP host. const char* test_hosts[] = { "www.google.com", "www.ask.com", "localhost" }; const char* expected_results[] = { "2", "1", "0" }; static_assert(arraysize(test_hosts) == arraysize(expected_results), "each host should have a test result"); IsSearchProviderTestData test_data[2 * arraysize(test_hosts)]; // Start results for the normal mode. for (size_t i = 0; i < arraysize(test_hosts); ++i) { test_data[i] = StartIsSearchProviderInstalledTest( browser(), test_hosts[i], expected_results[i]); FinishIsSearchProviderInstalledTest(test_data[i]); } // Start tests for incognito mode (and verify the result is 0). Browser* incognito_browser = CreateIncognitoBrowser(); for (size_t i = 0; i < arraysize(test_hosts); ++i) { test_data[i + arraysize(test_hosts)] = StartIsSearchProviderInstalledTest( incognito_browser, test_hosts[i], "0"); FinishIsSearchProviderInstalledTest(test_data[i + arraysize(test_hosts)]); } // The following should be re-enabled. At the moment, there are problems with // doing all of these queries in parallel -- see http://crbug.com/60043. #if 0 // Remove the calls to FinishIsSearchProviderInstalledTest above when // re-enabling this code. // Do the verification. for (size_t i = 0; i < arraysize(test_data); ++i) { FinishIsSearchProviderInstalledTest(test_data[i]); } #endif } IN_PROC_BROWSER_TEST_F(SearchProviderTest, TestIsSearchProviderInstalledWithException) { // Change the url for the test page to one that throws an exception when // toString is called on the argument given to isSearchProviderInstalled. search_provider_test_url_ = embedded_test_server()->GetURL( "/is_search_provider_installed_with_exception.html"); FinishIsSearchProviderInstalledTest(StartIsSearchProviderInstalledTest( browser(), "www.google.com", "")); }
37.903614
80
0.706135
cfab50d327446117bb01cefb5f39f0f426f13e75
1,169
dart
Dart
geography/lib/src/countries/anguilla.dart
GioCirque/dart-pub
44ae54c0cb6260d2ce3a1758f3fec080f1fa4556
[ "BSD-3-Clause" ]
2
2022-01-17T15:16:08.000Z
2022-01-19T13:27:19.000Z
geography/lib/src/countries/anguilla.dart
GioCirque/pub-dev
44ae54c0cb6260d2ce3a1758f3fec080f1fa4556
[ "BSD-3-Clause" ]
null
null
null
geography/lib/src/countries/anguilla.dart
GioCirque/pub-dev
44ae54c0cb6260d2ce3a1758f3fec080f1fa4556
[ "BSD-3-Clause" ]
null
null
null
/// Access to known geographies in Anguilla and their meta data. /// /// NOTICE: This file is auto-generated and should not be changed manually. import '../base.dart'; /// The country of `🇦🇮 Anguilla`, and its 0 states const Country anguilla = Country( id: 8, name: "Anguilla", longitude: -63.16666666, latitude: 18.25, capital: "The Valley", currency: "XCD", currencySymbol: "\$", emoji: "🇦🇮", emojiU: "U+1F1E6 U+1F1EE", iso2: "AI", iso3: "AIA", native: "Anguilla", numericCode: "660", phoneCode: "+1-264", region: "Americas", subregion: "Caribbean", tld: ".ai", states: [], timezones: [ Timezone( abbreviation: "AST", gmtOffset: -14400, gmtOffsetName: "UTC-04:00", tzName: "Atlantic Standard Time", zoneName: "America/Anguilla") ], translations: { "kr": "앵귈라", "br": "Anguila", "pt": "Anguila", "nl": "Anguilla", "hr": "Angvila", "fa": "آنگویلا", "de": "Anguilla", "es": "Anguilla", "fr": "Anguilla", "ja": "アンギラ", "it": "Anguilla", "cn": "安圭拉" });
23.857143
75
0.528657
650fea2f66a943f61a7df67af06d5e7c6c5c9522
418
sql
SQL
egov/egov-tl/src/main/resources/db/migration/main/V20170704142131__tl_roleaction_view_dcb.sql
getwasim/egov-smartcity-suites-test
361238c743d046080d66b7fcbe44673a8a784be2
[ "MIT" ]
1
2019-07-25T12:44:57.000Z
2019-07-25T12:44:57.000Z
egov/egov-tl/src/main/resources/db/migration/main/V20170704142131__tl_roleaction_view_dcb.sql
getwasim/egov-smartcity-suites-test
361238c743d046080d66b7fcbe44673a8a784be2
[ "MIT" ]
13
2020-03-05T00:01:16.000Z
2022-02-09T22:58:42.000Z
egov/egov-tl/src/main/resources/db/migration/main/V20170704142131__tl_roleaction_view_dcb.sql
getwasim/egov-smartcity-suites-test
361238c743d046080d66b7fcbe44673a8a784be2
[ "MIT" ]
1
2021-02-22T21:09:08.000Z
2021-02-22T21:09:08.000Z
insert into eg_roleaction values ((select id from eg_role where name='TLCreator'),(select id from eg_action where url like '/dcb/view')); insert into eg_roleaction values ((select id from eg_role where name='TLApprover'),(select id from eg_action where url like '/dcb/view')); insert into eg_roleaction values ((select id from eg_role where name='CSC Operator'),(select id from eg_action where url like '/dcb/view'));
104.5
140
0.767943
865e4970b3449f2ad7601d2c87ee4d836df3eb3a
8,546
lua
Lua
Lua/Libraries/CYK/TPBar.lua
flxLumyni/CreateYourKris
6400e3639c4c0ec80869818cc5c9d7ddd4e8d73d
[ "BSD-3-Clause" ]
30
2019-03-09T17:39:27.000Z
2022-01-07T20:13:44.000Z
Lua/Libraries/CYK/TPBar.lua
flxLumyni/CreateYourKris
6400e3639c4c0ec80869818cc5c9d7ddd4e8d73d
[ "BSD-3-Clause" ]
13
2019-02-03T05:52:02.000Z
2021-11-29T15:36:58.000Z
Lua/Libraries/CYK/TPBar.lua
flxLumyni/CreateYourKris
6400e3639c4c0ec80869818cc5c9d7ddd4e8d73d
[ "BSD-3-Clause" ]
15
2019-03-25T20:23:15.000Z
2022-02-15T18:59:43.000Z
return function(CreateYourKris) -- TP bar and info local self = { } self.CreateYourKris = CreateYourKris -- CYK core self.ySize = 187 -- Y size of the TP bar self.trueValue = 0 -- TP the team has self.barValue = 0 -- TP value used to display the bar self.previewValue = 0 -- TP value used to display the bar's preview (white bar) self.barSpeed = 1 -- Speed at which the bar can change per frame self.previewSpeed = 4 -- Speed at which the preview bar can change per frame self.bgColor32 = { 128, 0, 0 } -- Color of the TP bar's background self.noFullColor32 = { 255, 160, 64 } -- Color of the TP bar when not full self.fullColor32 = { 255, 208, 32 } -- Color of the TP bar when full self.previewUpColor32 = { 255, 255, 255 } -- Color of one of the preview bars of the TP bar self.previewDownColor32 = { 255, 0, 0 } -- Color of one of the preview bars of the TP bar self.isLossPreviewed = false -- Are we in the MAGIC choice, showing the TP loss if we choose this option? self.bar = { } -- TP bar background self.bar.bg = CreateSprite("px", "UpperUI") self.bar.bg.Scale(19, 187) self.bar.bg.SetPivot(0, 1) self.bar.bg.absx = 41 self.bar.bg.absy = 435 self.bar.bg.color32 = self.bgColor32 -- TP bar (white gauge) self.bar.preview = CreateSprite("px") self.bar.preview.SetParent(self.bar.bg) self.bar.preview.Scale(19, 0) self.bar.preview.SetAnchor(0, 0) self.bar.preview.SetPivot(0, 0) self.bar.preview.x = 0 self.bar.preview.y = 0 self.bar.preview.color32 = self.previewUpColor32 -- TP bar (red gauge) self.bar.previewDown = CreateSprite("px") self.bar.previewDown.SetParent(self.bar.bg) self.bar.previewDown.Scale(19, 0) self.bar.previewDown.SetAnchor(0, 0) self.bar.previewDown.SetPivot(0, 0) self.bar.previewDown.x = 0 self.bar.previewDown.y = 0 self.bar.previewDown.color32 = self.previewDownColor32 -- TP bar (normal gauge) self.bar.bar = CreateSprite("px") self.bar.bar.SetParent(self.bar.bg) self.bar.bar.Scale(19, 0) self.bar.bar.SetAnchor(0, 0) self.bar.bar.SetPivot(0, 0) self.bar.bar.x = 0 self.bar.bar.y = 0 self.bar.bar.color32 = self.noFullColor32 -- TP bar preview loss TP with MAGIC command choice self.bar.previewTPLoss = CreateSprite("px") self.bar.previewTPLoss.SetParent(self.bar.bg) self.bar.previewTPLoss.Scale(19, 0) self.bar.previewTPLoss.SetAnchor(0, 0) self.bar.previewTPLoss.SetPivot(0, 1) self.bar.previewTPLoss.x = 0 self.bar.previewTPLoss.y = 0 self.bar.previewTPLoss.color32 = self.previewUpColor32 -- TP bar mask self.bar.mask = CreateSprite("CreateYourKris/TP Bar/mask") self.bar.mask.SetParent(self.bar.bg) self.bar.mask.SetPivot(0, 0) self.bar.mask.SetAnchor(0, 0) self.bar.mask.x = -3 self.bar.mask.y = -4 -- TP bar text self.staticText = CreateSprite("CreateYourKris/TP Bar/text") self.staticText.SetParent(self.bar.bg) self.staticText.SetPivot(0, 1) self.staticText.absx = 0 self.staticText.absy = 435 -- TP bar numbers self.num1 = CreateSprite("CreateYourKris/TP Bar/Numbers/0") self.num1.SetParent(self.bar.bg) self.num1.SetPivot(0.5, 0) self.num1.absx = 20 self.num1.absy = 345 self.num2 = CreateSprite("empty") self.num2.SetParent(self.bar.bg) self.num2.SetPivot(0.5, 0) self.num2.absx = 28 self.num2.absy = 345 self.isBeingShown = false self.shownTimer = 0 -- Updates the TP bar function self.Update() if self.isBeingShown then self.bar.bg.x = self.bar.bg.x + (self.shownTimer < 10 and 5 or self.shownTimer < 15 and 4 or 2) self.shownTimer = self.shownTimer + 1 if self.shownTimer == 20 then self.isBeingShown = false end end -- Move the preview of the TP bar if it's not equal to the TP bar's true value if self.trueValue ~= self.previewValue then -- Case TP was 100 if self.previewValue == 100 then self.bar.bar.color32 = self.noFullColor32 self.staticText.Set("CreateYourKris/TP Bar/text") end local gt = self.trueValue > self.previewValue self.previewValue = self.previewValue + math.min(self.previewSpeed, math.abs(self.previewValue - self.trueValue)) * (gt and 1 or -1) -- Case TP is now 100: hide the numbers and set the bar's color if self.previewValue == 100 then self.barValue = 99 self.bar.bar.color32 = self.fullColor32 self.num1.Set("empty") self.num2.Set("empty") self.staticText.Set("CreateYourKris/TP Bar/textMAX") else -- Computes the scale of the bar and applies it local associatedYScale = self.previewValue / 100 * self.ySize if gt then self.bar.preview.yscale = associatedYScale + 1 -- +1 because the preview has to be visible else self.bar.bar.yscale = associatedYScale if self.barValue >= self.trueValue then self.bar.previewDown.yscale = associatedYScale end end -- Updates the numbers local twoNumbers = self.previewValue >= 10 self.num1.Set("CreateYourKris/TP Bar/Numbers/" .. (twoNumbers and tostring(math.floor(self.previewValue / 10)) or tostring(math.floor(self.previewValue)))) if twoNumbers then self.num1.absx = 12 self.num2.Set("CreateYourKris/TP Bar/Numbers/" .. tostring(math.floor(self.previewValue) % 10)) else self.num1.absx = 20 self.num2.Set("empty") end end end -- Move the TP bar if it's not equal to the TP bar's true value if self.trueValue ~= self.barValue then local gt = self.trueValue > self.barValue self.barValue = self.barValue + math.min(self.barSpeed, math.abs(self.barValue - self.trueValue)) * (gt and 1 or -1) -- Computes the scale of the bar and applies it local associatedYScale = self.barValue / 100 * self.ySize if gt then self.bar.bar.yscale = associatedYScale else self.bar.previewDown.yscale = associatedYScale self.bar.preview.yscale = associatedYScale + (self.barValue == 0 and 0 or 1) end -- Check if preview was above the other value local previewDiff = self.trueValue - self.previewValue local barDiff = self.trueValue - self.barValue associatedYScale = self.trueValue / 100 * self.ySize if (previewDiff < 0 and barDiff > 0) or (previewDiff > 0 and barDiff < 0) then if previewDiff < 0 then self.bar.preview.yscale = associatedYScale + (self.barValue == 0 and 0 or 1) else self.bar.bar.yscale = associatedYScale end end end if self.isLossPreviewed then self.bar.previewTPLoss.alpha = self.CreateYourKris.frame % 60 < 30 and self.CreateYourKris.frame % 60 / 40 or (60 - (self.CreateYourKris.frame % 60)) / 40 end end function self.PreviewTPLoss(loss) if loss > self.trueValue then self.isLossPreviewed = false self.bar.previewTPLoss.alpha = 0 return end self.isLossPreviewed = true self.bar.previewTPLoss.yscale = loss / 100 * self.ySize self.bar.previewTPLoss.y = self.barValue / 100 * self.ySize end -- Sets the TP bar's true value function self.Set(value, isRelative) self.trueValue = isRelative and self.trueValue + value or value if self.trueValue < 0 then self.trueValue = 0 end if self.trueValue > 100 then self.trueValue = 100 end end function self.Show() self.bar.bg.absx = -39 self.shownTimer = 0 self.isBeingShown = true end self.bar.bg.absx = -39 return self end
40.122066
171
0.5956
fd9b97a0ff847a2fb0006efaa076c0eb2f5d9b9b
598
css
CSS
src/assets/icon/iconfont.css
ggggggo/supermall
b5e1dc852a38637dc413b03f80c239036901d617
[ "MIT" ]
null
null
null
src/assets/icon/iconfont.css
ggggggo/supermall
b5e1dc852a38637dc413b03f80c239036901d617
[ "MIT" ]
null
null
null
src/assets/icon/iconfont.css
ggggggo/supermall
b5e1dc852a38637dc413b03f80c239036901d617
[ "MIT" ]
null
null
null
@font-face { font-family: "iconfont"; /* Project id 2589609 */ src: url('iconfont.woff2?t=1622705403903') format('woff2'), url('iconfont.woff?t=1622705403903') format('woff'), url('iconfont.ttf?t=1622705403903') format('truetype'); } .iconfont { font-family: "iconfont" !important; font-size: 16px; font-style: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .icon-home:before { content: "\e626"; } .icon-me:before { content: "\e610"; } .icon-cart:before { content: "\e607"; } .icon-category:before { content: "\ea54"; }
18.6875
62
0.650502
ed5b1bca96e7cf35b03e5a16d0031436d9de1b86
155
h
C
Estructura/Estructura/arbol bb-copia/nodo.h
dkmaster17/DKM
ef22411e57cb37f18b9ddd2305001050855cd137
[ "MIT" ]
null
null
null
Estructura/Estructura/arbol bb-copia/nodo.h
dkmaster17/DKM
ef22411e57cb37f18b9ddd2305001050855cd137
[ "MIT" ]
null
null
null
Estructura/Estructura/arbol bb-copia/nodo.h
dkmaster17/DKM
ef22411e57cb37f18b9ddd2305001050855cd137
[ "MIT" ]
null
null
null
#ifndef NODO_H #define NODO_H #include <iostream> using namespace std; class nodo { public: nodo *hi,*hd; int info; nodo(){hi=hd=NULL;} }; #endif
10.333333
21
0.664516
b7aa44e2c5d0931d4fa140cf37788bc7d4ed7ae3
3,393
cpp
C++
sumo/src/netbuild/NBPTLine.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netbuild/NBPTLine.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netbuild/NBPTLine.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
2
2017-12-14T16:41:59.000Z
2020-10-16T17:51:27.000Z
/****************************************************************************/ /// @file NBPTLine.cpp /// @author Gregor Laemmel /// @author Nikita Cherednychek /// @date Tue, 20 Mar 2017 /// @version $Id$ /// // The representation of one direction of a single pt line /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // /****************************************************************************/ #include <utils/iodevices/OutputDevice.h> #include <utility> #include "NBPTLine.h" #include "NBPTStop.h" NBPTLine::NBPTLine(std::string name) : myName(std::move(name)), myPTLineId(-1), myRef(name) { } void NBPTLine::addPTStop(NBPTStop* pStop) { myPTStops.push_back(pStop); } std::string NBPTLine::getName() { return myName; } std::vector<NBPTStop*> NBPTLine::getStops() { return myPTStops; } void NBPTLine::write(OutputDevice& device) { device.openTag(SUMO_TAG_PT_LINE); device.writeAttr(SUMO_ATTR_ID, myPTLineId); if (!myName.empty()) { device.writeAttr(SUMO_ATTR_NAME, myName); } device.writeAttr(SUMO_ATTR_LINE, myRef); device.writeAttr("completeness", toString((double)myPTStops.size()/(double)myNumOfStops)); if (!myRoute.empty()) { device.openTag(SUMO_TAG_ROUTE); device.writeAttr(SUMO_ATTR_EDGES, getRoute()); device.closeTag(); } for (auto& myPTStop : myPTStops) { device.openTag(SUMO_TAG_BUS_STOP); device.writeAttr(SUMO_ATTR_ID, myPTStop->getID()); device.writeAttr(SUMO_ATTR_NAME, myPTStop->getName()); device.closeTag(); } // device.writeAttr(SUMO_ATTR_LANE, myLaneId); // device.writeAttr(SUMO_ATTR_STARTPOS, myStartPos); // device.writeAttr(SUMO_ATTR_ENDPOS, myEndPos); // device.writeAttr(SUMO_ATTR_FRIENDLY_POS, "true"); device.closeTag(); } void NBPTLine::setId(long long int id) { myPTLineId = id; } void NBPTLine::addWayNode(long long int way, long long int node) { std::string wayStr = toString(way); if (wayStr != myCurrentWay) { myCurrentWay = wayStr; myWays.push_back(wayStr); } myWaysNodes[wayStr].push_back(node); } const std::vector<std::string>& NBPTLine::getMyWays() const { return myWays; } std::vector<long long int>* NBPTLine::getWaysNodes(std::string wayId) { if (myWaysNodes.find(wayId) != myWaysNodes.end()) { return &myWaysNodes[wayId]; } return nullptr; } void NBPTLine::setRef(std::string ref) { myRef = std::move(ref); } std::string NBPTLine::getRoute() { std::string route; for (auto& it : myRoute) { route += (" " + it->getID()); } return route; } void NBPTLine::addEdgeVector(std::vector<NBEdge*>::iterator fr, std::vector<NBEdge*>::iterator to) { myRoute.insert(myRoute.end(), fr, to); } void NBPTLine::setMyNumOfStops(unsigned long numStops) { myNumOfStops = numStops; }
31.12844
100
0.61008
1a8b48758fd78dc9f8109dbf304511cd2f57375b
643
py
Python
src/jamberry/order.py
soundstripe/jamberry
e5f7400ca274ceb357ef7098a32068f1b21db324
[ "MIT" ]
null
null
null
src/jamberry/order.py
soundstripe/jamberry
e5f7400ca274ceb357ef7098a32068f1b21db324
[ "MIT" ]
null
null
null
src/jamberry/order.py
soundstripe/jamberry
e5f7400ca274ceb357ef7098a32068f1b21db324
[ "MIT" ]
null
null
null
class Order: __slots__ = ( 'id', 'order_number', 'customer_name', 'shipping_name', 'order_date', 'order_details_url', 'subtotal', 'shipping_fee', 'tax', 'status', 'retail_bonus', 'order_type', 'customer_url', 'customer_id', 'customer_contact', 'total', 'qv', 'hostess', 'party', 'ship_date', 'line_items', 'shipping_address', ) class OrderLineItem: __slots__ = ( 'sku', 'name', 'price', 'quantity', 'total', )
18.371429
28
0.438569
41d857d92d504827e4cd96650cebbb21d32c8885
1,969
c
C
table_layout_depr.c
sebgod/gtk-plus-tutorial
3b9ed34bd87609cf65dc8c1ea572541786add686
[ "CC0-1.0" ]
1
2015-11-06T00:34:48.000Z
2015-11-06T00:34:48.000Z
table_layout_depr.c
sebgod/gtk-plus-tutorial
3b9ed34bd87609cf65dc8c1ea572541786add686
[ "CC0-1.0" ]
null
null
null
table_layout_depr.c
sebgod/gtk-plus-tutorial
3b9ed34bd87609cf65dc8c1ea572541786add686
[ "CC0-1.0" ]
null
null
null
#include <gtk/gtk.h> static void change_homogenous (GtkWidget *widget, GtkTable *table) { /* Homogenität ändern */ gtk_table_set_homogeneous (table, !gtk_table_get_homogeneous (table)); } int main (int argc, char *argv[]) { GtkWidget *window, *table, *buttons[5], *labels[4]; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); g_signal_connect (window, "destroy", G_CALLBACK(gtk_main_quit), NULL); /* Tabelle mit 3 Reihen und 3 Spalten, uneinheitliche Größe */ table = gtk_table_new (3, 3, FALSE); /* Knöpfe und Texte erstellen */ buttons[0] = gtk_button_new_with_label ("0"); buttons[1] = gtk_button_new_with_label ("rechts oben"); buttons[2] = gtk_button_new_with_label ("homogen?"); g_signal_connect (buttons[2], "clicked", G_CALLBACK(change_homogenous), table); buttons[3] = gtk_button_new_with_label ("0"); buttons[4] = gtk_button_new_with_label ("rechts unten"); labels[0] = gtk_label_new ("N"); labels[1] = gtk_label_new ("W"); labels[2] = gtk_label_new ("O"); labels[3] = gtk_label_new ("S"); /* erste Reihe */ gtk_table_attach_defaults (GTK_TABLE(table), buttons[0], 0, 1, 0, 1); gtk_table_attach_defaults (GTK_TABLE(table), labels[0], 1, 2, 0, 1); gtk_table_attach_defaults (GTK_TABLE(table), buttons[1], 2, 3, 0, 1); /* zweite Reihe */ gtk_table_attach_defaults (GTK_TABLE(table), labels[1], 0, 1, 1, 2); gtk_table_attach_defaults (GTK_TABLE(table), buttons[2], 1, 2, 1, 2); gtk_table_attach_defaults (GTK_TABLE(table), labels[2], 2, 3, 1, 2); /* dritte Reihe */ gtk_table_attach_defaults (GTK_TABLE(table), buttons[3], 0, 1, 2, 3); gtk_table_attach_defaults (GTK_TABLE(table), labels[3], 1, 2, 2, 3); gtk_table_attach_defaults (GTK_TABLE(table), buttons[4], 2, 3, 2, 3); gtk_container_add (GTK_CONTAINER(window), table); gtk_widget_show_all (window); gtk_main (); return 0; }
36.462963
74
0.669883
3a5ea8d93c0b749ba615284f9b65c47afebe4a99
589
bash
Shell
tools/snippet/snippet.bash
minisu/cloudrunner-go
803b2cace37e422b9a8f1f8264b66d01ffc14b60
[ "MIT" ]
null
null
null
tools/snippet/snippet.bash
minisu/cloudrunner-go
803b2cace37e422b9a8f1f8264b66d01ffc14b60
[ "MIT" ]
null
null
null
tools/snippet/snippet.bash
minisu/cloudrunner-go
803b2cace37e422b9a8f1f8264b66d01ffc14b60
[ "MIT" ]
null
null
null
#!/bin/bash file=$1 pattern=$2 # read stdin IN=$(cat -) # write snippet to file so that `sed` can read # it with `r` command (inserting directly is problematic # when snippet contains newlines). echo '```' >> snippettmp.txt echo "$IN" >> snippettmp.txt echo '```' >> snippettmp.txt lead="<!-- BEGIN $pattern -->" tail="<!-- END $pattern -->" # replace snippet region with content from file # this is taken from https://superuser.com/a/440057 out=$(sed -e "/$lead/,/$tail/{ /$lead/{p; r snippettmp.txt }; /$tail/p; d }" $file) # write the file echo "$out" > $file rm snippettmp.txt
21.035714
58
0.648557
75e27bd029d9a440540894bc7c78720d3995396b
102
dart
Dart
lib/main.dart
purposebakery/glowflutter
a783cfe8cfff53831979d32e7c555ddcbfcb1dd2
[ "Apache-2.0" ]
null
null
null
lib/main.dart
purposebakery/glowflutter
a783cfe8cfff53831979d32e7c555ddcbfcb1dd2
[ "Apache-2.0" ]
null
null
null
lib/main.dart
purposebakery/glowflutter
a783cfe8cfff53831979d32e7c555ddcbfcb1dd2
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/widgets.dart'; import 'package:glow/App.dart'; void main() => runApp(App());
20.4
38
0.705882
da7d8508c94baa18d75468b8695097eeafc6d569
131
php
PHP
src/Libraries/Text_Wiki/Wiki/Render/Plain/Include.php
mrcore5/parser
bf7f88af025e6853ba360c9b8faf8ed1c36a1f37
[ "MIT" ]
null
null
null
src/Libraries/Text_Wiki/Wiki/Render/Plain/Include.php
mrcore5/parser
bf7f88af025e6853ba360c9b8faf8ed1c36a1f37
[ "MIT" ]
null
null
null
src/Libraries/Text_Wiki/Wiki/Render/Plain/Include.php
mrcore5/parser
bf7f88af025e6853ba360c9b8faf8ed1c36a1f37
[ "MIT" ]
null
null
null
<?php class Text_Wiki_Render_Plain_Include extends Text_Wiki_Render { public function token() { return ''; } }
14.555556
61
0.656489
4c9538138188e3fae761b632c3e5b581c83e77c5
689
swift
Swift
Sources/Tools/llcastool/CommonOptions.swift
LaudateCorpus1/swift-llbuild2
b03dc24359a2b365514a32cca657804ae34114d7
[ "Apache-2.0" ]
268
2020-05-26T20:50:16.000Z
2022-03-23T04:30:15.000Z
Sources/Tools/llcastool/CommonOptions.swift
LaudateCorpus1/swift-llbuild2
b03dc24359a2b365514a32cca657804ae34114d7
[ "Apache-2.0" ]
14
2020-05-29T18:36:35.000Z
2021-04-23T18:23:18.000Z
Sources/Tools/llcastool/CommonOptions.swift
LaudateCorpus1/swift-llbuild2
b03dc24359a2b365514a32cca657804ae34114d7
[ "Apache-2.0" ]
17
2020-05-27T14:59:47.000Z
2022-03-26T10:42:51.000Z
// This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors import ArgumentParser import Foundation import LLBCASTool import TSCUtility struct CommonOptions: ParsableArguments { @Option(help: "The CAS database URL to use") var url: Foundation.URL } extension CommonOptions { func toToolOptions() -> LLBCASToolOptions { return LLBCASToolOptions( url: url ) } }
26.5
78
0.725689
d7ebe7619ac1d991011df78d6786976e46822390
6,744
rb
Ruby
spec/law/judgement_spec.rb
Freshly/law
2d932f2325da0e096478374209aab90a7aca16ad
[ "MIT" ]
1
2019-10-21T23:19:38.000Z
2019-10-21T23:19:38.000Z
spec/law/judgement_spec.rb
Freshly/law
2d932f2325da0e096478374209aab90a7aca16ad
[ "MIT" ]
5
2019-12-17T14:55:39.000Z
2021-06-09T15:39:56.000Z
spec/law/judgement_spec.rb
Freshly/law
2d932f2325da0e096478374209aab90a7aca16ad
[ "MIT" ]
1
2022-03-17T17:22:29.000Z
2022-03-17T17:22:29.000Z
# frozen_string_literal: true RSpec.describe Law::Judgement, type: :judgement do subject(:example_judgement) { described_class.new(petition) } let(:petition) { instance_double(Law::Petition, statute: statute) } let(:statute) { instance_double(Law::StatuteBase, unregulated?: unregulated?) } let(:unregulated?) { true } it { is_expected.to inherit_from Spicerack::RootObject } it { is_expected.to delegate_method(:statute).to(:petition) } it { is_expected.to delegate_method(:applicable_regulations).to(:petition) } it { is_expected.to delegate_method(:compliant?).to(:petition) } describe "#authorized?" do subject { example_judgement } context "without applied_regulations" do it { is_expected.not_to be_authorized } end context "with applied_regulations" do before do allow(example_judgement).to receive(:applied_regulations).and_return([instance_double(Law::RegulationBase)]) end context "without violations" do it { is_expected.to be_authorized } end context "with violations" do before { allow(example_judgement).to receive(:violations).and_return([ instance_double(Law::RegulationBase) ]) } it { is_expected.not_to be_authorized } end end end describe "#adjudicated?" do subject { example_judgement } context "without applied_regulations" do it { is_expected.not_to be_adjudicated } end context "with applied_regulations" do before do allow(example_judgement).to receive(:applied_regulations).and_return([instance_double(Law::RegulationBase)]) end it { is_expected.to be_adjudicated } end end describe ".judge!" do it_behaves_like "a class pass method", :judge! end describe ".judge" do it_behaves_like "a class pass method", :judge end describe "#judge" do subject(:judge) { example_judgement.judge } context "with StandardError" do before { allow(example_judgement).to receive(:judge!).and_raise(StandardError) } it "raises" do expect { judge }.to raise_error StandardError end end context "with Law::NotAuthorizedError" do before do allow(example_judgement).to receive(:judge!).and_raise(Law::NotAuthorizedError) allow(example_judgement).to receive(:error).and_call_original end it "is logged" do expect(judge).to eq false expect(example_judgement). to have_received(:error). with(:not_authorized, exception: instance_of(Law::NotAuthorizedError)) end end context "without error" do before { allow(example_judgement).to receive(:judge!).and_return(:example_return) } it { is_expected.to eq :example_return } end end describe "#judge!" do subject(:judge!) { example_judgement.judge! } context "with a petition" do before do allow(petition).to receive(:applicable_regulations).and_return(applicable_regulations) allow(petition).to receive(:compliant?).and_return(compliant?) end let(:applicable_regulations) { [] } let(:compliant?) { true } context "when unregulated" do let(:unregulated?) { true } it { is_expected.to eq true } end context "when regulated" do let(:unregulated?) { false } context "without applicable regulations" do it "raises" do expect { judge! }.to raise_error Law::InjunctionError end end context "with applicable regulations" do let(:applicable_regulations) { [ regulation0_class, regulation1_class ] } let(:regulation0_class) { Class.new(Law::RegulationBase) } let(:regulation0_instance) { instance_double(regulation0_class, valid?: regulation0_valid?) } let(:regulation1_class) { Class.new(Law::RegulationBase) } let(:regulation1_instance) { instance_double(regulation1_class, valid?: regulation1_valid?) } let(:expected_applied_regulations) { [ regulation0_instance, regulation1_instance ] } let(:expected_violations) { [] } before do allow(regulation0_class).to receive(:new).with(petition: petition).and_return(regulation0_instance) allow(regulation1_class).to receive(:new).with(petition: petition).and_return(regulation1_instance) end shared_examples_for "regulations are applied" do context "when not compliant?" do let(:compliant?) { false } it "has raises" do expect { judge! }.to raise_error Law::ComplianceError end end context "when compliant?" do it "changes applied_regulations" do expect { judge! }. to change { example_judgement.applied_regulations }.from([]).to(expected_applied_regulations) end end end shared_examples_for "violations are tracked" do context "when not compliant?" do let(:compliant?) { false } it "has raises" do expect { judge! }.to raise_error Law::ComplianceError end end context "when compliant?" do it "has violations" do expect { judge! }. to change { example_judgement.applied_regulations }.from([]).to(expected_applied_regulations). and change { example_judgement.violations }.from([]).to(expected_violations). and raise_error Law::NotAuthorizedError end end end context "when no regulations are invalid" do let(:regulation0_valid?) { true } let(:regulation1_valid?) { true } it { is_expected.to eq true } it_behaves_like "regulations are applied" end context "when one regulations is invalid" do let(:regulation0_valid?) { true } let(:regulation1_valid?) { false } let(:expected_violations) { [ regulation1_instance ] } it_behaves_like "violations are tracked" end context "when many regulations are invalid" do let(:regulation0_valid?) { false } let(:regulation1_valid?) { false } let(:expected_violations) { [ regulation0_instance, regulation1_instance ] } it_behaves_like "violations are tracked" end end end end context "without a petition" do let(:petition) { nil } it "raises" do expect { judge! }.to raise_error Law::InjunctionError end end end end
31.661972
120
0.632117
0d4fff54cd46ac65efd31c5c369c853f39fd866b
1,215
cs
C#
Api/ViewModels/PostCreateEditVm.cs
afonsof/meganium
f01416e693ea242916bef73a736113c603e47745
[ "MIT" ]
4
2015-03-13T02:29:47.000Z
2015-07-22T03:33:27.000Z
Api/ViewModels/PostCreateEditVm.cs
afonsof/meganium
f01416e693ea242916bef73a736113c603e47745
[ "MIT" ]
null
null
null
Api/ViewModels/PostCreateEditVm.cs
afonsof/meganium
f01416e693ea242916bef73a736113c603e47745
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using Meganium.Api.Entities; using Meganium.Api.Resources; namespace Meganium.Api.ViewModels { public class PostCreateEditVm { public List<Field> Fields { get; set; } public MultiSelectList CategoriesMultiselect { get; set; } public SelectList PrivacySelect { get; set; } public SelectList ParentSelect { get; set; } public PostType PostType { get; set; } public int Id { get; set; } [Required] [Display(Name="Title", ResourceType = typeof(Resource))] public string Title { get; set; } public DateTime PublishedAt { get; set; } public bool Published { get; set; } public string Content { get; set; } public DateTime StartedAt { get; set; } public DateTime EndedAt { get; set; } public string Location { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } public string FeaturedMediaFileJson { get; set; } public string MediaFilesJson { get; set; } public string Hash { get; set; } } }
30.375
66
0.637037
8dae2761060504a51b58e05078da7b870a429932
720
js
JavaScript
lib/scheduler/speed.js
lagdotcom/rot.js
b30fb816bfbeb986a477dee929b988fd2c7f9bf3
[ "BSD-3-Clause" ]
1,653
2015-01-02T10:11:35.000Z
2022-03-30T04:35:46.000Z
lib/scheduler/speed.js
lagdotcom/rot.js
b30fb816bfbeb986a477dee929b988fd2c7f9bf3
[ "BSD-3-Clause" ]
157
2015-01-02T20:03:56.000Z
2022-03-23T20:17:08.000Z
lib/scheduler/speed.js
lagdotcom/rot.js
b30fb816bfbeb986a477dee929b988fd2c7f9bf3
[ "BSD-3-Clause" ]
258
2015-01-06T14:02:55.000Z
2022-03-24T03:34:09.000Z
import Scheduler from "./scheduler.js"; /** * @class Speed-based scheduler */ export default class Speed extends Scheduler { /** * @param {object} item anything with "getSpeed" method * @param {bool} repeat * @param {number} [time=1/item.getSpeed()] * @see ROT.Scheduler#add */ add(item, repeat, time) { this._queue.add(item, time !== undefined ? time : 1 / item.getSpeed()); return super.add(item, repeat); } /** * @see ROT.Scheduler#next */ next() { if (this._current && this._repeat.indexOf(this._current) != -1) { this._queue.add(this._current, 1 / this._current.getSpeed()); } return super.next(); } }
27.692308
79
0.572222
ebc132b57a091afd4443f7f4786d6614976108fc
1,670
css
CSS
src/taskpane/taskpane.css
Fukushima-Computer-System/outlook-check-recipients-addin
99ffffb3ca0b162500f4f47395995dfd57c14398
[ "MIT" ]
null
null
null
src/taskpane/taskpane.css
Fukushima-Computer-System/outlook-check-recipients-addin
99ffffb3ca0b162500f4f47395995dfd57c14398
[ "MIT" ]
2
2021-11-09T05:12:57.000Z
2021-11-15T01:51:28.000Z
src/taskpane/taskpane.css
Fukushima-Computer-System/outlook-check-recipients-addin
99ffffb3ca0b162500f4f47395995dfd57c14398
[ "MIT" ]
1
2021-11-17T10:56:56.000Z
2021-11-17T10:56:56.000Z
html, body { width: 100%; height: 100%; margin: 0; padding: 0; } ul { margin: 0; padding: 0; } p { margin-top: 8px; margin-bottom: 8px; } .sample-container { margin-top: 8px; width: 90%; height: 72px; position: relative; display: flex; justify-content: center; align-items: center; border: 1px solid #ccc; } .sample-self-text { position: absolute; top: -1rem; left: -1rem; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; padding: 8px; background-color: rgb(26, 115, 232); color: white; } button { border: 1px solid #444; width: 120px; font-size: 12pt; background-color: rgb(26, 115, 232); padding: 8px; color: white; font-size: 14pt; font-weight: bold; } button:disabled { background-color: #888; } .is-error { color: #db2616; } .save-message { padding-top: 10px; display: block; } /* * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ .ms-header { padding: 20px; padding-bottom: 10px; padding-top: 10px; display: -webkit-flex; display: flex; -webkit-flex-direction: column; flex-direction: column; align-items: center; } .ms-main { display: -webkit-flex; display: flex; -webkit-flex-direction: column; flex-direction: column; -webkit-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-align-items: center; align-items: center; -webkit-flex: 1 0 0; flex: 1 0 0; padding: 10px 20px; } .ms-main > h2 { width: 100%; text-align: center; margin-top: 8px; margin-bottom: 8px; } .ms-font-su { display: block; font-size: 28px; }
15.904762
92
0.647904
a3dc6795b3e8c7dbbe37d21da8e07cf15fde1905
8,884
java
Java
src/rosplan/rosplan_dependencies/rddlsim/src/rddl/translate/cnf/SolutionReader.java
Eurobot2020/UAHR-ROSPlan
d171922ab2580bc86824addb47494b6ec9d46914
[ "BSD-2-Clause" ]
null
null
null
src/rosplan/rosplan_dependencies/rddlsim/src/rddl/translate/cnf/SolutionReader.java
Eurobot2020/UAHR-ROSPlan
d171922ab2580bc86824addb47494b6ec9d46914
[ "BSD-2-Clause" ]
null
null
null
src/rosplan/rosplan_dependencies/rddlsim/src/rddl/translate/cnf/SolutionReader.java
Eurobot2020/UAHR-ROSPlan
d171922ab2580bc86824addb47494b6ec9d46914
[ "BSD-2-Clause" ]
null
null
null
package rddl.translate.cnf; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SolutionReader { private final static String COMMENTH = "c ".intern(); private final static String VAR_INTEGER_REGULAR = "^(c \\d+ : [A-Z]{3} :)".intern(); private final static String NOOP_ACTION = "noop".intern(); private final static String COLON_SPLITTER = " : ".intern(); private static final String BLANK = " ".intern(); private static final String NULLSTRING = "".intern(); private static final String LINE1_RESULT = "time \\d+".intern(); private static final String LINE2_RESULT = "ans ".intern(); private static final String LINE3_RESULT = "cost \\d+".intern(); private static final String LINE4_RESULT = "v ".intern(); private HashMap<Integer, String> actList = null; private Vector<Integer> trueVars = null; private String outputName = null; public SolutionReader(String cnfFileName, String solutionFileName) { File cnf = new File(cnfFileName); File solution = new File(solutionFileName); if(!cnf.exists() || !solution.exists()) { System.out.println("Error: Input files are not exist!"); return; } else if(!cnf.isFile() || !solution.isFile()) { System.out.println("Error: Input are not file!"); return; } outputName = cnf.getParentFile().getPath() + cnf.getName()+solution.getName(); actList = ReadCNF(cnf); trueVars = ReadSolution(solution); } public SolutionReader(String cnfFileName, String solutionFileName, String outputDir) { File cnf = new File(cnfFileName); File solution = new File(solutionFileName); if(!cnf.exists() || !solution.exists()) { System.out.println("Error: Input files are not exist!"); return; } else if(!cnf.isFile() || !solution.isFile()) { System.out.println("Error: Input are not file!"); return; } outputName = outputDir + cnf.getName()+solution.getName(); actList = ReadCNF(cnf); trueVars = ReadSolution(solution); } public SolutionReader(String cnfFileName) { File cnf = new File(cnfFileName); if(!cnf.exists() ) { System.out.println("Error: Input files are not exist!"); return; } else if(!cnf.isFile() ) { System.out.println("Error: Input are not file!"); return; } actList = ReadCNF(cnf); } /* * Read RSAT output: * if is not a RSAT output or there is no solution return * new Vector<Integer>() * */ private Vector<Integer> ReadSolution(File solution) { Vector<Integer> context = new Vector<Integer>(); try { FileInputStream fis = new FileInputStream(solution); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = null; Pattern p1 = Pattern.compile(LINE1_RESULT); Pattern p2 = Pattern.compile(LINE2_RESULT); Pattern p3 = Pattern.compile(LINE3_RESULT); Pattern p4 = Pattern.compile(LINE4_RESULT); Matcher m; line = br.readLine(); m = p1.matcher(line); if(!m.find()) { System.out.println("Error: Result file is not correct.1"); return context; } line = br.readLine(); m = p2.matcher(line); if(!m.find()) { System.out.println("Error: Result file is not correct.2"); return context; } line = br.readLine(); m = p3.matcher(line); if(!m.find()) { System.out.println("Error: Result file is not correct.3"); return context; } line = br.readLine(); m = p4.matcher(line); if(!m.find()) { System.out.println("Error: Result file is not correct.4"); return context; } line = line.replace(LINE4_RESULT,NULLSTRING); while(line != null) { String[] indexs = line.split(BLANK); for(String s : indexs) { if(s != null && s != NULLSTRING) { Integer value = Integer.valueOf(s); if(value > 0) { context.add(value); } } } line = br.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); return new Vector<Integer>(); } catch (IOException e) { e.printStackTrace(); return new Vector<Integer>(); } catch(NullPointerException e) { e.printStackTrace(); return new Vector<Integer>(); } return context; } // Find all ordered action variables public ArrayList<String> SerialActions(String solutionName) { File solution = new File(solutionName); int cntNoop = 0; ArrayList<String> actions = new ArrayList<String>(); // Find all positive variables if(solution != null && solution.isFile()) { trueVars = ReadSolution(solution); } else { System.out.println("Error: Wrong solution file!"); return null; } if(trueVars.size() > 0) { int index = 0; // choose action variable to output && // Reorder actions by postpone noop for(int i = 0 ; i < trueVars.size(); i ++) { index = trueVars.get(i); String action = actList.get(index); if(action == null) { continue; } else if(action.contains(NOOP_ACTION)) { cntNoop++; } else { action = removeTimestep(action); actions.add(action) ; } } while(cntNoop>0) { actions.add(NOOP_ACTION); cntNoop--; } } return actions; } // format action variable name by remove "@timestep" private String removeTimestep(String action) { int pos = action.indexOf(CNF.AT); if(pos > 0) { return action.substring(0, pos); } return action; } //Read cnf file and list all action variables private HashMap<Integer, String> ReadCNF(File cnf) { HashMap<Integer, String> context = new HashMap<Integer, String>(); try { FileInputStream fis = new FileInputStream(cnf); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = null; Boolean inMappingSection = false; line = br.readLine(); Pattern p = Pattern.compile(VAR_INTEGER_REGULAR); Matcher m = null; while(line != null) { while(line.startsWith(BLANK)) { line = line.replaceFirst(BLANK, NULLSTRING); } if(line.startsWith(COMMENTH)) { m = p.matcher(line); if(m.find()) { // find a new variable and its index inMappingSection = true; line = line.replace(COMMENTH, NULLSTRING); String[] temp = line.split(COLON_SPLITTER); if(temp.length != 3) { System.out.println("Error: failed to read cnf, wrong match of mapping"); break; }else { if(temp[1].contains(CNF.VAR_TYPE[1])) { // find an action variable, save it int index = Integer.parseInt(temp[0]); String actionName = temp[2].replace(BLANK, ""); context.put(index, actionName); } } } else if(inMappingSection) {// exit of var2int mapping section break; }else { line = br.readLine(); continue; } } else { System.out.println("Error: Wrong format!"); return new HashMap<Integer, String>(); } line = br.readLine(); } br.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return new HashMap<Integer, String>(); } catch (IOException e) { e.printStackTrace(); return new HashMap<Integer, String>(); } return context; } public void PrintActions() { PrintWriter pw; if(actList == null || actList.size() == 0 ) { System.out.println("Error: Need init action list."); return; } try { pw = new PrintWriter(new FileWriter(outputName)); int cnt = 0; for(int i = 0 ; i < trueVars.size(); i++) { int index = trueVars.get(i); String action = actList.get(index); if(action != null) { pw.print(index + " : " + action + "\n"); System.out.println(index + " : " + action); cnt++; } } pw.print("Finished! Total count: " + cnt); System.out.println("Finished! Total count: " + cnt); pw.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("Error: Can not find output file"); } catch (IOException e) { e.printStackTrace(); System.out.println("Error: Can not create output file"); } } public static void main(String[] args) throws Exception { if (args.length != 2 || args.length != 3) { System.out.println("\nusage: CNF-File Solution-File\n"); System.out.println("\n or CNF-File Solution-File Output-Dir\n"); System.exit(1); } SolutionReader sr ; if(args.length == 2) sr = new SolutionReader(args[0], args[1]); else sr = new SolutionReader(args[0], args[1], args[2]); //all positive variables will be printed out. sr.PrintActions(); } }
25.676301
85
0.637213
87904bf37f99cf74073bb5ac7bca12a7bb7111b9
5,814
swift
Swift
Tests/IDNATests/SimpleToUnicodeTests.swift
karwa/swift-url-docs-test
2f01206325f5b8e512dcc89ffaf2075a9e3c5a75
[ "Apache-2.0" ]
null
null
null
Tests/IDNATests/SimpleToUnicodeTests.swift
karwa/swift-url-docs-test
2f01206325f5b8e512dcc89ffaf2075a9e3c5a75
[ "Apache-2.0" ]
null
null
null
Tests/IDNATests/SimpleToUnicodeTests.swift
karwa/swift-url-docs-test
2f01206325f5b8e512dcc89ffaf2075a9e3c5a75
[ "Apache-2.0" ]
null
null
null
// Copyright The swift-url Contributors. // // 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. import XCTest @testable import IDNA class SimpleToUnicodeTests: XCTestCase {} fileprivate struct Label: Equatable { var label: AnyRandomAccessCollection<Unicode.Scalar> var needsTrailingDot: Bool init(label: AnyRandomAccessCollection<Unicode.Scalar>, needsTrailingDot: Bool) { self.label = label self.needsTrailingDot = needsTrailingDot } init(_ labelString: String, needsTrailingDot: Bool) { self.init(label: AnyRandomAccessCollection(Array(labelString.unicodeScalars)), needsTrailingDot: needsTrailingDot) } static func == (lhs: Label, rhs: Label) -> Bool { lhs.label.elementsEqual(rhs.label) && lhs.needsTrailingDot == rhs.needsTrailingDot } } extension IDNA { fileprivate static func toUnicode_Typed<Source>( utf8: Source, writer: (Label) -> Bool ) -> Bool where Source: Collection, Source.Element == UInt8 { toUnicode(utf8: utf8) { writer(Label(label: $0, needsTrailingDot: $1)) } } } extension SimpleToUnicodeTests { func testBasic() { let tests: [(String, String?)] = [ // Mapping and normalization. ("hello.example.com", "hello.example.com"), ("hElLo.eXaMpLe.cOm", "hello.example.com"), ("0x𝟕f.1", "0x7f.1"), ("0Xc0.0250.01", "0xc0.0250.01"), ("www.foo。bar.com", "www.foo.bar.com"), ("GOO  goo.com", "goo goo.com"), ("ₓn--fa-hia.example", "faß.example"), ("caf\u{00E9}.fr", "caf\u{00E9}.fr"), ("cafe\u{0301}.fr", "caf\u{00E9}.fr"), ("xn--caf-dma.fr", "caf\u{00E9}.fr"), ("xn--cafe-yvc.fr", nil), // ASCII to Unicode. ("xn--n3h", "☃"), ("xn--fa-hia.example", "faß.example"), ("hello.xn--ls8h.com", "hello.💩.com"), ("xn--fa-hia.api.xn--6qqa088eba.com", "faß.api.你好你好.com"), ("a.xn--igbi0gl.com", "a.أهلا.com"), ("a.xn--mgbet1febhkb.com", "a.هذهالكلمة.com"), ("xn--b1abfaaepdrnnbgefbadotcwatmq2g4l", "почемужеонинеговорятпорусски"), ("xn--bbb", "խ"), ("xn--1ch.com", "≠.com"), // Validation. ("a.b.c.xn--pokxncvks", nil), // Empty labels. ("xn--", ""), ("", ""), ("a.b.xn--.c", "a.b..c"), ("a.b..c", "a.b..c"), (".", "."), ("....", "...."), ] for (input, expectedResult) in tests { var actualResult = "" let success = IDNA.toUnicode(utf8: input.utf8) { label, needsDot in if label.contains(".") { XCTFail("Labels may not contain dots") } actualResult.unicodeScalars += label if needsDot { actualResult += "." } return true } guard success else { XCTAssertNil(expectedResult, "Unexpected failure: \(input)") continue } guard let expectedResult = expectedResult else { XCTFail("Unexpected success: \(input) -> \(actualResult)") continue } XCTAssertEqualElements(expectedResult.unicodeScalars, actualResult.unicodeScalars) } } func testInvalidUTF8() { // Currently, we get NFC normalization by gathering all the mapped code-points in to a String, // and using Foundation APIs/stdlib SPIs on String. That means we don't have a true, per-label "stream", // and things like invalid UTF-8 are detected before any labels are ever written via the callback. // This is what the test checks for with `UsingSerializedNFC = true`. // // In the future, this should use the stdlib NFC iterator directly, which would allow us to process // the Unicode data in a true stream, without going through String. At that point, UTF-8 validation // will occur when the particular label is actually processed. // // We can test that behavior today by disabling normalization, and it is useful for checking // how the rest of the code behaves. This is what this test checks for with `UsingSerializedNFC = false`. let UsingSerializedNFC = true let tests: [(input: [UInt8], output: (success: Bool, visitedLabels: [Label]))] = [ ( input: [0xDD], output: (false, []) ), ( input: [0x61 /* a */, 0xDD], output: (false, []) ), ( input: [0x61 /* a */, 0x2E /* . */, 0xDD], output: (false, [Label("a", needsTrailingDot: true)]) ), ( input: [0x61 /* a */, 0x2E /* . */, 0x62 /* b */, 0xDD], output: (false, [Label("a", needsTrailingDot: true)]) ), ( input: [0x61 /* a */, 0x2E /* . */, 0x62 /* b */, 0x2E /* . */, 0xDD], output: (false, [Label("a", needsTrailingDot: true), Label("b", needsTrailingDot: true)]) ), ( input: [0x61 /* a */, 0x2E /* . */, 0x62 /* b */, 0x2E /* . */, 0x62 /* c */, 0xDD], output: (false, [Label("a", needsTrailingDot: true), Label("b", needsTrailingDot: true)]) ), ] for (input, expectedResult) in tests { var visitedLabels = [Label]() let success = IDNA.toUnicode_Typed(utf8: input) { visitedLabels.append($0) return true } XCTAssertEqual(success, expectedResult.success) if UsingSerializedNFC { XCTAssertEqualElements(visitedLabels, []) } else { XCTAssertEqualElements(visitedLabels, expectedResult.visitedLabels) } } } }
35.236364
118
0.610767
a7a59bbe0e1852d82a9f030ad50f91cd3ed9a316
3,443
ps1
PowerShell
Pester/Test-WSTrust.ps1
Sarafian/WcfPS
9bee3c5b110adf1e7913ad53611fb545b3727f51
[ "MIT" ]
6
2016-07-25T11:23:49.000Z
2022-01-13T22:28:42.000Z
Pester/Test-WSTrust.ps1
Sarafian/WcfPS
9bee3c5b110adf1e7913ad53611fb545b3727f51
[ "MIT" ]
null
null
null
Pester/Test-WSTrust.ps1
Sarafian/WcfPS
9bee3c5b110adf1e7913ad53611fb545b3727f51
[ "MIT" ]
null
null
null
Param ( [Parameter( Mandatory = $true )] [string]$MexUri, [Parameter( Mandatory = $true )] [string]$AuthenticationEndpoint, [Parameter( Mandatory = $false )] [PSCredential]$Credential=$null, [Parameter( Mandatory = $false )] [string]$SymmetricAppliesTo=$null, [Parameter( Mandatory = $false )] [string]$BearerAppliesTo=$null ) Describe "New-WcfWsdlImporter" { Context "Parameter" { It "HttpGet" { $wsdlImporter=New-WcfWsdlImporter -Endpoint $MexUri } } Context "Pipe" { It "HttpGet" { $wsdlImporter=$MexUri | New-WcfWsdlImporter } } } Describe "New-WcfServiceEndpoint" { Context "Parameter" { It "Endpoint not defined" { $endpoints=New-WcfServiceEndpoint -WsdlImporter $importer $endpoints.Count | Should BeGreaterThan 1 } It "Endpoint defined" { $endpoints=New-WcfServiceEndpoint -WsdlImporter $importer -Endpoint $AuthenticationEndpoint $endpoints.Count | Should Be 1 } } Context "Pipe" { It "Endpoint not defined" { $endpoints=$importer | New-WcfServiceEndpoint $endpoints.Count | Should BeGreaterThan 1 } It "Endpoint defined" { $endpoints=$importer | New-WcfServiceEndpoint -Endpoint $AuthenticationEndpoint $endpoints.Count | Should Be 1 } } BeforeEach { $importer=New-WcfWsdlImporter -Endpoint $MexUri } } Describe "New-WcfProxyType" { Context "Parameter" { It "Save assembly" { $filePath=[System.IO.Path]::GetTempFileName() $proxyType=New-WcfProxyType -WsdlImporter $importer -FilePath $filePath $proxyType.Name | Should Match "WSTrust13.*Client" } It "In memory" { $proxyType=New-WcfProxyType -WsdlImporter $importer $proxyType.Name | Should Match "WSTrust13.*Client" } } Context "Pipe" { It "Save assembly" { $filePath=[System.IO.Path]::GetTempFileName() $proxyType=$importer | New-WcfProxyType -FilePath $filePath $proxyType.Name | Should Match "WSTrust13.*Client" } It "In memory" { $proxyType=$importer | New-WcfProxyType $proxyType.Name | Should Match "WSTrust13.*Client" } } BeforeEach { $importer=New-WcfWsdlImporter -Endpoint $MexUri } } if($SymmetricAppliesTo) { Describe "New-SecurityToken for Symmetric Token" { It "Issue token" { {New-SecurityToken -Endpoint $issuerEndpoint -Credential $Credential -AppliesTo $SymmetricAppliesTo -Symmetric} | Should Not Throw } BeforeEach { $importer=New-WcfWsdlImporter -Endpoint $MexUri $issuerEndpoint=$importer | New-WcfServiceEndpoint -Endpoint $AuthenticationEndpoint } } } if($BearerAppliesTo) { Describe "New-SecurityToken for Bearer Token" { It "Issue token" { {New-SecurityToken -Endpoint $issuerEndpoint -Credential $Credential -AppliesTo $BearerAppliesTo -Bearer} | Should Not Throw } BeforeEach { $importer=New-WcfWsdlImporter -Endpoint $MexUri $issuerEndpoint=$importer | New-WcfServiceEndpoint -Endpoint $AuthenticationEndpoint } } }
29.93913
142
0.601801
a0ca2bc011df325cf6d257bc46ca03e72a4a5e74
1,554
swift
Swift
SwiftCalc/SwiftCalc/History/SwiftUI_HistoryView.swift
baju0218/SwiftCalc
2735950b48da30c548b0ff1249be92ec192bb379
[ "Apache-2.0" ]
null
null
null
SwiftCalc/SwiftCalc/History/SwiftUI_HistoryView.swift
baju0218/SwiftCalc
2735950b48da30c548b0ff1249be92ec192bb379
[ "Apache-2.0" ]
null
null
null
SwiftCalc/SwiftCalc/History/SwiftUI_HistoryView.swift
baju0218/SwiftCalc
2735950b48da30c548b0ff1249be92ec192bb379
[ "Apache-2.0" ]
null
null
null
// // SwiftUI_HistoryView.swift // SwiftCalc // // Created by 윤진영 on 2021/04/05. // import SwiftUI struct SwiftUI_HistoryView: View { weak var delegate: CalcPadViewController? @State private var historyList : [History] = histories var body: some View { Button("닫기") { delegate?.dismiss(animated: true, completion: nil) } .padding(EdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)) List(historyList) { history in HStack { HistoryRow(history: history) .onTapGesture { delegate?.currentOperation = history.calcOperation delegate?.showResult(UIButton()) histories = historyList delegate?.dismiss(animated: true, completion: nil) } Spacer() Button("삭제") { histories.remove(at: histories.firstIndex(where: { $0 == history })!) historyList = histories } .foregroundColor(.red) } } } init(_ delegate: CalcPadViewController) { self.delegate = delegate } } struct HistoryRow: View { var history: History var body: some View { VStack(alignment: .leading, spacing: 8) { Text("\(history.getCalcOperationString())") Text("\(history.getDateString())") } } }
26.793103
89
0.497426
dbc5a6f0431f091df5ad939da08ea871ebc192cc
1,666
php
PHP
src/RockPaperScissors.php
micahcourey/rock_paper_scissors
3a13bd4c06aacb12a983a52e56a93d7a45c3b72d
[ "MIT", "Unlicense" ]
null
null
null
src/RockPaperScissors.php
micahcourey/rock_paper_scissors
3a13bd4c06aacb12a983a52e56a93d7a45c3b72d
[ "MIT", "Unlicense" ]
null
null
null
src/RockPaperScissors.php
micahcourey/rock_paper_scissors
3a13bd4c06aacb12a983a52e56a93d7a45c3b72d
[ "MIT", "Unlicense" ]
null
null
null
<?php class RockPaperScissors { function playRockPaperScissors($input1, $input2) { //Lowercase the user inputs. $input1 = strtolower($input1); $input2 = strtolower($input2); //Validate the user input by making a counter that counts the number of valid weapons. $weapons = array("rock", "paper", "scissors"); $player_weapons = array($input1, $input2); $validate = 0; foreach ($weapons as $weapon) { foreach ($player_weapons as $player) { if ($weapon == $player) { $validate = $validate + 1; } } } if ($validate < 2) { return "Someone didn't enter a valid weapon!"; } else { $rockpaperscissors = array( "rock" => array( "rock" => "It's a tie!", "paper" => "Player two wins!", "scissors" => "Player one wins!" ), "paper" => array( "rock" => "Player one wins!", "paper" => "It's a tie!", "scissors" => "Player two wins!" ), "scissors" => array( "rock" => "Player two wins!", "paper" => "Player one wins!", "scissors" => "It's a tie!" ) ); return $rockpaperscissors[$input1][$input2]; } } } ?>
36.217391
98
0.384754
751cff45edf0d48fc0c6a1bcda826b314f272c4b
861
css
CSS
data/usercss/183461.user.css
33kk/uso-archive
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
[ "MIT" ]
118
2020-08-28T19:59:28.000Z
2022-03-26T16:28:40.000Z
data/usercss/183461.user.css
33kk/uso-archive
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
[ "MIT" ]
38
2020-09-02T01:08:45.000Z
2022-01-23T02:47:24.000Z
data/usercss/183461.user.css
33kk/uso-archive
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
[ "MIT" ]
21
2020-08-19T01:12:43.000Z
2022-03-15T21:55:17.000Z
/* ==UserStyle== @name HN MATERIAL DARK @namespace USO Archive @author karimel @description `Material dark theme for Hacker News - work in progress...` @version 20200509.10.17 @license NO-REDISTRIBUTION @preprocessor uso ==/UserStyle== */ @-moz-document domain("news.ycombinator.com") { body { background-color: #263238; } table { background-color: #37474F; } a:link { color: #fff; } .hnmore a:visited { color: #607D8B !important; } .pagetop a { color: #80CBC4; } /* comments */ .subtext a:nth-child(6) { color: #FFDEA1; } /* points */ .subtext span:first-child { color: #338D83; } /* date */ .subtext a:nth-child(1) { color: #607DB2; } /* comment text */ .commtext { color: #d0d0d0; } }
20.023256
75
0.543554
fda0824cefa4f0c3a3ff055fa77a1a44864487ee
214
sql
SQL
NoteBooks/Curso de SQL/Queries_Platzi/rank.sql
Alejandro-sin/Learning_Notebooks
161d6bed4c7b1d171b45f61c0cc6fa91e9894aad
[ "MIT" ]
1
2021-02-26T13:12:22.000Z
2021-02-26T13:12:22.000Z
NoteBooks/Curso de SQL/Queries_Platzi/rank.sql
Alejandro-sin/Learning_Notebooks
161d6bed4c7b1d171b45f61c0cc6fa91e9894aad
[ "MIT" ]
null
null
null
NoteBooks/Curso de SQL/Queries_Platzi/rank.sql
Alejandro-sin/Learning_Notebooks
161d6bed4c7b1d171b45f61c0cc6fa91e9894aad
[ "MIT" ]
null
null
null
SELECT * FROM ( SELECT *, RANK() OVER (PARTITION BY carrera_id ORDER BY colegiatura DESC) brand_rank FROM public.alumnos ) AS rank_colegiaturas_por_carrera WHERE brand_rank <3 ORDER BY carrera_id, brand_rank;
21.4
75
0.785047
8b5dcb1e1a0abd658212943c854851ef994c6e7f
1,545
rb
Ruby
spec/requests/openid_connect_authorize_spec.rb
s2t2/identity-idp
e2d1361093327b1e5c769939a7a4e05523fd1404
[ "CC0-1.0" ]
null
null
null
spec/requests/openid_connect_authorize_spec.rb
s2t2/identity-idp
e2d1361093327b1e5c769939a7a4e05523fd1404
[ "CC0-1.0" ]
null
null
null
spec/requests/openid_connect_authorize_spec.rb
s2t2/identity-idp
e2d1361093327b1e5c769939a7a4e05523fd1404
[ "CC0-1.0" ]
null
null
null
require 'rails_helper' describe 'user signs in partially and visits openid_connect/authorize' do let(:user) { create(:user, :signed_up, phone: '+1 (202) 555-1213') } it 'prompts the user to 2FA' do openid_test('select_account') follow_redirect! expect(response). to redirect_to login_two_factor_path(otp_delivery_preference: 'sms', reauthn: false) end it 'prompts the user to 2FA if prompt is login' do openid_test('login') sp_request_id = ServiceProviderRequest.last.uuid expect(response).to redirect_to sign_up_start_path(request_id: sp_request_id) end it 'prompts the user to 2FA if prompt is not given' do openid_test follow_redirect! expect(response). to redirect_to login_two_factor_path(otp_delivery_preference: 'sms', reauthn: false) end def openid_test(prompt = nil) client_id = 'urn:gov:gsa:openidconnect:sp:server' state = SecureRandom.hex nonce = SecureRandom.hex post new_user_session_path, params: { user: { email: user.email, password: user.password } } follow_redirect! params = { client_id: client_id, response_type: 'code', acr_values: Saml::Idp::Constants::LOA3_AUTHN_CONTEXT_CLASSREF, scope: 'openid email profile:name social_security_number', redirect_uri: 'http://localhost:7654/auth/result', state: state, nonce: nonce, } params[:prompt] = prompt if prompt get( openid_connect_authorize_path, params: params, headers: { 'Accept' => '*/*' } ) end end
30.9
96
0.69644
254ec97d7701b2ebc47d1972b7b852e577bfd9bf
320
swift
Swift
mengmeng/CodePractice1/017 Daffodils.swift
haiyanw5837/CodePracticeResult
9a619f32f417ba16966f1b86ce0ec0d68326bff8
[ "Apache-2.0" ]
18
2019-12-29T11:35:10.000Z
2020-08-30T14:34:28.000Z
mengmeng/CodePractice1/017 Daffodils.swift
haiyanw5837/CodePracticeResult
9a619f32f417ba16966f1b86ce0ec0d68326bff8
[ "Apache-2.0" ]
63
2020-01-04T19:34:57.000Z
2021-01-02T21:57:43.000Z
mengmeng/CodePractice1/017 Daffodils.swift
haiyanw5837/CodePracticeResult
9a619f32f417ba16966f1b86ce0ec0d68326bff8
[ "Apache-2.0" ]
36
2021-01-29T22:39:07.000Z
2022-01-24T00:41:13.000Z
func daffodils() -> [Int] { var a : [Int] = [] for i in 100 ... 999 { let b = Int (i / 100) let c = Int (i / 10 - b * 10) let d = Int (i - b * 100 - c * 10) if b * b * b + c * c * c + d * d * d == i { a.append(i) } } return a } show("\(daffodils())")
21.333333
51
0.35625
0ad95a176fa103bac62b77bd1baaf76ab4624e31
829
cs
C#
Runtime/AnimationContext.cs
krylov-na/neat.tweening
9e74d4e25ad98d097b3c66016ec7aed56f9a35e8
[ "MIT" ]
null
null
null
Runtime/AnimationContext.cs
krylov-na/neat.tweening
9e74d4e25ad98d097b3c66016ec7aed56f9a35e8
[ "MIT" ]
null
null
null
Runtime/AnimationContext.cs
krylov-na/neat.tweening
9e74d4e25ad98d097b3c66016ec7aed56f9a35e8
[ "MIT" ]
null
null
null
using System.Collections.Generic; using UnityEngine; namespace Neat.Tweening { public class AnimationContext : MonoBehaviour { public string animationName; private readonly List<Tween> tweens = new List<Tween>(); private int currentState = -1; private void Reset() { animationName = "Transition"; } public void Register(Tween tween) { tweens.Add(tween); if (currentState != -1) { tween.SetState(currentState); } } public void Unregister(Tween tween) { tweens.Remove(tween); } public void SetState(int state, bool forceInstant = false) { tweens.ForEach(tween => tween.SetState(state, forceInstant)); currentState = state; } } }
25.90625
73
0.574186
f4a8ca78083996db546df3a418acbe61b2b9f137
201
ts
TypeScript
api/src/common/http_error.ts
LiZhiHao97/denolib_registry
cddea1ab79f130eaaf82568e3a5cb66948bc2f72
[ "MIT" ]
1
2021-07-09T05:18:57.000Z
2021-07-09T05:18:57.000Z
api/src/common/http_error.ts
LiZhiHao97/denolib_registry
cddea1ab79f130eaaf82568e3a5cb66948bc2f72
[ "MIT" ]
null
null
null
api/src/common/http_error.ts
LiZhiHao97/denolib_registry
cddea1ab79f130eaaf82568e3a5cb66948bc2f72
[ "MIT" ]
null
null
null
import { HttpException, HttpStatus } from "@nestjs/common"; export class InvalidUrlException extends HttpException { constructor() { super("Invalid URL", HttpStatus.INTERNAL_SERVER_ERROR); } }
28.714286
59
0.756219
459f654e31e45c6e4ce99f9d39d667c41d0dd137
234
py
Python
Chapter01/2_add.py
blep/Deep-Learning-for-Computer-Vision
c5f07d1af15e804cf238e7f9dbdb3c139d5696b2
[ "MIT" ]
null
null
null
Chapter01/2_add.py
blep/Deep-Learning-for-Computer-Vision
c5f07d1af15e804cf238e7f9dbdb3c139d5696b2
[ "MIT" ]
null
null
null
Chapter01/2_add.py
blep/Deep-Learning-for-Computer-Vision
c5f07d1af15e804cf238e7f9dbdb3c139d5696b2
[ "MIT" ]
null
null
null
import tensorflow.compat.v1 as tf tf.disable_v2_behavior() x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) z = x + y session = tf.Session() values = {x: 5.0, y: 4.0} result = session.run([z], values) print(result)
14.625
33
0.683761
884961e0c2f6dceb304bc8242f1d7b0257cf6017
875
lua
Lua
Assets/Art/MLua/UI/CreateRoleWindow/CreateRoleWindow.lua
Ganchong/LuaUI
39c84d2d81d293824b2f593555b2790c81fe0532
[ "MIT" ]
null
null
null
Assets/Art/MLua/UI/CreateRoleWindow/CreateRoleWindow.lua
Ganchong/LuaUI
39c84d2d81d293824b2f593555b2790c81fe0532
[ "MIT" ]
null
null
null
Assets/Art/MLua/UI/CreateRoleWindow/CreateRoleWindow.lua
Ganchong/LuaUI
39c84d2d81d293824b2f593555b2790c81fe0532
[ "MIT" ]
null
null
null
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by 干冲. --- DateTime: 2018/3/24 22:25 --- CreateRoleWindow = class("CreateRoleWindow", WindowBase) local this = CreateRoleWindow function this:OnWDAwake(uiObj) Log("CreateRoleWindow InitUI") self.UIObj = uiObj self:BindWindow(uiObj) self:AddButtonEvent() end function this:BindWindow(uiObj) --self.headStyle = Util.GetChildComponent(root,"headStyle",1) self.ReturnButton = Util.GetChildComponent(uiObj,"root/ReturnButton",ComponentName.Button) end function this:OnWDStart() LuaAPP.GetBackGroundManager():Change("createRoleBack") end function this:AddButtonEvent() self.ReturnButton.onClick:AddListener(function ()self:ReturnEvent() end) end function this:ReturnEvent() self:FinishWindow() end function this:GetUIType() return WindowType.FullType end return this
24.305556
94
0.754286
828a40c5a054ba07d0839979881c468343844af0
1,407
sql
SQL
database.sql
lagunal/videos
71cc1dc372ed333663557e54d3057fa2689fb28b
[ "MIT" ]
null
null
null
database.sql
lagunal/videos
71cc1dc372ed333663557e54d3057fa2689fb28b
[ "MIT" ]
null
null
null
database.sql
lagunal/videos
71cc1dc372ed333663557e54d3057fa2689fb28b
[ "MIT" ]
null
null
null
CREATE DATABASE IF NOT EXISTS videos; USE videos; CREATE TABLE users( id int(255) auto_increment not null, role varchar(20), name varchar(255), surname varchar(255), email varchar(255), password varchar(255), image varchar(255), created_at datetime, updated_at datetime, remember_token varchar(255), CONSTRAINT pk_users PRIMARY KEY(id) )ENGINE=InnoDb; CREATE TABLE videos( id int(255) auto_increment not null, user_id int(255) not null, title varchar(255), description text, status varchar(20), image varchar(255), video_path varchar(255), created_at datetime, updated_at datetime, CONSTRAINT pk_videos PRIMARY KEY(id), CONSTRAINT fk_videos_users FOREIGN KEY(user_id) REFERENCES users(id) )ENGINE=InnoDb; CREATE TABLE comments( id int(255) auto_increment not null, user_id int(255) not null, video_id int(255) not null, body text, created_at datetime, updated_at datetime, CONSTRAINT pk_comment PRIMARY KEY(id), CONSTRAINT fk_comment_video FOREIGN KEY(video_id) REFERENCES videos(id), CONSTRAINT fk_comment_user FOREIGN KEY(user_id) REFERENCES users(id) )ENGINE=InnoDb; INSERT INTO users (role, name, surname, email, password) VALUES ('ADMIN', 'John', 'Peters', 'john@gmail.com', 'john'); INSERT INTO videos (user_id, title, description) VALUES (1, 'video 2', 'video 2'); INSERT INTO comments (user_id, video_id, body) VALUES (1, 2, 'comment 1');
22.693548
72
0.74769
a99c79d23a0960917e6030e39d14425784ab1a75
411
dart
Dart
bin/_9_loop_for.dart
somkiet073/BasicDartProgramming
5388f59f77881f9409597241bd10d77f6b13f7da
[ "MIT" ]
null
null
null
bin/_9_loop_for.dart
somkiet073/BasicDartProgramming
5388f59f77881f9409597241bd10d77f6b13f7da
[ "MIT" ]
null
null
null
bin/_9_loop_for.dart
somkiet073/BasicDartProgramming
5388f59f77881f9409597241bd10d77f6b13f7da
[ "MIT" ]
null
null
null
// การเรียนรู้ภาษา Dart // หัวข้อที่ 9 เรื่องการทำซ้ำด้วย loop for void main() { for(var i=0; i<=10; i++){ if(i == 6){ break; } print(i); } print('-----'); // for...in var numbers = [0,1,2,3,4,5,6]; for(var number in numbers){ print(number); } print('-----'); List dayLists = ['Sunday','Monday','Tueday']; for(var daylist in dayLists){ print(daylist); } }
15.222222
47
0.50365
c348c88a00b6f31e841ca9c8acf17235e3eb415a
731
sql
SQL
db/seed.sql
reggiemace/employee-tracker
9488170382810ef2e42ede2b61001aa64abe076d
[ "MIT" ]
null
null
null
db/seed.sql
reggiemace/employee-tracker
9488170382810ef2e42ede2b61001aa64abe076d
[ "MIT" ]
null
null
null
db/seed.sql
reggiemace/employee-tracker
9488170382810ef2e42ede2b61001aa64abe076d
[ "MIT" ]
null
null
null
use employee_trackerDB; INSERT INTO department (name) VALUES ('Cyber'), ('Devolopment'), ('Testing'),('Contracts'); INSERT INTO role (title, salary, department_id) VALUES ('Securty Analyst', 100000, 1), ('Security Specialist', 75000, 1), ('Senior Software Developer', 100000, 2), ('Junior Software Developer', 650000, 2), ('Software Test Analyst', 75000, 3), ('Test Engineer', 139000, 3), ('Contracts Lead', 85000, 3), ('Contracts Specialist', 79000, 3); INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('John', 'Brown', 1, 100), ('Lisa', 'Raye', 2, 1), ('Amanda', 'Avant', 3, 300), ('Billy', 'Blankenship', 4, 3), ('Cristy', 'Carol', 5, 500), ('Danny', 'Devito', 6, 5); SELECT * FROM employee;
29.24
91
0.659371
8795ca6d5ea06b689d723710ca962a3304986f87
7,214
rs
Rust
src/lib.rs
ignatenkobrain/unbytify
af20ecd9ec44bc3341feffe3d0be1a3543ebc31b
[ "Apache-2.0" ]
3
2018-01-16T02:54:31.000Z
2020-02-14T10:55:50.000Z
src/lib.rs
ignatenkobrain/unbytify
af20ecd9ec44bc3341feffe3d0be1a3543ebc31b
[ "Apache-2.0" ]
2
2018-04-21T03:10:41.000Z
2020-02-15T22:48:06.000Z
src/lib.rs
ignatenkobrain/unbytify
af20ecd9ec44bc3341feffe3d0be1a3543ebc31b
[ "Apache-2.0" ]
2
2018-04-16T19:15:33.000Z
2020-02-14T09:55:51.000Z
// Copyright 2017 Dmytro Milinevskyi <dmilinevskyi@gmail.com> // 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. #![warn(missing_docs)] //! # Unbytify is a library to parse and represent digital units //! //! # Installation //! To start using `unbytify` it's enough to just enable it in your `Cargo.toml`: //! //! ```toml //! [dependencies] //! unbytify = "0.2" //! ``` //! //! A simple example should be self-explanatory: //! //! ```rust //! extern crate unbytify; //! use unbytify::*; //! //! fn main() { //! assert_eq!(unbytify("1.5K"), Ok(1024 + 512)); //! assert_eq!(bytify(1024 + 512), (1.5, "KiB")); //! } //! ``` #[macro_use] extern crate lazy_static; lazy_static! { static ref SUFFIXES: Vec<&'static str> = vec![ "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", ]; static ref B_POWERS: Vec<u64> = (0..SUFFIXES.len()).map(|x| 1024u64.pow(x as u32)).collect(); static ref B_POWERS_F: Vec<f64> = B_POWERS.iter().map(|x| *x as f64).collect(); } /// Represents parse failure #[derive(PartialEq, PartialOrd, Clone, Copy, Debug)] pub enum ParseError { /// Invalid input value Invalid, /// An overflow occurred Overflow, } impl std::error::Error for ParseError { fn description(&self) -> &str { match *self { ParseError::Invalid => "could not interpret string as byte size", ParseError::Overflow => "byte size too large", } } } impl std::fmt::Display for ParseError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", std::error::Error::description(self)) } } /// Converts human readable number of bytes to a byte count /// /// # Example /// ```rust /// extern crate unbytify; /// use unbytify::*; /// /// fn main() { /// assert_eq!(unbytify("1.5K"), Ok(1024 + 512)); /// assert_eq!(unbytify("1O"), Err(ParseError::Invalid)); /// assert_eq!(unbytify("42E"), Err(ParseError::Overflow)); /// } /// ``` pub fn unbytify(value: &str) -> Result<u64, ParseError> { lazy_static! { static ref SUFFIXES_LOWER: Vec<String> = SUFFIXES.iter().map(|x| x[..1].to_lowercase()).collect(); } let value = value.trim().to_lowercase(); if &value[..1] == "-" { return Err(ParseError::Invalid); } if let Ok(x) = value.parse::<u64>() { return Ok(x); } for (idx, suffix) in SUFFIXES_LOWER.iter().enumerate() { let mut res = value.split(suffix); let val: f64 = match res.next() { Some(x) => { match x.trim().parse() { Ok(x) => x, _ => continue, } }, _ => continue, }; match res.next() { Some(rest) => { if !rest.is_empty() && rest != "b" && rest != "ib" { return Err(ParseError::Invalid); } }, _ => { if val.ceil() as u64 != val as u64 { return Err(ParseError::Invalid); } }, }; if val as u64 == 0 { return Ok(0); } if val.ceil() as u64 == val as u64 { return (val as u64) .checked_mul(B_POWERS[idx]) .ok_or(ParseError::Overflow); } let val = val * B_POWERS_F[idx]; if val as u64 == 0 { return Err(ParseError::Overflow); } return Ok(val.floor() as u64); } Err(ParseError::Invalid) } /// Converts a byte count to a human readable value /// /// Returns a tuple of converted value with a suffix. /// /// # Example /// ```rust /// extern crate unbytify; /// use unbytify::*; /// /// fn main() { /// assert_eq!(bytify(512), (512.0, "B")); /// assert_eq!(bytify(1024 + 512), (1.5, "KiB")); /// } /// ``` pub fn bytify(value: u64) -> (f64, &'static str) { let (mut val, mut idx) = (0.0, 0); if value > 0 { idx = (value as f64).log(1024.0).floor() as usize; val = value as f64 / B_POWERS_F[idx]; } ((val * 1000.0).round() / 1000.0, SUFFIXES[idx]) } #[cfg(test)] mod tests { use super::*; #[test] fn test_unbytify() { assert_eq!(unbytify("-1"), Err(ParseError::Invalid)); assert_eq!(unbytify("- 1"), Err(ParseError::Invalid)); assert_eq!(unbytify("-1.0"), Err(ParseError::Invalid)); assert_eq!(unbytify("- 1.0"), Err(ParseError::Invalid)); assert_eq!(unbytify("0"), Ok(0)); assert_eq!(unbytify("0K"), Ok(0)); assert_eq!(unbytify("16E"), Err(ParseError::Overflow)); assert_eq!(unbytify("15.75E"), Ok(15 * 1024u64.pow(6) + 3 * (1024u64.pow(6) / 4))); assert_eq!(unbytify("1"), Ok(1)); assert_eq!(unbytify("1.0"), Ok(1)); assert_eq!(unbytify("1K"), Ok(1024)); assert_eq!(unbytify(" 1 K "), Ok(1024)); assert_eq!(unbytify("1.0K"), Ok(1024)); assert_eq!(unbytify("1.5K"), Ok(1024 + 512)); assert_eq!(unbytify("1.25K"), Ok(1024 + 256)); assert_eq!(unbytify("1.2K"), Ok((1.2 * 1024.0) as u64)); assert_eq!(unbytify("16.000001E"), Err(ParseError::Overflow)); assert_eq!(unbytify("42E"), Err(ParseError::Overflow)); assert_eq!(unbytify("1.5"), Err(ParseError::Invalid)); assert_eq!(unbytify("1O"), Err(ParseError::Invalid)); for (idx, suffix) in SUFFIXES.iter().enumerate() { let val = 4; let expected = Ok(val * 2u64.pow(10 * idx as u32)); assert_eq!(unbytify(&(val.to_string() + suffix)), expected); assert_eq!(unbytify(&(val.to_string() + &suffix[..1])), expected); assert_eq!(unbytify(&(val.to_string() + &suffix.to_lowercase())), expected); assert_eq!(unbytify(&(val.to_string() + &suffix[..1].to_lowercase())), expected); } } #[test] fn test_bytify() { assert_eq!(bytify(0), (0.0, "B")); assert_eq!(bytify(1024), (1.0, "KiB")); assert_eq!(bytify(1025), (1.001, "KiB")); assert_eq!(bytify(1024u64.pow(2)), (1.0, "MiB")); assert_eq!(bytify(std::u64::MAX), (16.0, "EiB")); for (idx, suffix) in SUFFIXES.iter().enumerate() { let val = 4; let expected = (val as f64, *suffix); assert_eq!(bytify(val * B_POWERS[idx]), expected); } } #[test] fn test_rebytify() { for idx in 0..SUFFIXES.len() { let val = 4; let formatted = (|(a, b)| format!("{} {}", a, b))(bytify(val * B_POWERS[idx])); assert_eq!(unbytify(&formatted).unwrap(), val * B_POWERS[idx]); } } }
29.08871
106
0.5402
6d215920e8ee2508e318060341ad679f51345a22
1,010
tsx
TypeScript
packages/docs/docsite/src/components/mark-testers/arc-tester.tsx
ziminskida/chart-parts
1805a7f5f43952b5f7e5c69fe0f61dae8c0aecb1
[ "MIT" ]
1
2021-03-12T16:38:36.000Z
2021-03-12T16:38:36.000Z
packages/docs/docsite/src/components/mark-testers/arc-tester.tsx
ziminskida/chart-parts
1805a7f5f43952b5f7e5c69fe0f61dae8c0aecb1
[ "MIT" ]
364
2020-04-24T20:17:00.000Z
2021-08-02T17:14:30.000Z
packages/docs/docsite/src/components/mark-testers/arc-tester.tsx
aksh-h/test
730ed5693cd971dfdab3f4b763ef6505d25e6c2a
[ "MIT" ]
1
2020-07-30T12:40:24.000Z
2020-07-30T12:40:24.000Z
/*! * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project. */ import React from 'react' import { SingleMarkTester } from './util/single-mark-tester' import * as palette from './util/palette' const BASE_ITEM = { stroke: palette.CRIMSON, fill: palette.GREY, } const ArcTester: React.FC = () => ( <SingleMarkTester initialScenegraph={{ marktype: 'arc', items: [ { ...BASE_ITEM, startAngle: -0.73, endAngle: 0.73, padAngle: 0, innerRadius: 0, outerRadius: 50, strokeWidth: 4, x: 100, y: 100, }, ], }} sliders={[ { name: 'x' }, { name: 'y' }, { name: 'startAngle', min: -6.28, max: 6.28, step: 0.1 }, { name: 'endAngle', min: -6.28, max: 6.28, step: 0.1 }, { name: 'padAngle', min: -6.28, max: 6.28, step: 0.1 }, { name: 'innerRadius', max: 100 }, { name: 'outerRadius', max: 100 }, { name: 'strokeWidth', max: 10 }, ]} /> ) export default ArcTester
21.489362
67
0.577228
15cc841d2950bbe7dc5ca56308ef820201b9b9e4
2,379
dart
Dart
lib/main.dart
Vedantgupta2303/GetSetPro
b63ab5cc7479a5077f7c9dd91848cb9c7e2c02d0
[ "MIT" ]
1
2021-05-30T05:13:07.000Z
2021-05-30T05:13:07.000Z
lib/main.dart
aman440/Taskify
b63ab5cc7479a5077f7c9dd91848cb9c7e2c02d0
[ "MIT" ]
null
null
null
lib/main.dart
aman440/Taskify
b63ab5cc7479a5077f7c9dd91848cb9c7e2c02d0
[ "MIT" ]
null
null
null
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'models/tabs.dart'; import 'services/auth.dart'; import 'task_list/models/task_data.dart'; import 'vedant_task/slidebar.dart'; import 'views/home.dart'; import 'views/login.dart'; import 'views/register.dart'; import 'views/space/home.dart'; import 'views/space/splash.dart'; import 'views/splash.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(App()); } class App extends StatelessWidget { @override final Future<FirebaseApp> _initialization = Firebase.initializeApp(); Widget build(BuildContext context) { return FutureBuilder( future: _initialization, builder: (context, snapshot) { if (snapshot.hasError) { return Center( child: Container( height: 100, width: double.infinity, child: Image.asset('assets/images/sloth.gif'))); } if (snapshot.connectionState == ConnectionState.done) { return MyApp(); } return Center( child: Container( height: 100, width: 100, child: CircularProgressIndicator())); }, ); } } class MyApp extends StatelessWidget { final _firebaseAuthUser = FirebaseAuth.instance; @override Widget build(BuildContext context) { final _auth = Auth(firebaseAuth: _firebaseAuthUser); return MultiProvider( providers: [ Provider<Auth>( create: (context) => _auth, ), ChangeNotifierProvider<TabViews>( create: (context) => TabViews(), ), ChangeNotifierProvider<TaskData>( create: (context) => TaskData(), ) ], child: MaterialApp( debugShowCheckedModeBanner: false, initialRoute: SplashPage.id, routes: { AppContainer.id: (context) => AppContainer(), HomePage.id: (context) => HomePage(), SplashPage.id: (context) => SplashPage(), RegisterPage.id: (context) => RegisterPage(), LoginPage.id: (context) => LoginPage(), SpaceSplashPage.id: (context) => SpaceSplashPage(), SpaceHomePage.id: (context) => SpaceHomePage(), }, ), ); } }
29.012195
78
0.62211
8db3c32ad7fe35d5b065157dddca36467abd27f7
2,475
js
JavaScript
src/taroConvert/src/interface/goodsEvaluate.js
fightingljm/taro-fashop
fbb6c03e8403a7b3c0f7f63a5bb697b021b8d607
[ "Apache-2.0" ]
1
2019-01-26T01:14:22.000Z
2019-01-26T01:14:22.000Z
src/taroConvert/src/interface/goodsEvaluate.js
fightingljm/taro-fashop
fbb6c03e8403a7b3c0f7f63a5bb697b021b8d607
[ "Apache-2.0" ]
null
null
null
src/taroConvert/src/interface/goodsEvaluate.js
fightingljm/taro-fashop
fbb6c03e8403a7b3c0f7f63a5bb697b021b8d607
[ "Apache-2.0" ]
null
null
null
import Interface from '../utils/interface.js' import Exception from '../utils/exception.js' export class GoodsEvaluateListInterface extends Interface { constructor(param) { super() try { this.total_number = param.total_number this.list = param.list.map(function(item) { return new GoodsEvaluateListInfoInterface(item) }) } catch (e) { throw new Exception( e, 'GoodsEvaluateListInterface interface attribute error' ) } } } export class GoodsEvaluateListInfoInterface extends Interface { constructor(param) { super() try { this.id = param.id this.goods_id = param.goods_id this.order_id = param.order_id this.goods_sku_id = param.goods_sku_id this.goods_title = param.goods_title this.goods_price = param.goods_price this.goods_pay_price = param.goods_pay_price this.goods_num = param.goods_num this.goods_img = param.goods_img this.goods_spec = param.goods_spec this.goods_type = param.goods_type this.goods_freight_way = param.goods_freight_way this.goods_freight_fee = param.goods_freight_fee this.evaluate_state = param.evaluate_state this.evaluate_time = param.evaluate_time this.lock_state = param.lock_state this.refund_handle_state = param.refund_handle_state this.refund_id = param.refund_id } catch (e) { throw new Exception( e, 'OrderListGoodsInterface interface attribute error' ) } } } export class GoodsEvaluateInfoInterface extends Interface { constructor(param) { super() try { this.nickname = param.nickname this.avatar = param.avatar this.score = param.score this.create_time = param.create_time this.content = param.content this.images = param.images this.additional_content = param.additional_content this.additional_images = param.additional_images this.additional_time = param.additional_time this.additional_interval_day = param.additional_time ? parseInt((param.additional_time - param.create_time) / 86400) : null this.reply_content = param.reply_content this.reply_time = param.reply_time this.reply_content2 = param.reply_content2 this.reply_time2 = param.reply_time2 } catch (e) { throw new Exception( e, 'GoodsEvaluateInfoInterface interface attribute error' ) } } }
30.9375
71
0.686061
57fdd459d592a3e10cb0980184b28dede6985ff4
948
php
PHP
mobile/detailtransaksi.php
TIF-GEMSTONE/RotiSIP-Web
b326fe9b66a83ad5e965e2bd830572169aeda349
[ "MIT" ]
null
null
null
mobile/detailtransaksi.php
TIF-GEMSTONE/RotiSIP-Web
b326fe9b66a83ad5e965e2bd830572169aeda349
[ "MIT" ]
1
2018-05-02T04:56:01.000Z
2018-05-02T04:56:01.000Z
mobile/detailtransaksi.php
TIF-GEMSTONE/RotiSIP-Web
b326fe9b66a83ad5e965e2bd830572169aeda349
[ "MIT" ]
null
null
null
<?php include 'koneksi.php'; if(mysqli_connect_errno()){ die('Unable to connect to database'.mysqli_connect_error()); } //Mendapatkan Nilai Dari Variable nis yang ingin ditampilkan $no = $_POST['no_transaksi']; $stmt = $con->prepare("SELECT nama_roti, harga, jumlah_roti, sub_total_sales FROM tabel_transaksi_sales , tabel_detail_sales , tabel_roti , tabel_sales WHERE tabel_transaksi_sales.no_transaksi=tabel_detail_sales.no_transaksi AND tabel_detail_sales.id_roti=tabel_roti.id_roti AND tabel_transaksi_sales.id_sales=tabel_sales.id_sales AND tabel_detail_sales.no_transaksi='$no';"); $stmt->execute(); $stmt->bind_result($nama, $harga, $jumlah, $subtotal); $detail = array(); while ($stmt->fetch()) { $temp = array(); $temp['nama_roti']=$nama; $temp['harga']=$harga; $temp['jumlah_roti']=$jumlah; $temp['sub_total_sales']=$subtotal; array_push($detail,$temp); } echo json_encode(array('result'=>$detail)); ?>
33.857143
377
0.735232
8366c0b6d15d60347dbae3f4bcd218826bf92071
874
lua
Lua
scripts/zones/Riverne-Site_A01/npcs/Unstable_Displacement.lua
MatthewJHBerry/topaz
aa6f3a1b4be1f1ae1e71dde680d768d958e163a9
[ "FTL" ]
null
null
null
scripts/zones/Riverne-Site_A01/npcs/Unstable_Displacement.lua
MatthewJHBerry/topaz
aa6f3a1b4be1f1ae1e71dde680d768d958e163a9
[ "FTL" ]
null
null
null
scripts/zones/Riverne-Site_A01/npcs/Unstable_Displacement.lua
MatthewJHBerry/topaz
aa6f3a1b4be1f1ae1e71dde680d768d958e163a9
[ "FTL" ]
1
2020-05-28T21:35:05.000Z
2020-05-28T21:35:05.000Z
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- local ID = require("scripts/zones/Riverne-Site_A01/IDs") require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onTrade(player, npc, trade) local offset = npc:getID() - ID.npc.DISPLACEMENT_OFFSET if (offset == 5 and TradeBCNM(player, npc, trade)) then -- The Wyrmking Descends return end end function onTrigger(player, npc) local offset = npc:getID() - ID.npc.DISPLACEMENT_OFFSET -- OURYU COMETH if (offset == 5) then player:messageSpecial(ID.text.SPACE_SEEMS_DISTORTED) end end function onEventUpdate(player, csid, option, extras) EventUpdateBCNM(player, csid, option, extras) end function onEventFinish(player, csid, option) end
27.3125
84
0.631579
5316d032738e21ff11874cb82c9a3f6febc156de
116
swift
Swift
WMF Framework/Bundle.swift
svemir/wikipedia-ios
c8a8a56cba21e615431ec6ea5ca6c2ea9f72f6c8
[ "MIT" ]
3
2019-07-08T18:47:13.000Z
2019-08-30T01:28:47.000Z
WMF Framework/Bundle.swift
ibhargav7/wikipedia-ios
59a4aebca2ce86fe286dad729ad0cc90026c64b8
[ "MIT" ]
1
2021-03-09T21:22:06.000Z
2021-03-09T21:22:06.000Z
WMF Framework/Bundle.swift
ibhargav7/wikipedia-ios
59a4aebca2ce86fe286dad729ad0cc90026c64b8
[ "MIT" ]
1
2022-01-20T08:53:10.000Z
2022-01-20T08:53:10.000Z
import Foundation extension Bundle { @objc static let wmf: Bundle = Bundle(identifier: "org.wikimedia.WMF")! }
19.333333
75
0.724138
c6d868e243d8b1949db60caae3d8aed24ba595f0
4,932
py
Python
src/lib3to6/__main__.py
mbarkhau/lib3to6
a38d0f6aff079807a98a0fcecf9dafabc869f2bb
[ "MIT" ]
11
2018-11-12T13:37:44.000Z
2022-02-25T13:56:51.000Z
src/lib3to6/__main__.py
mbarkhau/lib3to6
a38d0f6aff079807a98a0fcecf9dafabc869f2bb
[ "MIT" ]
3
2018-09-04T14:07:59.000Z
2022-01-25T09:54:42.000Z
src/lib3to6/__main__.py
mbarkhau/lib3to6
a38d0f6aff079807a98a0fcecf9dafabc869f2bb
[ "MIT" ]
2
2018-09-04T12:37:57.000Z
2019-09-02T12:53:26.000Z
#!/usr/bin/env python # This file is part of the lib3to6 project # https://github.com/mbarkhau/lib3to6 # # Copyright (c) 2019-2021 Manuel Barkhau (mbarkhau@gmail.com) - MIT License # SPDX-License-Identifier: MIT import io import re import sys import typing as typ import difflib import logging import click from . import common from . import packaging from . import transpile try: import pretty_traceback pretty_traceback.install(envvar='ENABLE_PRETTY_TRACEBACK') except ImportError: pass # no need to fail because of missing dev dependency logger = logging.getLogger("lib3to6") def _configure_logging(verbose: int = 0) -> None: if verbose >= 2: log_format = "%(asctime)s.%(msecs)03d %(levelname)-7s %(name)-17s - %(message)s" log_level = logging.DEBUG elif verbose == 1: log_format = "%(levelname)-7s - %(message)s" log_level = logging.INFO else: log_format = "%(levelname)-7s - %(message)s" log_level = logging.INFO logging.basicConfig(level=log_level, format=log_format, datefmt="%Y-%m-%dT%H:%M:%S") logger.debug("Logging configured.") click.disable_unicode_literals_warning = True # type: ignore[attr-defined] def _print_diff(source_text: str, fixed_source_text: str) -> None: differ = difflib.Differ() source_lines = source_text.splitlines() fixed_source_lines = fixed_source_text.splitlines() diff_lines = differ.compare(source_lines, fixed_source_lines) if not sys.stdout.isatty(): click.echo("\n".join(diff_lines)) return for line in diff_lines: if line.startswith("+ "): click.echo("\u001b[32m" + line + "\u001b[0m") elif line.startswith("- "): click.echo("\u001b[31m" + line + "\u001b[0m") elif line.startswith("? "): click.echo("\u001b[36m" + line + "\u001b[0m") else: click.echo(line) print() __INSTALL_REQUIRES_HELP = """ install_requires package dependencies (space separated). Functions as a whitelist for backported modules. """ __DEFAULT_MODE_HELP = """ [enabled/disabled] Default transpile mode. To transpile some files but not others. """ @click.command() @click.option( '-v', '--verbose', count=True, help="Control log level. -vv for debug level.", ) @click.option( "--target-version", default="2.7", metavar="<version>", help="Target version of python.", ) @click.option( "--diff", default=False, is_flag=True, help="Output diff instead of transpiled source.", ) @click.option( "--in-place", default=False, is_flag=True, help="Write result back to input file.", ) @click.option( "--install-requires", default=None, metavar="<packages>", help=__INSTALL_REQUIRES_HELP.strip(), ) @click.option( "--default-mode", default='enabled', metavar="<mode>", help=__DEFAULT_MODE_HELP.strip(), ) @click.argument( "source_files", metavar="<source_file>", nargs=-1, type=click.File(mode="r"), ) def main( target_version : str, diff : bool, in_place : bool, install_requires: typ.Optional[str], source_files : typ.Sequence[io.TextIOWrapper], default_mode : str = 'enabled', verbose : int = 0, ) -> None: _configure_logging(verbose) has_opt_error = False if target_version and not re.match(r"[0-9]+\.[0-9]+", target_version): print(f"Invalid argument --target-version={target_version}") has_opt_error = True if default_mode not in ('enabled', 'disabled'): print(f"Invalid argument --default-mode={default_mode}") print(" Must be either 'enabled' or 'disabled'") has_opt_error = True if not any(source_files): print("No files.") has_opt_error = True if has_opt_error: sys.exit(1) cfg = packaging.eval_build_config( target_version=target_version, install_requires=install_requires, default_mode=default_mode, ) for src_file in source_files: ctx = common.BuildContext(cfg, src_file.name) source_text = src_file.read() try: fixed_source_text = transpile.transpile_module(ctx, source_text) except common.CheckError as err: loc = src_file.name if err.lineno >= 0: loc += "@" + str(err.lineno) err.args = (loc + " - " + err.args[0],) + err.args[1:] raise if diff: _print_diff(source_text, fixed_source_text) elif in_place: with io.open(src_file.name, mode="w", encoding="utf-8") as fobj: fobj.write(fixed_source_text) else: print(fixed_source_text) if __name__ == '__main__': # NOTE (mb 2020-07-18): click supplies the parameters # pylint:disable=no-value-for-parameter main()
26.516129
88
0.628954
ff5f2604767219fd7aefda98b68f39ceb0404a95
7,990
py
Python
release/stubs.min/System/Windows/Forms/__init___parts/Screen.py
htlcnn/ironpython-stubs
780d829e2104b2789d5f4d6f32b0ec9f2930ca03
[ "MIT" ]
182
2017-06-27T02:26:15.000Z
2022-03-30T18:53:43.000Z
release/stubs.min/System/Windows/Forms/__init___parts/Screen.py
htlcnn/ironpython-stubs
780d829e2104b2789d5f4d6f32b0ec9f2930ca03
[ "MIT" ]
28
2017-06-27T13:38:23.000Z
2022-03-15T11:19:44.000Z
release/stubs.min/System/Windows/Forms/__init___parts/Screen.py
htlcnn/ironpython-stubs
780d829e2104b2789d5f4d6f32b0ec9f2930ca03
[ "MIT" ]
67
2017-06-28T09:43:59.000Z
2022-03-20T21:17:10.000Z
class Screen(object): """ Represents a display device or multiple display devices on a single system. """ def Equals(self,obj): """ Equals(self: Screen,obj: object) -> bool Gets or sets a value indicating whether the specified object is equal to this Screen. obj: The object to compare to this System.Windows.Forms.Screen. Returns: true if the specified object is equal to this System.Windows.Forms.Screen; otherwise,false. """ pass @staticmethod def FromControl(control): """ FromControl(control: Control) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the largest portion of the specified control. control: A System.Windows.Forms.Control for which to retrieve a System.Windows.Forms.Screen. Returns: A System.Windows.Forms.Screen for the display that contains the largest region of the specified control. In multiple display environments where no display contains the control,the display closest to the specified control is returned. """ pass @staticmethod def FromHandle(hwnd): """ FromHandle(hwnd: IntPtr) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the largest portion of the object referred to by the specified handle. hwnd: The window handle for which to retrieve the System.Windows.Forms.Screen. Returns: A System.Windows.Forms.Screen for the display that contains the largest region of the object. In multiple display environments where no display contains any portion of the specified window,the display closest to the object is returned. """ pass @staticmethod def FromPoint(point): """ FromPoint(point: Point) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the specified point. point: A System.Drawing.Point that specifies the location for which to retrieve a System.Windows.Forms.Screen. Returns: A System.Windows.Forms.Screen for the display that contains the point. In multiple display environments where no display contains the point,the display closest to the specified point is returned. """ pass @staticmethod def FromRectangle(rect): """ FromRectangle(rect: Rectangle) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the largest portion of the rectangle. rect: A System.Drawing.Rectangle that specifies the area for which to retrieve the display. Returns: A System.Windows.Forms.Screen for the display that contains the largest region of the specified rectangle. In multiple display environments where no display contains the rectangle,the display closest to the rectangle is returned. """ pass @staticmethod def GetBounds(*__args): """ GetBounds(ctl: Control) -> Rectangle Retrieves the bounds of the display that contains the largest portion of the specified control. ctl: The System.Windows.Forms.Control for which to retrieve the display bounds. Returns: A System.Drawing.Rectangle that specifies the bounds of the display that contains the specified control. In multiple display environments where no display contains the specified control,the display closest to the control is returned. GetBounds(rect: Rectangle) -> Rectangle Retrieves the bounds of the display that contains the largest portion of the specified rectangle. rect: A System.Drawing.Rectangle that specifies the area for which to retrieve the display bounds. Returns: A System.Drawing.Rectangle that specifies the bounds of the display that contains the specified rectangle. In multiple display environments where no monitor contains the specified rectangle, the monitor closest to the rectangle is returned. GetBounds(pt: Point) -> Rectangle Retrieves the bounds of the display that contains the specified point. pt: A System.Drawing.Point that specifies the coordinates for which to retrieve the display bounds. Returns: A System.Drawing.Rectangle that specifies the bounds of the display that contains the specified point. In multiple display environments where no display contains the specified point,the display closest to the point is returned. """ pass def GetHashCode(self): """ GetHashCode(self: Screen) -> int Computes and retrieves a hash code for an object. Returns: A hash code for an object. """ pass @staticmethod def GetWorkingArea(*__args): """ GetWorkingArea(ctl: Control) -> Rectangle Retrieves the working area for the display that contains the largest region of the specified control. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. ctl: The System.Windows.Forms.Control for which to retrieve the working area. Returns: A System.Drawing.Rectangle that specifies the working area. In multiple display environments where no display contains the specified control,the display closest to the control is returned. GetWorkingArea(rect: Rectangle) -> Rectangle Retrieves the working area for the display that contains the largest portion of the specified rectangle. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. rect: The System.Drawing.Rectangle that specifies the area for which to retrieve the working area. Returns: A System.Drawing.Rectangle that specifies the working area. In multiple display environments where no display contains the specified rectangle,the display closest to the rectangle is returned. GetWorkingArea(pt: Point) -> Rectangle Retrieves the working area closest to the specified point. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. pt: A System.Drawing.Point that specifies the coordinates for which to retrieve the working area. Returns: A System.Drawing.Rectangle that specifies the working area. In multiple display environments where no display contains the specified point,the display closest to the point is returned. """ pass def ToString(self): """ ToString(self: Screen) -> str Retrieves a string representing this object. Returns: A string representation of the object. """ pass def __eq__(self,*args): """ x.__eq__(y) <==> x==y """ pass def __ne__(self,*args): pass BitsPerPixel=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the number of bits of memory,associated with one pixel of data. Get: BitsPerPixel(self: Screen) -> int """ Bounds=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the bounds of the display. Get: Bounds(self: Screen) -> Rectangle """ DeviceName=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the device name associated with a display. Get: DeviceName(self: Screen) -> str """ Primary=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether a particular display is the primary device. Get: Primary(self: Screen) -> bool """ WorkingArea=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the working area of the display. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. Get: WorkingArea(self: Screen) -> Rectangle """ AllScreens=None PrimaryScreen=None
24.660494
150
0.705757
455c52ef1fd06934a57e4b3dda7460cc4ef03550
5,645
py
Python
src/manager/om/script/gspylib/inspection/items/device/CheckInodeUsage.py
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
1
2020-06-30T15:00:50.000Z
2020-06-30T15:00:50.000Z
src/manager/om/script/gspylib/inspection/items/device/CheckInodeUsage.py
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
src/manager/om/script/gspylib/inspection/items/device/CheckInodeUsage.py
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
# -*- coding:utf-8 -*- # Copyright (c) 2020 Huawei Technologies Co.,Ltd. # # openGauss is licensed under Mulan PSL v2. # You can use this software according to the terms # and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. # ---------------------------------------------------------------------------- import os from gspylib.common.Common import DefaultValue from gspylib.common.ErrorCode import ErrorCode from gspylib.inspection.common import SharedFuncs from gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult import ResultStatus from gspylib.hardware.gsdisk import g_disk TOTAL_THRESHOLD_NG = 500000000 class CheckInodeUsage(BaseItem): def __init__(self): super(CheckInodeUsage, self).__init__(self.__class__.__name__) self.Threshold_NG = None self.Threshold_Warning = None def preCheck(self): # check current node contains cn instances if not raise exception super(CheckInodeUsage, self).preCheck() # check the threshold was set correctly if (not (self.threshold.__contains__( 'Threshold_NG') and self.threshold.__contains__( 'Threshold_Warning'))): raise Exception(ErrorCode.GAUSS_530["GAUSS_53013"] % "The threshold Threshold_NG" " and Threshold_Warning") if (not self.threshold['Threshold_NG'].isdigit() or not self.threshold[ 'Threshold_Warning'].isdigit()): raise Exception(ErrorCode.GAUSS_530["GAUSS_53014"] % ("The threshold Threshold_NG[%s]" " and Threshold_Warning[%s]" % (self.Threshold_NG, self.Threshold_Warning))) self.Threshold_NG = int(self.threshold['Threshold_NG']) self.Threshold_Warning = int(self.threshold['Threshold_Warning']) if (self.Threshold_NG < self.Threshold_Warning): raise Exception(ErrorCode.GAUSS_530["GAUSS_53015"] % (self.Threshold_NG, self.Threshold_Warning)) if (self.Threshold_NG > 99 or self.Threshold_Warning < 1): raise Exception(ErrorCode.GAUSS_530["GAUSS_53016"] % (self.Threshold_NG, self.Threshold_Warning)) def obtainDataDir(self, nodeInfo): dataDirList = [] for inst in nodeInfo.datanodes: dataDirList.append(inst.datadir) dataDirList.append(DefaultValue.getEnv("PGHOST")) dataDirList.append(DefaultValue.getEnv("GPHOME")) dataDirList.append(DefaultValue.getEnv("GAUSSHOME")) dataDirList.append(DefaultValue.getEnv("GAUSSLOG")) dataDirList.append("/tmp") return dataDirList def obtainDiskDir(self): cmd = "df -h -P | awk '{print $6}'" output = SharedFuncs.runShellCmd(cmd) allDiskPath = output.split('\n')[1:] return allDiskPath def doCheck(self): flag = "Normal" resultStr = "" top = "" DiskList = [] DiskInfoDict = {} if (self.cluster): pathList = self.obtainDataDir( self.cluster.getDbNodeByName(self.host)) else: pathList = self.obtainDiskDir() for path in pathList: diskName = g_disk.getMountPathByDataDir(path) diskType = g_disk.getDiskMountType(diskName) if (not diskType in ["xfs", "ext3", "ext4"]): resultStr += \ "Path(%s) inodes usage(%s) Warning reason: " \ "The file system type [%s] is unrecognized " \ "or not support. Please check it.\n" % ( path, 0, diskType) if (flag == "Normal"): flag = "Warning" continue usageInfo = g_disk.getDiskInodeUsage(path) if (diskName in DiskList): continue else: DiskList.append(diskName) DiskInfoDict[usageInfo] = "%s %s%%" % (diskName, usageInfo) if (usageInfo > self.Threshold_NG): resultStr += "The usage of the device " \ "disk inodes[%s:%d%%] cannot be greater than" \ " %d%%.\n" % ( diskName, usageInfo, self.Threshold_NG) flag = "Error" elif (usageInfo > self.Threshold_Warning): resultStr += \ "The usage of the device disk inodes[%s:%d%%] " \ "cannot be greater than %d%%.\n" % ( diskName, usageInfo, self.Threshold_Warning) if (flag == "Normal"): flag = "Warning" self.result.val = resultStr if (flag == "Normal"): self.result.rst = ResultStatus.OK self.result.val = "All disk inodes are sufficient." elif (flag == "Warning"): self.result.rst = ResultStatus.WARNING else: self.result.rst = ResultStatus.NG keys = DiskInfoDict.keys() sorted(keys) self.result.raw = "diskname inodeUsage" for diskInfo in map(DiskInfoDict.get, keys): self.result.raw += "\n%s" % diskInfo
42.126866
79
0.573782
0a4a6ea88f527f86f3c000f229226d2771bd9dbb
1,097
cs
C#
Twisted/Assets/_Scripts/TubeCleaner.cs
CipicReborn/twisted
f05d854606764ad593c223572d0c33fa98ee905d
[ "Apache-2.0" ]
1
2018-04-11T10:02:32.000Z
2018-04-11T10:02:32.000Z
Twisted/Assets/_Scripts/TubeCleaner.cs
CipicReborn/twisted
f05d854606764ad593c223572d0c33fa98ee905d
[ "Apache-2.0" ]
null
null
null
Twisted/Assets/_Scripts/TubeCleaner.cs
CipicReborn/twisted
f05d854606764ad593c223572d0c33fa98ee905d
[ "Apache-2.0" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TubeCleaner : MonoBehaviour { #region PUBLIC METHODS public void ClearPassedSegments () { for (int i = 0; i < transform.childCount; i++) { var lChild = transform.GetChild(0); var end = lChild.position.z + lChild.GetChild(0).localScale.z; if (end < m_segmentsClearanceZBoundary) { ClearSegment(lChild); } else { break; } } } public void ClearAllSegments () { int startIndex = transform.childCount - 1; for (int i = startIndex; i >= 0; i--) { ClearSegment(transform.GetChild(i)); } } #endregion #region PRIVATE float m_segmentsClearanceZBoundary; private void Awake () { m_segmentsClearanceZBoundary = Camera.main.transform.position.z; } private void ClearSegment (Transform segment) { SegmentsPool.Instance.PutBackToPool(segment.GetComponent<Segment>()); } #endregion }
23.847826
77
0.597995
38c9a8bd8b4463c31dcb3890192c8d4dd9e0f86d
403
php
PHP
tests/Integration/Httplug/BaseIntegrationTest.php
ZebulanStanphill/Buzz
e7468d13f33fb6656068372533f2a446602fef09
[ "MIT" ]
1,080
2015-01-02T07:19:08.000Z
2022-03-27T21:43:39.000Z
tests/Integration/Httplug/BaseIntegrationTest.php
ZebulanStanphill/Buzz
e7468d13f33fb6656068372533f2a446602fef09
[ "MIT" ]
183
2015-01-10T02:15:54.000Z
2022-03-25T13:57:41.000Z
tests/Integration/Httplug/BaseIntegrationTest.php
ZebulanStanphill/Buzz
e7468d13f33fb6656068372533f2a446602fef09
[ "MIT" ]
193
2015-01-14T14:35:30.000Z
2022-03-18T23:04:08.000Z
<?php declare(strict_types=1); namespace Buzz\Test\Integration\Httplug; use Http\Client\Tests\HttpClientTest; use Http\Client\Tests\PHPUnitUtility; abstract class BaseIntegrationTest extends HttpClientTest { protected function setUp(): void { parent::setUp(); if (false === PHPUnitUtility::getUri()) { $this->markTestSkipped('No URL provided'); } } }
20.15
57
0.672457
3866e31bc53f10122a85b96eb735bdc31ff51a09
215
php
PHP
application/managers/model/ManagersModel.php
liaoyizhong/pumobile
a147e878e7b61264bcf64c3f5b6f4bfe7a38b306
[ "Apache-2.0" ]
null
null
null
application/managers/model/ManagersModel.php
liaoyizhong/pumobile
a147e878e7b61264bcf64c3f5b6f4bfe7a38b306
[ "Apache-2.0" ]
null
null
null
application/managers/model/ManagersModel.php
liaoyizhong/pumobile
a147e878e7b61264bcf64c3f5b6f4bfe7a38b306
[ "Apache-2.0" ]
null
null
null
<?php namespace app\managers\model; use app\common\model\BasicModel; /** * User: liaoyizhong * Date: 2017/12/7/007 * Time: 18:28 */ class ManagersModel extends BasicModel { protected $table = 'managers'; }
15.357143
38
0.693023
1aa860ee5b442fdbe09fb2b83a4cb5783db84dc3
799
py
Python
Projects/Python/YoutubeDownloader.py
KevinGandhi9898/Hackoween-Hacktoberfest2021
e99601b43aa032ac1bc76f5782a39302175383bd
[ "MIT" ]
19
2021-10-03T06:12:28.000Z
2021-10-30T13:07:56.000Z
Projects/Python/YoutubeDownloader.py
KevinGandhi9898/Hackoween-Hacktoberfest2021
e99601b43aa032ac1bc76f5782a39302175383bd
[ "MIT" ]
68
2021-10-03T05:59:13.000Z
2021-10-31T17:34:40.000Z
Projects/Python/YoutubeDownloader.py
KevinGandhi9898/Hackoween-Hacktoberfest2021
e99601b43aa032ac1bc76f5782a39302175383bd
[ "MIT" ]
122
2021-10-01T03:01:59.000Z
2021-11-02T16:45:42.000Z
# importing the module # You must download pytube lib by "pip install pytube3" from pytube import YouTube # where to save SAVE_PATH = "E:/" #to_do # link of the video to be downloaded link="https://www.youtube.com/watch?v=xWOoBJUqlbI" try: # object creation using YouTube # which was imported in the beginning yt = YouTube(link) except: print("Connection Error") #to handle exception # filters out all the files with "mp4" extension mp4files = yt.filter('mp4') #to set the name of the file yt.set_filename('GeeksforGeeks Video') # get the video with the extension and # resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: # downloading the video d_video.download(SAVE_PATH) except: print("Some Error!") print('Task Completed!')
24.212121
64
0.745932
c46eebd2204e02c3dc058ad76df2592432e13bdb
580
lua
Lua
behavior3/nodes/decorators/always_fail.lua
Cabriter/behavior3lua
c4dd0dae342d6664c23dbc1df1467eb9b4af78df
[ "MIT" ]
53
2019-07-26T08:55:52.000Z
2022-03-31T07:10:24.000Z
behavior3/nodes/decorators/always_fail.lua
Cabriter/behavior3lua
c4dd0dae342d6664c23dbc1df1467eb9b4af78df
[ "MIT" ]
7
2019-10-25T01:28:17.000Z
2022-03-14T02:43:02.000Z
behavior3/nodes/decorators/always_fail.lua
Cabriter/behavior3lua
c4dd0dae342d6664c23dbc1df1467eb9b4af78df
[ "MIT" ]
21
2019-09-04T07:30:27.000Z
2022-03-04T14:44:44.000Z
-- AlwaysSuccess -- local bret = require 'behavior3.behavior_ret' local M = { name = 'AlwaysFail', type = 'Decorator', desc = '始终返回失败', doc = [[ + 只能有一个子节点,多个仅执行第一个 + 不管子节点是否成功都返回失败 ]] } function M.run(node, env, enemy) local yeild, last_ret = node:resume(env) if yeild then if last_ret == bret.RUNNING then return last_ret end return bret.FAIL end local r = node.children[1]:run(env) if r == bret.RUNNING then return node:yeild(env) end return bret.FAIL end return M
18.125
45
0.584483
55dfb34e826f1a3ab9cbe7a0b2b062ea54925a71
11,948
lua
Lua
spec/mat4_spec.lua
LuaDist-testing/cpml-ci
22c50c541aaae9a87e1c9ae6e7fab6ce9138ff93
[ "MIT" ]
9
2016-12-13T21:10:27.000Z
2020-06-13T05:25:35.000Z
libs/cpml/spec/mat4_spec.lua
artDeil4ek/ludum-dare-37
351e841c98f1729a4c3c4104720dc6c8022c59fe
[ "MIT" ]
3
2016-12-15T18:49:57.000Z
2016-12-15T22:03:21.000Z
libs/cpml/spec/mat4_spec.lua
artDeil4ek/ludum-dare-37
351e841c98f1729a4c3c4104720dc6c8022c59fe
[ "MIT" ]
2
2016-12-13T19:42:55.000Z
2020-06-13T05:25:52.000Z
local mat4 = require "modules.mat4" local vec3 = require "modules.vec3" local utils = require "modules.utils" describe("mat4:", function() it("creates an identity matrix", function() local a = mat4() assert.is.equal(1, a[1]) assert.is.equal(0, a[2]) assert.is.equal(0, a[3]) assert.is.equal(0, a[4]) assert.is.equal(0, a[5]) assert.is.equal(1, a[6]) assert.is.equal(0, a[7]) assert.is.equal(0, a[8]) assert.is.equal(0, a[9]) assert.is.equal(0, a[10]) assert.is.equal(1, a[11]) assert.is.equal(0, a[12]) assert.is.equal(0, a[13]) assert.is.equal(0, a[14]) assert.is.equal(0, a[15]) assert.is.equal(1, a[16]) assert.is_true(a:is_mat4()) end) it("creates a filled matrix", function() local a = mat4 { 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6 } assert.is.equal(3, a[1]) assert.is.equal(3, a[2]) assert.is.equal(3, a[3]) assert.is.equal(3, a[4]) assert.is.equal(4, a[5]) assert.is.equal(4, a[6]) assert.is.equal(4, a[7]) assert.is.equal(4, a[8]) assert.is.equal(5, a[9]) assert.is.equal(5, a[10]) assert.is.equal(5, a[11]) assert.is.equal(5, a[12]) assert.is.equal(6, a[13]) assert.is.equal(6, a[14]) assert.is.equal(6, a[15]) assert.is.equal(6, a[16]) end) it("creates a filled matrix from vec4s", function() local a = mat4 { { 3, 3, 3, 3 }, { 4, 4, 4, 4 }, { 5, 5, 5, 5 }, { 6, 6, 6, 6 } } assert.is.equal(3, a[1]) assert.is.equal(3, a[2]) assert.is.equal(3, a[3]) assert.is.equal(3, a[4]) assert.is.equal(4, a[5]) assert.is.equal(4, a[6]) assert.is.equal(4, a[7]) assert.is.equal(4, a[8]) assert.is.equal(5, a[9]) assert.is.equal(5, a[10]) assert.is.equal(5, a[11]) assert.is.equal(5, a[12]) assert.is.equal(6, a[13]) assert.is.equal(6, a[14]) assert.is.equal(6, a[15]) assert.is.equal(6, a[16]) end) it("creates a filled matrix from a 3x3 matrix", function() local a = mat4 { 3, 3, 3, 4, 4, 4, 5, 5, 5 } assert.is.equal(3, a[1]) assert.is.equal(3, a[2]) assert.is.equal(3, a[3]) assert.is.equal(0, a[4]) assert.is.equal(4, a[5]) assert.is.equal(4, a[6]) assert.is.equal(4, a[7]) assert.is.equal(0, a[8]) assert.is.equal(5, a[9]) assert.is.equal(5, a[10]) assert.is.equal(5, a[11]) assert.is.equal(0, a[12]) assert.is.equal(0, a[13]) assert.is.equal(0, a[14]) assert.is.equal(0, a[15]) assert.is.equal(1, a[16]) end) it("creates a matrix from perspective", function() local a = mat4.from_perspective(45, 1, 0.1, 1000) assert.is_true(utils.tolerance( 2.414-a[1], 0.001)) assert.is_true(utils.tolerance( 2.414-a[6], 0.001)) assert.is_true(utils.tolerance(-1 -a[11], 0.001)) assert.is_true(utils.tolerance(-1 -a[12], 0.001)) assert.is_true(utils.tolerance(-0.2 -a[15], 0.001)) end) it("creates a matrix from HMD perspective", function() local t = { LeftTan = 2.3465312, RightTan = 0.9616399, UpTan = 2.8664987, DownTan = 2.8664987 } local a = mat4.from_hmd_perspective(t, 0.1, 1000, false, false) assert.is_true(utils.tolerance(a[1] - 0.605, 0.001)) assert.is_true(utils.tolerance(a[6] - 0.349, 0.001)) assert.is_true(utils.tolerance(a[9] - -0.419, 0.001)) assert.is_true(utils.tolerance(a[11]- -1.000, 0.001)) assert.is_true(utils.tolerance(a[12]- -1.000, 0.001)) assert.is_true(utils.tolerance(a[15]- -0.200, 0.001)) end) it("clones a matrix", function() local a = mat4.identity() local b = a:clone() assert.is.equal(a, b) end) it("multiplies two 4x4 matrices", function() local a = mat4 { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } local b = mat4 { 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 } local c = mat4():mul(a, b) local d = a * b assert.is.equal(30, c[1]) assert.is.equal(70, c[2]) assert.is.equal(110, c[3]) assert.is.equal(150, c[4]) assert.is.equal(70, c[5]) assert.is.equal(174, c[6]) assert.is.equal(278, c[7]) assert.is.equal(382, c[8]) assert.is.equal(110, c[9]) assert.is.equal(278, c[10]) assert.is.equal(446, c[11]) assert.is.equal(614, c[12]) assert.is.equal(150, c[13]) assert.is.equal(382, c[14]) assert.is.equal(614, c[15]) assert.is.equal(846, c[16]) assert.is.equal(c, d) end) it("multiplies a matrix and a vec4", function() local a = mat4 { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } local b = { 10, 20, 30, 40 } local c = mat4.mul_vec4({}, a, b) local d = a * b assert.is.equal(900, c[1]) assert.is.equal(1000, c[2]) assert.is.equal(1100, c[3]) assert.is.equal(1200, c[4]) assert.is.equal(c[1], d[1]) assert.is.equal(c[2], d[2]) assert.is.equal(c[3], d[3]) assert.is.equal(c[4], d[4]) end) it("scales a matrix", function() local a = mat4() local b = mat4():scale(a, vec3(5, 5, 5)) assert.is.equal(5, b[1]) assert.is.equal(5, b[6]) assert.is.equal(5, b[11]) end) it("rotates a matrix", function() local a = mat4() local b = mat4():rotate(a, math.rad(45), vec3.unit_z) assert.is_true(utils.tolerance( 0.7071-b[1], 0.001)) assert.is_true(utils.tolerance( 0.7071-b[2], 0.001)) assert.is_true(utils.tolerance(-0.7071-b[5], 0.001)) assert.is_true(utils.tolerance( 0.7071-b[6], 0.001)) end) it("translates a matrix", function() local a = mat4() local b = mat4():translate(a, vec3(5, 5, 5)) assert.is.equal(5, b[13]) assert.is.equal(5, b[14]) assert.is.equal(5, b[15]) end) it("inverts a matrix", function() local a = mat4() a:rotate(a, math.pi/4, vec3.unit_y) a:translate(a, vec3(4, 5, 6)) local b = mat4():invert(a) local c = mat4():mul(a, b) assert.is.equal(mat4(), c) local d = mat4() d:rotate(d, math.pi/4, vec3.unit_y) d:translate(d, vec3(4, 5, 6)) local e = -d local f = mat4():mul(d, e) assert.is.equal(mat4(), f) end) it("transposes a matrix", function() local a = mat4 { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4 } local b = mat4():transpose(a) assert.is.equal(1, b[1]) assert.is.equal(2, b[2]) assert.is.equal(3, b[3]) assert.is.equal(4, b[4]) assert.is.equal(1, b[5]) assert.is.equal(2, b[6]) assert.is.equal(3, b[7]) assert.is.equal(4, b[8]) assert.is.equal(1, b[9]) assert.is.equal(2, b[10]) assert.is.equal(3, b[11]) assert.is.equal(4, b[12]) assert.is.equal(1, b[13]) assert.is.equal(2, b[14]) assert.is.equal(3, b[15]) assert.is.equal(4, b[16]) end) it("shears a matrix", function() local a = mat4() local yx, zx, xy, zy, xz, yz = 1, 1, 1, -1, -1, -1 local b = mat4():shear(a, yx, zx, xy, zy, xz, yz) assert.is.equal( 1, b[2]) assert.is.equal( 1, b[3]) assert.is.equal( 1, b[5]) assert.is.equal(-1, b[7]) assert.is.equal(-1, b[9]) assert.is.equal(-1, b[10]) end) it("projects a matrix into screen space", function() local v = vec3(0, 0, 10) local a = mat4() local b = mat4.from_perspective(45, 1, 0.1, 1000) local vp = { 0, 0, 400, 400 } local c = mat4.project(v, a, b, vp) assert.is.equal(200, c.x) assert.is.equal(200, c.y) assert.is_true(utils.tolerance(1.0101-c.z, 0.001)) end) it("unprojects a matrix into world space", function() local v = vec3(0, 0, 10) local a = mat4() local b = mat4.from_perspective(45, 1, 0.1, 1000) local vp = { 0, 0, 400, 400 } local c = mat4.project(v, a, b, vp) local d = mat4.unproject(c, a, b, vp) assert.is_true(utils.tolerance(v.x-d.x, 0.001)) assert.is_true(utils.tolerance(v.y-d.y, 0.001)) assert.is_true(utils.tolerance(v.z-d.z, 0.001)) end) it("transforms a matrix to look at a point", function() local a = mat4() local e = vec3(0, 0, 1.55) local c = vec3(4, 7, 1) local u = vec3(0, 0, 1) local b = mat4():look_at(a, e, c, u) assert.is_true(utils.tolerance( 0.868-b[1], 0.001)) assert.is_true(utils.tolerance( 0.034-b[2], 0.001)) assert.is_true(utils.tolerance(-0.495-b[3], 0.001)) assert.is_true(utils.tolerance( 0 -b[4], 0.001)) assert.is_true(utils.tolerance(-0.496-b[5], 0.001)) assert.is_true(utils.tolerance( 0.059-b[6], 0.001)) assert.is_true(utils.tolerance(-0.866-b[7], 0.001)) assert.is_true(utils.tolerance( 0 -b[8], 0.001)) assert.is_true(utils.tolerance( 0 -b[9], 0.001)) assert.is_true(utils.tolerance( 0.998-b[10], 0.001)) assert.is_true(utils.tolerance( 0.068-b[11], 0.001)) assert.is_true(utils.tolerance( 0 -b[12], 0.001)) assert.is_true(utils.tolerance( 0 -b[13], 0.001)) assert.is_true(utils.tolerance(-1.546-b[14], 0.001)) assert.is_true(utils.tolerance(-0.106-b[15], 0.001)) assert.is_true(utils.tolerance( 1 -b[16], 0.001)) end) it("converts a matrix to vec4s", function() local a = mat4() local v = a:to_vec4s() assert.is_true(type(v) == "table") assert.is_true(type(v[1]) == "table") assert.is_true(type(v[2]) == "table") assert.is_true(type(v[3]) == "table") assert.is_true(type(v[4]) == "table") assert.is.equal(1, v[1][1]) assert.is.equal(0, v[1][2]) assert.is.equal(0, v[1][3]) assert.is.equal(0, v[1][4]) assert.is.equal(0, v[2][1]) assert.is.equal(1, v[2][2]) assert.is.equal(0, v[2][3]) assert.is.equal(0, v[2][4]) assert.is.equal(0, v[3][1]) assert.is.equal(0, v[3][2]) assert.is.equal(1, v[3][3]) assert.is.equal(0, v[3][4]) assert.is.equal(0, v[4][1]) assert.is.equal(0, v[4][2]) assert.is.equal(0, v[4][3]) assert.is.equal(1, v[4][4]) end) it("converts a matrix to a quaternion", function() local a = mat4() local b = mat4 { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 } local q = b:to_quat() assert.is.equal(-0.5, q.x) assert.is.equal(-0.5, q.y) assert.is.equal(-0.5, q.z) assert.is.equal( 0.5, q.w) end) it("converts a matrix to a frustum", function() local a = mat4() local b = mat4.from_perspective(45, 1, 0.1, 1000) local f = mat4():mul(b, a):to_frustum() assert.is_true(utils.tolerance( 0.9239-f.left.a, 0.001)) assert.is_true(utils.tolerance( 0 -f.left.b, 0.001)) assert.is_true(utils.tolerance(-0.3827-f.left.c, 0.001)) assert.is_true(utils.tolerance( 0 -f.left.d, 0.001)) assert.is_true(utils.tolerance(-0.9239-f.right.a, 0.001)) assert.is_true(utils.tolerance( 0 -f.right.b, 0.001)) assert.is_true(utils.tolerance(-0.3827-f.right.c, 0.001)) assert.is_true(utils.tolerance( 0 -f.right.d, 0.001)) assert.is_true(utils.tolerance( 0 -f.bottom.a, 0.001)) assert.is_true(utils.tolerance( 0.9239-f.bottom.b, 0.001)) assert.is_true(utils.tolerance(-0.3827-f.bottom.c, 0.001)) assert.is_true(utils.tolerance( 0 -f.bottom.d, 0.001)) assert.is_true(utils.tolerance( 0 -f.top.a, 0.001)) assert.is_true(utils.tolerance(-0.9239-f.top.b, 0.001)) assert.is_true(utils.tolerance(-0.3827-f.top.c, 0.001)) assert.is_true(utils.tolerance( 0 -f.top.d, 0.001)) assert.is_true(utils.tolerance( 0 -f.near.a, 0.001)) assert.is_true(utils.tolerance( 0 -f.near.b, 0.001)) assert.is_true(utils.tolerance(-1 -f.near.c, 0.001)) assert.is_true(utils.tolerance(-0.1-f.near.d, 0.001)) assert.is_true(utils.tolerance( 0 -f.far.a, 0.001)) assert.is_true(utils.tolerance( 0 -f.far.b, 0.001)) assert.is_true(utils.tolerance( 1 -f.far.c, 0.001)) assert.is_true(utils.tolerance( 1000-f.far.d, 0.001)) end) it("checks to see if data is a valid matrix (not a table)", function() assert.is_not_true(mat4.is_mat4(0)) end) it("checks to see if data is a valid matrix (invalid data)", function() assert.is_not_true(mat4.is_mat4({})) end) it("gets a string representation of a matrix", function() local a = mat4() local b = a:to_string() local z = "+0.000" local o = "+1.000" local s = string.format( "[ %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ]", o, z, z, z, z, o, z, z, z, z, o, z, z, z ,z, o ) assert.is.equal(s, b) end) end) --[[ from_angle_axis from_quaternion from_direction from_transform from_ortho --]]
27.915888
72
0.607131
6de22f9c254dfd050054eb8597b62df05c7ca71f
1,677
ts
TypeScript
test/codegen/CodegenTest.ts
kasparsj/schema
098f3dc2663da478a76c98a4f1aadbfed84923bc
[ "MIT" ]
1
2020-03-24T01:48:07.000Z
2020-03-24T01:48:07.000Z
test/codegen/CodegenTest.ts
sutext/schema
811a9cd9504c11a2646a9cb7f23f57e471f65307
[ "MIT" ]
null
null
null
test/codegen/CodegenTest.ts
sutext/schema
811a9cd9504c11a2646a9cb7f23f57e471f65307
[ "MIT" ]
null
null
null
import * as fs from "fs"; import * as path from "path"; import * as rimraf from "rimraf"; import * as glob from "glob"; import * as assert from "assert"; import { generate } from "../../src/codegen/api"; const INPUT_DIR = path.resolve(__dirname, "sources"); const OUTPUT_DIR = path.resolve(__dirname, "tmp-codegen-output"); describe("schema-codegen", () => { beforeEach(() => { rimraf.sync(OUTPUT_DIR); fs.mkdirSync(OUTPUT_DIR); }); afterEach(() => { rimraf.sync(OUTPUT_DIR) fs.mkdirSync(OUTPUT_DIR); }); it("should generate 3 files", async () => { const inputFiles = glob.sync(path.resolve(INPUT_DIR, "*.ts")); generate("csharp", { files: inputFiles, output: OUTPUT_DIR }); const outputFiles = glob.sync(path.resolve(OUTPUT_DIR, "*.cs")); assert.equal(3, outputFiles.length); }); it("should auto-import related schema files", async () => { const inputFiles = glob.sync(path.resolve(INPUT_DIR, "Inheritance.ts")); generate("csharp", { files: inputFiles, output: OUTPUT_DIR }); const outputFiles = glob.sync(path.resolve(OUTPUT_DIR, "*.cs")); assert.equal(2, outputFiles.length); }); it("should support using 'type' along with `defineTypes`", async () => { const inputFiles = glob.sync(path.resolve(INPUT_DIR, "DefineTypes.js")); generate("csharp", { files: inputFiles, output: OUTPUT_DIR }); const outputFiles = glob.sync(path.resolve(OUTPUT_DIR, "*.cs")); assert.equal(1, outputFiles.length); }); });
29.421053
80
0.587955
7ef2c7f8a4683a738724d7d888269196fba24e70
296
rb
Ruby
sprout-osx-git/attributes/authors.rb
miketheman/sprout
711f465803d37704065a123a8af9d84b395debc6
[ "MIT" ]
1
2020-02-02T21:56:45.000Z
2020-02-02T21:56:45.000Z
sprout-osx-git/attributes/authors.rb
trinitronx/sprout-osx-apps
84319f7897e00c1e892f0bde4755eb1e311abb1a
[ "MIT" ]
null
null
null
sprout-osx-git/attributes/authors.rb
trinitronx/sprout-osx-apps
84319f7897e00c1e892f0bde4755eb1e311abb1a
[ "MIT" ]
2
2016-12-22T18:06:25.000Z
2022-03-18T19:31:18.000Z
node.default["sprout"]["git"]["domain"] = "pivotallabs.com" node.default["sprout"]["git"]["authors"] = [ {"initials" => "bc", "author" => "Brian Cunnie", "username" => "cunnie"}, {"initials" => "ah", "author" => "Abhi Hiremagalur", "username" => "abhi", "email" => "abhijit@hiremaga.com"}, ]
49.333333
112
0.587838
651addae4a3d8f72541495c61c9b4f4ca05441a1
7,523
css
CSS
WebApp/Styles/SharePanel.css
AppGeo/GPV
8adbbf68ad0022a3023eaec99310c2174e420233
[ "Apache-2.0" ]
10
2015-03-31T03:43:25.000Z
2018-11-20T17:05:53.000Z
WebApp/Styles/SharePanel.css
AppGeo/GPV
8adbbf68ad0022a3023eaec99310c2174e420233
[ "Apache-2.0" ]
147
2015-01-13T19:55:32.000Z
2020-02-14T15:34:58.000Z
WebApp/Styles/SharePanel.css
AppGeo/GPV
8adbbf68ad0022a3023eaec99310c2174e420233
[ "Apache-2.0" ]
8
2015-05-08T13:24:54.000Z
2018-09-15T03:03:12.000Z
/* Copyright 2016 Applied Geographics, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pnlShareContent{ top: 40px; } .share{ display: none; } #cmdPrint { left: 12px; top: 5px; } #frmPrint { margin-top: 6px; } /** New style for share panel Date 14-09-2017 */ /* Share details panel */ #pnlShareContent .share_box .frm_row .twoCol { float: left; } #pnlShareContent .share_box .frm_row .threeCol { float: left; } #pnlPrint .PrintOptionLabel{ float: left; position: relative; top: 2px; left: 5px; font-size: 12.5px; } .printInput label { margin-bottom: 15px; display: inline-block; width: 50px; float: left; font-weight : unset; } .printInput input { margin-bottom: 12px; display: inline-block; width: calc(100% - 50px); float: right; border: none; border-radius: 3px; padding: 5px 8px; font-size: 13px; height: 30px; } /*.seg_title{ font-size: 15px; } */ .share_box{ width: 100%; float: left; border: 1px solid #949494; min-height: 250px; margin-top: 20px; padding: 12px 15px; } .share .share_box .frmLabel{ width: 43px; } .share .share_box .frmField{ width: calc(100% - 47px); } #pnlShareContent .share_box { padding: 12px 12px; } .share .share_box .frmField .frmRadio{ position: relative; top: -1px; float: left; } .share .share_box .frmField .inlineCol{ display: inline-block; } .share .share_box .frmField .inlineCol .ratting{ width: 60px; border-radius: 0; } .customGoto{ width: 74%!important; float: left!important; margin-left: 0!important; } #pnlShareContent .share_box .frm_row .twoCol { float: left; width: 20%; } #cmdExternalMap{ min-width: 56px; float: right; min-height: 29px; } #pnlDownload .share_box .frm_row div.threeCol:first-child{ width: 50px; padding-top: 5px; } #pnlDownload .share_box .frm_row .customExport{ width: 76%; } #pnlDownload .share_box .frm_row div.threeCol:nth-of-type(3){ margin-top: 10px; width: 79%; float: right; } #cmdSaveMap{ float: left; } #pnlMarkup div:nth-of-type(3){ } #cmdSaveMap{ min-width: 70px; } #pnlPrintInputs .printInput{ float: left } /* ===========================SharePrint Custom DropDown============================= */ .customPrint { position: relative; /*Don't really need this just for demo styling*/ float: left; min-width: calc(100% / 2 - 8px); } .customPrint:after { content: " "; font: normal normal normal 17px/1 FontAwesome; color: #b7b7b7; right: 11px; top: 0; height: 29px; padding: 5px 0 0 8px; border-left: 1px solid #b7b7b7; position: absolute; pointer-events: none; background-color: #fff; width: 21px; background-image: url(../Images/UI/all-icons.png); background-position: -184px -92px; } /* IE11 hide native button (thanks Matt!) */ select::-ms-expand { display: none; } .customPrint select { -webkit-appearance: none; -moz-appearance: none; appearance: none; /* Add some styling */ display: block; width: 100%; max-width: 320px; height: 29px; float: right; margin: 0px; padding: 0px 40px 0 5px; font-size: 13px; line-height: 1.75; color: #333; background-color: #ffffff; background-image: none; border: none; -ms-word-break: normal; word-break: normal; outline: none; } /* ===========================ShareGoto Custom DropDown============================= */ .customGoto { position: relative; /*Don't really need this just for demo styling*/ float: left; min-width: calc(100% / 2 - 8px); } .customGoto:after { content: " "; font: normal normal normal 17px/1 FontAwesome; color: #b7b7b7; right: 11px; top: 0; height: 29px; padding: 5px 0 0 8px; border-left: 1px solid #b7b7b7; position: absolute; pointer-events: none; background-color: #fff; width: 21px; background-image: url(../Images/UI/all-icons.png); background-position: -184px -92px; } /* IE11 hide native button (thanks Matt!) */ select::-ms-expand { display: none; } .customGoto select { -webkit-appearance: none; -moz-appearance: none; appearance: none; /* Add some styling */ display: block; width: 100%; max-width: 320px; height: 29px; float: right; margin: 0px; padding: 0px 40px 0 5px; font-size: 13px; line-height: 1.75; color: #333; background-color: #ffffff; background-image: none; border: none; -ms-word-break: normal; word-break: normal; outline: none; } /* ===========================ShareExport Custom DropDown============================= */ .customExport { position: relative; /*Don't really need this just for demo styling*/ float: left; } .customExport:after { content: " "; font: normal normal normal 17px/1 FontAwesome; color: #b7b7b7; right: 11px; top: 0; height: 29px; padding: 5px 0 0 8px; border-left: 1px solid #b7b7b7; position: absolute; pointer-events: none; background-color: #fff; width: 21px; background-image: url(../Images/UI/all-icons.png); background-position: -184px -92px; } /* IE11 hide native button (thanks Matt!) */ select::-ms-expand { display: none; } .customExport select { -webkit-appearance: none; -moz-appearance: none; appearance: none; /* Add some styling */ display: block; width: 100%; max-width: 320px; height: 29px; float: right; margin: 0px; padding: 0px 40px 0 5px; font-size: 13px; line-height: 1.75; color: #333; background-color: #ffffff; background-image: none; border: none; -ms-word-break: normal; word-break: normal; outline: none; } .printInput input { margin-bottom: 12px; display: inline-block; width: calc(100% - 47px) !important; /* no need important*/ float: right; border: none; border-radius: 3px; padding: 5px 8px; font-size: 13px; height: 30px; } .printInput label { margin-bottom: 15px; display: inline-block; width: 47px !important; /* no need important*/ float: left; font-weight: unset; } .btnPrint { background-image: url(../Images/print-icon-black.png); background-repeat: no-repeat; background-position: 8px center !important; /* no need important*/ padding-left: 12px !important; /* no need important*/ } .LocPrint { background-image: url(../Images/loc-icon-black.png); background-repeat: no-repeat; background-repeat: no-repeat; background-position: 8px center !important; /* no need important*/ padding-left: 8px !important; /* no need important*/ } .exprtPrint { background-image: url(../Images/export-icon-black.png); background-repeat: no-repeat; background-repeat: no-repeat; background-position: 8px center !important; /* no need important*/ padding-left: 18px !important; /* no need important*/ } /* share panel ends */
21.494286
89
0.631929
f5e846b0a6f2b819254d49b9a978a4b64683b85d
2,281
css
CSS
frontend/web/css/leave.css
qingshanyinyin/yii-blog
be82a96d693f7a1b7b8b16d39ba2344b6a8be03d
[ "BSD-3-Clause" ]
2
2019-01-08T09:06:34.000Z
2019-07-09T07:52:39.000Z
frontend/web/css/leave.css
qingshanyinyin/yii-blog
be82a96d693f7a1b7b8b16d39ba2344b6a8be03d
[ "BSD-3-Clause" ]
null
null
null
frontend/web/css/leave.css
qingshanyinyin/yii-blog
be82a96d693f7a1b7b8b16d39ba2344b6a8be03d
[ "BSD-3-Clause" ]
null
null
null
@charset "UTF-8"; .leave-content { padding: 20px 30px; background: #fff; margin-bottom: 15px; position: relative; border-radius: 5px; } .nav-tabs a:focus { outline:none; } .comment-details { padding: 10px 10px 0 10px; margin-top: 15px; border-bottom: 1px dashed #ccc; } .comment-face { } .comment-face img { width: 45px; height: 45px; } .comment-account { margin-bottom: 5px; } .comment-content,.comment-other { font-size: 14px; line-height: 1.5em; margin: 0.5em 0; word-wrap: break-word; color: #666; } .comment-other a { font-size: 12px; background-color: transparent; color: #999; cursor: pointer; text-decoration: none; transition: color 0.15s linear 0s; margin-left: 10px; } .comment-page { } .comment-user-other { color: #96CDCD; font-size: 12px; } .comment-signature { color: #8B6914; font-size: 12px; } .webs-right { background: #fff; float: left; width: 100%; padding: 20px 20px; margin-bottom: 10px; } .webs-right h3 { font-size: 15px; color: #2aabd2; border-bottom: 1px solid #eee; margin-bottom: 15px; } .webs-owner .media a img { width: 50px; height: 50px; } .webs-owner .media h4 { color: #00b3ee; font-size: 14px; } .webs-adv img { margin-bottom: 10px; } .types-box h5 { margin-top: 5px; } .types-box h5, .types-box h5 a { color: #666; display: block; } .types-box h5 a:hover, .types-box p a:hover { color: #4F94CD; } .types-box p a { color: #666; display: block; padding-left: 15px; } .hots-article li { line-height: 180%; } .hots-article li a { color: #666; display: block; } .hots-article li a:hover { color: #4F94CD; } .keyword { color: #E94C4C; font-weight: bold; } .webs-adv img { width: 100%; } .site-apply-link { font-size: 12px; } .site-link { background: #ff6666; color: #fff; padding: 2px 5px; font-size: 12px; margin-bottom: 5px; display: inline-block; } .site-link:hover { color: #fff; } @media(max-width:767px) { }
14.908497
46
0.553705
c9804030c57ba10b31ec0a56c24642e618a60b9b
519
ts
TypeScript
src/publication/publication.controller.ts
FTN-Team-DevOps/nistagram-publications
3d5ecb63cc65a357d96784586dd9ee338244871d
[ "MIT" ]
null
null
null
src/publication/publication.controller.ts
FTN-Team-DevOps/nistagram-publications
3d5ecb63cc65a357d96784586dd9ee338244871d
[ "MIT" ]
null
null
null
src/publication/publication.controller.ts
FTN-Team-DevOps/nistagram-publications
3d5ecb63cc65a357d96784586dd9ee338244871d
[ "MIT" ]
null
null
null
import { Controller } from '@nestjs/common'; import { MessagePattern, Payload } from '@nestjs/microservices'; import { PublicationService } from './publication.service'; @Controller('/') export class PublicationController { constructor(private readonly publicationService: PublicationService) {} @MessagePattern('publications-get') // eslint-disable-next-line @typescript-eslint/no-unused-vars async myController(@Payload() data: any): Promise<string> { return await this.publicationService.test(); } }
34.6
73
0.753372
20e02272d764fe7eb4c244f7cad64f150f590ce1
14,704
py
Python
S3/FileLists.py
aral/s3cmd
df748aa5cd87c4d63423523392ab5514d6d336dc
[ "ADSL" ]
1
2021-09-04T03:58:18.000Z
2021-09-04T03:58:18.000Z
S3/FileLists.py
aral/s3cmd
df748aa5cd87c4d63423523392ab5514d6d336dc
[ "ADSL" ]
null
null
null
S3/FileLists.py
aral/s3cmd
df748aa5cd87c4d63423523392ab5514d6d336dc
[ "ADSL" ]
null
null
null
## Create and compare lists of files/objects ## Author: Michal Ludvig <michal@logix.cz> ## http://www.logix.cz/michal ## License: GPL Version 2 from S3 import S3 from Config import Config from S3Uri import S3Uri from SortedDict import SortedDict from Utils import * from Exceptions import ParameterError from logging import debug, info, warning, error import os import glob __all__ = ["fetch_local_list", "fetch_remote_list", "compare_filelists", "filter_exclude_include"] def _fswalk_follow_symlinks(path): ''' Walk filesystem, following symbolic links (but without recursion), on python2.4 and later If a recursive directory link is detected, emit a warning and skip. ''' assert os.path.isdir(path) # only designed for directory argument walkdirs = set([path]) targets = set() for dirpath, dirnames, filenames in os.walk(path): for dirname in dirnames: current = os.path.join(dirpath, dirname) target = os.path.realpath(current) if os.path.islink(current): if target in targets: warning("Skipping recursively symlinked directory %s" % dirname) else: walkdirs.add(current) targets.add(target) for walkdir in walkdirs: for value in os.walk(walkdir): yield value def _fswalk(path, follow_symlinks): ''' Directory tree generator path (str) is the root of the directory tree to walk follow_symlinks (bool) indicates whether to descend into symbolically linked directories ''' if follow_symlinks: return _fswalk_follow_symlinks(path) return os.walk(path) def filter_exclude_include(src_list): info(u"Applying --exclude/--include") cfg = Config() exclude_list = SortedDict(ignore_case = False) for file in src_list.keys(): debug(u"CHECK: %s" % file) excluded = False for r in cfg.exclude: if r.search(file): excluded = True debug(u"EXCL-MATCH: '%s'" % (cfg.debug_exclude[r])) break if excluded: ## No need to check for --include if not excluded for r in cfg.include: if r.search(file): excluded = False debug(u"INCL-MATCH: '%s'" % (cfg.debug_include[r])) break if excluded: ## Still excluded - ok, action it debug(u"EXCLUDE: %s" % file) exclude_list[file] = src_list[file] del(src_list[file]) continue else: debug(u"PASS: %s" % (file)) return src_list, exclude_list def fetch_local_list(args, recursive = None): def _get_filelist_local(local_uri): info(u"Compiling list of local files...") if local_uri.isdir(): local_base = deunicodise(local_uri.basename()) local_path = deunicodise(local_uri.path()) filelist = _fswalk(local_path, cfg.follow_symlinks) single_file = False else: local_base = "" local_path = deunicodise(local_uri.dirname()) filelist = [( local_path, [], [deunicodise(local_uri.basename())] )] single_file = True loc_list = SortedDict(ignore_case = False) for root, dirs, files in filelist: rel_root = root.replace(local_path, local_base, 1) for f in files: full_name = os.path.join(root, f) if not os.path.isfile(full_name): continue if os.path.islink(full_name): if not cfg.follow_symlinks: continue relative_file = unicodise(os.path.join(rel_root, f)) if os.path.sep != "/": # Convert non-unix dir separators to '/' relative_file = "/".join(relative_file.split(os.path.sep)) if cfg.urlencoding_mode == "normal": relative_file = replace_nonprintables(relative_file) if relative_file.startswith('./'): relative_file = relative_file[2:] sr = os.stat_result(os.lstat(full_name)) loc_list[relative_file] = { 'full_name_unicode' : unicodise(full_name), 'full_name' : full_name, 'size' : sr.st_size, 'mtime' : sr.st_mtime, ## TODO: Possibly more to save here... } return loc_list, single_file cfg = Config() local_uris = [] local_list = SortedDict(ignore_case = False) single_file = False if type(args) not in (list, tuple): args = [args] if recursive == None: recursive = cfg.recursive for arg in args: uri = S3Uri(arg) if not uri.type == 'file': raise ParameterError("Expecting filename or directory instead of: %s" % arg) if uri.isdir() and not recursive: raise ParameterError("Use --recursive to upload a directory: %s" % arg) local_uris.append(uri) for uri in local_uris: list_for_uri, single_file = _get_filelist_local(uri) local_list.update(list_for_uri) ## Single file is True if and only if the user ## specified one local URI and that URI represents ## a FILE. Ie it is False if the URI was of a DIR ## and that dir contained only one FILE. That's not ## a case of single_file==True. if len(local_list) > 1: single_file = False return local_list, single_file def fetch_remote_list(args, require_attribs = False, recursive = None): def _get_filelist_remote(remote_uri, recursive = True): ## If remote_uri ends with '/' then all remote files will have ## the remote_uri prefix removed in the relative path. ## If, on the other hand, the remote_uri ends with something else ## (probably alphanumeric symbol) we'll use the last path part ## in the relative path. ## ## Complicated, eh? See an example: ## _get_filelist_remote("s3://bckt/abc/def") may yield: ## { 'def/file1.jpg' : {}, 'def/xyz/blah.txt' : {} } ## _get_filelist_remote("s3://bckt/abc/def/") will yield: ## { 'file1.jpg' : {}, 'xyz/blah.txt' : {} } ## Furthermore a prefix-magic can restrict the return list: ## _get_filelist_remote("s3://bckt/abc/def/x") yields: ## { 'xyz/blah.txt' : {} } info(u"Retrieving list of remote files for %s ..." % remote_uri) s3 = S3(Config()) response = s3.bucket_list(remote_uri.bucket(), prefix = remote_uri.object(), recursive = recursive) rem_base_original = rem_base = remote_uri.object() remote_uri_original = remote_uri if rem_base != '' and rem_base[-1] != '/': rem_base = rem_base[:rem_base.rfind('/')+1] remote_uri = S3Uri("s3://%s/%s" % (remote_uri.bucket(), rem_base)) rem_base_len = len(rem_base) rem_list = SortedDict(ignore_case = False) break_now = False for object in response['list']: if object['Key'] == rem_base_original and object['Key'][-1] != os.path.sep: ## We asked for one file and we got that file :-) key = os.path.basename(object['Key']) object_uri_str = remote_uri_original.uri() break_now = True rem_list = {} ## Remove whatever has already been put to rem_list else: key = object['Key'][rem_base_len:] ## Beware - this may be '' if object['Key']==rem_base !! object_uri_str = remote_uri.uri() + key rem_list[key] = { 'size' : int(object['Size']), 'timestamp' : dateS3toUnix(object['LastModified']), ## Sadly it's upload time, not our lastmod time :-( 'md5' : object['ETag'][1:-1], 'object_key' : object['Key'], 'object_uri_str' : object_uri_str, 'base_uri' : remote_uri, } if break_now: break return rem_list cfg = Config() remote_uris = [] remote_list = SortedDict(ignore_case = False) if type(args) not in (list, tuple): args = [args] if recursive == None: recursive = cfg.recursive for arg in args: uri = S3Uri(arg) if not uri.type == 's3': raise ParameterError("Expecting S3 URI instead of '%s'" % arg) remote_uris.append(uri) if recursive: for uri in remote_uris: objectlist = _get_filelist_remote(uri) for key in objectlist: remote_list[key] = objectlist[key] else: for uri in remote_uris: uri_str = str(uri) ## Wildcards used in remote URI? ## If yes we'll need a bucket listing... if uri_str.find('*') > -1 or uri_str.find('?') > -1: first_wildcard = uri_str.find('*') first_questionmark = uri_str.find('?') if first_questionmark > -1 and first_questionmark < first_wildcard: first_wildcard = first_questionmark prefix = uri_str[:first_wildcard] rest = uri_str[first_wildcard+1:] ## Only request recursive listing if the 'rest' of the URI, ## i.e. the part after first wildcard, contains '/' need_recursion = rest.find('/') > -1 objectlist = _get_filelist_remote(S3Uri(prefix), recursive = need_recursion) for key in objectlist: ## Check whether the 'key' matches the requested wildcards if glob.fnmatch.fnmatch(objectlist[key]['object_uri_str'], uri_str): remote_list[key] = objectlist[key] else: ## No wildcards - simply append the given URI to the list key = os.path.basename(uri.object()) if not key: raise ParameterError(u"Expecting S3 URI with a filename or --recursive: %s" % uri.uri()) remote_item = { 'base_uri': uri, 'object_uri_str': unicode(uri), 'object_key': uri.object() } if require_attribs: response = S3(cfg).object_info(uri) remote_item.update({ 'size': int(response['headers']['content-length']), 'md5': response['headers']['etag'].strip('"\''), 'timestamp' : dateRFC822toUnix(response['headers']['date']) }) remote_list[key] = remote_item return remote_list def compare_filelists(src_list, dst_list, src_remote, dst_remote): def __direction_str(is_remote): return is_remote and "remote" or "local" # We don't support local->local sync, use 'rsync' or something like that instead ;-) assert(not(src_remote == False and dst_remote == False)) info(u"Verifying attributes...") cfg = Config() exists_list = SortedDict(ignore_case = False) debug("Comparing filelists (direction: %s -> %s)" % (__direction_str(src_remote), __direction_str(dst_remote))) debug("src_list.keys: %s" % src_list.keys()) debug("dst_list.keys: %s" % dst_list.keys()) for file in src_list.keys(): debug(u"CHECK: %s" % file) if dst_list.has_key(file): ## Was --skip-existing requested? if cfg.skip_existing: debug(u"IGNR: %s (used --skip-existing)" % (file)) exists_list[file] = src_list[file] del(src_list[file]) ## Remove from destination-list, all that is left there will be deleted del(dst_list[file]) continue attribs_match = True ## Check size first if 'size' in cfg.sync_checks and dst_list[file]['size'] != src_list[file]['size']: debug(u"XFER: %s (size mismatch: src=%s dst=%s)" % (file, src_list[file]['size'], dst_list[file]['size'])) attribs_match = False ## Check MD5 compare_md5 = 'md5' in cfg.sync_checks # Multipart-uploaded files don't have a valid MD5 sum - it ends with "...-NN" if compare_md5 and (src_remote == True and src_list[file]['md5'].find("-") >= 0) or (dst_remote == True and dst_list[file]['md5'].find("-") >= 0): compare_md5 = False info(u"Disabled MD5 check for %s" % file) if attribs_match and compare_md5: try: if src_remote == False and dst_remote == True: src_md5 = hash_file_md5(src_list[file]['full_name']) dst_md5 = dst_list[file]['md5'] elif src_remote == True and dst_remote == False: src_md5 = src_list[file]['md5'] dst_md5 = hash_file_md5(dst_list[file]['full_name']) elif src_remote == True and dst_remote == True: src_md5 = src_list[file]['md5'] dst_md5 = dst_list[file]['md5'] except (IOError,OSError), e: # MD5 sum verification failed - ignore that file altogether debug(u"IGNR: %s (disappeared)" % (file)) warning(u"%s: file disappeared, ignoring." % (file)) del(src_list[file]) del(dst_list[file]) continue if src_md5 != dst_md5: ## Checksums are different. attribs_match = False debug(u"XFER: %s (md5 mismatch: src=%s dst=%s)" % (file, src_md5, dst_md5)) if attribs_match: ## Remove from source-list, all that is left there will be transferred debug(u"IGNR: %s (transfer not needed)" % file) exists_list[file] = src_list[file] del(src_list[file]) ## Remove from destination-list, all that is left there will be deleted del(dst_list[file]) return src_list, dst_list, exists_list # vim:et:ts=4:sts=4:ai
42.49711
158
0.549034
1a20d0320eb0a5c753e94c1196b186080e2a3f83
470
kt
Kotlin
app/src/main/java/danggai/app/parcelwhere/data/rxbus/RxBusMainSelectAll.kt
danggai/FindMyPackage
b05daaab95c0293c4d3e386b85f7f6fe646f69ec
[ "Unlicense" ]
null
null
null
app/src/main/java/danggai/app/parcelwhere/data/rxbus/RxBusMainSelectAll.kt
danggai/FindMyPackage
b05daaab95c0293c4d3e386b85f7f6fe646f69ec
[ "Unlicense" ]
1
2021-08-31T00:58:53.000Z
2021-09-09T00:38:40.000Z
app/src/main/java/danggai/app/parcelwhere/data/rxbus/RxBusMainSelectAll.kt
danggai/FindMyPackage
b05daaab95c0293c4d3e386b85f7f6fe646f69ec
[ "Unlicense" ]
null
null
null
package danggai.app.parcelwhere.data.rxbus import io.reactivex.subjects.PublishSubject class RxBusMainSelectAll{ companion object { private var busSubject : PublishSubject<Boolean>? = null fun getSubject():PublishSubject<Boolean>?{ if(busSubject == null){ busSubject = PublishSubject.create() } return busSubject } fun release(){ busSubject = null } } }
22.380952
64
0.593617
c67b04ea07e36bb365d41a0de1a38cde1545aee0
1,947
rb
Ruby
model/credit_card.rb
cyhsutw-courses/service-security_credit-card-api-service
4d18ccb8795e65d6eac1211dd9031808fb583955
[ "MIT" ]
null
null
null
model/credit_card.rb
cyhsutw-courses/service-security_credit-card-api-service
4d18ccb8795e65d6eac1211dd9031808fb583955
[ "MIT" ]
null
null
null
model/credit_card.rb
cyhsutw-courses/service-security_credit-card-api-service
4d18ccb8795e65d6eac1211dd9031808fb583955
[ "MIT" ]
null
null
null
require 'json' require 'base64' require 'openssl' require 'sinatra/activerecord' require 'rbnacl/libsodium' require_relative '../environments.rb' require_relative '../lib/luhn_validator.rb' # Credit card entity class CreditCard < ActiveRecord::Base # Mixin the validator include LuhnValidator # instance variables with automatic getter/setter methods # attr_accessor :number, :expiration_date, :owner, :credit_network # # def initialize(number, expiration_date, owner, credit_network) # @number = number # @expiration_date = expiration_date # @owner = owner # @credit_network = credit_network # end # return a hash of the serialized credit card object def to_hash { number: number, expiration_date: expiration_date, owner: owner, credit_network: credit_network } end # returns json string def to_json to_hash.to_json end # returns all card information as single string def to_s to_json end # return a new CreditCard object given a serialized (JSON) representation def self.from_s(card_s) card = JSON.parse(card_s) CreditCard.new(card['number'], card['expiration_date'], card['owner'], card['credit_network']) end # return a cryptographically secure hash def hash_secure OpenSSL::Digest::SHA256.new.digest(to_json).unpack('H*').first end def secret_box @secret_box ||= RbNaCl::SecretBox.new(Base64.urlsafe_decode64(ENV['DB_KEY'])) end # number getter def number nonce_bytes = Base64.urlsafe_decode64(nonce) encrypted_number_bytes = Base64.urlsafe_decode64(encrypted_number) secret_box.decrypt(nonce_bytes, encrypted_number_bytes) end # number setter def number=(plain) nonce = RbNaCl::Random.random_bytes(secret_box.nonce_bytes) self.nonce = Base64.urlsafe_encode64(nonce) self.encrypted_number = Base64.urlsafe_encode64(secret_box.encrypt(nonce, plain)) end end
26.310811
85
0.724191
33bc39fa6225ca14386f2ba39fed4c150cb942f4
318
c
C
labs/4-uart/uart-tests/2hello-once.c
aym-v/cs140e-21spr
cb8460f5e4517ed03d47db40f81dd25470e1dab6
[ "MIT" ]
23
2022-01-05T00:06:04.000Z
2022-03-29T06:14:31.000Z
labs/4-uart/uart-tests/2hello-once.c
aym-v/cs140e-21spr
cb8460f5e4517ed03d47db40f81dd25470e1dab6
[ "MIT" ]
null
null
null
labs/4-uart/uart-tests/2hello-once.c
aym-v/cs140e-21spr
cb8460f5e4517ed03d47db40f81dd25470e1dab6
[ "MIT" ]
16
2021-03-31T06:30:25.000Z
2021-12-08T23:06:35.000Z
// print a single hello world and do a clean reboot. this will only // work with the bootloader. clean_reboot will cause my-install to // exit. you should be able to run this over and over from the // command line. #include "rpi.h" void notmain(void) { uart_init(); printk("hello world\n"); clean_reboot(); }
26.5
69
0.707547
ba707fa5d726343e57612d3c1f75cf6324775947
12,061
lua
Lua
ingredient_server.lua
Arc13/OC-BrewingManager
770d5192c87d5433fb08e012f3e92353f63e5a8c
[ "MIT" ]
1
2020-02-23T20:10:34.000Z
2020-02-23T20:10:34.000Z
ingredient_server.lua
Arc13/OC-BrewingManager
770d5192c87d5433fb08e012f3e92353f63e5a8c
[ "MIT" ]
null
null
null
ingredient_server.lua
Arc13/OC-BrewingManager
770d5192c87d5433fb08e012f3e92353f63e5a8c
[ "MIT" ]
null
null
null
local bRun = true local tQueue = {} local tPotions = {["night_vision"] = "minecraft:golden_carrot", ["invisibility"] = {"minecraft:golden_carrot", "minecraft:fermented_spider_eye"}, ["fire_resistance"] = "minecraft:magma_cream", ["leaping"] = "minecraft:rabbit_foot", ["slowness"] = {{"minecraft:rabbit_foot", "minecraft:fermented_spider_eye"}, {"minecraft:sugar", "minecraft:fermented_spider_eye"}}, ["swiftness"] = "minecraft:sugar", ["water_breathing"] = "minecraft:fish", ["healing"] = "minecraft:speckled_melon", ["harming"] = {{"minecraft:speckled_melon", "minecraft:fermented_spider_eye"}, {"minecraft:spider_eye", "minecraft:fermented_spider_eye"}}, ["poison"] = "minecraft:spider_eye", ["regeneration"] = "minecraft:ghast_tear", ["strength"] = "minecraft:blaze_powder", ["weakness"] = "minecraft:fermented_spider_eye"} local nState = 0 local tMissingComponents = {} --[[ States: 0 = idle 1 = brewing 2 = missing ingredient 3 = querying brewing stand status 4 = missing brewing stand component 5 = potion has finished ]] local component = require("component") local event = require("event") local sides = require("sides") local table = require("table") local serialization = require("serialization") local net_card = component.modem local inv_controller = component.inventory_controller local robot = component.robot net_card.open(4000) local function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end local function drop(slot, side) robot.select(slot) local containerSize = inv_controller.getInventorySize(side) local itemToDrop = inv_controller.getStackInInternalSlot(slot) local tEmptySlots = {} for i = 1, containerSize do local currentSlot = inv_controller.getStackInSlot(side, i) if currentSlot and currentSlot.name == itemToDrop.name then if currentSlot.size < currentSlot.maxSize then inv_controller.dropIntoSlot(side, i) itemToDrop = inv_controller.getStackInInternalSlot(slot) if not itemToDrop then break end end elseif not currentSlot then table.insert(tEmptySlots, i) end end itemToDrop = inv_controller.getStackInInternalSlot(slot) if itemToDrop then if #tEmptySlots > 0 then inv_controller.dropIntoSlot(side, tEmptySlots[1]) else return false end end robot.select(1) return true end local function findPosition() for i = 1, 4 do local _, blockType = robot.detect(sides.front) if blockType == "liquid" then robot.turn(false) break end robot.turn(true) end end local function clearInventory() local tIngredients = {} local tJunk = {} for i = 1, robot.inventorySize() do local item = inv_controller.getStackInInternalSlot(i) if item then if item.name == "minecraft:nether_wart" or item.name == "minecraft:gunpowder" or item.name == "minecraft:spider_eye" or item.name == "minecraft:blaze_powder" or item.name == "minecraft:ghast_tear" or item.name == "minecraft:redstone" or item.name == "minecraft:speckled_melon" or item.name == "minecraft:rabbit_foot" or item.name == "minecraft:sugar" or item.name == "minecraft:magma_cream" or item.name == "minecraft:glowstone" or item.name == "minecraft:fermented_spider_eye" then table.insert(tIngredients, i) else table.insert(tJunk, i) end end end if #tIngredients > 0 then for i = 1, #tIngredients do drop(tIngredients[i], sides.front) end end if #tJunk > 0 then robot.turn(true) for i = 1, #tJunk do drop(tJunk[i], sides.front) end robot.turn(true) end end local function clearSlot() if inv_controller.getStackInSlot(sides.bottom, 1) then inv_controller.suckFromSlot(sides.bottom, 1) local selectedItem = inv_controller.getStackInInternalSlot() local chestSize = inv_controller.getInventorySize(sides.front) print(chestSize) local tEmptySlots = {} local hasEmptiedSlot = false for i = 1, chestSize do local currentSlot = component.inventory_controller.getStackInSlot(sides.front, i) if not currentSlot then tEmptySlots.insert(i) elseif currentSlot.name == selectedItem.name then if currentSlot.size < currentSlot.maxSize then inv_controller.dropIntoSlot(sides.front, i, selectedItem.size) hasEmptiedSlot = true break end end end if not hasEmptiedSlot then inv_controller.dropIntoSlot(sides.front, tEmptySlots[1], selectedItem.size) end end end local function isIngredientPresent(ingredient) local chestSize = inv_controller.getInventorySize(sides.front) for i = 1, chestSize do local currentSlot = inv_controller.getStackInSlot(sides.front, i) if currentSlot and currentSlot.name == ingredient then return true, i end end return false end local function putIngredient(ingredient) local success, slot = isIngredientPresent(ingredient) if success then inv_controller.suckFromSlot(sides.front, slot, 1) inv_controller.dropIntoSlot(sides.bottom, 1, 1) end return success end local function modemMessageHandler(_, local_address, remote_address, port, distance, ...) local msg = {...} if msg[1] == "addPotion" then local potion = msg[2] local modifier = msg[3] local qty = msg[4] modifier = tonumber(modifier) qty = tonumber(qty) print("Received addPotion") if not modifier then modifier = 0 end if not qty then qty = 1 end if tPotions[potion] then local ingredients = tPotions[potion] local tPotion = {} if (potion) ~= "weakness" then table.insert(tPotion, "minecraft:nether_wart") end if type(ingredients) == "string" then -- Only one ingredient print("only one ingredient") table.insert(tPotion, ingredients) elseif type(ingredients) == "table" then -- 2+ ingredients if type(ingredients[1]) == "string" and type(ingredients[2]) == "string" then table.insert(tPotion, ingredients[1]) table.insert(tPotion, ingredients[2]) elseif type(ingredients[1]) == "table" and type(ingredients[2]) == "table" then local firstSet = ingredients[1] local secondSet = ingredients[2] if isIngredientPresent(firstSet[1]) then table.insert(tPotion, firstSet[1]) elseif isIngredientPresent(secondSet[1]) then table.insert(tPotion, secondSet[1]) else table.insert(tPotion, {firstSet[1], secondSet[1]}) end table.insert(tPotion, firstSet[2]) end end local hasGlowstone = bit32.band(modifier, 1) ~= 0 local hasRedstone = bit32.band(modifier, 2) ~= 0 local hasSplash = bit32.band(modifier, 4) ~= 0 local hasLingering = bit32.band(modifier, 8) ~= 0 local flagStr = "Flags: " if hasGlowstone then flagStr = flagStr.."G" table.insert(tPotion, "minecraft:glowstone") end if hasRedstone and not hasGlowstone then flagStr = flagStr.."R" table.insert(tPotion, "minecraft:redstone") end if hasSplash and not hasLingering then flagStr = flagStr.."S" table.insert(tPotion, "minecraft:gunpowder") end if hasLingering then flagStr = flagStr.."L" table.insert(tPotion, "minecraft:gunpowder") table.insert(tPotion, "minecraft:dragon_breath") end print(flagStr) table.insert(tQueue, {["ingredients"] = tPotion, ["ingredientsLeft"] = deepcopy(tPotion), ["name"] = potion, ["isReady"] = false, ["quantity"] = qty}) end elseif msg[1] == "getState" then local tData = {} if nState == 4 then tData = tMissingComponents end net_card.broadcast(4000, "updateState", serialization.serialize(tQueue), nState, serialization.serialize(tData)) elseif msg[1] == "removePotion" then local potionToRemove = tonumber(msg[2]) if potionToRemove and tQueue[potionToRemove] then table.remove(tQueue, potionToRemove) net_card.broadcast(4000, "potionRemoved", potionToRemove) end elseif msg[1] == "verification" then print("Verification received") if nState == 3 or nState == 4 then local tPotionToDo = tQueue[1] if tPotionToDo and not tPotionToDo["ready"] then if msg[2] and msg[3] then tPotionToDo["ready"] = true nState = 1 else nState = 4 tMissingComponents = {msg[2], msg[3]} end end end else print(msg[1]) end end local function keyDownHandler(_, keyboard_address, char, code, playerName) if char == 99 then event.ignore("modem_message", modemMessageHandler) event.ignore("key_down", keyDownHandler) net_card.close(4000) print("Exiting the program") bRun = false end end event.listen("modem_message", modemMessageHandler) event.listen("key_down", keyDownHandler) findPosition() clearInventory() print("Ready!") while bRun do if #tQueue > 0 then if not inv_controller.getStackInSlot(sides.bottom, 1) then while true do local tPotionToDo = tQueue[1] print("Current state: "..nState) if not tPotionToDo then nState = 0 break end if nState == 3 or nState == 4 then break end if #tPotionToDo["ingredientsLeft"] == 0 and tPotionToDo["quantity"] == 1 then table.remove(tQueue, 1) net_card.broadcast(4000, "potionFinished") nState = 5 print("Finished!") else if #tPotionToDo["ingredientsLeft"] == 0 and tPotionToDo["quantity"] > 1 then tPotionToDo["quantity"] = tPotionToDo["quantity"] - 1 tPotionToDo["ingredientsLeft"] = deepcopy(tPotionToDo["ingredients"]) tPotionToDo["ready"] = false net_card.broadcast(4000, "notifyQuantityDecreased") nState = 5 end if not tPotionToDo["isReady"] and (nState == 5 or nState == 0) then net_card.broadcast(4000, "wantsVerification") nState = 3 break end local currentIngredient = tPotionToDo["ingredientsLeft"][1] if type(currentIngredient) == "string" then if (putIngredient(currentIngredient)) then net_card.broadcast(4000, "notifyIngredient") nState = 1 table.remove(tQueue[1]["ingredientsLeft"], 1) else if nState ~= 2 then nState = 2 print("Missing ingredient: "..currentIngredient) net_card.broadcast(4000, "notifyMissingIngredient") end end elseif type(currentIngredient) == "table" then local ingredientToUse local ingredientsStr = currentIngredient[1] for i = 1, #currentIngredient do if i > 1 then ingredientsStr = ingredientsStr.." or "..currentIngredient[i] end if isIngredientPresent(currentIngredient[i]) then ingredientToUse = currentIngredient[i] end end if ingredientToUse and string.len(ingredientToUse) > 0 then putIngredient(ingredientToUse) net_card.broadcast(4000, "notifyIngredient") nState = 1 table.remove(tQueue[1]["ingredientsLeft"], 1) else if nState ~= 2 then nState = 2 print("Missing ingredients: "..ingredientsStr) net_card.broadcast(4000, "notifyMissingIngredient") end end end break end end end end os.sleep(1) end
30.611675
791
0.647625
980a1c56d638d6420d167e7fa8190d3d53719714
5,595
py
Python
asdfc/wrappers.py
surchs/ASD_subtype_code_supplement
8ed67ada3cdceb2a45b53e5d69b2a0a8cd6035f1
[ "CC-BY-4.0" ]
1
2020-04-09T01:26:07.000Z
2020-04-09T01:26:07.000Z
asdfc/wrappers.py
surchs/ASD_subtype_code_supplement
8ed67ada3cdceb2a45b53e5d69b2a0a8cd6035f1
[ "CC-BY-4.0" ]
null
null
null
asdfc/wrappers.py
surchs/ASD_subtype_code_supplement
8ed67ada3cdceb2a45b53e5d69b2a0a8cd6035f1
[ "CC-BY-4.0" ]
null
null
null
import functools import numpy as np import nibabel as nib import pathlib as pal from .stats import seed_correlation, \ subtype_partition, subtype_maps, subtype_weights, \ compute_icc def unpacker(func): # Wrapper used to turn argument functions into parallelizable functions that accept just one argument @functools.wraps(func) def wrapper_unpacker(arg_dict): return func(**arg_dict) return wrapper_unpacker def wrap_seed_based_correlation(func_in_p, sca_out_p, atlas_img, mask_img, confound_img=None, clobber=False): """ :param func_in_p: path to scrubbed functional time series :param sca_out_p: pathlib path to .npy file that will contain the seed maps :param atlas_img: nibabel image of atlas partition :param mask_img: nibabel image of atlas mask :param confound_img: nibabel image of confounds to be regressed. Uses partial seed correlation. None if none are to be regressed :param clobber: if True, overwrite. Otherwise stop if output exists :return: """ if not issubclass(type(sca_out_p), pal.Path): sca_out_p = pal.Path(sca_out_p) if sca_out_p.is_file() and not clobber: raise Exception(f'Designated output file exists. Set clobber=True to overwrite:\n{sca_out_p}') func_i = nib.load(str(func_in_p)) seed_map_fisher_z = seed_correlation(func_i, atlas_img, mask_img) np.save(str(sca_out_p), seed_map_fisher_z) return sca_out_p.is_file() def wrap_weight_stability(data_stack, sbt_ids, icc_ids, mode='classic', n_subtypes=3, dist_thr=0.7, part_thr=20): """ type: (np.ndarray, tuple, tuple, str, int, float, int) -> np.ndarray :param data_stack: numpy.ndarray of 4D :param sbt_ids: tuple with integer indices of the session to be used to generate subtypes :param icc_ids: tuple with integer indices of the sessions used to compute ICC on weights :param mode: str. Can be 'classic' for fixed subtypes or 'core' for data dependent subtypes based on thresholds :param n_subtypes: (only in 'classic' mode) :param dist_thr: (only in 'core' mode) float. maximum distance of subjects in a subtype :param part_thr: (only in 'core' mode) int, minimum number of subjects that need to be in a valid subtype :return: """ if not data_stack.ndim == 4: raise Exception(f'Data Stack must be 4D array but has shape {data_stack.shape} ({data_stack.ndim} D)') scale = data_stack.shape[2] n_icc = len(icc_ids) # Average the sessions used to make subtypes sbt_stack = np.mean(data_stack[..., sbt_ids], -1) # Slice the sessions used for the weights icc_stack = data_stack[..., icc_ids] # Transitioned this to thresholded subtype mode partition, distance, _ = subtype_partition(sbt_stack, mode=mode, n_subtypes=n_subtypes, dist_thr=dist_thr, part_thr=part_thr) subtypes = subtype_maps(sbt_stack, partition) weight_list = [subtype_weights(icc_stack[..., w_id], subtypes) for w_id in range(n_icc)] # The weight list is ordered: [ sessions [ seeds (subjects, subtype) ] ] with the tuple being the weights # Because the number of subtypes can differ between seeds, we cannot store this as an array # Instead we unpack the list. One advantage here is that the number of subtypes is the same for all the icc session # for which we extract the weights. So we can just pick one of the icc sessions and check the shape of the weights. # Then we iterate over the number of subtypes we found to get an intermediate list if subtypes with each element # having the shape of (n_subject, n_session) ]. Then we end up with a (n_subtype, 3 - for the 3 returns) array # which we average across subtypes to receive a 3-tuple of (icc, wms, bms). We iterate over seeds and stack those # tuples up which means that at the end we arrive at a (n_seeds, 3) array. This wouldn't really work without # averaging across subtypes. results = np.array([np.mean(np.stack([compute_icc(np.stack([weight_list[ses][seed][:, sbt] for ses in range(n_icc)], -1).T, 1, 'single') for sbt in range(weight_list[0][seed].shape[1])], axis=-1), axis=1) for seed in range(scale)]) n_sbt = list() avg_size_sbt = list() min_size_sbt = list() n_in_sbt = list() n_out_sbt = list() for seed_id in range(scale): n_sbt.append(np.max(partition[:, seed_id])) n_in_sbt.append(np.sum(partition[:, seed_id] != 0)) n_out_sbt.append(np.sum(partition[:, seed_id] == 0)) if np.max(partition[:, seed_id]) == 0: avg_size_sbt.append(0) min_size_sbt.append(0) else: avgsz = np.mean([np.sum(partition[:, seed_id] == part_id) for part_id in np.unique(partition[:, seed_id]) if not part_id == 0]) minsz = np.min([np.sum(partition[:, seed_id] == part_id) for part_id in np.unique(partition[:, seed_id]) if not part_id == 0]) avg_size_sbt.append(avgsz) min_size_sbt.append(minsz) sbt_info = np.stack([n_sbt, n_in_sbt, n_out_sbt, avg_size_sbt, min_size_sbt], -1) res_array = np.concatenate([results, sbt_info], 1) # The res_array has the dimensions (n_seeds, 8. With the following order # icc, wms, bms, n_sbt, n_subjects_in_subtypes, n_subjects_outside_subtypes, avg_subtype_size, min_subtype_size return res_array
52.783019
119
0.675067
df148221f764e677248703f2bf93143da8f57e9a
1,519
rb
Ruby
yaks/lib/yaks.rb
carlesjove/yaks
0bea2fbd398e02109a62bf1d988a7f91a358489a
[ "MIT" ]
null
null
null
yaks/lib/yaks.rb
carlesjove/yaks
0bea2fbd398e02109a62bf1d988a7f91a358489a
[ "MIT" ]
null
null
null
yaks/lib/yaks.rb
carlesjove/yaks
0bea2fbd398e02109a62bf1d988a7f91a358489a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- require 'forwardable' require 'set' require 'pathname' require 'json' require 'anima' require 'concord' require 'inflection' require 'uri_template' require 'rack/accept' require 'yaks/version' require 'yaks/util' require 'yaks/configurable' require 'yaks/fp' require 'yaks/fp/callable' require 'yaks/primitivize' require 'yaks/attributes' require 'yaks/stateful_builder' require 'yaks/errors' require 'yaks/default_policy' module Yaks Undefined = Module.new.freeze # Set the Root constant as the gems root path Root = Pathname(__FILE__).join('../..') class << self # @param [Proc] blk # @return [Yaks::Config] def new(&blk) Yaks::Config.new(&blk) end end end require 'yaks/resource' require 'yaks/null_resource' require 'yaks/resource/link' require 'yaks/collection_resource' require 'yaks/html5_forms' require 'yaks/mapper/association' require 'yaks/mapper/has_one' require 'yaks/mapper/has_many' require 'yaks/mapper/attribute' require 'yaks/mapper/link' require 'yaks/mapper/form' require 'yaks/mapper/form/field' require 'yaks/mapper/config' require 'yaks/mapper/class_methods' require 'yaks/mapper' require 'yaks/mapper/association_mapper' require 'yaks/collection_mapper' require 'yaks/resource/form' require 'yaks/serializer' require 'yaks/format' require 'yaks/format/hal' require 'yaks/format/halo' require 'yaks/format/json_api' require 'yaks/format/collection_json' require 'yaks/config/dsl' require 'yaks/config' require 'yaks/runner'
19.986842
47
0.753127
de798fcea879311b7f6b0e5c296c8f0b4f49860a
1,918
lua
Lua
nodetimer.lua
SwissalpS/mineunit
2d37a446cb9aab5342b8a800c3ff6a838332e7eb
[ "MIT" ]
2
2022-02-06T17:23:20.000Z
2022-03-22T14:40:57.000Z
nodetimer.lua
SwissalpS/mineunit
2d37a446cb9aab5342b8a800c3ff6a838332e7eb
[ "MIT" ]
27
2021-10-21T22:20:18.000Z
2022-03-31T14:50:52.000Z
nodetimer.lua
SwissalpS/mineunit
2d37a446cb9aab5342b8a800c3ff6a838332e7eb
[ "MIT" ]
2
2022-02-09T10:02:24.000Z
2022-03-19T22:19:06.000Z
local NodeTimerRef = {} -- -- NodeTimerRef Mineunit execution API -- function NodeTimerRef:_step(dtime, pos) if self:is_started() then self._elapsed = self._elapsed + (dtime or 0.1) if pos then self:_execute(pos) end end end function NodeTimerRef:_execute(pos) local elapsed = self:get_elapsed() local timeout = self:get_timeout() local dtime = elapsed - timeout if self:is_started() and dtime >= 0 then local on_timer = core.registered_nodes[core.get_node(pos).name].on_timer local result = on_timer(pos, dtime) if result == true then self:start(timeout) else -- TODO: Check if trashing data is expected behavior or should timer be stopped without trashing data self:stop() end end end -- -- NodeTimerRef public API -- -- set a timer's state -- `timeout` is in seconds, and supports fractional values (0.1 etc) -- `elapsed` is in seconds, and supports fractional values (0.1 etc) -- will trigger the node's `on_timer` function after `(timeout - elapsed)` seconds. function NodeTimerRef:set(timeout,elapsed) self._timeout = timeout self._elapsed = elapsed end -- start a timer, equivalent to `set(timeout,0)` function NodeTimerRef:start(timeout) self._timeout = timeout self._elapsed = 0 end -- stops the timer function NodeTimerRef:stop() self._timeout = 0 self._elapsed = 0 end -- if `timeout` equals `0`, timer is inactive function NodeTimerRef:get_timeout() return self._timeout end -- the node's `on_timer` function will be called after `(timeout - elapsed)` seconds. function NodeTimerRef:get_elapsed() return self._elapsed end -- returns `true` if timer is started, otherwise `false` function NodeTimerRef:is_started() return self:get_timeout() > 0 end mineunit.export_object(NodeTimerRef, { name = "NodeTimerRef", constructor = function(self) local obj = { _timeout = 0, _elapsed = 0, } setmetatable(obj, NodeTimerRef) return obj end, })
23.108434
104
0.729927
c9af10bd9ecc2448b0d32424736622b3853d215a
1,306
ts
TypeScript
packages/genesys-web-messaging-tester/__tests__/fixtures/webMessagePayloads.ts
ovotech/genesys-web-messaging-tester
481c7b8c22e4eedcfd4ff57de3e249ac0a1f25c2
[ "Apache-2.0" ]
5
2022-03-17T09:18:23.000Z
2022-03-30T20:07:41.000Z
packages/genesys-web-messaging-tester/__tests__/fixtures/webMessagePayloads.ts
ovotech/genesys-web-messaging-tester
481c7b8c22e4eedcfd4ff57de3e249ac0a1f25c2
[ "Apache-2.0" ]
null
null
null
packages/genesys-web-messaging-tester/__tests__/fixtures/webMessagePayloads.ts
ovotech/genesys-web-messaging-tester
481c7b8c22e4eedcfd4ff57de3e249ac0a1f25c2
[ "Apache-2.0" ]
null
null
null
import { StructuredMessage, SessionResponse } from '../../src'; /** * Payloads taken from real interactions */ export const webMessagePayloads = { sessionResponse: (): SessionResponse => ({ type: 'response', class: 'SessionResponse', code: 200, body: { connected: true, newSession: true }, }), inboundStructuredMessage: (text: string, date: Date): StructuredMessage => ({ type: 'message', class: 'StructuredMessage', code: 200, body: { originatingEntity: '', text, direction: 'Inbound', id: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', channel: { time: date.toISOString(), messageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', }, type: 'Text', metadata: { correlationId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', }, }, }), outboundStructuredMessage: (text: string, date: Date): StructuredMessage => ({ type: 'message', class: 'StructuredMessage', code: 200, body: { text, direction: 'Outbound', id: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', channel: { time: date.toISOString(), type: 'Private' }, type: 'Text', originatingEntity: 'Bot', metadata: { correlationId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', }, }, }), };
26.653061
80
0.601838