identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/kuangyh/saw/blob/master/storage/textio.go
Github Open Source
Open Source
MIT
null
saw
kuangyh
Go
Code
204
585
package storage import ( "bufio" "io" "strconv" "github.com/kuangyh/saw" "golang.org/x/net/context" ) // Format: textio // Reads and writes data line by line. datum.Key is ignored. type TextFormat struct { } func (tf TextFormat) DatumReader( ctx context.Context, rc ResourceSpec, shard int) (DatumReader, error) { f, err := rc.IOReader(ctx, shard) if err != nil { return nil, err } return &textDatumReader{ key: saw.DatumKey(strconv.Itoa(shard)), internal: f, reader: bufio.NewReader(f), }, nil } func (tf TextFormat) DatumWriter( ctx context.Context, rc ResourceSpec, shard int) (DatumWriter, error) { f, err := rc.IOWriter(ctx, shard) if err != nil { return nil, err } // TODO: check media and decide whether to buffer write, maybe for GCS, don't // need yet another buffer. return &textDatumWriter{internal: f, writer: bufio.NewWriter(f)}, nil } type textDatumReader struct { key saw.DatumKey internal io.ReadCloser reader *bufio.Reader } func (dr *textDatumReader) ReadDatum() (datum saw.Datum, err error) { datum.Key = dr.key datum.Value, err = dr.reader.ReadBytes('\n') return } func (dr *textDatumReader) Close() error { return dr.internal.Close() } type textDatumWriter struct { internal io.WriteCloser writer *bufio.Writer } func (dw *textDatumWriter) WriteDatum(datum saw.Datum) error { if _, err := dw.writer.Write(datum.Value.([]byte)); err != nil { return err } return dw.writer.WriteByte('\n') } func (dw *textDatumWriter) Close() error { return dw.internal.Close() } func init() { RegisterStorageFormat("textio", TextFormat{}) }
26,479
https://github.com/einarssons/adventofcode2020/blob/master/dec16/m16.py
Github Open Source
Open Source
MIT
null
adventofcode2020
einarssons
Python
Code
294
1,071
from dataclasses import dataclass import re rule_pattern = re.compile(r"([a-z ]+): (\d+)-(\d+) or (\d+)-(\d+)") ticket_pattern = re.compile(r"[0-9,]+$") class TicketInfo: def __init__(self, file_name: str): self.rules = [] self.all_tickets = [] # my ticket is 0 self.columns_mapped = set() self.nr_columns = 0 self.read_data(file_name) def read_data(self, filename: str): with open(filename) as ifh: for line in ifh: line = line.strip() m = rule_pattern.match(line) if m: name = m.group(1) self.rules.append(Rule(name, (int(m.group(2)), int(m.group(3))), (int(m.group(4)), int(m.group(5))), -1)) m = ticket_pattern.match(line) if m: self.all_tickets.append(read_ticket(line)) self.nr_columns = len(self.all_tickets[0]) def get_all_invalid(self): invalid_indices = [] all_invalid = [] for i, ticket in enumerate(self.all_tickets): for nr in ticket: valid = False for rule in self.rules: if rule.is_valid(nr): valid = True break if not valid: all_invalid.append(nr) invalid_indices.append(i) invalid_indices.reverse() print(f"There are {len(invalid_indices)} invalid tickets") for idx in invalid_indices: self.all_tickets.pop(idx) return all_invalid def free_columns(self) -> set(): return set(range(self.nr_columns)).difference(self.columns_mapped) def find_unique_column(self, rule) -> int: possible_columns = set() free_columns = self.free_columns() for column in free_columns: for ticket in self.all_tickets: if not rule.is_valid(ticket[column]): break else: possible_columns.add(column) if len(possible_columns) > 1: return -1 if len(possible_columns) == 0: raise ValueError(f"No column possible for {rule}") return possible_columns.pop() def match_all_columns(self): nr_loops = 0 while len(self.free_columns()) > 0: for rule in self.rules: if rule.pos >= 0: continue uc = self.find_unique_column(rule) if uc >= 0: rule.pos = uc self.columns_mapped.add(uc) nr_loops += 1 if nr_loops % 100 == 0: print(f"Looped {nr_loops} times") def read_ticket(line: str) -> [int]: return [int(x) for x in line.split(",")] @dataclass class Rule: name: str iv1: (int, int) iv2: (int, int) pos: int def is_valid(self, nr: int): return ((self.iv1[0] <= nr <= self.iv1[1]) or (self.iv2[0] <= nr <= self.iv2[1])) def main(): ti = TicketInfo("tickets.txt") invalid = ti.get_all_invalid() print(f"The sum is {sum(invalid)}") ti.match_all_columns() your_ticket = ti.all_tickets[0] prod = 1 for rule in ti.rules: if rule.name.startswith('departure'): prod *= your_ticket[rule.pos] print(f"The departure product is {prod}") if __name__ == "__main__": main()
6,373
https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet/blob/master/src/Microsoft.Graph/Generated/Models/VirtualEventAttendeeRegistrationStatus.cs
Github Open Source
Open Source
MIT
2,023
msgraph-beta-sdk-dotnet
microsoftgraph
C#
Code
39
161
// <auto-generated/> using System.Runtime.Serialization; using System; namespace Microsoft.Graph.Beta.Models { public enum VirtualEventAttendeeRegistrationStatus { [EnumMember(Value = "registered")] Registered, [EnumMember(Value = "canceled")] Canceled, [EnumMember(Value = "waitlisted")] Waitlisted, [EnumMember(Value = "pendingApproval")] PendingApproval, [EnumMember(Value = "rejectedByOrganizer")] RejectedByOrganizer, [EnumMember(Value = "unknownFutureValue")] UnknownFutureValue, } }
50,612
https://github.com/Novartis/peax/blob/master/Dockerfile
Github Open Source
Open Source
Apache-2.0
2,020
peax
Novartis
Dockerfile
Code
146
510
FROM continuumio/miniconda RUN apt-get update && apt-get -y install \ make \ build-essential \ zlib1g-dev \ libbz2-dev \ liblzma-dev \ vim WORKDIR /peax RUN conda install python=3.7 \ cython \ cytoolz \ seaborn \ flask \ flask-cors \ nodejs=10.* \ scikit-learn=0.22.0 \ pandas \ pywget \ bokeh \ pydot \ h5py \ testpath==0.4.2 \ tqdm \ matplotlib \ requests \ statsmodels \ tensorflow \ pip RUN conda install -c bioconda bwa \ samtools \ bedtools \ ucsc-bedtobigbed \ ucsc-fetchchromsizes \ deeptools \ pysam==0.15.3 RUN conda install -c conda-forge umap-learn \ tsfresh \ tslearn RUN pip install apricot-select \ cooler \ higlass-python==0.2.1 \ hnswlib==0.3.4 \ ipywidgets==7.5.1 \ joblib==0.14.0 \ jupyterlab==1.1.1 \ negspy \ numba==0.46.0 \ pybbi \ pytest==5.3.1 \ keras-tqdm \ fastdtw \ stringcase RUN conda install llvmlite==0.32.1 COPY ui ui WORKDIR /peax/ui RUN npm install RUN npm build WORKDIR /peax COPY start.py . COPY server server
32,618
https://github.com/hildamari/Marianne/blob/master/src/commands/Support Server/subscribe.ts
Github Open Source
Open Source
Apache-2.0
2,023
Marianne
hildamari
TypeScript
Code
184
563
import { ApplyOptions } from '@sapphire/decorators'; import { ChatInputCommand, Command } from '@sapphire/framework'; import type { Guild, Role } from 'discord.js'; // import { isMessageInstance } from '@sapphire/discord.js-utilities'; @ApplyOptions<Command.Options>({ name: 'Subscribe', description: 'Gives the "Marianne Subscriber" role to those who want to be notified of new updates' }) export class SubscribeCommand extends Command { // Register slash and context menu command public override registerApplicationCommands( registry: ChatInputCommand.Registry ) { registry.registerChatInputCommand( (builder) => builder .setName(this.name) .setDescription(this.description) .setDMPermission(false), { idHints: ['1014619040603447306'], } ); } public async chatInputRun(interaction: Command.ChatInputInteraction) { if(interaction.guild?.id == '650595160849121300') { const marianneSubscriberRole = interaction.guild?.roles.cache.find(roles => roles.name === "Marianne Subscriber") as Role; // if user has role // if user doesn't have role let guild = this.container.client.guilds.cache.get('907259574342537236') as Guild const member = await guild.members.fetch(interaction.user.id) const role = await guild.roles.fetch(marianneSubscriberRole.id) if(member.roles.cache.has(marianneSubscriberRole.id)) { await interaction.reply({ content: "The `Marianne Subscriber` role has been removed."}) } else { member.roles.add(role as Role) await interaction.reply({ content: "The `Marianne Subscriber` role has been added."}) } } else { await interaction.reply({ content: `You cannot use this command in this server. Please join the support server to obtain this role. https://discord.gg/WAVdN4E`}) } } }
43,837
https://github.com/SantipapP/BikeRental-VB/blob/master/BikeRT-V2/FRM_In.vb
Github Open Source
Open Source
MIT
null
BikeRental-VB
SantipapP
Visual Basic
Code
90
339
Public Class FRM_In Private Sub TBL_InBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TBL_InBindingNavigatorSaveItem.Click Me.Validate() Me.TBL_InBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me._BikeRT_V2DataSet) End Sub Private Sub FRM_In_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'TODO: This line of code loads data into the '_BikeRT_V2DataSet.TBL_Bike' table. You can move, or remove it, as needed. Me.TBL_BikeTableAdapter.Fill(Me._BikeRT_V2DataSet.TBL_Bike) 'TODO: This line of code loads data into the '_BikeRT_V2DataSet.TBL_In' table. You can move, or remove it, as needed. Me.TBL_InTableAdapter.Fill(Me._BikeRT_V2DataSet.TBL_In) End Sub Private Sub BindingNavigatorAddNewItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingNavigatorAddNewItem.Click End Sub End Class
48,341
https://github.com/mullet1989/strava-cups/blob/master/src/config/config.module.ts
Github Open Source
Open Source
MIT
null
strava-cups
mullet1989
TypeScript
Code
66
164
import { Module } from '@nestjs/common'; import { ConfigService } from './config.service'; import { join } from 'path'; import { ConfigProduction } from './config.production'; @Module({ providers: [ { provide: ConfigService, useFactory: () => { let env = process.env.NODE_ENV; if (env === "development") { return new ConfigService(join(__dirname, '../..', `${process.env.NODE_ENV}.env`)) } else { return new ConfigProduction(); } } }, ], exports: [ConfigService], }) export class ConfigModule { }
13,441
https://github.com/MiguelSombrero/bloogie-backend/blob/master/src/main/java/bloogie/backend/handler/PostHandler.java
Github Open Source
Open Source
0BSD
null
bloogie-backend
MiguelSombrero
Java
Code
463
1,358
package bloogie.backend.handler; import bloogie.backend.domain.Post; import bloogie.backend.domain.Views; import bloogie.backend.service.PostService; import bloogie.backend.validator.PostValidator; import org.springframework.beans.factory.annotation.Autowired; import static org.springframework.http.MediaType.APPLICATION_JSON; import org.springframework.http.codec.json.Jackson2CodecSupport; import org.springframework.stereotype.Component; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import static org.springframework.web.reactive.function.server.ServerResponse.noContent; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import static org.springframework.web.reactive.function.server.ServerResponse.status; import org.springframework.web.server.ServerWebInputException; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * Handler class for Post resource. When a user makes an API call to * base path /post, server request is processed in this class. * * @author miika */ @Component public class PostHandler implements ResourceHandler { @Autowired private PostValidator validator; @Autowired private PostService postService; /** * Handler for fetching all posts and returning * them in the body of server response. This handler is activated * with GET request to path /posts. * * @param request Request received from the client * @return Status 200 response with all posts in body */ @Override public Mono<ServerResponse> list(ServerRequest request) { Flux<Post> posts = postService.findAllPosts(); return ok().contentType(APPLICATION_JSON) .hint(Jackson2CodecSupport.JSON_VIEW_HINT, Views.Post.class) .body(posts, Post.class); } /** * Handler for creating a post and returning * it in the body of server response. Handler also validates * the Post object received from the request. This handler * is activated with POST request to path /posts. * * @param request Request received from the client * @return Status 200 response with created post in the body */ @Override public Mono<ServerResponse> create(ServerRequest request) { Mono<Post> post = request.bodyToMono(Post.class).doOnNext(this::validate); return postService.savePost(post) .flatMap(b -> ok().contentType(APPLICATION_JSON) .hint(Jackson2CodecSupport.JSON_VIEW_HINT, Views.Post.class) .bodyValue(b)); } /** * Handler for fetching one post and returning * it in the body of server response. This handler * is activated with GET request to path /posts/{id}. * * @param request Request received from the client * @return Status 200 response with requested blog in the body */ @Override public Mono<ServerResponse> getOne(ServerRequest request) { return postService.findOnePost(request.pathVariable("id")) .flatMap(p -> ok().contentType(APPLICATION_JSON) .hint(Jackson2CodecSupport.JSON_VIEW_HINT, Views.Post.class) .bodyValue(p)) .switchIfEmpty(ServerResponse.notFound().build()); } /** * Handler for updating existing post and returning * it in the body of server response. This handler * is activated with PUT request to path /posts/{id}. * * @param request Request received from the client * @return Status 201 (created) response with updated post in the body */ @Override public Mono<ServerResponse> update(ServerRequest request) { Mono<Post> post = request.bodyToMono(Post.class); return postService.updatePost(post, request.pathVariable("id")) .flatMap(p -> status(201).contentType(APPLICATION_JSON) .hint(Jackson2CodecSupport.JSON_VIEW_HINT, Views.Post.class) .bodyValue(p)); } /** * Handler for deleting post. This handler * is activated with DELETE request to path /posts/{id}. * * @param request Request received from the client * @return Status 204 (no content) response */ @Override public Mono<ServerResponse> delete(ServerRequest request) { return postService.deletePost(request.pathVariable("id")) .flatMap(p -> noContent().build()); } /** * Validates a Post received from the server request. If there * is a validation errors, throws new ServerWebInputException. * * @param post Post to validate */ private void validate(Post post) { Errors errors = new BeanPropertyBindingResult(post, "post"); validator.validate(post, errors); if (errors.hasErrors()) { throw new ServerWebInputException(errors.toString()); } } }
17,124
https://github.com/natinusala/skia/blob/master/tests/sksl/fp/GrGrSLTypesAreSupported.fp
Github Open Source
Open Source
BSD-3-Clause
2,022
skia
natinusala
GLSL
Code
89
290
int test_i (int a) { for (;;) { return a; } } int2 test_i2(int2 a) { for (;;) { return a; } } int3 test_i3(int3 a) { for (;;) { return a; } } int4 test_i4(int4 a) { for (;;) { return a; } } half3x4 test_h3x4(half3x4 a) { for (;;) { return a; } } float2x4 test_f2x4(float2x4 a) { for (;;) { return a; } } void main() { sk_OutColor = test_i(1).xxxx; sk_OutColor = test_i2(int2(1)).xxxx; sk_OutColor = test_i3(int3(1)).xxxx; sk_OutColor = test_i4(int4(1)).xxxx; sk_OutColor = test_h3x4(half3x4(1))[0]; sk_OutColor = half4(test_f2x4(float2x4(1))[0]); }
6,804
https://github.com/dreaderxxx/java-spring-messaging/blob/master/opentracing-spring-messaging-it/opentracing-spring-messaging-it-stream-common/src/main/java/io/opentracing/contrib/spring/integration/messaging/StreamApplication.java
Github Open Source
Open Source
Apache-2.0
null
java-spring-messaging
dreaderxxx
Java
Code
165
458
/** * Copyright 2017 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.integration.messaging; import io.opentracing.Tracer; import io.opentracing.mock.MockTracer; import io.opentracing.util.ThreadLocalActiveSpanSource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.integration.config.GlobalChannelInterceptor; /** * @author <a href="mailto:gytis@redhat.com">Gytis Trikleris</a> */ @SpringBootApplication public class StreamApplication { public static void main(String... args) { SpringApplication.run(StreamApplication.class, args); } @Bean public ThreadLocalActiveSpanSource threadLocalActiveSpanSource() { return new ThreadLocalActiveSpanSource(); } @Bean public MockTracer mockTracer() { return new MockTracer(new ThreadLocalActiveSpanSource(), MockTracer.Propagator.TEXT_MAP); } @Bean @GlobalChannelInterceptor public OpenTracingChannelInterceptor openTracingChannelInterceptor(Tracer tracer) { return new OpenTracingChannelInterceptor(tracer); } }
25,751
https://github.com/atarazana/quarkus-zero-to-serverless-guide/blob/master/documentation/modules/ROOT/pages/05-annex.adoc
Github Open Source
Open Source
Apache-2.0
null
quarkus-zero-to-serverless-guide
atarazana
AsciiDoc
Code
552
1,793
= ANNEX: Packing & building by using Docker include::_attributes.adoc[] [#native-mode-ii-generated-in-a-container] == Native Mode II (generated in a container) Quite often one only needs to create a native Linux executable for their Quarkus application (for example in order to run in a containerized environment) and would like to avoid the trouble of installing the proper GraalVM version in order to accomplish this task (for example, in CI environments it’s common practice to install as little software as possible). To this end, Quarkus provides a very convenient way of creating a native Linux executable by leveraging a container runtime such as Docker or podman. The easiest way of accomplishing this task is to execute: .If you want to use Mandrel instead of GraalVM **** [.console-input] [source,sh] ---- mvn package -Pnative -Dquarkus.native.container-build=true -Dquarkus.native.builder-image=quay.io/quarkus/ubi-quarkus-mandrel:{mandrel-flavor} ---- **** . Create the docker image: + [.console-input] [source,sh,role="copypaste"] ---- mvn package -DskipTests -Pnative -Dquarkus.native.container-build=true ---- . Create the docker image: + [.console-input] [source,sh,role="copypaste"] ---- docker build -f src/main/docker/Dockerfile.native -t atomic-fruit-service:1.0-SNAPSHOT . ---- + [TIP] ==== By default Quarkus automatically detects the container runtime. If you want to explicitely select the container runtime, you can do it with: [source,bash] ---- # Docker mvn package -Pnative -Dquarkus.native.container-build=true -Dquarkus.native.container-runtime=docker # Podman mvn package -Pnative -Dquarkus.native.container-build=true -Dquarkus.native.container-runtime=podman ---- These are normal Quarkus config properties, so if you always want to build in a container it is recommended you add these to your `application.properties` in order to avoid specifying them every time. ==== . Run the image created. + [.console-input] [source,sh,role="copypaste"] ---- docker run -i --rm -p 8080:8080 atomic-fruit-service:1.0-SNAPSHOT <1> ---- . Test from another terminal or a browser, you should receive a `hello` string. + [.console-input] [source,sh,role="copypaste"] ---- curl http://localhost:8080/fruit ---- <1> *_Ctrl+C_ to stop.* .Push to an image registry **** [TIP] ==== Finally you could push it to the image registry of your choice. [source,sh] ---- docker tag atomic-fruit-service:1.0-SNAPSHOT quay.io/<registry_user>/atomic-fruit-service:1.0-SNAPSHOT && \ docker push quay.io/<registry_user>/atomic-fruit-service:1.0-SNAPSHOT ---- ==== **** [#automatic-build-for-jvm-mode-using-docker] == Automatic build for JVM mode using `docker` With automatic builds we have to set `registry` and `group` to tag the image for pushing to the registry. Add these properties to the `application.properties` files or add them using `-D`. [source,properties,role="copypaste"] ---- ## OCI Image quarkus.container-image.registry=<registry> quarkus.container-image.group=<registry_user> ---- NOTE: Extentions for building images https://quarkus.io/guides/container-image[here] WARNING: For now you cannot use `podman` in this case... :-( https://github.com/quarkusio/quarkus/blob/master/extensions/container-image/container-image-docker/deployment/src/main/java/io/quarkus/container/image/docker/deployment/DockerProcessor.java[this] is the culprit. [.console-input] [source,sh,role="copypaste"] ---- mvn quarkus:add-extension -Dextensions="container-image-docker" mvn package -Dquarkus.native.container-build=true -Dquarkus.container-image.build=true ---- Run the image created. [.console-input] [source,sh,role="copypaste"] ---- docker run -i --rm -p 8080:8080 <registry>/<registry_user>/atomic-fruit-service:1.0-SNAPSHOT ---- Test from another terminal or a browser, you should receive a `hello` string. [.console-input] [source,sh,role="copypaste"] ---- curl http://localhost:8080/fruit ---- *_Ctrl+C_ to stop.* [#automatic-build-for-native-mode-using-docker] == Automatic build for Native mode using `docker` NOTE: Extentions for building images https://quarkus.io/guides/container-image[here]. WARNING: For now you cannot use `podman` in this case... :-( https://github.com/quarkusio/quarkus/blob/master/extensions/container-image/container-image-docker/deployment/src/main/java/io/quarkus/container/image/docker/deployment/DockerProcessor.java[this] is the culprit. [.console-input] [source,sh,role="copypaste"] ---- mvn quarkus:add-extension -Dextensions="container-image-docker" mvn package -Dquarkus.native.container-build=true -Dquarkus.container-image.build=true -Pnative ---- Run the image created. [.console-input] [source,sh,role="copypaste"] ---- docker run -i --rm -p 8080:8080 <registry>/<registry_user>/atomic-fruit-service:1.0-SNAPSHOT ---- Test from another terminal or a browser, you should receive a `hello` string. [.console-input] [source,sh,role="copypaste"] ---- curl http://localhost:8080/fruit ---- *_Ctrl+C_ to stop.* [#s2i-native-build] == S2i Native Build We saw how s2i works with the __JVM mode__ here: xref:04-deploy-openshift.adoc#deploying-to-openshift[Deploying to OpenShift]. What about native in this case? Easy, just add `-Dquarkus.native.container-build=true -Pnative`. [.console-input] [source,sh,role="copypaste"] ---- mvn clean package -Dquarkus.kubernetes.deploy=true -DskipTests -Pnative ----
1,978
https://github.com/igiu1988/iOS13.4.1-Runtime-Headers/blob/master/PrivateFrameworks/Coherence.framework/Coherence.CRDecodeContext.h
Github Open Source
Open Source
MIT
2,020
iOS13.4.1-Runtime-Headers
igiu1988
Objective-C
Code
18
69
/* Generated by EzioChiu Image: /System/Library/PrivateFrameworks/Coherence.framework/Coherence */ @interface Coherence.CRDecodeContext : _TtCs12_SwiftObject { void context; void references; } @end
29,929
https://github.com/zhangjiquan1/phpsourcecode/blob/master/imogo/MpHee/apps/article/view/index/layout.php
Github Open Source
Open Source
MIT
2,020
phpsourcecode
zhangjiquan1
Hack
Code
42
259
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>后台管理</title> <meta content="IE=8" http-equiv="X-UA-Compatible" /> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/base.css" /> <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/font-awesome.css"> <script type="text/javascript" src="__PUBLIC__/js/core/jquery.js"></script> </head> <body> <div id="contain"> {include file="$__template_file"} </div> </body> </html>
46,720
https://github.com/mikhailadvani/terraform-s3-backend/blob/master/test/backend_test.go
Github Open Source
Open Source
Apache-2.0
null
terraform-s3-backend
mikhailadvani
Go
Code
82
540
package test import ( "fmt" "strings" "testing" "github.com/gruntwork-io/terratest/modules/terraform" "github.com/stretchr/testify/assert" "github.com/gruntwork-io/terratest/modules/aws" "github.com/gruntwork-io/terratest/modules/random" ) func TestTerraformS3Backend(t *testing.T) { t.Parallel() testRandomValue := strings.ToLower(random.UniqueId()) expectedBucketName := fmt.Sprintf("terratest-backend-%s", testRandomValue) expectedDynamoDbTableName := fmt.Sprintf("terratest-backend-%s", testRandomValue) awsRegion := aws.GetRandomStableRegion(t, nil, nil) terraformOptions := &terraform.Options{ TerraformDir: "../", Vars: map[string]interface{}{ "bucket_name": expectedBucketName, "dynamodb_table_name": expectedDynamoDbTableName, }, EnvVars: map[string]string{ "AWS_DEFAULT_REGION": awsRegion, }, } defer terraform.Destroy(t, terraformOptions) terraform.InitAndApply(t, terraformOptions) actualBucketArn := terraform.Output(t, terraformOptions, "s3_bucket_arn") actualDynamoDbTableArn := terraform.Output(t, terraformOptions, "dynamodb_table_arn") expectedBucketArn := fmt.Sprintf("arn:aws:s3:::%s", expectedBucketName) expectedDynamoDbTableArn := fmt.Sprintf("arn:aws:dynamodb:%s:\\d{12}:table/%s", awsRegion, expectedDynamoDbTableName) assert.Equal(t, expectedBucketArn, actualBucketArn) assert.Regexp(t, expectedDynamoDbTableArn, actualDynamoDbTableArn) }
3,552
https://github.com/sheng3636/assistPlan/blob/master/src/views/outlineAuthorized/taskDivision.vue
Github Open Source
Open Source
MIT
null
assistPlan
sheng3636
Vue
Code
362
1,836
<template> <div class="app-container"> <div class="main-wrapper"> <div class="main-header">任务分工</div> <div class="main-content"> <el-form ref="queryParams" :model="queryParams" label-width="80px" label-position="top"> <el-row> <el-col :md="5" :sm="4"> <el-form-item label="段落内容" prop="projectNum"> <el-input v-model="queryParams.projectNum" /> </el-form-item> </el-col> <el-col :md="5" :sm="4"> <el-form-item label="撰写负责人" prop="projectName"> <el-input v-model="queryParams.projectName" /> </el-form-item> </el-col> <el-col :md="4" :sm="4"> <el-form-item class="textLeft param"> <el-button type="warning" size="mini" @click="queryList('queryParams')">查询</el-button> <el-button type="danger" size="mini" @click="resetData('queryParams')">重置</el-button> </el-form-item> </el-col> </el-row> </el-form> </div> </div> <div class="main-wrapper"> <div class="main-header"> <el-row> <el-col :md="6"> 任务分工列表 </el-col> <el-col :md="4" :offset="14" class="tableBtnGroup"> <el-button type="primary" size="mini">新增团队成员</el-button> </el-col> </el-row> </div> <!--列表--> <el-table :data="projectData" highlight-current-row style="width: 100%;" border > <el-table-column type="index" width="65" label="序号" align="center" /> <el-table-column prop="section" label="编写段落" :show-overflow-tooltip="true" align="center" /> <el-table-column prop="leader" label="编写负责人" width="180" align="center" sortable /> <el-table-column prop="time" label="时间节点" width="180" align="center" sortable /> <el-table-column fixed="right" label="操作" align="center" width="180" > <template slot-scope="scope"> <el-dropdown trigger="click"> <el-button type="success" size="mini" class="tab_select"> 更多菜单<i class="el-icon-arrow-down el-icon--right" /> </el-button> <el-dropdown-menu slot="dropdown"> <el-dropdown-item @click.native="editClick(scope.row)">编 辑</el-dropdown-item> <el-dropdown-item @click.native="deleteClick(scope.row.equiptId)">删 除</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </template> </el-table-column> </el-table> <!--分页--> <el-pagination :current-page.sync="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" /> </div> </div> </template> <script> export default { data() { return { total: 4, currentPage: 0, pageSize: 10, queryParams: { pageSize: 10, page: 1, projectNum: '', projectName: '', projectLeader: '', projectTime: '' }, projectData: [ { section: '发展基础和发展环境', leader: '杜健', time: '2019-12-21 12:21:12' }, { section: '指导思想、基本要求和发展目标', leader: '常云峰', time: '2019-12-21 12:21:12' }, { section: '扎实推进山海宜居美城建设', leader: '王红', time: '2019-10-11 10:20:00' }, { section: '着力推进国际智造名城建设', leader: '阿杰', time: '2019-11-01 9:25:00' } ] } }, mounted() { }, methods: { editClick(row) { console.log(row) }, detailClick(row) { console.log(row) }, deleteClick(row) { console.log(row) }, handleSizeChange(val) { this.params.pageSize = val this.getAreaList(this.params) }, handleCurrentChange(val) { this.params.page = val this.getAreaList(this.params) }, // 查询 queryList: function(formName) { this.$refs[formName].validate(valid => { if (valid) { console.log('查询') } else { return false } }) }, // 重置 resetData(formName) { this.$refs[formName].resetFields() console.log('重置') } } } </script> <style lang="scss" scoped> .tableRow{ display: flex; align-items: center; justify-content: space-between; margin-top: 3px; .countItem{ display: block; width: 120px; line-height: 40px; text-align: center; border-radius: 5px; color: #fff; font-size: 16px; background:rgba(22, 155, 213, 1); &:nth-child(2){ background: rgba(102, 204, 0, 1); } &:nth-child(3){ background: rgba(102, 102, 102, 1); } } } .tableBtnGroup{ display: flex; align-items: center; justify-content: flex-end; margin-top: 11px; } .sss{ display: flex; justify-content: space-between; button{ margin-right: 5px; } } </style>
15,636
https://github.com/homerooliveira/Bump/blob/master/Sources/XcodeProjWrapperMock/TargetMock.swift
Github Open Source
Open Source
MIT
null
Bump
homerooliveira
Swift
Code
43
114
// // File.swift // // // Created by Homero Oliveira on 11/07/20. // import XcodeProjWrapper public final class TargetMock: Target { public let name: String public let buildConfigurations: [BuildConfiguration]? public init(name: String, buildConfigurations: [BuildConfiguration]?) { self.name = name self.buildConfigurations = buildConfigurations } }
12,198
https://github.com/haunguyen2212/shop-laravel/blob/master/resources/views/frontend/cart.blade.php
Github Open Source
Open Source
MIT
null
shop-laravel
haunguyen2212
PHP
Code
320
1,494
@extends('layout.master') @section('title','Giỏ hàng') @section('style') <link rel="stylesheet" href="css/cart.css"> <link rel="stylesheet" href="css/toastr.min.css"> @endsection @section('content') <div id="breadcrumb" class="col-md-12"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{{ route('home') }}"><i class="fas fa-home"></i> Trang chủ</a></li> <li class="breadcrumb-item active" aria-current="page">Giỏ hàng</li> </ol> </nav> </div> <div class="product-caption">GIỎ HÀNG CỦA BẠN</div> @if(!isset($carts) || $carts->count() == 0) <div id="empty-cart"> <div class="empty-cart-img"> <img width="30%" src="img/img-cart-empty.png"> </div> <div class="empty-cart-text">Không có sản phẩm nào trong giỏ hàng</div> <div class="empty-cart-link"> <a class="btn btn-sm" href="{{ route('home') }}">VỀ TRANG CHỦ</a> </div> </div> @else <div class="table-responsive" id="shoppingcart"> <table class="table table-borderless table-bordered"> <thead> <tr> <th width="5%">STT</th> <th width="20%">Tên sản phẩm</th> <th width="20%">Hình ảnh</th> <th width="15%">Đơn giá</th> <th width="15%">Số lượng</th> <th width="15%">Thành tiền</th> <th width="10%">Xóa</th> </tr> </thead> <tbody> @foreach ($carts as $cart) <tr> <td>{{ $number++ }}</td> <td>{{ $cart->name }} ({{ $cart->options->color }})</td> <td><img src="img/product_detail/{{ $cart->options->image }}" alt="{{ $cart->name }}"></td> <td>{{ number_format($cart->price) }}</td> <td> <input type="number" class="update-cart" min="1" max="{{ $cart->options->max_qty }}" value="{{ ($cart->qty < $cart->options->max_qty) ? $cart->qty : $cart->options->max_qty }}" onchange="updateCart(this.value,'{{ $cart->rowId }}')"></td> <td>{{ number_format($cart->price*$cart->qty) }}</td> <td><a href="{{ route('cart.delete', ['rowId' => $cart->rowId ]) }}"><i class="fas fa-times"></i></a></td> </tr> @endforeach <tr id="total"> <td colspan="7">Tổng cộng:<span> {{ $total }} VND</span></td> </tr> </tbody> </table> <div class="d-flex float-end"> <a class="btn btn-sm btn-success ms-1" href="{{ route('checkout') }}">Đặt hàng</a> <!-- Button trigger modal --> <button type="button" class="btn btn-sm btn-danger ms-1" data-bs-toggle="modal" data-bs-target="#destroyCart"> Xóa tất cả </button> <!-- Modal --> <div class="modal fade" id="destroyCart" tabindex="-1" aria-labelledby="destroyCartLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title fw-bold text-danger" id="destroyCartLabel"><i class="fas fa-exclamation-triangle"></i> Cảnh Báo</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Thao tác này sẽ xóa toàn bộ giỏ hàng. Bạn có chắc muốn xóa toàn bộ giỏ hàng của mình không? </div> <div class="modal-footer"> <button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Không</button> <a href="{{ route('cart.destroy') }}" class="btn btn-sm btn-primary">Đồng ý</a> </div> </div> </div> </div> <a class="btn btn-sm btn-primary ms-1" href="{{ route('home') }}">Tiếp tục mua hàng</a> </div> </div> @endif @endsection @section('script') <script type="text/javascript" src="js/toastr.min.js"></script> {!! Toastr::message() !!} <script> function updateCart(qty,rowId){ $.get( '{{ route('cart.update') }}', {qty:qty,rowId:rowId}, function(){ location.reload(); } ); } </script> @endsection
14,253
https://github.com/Tomracer/CorsixTH/blob/master/CorsixTH/Lua/objects/gates_to_hell.lua
Github Open Source
Open Source
MIT
2,022
CorsixTH
Tomracer
Lua
Code
317
662
--[[ Copyright (c) 2013 Luís "driverpt" Duarte 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. --]] local object = {} object.id = "gates_to_hell" object.name = "Gates to Hell" object.thob = 48 object.ticks = true object.walk_in_to_use = true object.idle_animations = { south = 1602, east = 1602 } object.usage_animations = { south = { in_use = { ["Standard Male Patient"] = 4560, }, }, east = { in_use = { ["Standard Male Patient"] = 4560, }, } } local anim_mgr = TheApp.animation_manager anim_mgr:setMarker(object.usage_animations.south.in_use, 0, {0,0}) anim_mgr:setMarker(object.usage_animations.east.in_use, 0, {0,0}) -- Orientation directions are relative to the patient's death location: object.orientations = { south = { use_position = {0, 0}, footprint = { {1, 0, only_passable = true}, {0, 0, complete_cell = true}, {-1, 0, only_passable = true} }, use_animate_from_use_position = false }, east = { use_position = {0, 0}, footprint = { {0, -1, only_passable = true}, {0, 0, complete_cell = true}, {0, 1, only_passable = true} }, use_animate_from_use_position = false } } return object
7,039
https://github.com/ItsLastDay/KotlinFuzzer/blob/master/fuzzer/fuzzing_output/crashing_tests/verified/constructors.kt-803823115.kt
Github Open Source
Open Source
MIT
2,021
KotlinFuzzer
ItsLastDay
Kotlin
Code
55
275
import kotlin.reflect.* import kotlin.reflect.jvm.* import kotlin.test.assertEquals class A(d: Double, s: String, parent: A?) { class Nested(a: A) inner class Inner(nested: Nested) } tailrec fun box(): String { assertEquals(listOf(java.lang.Double.TYPE, String::class.java, A::class.java), ::A.parameters.map({it.type.javaType})) assertEquals(listOf(A::class.java), (if ((A::Nested) <= false) { (A::Nested) } else { false }).parameters.map({it.type.javaType})) assertEquals(listOf(A::class.java, A.Nested::class.java), A::Inner.parameters.map({it.type.javaType})) assertEquals(A::class.java, ::A.returnType.javaType) assertEquals(A.Nested::class.java, A::Nested.returnType.(javaType)!!) assertEquals(A.Inner::class.java, A::Inner.returnType.javaType) return "OK" }
32,263
https://github.com/ckhairul/backend/blob/master/tasks/artifacts.py
Github Open Source
Open Source
MIT
null
backend
ckhairul
Python
Code
27
125
import os from shutil import rmtree from huey import crontab from .config import huey @huey.periodic_task(crontab(minute='0', hour='*')) def clean_artifacts_runner(): for d in os.listdir('ansible/priv_data_dirs'): rmtree(f"ansible/priv_data_dirs/{d}/artifacts", ignore_errors=True) print("Artifacts all cleaned")
38,764
https://github.com/cr88192/bgbtech_btsr1arch/blob/master/tk_ports/Q3Src/q3core/q3_ui/vm/ui_splevel.asm
Github Open Source
Open Source
MIT
2,023
bgbtech_btsr1arch
cr88192
Assembly
Code
13,630
44,126
code proc PlayerIcon 80 20 file "../ui_splevel.c" line 128 ;1:/* ;2:=========================================================================== ;3:Copyright (C) 1999-2005 Id Software, Inc. ;4: ;5:This file is part of Quake III Arena source code. ;6: ;7:Quake III Arena source code is free software; you can redistribute it ;8:and/or modify it under the terms of the GNU General Public License as ;9:published by the Free Software Foundation; either version 2 of the License, ;10:or (at your option) any later version. ;11: ;12:Quake III Arena source code is distributed in the hope that it will be ;13:useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ;14:MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;15:GNU General Public License for more details. ;16: ;17:You should have received a copy of the GNU General Public License ;18:along with Foobar; if not, write to the Free Software ;19:Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ;20:=========================================================================== ;21:*/ ;22:// ;23:/* ;24:============================================================================= ;25: ;26:SINGLE PLAYER LEVEL SELECT MENU ;27: ;28:============================================================================= ;29:*/ ;30: ;31:#include "ui_local.h" ;32: ;33: ;34:#define ART_LEVELFRAME_FOCUS "menu/art/maps_select" ;35:#define ART_LEVELFRAME_SELECTED "menu/art/maps_selected" ;36:#define ART_ARROW "menu/art/narrow_0" ;37:#define ART_ARROW_FOCUS "menu/art/narrow_1" ;38:#define ART_MAP_UNKNOWN "menu/art/unknownmap" ;39:#define ART_MAP_COMPLETE1 "menu/art/level_complete1" ;40:#define ART_MAP_COMPLETE2 "menu/art/level_complete2" ;41:#define ART_MAP_COMPLETE3 "menu/art/level_complete3" ;42:#define ART_MAP_COMPLETE4 "menu/art/level_complete4" ;43:#define ART_MAP_COMPLETE5 "menu/art/level_complete5" ;44:#define ART_BACK0 "menu/art/back_0" ;45:#define ART_BACK1 "menu/art/back_1" ;46:#define ART_FIGHT0 "menu/art/fight_0" ;47:#define ART_FIGHT1 "menu/art/fight_1" ;48:#define ART_RESET0 "menu/art/reset_0" ;49:#define ART_RESET1 "menu/art/reset_1" ;50:#define ART_CUSTOM0 "menu/art/skirmish_0" ;51:#define ART_CUSTOM1 "menu/art/skirmish_1" ;52: ;53:#define ID_LEFTARROW 10 ;54:#define ID_PICTURE0 11 ;55:#define ID_PICTURE1 12 ;56:#define ID_PICTURE2 13 ;57:#define ID_PICTURE3 14 ;58:#define ID_RIGHTARROW 15 ;59:#define ID_PLAYERPIC 16 ;60:#define ID_AWARD1 17 ;61:#define ID_AWARD2 18 ;62:#define ID_AWARD3 19 ;63:#define ID_AWARD4 20 ;64:#define ID_AWARD5 21 ;65:#define ID_AWARD6 22 ;66:#define ID_BACK 23 ;67:#define ID_RESET 24 ;68:#define ID_CUSTOM 25 ;69:#define ID_NEXT 26 ;70: ;71:#define PLAYER_Y 314 ;72:#define AWARDS_Y (PLAYER_Y + 26) ;73: ;74: ;75:typedef struct { ;76: menuframework_s menu; ;77: menutext_s item_banner; ;78: menubitmap_s item_leftarrow; ;79: menubitmap_s item_maps[4]; ;80: menubitmap_s item_rightarrow; ;81: menubitmap_s item_player; ;82: menubitmap_s item_awards[6]; ;83: menubitmap_s item_back; ;84: menubitmap_s item_reset; ;85: menubitmap_s item_custom; ;86: menubitmap_s item_next; ;87: menubitmap_s item_null; ;88: ;89: qboolean reinit; ;90: ;91: const char * selectedArenaInfo; ;92: int numMaps; ;93: char levelPicNames[4][MAX_QPATH]; ;94: char levelNames[4][16]; ;95: int levelScores[4]; ;96: int levelScoresSkill[4]; ;97: qhandle_t levelSelectedPic; ;98: qhandle_t levelFocusPic; ;99: qhandle_t levelCompletePic[5]; ;100: ;101: char playerModel[MAX_QPATH]; ;102: char playerPicName[MAX_QPATH]; ;103: int awardLevels[6]; ;104: sfxHandle_t awardSounds[6]; ;105: ;106: int numBots; ;107: qhandle_t botPics[7]; ;108: char botNames[7][10]; ;109:} levelMenuInfo_t; ;110: ;111:static levelMenuInfo_t levelMenuInfo; ;112: ;113:static int selectedArenaSet; ;114:static int selectedArena; ;115:static int currentSet; ;116:static int currentGame; ;117:static int trainingTier; ;118:static int finalTier; ;119:static int minTier; ;120:static int maxTier; ;121: ;122: ;123:/* ;124:================= ;125:PlayerIcon ;126:================= ;127:*/ ;128:static void PlayerIcon( const char *modelAndSkin, char *iconName, int iconNameMaxSize ) { line 132 ;129: char *skin; ;130: char model[MAX_QPATH]; ;131: ;132: Q_strncpyz( model, modelAndSkin, sizeof(model)); ADDRLP4 4 ARGP4 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 133 ;133: skin = Q_strrchr( model, '/' ); ADDRLP4 4 ARGP4 CNSTI4 47 ARGI4 ADDRLP4 68 ADDRGP4 Q_strrchr CALLP4 ASGNP4 ADDRLP4 0 ADDRLP4 68 INDIRP4 ASGNP4 line 134 ;134: if ( skin ) { ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $69 line 135 ;135: *skin++ = '\0'; ADDRLP4 72 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 72 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 72 INDIRP4 CNSTI1 0 ASGNI1 line 136 ;136: } ADDRGP4 $70 JUMPV LABELV $69 line 137 ;137: else { line 138 ;138: skin = "default"; ADDRLP4 0 ADDRGP4 $71 ASGNP4 line 139 ;139: } LABELV $70 line 141 ;140: ;141: Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_%s.tga", model, skin ); ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 8 INDIRI4 ARGI4 ADDRGP4 $72 ARGP4 ADDRLP4 4 ARGP4 ADDRLP4 0 INDIRP4 ARGP4 ADDRGP4 Com_sprintf CALLV pop line 143 ;142: ;143: if( !trap_R_RegisterShaderNoMip( iconName ) && Q_stricmp( skin, "default" ) != 0 ) { ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 72 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRLP4 72 INDIRI4 CNSTI4 0 NEI4 $73 ADDRLP4 0 INDIRP4 ARGP4 ADDRGP4 $71 ARGP4 ADDRLP4 76 ADDRGP4 Q_stricmp CALLI4 ASGNI4 ADDRLP4 76 INDIRI4 CNSTI4 0 EQI4 $73 line 144 ;144: Com_sprintf(iconName, iconNameMaxSize, "models/players/%s/icon_default.tga", model ); ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 8 INDIRI4 ARGI4 ADDRGP4 $75 ARGP4 ADDRLP4 4 ARGP4 ADDRGP4 Com_sprintf CALLV pop line 145 ;145: } LABELV $73 line 146 ;146:} LABELV $68 endproc PlayerIcon 80 20 proc PlayerIconHandle 68 12 line 154 ;147: ;148: ;149:/* ;150:================= ;151:PlayerIconhandle ;152:================= ;153:*/ ;154:static qhandle_t PlayerIconHandle( const char *modelAndSkin ) { line 157 ;155: char iconName[MAX_QPATH]; ;156: ;157: PlayerIcon( modelAndSkin, iconName, sizeof(iconName) ); ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 0 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 PlayerIcon CALLV pop line 158 ;158: return trap_R_RegisterShaderNoMip( iconName ); ADDRLP4 0 ARGP4 ADDRLP4 64 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRLP4 64 INDIRI4 RETI4 LABELV $76 endproc PlayerIconHandle 68 12 proc UI_SPLevelMenu_SetBots 1068 12 line 167 ;159:} ;160: ;161: ;162:/* ;163:================= ;164:UI_SPLevelMenu_SetBots ;165:================= ;166:*/ ;167:static void UI_SPLevelMenu_SetBots( void ) { line 173 ;168: char *p; ;169: char *bot; ;170: char *botInfo; ;171: char bots[MAX_INFO_STRING]; ;172: ;173: levelMenuInfo.numBots = 0; ADDRGP4 levelMenuInfo+2512 CNSTI4 0 ASGNI4 line 174 ;174: if ( selectedArenaSet > currentSet ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 currentSet INDIRI4 LEI4 $79 line 175 ;175: return; ADDRGP4 $77 JUMPV LABELV $79 line 178 ;176: } ;177: ;178: Q_strncpyz( bots, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "bots" ), sizeof(bots) ); ADDRGP4 levelMenuInfo+1948 INDIRP4 ARGP4 ADDRGP4 $82 ARGP4 ADDRLP4 1036 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 12 ARGP4 ADDRLP4 1036 INDIRP4 ARGP4 CNSTI4 1024 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 180 ;179: ;180: p = &bots[0]; ADDRLP4 0 ADDRLP4 12 ASGNP4 ADDRGP4 $84 JUMPV line 181 ;181: while( *p && levelMenuInfo.numBots < 7 ) { LABELV $87 line 183 ;182: //skip spaces ;183: while( *p && *p == ' ' ) { line 184 ;184: p++; ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 line 185 ;185: } LABELV $88 line 183 ADDRLP4 1040 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 1040 INDIRI4 CNSTI4 0 EQI4 $90 ADDRLP4 1040 INDIRI4 CNSTI4 32 EQI4 $87 LABELV $90 line 186 ;186: if( !p ) { ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $91 line 187 ;187: break; ADDRGP4 $85 JUMPV LABELV $91 line 191 ;188: } ;189: ;190: // mark start of bot name ;191: bot = p; ADDRLP4 8 ADDRLP4 0 INDIRP4 ASGNP4 ADDRGP4 $94 JUMPV LABELV $93 line 194 ;192: ;193: // skip until space of null ;194: while( *p && *p != ' ' ) { line 195 ;195: p++; ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 line 196 ;196: } LABELV $94 line 194 ADDRLP4 1044 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 1044 INDIRI4 CNSTI4 0 EQI4 $96 ADDRLP4 1044 INDIRI4 CNSTI4 32 NEI4 $93 LABELV $96 line 197 ;197: if( *p ) { ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 EQI4 $97 line 198 ;198: *p++ = 0; ADDRLP4 1048 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 1048 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 1048 INDIRP4 CNSTI1 0 ASGNI1 line 199 ;199: } LABELV $97 line 201 ;200: ;201: botInfo = UI_GetBotInfoByName( bot ); ADDRLP4 8 INDIRP4 ARGP4 ADDRLP4 1048 ADDRGP4 UI_GetBotInfoByName CALLP4 ASGNP4 ADDRLP4 4 ADDRLP4 1048 INDIRP4 ASGNP4 line 202 ;202: if( botInfo ) { ADDRLP4 4 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $99 line 203 ;203: levelMenuInfo.botPics[levelMenuInfo.numBots] = PlayerIconHandle( Info_ValueForKey( botInfo, "model" ) ); ADDRLP4 4 INDIRP4 ARGP4 ADDRGP4 $103 ARGP4 ADDRLP4 1052 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 1052 INDIRP4 ARGP4 ADDRLP4 1056 ADDRGP4 PlayerIconHandle CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2512 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2516 ADDP4 ADDRLP4 1056 INDIRI4 ASGNI4 line 204 ;204: Q_strncpyz( levelMenuInfo.botNames[levelMenuInfo.numBots], Info_ValueForKey( botInfo, "name" ), 10 ); ADDRLP4 4 INDIRP4 ARGP4 ADDRGP4 $106 ARGP4 ADDRLP4 1060 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 1064 CNSTI4 10 ASGNI4 ADDRLP4 1064 INDIRI4 ADDRGP4 levelMenuInfo+2512 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+2544 ADDP4 ARGP4 ADDRLP4 1060 INDIRP4 ARGP4 ADDRLP4 1064 INDIRI4 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 205 ;205: } ADDRGP4 $100 JUMPV LABELV $99 line 206 ;206: else { line 207 ;207: levelMenuInfo.botPics[levelMenuInfo.numBots] = 0; ADDRGP4 levelMenuInfo+2512 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2516 ADDP4 CNSTI4 0 ASGNI4 line 208 ;208: Q_strncpyz( levelMenuInfo.botNames[levelMenuInfo.numBots], bot, 10 ); ADDRLP4 1052 CNSTI4 10 ASGNI4 ADDRLP4 1052 INDIRI4 ADDRGP4 levelMenuInfo+2512 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+2544 ADDP4 ARGP4 ADDRLP4 8 INDIRP4 ARGP4 ADDRLP4 1052 INDIRI4 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 209 ;209: } LABELV $100 line 210 ;210: Q_CleanStr( levelMenuInfo.botNames[levelMenuInfo.numBots] ); CNSTI4 10 ADDRGP4 levelMenuInfo+2512 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+2544 ADDP4 ARGP4 ADDRGP4 Q_CleanStr CALLP4 pop line 211 ;211: levelMenuInfo.numBots++; ADDRLP4 1052 ADDRGP4 levelMenuInfo+2512 ASGNP4 ADDRLP4 1052 INDIRP4 ADDRLP4 1052 INDIRP4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 line 212 ;212: } LABELV $84 line 181 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 EQI4 $114 ADDRGP4 levelMenuInfo+2512 INDIRI4 CNSTI4 7 LTI4 $88 LABELV $114 LABELV $85 line 213 ;213:} LABELV $77 endproc UI_SPLevelMenu_SetBots 1068 12 proc UI_SPLevelMenu_SetMenuArena 84 12 line 221 ;214: ;215: ;216:/* ;217:================= ;218:UI_SPLevelMenu_SetMenuItems ;219:================= ;220:*/ ;221:static void UI_SPLevelMenu_SetMenuArena( int n, int level, const char *arenaInfo ) { line 224 ;222: char map[MAX_QPATH]; ;223: ;224: Q_strncpyz( map, Info_ValueForKey( arenaInfo, "map" ), sizeof(map) ); ADDRFP4 8 INDIRP4 ARGP4 ADDRGP4 $116 ARGP4 ADDRLP4 64 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 0 ARGP4 ADDRLP4 64 INDIRP4 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 226 ;225: ;226: Q_strncpyz( levelMenuInfo.levelNames[n], map, sizeof(levelMenuInfo.levelNames[n]) ); ADDRFP4 0 INDIRI4 CNSTI4 4 LSHI4 ADDRGP4 levelMenuInfo+2212 ADDP4 ARGP4 ADDRLP4 0 ARGP4 CNSTI4 16 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 227 ;227: Q_strupr( levelMenuInfo.levelNames[n] ); ADDRFP4 0 INDIRI4 CNSTI4 4 LSHI4 ADDRGP4 levelMenuInfo+2212 ADDP4 ARGP4 ADDRGP4 Q_strupr CALLP4 pop line 229 ;228: ;229: UI_GetBestScore( level, &levelMenuInfo.levelScores[n], &levelMenuInfo.levelScoresSkill[n] ); ADDRFP4 4 INDIRI4 ARGI4 ADDRLP4 68 ADDRFP4 0 INDIRI4 CNSTI4 2 LSHI4 ASGNI4 ADDRLP4 68 INDIRI4 ADDRGP4 levelMenuInfo+2276 ADDP4 ARGP4 ADDRLP4 68 INDIRI4 ADDRGP4 levelMenuInfo+2292 ADDP4 ARGP4 ADDRGP4 UI_GetBestScore CALLV pop line 230 ;230: if( levelMenuInfo.levelScores[n] > 8 ) { ADDRFP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2276 ADDP4 INDIRI4 CNSTI4 8 LEI4 $122 line 231 ;231: levelMenuInfo.levelScores[n] = 8; ADDRFP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2276 ADDP4 CNSTI4 8 ASGNI4 line 232 ;232: } LABELV $122 line 234 ;233: ;234: strcpy( levelMenuInfo.levelPicNames[n], va( "levelshots/%s.tga", map ) ); ADDRGP4 $127 ARGP4 ADDRLP4 0 ARGP4 ADDRLP4 72 ADDRGP4 va CALLP4 ASGNP4 ADDRFP4 0 INDIRI4 CNSTI4 6 LSHI4 ADDRGP4 levelMenuInfo+1956 ADDP4 ARGP4 ADDRLP4 72 INDIRP4 ARGP4 ADDRGP4 strcpy CALLP4 pop line 235 ;235: if( !trap_R_RegisterShaderNoMip( levelMenuInfo.levelPicNames[n] ) ) { ADDRFP4 0 INDIRI4 CNSTI4 6 LSHI4 ADDRGP4 levelMenuInfo+1956 ADDP4 ARGP4 ADDRLP4 76 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRLP4 76 INDIRI4 CNSTI4 0 NEI4 $128 line 236 ;236: strcpy( levelMenuInfo.levelPicNames[n], ART_MAP_UNKNOWN ); ADDRFP4 0 INDIRI4 CNSTI4 6 LSHI4 ADDRGP4 levelMenuInfo+1956 ADDP4 ARGP4 ADDRGP4 $132 ARGP4 ADDRGP4 strcpy CALLP4 pop line 237 ;237: } LABELV $128 line 238 ;238: levelMenuInfo.item_maps[n].shader = 0; CNSTI4 88 ADDRFP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+68 ADDP4 CNSTI4 0 ASGNI4 line 239 ;239: if ( selectedArenaSet > currentSet ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 currentSet INDIRI4 LEI4 $135 line 240 ;240: levelMenuInfo.item_maps[n].generic.flags |= QMF_GRAYED; ADDRLP4 80 CNSTI4 88 ADDRFP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+44 ADDP4 ASGNP4 ADDRLP4 80 INDIRP4 ADDRLP4 80 INDIRP4 INDIRU4 CNSTU4 8192 BORU4 ASGNU4 line 241 ;241: } ADDRGP4 $136 JUMPV LABELV $135 line 242 ;242: else { line 243 ;243: levelMenuInfo.item_maps[n].generic.flags &= ~QMF_GRAYED; ADDRLP4 80 CNSTI4 88 ADDRFP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+44 ADDP4 ASGNP4 ADDRLP4 80 INDIRP4 ADDRLP4 80 INDIRP4 INDIRU4 CNSTU4 4294959103 BANDU4 ASGNU4 line 244 ;244: } LABELV $136 line 246 ;245: ;246: levelMenuInfo.item_maps[n].generic.flags &= ~QMF_INACTIVE; ADDRLP4 80 CNSTI4 88 ADDRFP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+44 ADDP4 ASGNP4 ADDRLP4 80 INDIRP4 ADDRLP4 80 INDIRP4 INDIRU4 CNSTU4 4294950911 BANDU4 ASGNU4 line 247 ;247:} LABELV $115 endproc UI_SPLevelMenu_SetMenuArena 84 12 proc UI_SPLevelMenu_SetMenuItems 44 12 line 249 ;248: ;249:static void UI_SPLevelMenu_SetMenuItems( void ) { line 254 ;250: int n; ;251: int level; ;252: const char *arenaInfo; ;253: ;254: if ( selectedArenaSet > currentSet ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 currentSet INDIRI4 LEI4 $144 line 255 ;255: selectedArena = -1; ADDRGP4 selectedArena CNSTI4 -1 ASGNI4 line 256 ;256: } ADDRGP4 $145 JUMPV LABELV $144 line 257 ;257: else if ( selectedArena == -1 ) { ADDRGP4 selectedArena INDIRI4 CNSTI4 -1 NEI4 $146 line 258 ;258: selectedArena = 0; ADDRGP4 selectedArena CNSTI4 0 ASGNI4 line 259 ;259: } LABELV $146 LABELV $145 line 261 ;260: ;261: if( selectedArenaSet == trainingTier || selectedArenaSet == finalTier ) { ADDRLP4 12 ADDRGP4 selectedArenaSet INDIRI4 ASGNI4 ADDRLP4 12 INDIRI4 ADDRGP4 trainingTier INDIRI4 EQI4 $150 ADDRLP4 12 INDIRI4 ADDRGP4 finalTier INDIRI4 NEI4 $148 LABELV $150 line 262 ;262: selectedArena = 0; ADDRGP4 selectedArena CNSTI4 0 ASGNI4 line 263 ;263: } LABELV $148 line 265 ;264: ;265: if( selectedArena != -1 ) { ADDRGP4 selectedArena INDIRI4 CNSTI4 -1 EQI4 $151 line 266 ;266: trap_Cvar_SetValue( "ui_spSelection", selectedArenaSet * ARENAS_PER_TIER + selectedArena ); ADDRGP4 $153 ARGP4 ADDRGP4 selectedArenaSet INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 selectedArena INDIRI4 ADDI4 CVIF4 4 ARGF4 ADDRGP4 trap_Cvar_SetValue CALLV pop line 267 ;267: } LABELV $151 line 269 ;268: ;269: if( selectedArenaSet == trainingTier ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 trainingTier INDIRI4 NEI4 $154 line 270 ;270: arenaInfo = UI_GetSpecialArenaInfo( "training" ); ADDRGP4 $156 ARGP4 ADDRLP4 16 ADDRGP4 UI_GetSpecialArenaInfo CALLP4 ASGNP4 ADDRLP4 8 ADDRLP4 16 INDIRP4 ASGNP4 line 271 ;271: level = atoi( Info_ValueForKey( arenaInfo, "num" ) ); ADDRLP4 8 INDIRP4 ARGP4 ADDRGP4 $157 ARGP4 ADDRLP4 20 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 20 INDIRP4 ARGP4 ADDRLP4 24 ADDRGP4 atoi CALLI4 ASGNI4 ADDRLP4 4 ADDRLP4 24 INDIRI4 ASGNI4 line 272 ;272: UI_SPLevelMenu_SetMenuArena( 0, level, arenaInfo ); CNSTI4 0 ARGI4 ADDRLP4 4 INDIRI4 ARGI4 ADDRLP4 8 INDIRP4 ARGP4 ADDRGP4 UI_SPLevelMenu_SetMenuArena CALLV pop line 273 ;273: levelMenuInfo.selectedArenaInfo = arenaInfo; ADDRGP4 levelMenuInfo+1948 ADDRLP4 8 INDIRP4 ASGNP4 line 275 ;274: ;275: levelMenuInfo.item_maps[0].generic.x = 256; ADDRGP4 levelMenuInfo+448+12 CNSTI4 256 ASGNI4 line 276 ;276: Bitmap_Init( &levelMenuInfo.item_maps[0] ); ADDRGP4 levelMenuInfo+448 ARGP4 ADDRGP4 Bitmap_Init CALLV pop line 277 ;277: levelMenuInfo.item_maps[0].generic.bottom += 32; ADDRLP4 28 ADDRGP4 levelMenuInfo+448+32 ASGNP4 ADDRLP4 28 INDIRP4 ADDRLP4 28 INDIRP4 INDIRI4 CNSTI4 32 ADDI4 ASGNI4 line 278 ;278: levelMenuInfo.numMaps = 1; ADDRGP4 levelMenuInfo+1952 CNSTI4 1 ASGNI4 line 280 ;279: ;280: levelMenuInfo.item_maps[1].generic.flags |= QMF_INACTIVE; ADDRLP4 32 ADDRGP4 levelMenuInfo+448+88+44 ASGNP4 ADDRLP4 32 INDIRP4 ADDRLP4 32 INDIRP4 INDIRU4 CNSTU4 16384 BORU4 ASGNU4 line 281 ;281: levelMenuInfo.item_maps[2].generic.flags |= QMF_INACTIVE; ADDRLP4 36 ADDRGP4 levelMenuInfo+448+176+44 ASGNP4 ADDRLP4 36 INDIRP4 ADDRLP4 36 INDIRP4 INDIRU4 CNSTU4 16384 BORU4 ASGNU4 line 282 ;282: levelMenuInfo.item_maps[3].generic.flags |= QMF_INACTIVE; ADDRLP4 40 ADDRGP4 levelMenuInfo+448+264+44 ASGNP4 ADDRLP4 40 INDIRP4 ADDRLP4 40 INDIRP4 INDIRU4 CNSTU4 16384 BORU4 ASGNU4 line 283 ;283: levelMenuInfo.levelPicNames[1][0] = 0; ADDRGP4 levelMenuInfo+1956+64 CNSTI1 0 ASGNI1 line 284 ;284: levelMenuInfo.levelPicNames[2][0] = 0; ADDRGP4 levelMenuInfo+1956+128 CNSTI1 0 ASGNI1 line 285 ;285: levelMenuInfo.levelPicNames[3][0] = 0; ADDRGP4 levelMenuInfo+1956+192 CNSTI1 0 ASGNI1 line 286 ;286: levelMenuInfo.item_maps[1].shader = 0; ADDRGP4 levelMenuInfo+448+88+68 CNSTI4 0 ASGNI4 line 287 ;287: levelMenuInfo.item_maps[2].shader = 0; ADDRGP4 levelMenuInfo+448+176+68 CNSTI4 0 ASGNI4 line 288 ;288: levelMenuInfo.item_maps[3].shader = 0; ADDRGP4 levelMenuInfo+448+264+68 CNSTI4 0 ASGNI4 line 289 ;289: } ADDRGP4 $155 JUMPV LABELV $154 line 290 ;290: else if( selectedArenaSet == finalTier ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 finalTier INDIRI4 NEI4 $189 line 291 ;291: arenaInfo = UI_GetSpecialArenaInfo( "final" ); ADDRGP4 $191 ARGP4 ADDRLP4 16 ADDRGP4 UI_GetSpecialArenaInfo CALLP4 ASGNP4 ADDRLP4 8 ADDRLP4 16 INDIRP4 ASGNP4 line 292 ;292: level = atoi( Info_ValueForKey( arenaInfo, "num" ) ); ADDRLP4 8 INDIRP4 ARGP4 ADDRGP4 $157 ARGP4 ADDRLP4 20 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 20 INDIRP4 ARGP4 ADDRLP4 24 ADDRGP4 atoi CALLI4 ASGNI4 ADDRLP4 4 ADDRLP4 24 INDIRI4 ASGNI4 line 293 ;293: UI_SPLevelMenu_SetMenuArena( 0, level, arenaInfo ); CNSTI4 0 ARGI4 ADDRLP4 4 INDIRI4 ARGI4 ADDRLP4 8 INDIRP4 ARGP4 ADDRGP4 UI_SPLevelMenu_SetMenuArena CALLV pop line 294 ;294: levelMenuInfo.selectedArenaInfo = arenaInfo; ADDRGP4 levelMenuInfo+1948 ADDRLP4 8 INDIRP4 ASGNP4 line 296 ;295: ;296: levelMenuInfo.item_maps[0].generic.x = 256; ADDRGP4 levelMenuInfo+448+12 CNSTI4 256 ASGNI4 line 297 ;297: Bitmap_Init( &levelMenuInfo.item_maps[0] ); ADDRGP4 levelMenuInfo+448 ARGP4 ADDRGP4 Bitmap_Init CALLV pop line 298 ;298: levelMenuInfo.item_maps[0].generic.bottom += 32; ADDRLP4 28 ADDRGP4 levelMenuInfo+448+32 ASGNP4 ADDRLP4 28 INDIRP4 ADDRLP4 28 INDIRP4 INDIRI4 CNSTI4 32 ADDI4 ASGNI4 line 299 ;299: levelMenuInfo.numMaps = 1; ADDRGP4 levelMenuInfo+1952 CNSTI4 1 ASGNI4 line 301 ;300: ;301: levelMenuInfo.item_maps[1].generic.flags |= QMF_INACTIVE; ADDRLP4 32 ADDRGP4 levelMenuInfo+448+88+44 ASGNP4 ADDRLP4 32 INDIRP4 ADDRLP4 32 INDIRP4 INDIRU4 CNSTU4 16384 BORU4 ASGNU4 line 302 ;302: levelMenuInfo.item_maps[2].generic.flags |= QMF_INACTIVE; ADDRLP4 36 ADDRGP4 levelMenuInfo+448+176+44 ASGNP4 ADDRLP4 36 INDIRP4 ADDRLP4 36 INDIRP4 INDIRU4 CNSTU4 16384 BORU4 ASGNU4 line 303 ;303: levelMenuInfo.item_maps[3].generic.flags |= QMF_INACTIVE; ADDRLP4 40 ADDRGP4 levelMenuInfo+448+264+44 ASGNP4 ADDRLP4 40 INDIRP4 ADDRLP4 40 INDIRP4 INDIRU4 CNSTU4 16384 BORU4 ASGNU4 line 304 ;304: levelMenuInfo.levelPicNames[1][0] = 0; ADDRGP4 levelMenuInfo+1956+64 CNSTI1 0 ASGNI1 line 305 ;305: levelMenuInfo.levelPicNames[2][0] = 0; ADDRGP4 levelMenuInfo+1956+128 CNSTI1 0 ASGNI1 line 306 ;306: levelMenuInfo.levelPicNames[3][0] = 0; ADDRGP4 levelMenuInfo+1956+192 CNSTI1 0 ASGNI1 line 307 ;307: levelMenuInfo.item_maps[1].shader = 0; ADDRGP4 levelMenuInfo+448+88+68 CNSTI4 0 ASGNI4 line 308 ;308: levelMenuInfo.item_maps[2].shader = 0; ADDRGP4 levelMenuInfo+448+176+68 CNSTI4 0 ASGNI4 line 309 ;309: levelMenuInfo.item_maps[3].shader = 0; ADDRGP4 levelMenuInfo+448+264+68 CNSTI4 0 ASGNI4 line 310 ;310: } ADDRGP4 $190 JUMPV LABELV $189 line 311 ;311: else { line 312 ;312: levelMenuInfo.item_maps[0].generic.x = 46; ADDRGP4 levelMenuInfo+448+12 CNSTI4 46 ASGNI4 line 313 ;313: Bitmap_Init( &levelMenuInfo.item_maps[0] ); ADDRGP4 levelMenuInfo+448 ARGP4 ADDRGP4 Bitmap_Init CALLV pop line 314 ;314: levelMenuInfo.item_maps[0].generic.bottom += 18; ADDRLP4 16 ADDRGP4 levelMenuInfo+448+32 ASGNP4 ADDRLP4 16 INDIRP4 ADDRLP4 16 INDIRP4 INDIRI4 CNSTI4 18 ADDI4 ASGNI4 line 315 ;315: levelMenuInfo.numMaps = 4; ADDRGP4 levelMenuInfo+1952 CNSTI4 4 ASGNI4 line 317 ;316: ;317: for ( n = 0; n < 4; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 LABELV $229 line 318 ;318: level = selectedArenaSet * ARENAS_PER_TIER + n; ADDRLP4 4 ADDRGP4 selectedArenaSet INDIRI4 CNSTI4 2 LSHI4 ADDRLP4 0 INDIRI4 ADDI4 ASGNI4 line 319 ;319: arenaInfo = UI_GetArenaInfoByNumber( level ); ADDRLP4 4 INDIRI4 ARGI4 ADDRLP4 20 ADDRGP4 UI_GetArenaInfoByNumber CALLP4 ASGNP4 ADDRLP4 8 ADDRLP4 20 INDIRP4 ASGNP4 line 320 ;320: UI_SPLevelMenu_SetMenuArena( n, level, arenaInfo ); ADDRLP4 0 INDIRI4 ARGI4 ADDRLP4 4 INDIRI4 ARGI4 ADDRLP4 8 INDIRP4 ARGP4 ADDRGP4 UI_SPLevelMenu_SetMenuArena CALLV pop line 321 ;321: } LABELV $230 line 317 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 4 LTI4 $229 line 323 ;322: ;323: if( selectedArena != -1 ) { ADDRGP4 selectedArena INDIRI4 CNSTI4 -1 EQI4 $233 line 324 ;324: levelMenuInfo.selectedArenaInfo = UI_GetArenaInfoByNumber( selectedArenaSet * ARENAS_PER_TIER + selectedArena ); ADDRGP4 selectedArenaSet INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 selectedArena INDIRI4 ADDI4 ARGI4 ADDRLP4 20 ADDRGP4 UI_GetArenaInfoByNumber CALLP4 ASGNP4 ADDRGP4 levelMenuInfo+1948 ADDRLP4 20 INDIRP4 ASGNP4 line 325 ;325: } LABELV $233 line 326 ;326: } LABELV $190 LABELV $155 line 329 ;327: ;328: // enable/disable arrows when they are valid/invalid ;329: if ( selectedArenaSet == minTier ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 minTier INDIRI4 NEI4 $236 line 330 ;330: levelMenuInfo.item_leftarrow.generic.flags |= ( QMF_INACTIVE | QMF_HIDDEN ); ADDRLP4 16 ADDRGP4 levelMenuInfo+360+44 ASGNP4 ADDRLP4 16 INDIRP4 ADDRLP4 16 INDIRP4 INDIRU4 CNSTU4 20480 BORU4 ASGNU4 line 331 ;331: } ADDRGP4 $237 JUMPV LABELV $236 line 332 ;332: else { line 333 ;333: levelMenuInfo.item_leftarrow.generic.flags &= ~( QMF_INACTIVE | QMF_HIDDEN ); ADDRLP4 16 ADDRGP4 levelMenuInfo+360+44 ASGNP4 ADDRLP4 16 INDIRP4 ADDRLP4 16 INDIRP4 INDIRU4 CNSTU4 4294946815 BANDU4 ASGNU4 line 334 ;334: } LABELV $237 line 336 ;335: ;336: if ( selectedArenaSet == maxTier ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 maxTier INDIRI4 NEI4 $242 line 337 ;337: levelMenuInfo.item_rightarrow.generic.flags |= ( QMF_INACTIVE | QMF_HIDDEN ); ADDRLP4 16 ADDRGP4 levelMenuInfo+800+44 ASGNP4 ADDRLP4 16 INDIRP4 ADDRLP4 16 INDIRP4 INDIRU4 CNSTU4 20480 BORU4 ASGNU4 line 338 ;338: } ADDRGP4 $243 JUMPV LABELV $242 line 339 ;339: else { line 340 ;340: levelMenuInfo.item_rightarrow.generic.flags &= ~( QMF_INACTIVE | QMF_HIDDEN ); ADDRLP4 16 ADDRGP4 levelMenuInfo+800+44 ASGNP4 ADDRLP4 16 INDIRP4 ADDRLP4 16 INDIRP4 INDIRU4 CNSTU4 4294946815 BANDU4 ASGNU4 line 341 ;341: } LABELV $243 line 343 ;342: ;343: UI_SPLevelMenu_SetBots(); ADDRGP4 UI_SPLevelMenu_SetBots CALLV pop line 344 ;344:} LABELV $143 endproc UI_SPLevelMenu_SetMenuItems 44 12 proc UI_SPLevelMenu_ResetDraw 0 20 line 352 ;345: ;346: ;347:/* ;348:================= ;349:UI_SPLevelMenu_ResetEvent ;350:================= ;351:*/ ;352:static void UI_SPLevelMenu_ResetDraw( void ) { line 353 ;353: UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 0, "WARNING: This resets all of the", UI_CENTER|UI_SMALLFONT, color_yellow ); CNSTI4 320 ARGI4 CNSTI4 356 ARGI4 ADDRGP4 $249 ARGP4 CNSTI4 17 ARGI4 ADDRGP4 color_yellow ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 354 ;354: UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 1, "single player game variables.", UI_CENTER|UI_SMALLFONT, color_yellow ); CNSTI4 320 ARGI4 CNSTI4 383 ARGI4 ADDRGP4 $250 ARGP4 CNSTI4 17 ARGI4 ADDRGP4 color_yellow ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 355 ;355: UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 2, "Do this only if you want to", UI_CENTER|UI_SMALLFONT, color_yellow ); CNSTI4 320 ARGI4 CNSTI4 410 ARGI4 ADDRGP4 $251 ARGP4 CNSTI4 17 ARGI4 ADDRGP4 color_yellow ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 356 ;356: UI_DrawProportionalString( SCREEN_WIDTH/2, 356 + PROP_HEIGHT * 3, "start over from the beginning.", UI_CENTER|UI_SMALLFONT, color_yellow ); CNSTI4 320 ARGI4 CNSTI4 437 ARGI4 ADDRGP4 $252 ARGP4 CNSTI4 17 ARGI4 ADDRGP4 color_yellow ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 357 ;357:} LABELV $248 endproc UI_SPLevelMenu_ResetDraw 0 20 proc UI_SPLevelMenu_ResetAction 0 8 line 359 ;358: ;359:static void UI_SPLevelMenu_ResetAction( qboolean result ) { line 360 ;360: if( !result ) { ADDRFP4 0 INDIRI4 CNSTI4 0 NEI4 $254 line 361 ;361: return; ADDRGP4 $253 JUMPV LABELV $254 line 365 ;362: } ;363: ;364: // clear game variables ;365: UI_NewGame(); ADDRGP4 UI_NewGame CALLV pop line 366 ;366: trap_Cvar_SetValue( "ui_spSelection", -4 ); ADDRGP4 $153 ARGP4 CNSTF4 3229614080 ARGF4 ADDRGP4 trap_Cvar_SetValue CALLV pop line 369 ;367: ;368: // make the level select menu re-initialize ;369: UI_PopMenu(); ADDRGP4 UI_PopMenu CALLV pop line 370 ;370: UI_SPLevelMenu(); ADDRGP4 UI_SPLevelMenu CALLV pop line 371 ;371:} LABELV $253 endproc UI_SPLevelMenu_ResetAction 0 8 proc UI_SPLevelMenu_ResetEvent 0 12 line 374 ;372: ;373:static void UI_SPLevelMenu_ResetEvent( void* ptr, int event ) ;374:{ line 375 ;375: if (event != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $257 line 376 ;376: return; ADDRGP4 $256 JUMPV LABELV $257 line 379 ;377: } ;378: ;379: UI_ConfirmMenu( "RESET GAME?", UI_SPLevelMenu_ResetDraw, UI_SPLevelMenu_ResetAction ); ADDRGP4 $259 ARGP4 ADDRGP4 UI_SPLevelMenu_ResetDraw ARGP4 ADDRGP4 UI_SPLevelMenu_ResetAction ARGP4 ADDRGP4 UI_ConfirmMenu CALLV pop line 380 ;380:} LABELV $256 endproc UI_SPLevelMenu_ResetEvent 0 12 proc UI_SPLevelMenu_LevelEvent 8 8 line 388 ;381: ;382: ;383:/* ;384:================= ;385:UI_SPLevelMenu_LevelEvent ;386:================= ;387:*/ ;388:static void UI_SPLevelMenu_LevelEvent( void* ptr, int notification ) { line 389 ;389: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $261 line 390 ;390: return; ADDRGP4 $260 JUMPV LABELV $261 line 393 ;391: } ;392: ;393: if ( selectedArenaSet == trainingTier || selectedArenaSet == finalTier ) { ADDRLP4 0 ADDRGP4 selectedArenaSet INDIRI4 ASGNI4 ADDRLP4 0 INDIRI4 ADDRGP4 trainingTier INDIRI4 EQI4 $265 ADDRLP4 0 INDIRI4 ADDRGP4 finalTier INDIRI4 NEI4 $263 LABELV $265 line 394 ;394: return; ADDRGP4 $260 JUMPV LABELV $263 line 397 ;395: } ;396: ;397: selectedArena = ((menucommon_s*)ptr)->id - ID_PICTURE0; ADDRGP4 selectedArena ADDRFP4 0 INDIRP4 CNSTI4 8 ADDP4 INDIRI4 CNSTI4 11 SUBI4 ASGNI4 line 398 ;398: levelMenuInfo.selectedArenaInfo = UI_GetArenaInfoByNumber( selectedArenaSet * ARENAS_PER_TIER + selectedArena ); ADDRGP4 selectedArenaSet INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 selectedArena INDIRI4 ADDI4 ARGI4 ADDRLP4 4 ADDRGP4 UI_GetArenaInfoByNumber CALLP4 ASGNP4 ADDRGP4 levelMenuInfo+1948 ADDRLP4 4 INDIRP4 ASGNP4 line 399 ;399: UI_SPLevelMenu_SetBots(); ADDRGP4 UI_SPLevelMenu_SetBots CALLV pop line 401 ;400: ;401: trap_Cvar_SetValue( "ui_spSelection", selectedArenaSet * ARENAS_PER_TIER + selectedArena ); ADDRGP4 $153 ARGP4 ADDRGP4 selectedArenaSet INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 selectedArena INDIRI4 ADDI4 CVIF4 4 ARGF4 ADDRGP4 trap_Cvar_SetValue CALLV pop line 402 ;402:} LABELV $260 endproc UI_SPLevelMenu_LevelEvent 8 8 proc UI_SPLevelMenu_LeftArrowEvent 4 0 line 410 ;403: ;404: ;405:/* ;406:================= ;407:UI_SPLevelMenu_LeftArrowEvent ;408:================= ;409:*/ ;410:static void UI_SPLevelMenu_LeftArrowEvent( void* ptr, int notification ) { line 411 ;411: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $268 line 412 ;412: return; ADDRGP4 $267 JUMPV LABELV $268 line 415 ;413: } ;414: ;415: if ( selectedArenaSet == minTier ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 minTier INDIRI4 NEI4 $270 line 416 ;416: return; ADDRGP4 $267 JUMPV LABELV $270 line 419 ;417: } ;418: ;419: selectedArenaSet--; ADDRLP4 0 ADDRGP4 selectedArenaSet ASGNP4 ADDRLP4 0 INDIRP4 ADDRLP4 0 INDIRP4 INDIRI4 CNSTI4 1 SUBI4 ASGNI4 line 420 ;420: UI_SPLevelMenu_SetMenuItems(); ADDRGP4 UI_SPLevelMenu_SetMenuItems CALLV pop line 421 ;421:} LABELV $267 endproc UI_SPLevelMenu_LeftArrowEvent 4 0 proc UI_SPLevelMenu_RightArrowEvent 4 0 line 429 ;422: ;423: ;424:/* ;425:================= ;426:UI_SPLevelMenu_RightArrowEvent ;427:================= ;428:*/ ;429:static void UI_SPLevelMenu_RightArrowEvent( void* ptr, int notification ) { line 430 ;430: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $273 line 431 ;431: return; ADDRGP4 $272 JUMPV LABELV $273 line 434 ;432: } ;433: ;434: if ( selectedArenaSet == maxTier ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 maxTier INDIRI4 NEI4 $275 line 435 ;435: return; ADDRGP4 $272 JUMPV LABELV $275 line 438 ;436: } ;437: ;438: selectedArenaSet++; ADDRLP4 0 ADDRGP4 selectedArenaSet ASGNP4 ADDRLP4 0 INDIRP4 ADDRLP4 0 INDIRP4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 line 439 ;439: UI_SPLevelMenu_SetMenuItems(); ADDRGP4 UI_SPLevelMenu_SetMenuItems CALLV pop line 440 ;440:} LABELV $272 endproc UI_SPLevelMenu_RightArrowEvent 4 0 proc UI_SPLevelMenu_PlayerEvent 0 0 line 448 ;441: ;442: ;443:/* ;444:================= ;445:UI_SPLevelMenu_PlayerEvent ;446:================= ;447:*/ ;448:static void UI_SPLevelMenu_PlayerEvent( void* ptr, int notification ) { line 449 ;449: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $278 line 450 ;450: return; ADDRGP4 $277 JUMPV LABELV $278 line 453 ;451: } ;452: ;453: UI_PlayerSettingsMenu(); ADDRGP4 UI_PlayerSettingsMenu CALLV pop line 454 ;454:} LABELV $277 endproc UI_SPLevelMenu_PlayerEvent 0 0 proc UI_SPLevelMenu_AwardEvent 4 8 line 462 ;455: ;456: ;457:/* ;458:================= ;459:UI_SPLevelMenu_AwardEvent ;460:================= ;461:*/ ;462:static void UI_SPLevelMenu_AwardEvent( void* ptr, int notification ) { line 465 ;463: int n; ;464: ;465: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $281 line 466 ;466: return; ADDRGP4 $280 JUMPV LABELV $281 line 469 ;467: } ;468: ;469: n = ((menucommon_s*)ptr)->id - ID_AWARD1; ADDRLP4 0 ADDRFP4 0 INDIRP4 CNSTI4 8 ADDP4 INDIRI4 CNSTI4 17 SUBI4 ASGNI4 line 470 ;470: trap_S_StartLocalSound( levelMenuInfo.awardSounds[n], CHAN_ANNOUNCER ); ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2488 ADDP4 INDIRI4 ARGI4 CNSTI4 7 ARGI4 ADDRGP4 trap_S_StartLocalSound CALLV pop line 471 ;471:} LABELV $280 endproc UI_SPLevelMenu_AwardEvent 4 8 proc UI_SPLevelMenu_NextEvent 0 4 line 479 ;472: ;473: ;474:/* ;475:================= ;476:UI_SPLevelMenu_NextEvent ;477:================= ;478:*/ ;479:static void UI_SPLevelMenu_NextEvent( void* ptr, int notification ) { line 480 ;480: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $285 line 481 ;481: return; ADDRGP4 $284 JUMPV LABELV $285 line 484 ;482: } ;483: ;484: if ( selectedArenaSet > currentSet ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 currentSet INDIRI4 LEI4 $287 line 485 ;485: return; ADDRGP4 $284 JUMPV LABELV $287 line 488 ;486: } ;487: ;488: if ( selectedArena == -1 ) { ADDRGP4 selectedArena INDIRI4 CNSTI4 -1 NEI4 $289 line 489 ;489: selectedArena = 0; ADDRGP4 selectedArena CNSTI4 0 ASGNI4 line 490 ;490: } LABELV $289 line 492 ;491: ;492: UI_SPSkillMenu( levelMenuInfo.selectedArenaInfo ); ADDRGP4 levelMenuInfo+1948 INDIRP4 ARGP4 ADDRGP4 UI_SPSkillMenu CALLV pop line 493 ;493:} LABELV $284 endproc UI_SPLevelMenu_NextEvent 0 4 proc UI_SPLevelMenu_BackEvent 0 0 line 501 ;494: ;495: ;496:/* ;497:================= ;498:UI_SPLevelMenu_BackEvent ;499:================= ;500:*/ ;501:static void UI_SPLevelMenu_BackEvent( void* ptr, int notification ) { line 502 ;502: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $293 line 503 ;503: return; ADDRGP4 $292 JUMPV LABELV $293 line 506 ;504: } ;505: ;506: if ( selectedArena == -1 ) { ADDRGP4 selectedArena INDIRI4 CNSTI4 -1 NEI4 $295 line 507 ;507: selectedArena = 0; ADDRGP4 selectedArena CNSTI4 0 ASGNI4 line 508 ;508: } LABELV $295 line 510 ;509: ;510: UI_PopMenu(); ADDRGP4 UI_PopMenu CALLV pop line 511 ;511:} LABELV $292 endproc UI_SPLevelMenu_BackEvent 0 0 proc UI_SPLevelMenu_CustomEvent 0 4 line 519 ;512: ;513: ;514:/* ;515:================= ;516:UI_SPLevelMenu_CustomEvent ;517:================= ;518:*/ ;519:static void UI_SPLevelMenu_CustomEvent( void* ptr, int notification ) { line 520 ;520: if (notification != QM_ACTIVATED) { ADDRFP4 4 INDIRI4 CNSTI4 3 EQI4 $298 line 521 ;521: return; ADDRGP4 $297 JUMPV LABELV $298 line 524 ;522: } ;523: ;524: UI_StartServerMenu( qfalse ); CNSTI4 0 ARGI4 ADDRGP4 UI_StartServerMenu CALLV pop line 525 ;525:} LABELV $297 endproc UI_SPLevelMenu_CustomEvent 0 4 proc UI_SPLevelMenu_MenuDraw 1152 20 line 535 ;526: ;527: ;528:/* ;529:================= ;530:UI_SPLevelMenu_MenuDraw ;531:================= ;532:*/ ;533:#define LEVEL_DESC_LEFT_MARGIN 332 ;534: ;535:static void UI_SPLevelMenu_MenuDraw( void ) { line 545 ;536: int n, i; ;537: int x, y; ;538: vec4_t color; ;539: int level; ;540:// int fraglimit; ;541: int pad; ;542: char buf[MAX_INFO_VALUE]; ;543: char string[64]; ;544: ;545: if( levelMenuInfo.reinit ) { ADDRGP4 levelMenuInfo+1944 INDIRI4 CNSTI4 0 EQI4 $301 line 546 ;546: UI_PopMenu(); ADDRGP4 UI_PopMenu CALLV pop line 547 ;547: UI_SPLevelMenu(); ADDRGP4 UI_SPLevelMenu CALLV pop line 548 ;548: return; ADDRGP4 $300 JUMPV LABELV $301 line 552 ;549: } ;550: ;551: // draw player name ;552: trap_Cvar_VariableStringBuffer( "name", string, 32 ); ADDRGP4 $106 ARGP4 ADDRLP4 16 ARGP4 CNSTI4 32 ARGI4 ADDRGP4 trap_Cvar_VariableStringBuffer CALLV pop line 553 ;553: Q_CleanStr( string ); ADDRLP4 16 ARGP4 ADDRGP4 Q_CleanStr CALLP4 pop line 554 ;554: UI_DrawProportionalString( 320, PLAYER_Y, string, UI_CENTER|UI_SMALLFONT, color_orange ); CNSTI4 320 ARGI4 CNSTI4 314 ARGI4 ADDRLP4 16 ARGP4 CNSTI4 17 ARGI4 ADDRGP4 color_orange ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 557 ;555: ;556: // check for model changes ;557: trap_Cvar_VariableStringBuffer( "model", buf, sizeof(buf) ); ADDRGP4 $103 ARGP4 ADDRLP4 104 ARGP4 CNSTI4 1024 ARGI4 ADDRGP4 trap_Cvar_VariableStringBuffer CALLV pop line 558 ;558: if( Q_stricmp( buf, levelMenuInfo.playerModel ) != 0 ) { ADDRLP4 104 ARGP4 ADDRGP4 levelMenuInfo+2336 ARGP4 ADDRLP4 1128 ADDRGP4 Q_stricmp CALLI4 ASGNI4 ADDRLP4 1128 INDIRI4 CNSTI4 0 EQI4 $304 line 559 ;559: Q_strncpyz( levelMenuInfo.playerModel, buf, sizeof(levelMenuInfo.playerModel) ); ADDRGP4 levelMenuInfo+2336 ARGP4 ADDRLP4 104 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 560 ;560: PlayerIcon( levelMenuInfo.playerModel, levelMenuInfo.playerPicName, sizeof(levelMenuInfo.playerPicName) ); ADDRGP4 levelMenuInfo+2336 ARGP4 ADDRGP4 levelMenuInfo+2400 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 PlayerIcon CALLV pop line 561 ;561: levelMenuInfo.item_player.shader = 0; ADDRGP4 levelMenuInfo+888+68 CNSTI4 0 ASGNI4 line 562 ;562: } LABELV $304 line 565 ;563: ;564: // standard menu drawing ;565: Menu_Draw( &levelMenuInfo.menu ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 Menu_Draw CALLV pop line 568 ;566: ;567: // draw player award levels ;568: y = AWARDS_Y; ADDRLP4 8 CNSTI4 340 ASGNI4 line 569 ;569: i = 0; ADDRLP4 80 CNSTI4 0 ASGNI4 line 570 ;570: for( n = 0; n < 6; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 LABELV $314 line 571 ;571: level = levelMenuInfo.awardLevels[n]; ADDRLP4 12 ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2464 ADDP4 INDIRI4 ASGNI4 line 572 ;572: if( level > 0 ) { ADDRLP4 12 INDIRI4 CNSTI4 0 LEI4 $319 line 573 ;573: if( i & 1 ) { ADDRLP4 80 INDIRI4 CNSTI4 1 BANDI4 CNSTI4 0 EQI4 $321 line 574 ;574: x = 224 - (i - 1 ) / 2 * (48 + 16); ADDRLP4 4 CNSTI4 224 ADDRLP4 80 INDIRI4 CNSTI4 1 SUBI4 CNSTI4 2 DIVI4 CNSTI4 6 LSHI4 SUBI4 ASGNI4 line 575 ;575: } ADDRGP4 $322 JUMPV LABELV $321 line 576 ;576: else { line 577 ;577: x = 368 + i / 2 * (48 + 16); ADDRLP4 4 ADDRLP4 80 INDIRI4 CNSTI4 2 DIVI4 CNSTI4 6 LSHI4 CNSTI4 368 ADDI4 ASGNI4 line 578 ;578: } LABELV $322 line 579 ;579: i++; ADDRLP4 80 ADDRLP4 80 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 line 581 ;580: ;581: if( level == 1 ) { ADDRLP4 12 INDIRI4 CNSTI4 1 NEI4 $323 line 582 ;582: continue; ADDRGP4 $315 JUMPV LABELV $323 line 585 ;583: } ;584: ;585: if( level >= 1000000 ) { ADDRLP4 12 INDIRI4 CNSTI4 1000000 LTI4 $325 line 586 ;586: Com_sprintf( string, sizeof(string), "%im", level / 1000000 ); ADDRLP4 16 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 $327 ARGP4 ADDRLP4 12 INDIRI4 CNSTI4 1000000 DIVI4 ARGI4 ADDRGP4 Com_sprintf CALLV pop line 587 ;587: } ADDRGP4 $326 JUMPV LABELV $325 line 588 ;588: else if( level >= 1000 ) { ADDRLP4 12 INDIRI4 CNSTI4 1000 LTI4 $328 line 589 ;589: Com_sprintf( string, sizeof(string), "%ik", level / 1000 ); ADDRLP4 16 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 $330 ARGP4 ADDRLP4 12 INDIRI4 CNSTI4 1000 DIVI4 ARGI4 ADDRGP4 Com_sprintf CALLV pop line 590 ;590: } ADDRGP4 $329 JUMPV LABELV $328 line 591 ;591: else { line 592 ;592: Com_sprintf( string, sizeof(string), "%i", level ); ADDRLP4 16 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 $331 ARGP4 ADDRLP4 12 INDIRI4 ARGI4 ADDRGP4 Com_sprintf CALLV pop line 593 ;593: } LABELV $329 LABELV $326 line 595 ;594: ;595: UI_DrawString( x + 24, y + 48, string, UI_CENTER, color_yellow ); ADDRLP4 4 INDIRI4 CNSTI4 24 ADDI4 ARGI4 ADDRLP4 8 INDIRI4 CNSTI4 48 ADDI4 ARGI4 ADDRLP4 16 ARGP4 CNSTI4 1 ARGI4 ADDRGP4 color_yellow ARGP4 ADDRGP4 UI_DrawString CALLV pop line 596 ;596: } LABELV $319 line 597 ;597: } LABELV $315 line 570 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 6 LTI4 $314 line 599 ;598: ;599: UI_DrawProportionalString( 18, 38, va( "Tier %i", selectedArenaSet + 1 ), UI_LEFT|UI_SMALLFONT, color_orange ); ADDRGP4 $332 ARGP4 ADDRGP4 selectedArenaSet INDIRI4 CNSTI4 1 ADDI4 ARGI4 ADDRLP4 1132 ADDRGP4 va CALLP4 ASGNP4 CNSTI4 18 ARGI4 CNSTI4 38 ARGI4 ADDRLP4 1132 INDIRP4 ARGP4 CNSTI4 16 ARGI4 ADDRGP4 color_orange ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 601 ;600: ;601: for ( n = 0; n < levelMenuInfo.numMaps; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $336 JUMPV LABELV $333 line 602 ;602: x = levelMenuInfo.item_maps[n].generic.x; ADDRLP4 4 CNSTI4 88 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+12 ADDP4 INDIRI4 ASGNI4 line 603 ;603: y = levelMenuInfo.item_maps[n].generic.y; ADDRLP4 8 CNSTI4 88 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+16 ADDP4 INDIRI4 ASGNI4 line 604 ;604: UI_FillRect( x, y + 96, 128, 18, color_black ); ADDRLP4 4 INDIRI4 CVIF4 4 ARGF4 ADDRLP4 8 INDIRI4 CNSTI4 96 ADDI4 CVIF4 4 ARGF4 CNSTF4 1124073472 ARGF4 CNSTF4 1099956224 ARGF4 ADDRGP4 color_black ARGP4 ADDRGP4 UI_FillRect CALLV pop line 605 ;605: } LABELV $334 line 601 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $336 ADDRLP4 0 INDIRI4 ADDRGP4 levelMenuInfo+1952 INDIRI4 LTI4 $333 line 607 ;606: ;607: if ( selectedArenaSet > currentSet ) { ADDRGP4 selectedArenaSet INDIRI4 ADDRGP4 currentSet INDIRI4 LEI4 $342 line 608 ;608: UI_DrawProportionalString( 320, 216, "ACCESS DENIED", UI_CENTER|UI_BIGFONT, color_red ); CNSTI4 320 ARGI4 CNSTI4 216 ARGI4 ADDRGP4 $344 ARGP4 CNSTI4 33 ARGI4 ADDRGP4 color_red ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 609 ;609: return; ADDRGP4 $300 JUMPV LABELV $342 line 613 ;610: } ;611: ;612: // show levelshots for levels of current tier ;613: Vector4Copy( color_white, color ); ADDRLP4 88 ADDRGP4 color_white INDIRF4 ASGNF4 ADDRLP4 88+4 ADDRGP4 color_white+4 INDIRF4 ASGNF4 ADDRLP4 88+8 ADDRGP4 color_white+8 INDIRF4 ASGNF4 ADDRLP4 88+12 ADDRGP4 color_white+12 INDIRF4 ASGNF4 line 614 ;614: color[3] = 0.5+0.5*sin(uis.realtime/PULSE_DIVISOR); ADDRGP4 uis+4 INDIRI4 CNSTI4 75 DIVI4 CVIF4 4 ARGF4 ADDRLP4 1136 ADDRGP4 sin CALLF4 ASGNF4 ADDRLP4 88+12 CNSTF4 1056964608 ADDRLP4 1136 INDIRF4 MULF4 CNSTF4 1056964608 ADDF4 ASGNF4 line 615 ;615: for ( n = 0; n < levelMenuInfo.numMaps; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $356 JUMPV LABELV $353 line 616 ;616: x = levelMenuInfo.item_maps[n].generic.x; ADDRLP4 4 CNSTI4 88 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+12 ADDP4 INDIRI4 ASGNI4 line 617 ;617: y = levelMenuInfo.item_maps[n].generic.y; ADDRLP4 8 CNSTI4 88 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448+16 ADDP4 INDIRI4 ASGNI4 line 619 ;618: ;619: UI_DrawString( x + 64, y + 96, levelMenuInfo.levelNames[n], UI_CENTER|UI_SMALLFONT, color_orange ); ADDRLP4 4 INDIRI4 CNSTI4 64 ADDI4 ARGI4 ADDRLP4 8 INDIRI4 CNSTI4 96 ADDI4 ARGI4 ADDRLP4 0 INDIRI4 CNSTI4 4 LSHI4 ADDRGP4 levelMenuInfo+2212 ADDP4 ARGP4 CNSTI4 17 ARGI4 ADDRGP4 color_orange ARGP4 ADDRGP4 UI_DrawString CALLV pop line 621 ;620: ;621: if( levelMenuInfo.levelScores[n] == 1 ) { ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2276 ADDP4 INDIRI4 CNSTI4 1 NEI4 $363 line 622 ;622: UI_DrawHandlePic( x, y, 128, 96, levelMenuInfo.levelCompletePic[levelMenuInfo.levelScoresSkill[n] - 1] ); ADDRLP4 4 INDIRI4 CVIF4 4 ARGF4 ADDRLP4 8 INDIRI4 CVIF4 4 ARGF4 CNSTF4 1124073472 ARGF4 CNSTF4 1119879168 ARGF4 ADDRLP4 1140 CNSTI4 2 ASGNI4 ADDRLP4 0 INDIRI4 ADDRLP4 1140 INDIRI4 LSHI4 ADDRGP4 levelMenuInfo+2292 ADDP4 INDIRI4 ADDRLP4 1140 INDIRI4 LSHI4 ADDRGP4 levelMenuInfo+2316-4 ADDP4 INDIRI4 ARGI4 ADDRGP4 UI_DrawHandlePic CALLV pop line 623 ;623: } LABELV $363 line 625 ;624: ;625: if ( n == selectedArena ) { ADDRLP4 0 INDIRI4 ADDRGP4 selectedArena INDIRI4 NEI4 $369 line 626 ;626: if( Menu_ItemAtCursor( &levelMenuInfo.menu ) == &levelMenuInfo.item_maps[n] ) { ADDRGP4 levelMenuInfo ARGP4 ADDRLP4 1140 ADDRGP4 Menu_ItemAtCursor CALLP4 ASGNP4 CNSTI4 88 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448 ADDP4 CVPU4 4 ADDRLP4 1140 INDIRP4 CVPU4 4 NEU4 $371 line 627 ;627: trap_R_SetColor( color ); ADDRLP4 88 ARGP4 ADDRGP4 trap_R_SetColor CALLV pop line 628 ;628: } LABELV $371 line 629 ;629: UI_DrawHandlePic( x-1, y-1, 130, 130 - 14, levelMenuInfo.levelSelectedPic ); ADDRLP4 1144 CNSTI4 1 ASGNI4 ADDRLP4 4 INDIRI4 ADDRLP4 1144 INDIRI4 SUBI4 CVIF4 4 ARGF4 ADDRLP4 8 INDIRI4 ADDRLP4 1144 INDIRI4 SUBI4 CVIF4 4 ARGF4 CNSTF4 1124204544 ARGF4 CNSTF4 1122500608 ARGF4 ADDRGP4 levelMenuInfo+2308 INDIRI4 ARGI4 ADDRGP4 UI_DrawHandlePic CALLV pop line 630 ;630: trap_R_SetColor( NULL ); CNSTP4 0 ARGP4 ADDRGP4 trap_R_SetColor CALLV pop line 631 ;631: } ADDRGP4 $370 JUMPV LABELV $369 line 632 ;632: else if( Menu_ItemAtCursor( &levelMenuInfo.menu ) == &levelMenuInfo.item_maps[n] ) { ADDRGP4 levelMenuInfo ARGP4 ADDRLP4 1140 ADDRGP4 Menu_ItemAtCursor CALLP4 ASGNP4 CNSTI4 88 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+448 ADDP4 CVPU4 4 ADDRLP4 1140 INDIRP4 CVPU4 4 NEU4 $375 line 633 ;633: trap_R_SetColor( color ); ADDRLP4 88 ARGP4 ADDRGP4 trap_R_SetColor CALLV pop line 634 ;634: UI_DrawHandlePic( x-31, y-30, 256, 256-27, levelMenuInfo.levelFocusPic); ADDRLP4 4 INDIRI4 CNSTI4 31 SUBI4 CVIF4 4 ARGF4 ADDRLP4 8 INDIRI4 CNSTI4 30 SUBI4 CVIF4 4 ARGF4 CNSTF4 1132462080 ARGF4 CNSTF4 1130692608 ARGF4 ADDRGP4 levelMenuInfo+2312 INDIRI4 ARGI4 ADDRGP4 UI_DrawHandlePic CALLV pop line 635 ;635: trap_R_SetColor( NULL ); CNSTP4 0 ARGP4 ADDRGP4 trap_R_SetColor CALLV pop line 636 ;636: } LABELV $375 LABELV $370 line 637 ;637: } LABELV $354 line 615 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $356 ADDRLP4 0 INDIRI4 ADDRGP4 levelMenuInfo+1952 INDIRI4 LTI4 $353 line 640 ;638: ;639: // show map name and long name of selected level ;640: y = 192; ADDRLP4 8 CNSTI4 192 ASGNI4 line 641 ;641: Q_strncpyz( buf, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "map" ), 20 ); ADDRGP4 levelMenuInfo+1948 INDIRP4 ARGP4 ADDRGP4 $116 ARGP4 ADDRLP4 1140 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 104 ARGP4 ADDRLP4 1140 INDIRP4 ARGP4 CNSTI4 20 ARGI4 ADDRGP4 Q_strncpyz CALLV pop line 642 ;642: Q_strupr( buf ); ADDRLP4 104 ARGP4 ADDRGP4 Q_strupr CALLP4 pop line 643 ;643: Com_sprintf( string, sizeof(string), "%s: %s", buf, Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "longname" ) ); ADDRGP4 levelMenuInfo+1948 INDIRP4 ARGP4 ADDRGP4 $382 ARGP4 ADDRLP4 1144 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 16 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 $380 ARGP4 ADDRLP4 104 ARGP4 ADDRLP4 1144 INDIRP4 ARGP4 ADDRGP4 Com_sprintf CALLV pop line 644 ;644: UI_DrawProportionalString( 320, y, string, UI_CENTER|UI_SMALLFONT, color_orange ); CNSTI4 320 ARGI4 ADDRLP4 8 INDIRI4 ARGI4 ADDRLP4 16 ARGP4 CNSTI4 17 ARGI4 ADDRGP4 color_orange ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 650 ;645: ;646:// fraglimit = atoi( Info_ValueForKey( levelMenuInfo.selectedArenaInfo, "fraglimit" ) ); ;647:// UI_DrawString( 18, 212, va("Frags %i", fraglimit) , UI_LEFT|UI_SMALLFONT, color_orange ); ;648: ;649: // draw bot opponents ;650: y += 24; ADDRLP4 8 ADDRLP4 8 INDIRI4 CNSTI4 24 ADDI4 ASGNI4 line 651 ;651: pad = (7 - levelMenuInfo.numBots) * (64 + 26) / 2; ADDRLP4 84 CNSTI4 90 CNSTI4 7 ADDRGP4 levelMenuInfo+2512 INDIRI4 SUBI4 MULI4 CNSTI4 2 DIVI4 ASGNI4 line 652 ;652: for( n = 0; n < levelMenuInfo.numBots; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $387 JUMPV LABELV $384 line 653 ;653: x = 18 + pad + (64 + 26) * n; ADDRLP4 4 ADDRLP4 84 INDIRI4 CNSTI4 18 ADDI4 CNSTI4 90 ADDRLP4 0 INDIRI4 MULI4 ADDI4 ASGNI4 line 654 ;654: if( levelMenuInfo.botPics[n] ) { ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2516 ADDP4 INDIRI4 CNSTI4 0 EQI4 $389 line 655 ;655: UI_DrawHandlePic( x, y, 64, 64, levelMenuInfo.botPics[n]); ADDRLP4 4 INDIRI4 CVIF4 4 ARGF4 ADDRLP4 8 INDIRI4 CVIF4 4 ARGF4 ADDRLP4 1148 CNSTF4 1115684864 ASGNF4 ADDRLP4 1148 INDIRF4 ARGF4 ADDRLP4 1148 INDIRF4 ARGF4 ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2516 ADDP4 INDIRI4 ARGI4 ADDRGP4 UI_DrawHandlePic CALLV pop line 656 ;656: } ADDRGP4 $390 JUMPV LABELV $389 line 657 ;657: else { line 658 ;658: UI_FillRect( x, y, 64, 64, color_black ); ADDRLP4 4 INDIRI4 CVIF4 4 ARGF4 ADDRLP4 8 INDIRI4 CVIF4 4 ARGF4 ADDRLP4 1148 CNSTF4 1115684864 ASGNF4 ADDRLP4 1148 INDIRF4 ARGF4 ADDRLP4 1148 INDIRF4 ARGF4 ADDRGP4 color_black ARGP4 ADDRGP4 UI_FillRect CALLV pop line 659 ;659: UI_DrawProportionalString( x+22, y+18, "?", UI_BIGFONT, color_orange ); ADDRLP4 4 INDIRI4 CNSTI4 22 ADDI4 ARGI4 ADDRLP4 8 INDIRI4 CNSTI4 18 ADDI4 ARGI4 ADDRGP4 $393 ARGP4 CNSTI4 32 ARGI4 ADDRGP4 color_orange ARGP4 ADDRGP4 UI_DrawProportionalString CALLV pop line 660 ;660: } LABELV $390 line 661 ;661: UI_DrawString( x, y + 64, levelMenuInfo.botNames[n], UI_SMALLFONT|UI_LEFT, color_orange ); ADDRLP4 4 INDIRI4 ARGI4 ADDRLP4 8 INDIRI4 CNSTI4 64 ADDI4 ARGI4 CNSTI4 10 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+2544 ADDP4 ARGP4 CNSTI4 16 ARGI4 ADDRGP4 color_orange ARGP4 ADDRGP4 UI_DrawString CALLV pop line 662 ;662: } LABELV $385 line 652 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $387 ADDRLP4 0 INDIRI4 ADDRGP4 levelMenuInfo+2512 INDIRI4 LTI4 $384 line 663 ;663:} LABELV $300 endproc UI_SPLevelMenu_MenuDraw 1152 20 export UI_SPLevelMenu_Cache proc UI_SPLevelMenu_Cache 32 8 line 671 ;664: ;665: ;666:/* ;667:================= ;668:UI_SPLevelMenu_Cache ;669:================= ;670:*/ ;671:void UI_SPLevelMenu_Cache( void ) { line 674 ;672: int n; ;673: ;674: trap_R_RegisterShaderNoMip( ART_LEVELFRAME_FOCUS ); ADDRGP4 $396 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 675 ;675: trap_R_RegisterShaderNoMip( ART_LEVELFRAME_SELECTED ); ADDRGP4 $397 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 676 ;676: trap_R_RegisterShaderNoMip( ART_ARROW ); ADDRGP4 $398 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 677 ;677: trap_R_RegisterShaderNoMip( ART_ARROW_FOCUS ); ADDRGP4 $399 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 678 ;678: trap_R_RegisterShaderNoMip( ART_MAP_UNKNOWN ); ADDRGP4 $132 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 679 ;679: trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE1 ); ADDRGP4 $400 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 680 ;680: trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE2 ); ADDRGP4 $401 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 681 ;681: trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE3 ); ADDRGP4 $402 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 682 ;682: trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE4 ); ADDRGP4 $403 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 683 ;683: trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE5 ); ADDRGP4 $404 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 684 ;684: trap_R_RegisterShaderNoMip( ART_BACK0 ); ADDRGP4 $405 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 685 ;685: trap_R_RegisterShaderNoMip( ART_BACK1 ); ADDRGP4 $406 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 686 ;686: trap_R_RegisterShaderNoMip( ART_FIGHT0 ); ADDRGP4 $407 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 687 ;687: trap_R_RegisterShaderNoMip( ART_FIGHT1 ); ADDRGP4 $408 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 688 ;688: trap_R_RegisterShaderNoMip( ART_RESET0 ); ADDRGP4 $409 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 689 ;689: trap_R_RegisterShaderNoMip( ART_RESET1 ); ADDRGP4 $410 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 690 ;690: trap_R_RegisterShaderNoMip( ART_CUSTOM0 ); ADDRGP4 $411 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 691 ;691: trap_R_RegisterShaderNoMip( ART_CUSTOM1 ); ADDRGP4 $412 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 693 ;692: ;693: for( n = 0; n < 6; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 LABELV $413 line 694 ;694: trap_R_RegisterShaderNoMip( ui_medalPicNames[n] ); ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 ui_medalPicNames ADDP4 INDIRP4 ARGP4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 pop line 695 ;695: levelMenuInfo.awardSounds[n] = trap_S_RegisterSound( ui_medalSounds[n], qfalse ); ADDRLP4 4 ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ASGNI4 ADDRLP4 4 INDIRI4 ADDRGP4 ui_medalSounds ADDP4 INDIRP4 ARGP4 CNSTI4 0 ARGI4 ADDRLP4 8 ADDRGP4 trap_S_RegisterSound CALLI4 ASGNI4 ADDRLP4 4 INDIRI4 ADDRGP4 levelMenuInfo+2488 ADDP4 ADDRLP4 8 INDIRI4 ASGNI4 line 696 ;696: } LABELV $414 line 693 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 6 LTI4 $413 line 698 ;697: ;698: levelMenuInfo.levelSelectedPic = trap_R_RegisterShaderNoMip( ART_LEVELFRAME_SELECTED ); ADDRGP4 $397 ARGP4 ADDRLP4 4 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2308 ADDRLP4 4 INDIRI4 ASGNI4 line 699 ;699: levelMenuInfo.levelFocusPic = trap_R_RegisterShaderNoMip( ART_LEVELFRAME_FOCUS ); ADDRGP4 $396 ARGP4 ADDRLP4 8 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2312 ADDRLP4 8 INDIRI4 ASGNI4 line 700 ;700: levelMenuInfo.levelCompletePic[0] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE1 ); ADDRGP4 $400 ARGP4 ADDRLP4 12 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2316 ADDRLP4 12 INDIRI4 ASGNI4 line 701 ;701: levelMenuInfo.levelCompletePic[1] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE2 ); ADDRGP4 $401 ARGP4 ADDRLP4 16 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2316+4 ADDRLP4 16 INDIRI4 ASGNI4 line 702 ;702: levelMenuInfo.levelCompletePic[2] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE3 ); ADDRGP4 $402 ARGP4 ADDRLP4 20 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2316+8 ADDRLP4 20 INDIRI4 ASGNI4 line 703 ;703: levelMenuInfo.levelCompletePic[3] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE4 ); ADDRGP4 $403 ARGP4 ADDRLP4 24 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2316+12 ADDRLP4 24 INDIRI4 ASGNI4 line 704 ;704: levelMenuInfo.levelCompletePic[4] = trap_R_RegisterShaderNoMip( ART_MAP_COMPLETE5 ); ADDRGP4 $404 ARGP4 ADDRLP4 28 ADDRGP4 trap_R_RegisterShaderNoMip CALLI4 ASGNI4 ADDRGP4 levelMenuInfo+2316+16 ADDRLP4 28 INDIRI4 ASGNI4 line 705 ;705:} LABELV $395 endproc UI_SPLevelMenu_Cache 32 8 proc UI_SPLevelMenu_Init 116 12 line 713 ;706: ;707: ;708:/* ;709:================= ;710:UI_SPLevelMenu_Init ;711:================= ;712:*/ ;713:static void UI_SPLevelMenu_Init( void ) { line 720 ;714: int skill; ;715: int n; ;716: int x, y; ;717: int count; ;718: char buf[MAX_QPATH]; ;719: ;720: skill = (int)trap_Cvar_VariableValue( "g_spSkill" ); ADDRGP4 $430 ARGP4 ADDRLP4 84 ADDRGP4 trap_Cvar_VariableValue CALLF4 ASGNF4 ADDRLP4 16 ADDRLP4 84 INDIRF4 CVFI4 4 ASGNI4 line 721 ;721: if( skill < 1 || skill > 5 ) { ADDRLP4 16 INDIRI4 CNSTI4 1 LTI4 $433 ADDRLP4 16 INDIRI4 CNSTI4 5 LEI4 $431 LABELV $433 line 722 ;722: trap_Cvar_Set( "g_spSkill", "2" ); ADDRGP4 $430 ARGP4 ADDRGP4 $434 ARGP4 ADDRGP4 trap_Cvar_Set CALLV pop line 723 ;723: skill = 2; ADDRLP4 16 CNSTI4 2 ASGNI4 line 724 ;724: } LABELV $431 line 726 ;725: ;726: memset( &levelMenuInfo, 0, sizeof(levelMenuInfo) ); ADDRGP4 levelMenuInfo ARGP4 CNSTI4 0 ARGI4 CNSTI4 2616 ARGI4 ADDRGP4 memset CALLP4 pop line 727 ;727: levelMenuInfo.menu.fullscreen = qtrue; ADDRGP4 levelMenuInfo+280 CNSTI4 1 ASGNI4 line 728 ;728: levelMenuInfo.menu.wrapAround = qtrue; ADDRGP4 levelMenuInfo+276 CNSTI4 1 ASGNI4 line 729 ;729: levelMenuInfo.menu.draw = UI_SPLevelMenu_MenuDraw; ADDRGP4 levelMenuInfo+268 ADDRGP4 UI_SPLevelMenu_MenuDraw ASGNP4 line 731 ;730: ;731: UI_SPLevelMenu_Cache(); ADDRGP4 UI_SPLevelMenu_Cache CALLV pop line 733 ;732: ;733: levelMenuInfo.item_banner.generic.type = MTYPE_BTEXT; ADDRGP4 levelMenuInfo+288 CNSTI4 10 ASGNI4 line 734 ;734: levelMenuInfo.item_banner.generic.x = 320; ADDRGP4 levelMenuInfo+288+12 CNSTI4 320 ASGNI4 line 735 ;735: levelMenuInfo.item_banner.generic.y = 16; ADDRGP4 levelMenuInfo+288+16 CNSTI4 16 ASGNI4 line 736 ;736: levelMenuInfo.item_banner.string = "CHOOSE LEVEL"; ADDRGP4 levelMenuInfo+288+60 ADDRGP4 $445 ASGNP4 line 737 ;737: levelMenuInfo.item_banner.color = color_red; ADDRGP4 levelMenuInfo+288+68 ADDRGP4 color_red ASGNP4 line 738 ;738: levelMenuInfo.item_banner.style = UI_CENTER; ADDRGP4 levelMenuInfo+288+64 CNSTI4 1 ASGNI4 line 740 ;739: ;740: levelMenuInfo.item_leftarrow.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+360 CNSTI4 6 ASGNI4 line 741 ;741: levelMenuInfo.item_leftarrow.generic.name = ART_ARROW; ADDRGP4 levelMenuInfo+360+4 ADDRGP4 $398 ASGNP4 line 742 ;742: levelMenuInfo.item_leftarrow.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; ADDRGP4 levelMenuInfo+360+44 CNSTU4 260 ASGNU4 line 743 ;743: levelMenuInfo.item_leftarrow.generic.x = 18; ADDRGP4 levelMenuInfo+360+12 CNSTI4 18 ASGNI4 line 744 ;744: levelMenuInfo.item_leftarrow.generic.y = 64; ADDRGP4 levelMenuInfo+360+16 CNSTI4 64 ASGNI4 line 745 ;745: levelMenuInfo.item_leftarrow.generic.callback = UI_SPLevelMenu_LeftArrowEvent; ADDRGP4 levelMenuInfo+360+48 ADDRGP4 UI_SPLevelMenu_LeftArrowEvent ASGNP4 line 746 ;746: levelMenuInfo.item_leftarrow.generic.id = ID_LEFTARROW; ADDRGP4 levelMenuInfo+360+8 CNSTI4 10 ASGNI4 line 747 ;747: levelMenuInfo.item_leftarrow.width = 16; ADDRGP4 levelMenuInfo+360+76 CNSTI4 16 ASGNI4 line 748 ;748: levelMenuInfo.item_leftarrow.height = 114; ADDRGP4 levelMenuInfo+360+80 CNSTI4 114 ASGNI4 line 749 ;749: levelMenuInfo.item_leftarrow.focuspic = ART_ARROW_FOCUS; ADDRGP4 levelMenuInfo+360+60 ADDRGP4 $399 ASGNP4 line 751 ;750: ;751: levelMenuInfo.item_maps[0].generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+448 CNSTI4 6 ASGNI4 line 752 ;752: levelMenuInfo.item_maps[0].generic.name = levelMenuInfo.levelPicNames[0]; ADDRGP4 levelMenuInfo+448+4 ADDRGP4 levelMenuInfo+1956 ASGNP4 line 753 ;753: levelMenuInfo.item_maps[0].generic.flags = QMF_LEFT_JUSTIFY; ADDRGP4 levelMenuInfo+448+44 CNSTU4 4 ASGNU4 line 754 ;754: levelMenuInfo.item_maps[0].generic.x = 46; ADDRGP4 levelMenuInfo+448+12 CNSTI4 46 ASGNI4 line 755 ;755: levelMenuInfo.item_maps[0].generic.y = 64; ADDRGP4 levelMenuInfo+448+16 CNSTI4 64 ASGNI4 line 756 ;756: levelMenuInfo.item_maps[0].generic.id = ID_PICTURE0; ADDRGP4 levelMenuInfo+448+8 CNSTI4 11 ASGNI4 line 757 ;757: levelMenuInfo.item_maps[0].generic.callback = UI_SPLevelMenu_LevelEvent; ADDRGP4 levelMenuInfo+448+48 ADDRGP4 UI_SPLevelMenu_LevelEvent ASGNP4 line 758 ;758: levelMenuInfo.item_maps[0].width = 128; ADDRGP4 levelMenuInfo+448+76 CNSTI4 128 ASGNI4 line 759 ;759: levelMenuInfo.item_maps[0].height = 96; ADDRGP4 levelMenuInfo+448+80 CNSTI4 96 ASGNI4 line 761 ;760: ;761: levelMenuInfo.item_maps[1].generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+448+88 CNSTI4 6 ASGNI4 line 762 ;762: levelMenuInfo.item_maps[1].generic.name = levelMenuInfo.levelPicNames[1]; ADDRGP4 levelMenuInfo+448+88+4 ADDRGP4 levelMenuInfo+1956+64 ASGNP4 line 763 ;763: levelMenuInfo.item_maps[1].generic.flags = QMF_LEFT_JUSTIFY; ADDRGP4 levelMenuInfo+448+88+44 CNSTU4 4 ASGNU4 line 764 ;764: levelMenuInfo.item_maps[1].generic.x = 186; ADDRGP4 levelMenuInfo+448+88+12 CNSTI4 186 ASGNI4 line 765 ;765: levelMenuInfo.item_maps[1].generic.y = 64; ADDRGP4 levelMenuInfo+448+88+16 CNSTI4 64 ASGNI4 line 766 ;766: levelMenuInfo.item_maps[1].generic.id = ID_PICTURE1; ADDRGP4 levelMenuInfo+448+88+8 CNSTI4 12 ASGNI4 line 767 ;767: levelMenuInfo.item_maps[1].generic.callback = UI_SPLevelMenu_LevelEvent; ADDRGP4 levelMenuInfo+448+88+48 ADDRGP4 UI_SPLevelMenu_LevelEvent ASGNP4 line 768 ;768: levelMenuInfo.item_maps[1].width = 128; ADDRGP4 levelMenuInfo+448+88+76 CNSTI4 128 ASGNI4 line 769 ;769: levelMenuInfo.item_maps[1].height = 96; ADDRGP4 levelMenuInfo+448+88+80 CNSTI4 96 ASGNI4 line 771 ;770: ;771: levelMenuInfo.item_maps[2].generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+448+176 CNSTI4 6 ASGNI4 line 772 ;772: levelMenuInfo.item_maps[2].generic.name = levelMenuInfo.levelPicNames[2]; ADDRGP4 levelMenuInfo+448+176+4 ADDRGP4 levelMenuInfo+1956+128 ASGNP4 line 773 ;773: levelMenuInfo.item_maps[2].generic.flags = QMF_LEFT_JUSTIFY; ADDRGP4 levelMenuInfo+448+176+44 CNSTU4 4 ASGNU4 line 774 ;774: levelMenuInfo.item_maps[2].generic.x = 326; ADDRGP4 levelMenuInfo+448+176+12 CNSTI4 326 ASGNI4 line 775 ;775: levelMenuInfo.item_maps[2].generic.y = 64; ADDRGP4 levelMenuInfo+448+176+16 CNSTI4 64 ASGNI4 line 776 ;776: levelMenuInfo.item_maps[2].generic.id = ID_PICTURE2; ADDRGP4 levelMenuInfo+448+176+8 CNSTI4 13 ASGNI4 line 777 ;777: levelMenuInfo.item_maps[2].generic.callback = UI_SPLevelMenu_LevelEvent; ADDRGP4 levelMenuInfo+448+176+48 ADDRGP4 UI_SPLevelMenu_LevelEvent ASGNP4 line 778 ;778: levelMenuInfo.item_maps[2].width = 128; ADDRGP4 levelMenuInfo+448+176+76 CNSTI4 128 ASGNI4 line 779 ;779: levelMenuInfo.item_maps[2].height = 96; ADDRGP4 levelMenuInfo+448+176+80 CNSTI4 96 ASGNI4 line 781 ;780: ;781: levelMenuInfo.item_maps[3].generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+448+264 CNSTI4 6 ASGNI4 line 782 ;782: levelMenuInfo.item_maps[3].generic.name = levelMenuInfo.levelPicNames[3]; ADDRGP4 levelMenuInfo+448+264+4 ADDRGP4 levelMenuInfo+1956+192 ASGNP4 line 783 ;783: levelMenuInfo.item_maps[3].generic.flags = QMF_LEFT_JUSTIFY; ADDRGP4 levelMenuInfo+448+264+44 CNSTU4 4 ASGNU4 line 784 ;784: levelMenuInfo.item_maps[3].generic.x = 466; ADDRGP4 levelMenuInfo+448+264+12 CNSTI4 466 ASGNI4 line 785 ;785: levelMenuInfo.item_maps[3].generic.y = 64; ADDRGP4 levelMenuInfo+448+264+16 CNSTI4 64 ASGNI4 line 786 ;786: levelMenuInfo.item_maps[3].generic.id = ID_PICTURE3; ADDRGP4 levelMenuInfo+448+264+8 CNSTI4 14 ASGNI4 line 787 ;787: levelMenuInfo.item_maps[3].generic.callback = UI_SPLevelMenu_LevelEvent; ADDRGP4 levelMenuInfo+448+264+48 ADDRGP4 UI_SPLevelMenu_LevelEvent ASGNP4 line 788 ;788: levelMenuInfo.item_maps[3].width = 128; ADDRGP4 levelMenuInfo+448+264+76 CNSTI4 128 ASGNI4 line 789 ;789: levelMenuInfo.item_maps[3].height = 96; ADDRGP4 levelMenuInfo+448+264+80 CNSTI4 96 ASGNI4 line 791 ;790: ;791: levelMenuInfo.item_rightarrow.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+800 CNSTI4 6 ASGNI4 line 792 ;792: levelMenuInfo.item_rightarrow.generic.name = ART_ARROW; ADDRGP4 levelMenuInfo+800+4 ADDRGP4 $398 ASGNP4 line 793 ;793: levelMenuInfo.item_rightarrow.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; ADDRGP4 levelMenuInfo+800+44 CNSTU4 260 ASGNU4 line 794 ;794: levelMenuInfo.item_rightarrow.generic.x = 606; ADDRGP4 levelMenuInfo+800+12 CNSTI4 606 ASGNI4 line 795 ;795: levelMenuInfo.item_rightarrow.generic.y = 64; ADDRGP4 levelMenuInfo+800+16 CNSTI4 64 ASGNI4 line 796 ;796: levelMenuInfo.item_rightarrow.generic.callback = UI_SPLevelMenu_RightArrowEvent; ADDRGP4 levelMenuInfo+800+48 ADDRGP4 UI_SPLevelMenu_RightArrowEvent ASGNP4 line 797 ;797: levelMenuInfo.item_rightarrow.generic.id = ID_RIGHTARROW; ADDRGP4 levelMenuInfo+800+8 CNSTI4 15 ASGNI4 line 798 ;798: levelMenuInfo.item_rightarrow.width = -16; ADDRGP4 levelMenuInfo+800+76 CNSTI4 -16 ASGNI4 line 799 ;799: levelMenuInfo.item_rightarrow.height = 114; ADDRGP4 levelMenuInfo+800+80 CNSTI4 114 ASGNI4 line 800 ;800: levelMenuInfo.item_rightarrow.focuspic = ART_ARROW_FOCUS; ADDRGP4 levelMenuInfo+800+60 ADDRGP4 $399 ASGNP4 line 802 ;801: ;802: trap_Cvar_VariableStringBuffer( "model", levelMenuInfo.playerModel, sizeof(levelMenuInfo.playerModel) ); ADDRGP4 $103 ARGP4 ADDRGP4 levelMenuInfo+2336 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 trap_Cvar_VariableStringBuffer CALLV pop line 803 ;803: PlayerIcon( levelMenuInfo.playerModel, levelMenuInfo.playerPicName, sizeof(levelMenuInfo.playerPicName) ); ADDRGP4 levelMenuInfo+2336 ARGP4 ADDRGP4 levelMenuInfo+2400 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 PlayerIcon CALLV pop line 804 ;804: levelMenuInfo.item_player.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+888 CNSTI4 6 ASGNI4 line 805 ;805: levelMenuInfo.item_player.generic.name = levelMenuInfo.playerPicName; ADDRGP4 levelMenuInfo+888+4 ADDRGP4 levelMenuInfo+2400 ASGNP4 line 806 ;806: levelMenuInfo.item_player.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY; ADDRGP4 levelMenuInfo+888+44 CNSTU4 2052 ASGNU4 line 807 ;807: levelMenuInfo.item_player.generic.x = 288; ADDRGP4 levelMenuInfo+888+12 CNSTI4 288 ASGNI4 line 808 ;808: levelMenuInfo.item_player.generic.y = AWARDS_Y; ADDRGP4 levelMenuInfo+888+16 CNSTI4 340 ASGNI4 line 809 ;809: levelMenuInfo.item_player.generic.id = ID_PLAYERPIC; ADDRGP4 levelMenuInfo+888+8 CNSTI4 16 ASGNI4 line 810 ;810: levelMenuInfo.item_player.generic.callback = UI_SPLevelMenu_PlayerEvent; ADDRGP4 levelMenuInfo+888+48 ADDRGP4 UI_SPLevelMenu_PlayerEvent ASGNP4 line 811 ;811: levelMenuInfo.item_player.width = 64; ADDRGP4 levelMenuInfo+888+76 CNSTI4 64 ASGNI4 line 812 ;812: levelMenuInfo.item_player.height = 64; ADDRGP4 levelMenuInfo+888+80 CNSTI4 64 ASGNI4 line 814 ;813: ;814: for( n = 0; n < 6; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 LABELV $613 line 815 ;815: levelMenuInfo.awardLevels[n] = UI_GetAwardLevel( n ); ADDRLP4 0 INDIRI4 ARGI4 ADDRLP4 96 ADDRGP4 UI_GetAwardLevel CALLI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2464 ADDP4 ADDRLP4 96 INDIRI4 ASGNI4 line 816 ;816: } LABELV $614 line 814 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 6 LTI4 $613 line 817 ;817: levelMenuInfo.awardLevels[AWARD_FRAGS] = 100 * (levelMenuInfo.awardLevels[AWARD_FRAGS] / 100); ADDRLP4 92 CNSTI4 100 ASGNI4 ADDRGP4 levelMenuInfo+2464+16 ADDRLP4 92 INDIRI4 ADDRGP4 levelMenuInfo+2464+16 INDIRI4 ADDRLP4 92 INDIRI4 DIVI4 MULI4 ASGNI4 line 819 ;818: ;819: y = AWARDS_Y; ADDRLP4 12 CNSTI4 340 ASGNI4 line 820 ;820: count = 0; ADDRLP4 4 CNSTI4 0 ASGNI4 line 821 ;821: for( n = 0; n < 6; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 LABELV $622 line 822 ;822: if( levelMenuInfo.awardLevels[n] ) { ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 levelMenuInfo+2464 ADDP4 INDIRI4 CNSTI4 0 EQI4 $626 line 823 ;823: if( count & 1 ) { ADDRLP4 4 INDIRI4 CNSTI4 1 BANDI4 CNSTI4 0 EQI4 $629 line 824 ;824: x = 224 - (count - 1 ) / 2 * (48 + 16); ADDRLP4 8 CNSTI4 224 ADDRLP4 4 INDIRI4 CNSTI4 1 SUBI4 CNSTI4 2 DIVI4 CNSTI4 6 LSHI4 SUBI4 ASGNI4 line 825 ;825: } ADDRGP4 $630 JUMPV LABELV $629 line 826 ;826: else { line 827 ;827: x = 368 + count / 2 * (48 + 16); ADDRLP4 8 ADDRLP4 4 INDIRI4 CNSTI4 2 DIVI4 CNSTI4 6 LSHI4 CNSTI4 368 ADDI4 ASGNI4 line 828 ;828: } LABELV $630 line 830 ;829: ;830: levelMenuInfo.item_awards[count].generic.type = MTYPE_BITMAP; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976 ADDP4 CNSTI4 6 ASGNI4 line 831 ;831: levelMenuInfo.item_awards[count].generic.name = ui_medalPicNames[n]; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+4 ADDP4 ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRGP4 ui_medalPicNames ADDP4 INDIRP4 ASGNP4 line 832 ;832: levelMenuInfo.item_awards[count].generic.flags = QMF_LEFT_JUSTIFY|QMF_SILENT|QMF_MOUSEONLY; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+44 ADDP4 CNSTU4 1050628 ASGNU4 line 833 ;833: levelMenuInfo.item_awards[count].generic.x = x; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+12 ADDP4 ADDRLP4 8 INDIRI4 ASGNI4 line 834 ;834: levelMenuInfo.item_awards[count].generic.y = y; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+16 ADDP4 ADDRLP4 12 INDIRI4 ASGNI4 line 835 ;835: levelMenuInfo.item_awards[count].generic.id = ID_AWARD1 + n; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+8 ADDP4 ADDRLP4 0 INDIRI4 CNSTI4 17 ADDI4 ASGNI4 line 836 ;836: levelMenuInfo.item_awards[count].generic.callback = UI_SPLevelMenu_AwardEvent; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+48 ADDP4 ADDRGP4 UI_SPLevelMenu_AwardEvent ASGNP4 line 837 ;837: levelMenuInfo.item_awards[count].width = 48; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+76 ADDP4 CNSTI4 48 ASGNI4 line 838 ;838: levelMenuInfo.item_awards[count].height = 48; CNSTI4 88 ADDRLP4 4 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976+80 ADDP4 CNSTI4 48 ASGNI4 line 839 ;839: count++; ADDRLP4 4 ADDRLP4 4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 line 840 ;840: } LABELV $626 line 841 ;841: } LABELV $623 line 821 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 6 LTI4 $622 line 843 ;842: ;843: levelMenuInfo.item_back.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+1504 CNSTI4 6 ASGNI4 line 844 ;844: levelMenuInfo.item_back.generic.name = ART_BACK0; ADDRGP4 levelMenuInfo+1504+4 ADDRGP4 $405 ASGNP4 line 845 ;845: levelMenuInfo.item_back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; ADDRGP4 levelMenuInfo+1504+44 CNSTU4 260 ASGNU4 line 846 ;846: levelMenuInfo.item_back.generic.x = 0; ADDRGP4 levelMenuInfo+1504+12 CNSTI4 0 ASGNI4 line 847 ;847: levelMenuInfo.item_back.generic.y = 480-64; ADDRGP4 levelMenuInfo+1504+16 CNSTI4 416 ASGNI4 line 848 ;848: levelMenuInfo.item_back.generic.callback = UI_SPLevelMenu_BackEvent; ADDRGP4 levelMenuInfo+1504+48 ADDRGP4 UI_SPLevelMenu_BackEvent ASGNP4 line 849 ;849: levelMenuInfo.item_back.generic.id = ID_BACK; ADDRGP4 levelMenuInfo+1504+8 CNSTI4 23 ASGNI4 line 850 ;850: levelMenuInfo.item_back.width = 128; ADDRGP4 levelMenuInfo+1504+76 CNSTI4 128 ASGNI4 line 851 ;851: levelMenuInfo.item_back.height = 64; ADDRGP4 levelMenuInfo+1504+80 CNSTI4 64 ASGNI4 line 852 ;852: levelMenuInfo.item_back.focuspic = ART_BACK1; ADDRGP4 levelMenuInfo+1504+60 ADDRGP4 $406 ASGNP4 line 854 ;853: ;854: levelMenuInfo.item_reset.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+1592 CNSTI4 6 ASGNI4 line 855 ;855: levelMenuInfo.item_reset.generic.name = ART_RESET0; ADDRGP4 levelMenuInfo+1592+4 ADDRGP4 $409 ASGNP4 line 856 ;856: levelMenuInfo.item_reset.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; ADDRGP4 levelMenuInfo+1592+44 CNSTU4 260 ASGNU4 line 857 ;857: levelMenuInfo.item_reset.generic.x = 170; ADDRGP4 levelMenuInfo+1592+12 CNSTI4 170 ASGNI4 line 858 ;858: levelMenuInfo.item_reset.generic.y = 480-64; ADDRGP4 levelMenuInfo+1592+16 CNSTI4 416 ASGNI4 line 859 ;859: levelMenuInfo.item_reset.generic.callback = UI_SPLevelMenu_ResetEvent; ADDRGP4 levelMenuInfo+1592+48 ADDRGP4 UI_SPLevelMenu_ResetEvent ASGNP4 line 860 ;860: levelMenuInfo.item_reset.generic.id = ID_RESET; ADDRGP4 levelMenuInfo+1592+8 CNSTI4 24 ASGNI4 line 861 ;861: levelMenuInfo.item_reset.width = 128; ADDRGP4 levelMenuInfo+1592+76 CNSTI4 128 ASGNI4 line 862 ;862: levelMenuInfo.item_reset.height = 64; ADDRGP4 levelMenuInfo+1592+80 CNSTI4 64 ASGNI4 line 863 ;863: levelMenuInfo.item_reset.focuspic = ART_RESET1; ADDRGP4 levelMenuInfo+1592+60 ADDRGP4 $410 ASGNP4 line 865 ;864: ;865: levelMenuInfo.item_custom.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+1680 CNSTI4 6 ASGNI4 line 866 ;866: levelMenuInfo.item_custom.generic.name = ART_CUSTOM0; ADDRGP4 levelMenuInfo+1680+4 ADDRGP4 $411 ASGNP4 line 867 ;867: levelMenuInfo.item_custom.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; ADDRGP4 levelMenuInfo+1680+44 CNSTU4 260 ASGNU4 line 868 ;868: levelMenuInfo.item_custom.generic.x = 342; ADDRGP4 levelMenuInfo+1680+12 CNSTI4 342 ASGNI4 line 869 ;869: levelMenuInfo.item_custom.generic.y = 480-64; ADDRGP4 levelMenuInfo+1680+16 CNSTI4 416 ASGNI4 line 870 ;870: levelMenuInfo.item_custom.generic.callback = UI_SPLevelMenu_CustomEvent; ADDRGP4 levelMenuInfo+1680+48 ADDRGP4 UI_SPLevelMenu_CustomEvent ASGNP4 line 871 ;871: levelMenuInfo.item_custom.generic.id = ID_CUSTOM; ADDRGP4 levelMenuInfo+1680+8 CNSTI4 25 ASGNI4 line 872 ;872: levelMenuInfo.item_custom.width = 128; ADDRGP4 levelMenuInfo+1680+76 CNSTI4 128 ASGNI4 line 873 ;873: levelMenuInfo.item_custom.height = 64; ADDRGP4 levelMenuInfo+1680+80 CNSTI4 64 ASGNI4 line 874 ;874: levelMenuInfo.item_custom.focuspic = ART_CUSTOM1; ADDRGP4 levelMenuInfo+1680+60 ADDRGP4 $412 ASGNP4 line 876 ;875: ;876: levelMenuInfo.item_next.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+1768 CNSTI4 6 ASGNI4 line 877 ;877: levelMenuInfo.item_next.generic.name = ART_FIGHT0; ADDRGP4 levelMenuInfo+1768+4 ADDRGP4 $407 ASGNP4 line 878 ;878: levelMenuInfo.item_next.generic.flags = QMF_RIGHT_JUSTIFY|QMF_PULSEIFFOCUS; ADDRGP4 levelMenuInfo+1768+44 CNSTU4 272 ASGNU4 line 879 ;879: levelMenuInfo.item_next.generic.x = 640; ADDRGP4 levelMenuInfo+1768+12 CNSTI4 640 ASGNI4 line 880 ;880: levelMenuInfo.item_next.generic.y = 480-64; ADDRGP4 levelMenuInfo+1768+16 CNSTI4 416 ASGNI4 line 881 ;881: levelMenuInfo.item_next.generic.callback = UI_SPLevelMenu_NextEvent; ADDRGP4 levelMenuInfo+1768+48 ADDRGP4 UI_SPLevelMenu_NextEvent ASGNP4 line 882 ;882: levelMenuInfo.item_next.generic.id = ID_NEXT; ADDRGP4 levelMenuInfo+1768+8 CNSTI4 26 ASGNI4 line 883 ;883: levelMenuInfo.item_next.width = 128; ADDRGP4 levelMenuInfo+1768+76 CNSTI4 128 ASGNI4 line 884 ;884: levelMenuInfo.item_next.height = 64; ADDRGP4 levelMenuInfo+1768+80 CNSTI4 64 ASGNI4 line 885 ;885: levelMenuInfo.item_next.focuspic = ART_FIGHT1; ADDRGP4 levelMenuInfo+1768+60 ADDRGP4 $408 ASGNP4 line 887 ;886: ;887: levelMenuInfo.item_null.generic.type = MTYPE_BITMAP; ADDRGP4 levelMenuInfo+1856 CNSTI4 6 ASGNI4 line 888 ;888: levelMenuInfo.item_null.generic.flags = QMF_LEFT_JUSTIFY|QMF_MOUSEONLY|QMF_SILENT; ADDRGP4 levelMenuInfo+1856+44 CNSTU4 1050628 ASGNU4 line 889 ;889: levelMenuInfo.item_null.generic.x = 0; ADDRGP4 levelMenuInfo+1856+12 CNSTI4 0 ASGNI4 line 890 ;890: levelMenuInfo.item_null.generic.y = 0; ADDRGP4 levelMenuInfo+1856+16 CNSTI4 0 ASGNI4 line 891 ;891: levelMenuInfo.item_null.width = 640; ADDRGP4 levelMenuInfo+1856+76 CNSTI4 640 ASGNI4 line 892 ;892: levelMenuInfo.item_null.height = 480; ADDRGP4 levelMenuInfo+1856+80 CNSTI4 480 ASGNI4 line 894 ;893: ;894: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_banner ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+288 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 896 ;895: ;896: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_leftarrow ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+360 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 897 ;897: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[0] ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+448 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 898 ;898: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[1] ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+448+88 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 899 ;899: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[2] ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+448+176 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 900 ;900: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_maps[3] ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+448+264 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 901 ;901: levelMenuInfo.item_maps[0].generic.bottom += 18; ADDRLP4 96 ADDRGP4 levelMenuInfo+448+32 ASGNP4 ADDRLP4 96 INDIRP4 ADDRLP4 96 INDIRP4 INDIRI4 CNSTI4 18 ADDI4 ASGNI4 line 902 ;902: levelMenuInfo.item_maps[1].generic.bottom += 18; ADDRLP4 100 ADDRGP4 levelMenuInfo+448+88+32 ASGNP4 ADDRLP4 100 INDIRP4 ADDRLP4 100 INDIRP4 INDIRI4 CNSTI4 18 ADDI4 ASGNI4 line 903 ;903: levelMenuInfo.item_maps[2].generic.bottom += 18; ADDRLP4 104 ADDRGP4 levelMenuInfo+448+176+32 ASGNP4 ADDRLP4 104 INDIRP4 ADDRLP4 104 INDIRP4 INDIRI4 CNSTI4 18 ADDI4 ASGNI4 line 904 ;904: levelMenuInfo.item_maps[3].generic.bottom += 18; ADDRLP4 108 ADDRGP4 levelMenuInfo+448+264+32 ASGNP4 ADDRLP4 108 INDIRP4 ADDRLP4 108 INDIRP4 INDIRI4 CNSTI4 18 ADDI4 ASGNI4 line 905 ;905: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_rightarrow ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+800 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 907 ;906: ;907: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_player ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+888 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 909 ;908: ;909: for( n = 0; n < count; n++ ) { ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $760 JUMPV LABELV $757 line 910 ;910: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_awards[n] ); ADDRGP4 levelMenuInfo ARGP4 CNSTI4 88 ADDRLP4 0 INDIRI4 MULI4 ADDRGP4 levelMenuInfo+976 ADDP4 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 911 ;911: } LABELV $758 line 909 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $760 ADDRLP4 0 INDIRI4 ADDRLP4 4 INDIRI4 LTI4 $757 line 912 ;912: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_back ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+1504 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 913 ;913: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_reset ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+1592 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 914 ;914: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_custom ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+1680 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 915 ;915: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_next ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+1768 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 916 ;916: Menu_AddItem( &levelMenuInfo.menu, &levelMenuInfo.item_null ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+1856 ARGP4 ADDRGP4 Menu_AddItem CALLV pop line 918 ;917: ;918: trap_Cvar_VariableStringBuffer( "ui_spSelection", buf, sizeof(buf) ); ADDRGP4 $153 ARGP4 ADDRLP4 20 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 trap_Cvar_VariableStringBuffer CALLV pop line 919 ;919: if( *buf ) { ADDRLP4 20 INDIRI1 CVII4 1 CNSTI4 0 EQI4 $767 line 920 ;920: n = atoi( buf ); ADDRLP4 20 ARGP4 ADDRLP4 112 ADDRGP4 atoi CALLI4 ASGNI4 ADDRLP4 0 ADDRLP4 112 INDIRI4 ASGNI4 line 921 ;921: selectedArenaSet = n / ARENAS_PER_TIER; ADDRGP4 selectedArenaSet ADDRLP4 0 INDIRI4 CNSTI4 4 DIVI4 ASGNI4 line 922 ;922: selectedArena = n % ARENAS_PER_TIER; ADDRGP4 selectedArena ADDRLP4 0 INDIRI4 CNSTI4 4 MODI4 ASGNI4 line 923 ;923: } ADDRGP4 $768 JUMPV LABELV $767 line 924 ;924: else { line 925 ;925: selectedArenaSet = currentSet; ADDRGP4 selectedArenaSet ADDRGP4 currentSet INDIRI4 ASGNI4 line 926 ;926: selectedArena = currentGame; ADDRGP4 selectedArena ADDRGP4 currentGame INDIRI4 ASGNI4 line 927 ;927: } LABELV $768 line 929 ;928: ;929: UI_SPLevelMenu_SetMenuItems(); ADDRGP4 UI_SPLevelMenu_SetMenuItems CALLV pop line 930 ;930:} LABELV $429 endproc UI_SPLevelMenu_Init 116 12 export UI_SPLevelMenu proc UI_SPLevelMenu 32 8 line 938 ;931: ;932: ;933:/* ;934:================= ;935:UI_SPLevelMenu ;936:================= ;937:*/ ;938:void UI_SPLevelMenu( void ) { line 943 ;939: int level; ;940: int trainingLevel; ;941: const char *arenaInfo; ;942: ;943: trainingTier = -1; ADDRGP4 trainingTier CNSTI4 -1 ASGNI4 line 944 ;944: arenaInfo = UI_GetSpecialArenaInfo( "training" ); ADDRGP4 $156 ARGP4 ADDRLP4 12 ADDRGP4 UI_GetSpecialArenaInfo CALLP4 ASGNP4 ADDRLP4 4 ADDRLP4 12 INDIRP4 ASGNP4 line 945 ;945: if( arenaInfo ) { ADDRLP4 4 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $770 line 946 ;946: minTier = trainingTier; ADDRGP4 minTier ADDRGP4 trainingTier INDIRI4 ASGNI4 line 947 ;947: trainingLevel = atoi( Info_ValueForKey( arenaInfo, "num" ) ); ADDRLP4 4 INDIRP4 ARGP4 ADDRGP4 $157 ARGP4 ADDRLP4 16 ADDRGP4 Info_ValueForKey CALLP4 ASGNP4 ADDRLP4 16 INDIRP4 ARGP4 ADDRLP4 20 ADDRGP4 atoi CALLI4 ASGNI4 ADDRLP4 8 ADDRLP4 20 INDIRI4 ASGNI4 line 948 ;948: } ADDRGP4 $771 JUMPV LABELV $770 line 949 ;949: else { line 950 ;950: minTier = 0; ADDRGP4 minTier CNSTI4 0 ASGNI4 line 951 ;951: trainingLevel = -2; ADDRLP4 8 CNSTI4 -2 ASGNI4 line 952 ;952: } LABELV $771 line 954 ;953: ;954: finalTier = UI_GetNumSPTiers(); ADDRLP4 16 ADDRGP4 UI_GetNumSPTiers CALLI4 ASGNI4 ADDRGP4 finalTier ADDRLP4 16 INDIRI4 ASGNI4 line 955 ;955: arenaInfo = UI_GetSpecialArenaInfo( "final" ); ADDRGP4 $191 ARGP4 ADDRLP4 20 ADDRGP4 UI_GetSpecialArenaInfo CALLP4 ASGNP4 ADDRLP4 4 ADDRLP4 20 INDIRP4 ASGNP4 line 956 ;956: if( arenaInfo ) { ADDRLP4 4 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $772 line 957 ;957: maxTier = finalTier; ADDRGP4 maxTier ADDRGP4 finalTier INDIRI4 ASGNI4 line 958 ;958: } ADDRGP4 $773 JUMPV LABELV $772 line 959 ;959: else { line 960 ;960: maxTier = finalTier - 1; ADDRGP4 maxTier ADDRGP4 finalTier INDIRI4 CNSTI4 1 SUBI4 ASGNI4 line 961 ;961: if( maxTier < minTier ) { ADDRGP4 maxTier INDIRI4 ADDRGP4 minTier INDIRI4 GEI4 $774 line 962 ;962: maxTier = minTier; ADDRGP4 maxTier ADDRGP4 minTier INDIRI4 ASGNI4 line 963 ;963: } LABELV $774 line 964 ;964: } LABELV $773 line 966 ;965: ;966: level = UI_GetCurrentGame(); ADDRLP4 24 ADDRGP4 UI_GetCurrentGame CALLI4 ASGNI4 ADDRLP4 0 ADDRLP4 24 INDIRI4 ASGNI4 line 967 ;967: if ( level == -1 ) { ADDRLP4 0 INDIRI4 CNSTI4 -1 NEI4 $776 line 968 ;968: level = UI_GetNumSPArenas() - 1; ADDRLP4 28 ADDRGP4 UI_GetNumSPArenas CALLI4 ASGNI4 ADDRLP4 0 ADDRLP4 28 INDIRI4 CNSTI4 1 SUBI4 ASGNI4 line 969 ;969: if( maxTier == finalTier ) { ADDRGP4 maxTier INDIRI4 ADDRGP4 finalTier INDIRI4 NEI4 $778 line 970 ;970: level++; ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 line 971 ;971: } LABELV $778 line 972 ;972: } LABELV $776 line 974 ;973: ;974: if( level == trainingLevel ) { ADDRLP4 0 INDIRI4 ADDRLP4 8 INDIRI4 NEI4 $780 line 975 ;975: currentSet = -1; ADDRGP4 currentSet CNSTI4 -1 ASGNI4 line 976 ;976: currentGame = 0; ADDRGP4 currentGame CNSTI4 0 ASGNI4 line 977 ;977: } ADDRGP4 $781 JUMPV LABELV $780 line 978 ;978: else { line 979 ;979: currentSet = level / ARENAS_PER_TIER; ADDRGP4 currentSet ADDRLP4 0 INDIRI4 CNSTI4 4 DIVI4 ASGNI4 line 980 ;980: currentGame = level % ARENAS_PER_TIER; ADDRGP4 currentGame ADDRLP4 0 INDIRI4 CNSTI4 4 MODI4 ASGNI4 line 981 ;981: } LABELV $781 line 983 ;982: ;983: UI_SPLevelMenu_Init(); ADDRGP4 UI_SPLevelMenu_Init CALLV pop line 984 ;984: UI_PushMenu( &levelMenuInfo.menu ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 UI_PushMenu CALLV pop line 985 ;985: Menu_SetCursorToItem( &levelMenuInfo.menu, &levelMenuInfo.item_next ); ADDRGP4 levelMenuInfo ARGP4 ADDRGP4 levelMenuInfo+1768 ARGP4 ADDRGP4 Menu_SetCursorToItem CALLV pop line 986 ;986:} LABELV $769 endproc UI_SPLevelMenu 32 8 export UI_SPLevelMenu_f proc UI_SPLevelMenu_f 0 4 line 994 ;987: ;988: ;989:/* ;990:================= ;991:UI_SPLevelMenu_f ;992:================= ;993:*/ ;994:void UI_SPLevelMenu_f( void ) { line 995 ;995: trap_Key_SetCatcher( KEYCATCH_UI ); CNSTI4 2 ARGI4 ADDRGP4 trap_Key_SetCatcher CALLV pop line 996 ;996: uis.menusp = 0; ADDRGP4 uis+16 CNSTI4 0 ASGNI4 line 997 ;997: UI_SPLevelMenu(); ADDRGP4 UI_SPLevelMenu CALLV pop line 998 ;998:} LABELV $783 endproc UI_SPLevelMenu_f 0 4 export UI_SPLevelMenu_ReInit proc UI_SPLevelMenu_ReInit 0 0 line 1006 ;999: ;1000: ;1001:/* ;1002:================= ;1003:UI_SPLevelMenu_ReInit ;1004:================= ;1005:*/ ;1006:void UI_SPLevelMenu_ReInit( void ) { line 1007 ;1007: levelMenuInfo.reinit = qtrue; ADDRGP4 levelMenuInfo+1944 CNSTI4 1 ASGNI4 line 1008 ;1008:} LABELV $785 endproc UI_SPLevelMenu_ReInit 0 0 bss align 4 LABELV maxTier skip 4 align 4 LABELV minTier skip 4 align 4 LABELV finalTier skip 4 align 4 LABELV trainingTier skip 4 align 4 LABELV currentGame skip 4 align 4 LABELV currentSet skip 4 align 4 LABELV selectedArena skip 4 align 4 LABELV selectedArenaSet skip 4 align 4 LABELV levelMenuInfo skip 2616 import UI_RankStatusMenu import RankStatus_Cache import UI_SignupMenu import Signup_Cache import UI_LoginMenu import Login_Cache import UI_RankingsMenu import Rankings_Cache import Rankings_DrawPassword import Rankings_DrawName import Rankings_DrawText import UI_InitGameinfo import UI_SPUnlockMedals_f import UI_SPUnlock_f import UI_GetAwardLevel import UI_LogAwardData import UI_NewGame import UI_GetCurrentGame import UI_CanShowTierVideo import UI_ShowTierVideo import UI_TierCompleted import UI_SetBestScore import UI_GetBestScore import UI_GetNumBots import UI_GetBotInfoByName import UI_GetBotInfoByNumber import UI_GetNumSPTiers import UI_GetNumSPArenas import UI_GetNumArenas import UI_GetSpecialArenaInfo import UI_GetArenaInfoByMap import UI_GetArenaInfoByNumber import UI_NetworkOptionsMenu import UI_NetworkOptionsMenu_Cache import UI_SoundOptionsMenu import UI_SoundOptionsMenu_Cache import UI_DisplayOptionsMenu import UI_DisplayOptionsMenu_Cache import UI_SaveConfigMenu import UI_SaveConfigMenu_Cache import UI_LoadConfigMenu import UI_LoadConfig_Cache import UI_TeamOrdersMenu_Cache import UI_TeamOrdersMenu_f import UI_TeamOrdersMenu import UI_RemoveBotsMenu import UI_RemoveBots_Cache import UI_AddBotsMenu import UI_AddBots_Cache import trap_SetPbClStatus import trap_VerifyCDKey import trap_SetCDKey import trap_GetCDKey import trap_MemoryRemaining import trap_LAN_GetPingInfo import trap_LAN_GetPing import trap_LAN_ClearPing import trap_LAN_ServerStatus import trap_LAN_GetPingQueueCount import trap_LAN_GetServerInfo import trap_LAN_GetServerAddressString import trap_LAN_GetServerCount import trap_GetConfigString import trap_GetGlconfig import trap_GetClientState import trap_GetClipboardData import trap_Key_SetCatcher import trap_Key_GetCatcher import trap_Key_ClearStates import trap_Key_SetOverstrikeMode import trap_Key_GetOverstrikeMode import trap_Key_IsDown import trap_Key_SetBinding import trap_Key_GetBindingBuf import trap_Key_KeynumToStringBuf import trap_S_RegisterSound import trap_S_StartLocalSound import trap_CM_LerpTag import trap_UpdateScreen import trap_R_DrawStretchPic import trap_R_SetColor import trap_R_RenderScene import trap_R_AddLightToScene import trap_R_AddPolyToScene import trap_R_AddRefEntityToScene import trap_R_ClearScene import trap_R_RegisterShaderNoMip import trap_R_RegisterSkin import trap_R_RegisterModel import trap_FS_Seek import trap_FS_GetFileList import trap_FS_FCloseFile import trap_FS_Write import trap_FS_Read import trap_FS_FOpenFile import trap_Cmd_ExecuteText import trap_Argv import trap_Argc import trap_Cvar_InfoStringBuffer import trap_Cvar_Create import trap_Cvar_Reset import trap_Cvar_SetValue import trap_Cvar_VariableStringBuffer import trap_Cvar_VariableValue import trap_Cvar_Set import trap_Cvar_Update import trap_Cvar_Register import trap_Milliseconds import trap_Error import trap_Print import UI_SPSkillMenu_Cache import UI_SPSkillMenu import UI_SPPostgameMenu_f import UI_SPPostgameMenu_Cache import UI_SPArena_Start import uis import m_entersound import UI_StartDemoLoop import UI_Cvar_VariableString import UI_Argv import UI_ForceMenuOff import UI_PopMenu import UI_PushMenu import UI_SetActiveMenu import UI_IsFullscreen import UI_DrawTextBox import UI_AdjustFrom640 import UI_CursorInRect import UI_DrawChar import UI_DrawString import UI_ProportionalStringWidth import UI_DrawProportionalString_AutoWrapped import UI_DrawProportionalString import UI_ProportionalSizeScale import UI_DrawBannerString import UI_LerpColor import UI_SetColor import UI_UpdateScreen import UI_DrawRect import UI_FillRect import UI_DrawHandlePic import UI_DrawNamedPic import UI_ClampCvar import UI_ConsoleCommand import UI_Refresh import UI_MouseEvent import UI_KeyEvent import UI_Shutdown import UI_Init import UI_RegisterClientModelname import UI_PlayerInfo_SetInfo import UI_PlayerInfo_SetModel import UI_DrawPlayer import DriverInfo_Cache import GraphicsOptions_Cache import UI_GraphicsOptionsMenu import ServerInfo_Cache import UI_ServerInfoMenu import UI_BotSelectMenu_Cache import UI_BotSelectMenu import ServerOptions_Cache import StartServer_Cache import UI_StartServerMenu import ArenaServers_Cache import UI_ArenaServersMenu import SpecifyServer_Cache import UI_SpecifyServerMenu import SpecifyLeague_Cache import UI_SpecifyLeagueMenu import Preferences_Cache import UI_PreferencesMenu import PlayerSettings_Cache import UI_PlayerSettingsMenu import PlayerModel_Cache import UI_PlayerModelMenu import UI_CDKeyMenu_f import UI_CDKeyMenu_Cache import UI_CDKeyMenu import UI_ModsMenu_Cache import UI_ModsMenu import UI_CinematicsMenu_Cache import UI_CinematicsMenu_f import UI_CinematicsMenu import Demos_Cache import UI_DemosMenu import Controls_Cache import UI_ControlsMenu import UI_DrawConnectScreen import TeamMain_Cache import UI_TeamMainMenu import UI_SetupMenu import UI_SetupMenu_Cache import UI_Message import UI_ConfirmMenu_Style import UI_ConfirmMenu import ConfirmMenu_Cache import UI_InGameMenu import InGame_Cache import UI_CreditMenu import UI_UpdateCvars import UI_RegisterCvars import UI_MainMenu import MainMenu_Cache import MenuField_Key import MenuField_Draw import MenuField_Init import MField_Draw import MField_CharEvent import MField_KeyDownEvent import MField_Clear import ui_medalSounds import ui_medalPicNames import ui_medalNames import text_color_highlight import text_color_normal import text_color_disabled import listbar_color import list_color import name_color import color_dim import color_red import color_orange import color_blue import color_yellow import color_white import color_black import menu_dim_color import menu_black_color import menu_red_color import menu_highlight_color import menu_dark_color import menu_grayed_color import menu_text_color import weaponChangeSound import menu_null_sound import menu_buzz_sound import menu_out_sound import menu_move_sound import menu_in_sound import ScrollList_Key import ScrollList_Draw import Bitmap_Draw import Bitmap_Init import Menu_DefaultKey import Menu_SetCursorToItem import Menu_SetCursor import Menu_ActivateItem import Menu_ItemAtCursor import Menu_Draw import Menu_AdjustCursor import Menu_AddItem import Menu_Focus import Menu_Cache import ui_cdkeychecked import ui_cdkey import ui_server16 import ui_server15 import ui_server14 import ui_server13 import ui_server12 import ui_server11 import ui_server10 import ui_server9 import ui_server8 import ui_server7 import ui_server6 import ui_server5 import ui_server4 import ui_server3 import ui_server2 import ui_server1 import ui_marks import ui_drawCrosshairNames import ui_drawCrosshair import ui_brassTime import ui_browserShowEmpty import ui_browserShowFull import ui_browserSortKey import ui_browserGameType import ui_browserMaster import ui_spSelection import ui_spSkill import ui_spVideos import ui_spAwards import ui_spScores5 import ui_spScores4 import ui_spScores3 import ui_spScores2 import ui_spScores1 import ui_botsFile import ui_arenasFile import ui_ctf_friendly import ui_ctf_timelimit import ui_ctf_capturelimit import ui_team_friendly import ui_team_timelimit import ui_team_fraglimit import ui_tourney_timelimit import ui_tourney_fraglimit import ui_ffa_timelimit import ui_ffa_fraglimit import BG_PlayerTouchesItem import BG_PlayerStateToEntityStateExtraPolate import BG_PlayerStateToEntityState import BG_TouchJumpPad import BG_AddPredictableEventToPlayerstate import BG_EvaluateTrajectoryDelta import BG_EvaluateTrajectory import BG_CanItemBeGrabbed import BG_FindItemForHoldable import BG_FindItemForPowerup import BG_FindItemForWeapon import BG_FindItem import bg_numItems import bg_itemlist import Pmove import PM_UpdateViewAngles import Com_Printf import Com_Error import Info_NextPair import Info_Validate import Info_SetValueForKey_Big import Info_SetValueForKey import Info_RemoveKey_big import Info_RemoveKey import Info_ValueForKey import va import Q_CleanStr import Q_PrintStrlen import Q_strcat import Q_strncpyz import Q_strrchr import Q_strupr import Q_strlwr import Q_stricmpn import Q_strncmp import Q_stricmp import Q_isalpha import Q_isupper import Q_islower import Q_isprint import Com_sprintf import Parse3DMatrix import Parse2DMatrix import Parse1DMatrix import SkipRestOfLine import SkipBracedSection import COM_MatchToken import COM_ParseWarning import COM_ParseError import COM_Compress import COM_ParseExt import COM_Parse import COM_GetCurrentParseLine import COM_BeginParseSession import COM_DefaultExtension import COM_StripExtension import COM_SkipPath import Com_Clamp import PerpendicularVector import AngleVectors import MatrixMultiply import MakeNormalVectors import RotateAroundDirection import RotatePointAroundVector import ProjectPointOnPlane import PlaneFromPoints import AngleDelta import AngleNormalize180 import AngleNormalize360 import AnglesSubtract import AngleSubtract import LerpAngle import AngleMod import BoxOnPlaneSide import SetPlaneSignbits import AxisCopy import AxisClear import AnglesToAxis import vectoangles import Q_crandom import Q_random import Q_rand import Q_acos import Q_log2 import VectorRotate import Vector4Scale import VectorNormalize2 import VectorNormalize import CrossProduct import VectorInverse import VectorNormalizeFast import DistanceSquared import Distance import VectorLengthSquared import VectorLength import VectorCompare import AddPointToBounds import ClearBounds import RadiusFromBounds import NormalizeColor import ColorBytes4 import ColorBytes3 import _VectorMA import _VectorScale import _VectorCopy import _VectorAdd import _VectorSubtract import _DotProduct import ByteToDir import DirToByte import ClampShort import ClampChar import Q_rsqrt import Q_fabs import axisDefault import vec3_origin import g_color_table import colorDkGrey import colorMdGrey import colorLtGrey import colorWhite import colorCyan import colorMagenta import colorYellow import colorBlue import colorGreen import colorRed import colorBlack import bytedirs import Com_Memcpy import Com_Memset import Hunk_Alloc import FloatSwap import LongSwap import ShortSwap import acos import fabs import abs import tan import atan2 import cos import sin import sqrt import floor import ceil import memcpy import memset import memmove import sscanf import vsprintf import _atoi import atoi import _atof import atof import toupper import tolower import strncpy import strstr import strchr import strcmp import strcpy import strcat import strlen import rand import srand import qsort lit align 1 LABELV $445 byte 1 67 byte 1 72 byte 1 79 byte 1 79 byte 1 83 byte 1 69 byte 1 32 byte 1 76 byte 1 69 byte 1 86 byte 1 69 byte 1 76 byte 1 0 align 1 LABELV $434 byte 1 50 byte 1 0 align 1 LABELV $430 byte 1 103 byte 1 95 byte 1 115 byte 1 112 byte 1 83 byte 1 107 byte 1 105 byte 1 108 byte 1 108 byte 1 0 align 1 LABELV $412 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 115 byte 1 107 byte 1 105 byte 1 114 byte 1 109 byte 1 105 byte 1 115 byte 1 104 byte 1 95 byte 1 49 byte 1 0 align 1 LABELV $411 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 115 byte 1 107 byte 1 105 byte 1 114 byte 1 109 byte 1 105 byte 1 115 byte 1 104 byte 1 95 byte 1 48 byte 1 0 align 1 LABELV $410 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 114 byte 1 101 byte 1 115 byte 1 101 byte 1 116 byte 1 95 byte 1 49 byte 1 0 align 1 LABELV $409 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 114 byte 1 101 byte 1 115 byte 1 101 byte 1 116 byte 1 95 byte 1 48 byte 1 0 align 1 LABELV $408 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 102 byte 1 105 byte 1 103 byte 1 104 byte 1 116 byte 1 95 byte 1 49 byte 1 0 align 1 LABELV $407 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 102 byte 1 105 byte 1 103 byte 1 104 byte 1 116 byte 1 95 byte 1 48 byte 1 0 align 1 LABELV $406 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 98 byte 1 97 byte 1 99 byte 1 107 byte 1 95 byte 1 49 byte 1 0 align 1 LABELV $405 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 98 byte 1 97 byte 1 99 byte 1 107 byte 1 95 byte 1 48 byte 1 0 align 1 LABELV $404 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 108 byte 1 101 byte 1 118 byte 1 101 byte 1 108 byte 1 95 byte 1 99 byte 1 111 byte 1 109 byte 1 112 byte 1 108 byte 1 101 byte 1 116 byte 1 101 byte 1 53 byte 1 0 align 1 LABELV $403 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 108 byte 1 101 byte 1 118 byte 1 101 byte 1 108 byte 1 95 byte 1 99 byte 1 111 byte 1 109 byte 1 112 byte 1 108 byte 1 101 byte 1 116 byte 1 101 byte 1 52 byte 1 0 align 1 LABELV $402 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 108 byte 1 101 byte 1 118 byte 1 101 byte 1 108 byte 1 95 byte 1 99 byte 1 111 byte 1 109 byte 1 112 byte 1 108 byte 1 101 byte 1 116 byte 1 101 byte 1 51 byte 1 0 align 1 LABELV $401 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 108 byte 1 101 byte 1 118 byte 1 101 byte 1 108 byte 1 95 byte 1 99 byte 1 111 byte 1 109 byte 1 112 byte 1 108 byte 1 101 byte 1 116 byte 1 101 byte 1 50 byte 1 0 align 1 LABELV $400 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 108 byte 1 101 byte 1 118 byte 1 101 byte 1 108 byte 1 95 byte 1 99 byte 1 111 byte 1 109 byte 1 112 byte 1 108 byte 1 101 byte 1 116 byte 1 101 byte 1 49 byte 1 0 align 1 LABELV $399 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 110 byte 1 97 byte 1 114 byte 1 114 byte 1 111 byte 1 119 byte 1 95 byte 1 49 byte 1 0 align 1 LABELV $398 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 110 byte 1 97 byte 1 114 byte 1 114 byte 1 111 byte 1 119 byte 1 95 byte 1 48 byte 1 0 align 1 LABELV $397 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 109 byte 1 97 byte 1 112 byte 1 115 byte 1 95 byte 1 115 byte 1 101 byte 1 108 byte 1 101 byte 1 99 byte 1 116 byte 1 101 byte 1 100 byte 1 0 align 1 LABELV $396 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 109 byte 1 97 byte 1 112 byte 1 115 byte 1 95 byte 1 115 byte 1 101 byte 1 108 byte 1 101 byte 1 99 byte 1 116 byte 1 0 align 1 LABELV $393 byte 1 63 byte 1 0 align 1 LABELV $382 byte 1 108 byte 1 111 byte 1 110 byte 1 103 byte 1 110 byte 1 97 byte 1 109 byte 1 101 byte 1 0 align 1 LABELV $380 byte 1 37 byte 1 115 byte 1 58 byte 1 32 byte 1 37 byte 1 115 byte 1 0 align 1 LABELV $344 byte 1 65 byte 1 67 byte 1 67 byte 1 69 byte 1 83 byte 1 83 byte 1 32 byte 1 68 byte 1 69 byte 1 78 byte 1 73 byte 1 69 byte 1 68 byte 1 0 align 1 LABELV $332 byte 1 84 byte 1 105 byte 1 101 byte 1 114 byte 1 32 byte 1 37 byte 1 105 byte 1 0 align 1 LABELV $331 byte 1 37 byte 1 105 byte 1 0 align 1 LABELV $330 byte 1 37 byte 1 105 byte 1 107 byte 1 0 align 1 LABELV $327 byte 1 37 byte 1 105 byte 1 109 byte 1 0 align 1 LABELV $259 byte 1 82 byte 1 69 byte 1 83 byte 1 69 byte 1 84 byte 1 32 byte 1 71 byte 1 65 byte 1 77 byte 1 69 byte 1 63 byte 1 0 align 1 LABELV $252 byte 1 115 byte 1 116 byte 1 97 byte 1 114 byte 1 116 byte 1 32 byte 1 111 byte 1 118 byte 1 101 byte 1 114 byte 1 32 byte 1 102 byte 1 114 byte 1 111 byte 1 109 byte 1 32 byte 1 116 byte 1 104 byte 1 101 byte 1 32 byte 1 98 byte 1 101 byte 1 103 byte 1 105 byte 1 110 byte 1 110 byte 1 105 byte 1 110 byte 1 103 byte 1 46 byte 1 0 align 1 LABELV $251 byte 1 68 byte 1 111 byte 1 32 byte 1 116 byte 1 104 byte 1 105 byte 1 115 byte 1 32 byte 1 111 byte 1 110 byte 1 108 byte 1 121 byte 1 32 byte 1 105 byte 1 102 byte 1 32 byte 1 121 byte 1 111 byte 1 117 byte 1 32 byte 1 119 byte 1 97 byte 1 110 byte 1 116 byte 1 32 byte 1 116 byte 1 111 byte 1 0 align 1 LABELV $250 byte 1 115 byte 1 105 byte 1 110 byte 1 103 byte 1 108 byte 1 101 byte 1 32 byte 1 112 byte 1 108 byte 1 97 byte 1 121 byte 1 101 byte 1 114 byte 1 32 byte 1 103 byte 1 97 byte 1 109 byte 1 101 byte 1 32 byte 1 118 byte 1 97 byte 1 114 byte 1 105 byte 1 97 byte 1 98 byte 1 108 byte 1 101 byte 1 115 byte 1 46 byte 1 0 align 1 LABELV $249 byte 1 87 byte 1 65 byte 1 82 byte 1 78 byte 1 73 byte 1 78 byte 1 71 byte 1 58 byte 1 32 byte 1 84 byte 1 104 byte 1 105 byte 1 115 byte 1 32 byte 1 114 byte 1 101 byte 1 115 byte 1 101 byte 1 116 byte 1 115 byte 1 32 byte 1 97 byte 1 108 byte 1 108 byte 1 32 byte 1 111 byte 1 102 byte 1 32 byte 1 116 byte 1 104 byte 1 101 byte 1 0 align 1 LABELV $191 byte 1 102 byte 1 105 byte 1 110 byte 1 97 byte 1 108 byte 1 0 align 1 LABELV $157 byte 1 110 byte 1 117 byte 1 109 byte 1 0 align 1 LABELV $156 byte 1 116 byte 1 114 byte 1 97 byte 1 105 byte 1 110 byte 1 105 byte 1 110 byte 1 103 byte 1 0 align 1 LABELV $153 byte 1 117 byte 1 105 byte 1 95 byte 1 115 byte 1 112 byte 1 83 byte 1 101 byte 1 108 byte 1 101 byte 1 99 byte 1 116 byte 1 105 byte 1 111 byte 1 110 byte 1 0 align 1 LABELV $132 byte 1 109 byte 1 101 byte 1 110 byte 1 117 byte 1 47 byte 1 97 byte 1 114 byte 1 116 byte 1 47 byte 1 117 byte 1 110 byte 1 107 byte 1 110 byte 1 111 byte 1 119 byte 1 110 byte 1 109 byte 1 97 byte 1 112 byte 1 0 align 1 LABELV $127 byte 1 108 byte 1 101 byte 1 118 byte 1 101 byte 1 108 byte 1 115 byte 1 104 byte 1 111 byte 1 116 byte 1 115 byte 1 47 byte 1 37 byte 1 115 byte 1 46 byte 1 116 byte 1 103 byte 1 97 byte 1 0 align 1 LABELV $116 byte 1 109 byte 1 97 byte 1 112 byte 1 0 align 1 LABELV $106 byte 1 110 byte 1 97 byte 1 109 byte 1 101 byte 1 0 align 1 LABELV $103 byte 1 109 byte 1 111 byte 1 100 byte 1 101 byte 1 108 byte 1 0 align 1 LABELV $82 byte 1 98 byte 1 111 byte 1 116 byte 1 115 byte 1 0 align 1 LABELV $75 byte 1 109 byte 1 111 byte 1 100 byte 1 101 byte 1 108 byte 1 115 byte 1 47 byte 1 112 byte 1 108 byte 1 97 byte 1 121 byte 1 101 byte 1 114 byte 1 115 byte 1 47 byte 1 37 byte 1 115 byte 1 47 byte 1 105 byte 1 99 byte 1 111 byte 1 110 byte 1 95 byte 1 100 byte 1 101 byte 1 102 byte 1 97 byte 1 117 byte 1 108 byte 1 116 byte 1 46 byte 1 116 byte 1 103 byte 1 97 byte 1 0 align 1 LABELV $72 byte 1 109 byte 1 111 byte 1 100 byte 1 101 byte 1 108 byte 1 115 byte 1 47 byte 1 112 byte 1 108 byte 1 97 byte 1 121 byte 1 101 byte 1 114 byte 1 115 byte 1 47 byte 1 37 byte 1 115 byte 1 47 byte 1 105 byte 1 99 byte 1 111 byte 1 110 byte 1 95 byte 1 37 byte 1 115 byte 1 46 byte 1 116 byte 1 103 byte 1 97 byte 1 0 align 1 LABELV $71 byte 1 100 byte 1 101 byte 1 102 byte 1 97 byte 1 117 byte 1 108 byte 1 116 byte 1 0
26,926
https://github.com/kagemeka/atcoder-submissions/blob/master/jp.atcoder/typical90/typical90_aa/26086840.py
Github Open Source
Open Source
MIT
2,022
atcoder-submissions
kagemeka
Python
Code
36
107
import sys import typing def main() -> typing.NoReturn: n = int(input()) s = sys.stdin.read().split() buf = set() res = [] for i in range(n): if s[i] in buf: continue res.append(i + 1) buf.add(s[i]) print(*res, sep='\n') main()
472
https://github.com/denimar/denibudget/blob/master/server/modules/transaction/transaction.controller.js
Github Open Source
Open Source
MIT
null
denibudget
denimar
JavaScript
Code
37
172
const transactionService = require('./transaction.service'); const commonConstant = require('../../../common/common.constant'); const bodyParser = require('body-parser'); const jsonParser = bodyParser.json(); module.exports = function(app) { app.get(commonConstant.ENDPOINT.TRANSACTION, transactionService.getTransactions); app.post(commonConstant.ENDPOINT.TRANSACTION + '/add', jsonParser, transactionService.addTransaction); app.post(commonConstant.ENDPOINT.TRANSACTION + '/upd', jsonParser, transactionService.updTransaction); app.delete(commonConstant.ENDPOINT.TRANSACTION + '/del/:id', transactionService.delTransaction); }
41,748
https://github.com/Tianle97/-Data-Centric-RAD-2017/blob/master/lab2/superheroes_wk2_part2.sql
Github Open Source
Open Source
Apache-2.0
null
-Data-Centric-RAD-2017
Tianle97
SQL
Code
303
1,267
-- MySQL dump 10.13 Distrib 5.7.9, for Win64 (x86_64) -- -- Host: localhost Database: superheroes -- ------------------------------------------------------ -- Server version 5.7.9 /*!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 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; DROP DATABASE IF EXISTS `superheroes`; CREATE DATABASE `superheroes`; USE `superheroes`; -- -- Table structure for table `superhero_city_table` -- DROP TABLE IF EXISTS `superhero_city_table`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `superhero_city_table` ( `name` varchar(20) NOT NULL, `city` varchar(20) NOT NULL, PRIMARY KEY (`name`,`city`), CONSTRAINT `fk_name` FOREIGN KEY (`name`) REFERENCES `superhero_table` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `superhero_city_table` -- LOCK TABLES `superhero_city_table` WRITE; /*!40000 ALTER TABLE `superhero_city_table` DISABLE KEYS */; INSERT INTO `superhero_city_table` VALUES ('Batgirl','Gotham City'),('Batman','Gotham City'),('Batman','Metropolis'),('Radioactiveman','Springfield'),('Spiderman','Metropolis'),('Spiderman','New York'),('Superman','Metropolis'); /*!40000 ALTER TABLE `superhero_city_table` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `superhero_table` -- DROP TABLE IF EXISTS `superhero_table`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `superhero_table` ( `name` varchar(20) NOT NULL, `real_first_name` varchar(20) DEFAULT NULL, `real_surname` varchar(20) DEFAULT NULL, `dob` date DEFAULT NULL, `powers` double(5,2) DEFAULT '77.88', PRIMARY KEY (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `superhero_table` -- LOCK TABLES `superhero_table` WRITE; /*!40000 ALTER TABLE `superhero_table` DISABLE KEYS */; INSERT INTO `superhero_table` VALUES ('Batgirl','Barbara','Gordon','1995-12-07',98.05),('Batman','Bruce','Wayne','1960-11-12',97.45),('Radioactiveman','Alan','Jones','2000-07-04',76.88),('Spiderman','Peter','Parker','1980-01-27',71.04),('Superman','Clark','Kent','1980-11-22',99.00); /*!40000 ALTER TABLE `superhero_table` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2016-08-30 15:26:10
45,776
https://github.com/dominikdassow/music-rs/blob/master/app/src/main/java/de/dominikdassow/musicrs/task/EvaluateSamplesTask.java
Github Open Source
Open Source
MIT
null
music-rs
dominikdassow
Java
Code
288
1,439
package de.dominikdassow.musicrs.task; import de.dominikdassow.musicrs.AppConfiguration; import de.dominikdassow.musicrs.model.Playlist; import de.dominikdassow.musicrs.model.Track; import de.dominikdassow.musicrs.model.feature.FeatureGenerator; import de.dominikdassow.musicrs.model.feature.TrackFeature; import de.dominikdassow.musicrs.recommender.MusicPlaylistContinuationEvaluator; import de.dominikdassow.musicrs.recommender.algorithm.AlgorithmConfiguration; import de.dominikdassow.musicrs.service.DatabaseService; import de.dominikdassow.musicrs.service.RecommendationService; import lombok.extern.slf4j.Slf4j; import org.uma.jmetal.solution.Solution; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; @Slf4j public class EvaluateSamplesTask extends Task { private static final int SAMPLE_SIZE = 25; private final Map<Integer, Playlist.Sample> samples = new HashMap<>(); private RecommendationService recommender; private List<AlgorithmConfiguration<? extends Solution<Integer>>> algorithmConfigurations; public EvaluateSamplesTask() { super("Evaluate Sample Playlists"); } public EvaluateSamplesTask using(List<AlgorithmConfiguration<? extends Solution<Integer>>> configurations) { this.algorithmConfigurations = configurations; return this; } public EvaluateSamplesTask sampling(Integer... playlists) { DatabaseService.readPlaylistsTracks(Set.of(playlists)).forEach((playlist, tracks) -> { Map<String, Map<TrackFeature.Audio, Double>> audioFeatures = DatabaseService.readTracksAudioFeatures(tracks.values()); List<Track> originalTracks = DatabaseService.readTracks(tracks.values()); List<Track> sampleTracks = originalTracks .subList(0, Math.min(originalTracks.size(), SAMPLE_SIZE)) .stream() .peek(track -> { track.setAudioFeaturesFrom(audioFeatures); track.setFeatures(FeatureGenerator.generateFor(track)); }) .collect(Collectors.toList()); Playlist samplePlaylist = Playlist.builder() .id(playlist) .tracks(IntStream.range(0, sampleTracks.size()).boxed() .collect(Collectors.toMap(Function.identity(), sampleTracks::get))) .build(); samplePlaylist.setFeatures(FeatureGenerator.generateFor(samplePlaylist)); samples.put(playlist, new Playlist.Sample(samplePlaylist, originalTracks)); }); return this; } @Override protected void init() { recommender = new RecommendationService(samples.values()); } @Override protected void execute() { List<RecommendationService.Result> recommendations = recommender .makeRecommendations(samples.keySet(), algorithmConfigurations); Map<String, Track> allRecommendedTracks = new HashMap<>() {{ DatabaseService.readTracks(recommendations.stream() .flatMap(recommendation -> recommendation.getTracks().stream()) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList()) ).forEach(track -> put(track.getId(), track)); }}; recommendations.forEach(recommendation -> { log.info("### RESULT [playlist=" + recommendation.getPlaylist() + "] " + "[" + recommendation.getConfiguration().getName() + "]"); List<Double> rPrecision = new ArrayList<>(); List<Double> ndcg = new ArrayList<>(); List<Double> recommendedSongClicks = new ArrayList<>(); recommendation.getTracks().forEach(tracks -> { final MusicPlaylistContinuationEvaluator evaluator = new MusicPlaylistContinuationEvaluator( samples.get(recommendation.getPlaylist()).getOriginalTracks(), tracks.subList(0, AppConfiguration.get().numberOfTracks).stream() .map(allRecommendedTracks::get) .collect(Collectors.toList()) ); // log.info("(1) " + tracks.get(0)); // log.info("(2) " + tracks.get(1)); // log.info("(3) " + tracks.get(2)); // log.info("> R-Precision: " + evaluator.getRPrecision()); // log.info("> NDCG: " + evaluator.getNDCG()); // log.info("> Recommended Songs Clicks: " + evaluator.getRecommendedSongsClicks()); rPrecision.add(evaluator.getRPrecision()); ndcg.add(evaluator.getNDCG()); recommendedSongClicks.add(evaluator.getRecommendedSongsClicks()); }); log.info("###"); log.info("~ R-Precision: " + rPrecision.stream().mapToDouble(d -> d).average().orElseThrow()); log.info("~ NDCG: " + ndcg.stream().mapToDouble(d -> d).average().orElseThrow()); log.info("~ Recommended Songs Clicks: " + recommendedSongClicks.stream().mapToDouble(d -> d).average().orElseThrow()); }); } }
37,072
https://github.com/ingresso-group/django-debug-toolbar-api-requests/blob/master/setup.py
Github Open Source
Open Source
MIT
2,020
django-debug-toolbar-api-requests
ingresso-group
Python
Code
104
337
#import os from setuptools import setup # allow setup.py to be run from any path #os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-debug-toolbar-api-requests', version='0.1.0', packages=['djdt_api_requests', 'djdt_api_requests.panels'], include_package_data=True, description=( 'A plugin to the Django Debug Toolbar to record stats on requests ' 'made to APIs using the requests library' ), long_description=open('README.md').read(), author='Ingresso', author_email='systems@ingresso.co.uk', install_requires=['django-debug-toolbar'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', ], )
28,256
https://github.com/MarkCBell/flipper/blob/master/flipper/kernel/bundle.py
Github Open Source
Open Source
MIT
2,021
flipper
MarkCBell
Python
Code
503
1,795
''' A module for representing triangulations of surface bundles over the circle. Provides one class: Bundle. ''' import flipper class Bundle: ''' This represents a triangulation of a surface bundle over the circle. It is specified by a triangulation of the surface, a triangulation of the bundle and an immersion map. Mapping classes can build their bundles and this is the standard way users are expected to create these. ''' def __init__(self, triangulation, triangulation3, immersion): assert isinstance(triangulation, flipper.kernel.Triangulation) assert isinstance(triangulation3, flipper.kernel.Triangulation3) assert isinstance(immersion, dict) assert all(triangle in immersion for triangle in triangulation) assert all(isinstance(immersion[triangle], (list, tuple)) for triangle in triangulation) assert all(len(immersion[triangle]) == 2 for triangle in triangulation) assert all(isinstance(immersion[triangle][0], flipper.kernel.Tetrahedron) for triangle in triangulation) assert all(isinstance(immersion[triangle][1], flipper.kernel.Permutation) for triangle in triangulation) self.triangulation = triangulation self.triangulation3 = triangulation3 self.immersion = immersion # This is a dict mapping: # triangle |---> (tetrahedra, perm). assert self.triangulation3.is_closed() def __repr__(self): return str(self) def __str__(self): return str(self.triangulation3) def snappy_string(self, name='flipper_triangulation', filled=True): ''' Return the SnapPy string describing this triangulation. If filled=True then the fake cusps are filled along their fibre slope. ''' fillings = [slope if filled_cusp else (0, 0) for filled_cusp, slope in zip(self.cusp_types(), self.fibre_slopes())] if filled else None return self.triangulation3.snappy_string(name, fillings) def __snappy__(self): return self.snappy_string() def cusp_types(self): ''' Return the list of the type of each cusp. ''' cusp_types = [None] * self.triangulation3.num_cusps for corner_class in self.triangulation.corner_classes: vertex = corner_class[0].vertex filled = vertex.filled for corner in corner_class: tetrahedron, permutation = self.immersion[corner.triangle] index = tetrahedron.cusp_indices[permutation(corner.side)] if cusp_types[index] is None: cusp_types[index] = filled else: assert cusp_types[index] == filled return cusp_types def fibre_slopes(self): ''' Return the list of fibre slopes on each cusp. ''' LONGITUDES, MERIDIANS = flipper.kernel.triangulation3.LONGITUDES, flipper.kernel.triangulation3.MERIDIANS slopes = [None] * self.triangulation3.num_cusps for index in range(self.triangulation3.num_cusps): meridian_intersection, longitude_intersection = 0, 0 for corner_class in self.triangulation.corner_classes: corner = corner_class[0] tetra, perm = self.immersion[corner.triangle] if tetra.cusp_indices[perm(corner.side)] == index: for corner in corner_class: tetra, perm = self.immersion[corner.triangle] side, other = perm(corner.side), perm(3) meridian_intersection += tetra.peripheral_curves[MERIDIANS][side][other] longitude_intersection += tetra.peripheral_curves[LONGITUDES][side][other] slopes[index] = (longitude_intersection, -meridian_intersection) break else: raise RuntimeError('No vertex was mapped to this cusp.') return slopes def degeneracy_slopes(self): ''' Return the list of degeneracy slopes on each cusp. This triangulation is must be veering. ''' assert self.triangulation3.is_veering() VEERING_LEFT, VEERING_RIGHT = flipper.kernel.triangulation3.VEERING_LEFT, flipper.kernel.triangulation3.VEERING_RIGHT TEMPS = flipper.kernel.triangulation3.TEMPS VERTICES_MEETING = flipper.kernel.triangulation3.VERTICES_MEETING EXIT_CUSP_LEFT, EXIT_CUSP_RIGHT = flipper.kernel.triangulation3.EXIT_CUSP_LEFT, flipper.kernel.triangulation3.EXIT_CUSP_RIGHT slopes = [None] * self.triangulation3.num_cusps cusp_pairing = self.triangulation3.cusp_identification_map() for index, cusp in enumerate(self.triangulation3.cusps): self.triangulation3.clear_temp_peripheral_structure() # Set the degeneracy curve into the TEMPS peripheral structure. # First find a good starting point: start_tetrahedron, start_side = cusp[0] edge_labels = [start_tetrahedron.get_edge_label(start_side, other) for other in VERTICES_MEETING[start_side]] for i in range(3): if edge_labels[(i+1) % 3] == VEERING_RIGHT and edge_labels[(i+2) % 3] == VEERING_LEFT: start_other = VERTICES_MEETING[start_side][i] break # Then walk around, never crossing through an edge where both ends veer the same way. current_tetrahedron, current_side, current_other = start_tetrahedron, start_side, start_other while True: current_tetrahedron.peripheral_curves[TEMPS][current_side][current_other] += 1 if start_tetrahedron.get_edge_label(current_side, current_other) == VEERING_LEFT: leave = EXIT_CUSP_LEFT[(current_side, current_other)] else: leave = EXIT_CUSP_RIGHT[(current_side, current_other)] current_tetrahedron.peripheral_curves[TEMPS][current_side][leave] -= 1 current_tetrahedron, current_side, current_other = cusp_pairing[(current_tetrahedron, current_side, leave)] if (current_tetrahedron, current_side, current_other) == (start_tetrahedron, start_side, start_other): break slopes[index] = self.triangulation3.slope() return slopes
7,051
https://github.com/Den-Rimus/dokka/blob/master/core/src/test/kotlin/NodeSelect.kt
Github Open Source
Open Source
Apache-2.0
2,022
dokka
Den-Rimus
Kotlin
Code
245
811
package org.jetbrains.dokka.tests import org.jetbrains.dokka.DocumentationNode import org.jetbrains.dokka.NodeKind import org.jetbrains.dokka.RefKind class SelectBuilder { private val root = ChainFilterNode(SubgraphTraverseFilter(), null) private var activeNode = root private val chainEnds = mutableListOf<SelectFilter>() fun withName(name: String) = matching { it.name == name } fun withKind(kind: NodeKind) = matching{ it.kind == kind } fun matching(block: (DocumentationNode) -> Boolean) { attachFilterAndMakeActive(PredicateFilter(block)) } fun subgraph() { attachFilterAndMakeActive(SubgraphTraverseFilter()) } fun subgraphOf(kind: RefKind) { attachFilterAndMakeActive(DirectEdgeFilter(kind)) } private fun attachFilterAndMakeActive(next: SelectFilter) { activeNode = ChainFilterNode(next, activeNode) } private fun endChain() { chainEnds += activeNode } fun build(): SelectFilter { endChain() return CombineFilterNode(chainEnds) } } private class ChainFilterNode(val filter: SelectFilter, val previous: SelectFilter?): SelectFilter() { override fun select(roots: Sequence<DocumentationNode>): Sequence<DocumentationNode> { return filter.select(previous?.select(roots) ?: roots) } } private class CombineFilterNode(val previous: List<SelectFilter>): SelectFilter() { override fun select(roots: Sequence<DocumentationNode>): Sequence<DocumentationNode> { return previous.asSequence().flatMap { it.select(roots) } } } abstract class SelectFilter { abstract fun select(roots: Sequence<DocumentationNode>): Sequence<DocumentationNode> } private class SubgraphTraverseFilter: SelectFilter() { override fun select(roots: Sequence<DocumentationNode>): Sequence<DocumentationNode> { val visited = mutableSetOf<DocumentationNode>() return roots.flatMap { generateSequence(listOf(it)) { nodes -> nodes.flatMap { it.allReferences() } .map { it.to } .filter { visited.add(it) } .takeUnless { it.isEmpty() } } }.flatten() } } private class PredicateFilter(val condition: (DocumentationNode) -> Boolean): SelectFilter() { override fun select(roots: Sequence<DocumentationNode>): Sequence<DocumentationNode> { return roots.filter(condition) } } private class DirectEdgeFilter(val kind: RefKind): SelectFilter() { override fun select(roots: Sequence<DocumentationNode>): Sequence<DocumentationNode> { return roots.flatMap { it.references(kind).asSequence() }.map { it.to } } } fun selectNodes(root: DocumentationNode, block: SelectBuilder.() -> Unit): List<DocumentationNode> { val builder = SelectBuilder() builder.apply(block) return builder.build().select(sequenceOf(root)).toMutableSet().toList() }
30,700
https://github.com/NETMF/llilum/blob/master/Zelig/Zelig/CompileTime/CodeGenerator/CodeTransformation/Annotations/RegisterCouplingConstraintAnnotation.cs
Github Open Source
Open Source
MIT
2,022
llilum
NETMF
C#
Code
374
1,218
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class RegisterCouplingConstraintAnnotation : Annotation { // // State // private int m_varIndex1; private bool m_fIsResult1; private int m_varIndex2; private bool m_fIsResult2; // // Constructor Methods // private RegisterCouplingConstraintAnnotation( int index1 , bool fIsResult1 , int index2 , bool fIsResult2 ) { m_varIndex1 = index1; m_fIsResult1 = fIsResult1; m_varIndex2 = index2; m_fIsResult2 = fIsResult2; } public static RegisterCouplingConstraintAnnotation Create( TypeSystemForIR ts , int index1 , bool fIsResult1 , int index2 , bool fIsResult2 ) { return (RegisterCouplingConstraintAnnotation)MakeUnique( ts, new RegisterCouplingConstraintAnnotation( index1, fIsResult1, index2, fIsResult2 ) ); } // // Equality Methods // public override bool Equals( Object obj ) { if(obj is RegisterCouplingConstraintAnnotation) { var other = (RegisterCouplingConstraintAnnotation)obj; if(m_varIndex1 == other.m_varIndex1 && m_fIsResult1 == other.m_fIsResult1 && m_varIndex2 == other.m_varIndex2 && m_fIsResult2 == other.m_fIsResult2 ) { return true; } } return false; } public override int GetHashCode() { return 0x0E47C2CA ^ m_varIndex1 ^ (m_varIndex2 << 10); } // // Helper Methods // public override Annotation Clone( CloningContext context ) { return this; // Nothing to change. } //--// public override void ApplyTransformation( TransformationContextForIR context ) { var context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); base.ApplyTransformation( context2 ); context2.Transform( ref m_varIndex1 ); context2.Transform( ref m_fIsResult1 ); context2.Transform( ref m_varIndex2 ); context2.Transform( ref m_fIsResult2 ); context2.Pop(); } //--// public void ExtractTargets( Operator op , out VariableExpression var1 , out VariableExpression var2 ) { var1 = m_fIsResult1 ? op.Results[m_varIndex1] : (op.Arguments[m_varIndex1] as VariableExpression); var2 = m_fIsResult2 ? op.Results[m_varIndex2] : (op.Arguments[m_varIndex2] as VariableExpression); } public VariableExpression FindCoupledExpression( Operator op , VariableExpression ex ) { VariableExpression var1; VariableExpression var2; ExtractTargets( op, out var1, out var2 ); if(var1 == ex) return var2; if(var2 == ex) return var1; return null; } //--// // // Access Methods // public int VarIndex1 { get { return m_varIndex1; } } public bool IsResult1 { get { return m_fIsResult1; } } public int VarIndex2 { get { return m_varIndex2; } } public bool IsResult2 { get { return m_fIsResult2; } } //--// // // Debug Methods // public override string FormatOutput( IIntermediateRepresentationDumper dumper ) { return dumper.FormatOutput( "<RegisterCouplingConstraintAnnotation: {0}({1}) <=> {2}({3})>", m_fIsResult1 ? "LHS" : "RHS", m_varIndex1, m_fIsResult2 ? "LHS" : "RHS", m_varIndex2 ); } } }
25,968
https://github.com/vicky-primathon/appsmith/blob/master/app/client/src/components/ads/Switch.tsx
Github Open Source
Open Source
Apache-2.0
2,021
appsmith
vicky-primathon
TSX
Code
24
66
import styled from "constants/DefaultTheme"; import { Switch } from "@blueprintjs/core"; export default styled(Switch)` &&&&& input:checked ~ span { background: ${(props) => props.theme.colors.selected}; } `;
44,796
https://github.com/maddapper/prebid-server-java/blob/master/src/main/java/org/prebid/server/bidder/facebook/proto/FacebookNative.java
Github Open Source
Open Source
Apache-2.0
2,020
prebid-server-java
maddapper
Java
Code
26
103
package org.prebid.server.bidder.facebook.proto; import com.iab.openrtb.request.Native; import lombok.EqualsAndHashCode; import lombok.Value; import lombok.experimental.SuperBuilder; @Value @SuperBuilder @EqualsAndHashCode(callSuper = true) public class FacebookNative extends Native { Integer w; Integer h; }
32,597
https://github.com/JaneliaSciComp/osgpyplusplus/blob/master/src/modules/osg/generated_code/vector_less__osg_scope_Vec3f__greater_.pypp.hpp
Github Open Source
Open Source
BSD-3-Clause
2,022
osgpyplusplus
JaneliaSciComp
C++
Code
15
112
// This file has been generated by Py++. #ifndef vector_less__osg_scope_Vec3f__greater__hpp__pyplusplus_wrapper #define vector_less__osg_scope_Vec3f__greater__hpp__pyplusplus_wrapper void register_vector_less__osg_scope_Vec3f__greater__class(); #endif//vector_less__osg_scope_Vec3f__greater__hpp__pyplusplus_wrapper
44,146
https://github.com/jew977/laravelhub/blob/master/resources/views/article/create.blade.php
Github Open Source
Open Source
MIT
2,015
laravelhub
jew977
Blade
Code
188
1,070
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>撰写博客</title> @include('Home.style') </head> <body> @include('Home.nav') <div class="main"> <form method="post" class="create_blog"> <input type="hidden" name="_token" value="{{csrf_token()}}"/> <div class="container"> <div class="row blog-title"> <div class="col-md-10"> <input type="text" class="form-control" name="title" required="required" placeholder="博客标题:夕阳下奔跑的少年"> </div> <div class="col-md-2"> <button type="button" class="btn btn-primary form-control" id="publish" data-toggle="modal" data-target="#fabumodal">发表博客</button> </div> </div> <div class="row"> <div class="col-md-12"> @include('editor::head') <div class="editor"> <textarea id='myEditor' name="content"></textarea> </div> </div> </div> </div> <!----遮罩层---> <div class="modal fade" id="fabumodal" aria-hidden='true'> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <span data-dismiss="modal" class="cancle">X</span> <h3 class="modal-title">文章设置</h3> </div> <div class="modal-body"> <div class="form-horizontal"> <div class="form-group"> <label class="control-label col-md-2">博客类型</label> <div class="col-md-10"> <select name="type" id="" class="form-control"> <option value="0">--请选择--</option> <option value="0">原创</option> <option value="1">转载</option> <option value="2">翻译</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-md-2">个人分类</label> <div class="col-md-10"> <input type="text" name="typename" maxlength="10" class="form-control" required="required"/> </div> </div> <div> <div class="col-md-10 col-md-offset-2"> <div id="blog-categories-box" style="display: block;"> @foreach($Categorys as $category) <span class="label label-default set_tag_key">{{$category->typename}}</span> @endforeach </div> </div> <div class="form-group"> <label class="control-label col-md-2">文章摘要</label> <div class="col-md-10"> <textarea name="desc" class="form-control" id="description" required="required"></textarea> </div> </div> <div class="from-group"></div> </div> </div> <div class="modal-footer blog-footer"> <button type="submit" class="btn btn-primary">发布</button><button data-dismiss="modal" class="btn btn-danger">取消</button> </div> </div> </div> </div> <!----> </form> </div> @include('Home.footer') <script type="text/javascript"> $(document).ready(function(){ $('#publish').click(function(){ var str_content=$.trim($('.CodeMirror-code').text()); var str_string=str_content.substr(0,100); $('#description').val(str_string); }) }); </script> </body> </html>
24,135
https://github.com/Miguel-Con-Queso/Pic-A-Flick/blob/master/seeds/index.js
Github Open Source
Open Source
MIT
null
Pic-A-Flick
Miguel-Con-Queso
JavaScript
Code
61
213
const seedUsers = require('./user-seeds'); // const seedGenres = require('./genres-seeds'); const seedMovies = require('./movies-seeds'); // const seedVotes = require('./vote-seeds'); const sequelize = require('../config/connection'); const seedAll = async () => { await sequelize.sync({ force: true }); console.log('\n----- DATABASE SYNCED -----\n'); await seedUsers(); console.log('\n----- USERS SEEDED -----\n'); await seedMovies(); console.log('\n----- MOVIES SEEDED -----\n'); // await seedVotes(); // console.log('\n----- VOTES SEEDED -----\n'); process.exit(0); }; seedAll();
20,950
https://github.com/yang-zhang99/hzero-platform/blob/master/src/main/java/org/hzero/platform/infra/repository/impl/DatasourceRepositoryImpl.java
Github Open Source
Open Source
Apache-2.0
2,021
hzero-platform
yang-zhang99
Java
Code
124
683
package org.hzero.platform.infra.repository.impl; import org.hzero.boot.platform.lov.annotation.ProcessLovValue; import org.hzero.core.base.BaseConstants; import org.hzero.mybatis.base.impl.BaseRepositoryImpl; import org.hzero.mybatis.domian.Condition; import org.hzero.mybatis.util.Sqls; import org.hzero.platform.domain.entity.Datasource; import org.hzero.platform.domain.repository.DatasourceRepository; import org.hzero.platform.infra.mapper.DatasourceMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import io.choerodon.core.domain.Page; import io.choerodon.mybatis.pagehelper.PageHelper; import io.choerodon.mybatis.pagehelper.domain.PageRequest; import java.util.List; import java.util.Objects; /** * 数据源配置 资源库实现 * * @author like.zhang@hand-china.com 2018-09-13 14:10:13 */ @Component public class DatasourceRepositoryImpl extends BaseRepositoryImpl<Datasource> implements DatasourceRepository { @Autowired private DatasourceMapper datasourceMapper; @Override @ProcessLovValue public Page<Datasource> pageDatasource(PageRequest pageRequest, Datasource datasource, Boolean orgQueryFlag) { return PageHelper.doPageAndSort(pageRequest, () -> datasourceMapper.selectDatasources(datasource, orgQueryFlag)); } @Override @ProcessLovValue public Datasource selectDatasource(Long datasourceId) { return datasourceMapper.selectDatasource(datasourceId); } @Override public Datasource getByUnique(Long tenantId, String datasourceCode) { return datasourceMapper.getByUnique(tenantId, datasourceCode); } @Override public List<Datasource> listDatasourceByCondition(Datasource datasource) { if (Objects.isNull(datasource)) { // 返回所有启用的数据源信息 return selectByCondition(Condition.builder(Datasource.class) .andWhere(Sqls.custom() .andEqualTo(Datasource.FIELD_ENABLED_FLAG, BaseConstants.Flag.YES) ) .build()); } else { // 按照条件查询进行返回 return select(datasource); } } }
18,240
https://github.com/MikiSoft/UniBot/blob/master/UniBot v1.5 - by MikiSoft/Plugins/Sources (VB6)/captcha9kw/frmS.frm
Github Open Source
Open Source
MIT
2,019
UniBot
MikiSoft
Visual Basic
Code
1,546
4,229
VERSION 5.00 Begin VB.Form frmS BorderStyle = 4 'Fixed ToolWindow Caption = "captcha9kw settings" ClientHeight = 2835 ClientLeft = 45 ClientTop = 285 ClientWidth = 3375 KeyPreview = -1 'True LinkTopic = "Form1" MaxButton = 0 'False MinButton = 0 'False ScaleHeight = 2835 ScaleWidth = 3375 ShowInTaskbar = 0 'False StartUpPosition = 1 'CenterOwner Begin VB.CommandButton cmdOK Caption = "OK" Default = -1 'True BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 120 TabIndex = 18 Top = 2460 Width = 3135 End Begin VB.CheckBox chkNoSave Caption = "&Don't save" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 2160 TabIndex = 17 ToolTipText = "Use current settings only for this session" Top = 2125 Width = 1095 End Begin VB.TextBox txtMaxL BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 285 Left = 1560 TabIndex = 15 Top = 1680 Width = 495 End Begin VB.CheckBox chkRem Caption = "Remember each &chng." BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 120 TabIndex = 16 ToolTipText = "Rememeber changes after each calling of this plugin." Top = 2125 Width = 1935 End Begin VB.Frame Frame1 Caption = "Default options" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 1575 Left = 120 TabIndex = 2 Top = 480 Width = 3135 Begin VB.CheckBox chkNum Caption = "&Num." BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 120 TabIndex = 3 ToolTipText = "Numeric" Top = 240 Width = 705 End Begin VB.TextBox txtMin BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 285 Left = 1380 TabIndex = 13 Top = 865 Width = 495 End Begin VB.TextBox txtPrior BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 285 Left = 2685 TabIndex = 11 ToolTipText = "Leave zero for unlimited." Top = 1220 Width = 275 End Begin VB.CheckBox chkNoSpace Caption = "No spac&e" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 2040 TabIndex = 9 Top = 865 Width = 975 End Begin VB.CheckBox chkOCR Caption = "&OCR" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 2400 TabIndex = 6 Top = 240 Width = 705 End Begin VB.CheckBox chkSym Caption = "with s&ymbols" Enabled = 0 'False BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 1560 TabIndex = 8 Top = 550 Width = 1300 End Begin VB.CheckBox chkMath Caption = "Mat&h" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 1680 TabIndex = 5 Top = 240 Width = 735 End Begin VB.CheckBox chkCase Caption = "Case &sensitive" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 120 TabIndex = 7 Top = 550 Width = 1335 End Begin VB.CheckBox chkPhrase Caption = "&Phrase" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 840 TabIndex = 4 ToolTipText = "Captcha contains two or more words." Top = 240 Width = 855 End Begin VB.Label Label6 Caption = "Ma&ximum length:" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 120 TabIndex = 14 ToolTipText = "Maximum length" Top = 1200 Width = 1215 End Begin VB.Label Label5 Caption = "M&inimum length:" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 120 TabIndex = 12 Top = 865 Width = 1215 End Begin VB.Label Label4 Caption = "P&riority:" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 2040 TabIndex = 10 Top = 1220 Width = 615 End End Begin VB.TextBox txtKey BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 285 Left = 840 MaxLength = 32 TabIndex = 1 Top = 120 Width = 2415 End Begin VB.Label Label1 Caption = "&API key:" BeginProperty Font Name = "Tahoma" Size = 8.25 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 255 Left = 120 TabIndex = 0 Top = 120 Width = 615 End End Attribute VB_Name = "frmS" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Public strKey As String Public bytMin As Byte Public bytMaxL As Byte Public bytCase As Boolean Public bytPrior As Byte Public bolNum As Boolean Public bolMath As Boolean Public bolPhrase As Boolean Public bolOCR As Boolean Public bolNoSpace As Boolean Public bolNoRem As Boolean Public bolSave As Boolean Function RplKey(strT As String) As String If Len(strT) >= 5 And Len(strT) <= 50 Then If Not strT Like "*[!A-Za-z0-9]*" Then RplKey = strT End Function Private Sub chkCase_Click() chkSym.Enabled = CBool(chkCase.Value) End Sub Private Sub cmdOK_Click() strKey = RplKey(Replace(Replace(Replace(txtKey.Text, vbCr, vbNullString), vbLf, vbNullString), vbTab, vbNullString)) If strKey = vbNullString Then If MsgBox("You have entered key of invalid length so it won't be saved! Continue?", vbExclamation + vbYesNo) = vbNo Then Exit Sub If txtPrior.Text < 20 Then bytPrior = txtPrior.Text Else: bytPrior = 20 ChngM txtMin, txtMaxL, bytMin, bytMaxL, 3 If chkCase.Value = 1 Then bytCase = chkCase.Value + chkSym.Value bolMath = CBool(chkMath.Value) bolNum = CBool(chkNum.Value) bolPhrase = CBool(chkPhrase.Value) bolOCR = CBool(chkOCR.Value) bolNoSpace = CBool(chkNoSpace.Value) bolNoRem = Not CBool(chkRem.Value) bolSave = Not CBool(chkNoSave.Value) Unload Me End Sub Private Sub ChngM(txt1 As TextBox, txt2 As TextBox, bytM As Byte, bytM1 As Byte, bytDMin As Byte) If txt2.Text < 255 Then bytM1 = txt2.Text Else: bytM1 = 255 If txt1.Text < 255 Then If txt1.Text > 0 Then bytM = txt1.Text Else: If bytM1 > 0 Then bytM = bytM1 Else: bytM = bytDMin Else: bytM = 255 End If If bytM1 > 0 And bytM1 < bytM Then bytM1 = bytM End Sub Private Sub Form_Load() txtKey.Text = strKey txtMin.Text = bytMin txtMaxL.Text = bytMaxL txtPrior.Text = bytPrior If bytCase >= 1 Then chkCase.Value = 1 If bytCase = 2 Then chkSym.Value = 1 End If chkMath.Value = CInt(bolMath) * (-1) chkPhrase.Value = CInt(bolPhrase) * (-1) chkNum.Value = CInt(bolNum) * (-1) chkOCR.Value = CInt(bolOCR) * (-1) chkNoSpace.Value = CInt(bolNoSpace) * (-1) chkRem.Value = CInt(Not bolNoRem) * (-1) chkNoSave.Value = CInt(Not bolSave) * (-1) End Sub Private Function CheckText(obj As TextBox) On Error Resume Next If obj.Text = vbNullString Then obj.Text = 0 obj.SelStart = 1 obj.Tag = vbNullString Exit Function End If If IsNumeric(obj.Text) Then If obj.Text < 0 Then Dim intS As Integer If obj.SelStart > 0 Then intS = obj.SelStart - 1 Else: intS = obj.SelStart obj.Text = obj.Text * (-1) obj.SelStart = intS End If obj.Tag = CLng(obj.Text) End If intS = obj.SelStart obj.Text = obj.Tag obj.SelStart = intS End Function Private Sub txtMin_Change() CheckText txtMin End Sub Private Sub txtMaxL_Change() CheckText txtMaxL End Sub Private Sub txtPrior_Change() CheckText txtPrior End Sub Private Sub Form_KeyPress(KeyAscii As Integer) If KeyAscii = 27 Then Unload Me End Sub Private Sub txtKey_KeyPress(KeyAscii As Integer) If KeyAscii = 1 Then KeyAscii = 0 txtKey.SelStart = 0 txtKey.SelLength = Len(txtKey.Text) ElseIf KeyAscii = 8 Or KeyAscii = 22 Or KeyAscii = 3 Or KeyAscii = 24 Then Exit Sub ElseIf Chr(KeyAscii) Like "[A-Za-z0-9]" Then Exit Sub Else: KeyAscii = 0 End If End Sub
48,100
https://github.com/opencomputeproject/HWMgmt-DeviceMgr-PSME/blob/master/PSME/common/ssdp/include/ssdp/ssdp_packet.hpp
Github Open Source
Open Source
Apache-2.0
2,022
HWMgmt-DeviceMgr-PSME
opencomputeproject
C++
Code
967
2,348
/*! * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * * @file ssdp_packet.hpp * * @brief Declaration of SsdpPacket. * */ #pragma once #include <string> #include <vector> namespace ssdp { /*! * Class for storing SSDP datagram data. * * SsdpPacket consists of packet type and headers. */ class SsdpPacket { public: /*! Service location header */ static constexpr const char AL[] = "AL"; /*! Host header */ static constexpr const char HOST[] = "Host"; /*! Location header */ static constexpr const char LOCATION[] = "Location"; /*! HTTP Cache-Control header */ static constexpr const char CACHE_CONTROL[] = "Cache-Control"; /*! HTTP Server header */ static constexpr const char SERVER[] = "Server"; /*! Notification type header */ static constexpr const char NT[] = "NT"; /*! Notification sub type header */ static constexpr const char NTS[] = "NTS"; /*! Notification sub type value */ static constexpr const char SSDP_ALIVE_STR[] = "ssdp:alive"; /*! Notification sub type value */ static constexpr const char SSDP_BYEBYE_STR[] = "ssdp:byebye"; /*! Unique Service Name header */ static constexpr const char USN[] = "USN"; /*! Search target header */ static constexpr const char ST[] = "ST"; /*! Header required by HTTP Extension Framework. Shall be "ssdp:discover". */ static constexpr const char MAN[] = "MAN"; /*! Value of MAN header */ static constexpr const char SSDP_DISCOVER[] = "\"ssdp:discover\""; /*! Header containing maximum wait time in seconds. */ static constexpr const char MX[] = "MX"; /*! Required for backward compatibility with UPnP 1.0. */ static constexpr const char EXT[] = "Ext"; /*! Represents SSDP packet type. */ class Type { public: /*! * Enumeration of available SSDP packet types. */ enum TypeEnum : std::uint8_t { NOTIFY, SEARCH_REQUEST, SEARCH_RESPONSE, UNKNOWN }; /*! * Converts string to corresponding Type. * @param type_string text to be converted to Type. * @return corresponding Type or UNKNOWN if not recognized. * */ static Type from_request_line_string(const std::string& type_string); /*! * Constructor. * @param value TypeEnum value. * */ constexpr Type(TypeEnum value) : m_value(value) { } /*! * Converts Type to const char* (cstring). * @return String representation of Type * compatible with SSDP request line format. * */ const std::string& to_request_line_string() const; /*! * Converts Type to const char* (cstring). * @return String representation of Type. * */ const std::string& to_string() const; /*! * Conversion operator * * @return TypeEnum value of this Type. * */ constexpr operator TypeEnum() const { return static_cast<TypeEnum>(m_value); } private: std::uint8_t m_value{}; }; /*! * Constructor. Creates SsdpPacket of given type. * @param type SSDP packet type. */ explicit SsdpPacket(Type type); /*! * SSDP packet type getter. * @return type of SSDP packet. */ Type get_type() const; /*! * Tests if it is SSDP search request packet. * @return true if packet is a SSDP search request */ bool is_search_request() const; /*! * Tests if it is SSDP notify packet. * @return true if packet is a SSDP notification */ bool is_notify() const; /*! * Tests if it is SSDP search response packet. * @return true if packet is a SSDP search response */ bool is_search_response() const; /*! * SSDP header setter. * @param name name of header to be set. * @param value value of header to be set. */ void set_header(const std::string& name, const std::string& value); /*! * SSDP header getter. * @param name name of requested header. * @return Value of requested header. */ const std::string& get_header(const std::string& name) const; /*! * Tests for header presence. * @param name name of requested header. * @return true if requested header is present, false otherwise. */ bool has_header(const std::string& name) const; /*! * Converts SsdpPacket to string representation. * String representation is ready to be send out via Socket. * @return String representation of SsdpPacket. */ std::string to_string() const; private: class Headers { using Container = std::vector<std::pair<std::string, std::string>>; Container m_headers{}; public: Container::const_iterator find(const std::string& key) const; Container::iterator find(const std::string& key); void set_header(const std::string& name, const std::string& value); const std::string& get_header(const std::string& name) const; bool contains(const std::string& name) const; Container::const_iterator begin() const { return m_headers.cbegin(); } Container::const_iterator end() const { return m_headers.cend(); } Container::iterator begin() { return m_headers.begin(); } Container::iterator end() { return m_headers.end(); } Container::size_type size() { return m_headers.size(); } }; Type m_type; Headers m_headers{}; }; /*! * Used as a key in associative containers. */ class SsdpPacketKey { public: /*! Constructor */ SsdpPacketKey() {} /*! * Constructor * param[in] type SsdpPacket type. * param[in] sub_type SsdpPacket notification sub type. */ SsdpPacketKey(const SsdpPacket::Type::TypeEnum& type, const std::string& sub_type = {}) : m_type(type), m_sub_type(sub_type) { } /*! * Constructor * param[in] packet SsdpPacket */ explicit SsdpPacketKey(const SsdpPacket& packet) : m_type{packet.get_type()} { if (packet.has_header(SsdpPacket::NTS)) { m_sub_type = packet.get_header(SsdpPacket::NTS); } } SsdpPacketKey(const SsdpPacketKey& packet_key) = default; SsdpPacketKey& operator=(const SsdpPacketKey& packet_key) = default; /*! Equal operator */ bool operator==(const SsdpPacketKey& other) const { return m_type == other.m_type && m_sub_type == other.m_sub_type; } /*! Less operator */ bool operator<(const SsdpPacketKey& other) const { if (m_type == other.m_type) { return m_sub_type < other.m_sub_type; } return m_type < other.m_type; } private: friend std::hash<ssdp::SsdpPacketKey>; SsdpPacket::Type::TypeEnum m_type{SsdpPacket::Type::UNKNOWN}; std::string m_sub_type{}; }; } namespace std { // Allows SsdpPacketKey to be used as unordered_map key template <> struct hash<ssdp::SsdpPacketKey> { std::size_t operator()(const ssdp::SsdpPacketKey& type) const { if (!type.m_sub_type.empty()) { return type.m_type ^ (std::hash<std::string>()(type.m_sub_type) << 2); } else { return type.m_type; } } }; }
24,581
https://github.com/bozhidarmihaylov/20200407-shouty.java/blob/master/src/test/java/shouty/ShoutyHelper.java
Github Open Source
Open Source
MIT
null
20200407-shouty.java
bozhidarmihaylov
Java
Code
53
192
package shouty; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; @Component @Scope("cucumber-glue") public class ShoutyHelper { private final Shouty shouty = new Shouty(); public void setLocation(String person, Coordinate location) { shouty.setLocation(person, location); } public void shout(String shouter, String shout) { shouty.shout(shouter, shout); } public Map<String, List<String>> getShoutsHeardBy(String listener) { return shouty.getShoutsHeardBy(listener); } }
30,151
https://github.com/Spieldichein/ShoprX/blob/master/Android/ShoprX/src/main/java/de/tum/in/schlichter/shoprx/ui/explanation/SettingFragment.java
Github Open Source
Open Source
Apache-2.0
null
ShoprX
Spieldichein
Java
Code
24
95
package de.tum.in.schlichter.shoprx.ui.explanation; import android.app.Fragment; import de.tum.in.schlichter.shoprx.algorithm.model.Attributes; /** * Created by Nicksteal on 03.04.2015. */ public class SettingFragment extends Fragment { private Attributes.Attribute attribute; }
41,108
https://github.com/kurli/chromium-crosswalk/blob/master/cc/output/renderer.h
Github Open Source
Open Source
BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause
null
chromium-crosswalk
kurli
C
Code
290
805
// Copyright 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. #ifndef CC_OUTPUT_RENDERER_H_ #define CC_OUTPUT_RENDERER_H_ #include "base/basictypes.h" #include "cc/base/cc_export.h" #include "cc/quads/render_pass.h" #include "cc/trees/layer_tree_host.h" namespace cc { class CompositorFrameAck; class CompositorFrameMetadata; class ScopedResource; class CC_EXPORT RendererClient { public: // These return the draw viewport and clip in non-y-flipped window space. // Note that while a draw is in progress, these are guaranteed to be // contained within the output surface size. virtual gfx::Rect DeviceViewport() const = 0; virtual gfx::Rect DeviceClip() const = 0; virtual void SetFullRootLayerDamage() = 0; virtual CompositorFrameMetadata MakeCompositorFrameMetadata() const = 0; protected: virtual ~RendererClient() {} }; class CC_EXPORT Renderer { public: virtual ~Renderer() {} virtual const RendererCapabilities& Capabilities() const = 0; virtual void ViewportChanged() {} virtual bool CanReadPixels() const = 0; virtual void DecideRenderPassAllocationsForFrame( const RenderPassList& render_passes_in_draw_order) {} virtual bool HaveCachedResourcesForRenderPassId(RenderPass::Id id) const; // This passes ownership of the render passes to the renderer. It should // consume them, and empty the list. The parameters here may change from frame // to frame and should not be cached. virtual void DrawFrame(RenderPassList* render_passes_in_draw_order, ContextProvider* offscreen_context_provider, float device_scale_factor, bool allow_partial_swap) = 0; // Waits for rendering to finish. virtual void Finish() = 0; virtual void DoNoOp() {} // Puts backbuffer onscreen. virtual void SwapBuffers() = 0; virtual void ReceiveSwapBuffersAck(const CompositorFrameAck& ack) {} virtual void GetFramebufferPixels(void* pixels, gfx::Rect rect) = 0; virtual bool IsContextLost(); virtual void SetVisible(bool visible) = 0; virtual void SendManagedMemoryStats(size_t bytes_visible, size_t bytes_visible_and_nearby, size_t bytes_allocated) = 0; virtual void SetDiscardBackBufferWhenNotVisible(bool discard) = 0; protected: explicit Renderer(RendererClient* client, const LayerTreeSettings* settings) : client_(client), settings_(settings) {} RendererClient* client_; const LayerTreeSettings* settings_; private: DISALLOW_COPY_AND_ASSIGN(Renderer); }; } // namespace cc #endif // CC_OUTPUT_RENDERER_H_
11,356
https://github.com/muhammadoginh/parsley/blob/master/Playground/EllipseDetection.cs
Github Open Source
Open Source
BSD-3-Clause
2,021
parsley
muhammadoginh
C#
Code
253
926
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using Emgu.CV.Structure; using MathNet.Numerics.LinearAlgebra; using Parsley.Core.Extensions; namespace Playground { [Parsley.Core.Addins.Addin] public class EllipseDetection : Parsley.Core.IImageAlgorithm { private int _threshold; private int _min_contour_count; private double _distance_threshold; public EllipseDetection() { _threshold = 40; _min_contour_count = 40; _distance_threshold = 1; } /// <summary> /// Set the threshold for blackness /// </summary> [Description("Set the threshold for blackness")] public int Threshold { get { return _threshold; } set { _threshold = value; } } /// <summary> /// Set minimum number of contour points for ellipse filter /// </summary> [Description("Set minimum number of contour points for ellipse filter")] public int MinContourCount { get { return _min_contour_count; } set { _min_contour_count = value; } } public double MeanDistanceThreshold { get { return _distance_threshold; } set { _distance_threshold = value; } } public virtual void ProcessImage(Emgu.CV.Image<Emgu.CV.Structure.Bgr, byte> image) { Emgu.CV.Image<Gray, byte> gray = image.Convert<Gray, byte>(); gray._ThresholdBinary(new Gray(_threshold), new Gray(255.0)); gray._Not(); Parsley.Core.EllipseDetector ed = new Parsley.Core.EllipseDetector(); ed.MinimumContourCount = _min_contour_count; List < Parsley.Core.DetectedEllipse > ellipses = new List<Parsley.Core.DetectedEllipse>(ed.DetectEllipses(gray)); List < Parsley.Core.DetectedEllipse > finals = new List<Parsley.Core.DetectedEllipse>( ellipses.Where(e => { return e.Rating < _distance_threshold; }) ); finals.Sort( (a, b) => { double dista = a.Ellipse.MCvBox2D.center.X * a.Ellipse.MCvBox2D.center.X + a.Ellipse.MCvBox2D.center.Y * a.Ellipse.MCvBox2D.center.Y; double distb = b.Ellipse.MCvBox2D.center.X * b.Ellipse.MCvBox2D.center.X + b.Ellipse.MCvBox2D.center.Y * b.Ellipse.MCvBox2D.center.Y; return dista.CompareTo(distb); } ); Bgr bgr = new Bgr(0, 255, 0); MCvFont f = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_PLAIN, 0.8, 0.8); int count = 1; foreach (Parsley.Core.DetectedEllipse e in finals) { image.Draw(e.Ellipse, bgr, 2); image.Draw(count.ToString(), ref f, new System.Drawing.Point((int)e.Ellipse.MCvBox2D.center.X, (int)e.Ellipse.MCvBox2D.center.Y), bgr); count++; } } } }
39,194
https://github.com/YuLeven/HaruGaKitaJavaApiPOC/blob/master/src/app/util/APIError.java
Github Open Source
Open Source
MIT
2,018
HaruGaKitaJavaApiPOC
YuLeven
Java
Code
114
313
package util; /** * Copyright 2017, Haru ga Kita! - All Rights Reserved * Written by Yuri Levenhagen <yurileven@gmail.com>, 2017-01-30 */ public enum APIError { INTERNAL_SERVER_ERROR, RESOURCE_NOT_FOUND, USER_NOT_FOUND, PACKAGE_NOT_FOUND, KANJI_NOT_FOUND, UNAUTHORIZED; public String getHumanReadableMessage() { switch (this) { case INTERNAL_SERVER_ERROR: return "The server behaved unexpectedly and your request couldn't be processed"; case RESOURCE_NOT_FOUND: return "The requested resource couldn't be found"; case USER_NOT_FOUND: return "The requested user could not be found."; case PACKAGE_NOT_FOUND: return "The requested pre-paid package could not be found."; case KANJI_NOT_FOUND: return "The requested kanji could not be found."; case UNAUTHORIZED: return "The informed credentials are invalid."; default: return "An error occurred but a message could not be retrieved"; } } }
13,115
https://github.com/kmykoh97/Unity-Games/blob/master/Roll A Ball/Assets/scripts/secondSceneVolume.cs
Github Open Source
Open Source
MIT
2,018
Unity-Games
kmykoh97
C#
Code
31
85
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class secondSceneVolume : MonoBehaviour { public AudioSource myMusic; // Use this for initialization void Start () { myMusic.volume = changeMusicVolume.volumeValue; } }
26,822
https://github.com/ezbuy/ezorm/blob/master/e2e/mongo/nested/gen_mongo_config.go
Github Open Source
Open Source
Apache-2.0
2,023
ezorm
ezbuy
Go
Code
153
556
package nested import ( "context" "fmt" "github.com/ezbuy/ezorm/v2/pkg/db" "github.com/ezbuy/wrapper/database" "go.mongodb.org/mongo-driver/mongo" ) type SetupOption struct { monitor database.Monitor postHooks []func() } type SetupOptionFn func(opts *SetupOption) func WithStatsDMonitor(app string) SetupOptionFn { return func(opts *SetupOption) { opts.monitor = database.NewStatsDPoolMonitor(app) } } func WithPrometheusMonitor(app, gatewayAddress string) SetupOptionFn { return func(opts *SetupOption) { opts.monitor = database.NewPrometheusPoolMonitor(app, gatewayAddress) } } func WithPostHooks(fn ...func()) SetupOptionFn { return func(opts *SetupOption) { opts.postHooks = append(opts.postHooks, fn...) } } var mongoDriver *db.MongoDriver func MgoSetup(config *db.MongoConfig, opts ...SetupOptionFn) { sopt := &SetupOption{} for _, opt := range opts { opt(sopt) } // setup the indexes sopt.postHooks = append(sopt.postHooks, UserIndexesFunc, ) var dopt []db.MongoDriverOption if sopt.monitor != nil { dopt = append(dopt, db.WithPoolMonitor(database.NewMongoDriverMonitor(sopt.monitor))) } db.Setup(config) var err error mongoDriver, err = db.NewMongoDriver( context.Background(), dopt..., ) if err != nil { panic(fmt.Errorf("failed to create mongodb driver: %s", err)) } for _, hook := range sopt.postHooks { hook() } } func Col(col string) *mongo.Collection { return mongoDriver.GetCol(col) }
17,847
https://github.com/KoanHealth/aws-flow-ruby/blob/master/aws-flow/lib/aws/templates/default.rb
Github Open Source
Open Source
Apache-2.0
2,017
aws-flow-ruby
KoanHealth
Ruby
Code
482
1,300
module AWS module Flow module Templates # Default workflow class for the AWS Flow Framework for Ruby. It # can run workflows defined by WorkflowTemplates. class FlowDefaultWorkflowRuby extend AWS::Flow::Workflows # Create activity client and child workflow client activity_client :act_client child_workflow_client :child_client # Create the workflow type with default options workflow FlowConstants.defaults[:execution_method] do { version: FlowConstants.defaults[:version], prefix_name: FlowConstants.defaults[:prefix_name], default_task_list: FlowConstants.defaults[:task_list], default_execution_start_to_close_timeout: FlowConstants.defaults[:execution_start_to_close_timeout] } end # Define the workflow method :start. It will take in an input hash # that contains the root template (:definition) and the arguments to the # template (:args). # @param input Hash # A hash containing the following keys - # definition: An object of type AWS::Flow::Templates::RootTemplate # args: Hash of arguments to be passed to the definition # def start(input) raise ArgumentError, "Workflow input must be a Hash" unless input.is_a?(Hash) raise ArgumentError, "Input hash must contain key :definition" if input[:definition].nil? raise ArgumentError, "Input hash must contain key :args" if input[:args].nil? definition = input[:definition] args = input[:args] unless definition.is_a?(AWS::Flow::Templates::RootTemplate) raise "Workflow Definition must be a AWS::Flow::Templates::RootTemplate" end raise "Input must be a Hash" unless args.is_a?(Hash) # Run the root workflow template definition.run(args, self) end end # Proxy classes for user activities are created in this module module ActivityProxies; end # Used to convert a regular ruby class into a Ruby Flow Activity class, # i.e. extends the AWS::Flow::Activities module. It converts all user # defined instance methods into activities and assigns the following # defaults to the ActivityType - version: "1.0" def self.make_activity_class(klass) return klass if klass.nil? name = klass.name.split(":").last proxy_name = name + "Proxy" # Create a proxy activity class that will define activities for all # instance methods of the class. new_klass = self::ActivityProxies.const_set(proxy_name.to_sym, Class.new(Object)) # Extend the AWS::Flow::Activities module and create activities for all # instance methods new_klass.class_exec do extend AWS::Flow::Activities attr_reader :instance @@klass = klass def initialize @instance = @@klass.new end # Creates activities for all instance methods of the held klass @@klass.instance_methods(false).each do |method| activity(method) do { version: "1.0", prefix_name: name } end end # Redirect all method calls to the held instance def method_missing(method, *args, &block) @instance.send(method, *args, &block) end end new_klass end # Default result reporting activity class for the AWS Flow Framework for # Ruby class FlowDefaultResultActivityRuby extend AWS::Flow::Activities # Create the activity type with default options activity FlowConstants.defaults[:result_activity_method] do { version: FlowConstants.defaults[:result_activity_version], prefix_name: FlowConstants.defaults[:result_activity_prefix], default_task_list: FlowConstants.defaults[:task_list], exponential_retry: FlowConstants.defaults[:retry_policy] } end # @param writer IO # An optional IO file descripter to write the result to. # def initialize(writer=nil) @writer = writer end # Serialize the input and write it to an IO writer if provided def run(input) unless input.is_a?(Hash) && input.include?(:key) && input.include?(:result) raise ArgumentError, "Incorrect input format for "\ "FlowDefaultResultActivityRuby.run" end @writer.puts Marshal.dump(input) if @writer end end # Returns the default result activity class # @api private def self.result_activity return AWS::Flow::Templates.const_get(FlowConstants.defaults[:result_activity_prefix]) end # Returns the default workflow class # @api private def self.default_workflow return AWS::Flow::Templates.const_get(FlowConstants.defaults[:prefix_name]) end end end end
37,142
https://github.com/LibreCat/librecat-citation/blob/master/t/LibreCat/Citation.t
Github Open Source
Open Source
Artistic-1.0
null
librecat-citation
LibreCat
Perl
Code
157
539
use Catmandu::Sane; use warnings FATAL => 'all'; use Test::More; use Test::Exception; use LibreCat -load => {layer_paths => [qw(t/layer)]}; use Data::Dumper; my $pkg; BEGIN { $pkg = 'LibreCat::Citation'; use_ok $pkg; } require_ok $pkg; lives_ok {$pkg->new()} 'lives_ok'; done_testing; __END__ my $rec = Catmandu->importer('YAML', file => 't/records/valid-publication.yml') ->first; subtest 'engine none' => sub { Catmandu->config->{citation}->{engine} = 'none'; my $c = $pkg->new; ok !$c->create($rec), "engine set to 'none'"; }; subtest 'no engine set' => sub { Catmandu->config->{citation}->{engine} = undef; my $c = $pkg->new; ok !$c->create($rec), "engine not defined"; }; SKIP: { skip("No variable CSL_TEST set", 5) unless $ENV{CSL_TEST}; Catmandu->config->{citation}->{engine} = 'csl'; subtest 'styles' => sub { my $c = $pkg->new; my $style_obj = $c->create($rec); ok $style_obj, "default style"; $c = $pkg->new(style => 'whatever'); $style_obj = $c->create($rec); ok !$style_obj, "unknown style"; $c = $pkg->new(style => 'ama', locale => 'de'); $style_obj = $c->create($rec); ok $style_obj, "style with locale"; $c = $pkg->new(all => 1); $style_obj = $c->create($rec); ok $style_obj, "all styles"; }; } done_testing;
48,663
https://github.com/odpi/egeria/blob/master/open-metadata-implementation/frameworks/open-connector-framework/src/main/java/org/odpi/openmetadata/frameworks/connectors/properties/beans/ElementOriginCategory.java
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, Apache-2.0, CC-BY-4.0, LicenseRef-scancode-proprietary-license
2,023
egeria
odpi
Java
Code
685
1,363
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.frameworks.connectors.properties.beans; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * ElementOriginCategory defines where the metadata comes from. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public enum ElementOriginCategory { /** * Unknown provenance. */ UNKNOWN (0, "<Unknown>", "Unknown provenance"), /** * The element is being maintained within one of the local cohort members. The metadata collection id is for one of the * repositories in the cohort. This metadata collection id identifies the home repository for this element. */ LOCAL_COHORT (1, "Local to cohort", "The element is being maintained within one of the local cohort members. " + "The metadata collection id is for one of the repositories in the cohort. " + "This metadata collection id identifies the home repository for this element. "), /** * The element was created from an export archive. The metadata collection id for the element is the metadata * collection id of the originating server. If the originating server later joins the cohort with the same * metadata collection id then these elements will be refreshed from the originating server's current repository. */ EXPORT_ARCHIVE (2, "Export Archive", "The element was created from an export archive. " + "The metadata collection id for the element is the metadata collection id of the originating server. " + "If the originating server later joins the cohort with the same metadata collection id " + "then these elements will be refreshed from the originating server's current repository."), /** * The element comes from an open metadata content pack. The metadata collection id of the elements is set to the GUID of the pack. */ CONTENT_PACK (3, "Content Pack", "The element comes from an open metadata content pack. " + "The metadata collection id of the elements is set to the GUID of the pack."), /** * The element comes from a metadata repository that used to be a member of the one of the local repository's cohorts, but it has been deregistered. * The metadata collection id remains the same. If the repository rejoins the cohort then these elements can be refreshed from the rejoining repository. */ DEREGISTERED_REPOSITORY (4, "Deregistered Repository", "The element comes from a metadata repository that " + "used to be a member of the one of the local repository's cohorts, but it has been deregistered. " + "The metadata collection id remains the same. If the repository rejoins the cohort " + "then these elements can be refreshed from the rejoining repository."), /** * The element is part of a service's configuration. The metadata collection id is null. */ CONFIGURATION (5, "Configuration", "The element is part of a service's configuration. The metadata collection id is null."), /** * The element is maintained by an external technology. The metadata collection id is the guid of the technology's descriptive entity. */ EXTERNAL_SOURCE (6, "External Source", "The element is maintained by an external technology. The metadata collection id is the guid of the technology's descriptive entity."); private static final long serialVersionUID = 1L; private final int originCode; private final String originName; private final String originDescription; /** * Constructor for the enum. * * @param originCode code number for origin * @param originName name for origin * @param originDescription description for origin */ ElementOriginCategory(int originCode, String originName, String originDescription) { this.originCode = originCode; this.originName = originName; this.originDescription = originDescription; } /** * Return the code for metadata element. * * @return int code for the origin */ public int getOrdinal() { return originCode; } /** * Return the name of the metadata element origin. * * @return String name */ public String getName() { return originName; } /** * Return the description of the metadata element origin. * * @return String description */ public String getDescription() { return originDescription; } /** * Standard toString method. * * @return print out of variables in a JSON-style */ @Override public String toString() { return "ElementOriginCategory{" + "originCode=" + originCode + ", originName='" + originName + '\'' + ", originDescription='" + originDescription + '\'' + '}'; } }
50,650
https://github.com/elifarley/kotlin-misc-lib/blob/master/src/com/github/elifarley/kotlin/textfile/DailyTextExporter.kt
Github Open Source
Open Source
MIT
2,019
kotlin-misc-lib
elifarley
Kotlin
Code
318
1,142
package com.orgecc.util.textfile import com.orgecc.util.DateTimeKit.toDate import com.orgecc.util.WithLogging import com.orgecc.util.io.IOWithDigest import com.orgecc.util.path.createParentDirectories import java.nio.file.Path import java.nio.file.Paths import java.sql.ResultSet import java.time.LocalDateTime import java.util.* import javax.sql.DataSource abstract class DailyTextExporter<out E: Any> ( config: DailyTextExporterConfig<ResultSet, E>, dataSource: DataSource ) : DailyTextImex(config, dataSource) { companion object : WithLogging() init { LOG.info("[init] ${config.reportName}.listQuery: [{}]", config.listQuery) if (config.listQuery.isNullOrBlank()) throw IllegalArgumentException("'${config.reportName}.listQuery' is null or blank!") if (!config.listQuery.trim().contains(' ')) throw IllegalArgumentException("'${config.reportName}.listQuery' has no spaces!") config.listQuery.count { it == '?' }.let { if (it < 2) throw IllegalArgumentException("'${config.reportName}.listQuery' has '$it' parameters, but it should have at least 2") } } @Suppress("UNCHECKED_CAST") override val config: DailyTextExporterConfig<ResultSet, E> get() = super.config as DailyTextExporterConfig<ResultSet, E> private fun asResultSetHandler(objectHandler: (E) -> Unit): (rs: ResultSet) -> Unit = { it -> objectHandler(config.toObject(it)) } fun forEachRowOH(params: NextDailyImexParams, objectHandler: (E) -> Unit): Unit = forEachRow(params, asResultSetHandler(objectHandler)) private fun forEachRow(params: NextDailyImexParams, rsHandler: (rs: ResultSet) -> Unit): Unit { LOG.info("[forEachRow] {}; listQuery SQL: [{}]", params, config.listQuery) jdbcTemplate.query(config.listQuery, params.queryParams, rsHandler) } private fun export(header: Map<String, Any>, params: NextDailyImexParams, mdWriter: IOWithDigest.MDWriter): Int { mdWriter.write(header) var detailLineCount = 0 forEachRowOH(params) { mdWriter.write(it) detailLineCount++ LOG.trace("#{}: {}", detailLineCount, it) } mdWriter.write(detailLineCount + 2) mdWriter.flush() return detailLineCount } fun export(outputFilePrefix: String, fileDate: LocalDateTime) { val processContext = Context().put("file-date", fileDate.toString()) val params: NextDailyImexParams? try { val endDate = fileDate.toLocalDate().minusDays(1L) // end date is yesterday params = processContext.nextParamsForDate(endDate) ?: return } catch (e: Exception) { processContext.close("[export] Error in 'nextReportParams'", e) throw e } val fileSeq = params.nextSequence val header = mapOf("file-date" to fileDate.toDate(), "file-seq" to fileSeq) val filePath: Path try { filePath = Paths.get(outputFilePrefix.addDateTimeSequence( header["file-date"] as Date, header["file-seq"] as Int) ).createParentDirectories() } catch(e: Exception) { processContext.close("[export] Unable to create output file path for prefix [$outputFilePrefix]", e) throw e } processContext.startExport(filePath) try { var detailLineCount: Int = 0 var md5 = ByteArray(0) config.useNewWriter(config.reportName, filePath) { mdWriter -> detailLineCount = export(header, params, mdWriter) md5 = mdWriter.digest } processContext.endIO(detailLineCount, md5) } catch(e: Exception) { processContext.close("[export] Unable to export data", e) throw e } finally { processContext.close() } } }
15,611
https://github.com/Akuli/odotdot/blob/master/src/parse.c
Github Open Source
Open Source
MIT
2,018
odotdot
Akuli
C
Code
2,816
9,140
// some assert()s in this file have a comment like 'TODO: report error' // it means that invalid syntax causes that assert() to fail // FIXME: nomemerr handling #include "parse.h" #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include "interpreter.h" #include "objectsystem.h" #include "operator.h" #include "tokenizer.h" #include "unicode.h" #include "objects/array.h" #include "objects/astnode.h" #include "objects/errors.h" #include "objects/integer.h" #include "objects/mapping.h" #include "objects/string.h" // remember to change this if you add more expressions! // this never fails static bool expression_coming_up(struct Token *curtok) { if (!curtok) return false; if (curtok->kind == TOKEN_STR || curtok->kind == TOKEN_INT || curtok->kind == TOKEN_ID) return true; if (curtok->kind == TOKEN_OP) return curtok->str.len == 1 && ( curtok->str.val[0] == '(' || curtok->str.val[0] == '{' || curtok->str.val[0] == '['); return false; } // all parse_blahblah() functions RETURN A NEW REFERENCE or NULL on error // "asd" static struct Object *parse_string(struct Interpreter *interp, char *filename, struct Token **curtok) { // these should be checked by the caller assert(*curtok); assert((*curtok)->kind == TOKEN_STR); // tokenizer.c makes sure that the escapes are valid, so there's no need to keep track of the source length unicode_char *src = (*curtok)->str.val; // the new string's length is never more than (*curtok)->str.len - 2 // because (*curtok)->str.len includes a " in both sides // and 2-character escape sequences represent 1 character in the string // e.g. \n (2 characters) represents a newline (1 character) // so length of a \n representation is bigger than length of a string with newlines unicode_char *dst = malloc(sizeof(unicode_char) * ((*curtok)->str.len - 2)); if (!dst) { errorobject_thrownomem(interp); return NULL; } size_t dstlen = 0; // skip initial " src++; while (*src != '"') { if (*src == '\\') { src++; if (*src == 'n') dst[dstlen++] = '\n'; else if (*src == 't') dst[dstlen++] = '\t'; else if (*src == '\\') dst[dstlen++] = '\\'; else if (*src == '"') dst[dstlen++] = '"'; else assert(0); src++; } else { dst[dstlen++] = *src++; } } struct Object *info = stringobject_newfromustr(interp, (struct UnicodeString) { .len = dstlen, .val = dst }); if (!info) return NULL; struct Object *res = astnodeobject_new(interp, AST_STR, filename, (*curtok)->lineno, info); if (!res) { OBJECT_DECREF(interp, info); return NULL; } *curtok = (*curtok)->next; return res; } // 123, -456 static struct Object *parse_int(struct Interpreter *interp, char *filename, struct Token **curtok) { assert(*curtok); assert((*curtok)->kind == TOKEN_INT); struct Object *info = integerobject_newfromustr(interp, (*curtok)->str); if (!info) return NULL; struct Object *res = astnodeobject_new(interp, AST_INT, filename, (*curtok)->lineno, info); if(!res) { OBJECT_DECREF(interp, info); return NULL; } *curtok = (*curtok)->next; return res; } // x static struct Object *parse_getvar(struct Interpreter *interp, char *filename, struct Token **curtok) { assert(*curtok); assert((*curtok)->kind == TOKEN_ID); struct AstGetVarInfo *info = malloc(sizeof(struct AstGetVarInfo)); if (!info) return NULL; if (!(info->varname = stringobject_newfromustr_copy(interp, (*curtok)->str))) { free(info); return NULL; } struct Object *res = astnodeobject_new(interp, AST_GETVAR, filename, (*curtok)->lineno, info); if (!res) { OBJECT_DECREF(interp, info->varname); free(info); return NULL; } *curtok = (*curtok)->next; return res; } // func arg1 arg2 opt1:val1 opt2:val2; // this takes the function as an already-parsed argument // this way parse_statement() knows when this should be called static struct Object *parse_call(struct Interpreter *interp, char *filename, struct Token **curtok, struct Object *funcnode) { size_t lineno = (*curtok)->lineno; struct AstCallInfo *callinfo = malloc(sizeof(struct AstCallInfo)); if (!callinfo) { errorobject_thrownomem(interp); return NULL; } if (!(callinfo->args = arrayobject_newempty(interp))) { free(callinfo); return NULL; } if (!(callinfo->opts = mappingobject_newempty(interp))) { OBJECT_DECREF(interp, callinfo->args); free(callinfo); return NULL; } callinfo->funcnode = funcnode; OBJECT_INCREF(interp, funcnode); while (expression_coming_up(*curtok)) { if ((*curtok)->kind == TOKEN_ID && (*curtok)->next && (*curtok)->next->kind == TOKEN_OP && (*curtok)->next->str.len == 1 && (*curtok)->next->str.val[0] == ':') { // opt:val struct Object *optstr = stringobject_newfromustr_copy(interp, (*curtok)->str); if (!optstr) goto error; *curtok = (*curtok)->next->next; // skip opt and : struct Object *valnode = parse_expression(interp, filename, curtok); if (!valnode) { OBJECT_DECREF(interp, optstr); goto error; } bool ok = mappingobject_set(interp, callinfo->opts, optstr, valnode); OBJECT_DECREF(interp, optstr); OBJECT_DECREF(interp, valnode); if (!ok) goto error; } else { struct Object *arg = parse_expression(interp, filename, curtok); if(!arg) goto error; bool ok = arrayobject_push(interp, callinfo->args, arg); OBJECT_DECREF(interp, arg); if (!ok) goto error; } } struct Object *res = astnodeobject_new(interp, AST_CALL, filename, lineno, callinfo); if (!res) { OBJECT_DECREF(interp, funcnode); OBJECT_DECREF(interp, callinfo->args); OBJECT_DECREF(interp, callinfo->opts); free(callinfo); return NULL; } return res; error: OBJECT_DECREF(interp, funcnode); OBJECT_DECREF(interp, callinfo->args); OBJECT_DECREF(interp, callinfo->opts); free(callinfo); return NULL; } // arg1 OPERATOR arg2 // where OPERATOR is one of: + - * / == != static struct Object *parse_operator_call(struct Interpreter *interp, char *filename, struct Token **curtok, struct Object *lhs) { size_t lineno = (*curtok)->lineno; assert((*curtok)->kind == TOKEN_OP); struct UnicodeString op = (*curtok)->str; *curtok = (*curtok)->next; struct Object *rhs = parse_expression(interp, filename, curtok); if (!rhs) return NULL; struct AstOpCallInfo *opcallinfo = malloc(sizeof(struct AstOpCallInfo)); if (!opcallinfo) { OBJECT_DECREF(interp, rhs); return NULL; } if (op.len == 1) { if (op.val[0] == '+') opcallinfo->op = OPERATOR_ADD; else if (op.val[0] == '-') opcallinfo->op = OPERATOR_SUB; else if (op.val[0] == '*') opcallinfo->op = OPERATOR_MUL; else if (op.val[0] == '/') opcallinfo->op = OPERATOR_DIV; else if (op.val[0] == '>') opcallinfo->op = OPERATOR_GT; else if (op.val[0] == '<') opcallinfo->op = OPERATOR_LT; else assert(0); } else if (op.len == 2) { if (op.val[0] == '=' && op.val[1] == '=') opcallinfo->op = OPERATOR_EQ; else if (op.val[0] == '!' && op.val[1] == '=') opcallinfo->op = OPERATOR_NE; else if (op.val[0] == '>' && op.val[1] == '=') opcallinfo->op = OPERATOR_GE; else if (op.val[0] == '<' && op.val[1] == '=') opcallinfo->op = OPERATOR_LE; else assert(0); } else assert(0); opcallinfo->lhs = lhs; OBJECT_INCREF(interp, lhs); opcallinfo->rhs = rhs; // already holding a reference to rhs struct Object *res = astnodeobject_new(interp, AST_OPCALL, filename, lineno, opcallinfo); if (!res) { OBJECT_DECREF(interp, opcallinfo->lhs); OBJECT_DECREF(interp, opcallinfo->rhs); free(opcallinfo); return NULL; } return res; } // arg1 `func` arg2 static struct Object *parse_infix_call(struct Interpreter *interp, char *filename, struct Token **curtok, struct Object *arg1) { size_t lineno = (*curtok)->lineno; // this SHOULD be checked by parse_expression() assert((*curtok)->str.len == 1 && (*curtok)->str.val[0] == '`'); *curtok = (*curtok)->next; struct Object *func = parse_expression(interp, filename, curtok); if (!func) return NULL; if ((*curtok)->str.len != 1 || (*curtok)->str.val[0] != '`') { // TODO: report error "expected another `" assert(0); } *curtok = (*curtok)->next; struct Object *arg2 = parse_expression(interp, filename, curtok); if (!arg2) { OBJECT_DECREF(interp, func); return NULL; } struct AstCallInfo *callinfo = malloc(sizeof(struct AstCallInfo)); if (!callinfo) { OBJECT_DECREF(interp, arg2); OBJECT_DECREF(interp, func); return NULL; } // infix calls don't support options, so this is left empty if (!(callinfo->opts = mappingobject_newempty(interp))) { free(callinfo); OBJECT_DECREF(interp, arg2); OBJECT_DECREF(interp, func); return NULL; } callinfo->funcnode = func; callinfo->args = arrayobject_new(interp, (struct Object *[]) { arg1, arg2 }, 2); OBJECT_DECREF(interp, arg2); if (!callinfo->args) { OBJECT_DECREF(interp, callinfo->opts); free(callinfo); OBJECT_DECREF(interp, func); return NULL; } struct Object *res = astnodeobject_new(interp, AST_CALL, filename, lineno, callinfo); if (!res) { OBJECT_DECREF(interp, callinfo->args); OBJECT_DECREF(interp, callinfo->opts); free(callinfo); OBJECT_DECREF(interp, func); return NULL; } return res; } // (func arg1 arg2) // or: (arg1 `func` arg2) // or: (arg1 OPERATOR arg2) where OPERATOR is one of: + - * / < > static struct Object *parse_call_expression(struct Interpreter *interp, char *filename, struct Token **curtok) { // this SHOULD be checked by parse_expression() assert((*curtok)->str.len == 1 && (*curtok)->str.val[0] == '('); *curtok = (*curtok)->next; struct Object *first = parse_expression(interp, filename, curtok); if (!first) return NULL; struct Object *res; #define f(x) ((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == (x)) if (f('`')) res = parse_infix_call(interp, filename, curtok, first); #define g(x,y) ((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 2 && (*curtok)->str.val[0] == (x) && (*curtok)->str.val[1] == (y)) else if (f('+')||f('-')||f('*')||f('/')||f('<')||f('>')||g('!','=')||g('=','=')||g('>','=')||g('<','=')) #undef f #undef g res = parse_operator_call(interp, filename, curtok, first); else res = parse_call(interp, filename, curtok, first); OBJECT_DECREF(interp, first); if (!res) return NULL; // TODO: report error "missing ')'" assert((*curtok)->str.len == 1 && (*curtok)->str.val[0] == ')'); *curtok = (*curtok)->next; return res; } // [a b c] static struct Object *parse_array(struct Interpreter *interp, char *filename, struct Token **curtok) { assert(*curtok); assert((*curtok)->kind == TOKEN_OP); assert((*curtok)->str.len == 1); assert((*curtok)->str.val[0] == '['); size_t lineno = (*curtok)->lineno; *curtok = (*curtok)->next; assert(*curtok); // TODO: report error "unexpected end of file" struct Object *elements = arrayobject_newempty(interp); if (!elements) return NULL; while ((*curtok) && !((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == ']')) { struct Object *elem = parse_expression(interp, filename, curtok); if(!elem) { OBJECT_DECREF(interp, elements); return NULL; } bool ok = arrayobject_push(interp, elements, elem ); OBJECT_DECREF(interp, elem); if (!ok) { OBJECT_DECREF(interp, elements); return NULL; } } assert(*curtok); // TODO: report error "unexpected end of file" assert((*curtok)->str.len == 1 && (*curtok)->str.val[0] == ']'); *curtok = (*curtok)->next; // skip ']' struct Object *res = astnodeobject_new(interp, AST_ARRAY, filename, lineno, elements); if (!res) { OBJECT_DECREF(interp, elements); return NULL; } return res; } // creates an AstNode that represents getting a variable named return static struct Object *create_return_getvar(struct Interpreter *interp, char *filename, size_t lineno) { struct AstGetVarInfo *info = malloc(sizeof (struct AstGetVarInfo)); if (!info) { errorobject_thrownomem(interp); return NULL; } info->varname = interp->strings.return_; OBJECT_INCREF(interp, info->varname); struct Object *res = astnodeobject_new(interp, AST_GETVAR, filename, lineno, info); if (!res) { OBJECT_DECREF(interp, info->varname); free(info); return NULL; } return res; } // create an AstNode that represents 'return returnednode;' static struct Object *create_return_call(struct Interpreter *interp, struct Object *returnednode) { struct AstCallInfo *callinfo = malloc(sizeof(struct AstCallInfo)); if (!callinfo) { errorobject_thrownomem(interp); return NULL; } if (!(callinfo->opts = mappingobject_newempty(interp))) { errorobject_thrownomem(interp); free(callinfo); return NULL; } struct AstNodeObjectData* tmp = returnednode->objdata.data; if (!(callinfo->funcnode = create_return_getvar(interp, tmp->filename, tmp->lineno))) { OBJECT_DECREF(interp, callinfo->opts); free(callinfo); return NULL; } if (!(callinfo->args = arrayobject_new(interp, &returnednode, 1))) { OBJECT_DECREF(interp, callinfo->funcnode); OBJECT_DECREF(interp, callinfo->opts); free(callinfo); return NULL; } struct Object *res = astnodeobject_new(interp, AST_CALL, tmp->filename, tmp->lineno, callinfo); if (!res) { OBJECT_DECREF(interp, callinfo->args); OBJECT_DECREF(interp, callinfo->funcnode); OBJECT_DECREF(interp, callinfo->opts); free(callinfo); return NULL; } return res; } // { ... } static struct Object *parse_block(struct Interpreter *interp, char *filename, struct Token **curtok) { assert(*curtok); assert((*curtok)->kind == TOKEN_OP); assert((*curtok)->str.len == 1); assert((*curtok)->str.val[0] == '{'); size_t lineno = (*curtok)->lineno; *curtok = (*curtok)->next; assert(*curtok); // TODO: report error "unexpected end of file" // figure out whether it contains a semicolon before } // if not, this is an implicit return: { expr } is same as { return expr; } bool implicitreturn; if ((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == '}') { // { } is an empty block implicitreturn = false; } else { // check if there's a ; before } // must match braces because blocks can be nested unsigned int bracecount = 1; bool foundit = false; for (struct Token *futtok = *curtok; futtok; futtok = futtok->next) { if (futtok->kind != TOKEN_OP || futtok->str.len != 1) continue; if (futtok->str.val[0] == ';' && bracecount == 1) { // found a ; not nested in another { } implicitreturn = false; foundit = true; break; } if (futtok->str.val[0] == '}' && --bracecount == 0) { // found the terminating } before a ; implicitreturn = true; foundit = true; break; } if (futtok->str.val[0] == '{') bracecount++; } // TODO: report error "missing }" assert(foundit); } struct Object *statements = arrayobject_newempty(interp); if (!statements) return NULL; if (implicitreturn) { struct Object *returnme = parse_expression(interp, filename, curtok); if (!returnme) { OBJECT_DECREF(interp, statements); return NULL; } struct Object *returncall = create_return_call(interp, returnme); OBJECT_DECREF(interp, returnme); if (!returncall) { OBJECT_DECREF(interp, statements); return NULL; } bool ok = arrayobject_push(interp, statements, returncall); OBJECT_DECREF(interp, returncall); if (!ok) { OBJECT_DECREF(interp, statements); return NULL; } } else { while ((*curtok) && !((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == '}')) { struct Object *stmt = parse_statement(interp, filename, curtok); if (!stmt) { OBJECT_DECREF(interp, statements); return NULL; } bool ok = arrayobject_push(interp, statements, stmt); OBJECT_DECREF(interp, stmt); if (!ok) { OBJECT_DECREF(interp, statements); return NULL; } } }; assert(*curtok); // TODO: report error "unexpected end of file" assert((*curtok)->str.len == 1 && (*curtok)->str.val[0] == '}'); *curtok = (*curtok)->next; // skip ']' struct Object *res = astnodeobject_new(interp, AST_BLOCK, filename, lineno, statements); if (!res) { OBJECT_DECREF(interp, statements); return NULL; } return res; } // parses the y of x.y, returning an AstNode that represents the whole x.y // attrofwhat is the x struct Object *parse_attribute(struct Interpreter *interp, char *filename, struct Token **curtok, struct Object *attrofwhat) { assert((*curtok)->kind == TOKEN_ID); // TODO: report error "invalid attribute name 'bla bla'" size_t lineno = (*curtok)->lineno; // lineno of an attribute is the lineno of the attribute name struct AstGetAttrInfo *getattrinfo = malloc(sizeof(struct AstGetAttrInfo)); if(!getattrinfo) // TODO: set no mem error return NULL; getattrinfo->objnode = attrofwhat; OBJECT_INCREF(interp, attrofwhat); if (!(getattrinfo->name = stringobject_newfromustr_copy(interp, (*curtok)->str))) { OBJECT_DECREF(interp, attrofwhat); free(getattrinfo); return NULL; } *curtok = (*curtok)->next; struct Object *getattr = astnodeobject_new(interp, AST_GETATTR, filename, lineno, getattrinfo); if(!getattr) { OBJECT_DECREF(interp, getattrinfo->name); OBJECT_DECREF(interp, attrofwhat); free(getattrinfo); return NULL; } return getattr; } // parses the (a b c) of x.(a b c), returning an AstNode that represents x.(a b c) // x.(a b c) is equivalent to (x.a b c) // methodofwhat is the x struct Object *parse_dotparen_method_call(struct Interpreter *interp, char *filename, struct Token **curtok, struct Object *methodofwhat) { // this should be checked by the caller assert((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == '('); *curtok = (*curtok)->next; struct Object *getattr = parse_attribute(interp, filename, curtok, methodofwhat); if (!getattr) return NULL; struct Object *call = parse_call(interp, filename, curtok, getattr); OBJECT_DECREF(interp, getattr); if (!call) return NULL; // TODO: report error "missing ')'" assert((*curtok)->str.len == 1 && (*curtok)->str.val[0] == ')'); *curtok = (*curtok)->next; return call; } struct Object *parse_expression(struct Interpreter *interp, char *filename, struct Token **curtok) { struct Object *res; switch ((*curtok)->kind) { case TOKEN_STR: res = parse_string(interp, filename, curtok); break; case TOKEN_INT: res = parse_int(interp, filename, curtok); break; case TOKEN_ID: res = parse_getvar(interp, filename, curtok); break; case TOKEN_OP: if ((*curtok)->str.len == 1) { if ((*curtok)->str.val[0] == '[') { res = parse_array(interp, filename, curtok); break; } if ((*curtok)->str.val[0] == '{') { res = parse_block(interp, filename, curtok); break; } if ((*curtok)->str.val[0] == '(') { res = parse_call_expression(interp, filename, curtok); break; } } default: // TODO: report error "expected this, that or those, got '%s'" assert(0); } if (!res) return NULL; // attributes and .( method calls while ((*curtok) && (*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == '.') { *curtok = (*curtok)->next; // skip '.' assert((*curtok)); // TODO: report error "expected an attribute name or (, but the file ended" struct Object *res2; if ((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == '(') res2 = parse_dotparen_method_call(interp, filename, curtok, res); else res2 = parse_attribute(interp, filename, curtok, res); OBJECT_DECREF(interp, res); if (!res2) return NULL; res = res2; } return res; } // var x = y; static struct Object *parse_var_statement(struct Interpreter *interp, char *filename, struct Token **curtok) { // parse_statement() has checked (*curtok)->kind // TODO: report error? size_t lineno = (*curtok)->lineno; assert((*curtok)->str.len == 3); assert((*curtok)->str.val[0] == 'v'); assert((*curtok)->str.val[1] == 'a'); assert((*curtok)->str.val[2] == 'r'); *curtok = (*curtok)->next; // TODO: report error assert((*curtok)->kind == TOKEN_ID); struct Object *varname = stringobject_newfromustr_copy(interp, (*curtok)->str); if (!varname) return NULL; *curtok = (*curtok)->next; // TODO: should 'var x;' set x to null? or just be forbidden? assert((*curtok)->kind == TOKEN_OP); assert((*curtok)->str.len == 1); assert((*curtok)->str.val[0] == '='); *curtok = (*curtok)->next; struct Object *value = parse_expression(interp, filename, curtok); if (!value) { OBJECT_DECREF(interp, varname); return NULL; } struct AstCreateOrSetVarInfo *info = malloc(sizeof(struct AstCreateOrSetVarInfo)); if (!info) { // TODO: set no mem error OBJECT_DECREF(interp, value); OBJECT_DECREF(interp, varname); return NULL; } info->varname = varname; info->valnode = value; struct Object *res = astnodeobject_new(interp, AST_CREATEVAR, filename, lineno, info); if (!res) { // TODO: set no mem error free(info); OBJECT_DECREF(interp, value); OBJECT_DECREF(interp, varname); return NULL; } return res; } // x = y; static struct Object *parse_assignment(struct Interpreter *interp, char *filename, struct Token **curtok, struct Object *lhs) { struct AstNodeObjectData *lhsdata = lhs->objdata.data; if (lhsdata->kind != AST_GETVAR && lhsdata->kind != AST_GETATTR) { // TODO: report an error e.g. like this: // the x of 'x = y;' must be a variable name or an attribute assert(0); } // these should be checked by the caller assert((*curtok)->str.len == 1); assert((*curtok)->str.val[0] == '='); *curtok = (*curtok)->next; struct Object *rhs = parse_expression(interp, filename, curtok); if (!rhs) return NULL; if (lhsdata->kind == AST_GETVAR) { struct AstGetVarInfo *lhsinfo = lhsdata->info; struct AstCreateOrSetVarInfo *info = malloc(sizeof(struct AstCreateOrSetVarInfo)); if (!info) goto error; info->varname = lhsinfo->varname; OBJECT_INCREF(interp, info->varname); info->valnode = rhs; struct Object *result = astnodeobject_new(interp, AST_SETVAR, filename, lhsdata->lineno, info); if (!result) { OBJECT_DECREF(interp, info->varname); free(info); goto error; } return result; } else { assert(lhsdata->kind == AST_GETATTR); struct AstGetAttrInfo *lhsinfo = lhsdata->info; struct AstSetAttrInfo *info = malloc(sizeof(struct AstSetAttrInfo)); if (!info) goto error; info->attr = lhsinfo->name; OBJECT_INCREF(interp, lhsinfo->name); info->objnode = lhsinfo->objnode; OBJECT_INCREF(interp, lhsinfo->objnode); info->valnode = rhs; struct Object *result = astnodeobject_new(interp, AST_SETATTR, filename, lhsdata->lineno, info); if (!result) { OBJECT_DECREF(interp, lhsinfo->name); OBJECT_DECREF(interp, lhsinfo->objnode); free(info); goto error; } return result; } error: OBJECT_DECREF(interp, rhs); return NULL; } struct Object *parse_statement(struct Interpreter *interp, char *filename, struct Token **curtok) { struct Object *res; if ((*curtok)->kind == TOKEN_KEYWORD) { // var is currently the only keyword res = parse_var_statement(interp, filename, curtok); } else { // a function call or an assignment struct Object *first = parse_expression(interp, filename, curtok); if (!first) return NULL; if ((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == '=') res = parse_assignment(interp, filename, curtok, first); // TODO: are infix call statements actually useful for something? else if ((*curtok)->kind == TOKEN_OP && (*curtok)->str.len == 1 && (*curtok)->str.val[0] == '`') res = parse_infix_call(interp, filename, curtok, first); else res = parse_call(interp, filename, curtok, first); OBJECT_DECREF(interp, first); if (!res) return NULL; } // TODO: report error "missing ';'" assert((*curtok)->kind == TOKEN_OP); assert((*curtok)->str.len == 1); assert((*curtok)->str.val[0] == ';'); *curtok = (*curtok)->next; return res; }
28,944
https://github.com/mangpo/greenthumb/blob/master/arm/programs/p17_p21.s
Github Open Source
Open Source
BSD-2-Clause
2,022
greenthumb
mangpo
GAS
Code
36
115
cmp r0, r1 movne r2, r3 cmp r0, r3 eoreq r0, r3, r1 movne r0, #0 eor r0, r2, r0 sub r3, r0, #1 orr r3, r3, r0 add r3, r3, #1 and r0, r3, r0
19,339
https://github.com/lesit/NeuroStudio/blob/master/NeuroKernel/engine/NeuralNetworkPredictor.h
Github Open Source
Open Source
W3C
2,022
NeuroStudio
lesit
C
Code
57
223
#pragma once #include "NeuralNetworkProcessor.h" #include "NeuroData/StreamWriter.h" namespace np { namespace engine { struct PREDICT_SETUP { dp::preprocessor::DataProvider* provider; dp::StreamWriter* result_writer; RecvSignal* recv_signal; }; class NeuralNetworkPredictor : public NeuralNetworkProcessor { public: NeuralNetworkPredictor(NeuralNetworkEngine& nn); ~NeuralNetworkPredictor(); bool IsLearn() const override { return false; } // bool Run(const _VALUE_VECTOR& input, const _VALUE_VECTOR* output = NULL); bool Run(const engine::PREDICT_SETUP& setup); }; } }
22,820
https://github.com/bsmsnd/LeetCode-CharlieChen/blob/master/304.range-sum-query-2-d-immutable.cpp
Github Open Source
Open Source
MIT
null
LeetCode-CharlieChen
bsmsnd
C++
Code
207
635
/* * @lc app=leetcode id=304 lang=cpp * * [304] Range Sum Query 2D - Immutable */ #include <iostream> #include <vector> using namespace std; class NumMatrix { public: vector<vector<int>> sums; NumMatrix(vector<vector<int>>& matrix) { int n_rows = matrix.size(); int n_cols = matrix[0].size(); // first row int first_row_sum = 0; vector<int> first_row(n_cols); for (int j = 0;j<n_cols;j++) { first_row_sum += matrix[0][j]; first_row[j] = first_row_sum; } sums.push_back(first_row); for (int i=1;i<n_rows;i++) { vector<int> row_vector(n_cols); for (int j = 0; j < n_cols; j++) { if (j == 0) row_vector[j] = sums[i-1][j] + matrix[i][j]; else row_vector[j] = sums[i-1][j] + row_vector[j-1] - sums[i-1][j-1] + matrix[i][j]; } sums.push_back(row_vector); } } int sumRegion(int row1, int col1, int row2, int col2) { // cout<<row1<<" "<<col1<<" "<<row2<<" "<<col2<<" "<<sums[row2][col2]<<" " << (col1 == 0? 0 : sums[row2][col1 - 1]) << " "<< (row1==0 ? 0 : sums[row1 - 1][col2]) << " "<< (row1==0 || col1 == 0? 0 : sums[row1][col1])<<endl; return sums[row2][col2] - (col1 == 0? 0 : sums[row2][col1 - 1]) - (row1==0 ? 0 : sums[row1 - 1][col2]) + (row1==0 || col1 == 0? 0 : sums[row1 - 1][col1 - 1]); } }; /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * int param_1 = obj->sumRegion(row1,col1,row2,col2); */
41,474
https://github.com/ETGgames/MIPS_Simulator/blob/master/test/mips_assembly/slti.mips.s
Github Open Source
Open Source
MIT
2,021
MIPS_Simulator
ETGgames
GAS
Code
26
61
#author: ES5017 #expected_exit_code: 1 #extra_info: tests simple case for slti and ensures numbers are compared as signed lui $2, 0xF013 slti $2, $2, 1 jr $0
2,077
https://github.com/rpl/git-wiki/blob/master/static/themes/blue/print.sass
Github Open Source
Open Source
MIT
2,019
git-wiki
rpl
Sass
Code
203
728
@import ../lib/reset.sass @import ../lib/changes.sass body color: #000 background: #FFF font-family: Verdana, Arial, Helvetica, sans-serif font-size: 10pt line-height: 1.2em h1 font-size: 180% h2 font-size: 170% h3 font-size: 150% h4 font-size: 120% h5 font-size: 120% h6 font-size: 120% h1,h2,h3,h4,h5,h6 font-family: Georgia, serif color: #0b3e71 margin: 1em 0 0.5em 0 border-bottom: 1px solid #999 ul,ol,p margin: 0.8em 0 0.8em 0 ul,ol ul,ol margin: 0 ul list-style-type: disc ol list-style-type: decimal ul, ol list-style-position: outside padding-left: 1.5em table border-collapse: collapse border-spacing: 0 border: 1px solid #999 tr td, th border: 1px solid #999 padding: 0.2em 0.5em &.link padding: 0 a margin: 0 padding: 0.2em 0.5em display: block th font-variant: small-caps a &, &:visited color: #0B3E71 text-decoration: none &:hover, &:active color: #FFF background: #0B3E71 text-decoration: none &:active background: #022763 &.img background: transparent div.img & border: 1px solid #999 float: right text-align: center color: #000 background: #FFF padding: 0.2em img display: block img vertical-align: middle hr background: #999 border: none height: 1px #header, #sidebar, #menu, .editlink, .backref, .hidden, .noprint display: none !important #footer display: block margin-top: 1em .ref, .ref:visited, .ref:active, .ref:hover vertical-align: super font-size: 80% color: #000 .date .ago display: none !important .full display: inline !important .toc padding: 0.5em 2em ul margin: 0 .toc1 font-weight: bold .toc2 font-weight: normal
29,519
https://github.com/peerlinks/peerlinks-desktop/blob/master/src/App.js
Github Open Source
Open Source
MIT
2,020
peerlinks-desktop
peerlinks
JavaScript
Code
233
721
import React, { useEffect } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { HashRouter as Router, Route } from 'react-router-dom'; import './App.css'; import { checkNetwork, setFocus } from './redux/actions'; import FullScreen from './layouts/FullScreen'; import ChannelLayout from './layouts/Channel'; import Channel from './pages/Channel'; import SignIn from './pages/SignIn'; import NewChannel from './pages/NewChannel'; import ImportFeed from './pages/ImportFeed'; import InviteRequest from './pages/InviteRequest'; import DeleteChannel from './pages/DeleteChannel'; function App({ network, checkNetwork, setFocus }) { // Check if the window as reopened and network is ready useEffect(() => { checkNetwork(); }, [ checkNetwork ]); // Propagate focus/blur state changes to redux useEffect(() => { const onFocus = () => { setFocus(true); }; const onBlur = () => { setFocus(false); }; window.addEventListener('focus', onFocus); window.addEventListener('blur', onBlur); return () => { window.removeEventListener('focus', onFocus); window.removeEventListener('blur', onBlur); }; }, [ setFocus ]); if (network.isReady) { return <Router> <ChannelLayout> <Route path='/new-channel' exact render={() => { return <NewChannel isFeed={false}/>; }}/> <Route path='/new-feed' exact render={() => { return <NewChannel isFeed={true}/>; }}/> <Route path='/import-feed' exact component={ImportFeed}/> <Route path='/request-invite' exact component={InviteRequest}/> <Route path='/channel/:id/' exact component={Channel}/> <Route path='/channel/:id/delete' exact component={DeleteChannel}/> </ChannelLayout> </Router>; } return <FullScreen> <SignIn/> </FullScreen>; } App.propTypes = { network: PropTypes.shape({ isReady: PropTypes.bool.isRequired, }), checkNetwork: PropTypes.func.isRequired, setFocus: PropTypes.func.isRequired, }; const mapStateToProps = (state) => { return { network: state.network, }; }; const mapDispatchToProps = (dispatch) => { return { checkNetwork: (...args) => dispatch(checkNetwork(...args)), setFocus: (...args) => dispatch(setFocus(...args)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(App);
47,042
https://github.com/4saito5/sensor-management-web/blob/master/client/containers/SignUp.ts
Github Open Source
Open Source
MIT
2,018
sensor-management-web
4saito5
TypeScript
Code
54
172
import {connect} from 'react-redux' import {Dispatch} from 'redux' import {ReduxAction, ReduxState} from '../store' // import {decrementAmount, incrementAmount} from '../modules/SignUp' import SignUpForm from '../component/SignUp' // dispatch処理 export class ActionDispatcher { constructor(private dispatch: (action: ReduxAction) => void) {} } // stateとactionの両方を渡す export default connect( (state: ReduxState) => ({value: state.signup}), (dispatch: Dispatch<ReduxAction>) => ({actions: new ActionDispatcher(dispatch)}) )(SignUpForm)
37,518
https://github.com/Carcacri/Delirium/blob/master/src/app/comun/indicador-pantalla/indicador-pantalla.component.sass
Github Open Source
Open Source
MIT
null
Delirium
Carcacri
Sass
Code
63
271
@import "../../../variables.sass" @import "../../../breakpoints.scss" ::ng-deep .contenedorIndicadorPantalla .contenedorIndicadorPantalla position: absolute bottom: 0 right: 0 z-index: 1000 color: white text-align: center background-color: green @include media("<=desktop") background-color: blue @include media("<=tablet") color: black background-color: yellow @include media("<=phone") color: black background-color: orange @include media("<=smphone") color: black background-color: red .textoIndicadorPantalla::before content: "No media" @include media("<=desktop") content: "<=desktop" @include media("<=tablet") content: "<=tablet" @include media("<=phone") content: "<=phone" @include media("<=smphone") content: "<=smphone"
10,430
https://github.com/wuhou123/react-blogs/blob/master/umi-demo/src/pages/index/components/douyin/index.module.scss
Github Open Source
Open Source
MIT
null
react-blogs
wuhou123
SCSS
Code
89
303
.recomment-config { width: 600px; height: 100%; position: relative; padding: 50px 0 0 60px; .title { h2 { font-size: 24px; } } .content { width: 600px; height: 600px; position: relative; background: #fff; li { width: 100%; text-align: left; color: #fff; font-size: 18px; font-weight: bold; cursor: pointer; .name { width: 550px; display: inline-block; height: 30px; line-height: 30px; vertical-align: middle; } .date { width: 50px; display: inline-block; color: #999; font-size: 13px; text-align: center; } } } } .thumbVertical { width: 6px; background: linear-gradient(0deg, #9569ff, #00ccf3); position: relative; left: -3px; cursor: pointer; }
8,145
https://github.com/9elements/gulp-9e-sass-lint/blob/master/test/fixtures/test.sass
Github Open Source
Open Source
MIT, Unlicense
null
gulp-9e-sass-lint
9elements
Sass
Code
14
40
.overlay position: absolute color: red top: 0 left: 0 .foo color: red @include clearfix
17,327
https://github.com/ZhyliaievD/gauge-java/blob/master/src/main/java/com/thoughtworks/gauge/Table.java
Github Open Source
Open Source
Apache-2.0
2,022
gauge-java
ZhyliaievD
Java
Code
689
1,933
/*---------------------------------------------------------------- * Copyright (c) ThoughtWorks, Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE.txt in the project root for license information. *----------------------------------------------------------------*/ package com.thoughtworks.gauge; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * Custom Table structure used as parameter in steps. */ public class Table { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final String DASH = "-"; private static final String PIPE = "|"; private static final char SPACE_AS_CHAR = " ".charAt(0); private final List<String> headers; private final List<List<String>> rows; private final List<TableRow> tableRows; public Table(List<String> headers) { this.headers = headers; rows = new ArrayList<>(); tableRows = new ArrayList<>(); } public void addRow(List<String> row) { if (row.size() != headers.size()) { throw new RowSizeMismatchException(String.format("Row size mismatch. Expected row size: %d. Obtained row size: %d.", headers.size(), row.size())); } rows.add(row); TableRow rowToAdd = new TableRow(); for (String header : headers) { rowToAdd.addCell(header, row.get(headers.indexOf(header))); } tableRows.add(rowToAdd); } /** * @return List of Names of the Columns on the table */ public List<String> getColumnNames() { return headers; } /** * Gets a Column name by index. * * @param columnIndex * @return a single column name by given column index. */ public String getColumnName(int columnIndex) { if (columnIndex < 0 || columnIndex >= getColumnNames().size()) { throw new IndexOutOfBoundsException(String.format("Column with index %d not found. Actual column size: %d.", columnIndex, getColumnNames().size())); } return getColumnNames().get(columnIndex); } /** * @return List of Rows in the table. Each Row is represented by a TableRow. */ public List<TableRow> getTableRows() { return tableRows; } /** * @return List of TableRows in the table. Each Row is represented by a List * of String values according to the order of column names * @deprecated Use getTableRows() method instead of this. */ @Deprecated public List<List<String>> getRows() { return rows; } /** * Get all the values of a column in Table. * * @param columnName * - The column name of the Table * @return List of values against a column in Table. */ public List<String> getColumnValues(String columnName) { int columnIndex = headers.indexOf(columnName); return getColumnValues(columnIndex); } /** * Get all the values of a column in a Table. * * @param columnIndex * - The column index of the table * @return List of row values of a given column index in a Table. */ public List<String> getColumnValues(int columnIndex) { if (columnIndex >= 0) { return rows.stream().map(row -> row.get(columnIndex)).collect(Collectors.toList()); } return new ArrayList<>(); } @Override public String toString() { int maxStringLength = getMaxStringLength(); if (maxStringLength >= 0) { return formatAsMarkdownTable(maxStringLength); } return StringUtils.EMPTY; } private String formatAsMarkdownTable(int maxStringLength) { List<String> formattedHeaderAndRows = new ArrayList<>(); addHeader(maxStringLength, formattedHeaderAndRows); addDashes(maxStringLength, formattedHeaderAndRows); addValues(maxStringLength, formattedHeaderAndRows); return Joiner.on(LINE_SEPARATOR).join(formattedHeaderAndRows); } private void addDashes(int maxStringLength, List<String> formattedHeaderAndRows) { String dashesString = Joiner.on(StringUtils.EMPTY).join(Collections.nCopies(maxStringLength, DASH)); List<String> dashes = Collections.nCopies(headers.size(), dashesString); String formattedDashes = formattedRow(dashes, maxStringLength); formattedHeaderAndRows.add(formattedDashes); } private void addHeader(int maxStringLength, List<String> formattedHeaderAndRows) { String formattedHeaders = formattedRow(headers, maxStringLength); formattedHeaderAndRows.add(formattedHeaders); } private void addValues(int maxStringLength, List<String> formattedHeaderAndRows) { tableRows.stream().map(tableRow -> formattedRow(tableRow.getCellValues(), maxStringLength)).forEach(formattedHeaderAndRows::add); } private String formattedRow(List<String> strings, int maxStringLength) { List<String> formattedStrings = Lists.transform(strings, format(maxStringLength)); return PIPE + Joiner.on(PIPE).join(formattedStrings) + PIPE; } private Function<String, String> format(final int maxStringLength) { return input -> Strings.padEnd(input, maxStringLength, SPACE_AS_CHAR); } private Integer getMaxStringLength() { List<Integer> maxs = new ArrayList<>(); maxs.add(getMaxStringSize(headers)); for (TableRow tableRow : tableRows) { maxs.add(getMaxStringSize(tableRow.getCellValues())); } return Collections.max(maxs); } private int getMaxStringSize(List<String> candidates) { if (candidates == null || candidates.isEmpty()) { return -1; } return Collections.max(candidates, maxStringLength()).length(); } private Comparator<String> maxStringLength() { return (o1, o2) -> { if (o1.length() < o2.length()) { return -1; } return 1; }; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((headers == null) ? 0 : headers.hashCode()); result = prime * result + ((rows == null) ? 0 : rows.hashCode()); result = prime * result + ((tableRows == null) ? 0 : tableRows.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Table other = (Table) obj; return headers.equals(other.getColumnNames()) && tableRows.equals(other.getTableRows()); } }
14,216
https://github.com/sean-roberts/parallel-data/blob/master/src/request-maker.js
Github Open Source
Open Source
MIT
2,021
parallel-data
sean-roberts
JavaScript
Code
353
1,035
import { error } from './console' import { assign } from './utils' let xhrRequests = {} let fetchRequests = {} let allRequestsOptions = {} const getKey = (method, url)=>{ return `${method.toUpperCase()}-${url}` } const makeXHRRequest = (method, url, headers, options )=>{ const key = getKey(method, url) // don't allow duplicate fetches for the same url/method combo if(xhrRequests[key]){ return; } const xhr = new XMLHttpRequest() const storedRequest = xhrRequests[key] = { url, method, headers, xhrRef: xhr, events: { load: null, error: null, timeout: null } } xhr.__PDInternal__ = true xhr.open(method, url) // merge in the allRequests headers with the request specific headers headers = assign({}, allRequestsOptions.headers, headers || {}) Object.keys(headers).forEach((key)=>{ xhr.setRequestHeader(key, headers[key]) }) if (options && options.onParallelDataResponse) { console.log('set'); xhr.addEventListener('readystatechange', () => { console.log('internal', xhr.readyState); if (xhr.readyState === 4) { options.onParallelDataResponse(xhr, { transferredToApp: !!xhr.__PDConsumed__ }) } }) } Object.keys(storedRequest.events).forEach((eventName)=>{ xhr.addEventListener(eventName, (event) => { storedRequest.events[eventName] = event }) }) xhr.send() } const makeFetchRequest = (method, url, options) => { const key = getKey(method, url) // don't allow duplicate fetches for the same url/method combo if(fetchRequests[key]){ return; } const fetchSent = fetchRequests[key] = fetch(url, assign({}, options, { __PDFetch__: true, method, // combine with allRequests configuration headers: assign({}, allRequestsOptions.headers, options.headers || {}), // forced if not defined credentials: options.credentials || 'include', redirect: options.redirect || 'follow' })).then( response => { if (options && options.onParallelDataResponse) { // note, cloning because interfaces like .text() and .json() can only be used once options.onParallelDataResponse(response.clone(), { transferredToApp: !!fetchSent.__PDConsumed__ }) } return response }).catch((e)=>{ error('fetch request failed', e); throw e }) } export function getForXHR (url, options){ options = options || {} try { makeXHRRequest('GET', url, options.headers, options) }catch(e){ error('makeXHRRequest failed', e) } } export function getForFetch (url, options){ options = options || {} try { if('fetch' in window && 'Promise' in window){ makeFetchRequest('GET', url, options) }else { // falling back to XHR if it is not supported getForXHR(url, options) } }catch(e){ error('fetch request failed', e) } } export function getRequestReference (request, type){ if(request && request.method && request.url){ const key = getKey(request.method, request.url) return type === 'xhr' ? xhrRequests[key] : fetchRequests[key] } } export function configureAllRequests (options){ allRequestsOptions = assign({}, allRequestsOptions, options || {}) }
1,063
https://github.com/tsuliuchao/gmc/blob/master/middleware/accesslog/accesslog.go
Github Open Source
Open Source
MIT
null
gmc
tsuliuchao
Go
Code
157
758
package accesslog import ( "fmt" "github.com/snail007/gmc" gmclog "github.com/snail007/gmc/base/log" gmcconfig "github.com/snail007/gmc/config" gmcrouter "github.com/snail007/gmc/http/router" "github.com/snail007/gmc/util/cast" "strings" "time" ) type accesslog struct { logger *gmclog.GMCLog format string } func newFromConfig(c *gmcconfig.Config) *accesslog { cfg := c.Sub("accesslog") logger := gmclog.NewGMCLog().(*gmclog.GMCLog) logger.SetFlags(0) logger.SetOutput(gmclog.NewFileWriter(cfg.GetString("filename"), cfg.GetString("dir"), cfg.GetBool("gzip"))) logger.EnableAsync() return &accesslog{ format: cfg.GetString("format"), logger: logger, } } func NewWebFromConfig(c *gmcconfig.Config) gmc.MiddlewareWeb { a := newFromConfig(c) return func(ctx *gmcrouter.Ctx, server *gmc.HTTPServer) (isStop bool) { go log(ctx, a) return false } } func NewAPIFromConfig(c *gmcconfig.Config) gmc.MiddlewareAPI { a := newFromConfig(c) return func(ctx *gmcrouter.Ctx, server *gmc.APIServer) (isStop bool) { go log(ctx, a) return false } } func log(ctx *gmcrouter.Ctx, logger *accesslog) { rule := [][]string{ []string{"$host", ctx.Request.Host}, []string{"$uri", ctx.Request.URL.RequestURI()}, []string{"$time_used", cast.ToString(int(ctx.TimeUsed() / time.Millisecond))}, []string{"$status_code", cast.ToString(ctx.StatusCode())}, []string{"$query", ctx.Request.URL.Query().Encode()}, []string{"$req_time", time.Now().Format("2006-01-02 15:04:05")}, []string{"$client_ip", ctx.ClientIP()}, []string{"$remote_addr", ctx.Request.RemoteAddr}, []string{"$local_addr", ctx.LocalAddr}, } str := logger.format for _, v := range rule { key := fmt.Sprintf("${%s}", v[0][1:]) str = strings.Replace(str, key, v[1], 1) str = strings.Replace(str, v[0], v[1], 1) } logger.logger.Write(str + "\n") }
22,796
https://github.com/deshankoswatte/tesb-rt-se/blob/master/job/controller/src/test/java/org/talend/esb/job/controller/internal/RuntimeESBConsumerTest.java
Github Open Source
Open Source
Apache-2.0
null
tesb-rt-se
deshankoswatte
Java
Code
419
1,444
/* * #%L * Talend :: ESB :: Job :: Controller * %% * Copyright (C) 2011-2020 Talend 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. * #L% */ package org.talend.esb.job.controller.internal; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.talend.esb.job.controller.ESBEndpointConstants.EsbSecurity; import org.talend.esb.sam.agent.feature.EventFeature; import org.talend.esb.servicelocator.cxf.LocatorFeature; import org.xml.sax.ErrorHandler; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.apache.cxf.Bus; import org.apache.cxf.feature.Feature; import org.apache.cxf.headers.Header; import org.apache.neethi.Policy; import org.apache.wss4j.common.crypto.Crypto; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import static org.easymock.EasyMock.createNiceMock; public class RuntimeESBConsumerTest { private ClassPathXmlApplicationContext serviceContext; private ClassPathXmlApplicationContext startContext(String configFileName) { ClassPathXmlApplicationContext context; context = new ClassPathXmlApplicationContext( new String[] { configFileName }); context.start(); return context; } @Before public void startCustomerService() { startContext("classpath:conf/libraryService/spring/service-context.xml"); } @Test public void noPropertiesSetProvidesEmptyArgumentList() throws Exception { QName serviceName = new QName("http://services.talend.org/test/Library/1.0", "LibraryProvider"); QName portName = new QName("http://services.talend.org/test/Library/1.0", "LibraryHttpPort"); QName operationName = new QName("http://services.talend.org/test/Library/1.0", "seekBook"); String publishedEndpointUrl = "local://LibraryHttpPort"; String wsdlURL = "classpath:/conf/libraryService/Library.wsdl"; boolean useServiceLocator = false; LocatorFeature locatorFeature = null; Map<String, String> locatorProps = new HashMap<String, String>(); EventFeature samFeature = null; Map<String, String> samProps = new HashMap<String, String>(); boolean useServiceRegistry = false; EsbSecurity esbSecurity = null; Policy policy = null; String username = ""; String password = ""; String alias = ""; Map<String, String> clientProperties = new HashMap<String, String>(); String roleName = ""; Object securityToken = null; Crypto cryptoProvider = null; SecurityArguments securityArguments = new SecurityArguments(esbSecurity, policy, username, password, alias, clientProperties, roleName, securityToken, cryptoProvider); Bus bus = null; boolean logging = false; List<Header> soapHeaders = new ArrayList<Header>(); Feature httpHeadersFeature = null; boolean enhancedResponse = false; Object correlationIDCallbackHandler = null; final boolean useGZipCompression = false; RuntimeESBConsumer consumer = new RuntimeESBConsumer(serviceName, portName, operationName, publishedEndpointUrl, wsdlURL, useServiceLocator, locatorFeature, locatorProps, samFeature, samProps, useServiceRegistry, securityArguments, bus, logging, soapHeaders, httpHeadersFeature, enhancedResponse, correlationIDCallbackHandler, useGZipCompression); String requestString = "<ns2:SearchFor xmlns:ns2=\"http://types.talend.org/test/Library/Common/1.0\" "+ "xmlns:ns3=\"http://types.talend.org/test/GeneralObjects/ErrorHandling/1.0\">" + "<AuthorLastName>Icebear</AuthorLastName><ISBNNumber>123</ISBNNumber></ns2:SearchFor>"; consumer.invoke(getDocumentFromString(requestString)); } private Document getDocumentFromString(String xmlString) { SAXReader reader = new SAXReader(); reader.setValidation(false); reader.setErrorHandler(createNiceMock(ErrorHandler.class)); try { return reader.read(new StringReader(xmlString)); } catch (DocumentException e) { return null; } } @After public void closeContextAfterEachTest() { if (serviceContext != null) { serviceContext.stop(); serviceContext.close(); serviceContext = null; } } }
18,332
https://github.com/PCOL/FluentIL/blob/master/test/FluentILUnitTests/Resources/ITestInterface.cs
Github Open Source
Open Source
MIT
2,022
FluentIL
PCOL
C#
Code
34
79
namespace FluentILUnitTests.Resources { /// <summary> /// defines a test interface. /// </summary> public interface ITestInterface { /// <summary> /// Gets or sets a property. /// </summary> string GetSetProperty { get; set; } } }
14,787
https://github.com/whitemike889/hotchocolate/blob/master/src/Client/Demo/GraphQL/Generated/StarWarsClient.cs
Github Open Source
Open Source
MIT
null
hotchocolate
whitemike889
C#
Code
135
507
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using StrawberryShake; namespace StrawberryShake.Client.GraphQL { public class StarWarsClient : IStarWarsClient { private readonly IOperationExecutor _executor; public StarWarsClient(IOperationExecutor executor) { _executor = executor ?? throw new ArgumentNullException(nameof(executor)); } public Task<IOperationResult<IGetHero>> GetHeroAsync( Episode? episode) => GetHeroAsync(episode, CancellationToken.None); public Task<IOperationResult<IGetHero>> GetHeroAsync( Episode? episode, CancellationToken cancellationToken) { return _executor.ExecuteAsync( new GetHeroOperation {Episode = episode }, cancellationToken); } public Task<IOperationResult<IGetHuman>> GetHumanAsync( string id) => GetHumanAsync(id, CancellationToken.None); public Task<IOperationResult<IGetHuman>> GetHumanAsync( string id, CancellationToken cancellationToken) { if (id is null) { throw new ArgumentNullException(nameof(id)); } return _executor.ExecuteAsync( new GetHumanOperation {Id = id }, cancellationToken); } public Task<IOperationResult<ISearch>> SearchAsync( string text) => SearchAsync(text, CancellationToken.None); public Task<IOperationResult<ISearch>> SearchAsync( string text, CancellationToken cancellationToken) { if (text is null) { throw new ArgumentNullException(nameof(text)); } return _executor.ExecuteAsync( new SearchOperation {Text = text }, cancellationToken); } } }
6,338
https://github.com/moazzamwaheed2017/carparkapi/blob/master/CarParkArcGisApi/CarParkArcGisApi/env/Lib/site-packages/arcgis/geoanalytics/find_locations.py
Github Open Source
Open Source
MIT
null
carparkapi
moazzamwaheed2017
Python
Code
3,388
8,006
""" These tools are used to identify areas that meet a number of different criteria you specify. find_similar_locations finds locations most similar to one or more reference locations based on criteria you specify. """ import json as _json import logging as _logging import arcgis as _arcgis from arcgis.features import FeatureSet as _FeatureSet from arcgis.geoprocessing._support import _execute_gp_tool from ._util import _id_generator, _feature_input, _set_context, _create_output_service, GAJob import datetime _log = _logging.getLogger(__name__) # url = "https://dev003153.esri.com/gax/rest/services/System/GeoAnalyticsTools/GPServer" _use_async = True def geocode_locations(input_layer, country=None, category=None, include_attributes=True, locator_parameters=None, output_name=None, geocode_service=None, geocode_parameters=None, gis=None, context=None, future=False): """ .. image:: _static/images/geocode_locations/geocode_locations.png The ``geocode_locations`` task geocodes a table from a big data file share. The task uses a geocode utility service configured with your portal. If you do not have a geocode utility service configured, talk to your administrator. `Learn more about configuring a locator service <https://enterprise.arcgis.com/en/portal/latest/administer/windows/configure-portal-to-geocode-addresses.htm>`_. When preparing to use the Geocode Location task be sure to review `Best Practices for geocoding with GeoAnalytics Server <https://enterprise.arcgis.com/en/portal/latest/use/geoanalytics-geocoding-best-practices.htm>`_. ========================== =============================================================== **Argument** **Description** -------------------------- --------------------------------------------------------------- input_layer Required layer. The tabular input that will be geocoded. See :ref:`Feature Input<FeatureInput>`. -------------------------- --------------------------------------------------------------- country Optional string. If all your data is in one country, this helps improve performance for locators that accept that variable. -------------------------- --------------------------------------------------------------- category Optional string. Enter a category for more precise geocoding results, if applicable. Some geocoding services do not support category, and the available options depend on your geocode service. -------------------------- --------------------------------------------------------------- include_attributes Optional boolean. A Boolean value to return the output fields from the geocoding service in the results. To output all available output fields, set this value to 'True'. Setting the value to false will return your original data and with geocode coordinates. Some geocoding services do not support output fields, and the available options depend on your geocode service. -------------------------- --------------------------------------------------------------- locator_parameters Optional dict. Additional parameters specific to your locator. -------------------------- --------------------------------------------------------------- output_name Optional string. The task will create a feature service of the results. You define the name of the service. -------------------------- --------------------------------------------------------------- geocode_service Optional string or Geocoder. The URL of the geocode service that you want to geocode your addresses against. The URL must end in geocodeServer and allow batch requests. The geocode service must be configured to allow for batch geocoding. For more information, see `Configuring batch geocoding <https://enterprise.arcgis.com/en/portal/latest/administer/windows/configure-portal-to-geocode-addresses.htm>`_ -------------------------- --------------------------------------------------------------- geocode_parameters optional dict. This includes parameters that help parse the input data, as well the field lengths and a field mapping. This value is the output from the AnalyzeGeocodeInput tool available on your server designated to geocode. It is important to inspect the field mapping closely and adjust them accordingly before submitting your job, otherwise your geocoding results may not be accurate. It is recommended to use the output from AnalyzeGeocodeInput and modify the field mapping instead of constructing this JSON by hand. **Values** **field_info** - A list of triples with the field names of your input data, the field type (usually TEXT), and the allowed length (usually 255). Example: [['ObjectID', 'TEXT', 255], ['Address', 'TEXT', 255], ['Region', 'TEXT', 255], ['Postal', 'TEXT', 255]] **header_row_exists** - Enter true or false. **column_names** - Submit the column names of your data if your data does not have a header row. **field_mapping** - Field mapping between each input field and candidate fields on the geocoding service. Example: [['ObjectID', 'OBJECTID'], ['Address', 'Address'], ['Region', 'Region'], ['Postal', 'Postal']] -------------------------- --------------------------------------------------------------- gis Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used. -------------------------- --------------------------------------------------------------- context Optional dict. Context contains additional settings that affect task execution. For this task, there are three settings: Processing spatial reference (``processSR``) - The features will be projected into this coordinate system for analysis. Output spatial reference (``outSR``) - The features will be projected into this coordinate system after the analysis to be saved. The output spatial reference for the spatiotemporal big data store is always WGS84. Data store (``dataStore``) - Results will be saved to the specified data store. The default is the spatiotemporal big data store. -------------------------- --------------------------------------------------------------- future Optional boolean. If True, a GPJob is returned instead of results. The GPJob can be queried on the status of the execution. ========================== =============================================================== :returns: Feature Layer .. code-block:: python # Usage Example: To geocode a big data file share of mailing addresses in the United States Northwest. geocode_server = "https://mymachine.domain.com/server/rest/services/USALocator/GeocodeServer" geo_parameters = {"field_info": "[('ObjectID', 'TEXT', 255), ('Street', 'TEXT', 255), ('City', 'TEXT', 255), ('Region', 'TEXT', 255), ('State', 'TEXT', 255)]", "column_names": "", "file_type": "table", "header_row_exists": "true", "field_mapping": "[[\"Street\", \"Street\"], [\"City\", \"City\"], [\"State\", \"State\"], [\"ZIP\", \"ZIP\"]]"} geocode_result = find_locations.geocode_locations(input_layer=NW_addresses, output_name="geocoded_NW_USA", geocode_service=geocode_server, geocode_parameters = geo_parameters) """ from arcgis.features.layer import Layer from arcgis.gis import Item from arcgis.geocoding._functions import Geocoder kwargs = locals() tool_name = "GeocodeLocations" gis = _arcgis.env.active_gis if gis is None else gis url = gis.properties.helperServices.geoanalytics.url params = { "f" : "json" } for key, value in kwargs.items(): if value is not None: params[key] = value if output_name is None: output_service_name = 'Geocoding_Results_' + _id_generator() output_service_name = output_service_name.replace(' ', '_') else: output_service_name = output_name.replace(' ', '_') if isinstance(input_layer, str): input_layer = {'url' : input_layer} elif isinstance(input_layer, Item): input_layer = input_layer.layers[0]._lyr_dict if 'type' in input_layer: input_layer.pop('type') elif isinstance(input_layer, Layer): input_layer = input_layer._lyr_dict if 'type' in input_layer: input_layer.pop('type') elif isinstance(input_layer, dict) and \ not "url" in input_layer: raise ValueError("Invalid Input: input_layer dictionary" + \ " must have format {'url' : <url>}") elif isinstance(input_layer, dict) and "url" in input_layer: pass else: raise ValueError("Invalid input_layer input. Please pass an Item, " + \ "Big DataStore Layer or Big DataStore URL to geocode.") if geocode_service is None: for service in gis.properties.helperServices.geocode: if 'batch' in service and service['batch'] == True: geocode_service_url = service["url"] break if geocode_service_url is None: raise ValueError("A geocoder with batch enabled must be configured" + \ " with this portal to use this service.") params['geocode_service_url'] = geocode_service_url elif isinstance(geocode_service, Geocoder): geocode_service = geocode_service.url params['geocode_service_url'] = geocode_service_url elif isinstance(geocode_service, str): params['geocode_service_url'] = geocode_service else: raise ValueError("geocode_service_url must be a string or GeoCoder") if geocode_parameters is None: from arcgis.geoprocessing._tool import Toolbox analyze_geocode_url = gis.properties.helperServices.asyncGeocode.url tbx = Toolbox(url=analyze_geocode_url, gis=gis) geocode_parameters = tbx.analyze_geocode_input(input_table=input_layer, geocode_service_url=geocode_service_url) params['geocode_parameters'] = geocode_parameters output_service = _create_output_service(gis, output_name, output_service_name, 'Geocoded Locations') params['output_name'] = _json.dumps({ "serviceProperties": {"name" : output_name, "serviceUrl" : output_service.url}, "itemProperties": {"itemId" : output_service.itemid}}) _set_context(params) param_db = { "input_layer": (_FeatureSet, "inputLayer"), "geocode_service_url": (str, "geocodeServiceURL"), "geocode_parameters": (str, "geocodeParameters"), "country": (str, "sourceCountry"), "category": (str, "category"), "include_attributes" : (bool, "includeAttributes"), "locator_parameters" : (str, "locatorParameters"), "output_name": (str, "outputName"), "output": (_FeatureSet, "output"), "context": (str, "context") } return_values = [ {"name": "output", "display_name": "Output Features", "type": _FeatureSet}, ] try: if future: gpjob = _execute_gp_tool(gis, tool_name, params, param_db, return_values, _use_async, url, True, future=future) return GAJob(gpjob=gpjob, return_service=output_service) res = _execute_gp_tool(gis, tool_name, params, param_db, return_values, _use_async, url, True, future=future) return output_service except: output_service.delete() raise return def detect_incidents(input_layer, track_fields, start_condition_expression, end_condition_expression=None, output_mode="AllFeatures", time_boundary_split=None, time_split_unit=None, time_reference=None, output_name=None, gis=None, context=None, future=False): """ .. image:: _static/images/detect_incidents/detect_incidents.png The ``detect_incidents`` task works with a time-enabled layer of points, lines, areas, or tables that represents an instant in time. Using sequentially ordered features, called tracks, this tool determines which features are incidents of interest. Incidents are determined by conditions that you specify. First, the tool determines which features belong to a track using one or more fields. Using the time at each feature, the tracks are ordered sequentially and the incident condition is applied. Features that meet the starting incident condition are marked as an incident. You can optionally apply an ending incident condition; when the end condition is 'True', the feature is no longer an incident. The results will be returned with the original features with new columns representing the incident name and indicate which feature meets the incident condition. You can return all original features, only the features that are incidents, or all of the features within tracks where at least one incident occurred. For example, suppose you have GPS measurements of hurricanes every 10 minutes. Each GPS measurement records the hurricane's name, location, time of recording, and wind speed. Using these fields, you could create an incident where any measurement with a wind speed greater than 208 km/h is an incident titled Catastrophic. By not setting an end condition, the incident would end if the feature no longer meets the start condition (wind speed slows down to less than 208). Using another example, suppose you were monitoring concentrations of a chemical in your local water supply using a field called contanimateLevel. You know that the recommended levels are less than 0.01 mg/L, and dangerous levels are above 0.03 mg/L. To detect incidents, where a value above 0.03mg/L is an incident, and remains an incident until contamination levels are back to normal, you create an incident using a start condition of contanimateLevel > 0.03 and an end condition of contanimateLevel < 0.01. This will mark any sequence where values exceed 0.03mg/L until they return to a value less than 0.01. ========================== =============================================================== **Argument** **Description** -------------------------- --------------------------------------------------------------- input_layer Required layer. The table, point, line or polygon features containing potential incidents. See :ref:`Feature Input<FeatureInput>`. -------------------------- --------------------------------------------------------------- track_fields Required string. The fields used to identify distinct tracks. There can be multiple ``track_fields``. -------------------------- --------------------------------------------------------------- start_condition_expression Required string. The condition used to identify incidents. If there is no ``end_condition_expression`` specified, any feature that meets this condition is an incident. If there is an end condition, any feature that meets the ``start_condition_expression`` and does not meet the ``end_condition_expression`` is an incident. The expressions are Arcade expressions. -------------------------- --------------------------------------------------------------- end_condition_expression Optional string. The condition used to identify incidents. If there is no ``end_condition_expression`` specified, any feature that meets this condition is an incident. If there is an end condition, any feature that meets the ``start_condition_expression`` and does not meet the ``end_condition_expression`` is an incident. This is an Arcade expression. -------------------------- --------------------------------------------------------------- output_mode Optional string. Determines which features are returned. Choice list: [AllFeatures', 'Incidents'] - ``AllFeatures`` - All of the input features are returned. - ``Incidents`` - Only features that were found to be incidents are returned. The default value is 'AllFeatures'. -------------------------- --------------------------------------------------------------- time_boundary_split Optional integer. A time boundary to detect and incident. A time boundary allows your to analyze values within a defined time span. For example, if you use a time boundary of 1 day, starting on January 1st, 1980 tracks will be analyzed 1 day at a time. The time boundary parameter was introduced in ArcGIS Enterprise 10.7. The ``time_boundary_split`` parameter defines the scale of the time boundary. In the case above, this would be 1. See the portal documentation for this tool to learn more. -------------------------- --------------------------------------------------------------- time_split_unit Optional string. The unit to detect an incident is `time_boundary_split` is used. Choice list: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds', 'Milliseconds']. -------------------------- --------------------------------------------------------------- time_reference Optional datetime.detetime. The starting date/time where analysis will begin from. -------------------------- --------------------------------------------------------------- output_name optional string, The task will create a feature service of the results. You define the name of the service. -------------------------- --------------------------------------------------------------- gis optional GIS, the GIS on which this tool runs. If not specified, the active GIS is used. -------------------------- --------------------------------------------------------------- context Optionl dict. The context parameter contains additional settings that affect task execution. For this task, there are four settings: #. Extent (``extent``) - A bounding box that defines the analysis area. Only those features that intersect the bounding box will be analyzed. #. Processing spatial reference (``processSR``) - The features will be projected into this coordinate system for analysis. #. Output spatial reference (``outSR``) - The features will be projected into this coordinate system after the analysis to be saved. The output spatial reference for the spatiotemporal big data store is always WGS84. #. Data store (``dataStore``) - Results will be saved to the specified data store. The default is the spatiotemporal big data store. -------------------------- --------------------------------------------------------------- future optional boolean. If True, a GPJob is returned instead of results. The GPJob can be queried on the status of the execution. The default value is 'False'. ========================== =============================================================== :returns: result_layer : Output Features as feature layer collection item. .. code-block:: python # Usage Example: This example finds when and where snowplows were moving slower than 10 miles per hour by calculating the mean of a moving window of five speed values. arcgis.env.verbose = True # set environment arcgis.env.defaultAggregations = True # set environment delay_incidents = output = detect_incidents(input_layer=snowplows, track_fields="plowID, dayOfYear", start_condition_expression="Mean($track.field["speed"].window(-5, 0)) < 10", output_name="Slow_Plow_Incidents") """ kwargs = locals() tool_name = "DetectIncidents" gis = _arcgis.env.active_gis if gis is None else gis url = gis.properties.helperServices.geoanalytics.url params = { "f" : "json" } for key, value in kwargs.items(): if value is not None: params[key] = value if output_name is None: output_service_name = 'Detect_Incidents_' + _id_generator() output_name = output_service_name.replace(' ', '_') else: output_service_name = output_name.replace(' ', '_') output_service = _create_output_service(gis, output_name, output_service_name, 'Detect Track Incidents') params['output_name'] = _json.dumps({ "serviceProperties": {"name" : output_name, "serviceUrl" : output_service.url}, "itemProperties": {"itemId" : output_service.itemid}}) if context is not None: params["context"] = context else: _set_context(params) param_db = { "input_layer": (_FeatureSet, "inputLayer"), "track_fields": (str, "trackFields"), "start_condition_expression": (str, "startConditionExpression"), "end_condition_expression": (str, "endConditionExpression"), "output_mode": (str, "outputMode"), "time_boundary_split" : (int, "timeBoundarySplit"), "time_split_unit" : (str, "timeBoundarySplitUnit"), "time_reference" : (datetime.datetime, "timeBoundaryReference"), "output_name": (str, "outputName"), "output": (_FeatureSet, "output"), "context": (str, "context") } return_values = [ {"name": "output", "display_name": "Output Features", "type": _FeatureSet}, ] try: if future: gpjob = _execute_gp_tool(gis, tool_name, params, param_db, return_values, _use_async, url, True, future=future) return GAJob(gpjob=gpjob, return_service=output_service) _execute_gp_tool(gis, tool_name, params, param_db, return_values, _use_async, url, True, future=future) return output_service except: output_service.delete() raise return def find_similar_locations( input_layer, search_layer, analysis_fields, most_or_least_similar="MostSimilar", match_method="AttributeValues", number_of_results=10, append_fields=None, output_name=None, gis=None, context=None, future=False, return_tuple=False): """ .. image:: _static/images/find_similar_locations/find_similar_locations.png The ``find_similar_locations`` task measures the similarity of candidate locations to one or more reference locations. Based on criteria you specify, ``find_similar_locations`` can answer questions such as the following: * Which of your stores are most similar to your top performers with regard to customer profiles? * Based on characteristics of villages hardest hit by the disease, which other villages are high risk? * To answer questions such as these, you provide the reference locations (the ``input_layer`` parameter), the candidate locations (the ``search_layer`` parameter), and the fields representing the criteria you want to match. For example, the ``input_layer`` might be a layer containing your top performing stores or the villages hardest hit by the disease. The ``search_layer`` contains your candidate locations to search. This might be all of your stores or all other villages. Finally, you supply a list of fields to use for measuring similarity. The ``find_similar_locations`` task will rank all of the candidate locations by how closely they match your reference locations across all of the fields you have selected. ========================== =============================================================== **Argument** **Description** -------------------------- --------------------------------------------------------------- input_layer Required layer. The ``input_layer`` contains one or more reference locations against which features in the ``search_layer`` will be evaluated for similarity. For example, the ``input_layer`` might contain your top performing stores or the villages hardest hit by a disease. See :ref:`Feature Input<FeatureInput>`. It is not uncommon for ``input_layer`` and ``search_layer`` to be the same feature service. For example, the feature service contains locations of all stores, one of which is your top performing store. If you want to rank the remaining stores from most to least similar to your top performing store, you can provide a filter for both ``input_layer`` and ``search_layer``. The filter on ``input_layer`` would select the top performing store, while the filter on ``search_layer`` would select all stores except for the top performing store. You can use the optional filter parameter to specify reference locations. If there is more than one reference location, similarity will be based on averages for the fields you specify in the ``analysis_fields`` parameter. For example, if there are two reference locations and you are interested in matching population, the task will look for candidate locations in ``search_layer`` with populations that are most like the average population for both reference locations. If the values for the reference locations are 100 and 102, for example, the task will look for candidate locations with populations near 101. Consequently, you will want to use fields for the reference locations fields that have similar values. If, for example, the population values for one reference location is 100 and the other is 100,000, the tool will look for candidate locations with population values near the average of those two values: 50,050. Notice that this averaged value is nothing like the population for either of the reference locations. -------------------------- --------------------------------------------------------------- search_layer Required layer. The layer containing candidate locations that will be evaluated against the reference locations. See :ref:`Feature Input<FeatureInput>`. -------------------------- --------------------------------------------------------------- analysis_fields Required string. A list of fields whose values are used to determine similarity. They must be numeric fields, and the fields must exist on both the ``input_layer`` and the ``search_layer``. Depending on the ``match_method`` selected, the task will find features that are most similar based on values or profiles of the fields. -------------------------- --------------------------------------------------------------- most_or_least_similar Optional string. The features you want to be returned. You can search for features that are either most similar or least similar to the ``input_layer``, or search both the most and least similar. Choice list:['MostSimilar', 'LeastSimilar', 'Both'] The default value is 'MostSimilar'. -------------------------- --------------------------------------------------------------- match_method Optional string. The method you select determines how matching is determined. Choice list:['AttributeValues', 'AttributeProfiles'] * The ``AttributeValues`` method uses the squared differences of standardized values. * The ``AttributeProfiles`` method uses cosine similarity mathematics to compare the profile of standardized values. Using ``AttributeProfiles`` requires the use of at least two analysis fields. The default value is 'AttributeValues'. -------------------------- --------------------------------------------------------------- number_of_results Optional integer. The number of ranked candidate locations output to ``similar_result_layer``. If ``number_of_results`` is not set, the 10 locations will be returned. The maximum number of results is 10000. The default value is 10. -------------------------- --------------------------------------------------------------- append_fields Optional string. Optionally add fields to your data from your search layer. By default, all fields from the search layer are appended. -------------------------- --------------------------------------------------------------- output_name Optional string. The task will create a feature service of the results. You define the name of the service. -------------------------- --------------------------------------------------------------- gis Optional GIS. The GIS on which this tool runs. If not specified, the active GIS is used. -------------------------- --------------------------------------------------------------- context Optional dict. The context parameter contains additional settings that affect task execution. For this task, there are four settings: #. Extent (``extent``) - A bounding box that defines the analysis area. Only those features that intersect the bounding box will be analyzed. #. Processing spatial reference (``processSR``) - The features will be projected into this coordinate system for analysis. #. Output spatial reference (``outSR``) - The features will be projected into this coordinate system after the analysis to be saved. The output spatial reference for the spatiotemporal big data store is always WGS84. #. Data store (``dataStore``) - Results will be saved to the specified data store. The default is the spatiotemporal big data store. -------------------------- --------------------------------------------------------------- future Optional boolean. If 'True', a GPJob is returned instead of results. The GPJob can be queried on the status of the execution. The default value is 'False'. -------------------------- --------------------------------------------------------------- return_tuple Optional boolean. If 'True', a named tuple with multiple output keys is returned. The default value is 'False'. ========================== =============================================================== :returns: named tuple with the following keys if ``return_tuple`` is set to 'True': "output" : feature layer "process_info" : list else returns a feature layer of the results. .. code-block:: python # Usage Example: To find potential retail locations based on the current top locations and their attributes. similar_location_result = find_similar_locations(input_layer=stores_layer, search_layer=locations, analysis_fields="median_income, population, nearest_competitor", most_or_least_similar="MostSimilar", match_method="AttributeValues", number_of_results=50, output_name="similar_locations") """ kwargs = locals() gis = _arcgis.env.active_gis if gis is None else gis url = gis.properties.helperServices.geoanalytics.url params = {} for key, value in kwargs.items(): if value is not None: params[key] = value if output_name is None: output_service_name = 'Similar Locations_' + _id_generator() output_name = output_service_name.replace(' ', '_') else: output_service_name = output_name.replace(' ', '_') output_service = _create_output_service(gis, output_name, output_service_name, 'Find Similar Locations') params['output_name'] = _json.dumps({ "serviceProperties": {"name" : output_name, "serviceUrl" : output_service.url}, "itemProperties": {"itemId" : output_service.itemid}}) if context is not None: params["context"] = context else: _set_context(params) param_db = { "input_layer": (_FeatureSet, "inputLayer"), "search_layer": (_FeatureSet, "searchLayer"), "analysis_fields": (str, "analysisFields"), "most_or_least_similar": (str, "mostOrLeastSimilar"), "match_method": (str, "matchMethod"), "number_of_results": (int, "numberOfResults"), "append_fields": (str, "appendFields"), "output_name": (str, "outputName"), "context": (str, "context"), "return_tuple": (bool, "returnTuple"), "output": (_FeatureSet, "Output Features"), "process_info": (list, "processInfo") } return_values = [ {"name": "output", "display_name": "Output Features", "type": _FeatureSet}, {"name": "process_info", "display_name": "Process Information", "type": list} ] try: if future: gpjob = _execute_gp_tool(gis, "FindSimilarLocations", params, param_db, return_values, _use_async, url, True, future=future) return GAJob(gpjob=gpjob, return_service=output_service) res = _execute_gp_tool(gis, "FindSimilarLocations", params, param_db, return_values, _use_async, url, True, future=future) if return_tuple: return res else: return output_service except: output_service.delete() raise find_similar_locations.__annotations__ = { 'most_or_least_similar': str, 'match_method': str, 'number_of_results': int, 'append_fields': str, 'output_name': str}
49,934
https://github.com/nitika4/JsonPath/blob/master/json-path/src/test/java/com/jayway/jsonpath/TransformationBasicTest.java
Github Open Source
Open Source
Apache-2.0
2,022
JsonPath
nitika4
Java
Code
90
415
package com.jayway.jsonpath; import com.jayway.jsonpath.spi.transformer.TransformationSpec; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.nio.charset.Charset; import static org.junit.Assert.assertEquals; public class TransformationBasicTest { InputStream sourceStream; InputStream transformSpec; Configuration configuration; TransformationSpec spec; Object sourceJson; @Before public void setup() { configuration = Configuration.builder() .options(Option.CREATE_MISSING_PROPERTIES_ON_DEFINITE_PATH).build(); sourceStream = this.getClass().getClassLoader().getResourceAsStream("transforms/transformsource.json"); sourceJson = configuration.jsonProvider().parse(sourceStream, Charset.defaultCharset().name()); DocumentContext jsonContext = JsonPath.parse(sourceJson); System.out.println("Document Input :" + jsonContext.jsonString()); transformSpec = this.getClass().getClassLoader().getResourceAsStream("transforms/transformspec.json"); spec = configuration.transformationProvider().spec(transformSpec, configuration); } @Test public void simple_transform_spec_test() { Object transformed = configuration.transformationProvider().transform(sourceJson,spec, configuration); DocumentContext jsonContext = JsonPath.parse(transformed); String path = "$.shipment.unloading.location"; assertEquals("-98,225", jsonContext.read(path)); System.out.println("Document Created by Transformation:" + jsonContext.jsonString()); } }
307
https://github.com/adrianstevens/Xamarin-Plugins/blob/master/SimpleAudioPlayer/SimpleAudioPlayer/Plugin.SimpleAudioPlayer.Android/SimpleAudioPlayerImplementation.cs
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,022
Xamarin-Plugins
adrianstevens
C#
Code
680
1,939
using Android.Content.Res; using System; using System.IO; using Uri = Android.Net.Uri; namespace Plugin.SimpleAudioPlayer { /// <summary> /// Implementation for Feature /// </summary> [Android.Runtime.Preserve(AllMembers = true)] public class SimpleAudioPlayerImplementation : ISimpleAudioPlayer { ///<Summary> /// Raised when audio playback completes successfully ///</Summary> public event EventHandler PlaybackEnded; Android.Media.MediaPlayer player; static int index = 0; ///<Summary> /// Length of audio in seconds ///</Summary> public double Duration => player == null ? 0 : player.Duration / 1000.0; ///<Summary> /// Current position of audio playback in seconds ///</Summary> public double CurrentPosition => player == null ? 0 : (player.CurrentPosition) / 1000.0; ///<Summary> /// Playback volume (0 to 1) ///</Summary> public double Volume { get =>_volume; set { SetVolume(_volume = value, Balance); } } double _volume = 0.5; ///<Summary> /// Balance left/right: -1 is 100% left : 0% right, 1 is 100% right : 0% left, 0 is equal volume left/right ///</Summary> public double Balance { get => _balance; set { SetVolume(Volume, _balance = value); } } double _balance = 0; ///<Summary> /// Indicates if the currently loaded audio file is playing ///</Summary> public bool IsPlaying => player != null && player.IsPlaying; ///<Summary> /// Continously repeats the currently playing sound ///</Summary> public bool Loop { get => _loop; set { _loop = value; if (player != null) player.Looping = _loop; } } bool _loop; ///<Summary> /// Indicates if the position of the loaded audio file can be updated ///</Summary> public bool CanSeek => player != null; string path; /// <summary> /// Instantiates a new SimpleAudioPlayer /// </summary> public SimpleAudioPlayerImplementation() { player = new Android.Media.MediaPlayer() { Looping = Loop }; player.Completion += OnPlaybackEnded; } ///<Summary> /// Load wav or mp3 audio file as a stream ///</Summary> public bool Load(Stream audioStream) { player.Reset(); DeleteFile(path); //cache to the file system path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"cache{index++}.wav"); var fileStream = File.Create(path); audioStream.CopyTo(fileStream); fileStream.Close(); try { player.SetDataSource(path); } catch { try { var context = Android.App.Application.Context; player?.SetDataSource(context, Uri.Parse(Uri.Encode(path))); } catch { return false; } } return PreparePlayer(); } ///<Summary> /// Load wav or mp3 audio file from the iOS Resources folder ///</Summary> public bool Load(string fileName) { player.Reset(); AssetFileDescriptor afd = Android.App.Application.Context.Assets.OpenFd(fileName); player?.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length); return PreparePlayer(); } bool PreparePlayer() { player?.Prepare(); return player != null; } void DeletePlayer() { Stop(); if (player != null) { player.Completion -= OnPlaybackEnded; player.Release(); player.Dispose(); player = null; } DeleteFile(path); path = string.Empty; } void DeleteFile(string path) { if (string.IsNullOrWhiteSpace(path) == false) { try { File.Delete(path); } catch { } } } ///<Summary> /// Begin playback or resume if paused ///</Summary> public void Play() { if (player == null) return; if (IsPlaying) { Pause(); Seek(0); } player.Start(); } ///<Summary> /// Stop playack and set the current position to the beginning ///</Summary> public void Stop() { if(!IsPlaying) return; Pause(); Seek(0); PlaybackEnded?.Invoke(this, EventArgs.Empty); } ///<Summary> /// Pause playback if playing (does not resume) ///</Summary> public void Pause() { player?.Pause(); } ///<Summary> /// Set the current playback position (in seconds) ///</Summary> public void Seek(double position) { if(CanSeek) player?.SeekTo((int)(position * 1000D)); } ///<Summary> /// Sets the playback volume as a double between 0 and 1 /// Sets both left and right channels ///</Summary> void SetVolume(double volume, double balance) { volume = Math.Max(0, volume); volume = Math.Min(1, volume); balance = Math.Max(-1, balance); balance = Math.Min(1, balance); // Using the "constant power pan rule." See: http://www.rs-met.com/documents/tutorials/PanRules.pdf var left = Math.Cos((Math.PI * (balance + 1)) / 4) * volume; var right = Math.Sin((Math.PI * (balance + 1)) / 4) * volume; player?.SetVolume((float)left, (float)right); } void OnPlaybackEnded(object sender, EventArgs e) { PlaybackEnded?.Invoke(sender, e); //this improves stability on older devices but has minor performance impact // We need to check whether the player is null or not as the user might have dipsosed it in an event handler to PlaybackEnded above. if (player != null && Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.M) { player.SeekTo(0); player.Stop(); player.Prepare(); } } bool isDisposed = false; ///<Summary> /// Dispose SimpleAudioPlayer and release resources ///</Summary> protected virtual void Dispose(bool disposing) { if (isDisposed || player == null) return; if (disposing) DeletePlayer(); isDisposed = true; } ~SimpleAudioPlayerImplementation() { Dispose(false); } ///<Summary> /// Dispose SimpleAudioPlayer and release resources ///</Summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
37,302
https://github.com/bolero-MURAKAMI/Sprig/blob/master/sprig/static_warning.hpp
Github Open Source
Open Source
BSL-1.0
2,018
Sprig
bolero-MURAKAMI
C++
Code
81
393
/*============================================================================= Copyright (c) 2010-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprig Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPRIG_STATIC_WARNING_HPP #define SPRIG_STATIC_WARNING_HPP #include <sprig/config/config.hpp> #ifdef SPRIG_USING_PRAGMA_ONCE # pragma once #endif // #ifdef SPRIG_USING_PRAGMA_ONCE #include <boost/mpl/bool.hpp> #include <boost/preprocessor/cat.hpp> #include <sprig/pred_check.hpp> #define SPRIG_STATIC_WARNING(B) \ static sprig::STATIC_WARNING_FAILED BOOST_PP_CAT(static_warning_, __LINE__) \ = (sprig::STATIC_WARNING_CHECK)SPRIG_PRED_CHECK((boost::mpl::bool_<B>)) namespace sprig { // // STATIC_WARNING_CHECK // typedef std::size_t STATIC_WARNING_CHECK; // // STATIC_WARNING_FAILED // typedef bool const STATIC_WARNING_FAILED; } // namespace sprig #endif // #ifndef SPRIG_STATIC_WARNING_HPP
7,961
https://github.com/FrankPfattheicher/stonehenge3/blob/master/IctBaden.Stonehenge3.Vue.SampleCore/Program.cs
Github Open Source
Open Source
MIT
2,021
stonehenge3
FrankPfattheicher
C#
Code
254
886
using System; using System.Diagnostics; using System.Threading; using IctBaden.Stonehenge3.Hosting; using IctBaden.Stonehenge3.Kestrel; using IctBaden.Stonehenge3.Resources; using IctBaden.Stonehenge3.SimpleHttp; using Microsoft.Extensions.Logging; namespace IctBaden.Stonehenge3.Vue.SampleCore { internal static class Program { private static IStonehengeHost _server; // ReSharper disable once MemberCanBePrivate.Global public static readonly ILoggerFactory LoggerFactory = StonehengeLogger.DefaultFactory; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main() { Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener()); StonehengeLogger.DefaultLevel = LogLevel.Trace; var logger = LoggerFactory.CreateLogger("stonehenge"); Console.WriteLine(@""); Console.WriteLine(@"Stonehenge 3 sample"); Console.WriteLine(@""); logger.LogInformation("Vue.SampleCore started"); // select hosting options var options = new StonehengeHostOptions { Title = "VueSample", ServerPushMode = ServerPushModes.LongPolling, PollIntervalSec = 10, SessionIdMode = SessionIdModes.Automatic // SslCertificatePath = Path.Combine(StonehengeApplication.BaseDirectory, "stonehenge.pfx"), // SslCertificatePassword = "test" }; // Select client framework Console.WriteLine(@"Using client framework vue"); var vue = new VueResourceProvider(logger); var loader = StonehengeResourceLoader.CreateDefaultLoader(logger, vue); // Select hosting technology var hosting = "kestrel"; if (Environment.CommandLine.Contains("/simple")) { hosting = "simple"; } switch (hosting) { case "kestrel": Console.WriteLine(@"Using Kestrel hosting"); _server = new KestrelHost(loader, options); break; case "simple": Console.WriteLine(@"Using simple http hosting"); _server = new SimpleHttpHost(loader, options); break; } Console.WriteLine(@"Starting server"); var terminate = new AutoResetEvent(false); Console.CancelKeyPress += (_, _) => { terminate.Set(); }; var host = Environment.CommandLine.Contains("/localhost") ? "localhost" : "*"; if (_server.Start(host, 32000)) { Console.WriteLine(@"Server reachable on: " + _server.BaseUrl); if (Environment.CommandLine.Contains("/window")) { var wnd = new HostWindow(_server.BaseUrl, options.Title); if (!wnd.Open()) { logger.LogError("Failed to open main window"); terminate.Set(); } } else { terminate.WaitOne(); } Console.WriteLine(@"Server terminated."); } else { Console.WriteLine(@"Failed to start server on: " + _server.BaseUrl); } #pragma warning disable 0162 // ReSharper disable once HeuristicUnreachableCode _server.Terminate(); Console.WriteLine(@"Exit sample app"); Environment.Exit(0); } } }
39,953
https://github.com/AndrewKralovec/FantasyCritic/blob/master/FantasyCritic.Lib/Services/FantasyCriticRoleManager.cs
Github Open Source
Open Source
MIT
2,022
FantasyCritic
AndrewKralovec
C#
Code
46
199
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FantasyCritic.Lib.Domain; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; namespace FantasyCritic.Lib.Services { public class FantasyCriticRoleManager : RoleManager<FantasyCriticRole> { public FantasyCriticRoleManager(IRoleStore<FantasyCriticRole> store, IEnumerable<IRoleValidator<FantasyCriticRole>> roleValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, ILogger<RoleManager<FantasyCriticRole>> logger) : base(store, roleValidators, keyNormalizer, errors, logger) { } } }
5,345
https://github.com/NikitoG/TelerikAcademyHomeworks/blob/master/C#-II-Homework/TextFiles/CountWords/CounterForWords.cs
Github Open Source
Open Source
MIT
null
TelerikAcademyHomeworks
NikitoG
C#
Code
225
656
//Problem 13. Count words //Write a program that reads a list of words from the file words.txt and finds how many times each of the words is contained //in another file test.txt. //The result should be written in the file result.txt and the words should be sorted by the number of their occurrences in //descending order. //Handle all possible exceptions in your methods. using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Linq; class RemoveWordsSalution { static void Main() { try { StreamReader getWords = new StreamReader(@"..\..\Files\words.txt"); Dictionary<string, int> countWords = new Dictionary<string, int>(); using (getWords) { string currentLine = getWords.ReadLine(); while (currentLine != null) { string[] removeWords = currentLine.Split(new char[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries); foreach (var word in removeWords) { countWords.Add(word.ToString(), 0); } currentLine = getWords.ReadLine(); } } StreamReader getText = new StreamReader(@"..\..\Files\test.txt"); using (getText) { string currentLine = getText.ReadLine(); while (currentLine != null) { foreach (var word in Regex.Matches(currentLine, @"\w+")) { if (countWords.ContainsKey(word.ToString())) { ++countWords[word.ToString()]; } } currentLine = getText.ReadLine(); } } var sorted = countWords.OrderBy(key => key.Value).Reverse(); foreach (var letters in sorted) { StreamWriter result = new StreamWriter(@"..\..\Files\result.txt", true); using (result) { result.WriteLine("{0} -> {1} times.", letters.Key, letters.Value); } } } catch (DirectoryNotFoundException ex) { Console.WriteLine(ex.Message); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } catch (UnauthorizedAccessException ex) { Console.WriteLine(ex.Message); } } }
48,938
https://github.com/Agent0005/hello-Community/blob/master/src/components/SocialMedia/styles.ts
Github Open Source
Open Source
MIT
null
hello-Community
Agent0005
TypeScript
Code
50
172
import styled from 'styled-components'; export const NavigationIcons = styled.nav` padding: 1rem 0; a { color: ${props => props.theme.colors.silver}; font-size: 1.5rem; text-decoration: none; margin-right: 8px; transition: 0.3s; &:hover { color: ${props => props.theme.colors['dodger-blue']}; } } @media screen and (max-width: 370px) { padding: 0.5rem 0; a { font-size: 1.1rem; } } `;
11,791
https://github.com/Sparvnastet/make-all.se/blob/master/map.js
Github Open Source
Open Source
MIT
2,012
make-all.se
Sparvnastet
JavaScript
Code
65
317
var options = { projection: new OpenLayers.Projection("EPSG:900913"), displayProjection: new OpenLayers.Projection("EPSG:4326") }; var map = new OpenLayers.Map('map', options); var mapnik = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)"); var size = new OpenLayers.Size(100,68); var offset = new OpenLayers.Pixel(-(size.w/2), -(size.h/2)); var icon = new OpenLayers.Icon('makeall-small.png', size, offset); var poi = new OpenLayers.Layer.Markers( "Markers" ); poi.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(18.119309,59.332492) .transform(map.displayProjection, map.projection), icon.clone())); map.addLayers([mapnik, poi]); var area = 0.001; map.zoomToExtent(new OpenLayers.Bounds(18.119309-area,59.332492-area, 18.119309+area,59.332492+area) .transform(map.displayProjection, map.projection));
15,157
https://github.com/aliefnaa/surveilans-undip/blob/master/surveilans-undip-master/application/controllers/Deteksi.php
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,020
surveilans-undip
aliefnaa
PHP
Code
111
534
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Deteksi extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("m_deteksi"); } public function index() { $this->load->view('user/v_deteksi'); } public function hasil() { $data["deteksi"] = $this->m_deteksi->getHasil(); $check = $this->m_deteksi->getHasil(); if ($check == !null) { $this->load->view('user/v_hasil_deteksi', $data); } else { $this->load->view('user/v_cari_gagal', $data); } } public function add() { $deteksi = $this->m_deteksi; $deteksi->save(); $this->hasil(); } public function cari() { $this->load->view('user/v_cari_deteksi'); } public function update() { $deteksi = $this->m_deteksi; $deteksi->update(); $this->hasil(); } public function edit($id = null) { if (!isset($id)) redirect('deteksi'); $deteksi = $this->m_deteksi; $data["deteksi"] = $deteksi->getById($id); if (!$data["deteksi"]) show_404(); $this->load->view('user/v_deteksi_update', $data); } public function delete($id=null) { if (!isset($id)) show_404(); if ($this->m_deteksi->delete($id)) { redirect(site_url('admin/admin_barbuk')); } } }
20,632
https://github.com/aliyun/alibabacloud-php-sdk/blob/master/cityvisual-20181030/src/Models/DescribeWorkGroupsResponseBody/workGroups/workGroup.php
Github Open Source
Open Source
Apache-2.0
2,023
alibabacloud-php-sdk
aliyun
PHP
Code
272
939
<?php // This file is auto-generated, don't edit it. Thanks. namespace AlibabaCloud\SDK\Cityvisual\V20181030\Models\DescribeWorkGroupsResponseBody\workGroups; use AlibabaCloud\Tea\Model; class workGroup extends Model { /** * @var string */ public $updateTime; /** * @var string */ public $description; /** * @var string */ public $protocol; /** * @var string */ public $createTime; /** * @var string */ public $instanceId; /** * @var string */ public $theoryCutStatus; /** * @var string */ public $workGroupId; /** * @var string */ public $workGroupName; protected $_name = [ 'updateTime' => 'UpdateTime', 'description' => 'Description', 'protocol' => 'Protocol', 'createTime' => 'CreateTime', 'instanceId' => 'InstanceId', 'theoryCutStatus' => 'TheoryCutStatus', 'workGroupId' => 'WorkGroupId', 'workGroupName' => 'WorkGroupName', ]; public function validate() { } public function toMap() { $res = []; if (null !== $this->updateTime) { $res['UpdateTime'] = $this->updateTime; } if (null !== $this->description) { $res['Description'] = $this->description; } if (null !== $this->protocol) { $res['Protocol'] = $this->protocol; } if (null !== $this->createTime) { $res['CreateTime'] = $this->createTime; } if (null !== $this->instanceId) { $res['InstanceId'] = $this->instanceId; } if (null !== $this->theoryCutStatus) { $res['TheoryCutStatus'] = $this->theoryCutStatus; } if (null !== $this->workGroupId) { $res['WorkGroupId'] = $this->workGroupId; } if (null !== $this->workGroupName) { $res['WorkGroupName'] = $this->workGroupName; } return $res; } /** * @param array $map * * @return workGroup */ public static function fromMap($map = []) { $model = new self(); if (isset($map['UpdateTime'])) { $model->updateTime = $map['UpdateTime']; } if (isset($map['Description'])) { $model->description = $map['Description']; } if (isset($map['Protocol'])) { $model->protocol = $map['Protocol']; } if (isset($map['CreateTime'])) { $model->createTime = $map['CreateTime']; } if (isset($map['InstanceId'])) { $model->instanceId = $map['InstanceId']; } if (isset($map['TheoryCutStatus'])) { $model->theoryCutStatus = $map['TheoryCutStatus']; } if (isset($map['WorkGroupId'])) { $model->workGroupId = $map['WorkGroupId']; } if (isset($map['WorkGroupName'])) { $model->workGroupName = $map['WorkGroupName']; } return $model; } }
14,052
https://github.com/tateshitah/PPPlot/blob/master/app/src/main/java/org/braincopy/gnss/plot/PointArray.java
Github Open Source
Open Source
MIT
2,018
PPPlot
tateshitah
Java
Code
805
1,914
/* Copyright (c) 2013-2014 Hiroaki Tateshita 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. */ package org.braincopy.gnss.plot; import android.util.Log; /** * Que of points. * * @author Hiroaki Tateshita * @version 0.6 * */ public class PointArray { /** * */ private Point[] pointArray; /** * this is current size, not max size. */ private int size; /** * */ private int cursor; /** * * @param _size_max * max size of array */ PointArray(int _size_max) { pointArray = new Point[_size_max]; for (int i = 0; i < _size_max; i++) { pointArray[i] = new Point(-1000000, -1000000); } this.size = 0; cursor = 0; } /** * * @param x * x of the point which will be added * @param y * y of the point which will be added */ public final void addPoint(final double _x, final double _y) { if (this.size < pointArray.length - 1) { // pointArray[this.size] = new Point(_x, _y); pointArray[this.size].x = _x; pointArray[this.size].y = _y; this.size++; this.cursor++; } else if (this.size == pointArray.length - 1) { // pointArray[this.cursor] = new Point(_x, _y); pointArray[this.cursor].x = _x; pointArray[this.cursor].y = _y; if (this.cursor < pointArray.length - 1) { this.cursor++; } else if (this.cursor == pointArray.length - 1) { this.cursor = 0; } else { Log.e("hiro", "the cursor of pointArray is strange."); } } else { Log.e("hiro", "pointArray is wired"); } } /** * * @param index * from 0 to (size -1) * @return x of the point of the index, if no value, Double.MAX_VALUE will * be returned */ public final double getX(final int index) { double result = Double.MAX_VALUE; if (index < this.size && index >= 0) { result = pointArray[index].x; } return result; } /** * * @param index * from 0 to (size -1) * @return y if no value, return Double.MAX_VALUE */ public final double getY(final int index) { double result = Double.MAX_VALUE; if (index < this.size && index >= 0) { result = pointArray[index].y; } return result; } /** * * @return if no value, Double.MAX_VALUE will be returned */ public final double getLatestX() { double result = Double.MAX_VALUE; if (this.cursor == 0) { result = pointArray[this.size].x; } else if (this.cursor <= this.size) { result = pointArray[this.cursor - 1].x; } return result; } /** * * @return if no value, Double.MAX_VALUE will be returned */ public final double getLatestY() { double result = Double.MAX_VALUE; if (this.cursor == 0) { result = pointArray[this.size].y; } else if (this.cursor <= this.size) { result = pointArray[this.cursor - 1].y; } return result; } /** * * @author Hiroaki Tateshita * */ private class Point { /** * */ private double x; /** * */ private double y; /** * * @param _x * @param _y */ public Point(double _x, double _y) { this.x = _x; this.y = _y; } /** * @return string */ public final String toString() { return "(" + this.x + ", " + this.y + ")"; } } /** * * @param deltaX * delta x * @param deltaY * delta y */ public final void moveAll(final double deltaX, final double deltaY) { for (int i = 0; i < this.size; i++) { set_x(i, getX(i) + deltaX); set_y(i, getY(i) + deltaY); } } /** * * @param i * index * @param _x * x */ private void set_x(final int i, final double _x) { pointArray[i].x = _x; } private void set_y(int i, double _y) { pointArray[i].y = _y; } /** * * @param zoomRate * @param center_x * @param center_y */ public final void zoomAll(double zoomRate, double center_x, double center_y) { for (int i = 0; i < this.size; i++) { set_x(i, getX(i) * zoomRate + (1 - zoomRate) * center_x); set_y(i, getY(i) * zoomRate + (1 - zoomRate) * center_y); } } /** * * @param i */ public final void setSize(int i) { this.size = i; } /** * * @return */ public final int getSize() { return this.size; } }
35,324
https://github.com/Crisspl/Nabla/blob/master/include/SColor.h
Github Open Source
Open Source
Apache-2.0
null
Nabla
Crisspl
C
Code
1,755
3,767
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __COLOR_H_INCLUDED__ #define __COLOR_H_INCLUDED__ #include "irr/core/core.h" #include "vectorSIMD.h" #include "irr/asset/format/decodePixels.h" namespace irr { namespace video { // nuke this //! Creates a 16 bit A1R5G5B5 color inline uint16_t RGBA16(uint32_t r, uint32_t g, uint32_t b, uint32_t a=0xFF) { return (uint16_t)((a & 0x80) << 8 | (r & 0xF8) << 7 | (g & 0xF8) << 2 | (b & 0xF8) >> 3); } //! Creates a 16 bit A1R5G5B5 color inline uint16_t RGB16(uint32_t r, uint32_t g, uint32_t b) { return RGBA16(r,g,b); } //! Converts a 32bit (X8R8G8B8) color to a 16bit A1R5G5B5 color inline uint16_t X8R8G8B8toA1R5G5B5(uint32_t color) { return (uint16_t)(0x8000 | ( color & 0x00F80000) >> 9 | ( color & 0x0000F800) >> 6 | ( color & 0x000000F8) >> 3); } //! Convert A8R8G8B8 Color from A1R5G5B5 color /** build a nicer 32bit Color by extending dest lower bits with source high bits. */ inline uint32_t A1R5G5B5toA8R8G8B8(uint16_t color) { return ( (( -( (int32_t) color & 0x00008000 ) >> (int32_t) 31 ) & 0xFF000000 ) | (( color & 0x00007C00 ) << 9) | (( color & 0x00007000 ) << 4) | (( color & 0x000003E0 ) << 6) | (( color & 0x00000380 ) << 1) | (( color & 0x0000001F ) << 3) | (( color & 0x0000001C ) >> 2) ); } //! Class representing a 32 bit ARGB color. /** The color values for alpha, red, green, and blue are stored in a single uint32_t. So all four values may be between 0 and 255. Alpha in Irrlicht is opacity, so 0 is fully transparent, 255 is fully opaque (solid). This class is used by most parts of the Irrlicht Engine to specify a color. Another way is using the class SColorf, which stores the color values in 4 floats. This class must consist of only one uint32_t and must not use virtual functions. */ class SColor { public: //! Constructor of the Color. Does nothing. /** The color value is not initialized to save time. */ SColor() {} //! Constructs the color from 4 values representing the alpha, red, green and blue component. /** Must be values between 0 and 255. */ SColor (uint32_t a, uint32_t r, uint32_t g, uint32_t b) : color(((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff)) {} //! Constructs the color from a 32 bit value. Could be another color. SColor(uint32_t clr) : color(clr) {} //! Returns the alpha component of the color. /** The alpha component defines how opaque a color is. \return The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */ uint32_t getAlpha() const { return color>>24; } //! Returns the red component of the color. /** \return Value between 0 and 255, specifying how red the color is. 0 means no red, 255 means full red. */ uint32_t getRed() const { return (color>>16) & 0xff; } //! Returns the green component of the color. /** \return Value between 0 and 255, specifying how green the color is. 0 means no green, 255 means full green. */ uint32_t getGreen() const { return (color>>8) & 0xff; } //! Returns the blue component of the color. /** \return Value between 0 and 255, specifying how blue the color is. 0 means no blue, 255 means full blue. */ uint32_t getBlue() const { return color & 0xff; } //! Sets the alpha component of the Color. /** The alpha component defines how transparent a color should be. \param a The alpha value of the color. 0 is fully transparent, 255 is fully opaque. */ void setAlpha(uint32_t a) { color = ((a & 0xff)<<24) | (color & 0x00ffffff); } //! Sets the red component of the Color. /** \param r: Has to be a value between 0 and 255. 0 means no red, 255 means full red. */ void setRed(uint32_t r) { color = ((r & 0xff)<<16) | (color & 0xff00ffff); } //! Sets the green component of the Color. /** \param g: Has to be a value between 0 and 255. 0 means no green, 255 means full green. */ void setGreen(uint32_t g) { color = ((g & 0xff)<<8) | (color & 0xffff00ff); } //! Sets the blue component of the Color. /** \param b: Has to be a value between 0 and 255. 0 means no blue, 255 means full blue. */ void setBlue(uint32_t b) { color = (b & 0xff) | (color & 0xffffff00); } //! Converts color to OpenGL color format /** From ARGB to RGBA in 4 byte components for endian aware passing to OpenGL \param dest: address where the 4x8 bit OpenGL color is stored. */ void toOpenGLColor(uint8_t* dest) const { *dest = (uint8_t)getRed(); *++dest = (uint8_t)getGreen(); *++dest = (uint8_t)getBlue(); *++dest = (uint8_t)getAlpha(); } //! Sets all four components of the color at once. /** Constructs the color from 4 values representing the alpha, red, green and blue components of the color. Must be values between 0 and 255. \param a: Alpha component of the color. The alpha component defines how transparent a color should be. Has to be a value between 0 and 255. 255 means not transparent (opaque), 0 means fully transparent. \param r: Sets the red component of the Color. Has to be a value between 0 and 255. 0 means no red, 255 means full red. \param g: Sets the green component of the Color. Has to be a value between 0 and 255. 0 means no green, 255 means full green. \param b: Sets the blue component of the Color. Has to be a value between 0 and 255. 0 means no blue, 255 means full blue. */ void set(uint32_t a, uint32_t r, uint32_t g, uint32_t b) { color = (((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff)); } void set(uint32_t col) { color = col; } //! Compares the color to another color. /** \return True if the colors are the same, and false if not. */ bool operator==(const SColor& other) const { return other.color == color; } //! Compares the color to another color. /** \return True if the colors are different, and false if they are the same. */ bool operator!=(const SColor& other) const { return other.color != color; } //! comparison operator /** \return True if this color is smaller than the other one */ bool operator<(const SColor& other) const { return (color < other.color); } //! color in A8R8G8B8 Format uint32_t color; }; // nuke end //! Class representing a color with four floats. /** The color values for red, green, blue and alpha are each stored in a 32 bit floating point variable. So all four values may be between 0.0f and 1.0f. Another, faster way to define colors is using the class SColor, which stores the color values in a single 32 bit integer. */ class SColorf : private core::vectorSIMDf { public: //! Default constructor for SColorf. /** Sets red, green and blue to 0.0f and alpha to 1.0f. */ SColorf() : vectorSIMDf(0.f,0.f,0.f,1.f) {} //! Constructs a color from up to four color values: red, green, blue, and alpha. /** \param r: Red color component. Should be a value between 0.0f meaning no red and 1.0f, meaning full red. \param g: Green color component. Should be a value between 0.0f meaning no green and 1.0f, meaning full green. \param b: Blue color component. Should be a value between 0.0f meaning no blue and 1.0f, meaning full blue. \param a: Alpha color component of the color. The alpha component defines how transparent a color should be. Has to be a value between 0.0f and 1.0f, 1.0f means not transparent (opaque), 0.0f means fully transparent. */ SColorf(float r_in, float g_in, float b_in, float a_in = 1.0f) : vectorSIMDf(r_in,g_in,b_in,a_in) {} SColorf(const vectorSIMDf& fromVec4) : vectorSIMDf(fromVec4) {} //! Constructs a color from 32 bit Color. /** \param c: 32 bit color from which this SColorf class is constructed from. */ SColorf(SColor c) { r = static_cast<float>(c.getRed()); g = static_cast<float>(c.getGreen()); b = static_cast<float>(c.getBlue()); a = static_cast<float>(c.getAlpha()); const float inv = 1.0f / 255.0f; *this *= inv; } inline static SColorf fromSRGB(SColorf&& input) { float color[3] = {input.r, input.g, input.b}; asset::impl::SRGB2lin<float>(color); return SColorf(color[0], color[1], color[2], input.getAlpha()); } inline static SColorf toSRGB(SColorf&& input) { float color[3] = {input.r, input.g, input.b}; asset::impl::lin2SRGB<float>(color); return SColorf(color[0], color[1], color[2], input.getAlpha()); } //! Converts this color to a SColor without floats. inline SColor toSColor() const { vectorSIMDf tmp = (*this) * 255.f; return SColor(core::round<float, uint32_t>(tmp.a), core::round<float, uint32_t>(tmp.r), core::round<float, uint32_t>(tmp.g), core::round<float, uint32_t>(tmp.b)); } //! Sets three color components to new values at once. /** \param rr: Red color component. Should be a value between 0.0f meaning no red (=black) and 1.0f, meaning full red. \param gg: Green color component. Should be a value between 0.0f meaning no green (=black) and 1.0f, meaning full green. \param bb: Blue color component. Should be a value between 0.0f meaning no blue (=black) and 1.0f, meaning full blue. */ inline void set(float rr, float gg, float bb) {r = rr; g =gg; b = bb; } //! Sets all four color components to new values at once. /** \param aa: Alpha component. Should be a value between 0.0f meaning fully transparent and 1.0f, meaning opaque. \param rr: Red color component. Should be a value between 0.0f meaning no red and 1.0f, meaning full red. \param gg: Green color component. Should be a value between 0.0f meaning no green and 1.0f, meaning full green. \param bb: Blue color component. Should be a value between 0.0f meaning no blue and 1.0f, meaning full blue. */ inline void set(float aa, float rr, float gg, float bb) {a = aa; r = rr; g =gg; b = bb; } //! Returns the alpha component of the color in the range 0.0 (transparent) to 1.0 (opaque) inline float getAlpha() const { return a; } //! Returns the red component of the color in the range 0.0 to 1.0 inline float getRed() const { return r; } //! Returns the green component of the color in the range 0.0 to 1.0 inline float getGreen() const { return g; } //! Returns the blue component of the color in the range 0.0 to 1.0 inline float getBlue() const { return b; } //! inline vectorSIMDf& getAsVectorSIMDf() {return *this;} inline const vectorSIMDf& getAsVectorSIMDf() const {return *this;} }; } // end namespace video } // end namespace irr #endif
614
https://github.com/sql-machine-learning/elasticdl/blob/master/setup.py
Github Open Source
Open Source
MIT
2,023
elasticdl
sql-machine-learning
Python
Code
179
541
# Copyright 2020 The ElasticDL Authors. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import find_packages, setup with open("elasticdl/requirements.txt") as f: required_deps = f.read().splitlines() required_deps.append("elasticai_api") required_deps.append("elasticdl_client") required_deps.append("elasticdl_preprocessing") extras = {} with open("elasticdl/requirements-dev.txt") as f: extras["develop"] = f.read().splitlines() setup( name="elasticdl", version="0.3.0rc0.dev0", description="A Kubernetes-native Deep Learning Framework", long_description="ElasticDL is a Kubernetes-native deep learning framework" " built on top of TensorFlow 2.0 that supports" " fault-tolerance and elastic scheduling.", long_description_content_type="text/markdown", author="Ant Group", url="https://elasticdl.org", install_requires=required_deps, extras_require=extras, python_requires=">=3.5", packages=find_packages( exclude=[ "*test*", "elasticdl_client*", "elasticdl_preprocessing*", "model_zoo*", ] ), package_data={ "": [ "proto/*.proto", "docker/*", "Makefile", "requirements.txt", "go/bin/elasticdl_ps", "go/pkg/kernel/capi/*", ] }, )
5,226
https://github.com/znerol-forks/fullbogons-nftables-gen/blob/master/main.go
Github Open Source
Open Source
Apache-2.0
2,021
fullbogons-nftables-gen
znerol-forks
Go
Code
676
1,887
/* * Copyright 2021 Spæren, Teodor <teodor@sparen.no> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package main import ( "bufio" "context" "fmt" "io" "log" "net" "net/http" "os" "strings" "sync" "time" "github.com/google/renameio/v2" ) const ( IPv4ListUrl = "https://www.team-cymru.org/Services/Bogons/fullbogons-ipv4.txt" IPv6ListUrl = "https://www.team-cymru.org/Services/Bogons/fullbogons-ipv6.txt" ) // Data is the data passed to the tmplText type Data struct { Date time.Time IPv4s []net.IPNet IPv6s []net.IPNet } func main() { if len(os.Args) != 2 { log.Fatalf("We require one argument, that being the filename") } fd, err := renameio.NewPendingFile(os.Args[1], renameio.WithExistingPermissions(), renameio.WithPermissions(0644), ) if err != nil { log.Fatalf("new pending file: %v", err) } defer fd.Cleanup() // We can't wait all day! ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) defer cancel() data := Data{Date: time.Now()} var wg sync.WaitGroup // IPv4 wg.Add(1) go func() { defer wg.Done() ips, err := fetchIpList(ctx, ValidIPv4, IPv4ListUrl) if err != nil { log.Fatalf("fetch ipv4 list: %v", err) } data.IPv4s = ips }() // IPv6 wg.Add(1) go func() { defer wg.Done() ips, err := fetchIpList(ctx, ValidIPv6, IPv6ListUrl) if err != nil { log.Fatalf("fetch ipv6 list: %v", err) } data.IPv6s = ips }() wg.Wait() if err := writeDefFile(fd, data); err != nil { log.Fatalf("writeDefFile: %v", err) } if err := fd.CloseAtomicallyReplace(); err != nil { log.Fatalf("closing file atomically: %v", err) } } // writeDefFile writes the tempalte to the given writer based on the // data in d func writeDefFile(w io.Writer, d Data) error { bw := bufio.NewWriter(w) // Write the header if _, err := fmt.Fprintf(bw, strings.TrimSpace(` # Generated by fullbogons-nftables-gen at %s # Based on https://team-cymru.com/community-services/bogon-reference/ # Source at https://github.com/rhermes/fullbogons-nftables-gen `), d.Date.Format("2006-01-02 15:04:05Z07:00")); err != nil { return err } // newline if _, err := fmt.Fprintln(bw, "\n"); err != nil { return err } // Write IPV4_BOGONS if err := writeIpList(bw, "IPV4_BOGONS", d.IPv4s); err != nil { return err } // newline if _, err := fmt.Fprintln(bw, ""); err != nil { return err } // Write IPV6_BOGONS if err := writeIpList(bw, "IPV6_BOGONS", d.IPv6s); err != nil { return err } // remember to flush the buffer return bw.Flush() } // writeIpList writes func writeIpList(w io.Writer, name string, ips []net.IPNet) error { if _, err := fmt.Fprintf(w, "define %s = {", name); err != nil { return err } for i, ip := range ips { s := " %s,\n" if i == 0 { s = "\n %s,\n" } if _, err := fmt.Fprintf(w, s, ip.String()); err != nil { return err } } if _, err := fmt.Fprintln(w, "}"); err != nil { return err } return nil } // fetchIpList fetches the IP list and validates the contents func fetchIpList(ctx context.Context, validator IpValidator, listUrl string) ([]net.IPNet, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, listUrl, http.NoBody) if err != nil { return nil, err } resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() ips := make([]net.IPNet, 0) scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() // Skip comments if strings.HasPrefix(line, "#") { continue } // Parse line _, ip, err := net.ParseCIDR(line) if err != nil { return nil, err } if !validator(ip) { return nil, fmt.Errorf("invalid ip by validator: %s", ip.String()) } ips = append(ips, *ip) } if err := scanner.Err(); err != nil { return nil, err } return ips, nil } // An IpValidator returns if the ip is a valid ip for the context. type IpValidator func(ip *net.IPNet) bool // Taken from https://github.com/asaskevich/govalidator func ValidIPv4(ip *net.IPNet) bool { return ip != nil && strings.Contains(ip.IP.String(), ".") } // Taken from https://github.com/asaskevich/govalidator func ValidIPv6(ip *net.IPNet) bool { return ip != nil && strings.Contains(ip.IP.String(), ":") }
14,210
https://github.com/5GinFIRE/-eu.5ginfire.nbi.osm4java/blob/master/src/main/java/yang/project/nsd/rev170228/project/NsdCatalog.java
Github Open Source
Open Source
Apache-2.0
2,019
-eu.5ginfire.nbi.osm4java
5GinFIRE
Java
Code
120
459
package yang.project.nsd.rev170228.project; import java.util.List; import javax.annotation.Nullable; import org.opendaylight.yangtools.yang.binding.Augmentable; import org.opendaylight.yangtools.yang.binding.ChildOf; import org.opendaylight.yangtools.yang.common.QName; import yang.project.nsd.rev170228.$YangModuleInfoImpl; import yang.project.nsd.rev170228.Project1; import yang.project.nsd.rev170228.project.nsd.catalog.Nsd; /** * * <p> * This class represents the following YANG schema fragment defined in module * <b>project-nsd</b> * * <pre> * container nsd-catalog { * list nsd { * key id; * uses nsd-descriptor; * } * } * </pre> * * The schema path to identify an instance is * <i>project-nsd/project/(http://riftio.com/ns/riftware-1.0/project-nsd?revision=2017-02-28)nsd-catalog</i> * * <p> * To create instances of this class use {@link NsdCatalogBuilder}. * * @see NsdCatalogBuilder * */ public interface NsdCatalog extends ChildOf<Project1>, Augmentable<NsdCatalog> { public static final QName QNAME = $YangModuleInfoImpl.qnameOf("nsd-catalog"); /** * @return <code>java.util.List</code> <code>nsd</code>, or <code>null</code> if * not present */ @Nullable List<Nsd> getNsd(); }
39,246
https://github.com/mootrichard/team-crater-eo/blob/master/client/src/Components/validate.js
Github Open Source
Open Source
MIT
2,017
team-crater-eo
mootrichard
JavaScript
Code
32
71
const validate = values => { const errors = {} if (!values.fname) { errors.fname = '* Required' } if (!values.lname) { errors.lname = '* Required' } return errors } export default validate
47,900
https://github.com/etoile/XMPPKit/blob/master/XMPPCapabilities.m
Github Open Source
Open Source
BSD-2-Clause, BSD-3-Clause
2,014
XMPPKit
etoile
Objective-C
Code
755
2,820
// // Capabilities.m // Jabber // // Created by David Chisnall on 08/05/2005. // Copyright 2005 __MyCompanyName__. All rights reserved. // #import "XMPPCapabilities.h" @implementation XMPPXMPPDiscoIdentity + (XMPPXMPPDiscoIdentity*) identityWithCategory:(NSString*)aCategory type:(NSString*)aType name:(NSString*)aName { return [[[XMPPXMPPDiscoIdentity alloc] initWithCategory:aCategory type:aType name:aName] autorelease]; } - (XMPPXMPPDiscoIdentity*) initWithCategory:(NSString*)aCategory type:(NSString*)aType name:(NSString*)aName { SELFINIT category = [aCategory retain]; type = [aType retain]; name = [aName retain]; return self; } + (XMPPXMPPDiscoIdentity*) identityWithXML:(ETXMLNode*)xml { return [[[XMPPXMPPDiscoIdentity alloc] initWithXML:xml] autorelease]; } - (XMPPXMPPDiscoIdentity*) initWithXML:(ETXMLNode*)xml { if(![[xml getType] isEqualToString:@"identity"]) { return nil; } type = [xml get:@"type"]; name = [xml get:@"name"]; category = [xml get:@"category"]; if((type == nil) || (name == nil) || (category == nil)) { return nil; } [type retain]; [name retain]; [category retain]; return self; } - (NSString*) category { return category; } - (NSString*) type { return type; } - (NSString*) name { return name; } - (ETXMLNode*) toXML { return [ETXMLNode ETXMLNodeWithType:@"identity" attributes:[NSDictionary dictionaryWithObjectsAndKeys: category, @"category", type, @"type", name, @"name", nil]]; } @end @implementation XMPPDiscoNode + (XMPPDiscoNode*) discoNodeWithJID:(JID*)aJID node:(NSString*)aNode identities:(NSSet*)anIdentities features:(NSSet*)aFeatures { return [[[XMPPDiscoNode alloc] initWithJID:aJID node:aNode identities:anIdentities features:aFeatures] autorelease]; } - (XMPPDiscoNode*) initWithJID:(JID*)aJID node:(NSString*)aNode identities:(NSSet*)anIdentities features:(NSSet*)aFeatures { if((self = [self init]) == nil) { return nil; } jid = [aJID retain]; node = [aNode retain]; identities = [anIdentities retain]; features = [aFeatures retain]; return self; } + (XMPPDiscoNode*) discoNodeFromXML:(ETXMLNode*)xml { return [[[XMPPDiscoNode alloc] initFromXML:xml] autorelease]; } - (XMPPDiscoNode*) initFromXML:(ETXMLNode*)xml { if((self = [self init]) == nil) { return nil; } if([[xml getType] isEqualToString:@"iq"] && [[xml get:@"type"] isEqualToString:@"result"]) { NSString * from = [xml get:@"from"]; ETXMLNode * query = [[xml getChildrenWithName:@"query"] anyObject]; //Check we are receiving a disco reply if([[query get:@"xmlns"] isEqualToString:@"http://jabber.org/protocol/disco#info"]) { NSMutableSet * mutableFeatures = [[NSMutableSet alloc] init]; NSMutableSet * mutableIdentities = [[NSMutableSet alloc] init]; NSEnumerator * identityEnumerator = [[query getChildrenWithName:@"identity"] objectEnumerator]; ETXMLNode * nextIdentity; while((nextIdentity = [identityEnumerator nextObject])) { [mutableIdentities addObject:[XMPPXMPPDiscoIdentity identityWithXML:nextIdentity]]; } NSEnumerator * enumerator = [[query getChildrenWithName:@"feature"] objectEnumerator]; ETXMLNode * nextFeature; while((nextFeature = [enumerator nextObject])) { [mutableFeatures addObject:[nextFeature get:@"var"]]; } jid = [[JID jidWithString:from] retain]; //In theory, I should make these into new NSSets, but it save a bit of time if I don't bother. features = mutableFeatures; identities = mutableIdentities; return self; } } [self release]; return nil; } - (ETXMLNode*) toXML { ETXMLNode * iq = [[[ETXMLNode alloc] initWithType:@"iq" attributes:[NSDictionary dictionaryWithObjectsAndKeys: [jid jidString], @"from", @"result", @"type", nil]] autorelease]; ETXMLNode * query = [[[ETXMLNode alloc] initWithType:@"query" attributes:[NSDictionary dictionaryWithObject:@"http://jabber.org/protocol/disco#info" forKey:@"xmlns"]] autorelease]; //Add identities NSEnumerator * enumerator = [identities objectEnumerator]; XMPPXMPPDiscoIdentity * identity; while((identity = [enumerator nextObject])) { [query addChild:[identity toXML]]; } enumerator = [features objectEnumerator]; NSString * feature; while((feature = [enumerator nextObject])) { ETXMLNode * featureNode = [[[ETXMLNode alloc] initWithType:@"feature" attributes:[NSDictionary dictionaryWithObject:feature forKey:@"var"]] autorelease]; [query addChild:featureNode]; } [iq addChild:query]; return iq; } - (NSString*) name { return name; } - (NSString*) node { return node; } - (NSString*) type { return type; } - (JID*) jid { return jid; } - (BOOL) supportsFeature:(NSString*)feature { if([features member:feature] != nil) { return YES; } return NO; } - (NSSet*) features { return features; } - (void) dealloc { [name release]; [type release]; [features release]; [jid release]; [super dealloc]; } @end @implementation XMPPDiscoNodeTree + (XMPPDiscoTreeNode*) discoTreeNodeWithJID:(JID*)aJID name:(NSString*)aName node:(NSString*)aNode { return [[[XMPPDiscoTreeNode alloc] initWithJID:aJID name:aName node:aNode] autorelease]; } - (XMPPDiscoTreeNode*) initWithJID:(JID*)aJID name:(NSString*)aName node:(NSString*)aNode { if((self = [self init]) == nil) { return nil; } jid = [aJID retain]; name = [aName retain]; node = [aNode retain]; children = nil; return self; } - (void) addChildrenFromXML:(ETXMLNode*)xml { [children release]; children = [[NSMutableSet alloc] init]; ETXMLNode * query = [[xml getChildrenWithName:@"query"] anyObject]; ETXMLNode * child; NSEnumerator * enumerator = [[query children] objectEnumerator]; while((child = [enumerator nextObject])) { if([[child getType] isEqualToString:@"item"]) { [children addObject:[XMPPDiscoTreeNode discoTreeNodeWithJID:[JID jidWithString:[child get:@"jid"]] name:[child get:@"name"] node:[child get:@"node"] children:nil]]; } } } - (JID*) jid { return jid; } - (NSString*) name { return name; } - (NSString*) node { return node; } - (NSSet*) children { return children; } - (unsigned) hash { return [[NSString stringWithFormat:@"%@ <@£$@^&> %@", [jid jidString], name] hash]; } - (BOOL)isEqual:(id)anObject { if(![anObject isKindOfClass:[XMPPDiscoTreeNode class]]) { return NO; } return [jid isEqual:[anObject jid]] && [name isEqualToString:[anObject name]]; } - (ETXMLNode*) toXML { ETXMLNode * iq = [ETXMLNode ETXMLNodeWithType:@"iq" attributes:[NSDictionary dictionaryWithObjectsAndKeys: [jid jidString], @"from", @"result", @"type", nil]]; ETXMLNode * query = [ETXMLNode ETXMLNodeWithType:@"query" attributes:[NSDictionary dictionaryWithObjectsAndKeys: @"http://jabber.org/protocol/disco#items", @"xmlns", nil]]; [iq addChild:query]; NSEnumerator * enumerator = [children objectEnumerator]; XMPPDiscoTreeNode * node; while((node = [enumerator nextObject])) { [query addChild:[node toXMLAsChild]]; } return iq; } - (ETXMLNode*) toXMLAsChild { if(node == nil) { return [ETXMLNode ETXMLNodeWithType:@"item" attributes:[NSDictionary dictionaryWithObjectsAndKeys: [jid jidString], @"jid", name, @"name", nil]]; } return [ETXMLNode ETXMLNodeWithType:@"item" attributes:[NSDictionary dictionaryWithObjectsAndKeys: [jid jidString], @"jid", name, @"name", node, @"node", nil]]; } @end
48,777
https://github.com/etclabscore/evm_llvm/blob/master/test/ThinLTO/X86/Inputs/index-const-prop-cache-foo.ll
Github Open Source
Open Source
NCSA, LLVM-exception, Apache-2.0
2,020
evm_llvm
etclabscore
LLVM
Code
73
231
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" @gFoo = internal unnamed_addr global i32 1, align 4 ; Function Attrs: norecurse nounwind readonly ssp uwtable define i32 @foo() local_unnamed_addr { %1 = load i32, i32* @gFoo, align 4 ret i32 %1 } ; Function Attrs: nounwind ssp uwtable define void @bar() local_unnamed_addr { %1 = tail call i32 @rand() store i32 %1, i32* @gFoo, align 4 ret void } declare i32 @rand() local_unnamed_addr
46,129
https://github.com/stefaneberl/openkit-native/blob/master/src/core/communication/IBeaconSendingContext.h
Github Open Source
Open Source
Apache-2.0
null
openkit-native
stefaneberl
C
Code
1,130
2,580
/** * Copyright 2018-2020 Dynatrace LLC * * 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. */ #ifndef _CORE_COMMUNICATION_IBEACONSENDINGCONTEXT_H #define _CORE_COMMUNICATION_IBEACONSENDINGCONTEXT_H #include "IBeaconSendingState.h" #include "core/objects/SessionInternals.h" #include "protocol/IHTTPClient.h" #include "protocol/IStatusResponse.h" #include "protocol/IResponseAttributes.h" #include "providers/IHTTPClientProvider.h" #include <cstdint> #include <memory> #include <vector> namespace core { namespace communication { class IBeaconSendingContext { public: virtual ~IBeaconSendingContext() = default; /// /// Executes the current state /// virtual void executeCurrentState() = 0; /// /// Request shutdown /// virtual void requestShutdown() = 0; /// /// Return a flag if shutdown was requested /// @returns @c true if shutdown was requested, @c false if not /// virtual bool isShutdownRequested() const = 0; /// /// Blocking method waiting until initialization finished /// @return @c true if initialization succeeded, @c false if initialization failed /// virtual bool waitForInit() = 0; /// /// Wait until OpenKit has been fully initialized or timeout expired. /// If initialization is interrupted (e.g. @ref requestShutdown() was called), then this method also returns. /// @param[in] timeoutMillis The maximum number of milliseconds to wait for initialization being completed. /// @return @c true if OpenKit is fully initialized, @c false if OpenKit init got interrupted or time to wait expired /// virtual bool waitForInit(int64_t timeoutMillis) = 0; /// /// Complete OpenKit initialization /// NOTE: This will wake up every caller waiting in the @c #waitForInit() method. /// @param[in] success @c true if OpenKit was successfully initialized, @c false if it was interrupted /// virtual void setInitCompleted(bool success) = 0; /// /// Get a boolean indicating whether OpenKit is initialized or not. /// @returns @c true if OpenKit is initialized, @c false otherwise. /// virtual bool isInitialized() const = 0; /// /// Return a flag if the current state of this context is a terminal state /// @returns @c true if the current state is a terminal state /// virtual bool isInTerminalState() const = 0; /// /// Returns a flag if capturing is enabled /// @returns @c true if capturing is enabled, @c false if capturing is disabled /// virtual bool isCaptureOn() const = 0; /// /// Gets the current state. /// @returns the current state /// virtual std::shared_ptr<IBeaconSendingState> getCurrentState() const = 0; /// /// Register a state following the current state once the current state finished /// @param nextState instance of the IBeaconSendingState that follows after the current state /// virtual void setNextState(std::shared_ptr<IBeaconSendingState> nextState) = 0; /// /// Return the next state for testing purposes /// @returns the next state /// virtual std::shared_ptr<IBeaconSendingState> getNextState() = 0; /// /// Gets the HTTP client provider. /// @return a class responsible for retrieving an instance of @ref protocol::IHTTPClient. /// virtual std::shared_ptr<providers::IHTTPClientProvider> getHTTPClientProvider() = 0; /// /// Returns the HTTPClient created by the current BeaconSendingContext /// @returns a shared pointer to the HTTPClient created by the BeaconSendingContext /// virtual std::shared_ptr<protocol::IHTTPClient> getHTTPClient() = 0; /// /// Get current timestamp /// @returns current timestamp /// virtual int64_t getCurrentTimestamp() const = 0; /// /// Sleep some time (@ref DEFAULT_SLEEP_TIME_MILLISECONDS} /// virtual void sleep() = 0; /// /// Sleep for a given amount of time /// @param[in] ms number of milliseconds /// virtual void sleep(int64_t ms) = 0; /// /// Get timestamp when open sessions were sent last /// @returns timestamp of last sending of open session /// virtual int64_t getLastOpenSessionBeaconSendTime() const = 0; /// /// Set timestamp when open sessions were sent last /// @param[in] timestamp of last sendinf of open session /// virtual void setLastOpenSessionBeaconSendTime(int64_t timestamp) = 0; /// /// Get timestamp when last status check was performed /// @returns timestamp of last status check /// virtual int64_t getLastStatusCheckTime() const = 0; /// /// Set timestamp when last status check was performed /// @param[in] lastStatusCheckTime timestamp of last status check /// virtual void setLastStatusCheckTime(int64_t lastStatusCheckTime) = 0; /// /// Get the send interval for open sessions. /// @return the send interval for open sessions /// virtual int64_t getSendInterval() const = 0; /// /// Disable data capturing. /// virtual void disableCaptureAndClear() = 0; /// /// Handle the status response received from the server /// Update the current configuration accordingly /// virtual void handleStatusResponse(std::shared_ptr<protocol::IStatusResponse> response) = 0; /// /// Updates the last known response attributes of this context from the given status response if the given IStatusResponse /// is successful @see BeaconSendingResponseUtil::isSuccessfulResponse(std::shared_ptr<protocol::IStatusResponse>). /// /// @param statusResponse the status response from which to update the last response attributes. /// /// @return in case the given IStatusResponse was successful the updated response attributes are returned. Otherwise /// the current response attributes are returned. /// virtual std::shared_ptr<protocol::IResponseAttributes> updateLastResponseAttributesFrom(std::shared_ptr<protocol::IStatusResponse> statusResponse) = 0; /// /// Returns the last attributes received as response from the server. /// virtual std::shared_ptr<protocol::IResponseAttributes> getLastResponseAttributes() const = 0; /// /// Get all sessions that were not yet configured. /// /// @par /// A session is considered as not configured if it did not receive a server configuration update (either /// when receiving a successful for the first new session request or when capturing for the session got /// disabled due to an unsuccessful response). /// /// The returned list is a snapshot and might change during traversal. /// /// @returns a shallow copy of all sessions which were not yet configured. /// virtual std::vector<std::shared_ptr<core::objects::SessionInternals>> getAllNotConfiguredSessions() = 0; /// /// Gets all open and configured sessions. /// @return a shallow copy of all open sessions. /// virtual std::vector<std::shared_ptr<core::objects::SessionInternals>> getAllOpenAndConfiguredSessions() = 0; /// /// Get a list of all sessions that have been configured and are currently finished /// @returns a shallow copy of all finished and configured sessions. /// virtual std::vector<std::shared_ptr<core::objects::SessionInternals>> getAllFinishedAndConfiguredSessions() = 0; /// /// Returns the number of sessions currently known to this context /// virtual size_t getSessionCount() = 0; /// /// Returns the current server ID to be used for creating new sessions. /// virtual int32_t getCurrentServerID() const = 0; /// /// Adds the given session to the internal container of sessions /// /// @param session the new session to add. /// virtual void addSession(std::shared_ptr<core::objects::SessionInternals> session) = 0; /// /// Remove the given session form the sessions known by this context. /// /// @param[in] session the session to be removed. /// @returns @c true if @c sessionWrapper was found in the session wrapper list and was removed successfully, /// @c false otherwise /// virtual bool removeSession(std::shared_ptr<core::objects::SessionInternals> session) = 0; /// /// Returns the type of state /// @returns type of state as defined in IBeaconSendingState /// virtual IBeaconSendingState::StateType getCurrentStateType() const = 0; }; } } #endif
46,574
https://github.com/kunaltyagi/ign-common/blob/master/src/CMakeLists.txt
Github Open Source
Open Source
Apache-2.0
2,021
ign-common
kunaltyagi
CMake
Code
252
871
# Collect source files into the "sources" variable and unit test files into the # "gtest_sources" variable ign_get_libsources_and_unittests(sources gtest_sources) # Create the library target ign_create_core_library( SOURCES ${sources} CXX_STANDARD 17) # Link the libraries that we always need target_link_libraries(${PROJECT_LIBRARY_TARGET_NAME} PRIVATE ${DL_TARGET}) # This is required by the WorkerPool::WaitForResults(const Time &_timeout) # TODO(anyone): IGN_DEPRECATED(4). Remove this part when the method is removed target_include_directories(${PROJECT_LIBRARY_TARGET_NAME} PRIVATE ${ignition-math${IGN_MATH_VER}_INCLUDE_DIRS}) # Handle non-Windows configuration settings if(NOT WIN32) # Link the libraries that we don't expect to find on Windows target_link_libraries(${PROJECT_LIBRARY_TARGET_NAME} PUBLIC UUID::UUID pthread) else() target_link_libraries(${PROJECT_LIBRARY_TARGET_NAME} PRIVATE shlwapi) endif() # don't build MovingWindowFilter_TEST if we don't have ignition-math if(NOT ignition-math${IGN_MATH_VER}_FOUND) list(REMOVE_ITEM gtest_sources MovingWindowFilter_TEST.cc) endif() # Build the unit tests ign_build_tests( TYPE UNIT SOURCES ${gtest_sources} LIB_DEPS ignition-cmake${IGN_CMAKE_VER}::utilities INCLUDE_DIRS # Used to make internal source file headers visible to the unit tests ${CMAKE_CURRENT_SOURCE_DIR} # Used to make test-directory headers visible to the unit tests ${PROJECT_SOURCE_DIR} # Used to make test_config.h visible to the unit tests ${PROJECT_BINARY_DIR}) if(TARGET UNIT_MovingWindowFilter_TEST) target_include_directories(UNIT_MovingWindowFilter_TEST PRIVATE ${ignition-math${IGN_MATH_VER}_INCLUDE_DIRS}) endif() if(TARGET UNIT_PluginLoader_TEST) target_compile_definitions(UNIT_PluginLoader_TEST PRIVATE "IGN_COMMON_LIB_PATH=\"$<TARGET_FILE_DIR:${PROJECT_LIBRARY_TARGET_NAME}>\"") endif() # Produce warning on Windows if the user has decided to turn on the symlink # tests. In order for those tests to work, they will need to run the tests in # administrative mode, or use some other workaround. if(WIN32) if(IGN_BUILD_SYMLINK_TESTS_ON_WINDOWS) message(STATUS "") message(STATUS "You have opted to enable symlink tests on a Windows platform.") message(STATUS "The test UNIT_Filesystem_TEST will require elevated privileges") message(STATUS "in order to succeed. For more information, see the issue") message(STATUS "https://github.com/ignitionrobotics/ign-common/issues/21") message(STATUS "") target_compile_definitions(UNIT_Filesystem_TEST PRIVATE IGN_BUILD_SYMLINK_TESTS_ON_WINDOWS) endif() endif()
12,135
https://github.com/7alip/rsk-academy-dapp/blob/master/deployed/deployed-2021-07-08/Quote.sol
Github Open Source
Open Source
MIT
2,021
rsk-academy-dapp
7alip
Solidity
Code
94
257
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; contract Quote { address public owner; string private message; mapping (address => bool) public whiteList; constructor() { owner = msg.sender; whiteList[msg.sender] = true; } modifier onlyOwner { require(msg.sender == owner,"Only owner"); _; } modifier onlyWhitelist { require(whiteList[msg.sender] == true, "Only whitelist"); _; } function setQuote(string memory _message) public onlyWhitelist { message = _message; } function getQuote() public view returns (string memory) { return message; } function addMember (address _member) public onlyOwner { whiteList[_member] = true; } function delMember (address _member) public onlyOwner { whiteList[_member] = false; } }
9,338
https://github.com/JetBrains/intellij-scala/blob/master/scala/worksheet/src/org/jetbrains/plugins/scala/worksheet/actions/repl/WorksheetResNGotoHandler.scala
Github Open Source
Open Source
Apache-2.0
2,023
intellij-scala
JetBrains
Scala
Code
222
743
package org.jetbrains.plugins.scala.worksheet.actions.repl import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.plugins.scala.extensions.OptionExt import org.jetbrains.plugins.scala.lang.psi.api.expr.ScReferenceExpression import org.jetbrains.plugins.scala.worksheet.{GotoOriginalHandlerUtil, WorksheetFile} final class WorksheetResNGotoHandler extends GotoDeclarationHandler { override def getGotoDeclarationTargets(sourceElement: PsiElement, offset: Int, editor: Editor): Array[PsiElement] = { if (sourceElement == null) null else { sourceElement.getContainingFile match { case file: WorksheetFile if ResNUtils.isResNSupportedInFile(file) => val referenced = WorksheetResNGotoHandler.findReferencedPsi(sourceElement.getParent) referenced.orNull case _ => null } } } override def getActionText(context: DataContext): String = null } private object WorksheetResNGotoHandler { private [repl] def findReferencedPsi(psiElement: PsiElement): Option[Array[PsiElement]] = for { ref <- Option(psiElement).filterByType[ScReferenceExpression] target <- findReferencedPsi(ref) } yield target /** * We are using `multiResolveScala` instead of `resolve` because there might be * explicitly-defined `resN` values in user code. * `resolve` would select only definition in the file * * * @example {{{ * val res1 = 1 * val res2 = 2 * val res3 = 3 * * res3 * res2 * res1 * }}} * @see SCL-20478 */ private def findReferencedPsi(ref: ScReferenceExpression): Option[Array[PsiElement]] = { val resolvedElements: Array[PsiElement] = ref.multiResolveScala(false).map(_.element) val resolvedResNCandidate = resolvedElements.find { r => val parent = r.getParent parent != null && !parent.isPhysical } val resolvedElementWithResNTarget = for { resolved <- resolvedResNCandidate target <- GotoOriginalHandlerUtil.getGoToTarget2(resolved) if target.isValid } yield (resolved, target) resolvedElementWithResNTarget.map { case (element, target) => val result = resolvedElements.map(el => if (el eq element) target else el) result.sortBy(_.getNode.getStartOffset) } } }
12,677
https://github.com/mozilla/airmozilla/blob/master/airmozilla/base/mozillians.py
Github Open Source
Open Source
BSD-3-Clause
2,022
airmozilla
mozilla
Python
Code
450
1,588
import logging import urllib import requests from django.core.cache import cache from django.conf import settings class BadStatusCodeError(Exception): pass def _fetch_users(email=None, group=None, is_username=False, **options): if not getattr(settings, 'MOZILLIANS_API_KEY', None): # pragma no cover logging.warning("'MOZILLIANS_API_KEY' not set up.") return False url = settings.MOZILLIANS_API_BASE + '/api/v2/users/' options['api-key'] = settings.MOZILLIANS_API_KEY if email: if is_username: options['username'] = email else: options['email'] = email if group: if isinstance(group, (list, tuple)): # pragma: no cover raise NotImplementedError( 'You can not find users by MULTIPLE groups' ) options['group'] = group url += '?' + urllib.urlencode(options) resp = requests.get(url) if resp.status_code != 200: url = url.replace(settings.MOZILLIANS_API_KEY, 'xxxscrubbedxxx') raise BadStatusCodeError('%s: on: %s' % (resp.status_code, url)) return resp.json() def _fetch_user(url): options = {} assert 'api-key=' not in url, url options['api-key'] = settings.MOZILLIANS_API_KEY url += '?' + urllib.urlencode(options) resp = requests.get(url) if resp.status_code != 200: url = url.replace(settings.MOZILLIANS_API_KEY, 'xxxscrubbedxxx') raise BadStatusCodeError('%s: on: %s' % (resp.status_code, url)) return resp.json() def is_vouched(email): content = _fetch_users(email) if content: for obj in content['results']: return obj['is_vouched'] return False def fetch_user(email, is_username=False): content = _fetch_users(email, is_username=is_username) if content: for obj in content['results']: return _fetch_user(obj['_url']) def fetch_user_name(email, is_username=False): user = fetch_user(email, is_username=is_username) if user: full_name = user.get('full_name') if full_name and full_name['privacy'] == 'Public': return full_name['value'] def in_group(email, group): if isinstance(group, list): # pragma: no cover raise NotImplementedError('supply a single group name') content = _fetch_users(email, group=group) return not not content['results'] def _fetch_groups(order_by='name', url=None, name=None, name_search=None): if not getattr(settings, 'MOZILLIANS_API_KEY', None): # pragma no cover logging.warning("'MOZILLIANS_API_KEY' not set up.") return False if not url: url = settings.MOZILLIANS_API_BASE + '/api/v2/groups/' data = { 'api-key': settings.MOZILLIANS_API_KEY, } if name: data['name'] = name if name_search: data['name__icontains'] = name_search url += '?' + urllib.urlencode(data) resp = requests.get(url) if resp.status_code != 200: url = url.replace(settings.MOZILLIANS_API_KEY, 'xxxscrubbedxxx') raise BadStatusCodeError('%s: on: %s' % (resp.status_code, url)) return resp.json() def get_all_groups(name=None, name_search=None): all_groups = [] next_url = None while True: found = _fetch_groups( name=name, name_search=name_search, url=next_url, ) all_groups.extend(found['results']) if len(all_groups) >= found['count']: break next_url = found['next'] return all_groups def get_all_groups_cached(name_search=None, lasting=60 * 60): cache_key = 'all_mozillian_groups' cache_key_lock = cache_key + 'lock' all_groups = cache.get(cache_key) if all_groups is None: if cache.get(cache_key_lock): return [] cache.set(cache_key_lock, True, 60) all_groups = get_all_groups() cache.set(cache_key, all_groups, lasting) cache.delete(cache_key_lock) return all_groups def get_contributors(): """Return a list of all users who are in the https://mozillians.org/en-US/group/air-mozilla-contributors/ group and whose usernames are in the settings.CONTRIBUTORS list. Return them in the order of settings.CONTRIBUTORS. """ _users = _fetch_users(group='air mozilla contributors', is_vouched=True) # turn that into a dict of username -> url urls = dict( (x['username'], x['_url']) for x in _users['results'] if x['username'] in settings.CONTRIBUTORS ) users = [] for username in settings.CONTRIBUTORS: if username not in urls: continue user = _fetch_user(urls[username]) if not user.get('photo') or user['photo']['privacy'] != 'Public': # skip users who don't have a public photo continue assert user['is_public'] users.append(user) return users
27,877
https://github.com/thecoons/FlappyBirdS/blob/master/web/assets/vendor/vue/test/unit/modules/compiler/optimizer.spec.js
Github Open Source
Open Source
MIT
null
FlappyBirdS
thecoons
JavaScript
Code
657
2,929
import { parse } from 'compiler/parser/index' import { optimize } from 'compiler/optimizer' import { baseOptions } from 'web/compiler/index' describe('optimizer', () => { it('simple', () => { const ast = parse('<h1 id="section1"><span>hello world</span></h1>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(true) // h1 expect(ast.staticRoot).toBe(true) expect(ast.children[0].static).toBe(true) // span }) it('skip simple nodes', () => { const ast = parse('<h1 id="section1">hello</h1>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(true) expect(ast.staticRoot).toBe(false) // this is too simple to warrant a static tree }) it('interpolation', () => { const ast = parse('<h1>{{msg}}</h1>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) // h1 expect(ast.children[0].static).toBe(false) // text node with interpolation }) it('nested elements', () => { const ast = parse('<ul><li>hello</li><li>world</li></ul>', baseOptions) optimize(ast, baseOptions) // ul expect(ast.static).toBe(true) expect(ast.staticRoot).toBe(true) // li expect(ast.children[0].static).toBe(true) // first expect(ast.children[1].static).toBe(true) // second // text node inside li expect(ast.children[0].children[0].static).toBe(true) // first expect(ast.children[1].children[0].static).toBe(true) // second }) it('nested complex elements', () => { const ast = parse('<ul><li>{{msg1}}</li><li>---</li><li>{{msg2}}</li></ul>', baseOptions) optimize(ast, baseOptions) // ul expect(ast.static).toBe(false) // ul // li expect(ast.children[0].static).toBe(false) // firts expect(ast.children[1].static).toBe(true) // second expect(ast.children[2].static).toBe(false) // third // text node inside li expect(ast.children[0].children[0].static).toBe(false) // first expect(ast.children[1].children[0].static).toBe(true) // second expect(ast.children[2].children[0].static).toBe(false) // third }) it('v-if directive', () => { const ast = parse('<h1 id="section1" v-if="show">hello world</h1>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(true) }) it('v-else directive', () => { const ast = parse('<div><p v-if="show">hello world</p><p v-else>foo bar</p></div>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(false) expect(ast.children[0].conditions[1].block.static).toBeUndefined() }) it('v-pre directive', () => { const ast = parse('<ul v-pre><li>{{msg}}</li><li>world</li></ul>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(true) expect(ast.staticRoot).toBe(true) expect(ast.children[0].static).toBe(true) expect(ast.children[1].static).toBe(true) expect(ast.children[0].children[0].static).toBe(true) expect(ast.children[1].children[0].static).toBe(true) }) it('v-for directive', () => { const ast = parse('<ul><li v-for="item in items">hello world {{$index}}</li></ul>', baseOptions) optimize(ast, baseOptions) // ul expect(ast.static).toBe(false) // li with v-for expect(ast.children[0].static).toBe(false) expect(ast.children[0].children[0].static).toBe(false) }) it('v-once directive', () => { const ast = parse('<p v-once>{{msg}}</p>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) // p expect(ast.children[0].static).toBe(false) // text node }) it('single slot', () => { const ast = parse('<slot>hello</slot>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) // slot expect(ast.children[0].static).toBe(true) // text node }) it('named slot', () => { const ast = parse('<slot name="one">hello world</slot>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) // slot expect(ast.children[0].static).toBe(true) // text node }) it('slot target', () => { const ast = parse('<p slot="one">hello world</p>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) // slot expect(ast.children[0].static).toBe(true) // text node }) it('component', () => { const ast = parse('<my-component></my-component>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) // component }) it('component for inline-template', () => { const ast = parse('<my-component inline-template><p>hello world</p><p>{{msg}}</p></my-component>', baseOptions) optimize(ast, baseOptions) // component expect(ast.static).toBe(false) // component // p expect(ast.children[0].static).toBe(true) // first expect(ast.children[1].static).toBe(false) // second // text node inside p expect(ast.children[0].children[0].static).toBe(true) // first expect(ast.children[1].children[0].static).toBe(false) // second }) it('class binding', () => { const ast = parse('<p :class="class1">hello world</p>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(true) }) it('style binding', () => { const ast = parse('<p :style="error">{{msg}}</p>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(false) }) it('key', () => { const ast = parse('<p key="foo">hello world</p>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(true) }) it('ref', () => { const ast = parse('<p ref="foo">hello world</p>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(true) }) it('transition', () => { const ast = parse('<p v-if="show" transition="expand">hello world</p>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(true) }) it('v-bind directive', () => { const ast = parse('<input type="text" name="field1" :value="msg">', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) }) it('v-on directive', () => { const ast = parse('<input type="text" name="field1" :value="msg" @input="onInput">', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) }) it('custom directive', () => { const ast = parse('<form><input type="text" name="field1" :value="msg" v-validate:field1="required"></form>', baseOptions) optimize(ast, baseOptions) expect(ast.static).toBe(false) expect(ast.children[0].static).toBe(false) }) it('not root ast', () => { const ast = null optimize(ast, baseOptions) expect(ast).toBe(null) }) it('not specified isReservedTag option', () => { const ast = parse('<h1 id="section1">hello world</h1>', baseOptions) optimize(ast, {}) expect(ast.static).toBe(false) }) it('mark static trees inside v-for', () => { const ast = parse(`<div><div v-for="i in 10"><p><span>hi</span></p></div></div>`, baseOptions) optimize(ast, baseOptions) expect(ast.children[0].children[0].staticRoot).toBe(true) expect(ast.children[0].children[0].staticInFor).toBe(true) }) it('mark static trees inside v-for with nested v-else and v-once', () => { const ast = parse(` <div v-if="1"></div> <div v-else-if="2"> <div v-for="i in 10" :key="i"> <div v-if="1">{{ i }}</div> <div v-else-if="2" v-once>{{ i }}</div> <div v-else v-once>{{ i }}</div> </div> </div> <div v-else> <div v-for="i in 10" :key="i"> <div v-if="1">{{ i }}</div> <div v-else v-once>{{ i }}</div> </div> </div> `, baseOptions) optimize(ast, baseOptions) expect(ast.conditions[1].block.children[0].children[0].conditions[1].block.staticRoot).toBe(false) expect(ast.conditions[1].block.children[0].children[0].conditions[1].block.staticInFor).toBe(true) expect(ast.conditions[1].block.children[0].children[0].conditions[2].block.staticRoot).toBe(false) expect(ast.conditions[1].block.children[0].children[0].conditions[2].block.staticInFor).toBe(true) expect(ast.conditions[2].block.children[0].children[0].conditions[1].block.staticRoot).toBe(false) expect(ast.conditions[2].block.children[0].children[0].conditions[1].block.staticInFor).toBe(true) }) })
26,661
https://github.com/Krilline/Projet-DoctoTrip/blob/master/templates/home/housing.html.twig
Github Open Source
Open Source
MIT
null
Projet-DoctoTrip
Krilline
Twig
Code
66
365
{% extends 'base.html.twig' %} {% block body %} <div class="container"> <div class="row"> {% for housing in housings %} <div class="col-lg-4 col-md-6 col-sm-7"> <h5 class="card-title">{{ housing.name }}</h5> <img class="card-img-top" src="{{ housing.poster }}" alt="Card image cap"> <div class="card-body"> <p class="card-text"><img class="logo_housing" src="https://us.123rf.com/450wm/tmricons/tmricons1510/tmricons151000176/45804740-plan-pointeur-ic%C3%B4ne-bouton-de-localisation-.jpg?ver=6" alt="">{{ housing.city.name }}</p> <p class="card-text"><img class="logo_housing" src="https://banner2.cleanpng.com/20180425/qgq/kisspng-address-symbol-5ae01b2bce49c7.004939681524636459845.jpg" alt="">{{ housing.address }}</p> <p class="bouton"><a href="{{ path('show_housing') }}" class="btn">see</a></p> </div> </div> {% endfor %} </div> </div> {% endblock %}
25,688
https://github.com/SimulationEverywhere/CDPP_ExtendedStates-codename-Santi/blob/master/src/cd++/parser/cdlang/tuple_node.cpp
Github Open Source
Open Source
MIT
2,022
CDPP_ExtendedStates-codename-Santi
SimulationEverywhere
C++
Code
212
839
#include <string> #include <vector> #include "tuple_node.h" const TupleType TupleType::TheTuple; TupleType::TupleType() : TypeValue(ttuple) { } TupleNode::TupleNode(v_tuple* t) : tuple(t) { } TupleNode::TupleNode(const Tuple<SyntaxNode*> &t) : tuple(t) { } SyntaxNode *TupleNode::clone() { return new TupleNode(this->tuple); } const std::string TupleNode::name() { return "TupleNode"; } value_ptr TupleNode::evaluate() { std::vector<Real> v; for(int i = 0; i < this->tuple.size(); ++i) { SyntaxNode *node = this->tuple[i]; value_ptr node_val = node->evaluate(); real_ptr r = std::dynamic_pointer_cast<Real>(node_val); v.push_back(*r); } value_ptr p(new Tuple<Real>(&v)); return p; } const TypeValue &TupleNode::type() const { return TupleType::TheTuple; } bool TupleNode::checkType() const { for(int i = 0; i < this->tuple.size(); ++i) { if(!this->tuple[i]->checkType() || !this->tuple[i]->type().isValid(RealType::TheReal)) return false; } return true; } std::ostream &TupleNode::print(std::ostream &os) { // TODO return os; } TuplePositionNode::TuplePositionNode(SyntaxNode* t, SyntaxNode* c) : tuple(t), pos(c) { } SyntaxNode *TuplePositionNode::clone() { return new TuplePositionNode(this->tuple, this->pos); } const std::string TuplePositionNode::name() { return "TuplePositionNode"; } value_ptr TuplePositionNode::evaluate() { value_ptr tup_ptr = this->tuple->evaluate(); value_ptr pos_ptr = this->pos->evaluate(); Real pos = Real::from_value(pos_ptr); tuple_ptr<Real> tup = Tuple<Real>::ptr_from_value(tup_ptr); // In case the left operand is not a tuple. if(tup == nullptr) return AbstractValue::to_value_ptr(Real::tundef); MASSERT(pos >= 0 && pos < tup->size()); return AbstractValue::to_value_ptr((*tup)[pos.value()]); } const TypeValue &TuplePositionNode::type() const { return RealType::TheReal; } bool TuplePositionNode::checkType() const { return this->tuple->checkType() && this->tuple->type().isValid(TupleType::TheTuple) && this->pos->checkType() && this->pos->type().isValid(RealType::TheReal); } std::ostream &TuplePositionNode::print(std::ostream& os) { // TODO return os; }
20,006
https://github.com/ducklingcloud/vmt/blob/master/api/src/main/java/net/duckling/vmt/api/IRestOrgService.java
Github Open Source
Open Source
Apache-2.0
2,016
vmt
ducklingcloud
Java
Code
604
2,738
/* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * */ package net.duckling.vmt.api; import java.util.List; import java.util.Map; import net.duckling.vmt.api.domain.TreeNode; import net.duckling.vmt.api.domain.VmtDepart; import net.duckling.vmt.api.domain.VmtOrg; import net.duckling.vmt.api.domain.VmtOrgDomain; import net.duckling.vmt.api.domain.VmtUser; import cn.vlabs.rest.ServiceException; /** * 定义了一些对组织机构的操作 * @author lvly * @since 2013-5-21 */ public interface IRestOrgService { /** *获得一个人可见的组织,权限和是否是管理员,影响结果集 *@param umtId 某个人的umtId *@throws ServiceException **/ List<VmtOrg> getSbOrg(String umtId) throws ServiceException; /** * 获得一个组织下的所有用户 * @param orgDN 组织的dn * @throws ServiceException * validate:ErrorCode.DN_NOT_EXISTS dn不存在<br> * validate:ErrorCode.NOT_A_ORG 所提供的DN并不是一个有效的机构DN<br> * @return 所有用户 * */ List<VmtUser> getAllUsers(String orgDN) throws ServiceException; /** * 创建组织机构 * @param org 群组实体类 * @return 生成的dn * @throws ServiceException <br> * required:ErrorCode.FIELD_NULL creator,name,symbol<br> * validate:ErrorCode.SYMBOL_USED symbol已使用<br> * ErrorCode.PATTERN_ERROR 字段不符合规范<br> * @return 生成的组织的dn * */ String create(VmtOrg org)throws ServiceException; /** * 重命名组织机构 * @param orgDN 要改名的组织机构DN * @param newName 要改成的新名字 * @throws ServiceException <br> * validate:ErrorCode.DN_NOT_EXISTS dn不存在<br> * validate:ErrorCode.NOT_A_ORG 所提供的DN并不是一个有效的机构DN<br> * * */ void rename(String orgDN,String newName)throws ServiceException; /** * 删除一个组织机构 * @param orgDN 要删除的组织机构的DN * @throws ServiceException<br> * validate:ErrorCode.DN_NOT_EXISTS dn不存在<br> * validate:ErrorCode.NOT_A_ORG 所提供的DN并不是一个有效的机构DN<br> * */ void delete(String orgDN)throws ServiceException; /** * 给一个组织机构增加管理员,必须是组织的成员 * @param orgDN 目标组织机构的DN * @param umtId 期望加入的管理员的umtId * @throws ServiceException<br> * validate:ErrorCode.NOT_A_ORG 所提供的DN并不是一个有效的机构DN<br> * validate:ErrorCode.USER_NOT_EXISTS 所提供的umtId并不在当前组织里面<br> * */ void addAdmin(String orgDN,String umtId)throws ServiceException; /** * 判断组织机构的标识是否已被占用 * @param symbol 期望使用的组织标识 * @return (true,false) * <p>true:已被使用 * <p>false:可以使用 * */ boolean hasSymbolUsed(String symbol)throws ServiceException; /*** * 增加一个部门 * @param pdn 期望加到哪里,路径,如果为orgDN,那么就会加入到根 * @param depart 加入的部门信息 * @return 返回生成的部门dn * @throws ServiceException <br> * required:ErrorCode.FILELD_REQUIRED creator,name,symbol<br> * validate:ErrorCode.NOT_A_ORG 提供的部门不是标准的组织dn<br> * validate:ErrorCode.NAME_USED 部门名称已被使用<br> * validate:ErrorCode.SYMBOL_USED 部门标识已被使用<br> * validate:ErrorCode.PARTTERN_ERROR 字段名称不符合规范<br> * */ String addDepartment(String pdn,VmtDepart depart)throws ServiceException; /*** * 删除部门 * @param departDN 部门的dn * @return 返回删除的人员数量 * @throws ServiceException<br> * validate:ErrorCode.NOT_A_ORG 提供的部门不是标准的组织dn * */ int removeDepartment(String departDN) throws ServiceException; /** * 重命名部门 * @param departDN 期望重命名的部门的DN * @param newName 期望改成的名字 * @throws ServiceException<br> * validate:ErrorCode.NOT_A_ORG 提供的部门不是标准的组织dn<br> * validate:ErrorCode.NAME_USED 名字已被别人使用 * */ void renameDepartment(String departDN,String newName) throws ServiceException; /** * 判断部门名字是否可以使用 * @param pdn 期望探知的部门父路径 * @param departName 期望探知的部门名 * @return (true,false) * <p>true:已经被使用 * <p>false:可以使用 * @throws ServiceException<br> * validate:ErrorCode.NOT_A_ORG 提供的部门不是标准的组织dn<br> * */ boolean hasDepartNameUsed(String pdn,String departName)throws ServiceException; /** * 判断一个部门标识是否被使用 * @param pdn 期望探知的部门父路径 * @param symbol 期望探知的部门标识 * @return (true,false) * <p>true:已经被使用 * <p>false:可以使用 * @throws ServiceException<br> * validate:ErrorCode.NOT_A_ORG 提供的部门不是标准的组织dn<br> * */ boolean hasDepartSymbolUsed(String pdn,String symbol)throws ServiceException; /** * 移动人员(或者部门,部门功能暂时未开放) * @param targetDN 目标dn,如果成功则被移动到这里 * @param dns 用户(或者部门,部门功能暂时未开放)的dns; * @throws ServiceException<br> * validate:ErrorCode.NOT_A_ORG 提供的部门不是标准的组织dn<br> * */ void move(String targetDN,String dns[])throws ServiceException; /** * 获得树状结构, * @param targetDN 是组织的根节点 * @throws ServiceException<br> * validate:ErrorCode.NOT_A_ORG 提供的dn不是标准的组织dn<br> * ErrorCode.DN_NOT_EXISTS dn不存在<br> * @return 树状的TreeNode */ TreeNode getTree(String targetDN)throws ServiceException; /*** * 获得某个DN的下一个实体,有可能是VmtDepart或者VmtUser * * @param dn 父目录的dn * @throws ServiceException<br> * validate: * ErrorCode.NOT_A_ORG 提供的dn不是标准的组织dn<br> * ErrorCode.DN_NOT_EXISTS dn不存在<br> * ErrorCode.FILELD_REQUIRED * @return 获得下级目录 */ List<?> getChild(String dn)throws ServiceException; /** * 根据域名查询组织的详细信息 * @params domain 域名 例如 cstnet.cn * @return 匹配的组织,应该只有一个 * */ VmtOrg getOrgByDomain(String domain)throws ServiceException; /** * 所有组织和域名的对应关系 * @return return all org-domain mappings * */ List<VmtOrgDomain> getAllDomains()throws ServiceException; /** * 查询组织下所有用户的属性值 * @param dn * @param attributeName * @return * @throws ServiceException */ Map<String,String> searchUserAttribute(String dn, String attributeName) throws ServiceException; }
36,170
https://github.com/SaschaIoT/robot.sl/blob/master/robot.sl/Audio/AudioPlaying/AudioName.cs
Github Open Source
Open Source
MIT
2,018
robot.sl
SaschaIoT
C#
Code
74
480
namespace robot.sl.Audio.AudioPlaying { public enum AudioName { Welcome, Forward, Backward, Left, Right, Stop, Turn, SlightlyLeft, SlightlyRight, VerySlightlyLeft, VerySlightlyRight, Slow, Normal, Fast, DanceOn, DanceOff, DanceOn_Status, DanceOff_Status, DanceOnAlready, DanceOffAlready, StrongVibration, Stand, AutomatischesFahrenFesthaengen, Restart, Shutdown, AutomaticDriveOn, AutomaticDriveOff, AutomaticDriveOn_Status, AutomaticDriveOff_Status, AutomaticDriveOnAlready, AutomaticDriveOffAlready, ReallyRestart, ReallyShutdown, AppError, GamepadVibrationOn, GamepadVibrationOff, CliffSensorOn, CliffSensorOff, CliffSensorAlreadyOn, CliffSensorAlreadyOff, SoundModeAlreadyOn, HeadsetSpeakerOff, HeadsetSpeakerAlreadyOff, HeadsetSpeakerOn, HeadsetSpeakerAlreadyOn, CarSpeakerOff, CarSpeakerAlreadyOff, CarSpeakerOn, CarSpeakerAlreadyOn, AllSpeakerOff, AllSpeakerAlreadyOff, AllSpeakerOn, AllSpeakerAlreadyOn, SoundModeOn, SoundModusAlreadyOff, SoundModusOff, Commands, ControlCommands, SystemCommands, CameraUp, CameraDown, CameraSlightlyUp, CameraSlightlyDown, TurnToLongLeft, TurnToLongRight } }
42,109
https://github.com/niteshregmi1234/avasplus/blob/master/onlineChat/app/start/global.php
Github Open Source
Open Source
MIT
2,017
avasplus
niteshregmi1234
PHP
Code
515
1,175
<?php use Illuminate\Support\Facades\Config; /* |-------------------------------------------------------------------------- | Register The Laravel Class Loader |-------------------------------------------------------------------------- | | In addition to using Composer, you may use the Laravel class loader to | load your controllers and models. This is useful for keeping all of | your classes in the "global" namespace without Composer updating. | */ ClassLoader::addDirectories(array( app_path().'/commands', app_path().'/controllers', app_path().'/drivers', app_path().'/models', app_path().'/database/seeds', app_path().'/utils', )); /* |-------------------------------------------------------------------------- | Application Error Logger |-------------------------------------------------------------------------- | | Here we will configure the error logger setup for the application which | is built on top of the wonderful Monolog library. By default we will | build a basic log file setup which creates a single file for logs. | */ Log::useFiles(storage_path().'/logs/laravel.log'); /* |-------------------------------------------------------------------------- | Application Error Handler |-------------------------------------------------------------------------- | | Here you may handle any errors that occur in your application, including | logging them or displaying custom views for specific errors. You may | even register several error handlers to handle different types of | exceptions. If nothing is returned, the default error view is | shown, which includes a detailed stack trace during debug. | */ App::error(function(Exception $exception, $code) { // Since API errors can occur in any controller, define a global handler // that redirects to login (if non-Ajax request) // or returns status (Ajax) appropriately. if($exception instanceof GuzzleHttp\Exception\RequestException && $exception->getResponse()) { $apiStatus = $exception->getResponse()->getStatusCode(); } else if($exception instanceof GuzzleHttp\Exception\ConnectException) { $apiStatus = 503; // service not available } else { $apiStatus = 500; } $apiRequestUnauthorized = $apiStatus == 401; $notAuthenticated = $exception instanceof OnlineChatNotAuthenticatedException; if($apiRequestUnauthorized || $notAuthenticated) { if(Request::ajax()) { // There is nothing an Ajax client can do at this point - // the human will have to log in. There will need to be appropriate // feedback for this in the UI, when an Ajax call fails; // e.g. a lightbox with a link to the login page. return Response::make('Unauthorized', 401); } else { if($apiRequestUnauthorized) { Session::flash('error', 'Your session has reached its time limit. Please log in again to continue using the CLEAR application.'); } return Redirect::guest('/login'); } } Log::error(get_class($exception)."|{$_SERVER['REQUEST_METHOD']}|{$_SERVER['REQUEST_URI']}|".Session::get('email')); if (isset($_SERVER['HTTP_REFERER'])) { Log::error("Referrer: ".$_SERVER['HTTP_REFERER']); } // find the last point in application code and log the parameters used there foreach ($exception->getTrace() as $trace) { if (isset($trace['file']) && !empty($trace['args']) && false !== strpos($trace['file'], "onlineChat/app")) { Log::error($trace['file']." : ".$trace['line']); Log::error($trace['args']); break; } } Log::error($exception); // Avoid default HTML error page for Ajax if(Request::ajax()) { return Response::make(Config::get('app.debug') ? $exception->getMessage() : 'Error', $apiStatus); } }); /* |-------------------------------------------------------------------------- | Maintenance Mode Handler |-------------------------------------------------------------------------- | | The "down" Artisan command gives you the ability to put an application | into maintenance mode. Here, you will define what is displayed back | to the user if maintenance mode is in effect for the application. | */ App::down(function() { return Response::make("Be right back!", 503); }); /* |-------------------------------------------------------------------------- | Require The Filters File |-------------------------------------------------------------------------- | | Next we will load the filters file for the application. This gives us | a nice separate location to store our route and application filter | definitions instead of putting them all in the main routes file. | */ require app_path().'/filters.php'; Auth::extend('onlineChatApi', function($app) { return new \Illuminate\Auth\Guard(new OnlineChatApiUserProvider(), App::make('session.store')); });
42,366
https://github.com/ava-labs/avalanchego/blob/master/vms/avm/txs/executor/semantic_verifier_test.go
Github Open Source
Open Source
BSD-3-Clause
2,023
avalanchego
ava-labs
Go
Code
2,086
10,829
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. package executor import ( "reflect" "testing" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/manager" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/avm/fxs" "github.com/ava-labs/avalanchego/vms/avm/states" "github.com/ava-labs/avalanchego/vms/avm/txs" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) func TestSemanticVerifierBaseTx(t *testing.T) { ctx := newContext(t) typeToFxIndex := make(map[reflect.Type]int) secpFx := &secp256k1fx.Fx{} parser, err := txs.NewCustomParser( typeToFxIndex, new(mockable.Clock), logging.NoWarn{}, []fxs.Fx{ secpFx, }, ) require.NoError(t, err) codec := parser.Codec() txID := ids.GenerateTestID() utxoID := avax.UTXOID{ TxID: txID, OutputIndex: 2, } asset := avax.Asset{ ID: ids.GenerateTestID(), } inputSigner := secp256k1fx.Input{ SigIndices: []uint32{ 0, }, } fxInput := secp256k1fx.TransferInput{ Amt: 12345, Input: inputSigner, } input := avax.TransferableInput{ UTXOID: utxoID, Asset: asset, In: &fxInput, } baseTx := txs.BaseTx{ BaseTx: avax.BaseTx{ Ins: []*avax.TransferableInput{ &input, }, }, } backend := &Backend{ Ctx: ctx, Config: &feeConfig, Fxs: []*fxs.ParsedFx{ { ID: secp256k1fx.ID, Fx: secpFx, }, }, TypeToFxIndex: typeToFxIndex, Codec: codec, FeeAssetID: ids.GenerateTestID(), Bootstrapped: true, } require.NoError(t, secpFx.Bootstrapped()) outputOwners := secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ keys[0].Address(), }, } output := secp256k1fx.TransferOutput{ Amt: 12345, OutputOwners: outputOwners, } utxo := avax.UTXO{ UTXOID: utxoID, Asset: asset, Out: &output, } unsignedCreateAssetTx := txs.CreateAssetTx{ States: []*txs.InitialState{{ FxIndex: 0, }}, } createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } tests := []struct { name string stateFunc func(*gomock.Controller) states.Chain txFunc func(*require.Assertions) *txs.Tx err error }{ { name: "valid", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: nil, }, { name: "assetID mismatch", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) utxo := utxo utxo.Asset.ID = ids.GenerateTestID() state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: errAssetIDMismatch, }, { name: "not allowed input feature extension", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: errIncompatibleFx, }, { name: "invalid signature", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[1]}, }, )) return tx }, err: secp256k1fx.ErrWrongSig, }, { name: "missing UTXO", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(nil, database.ErrNotFound) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: database.ErrNotFound, }, { name: "invalid UTXO amount", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) output := output output.Amt-- utxo := utxo utxo.Out = &output state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: secp256k1fx.ErrMismatchedAmounts, }, { name: "not allowed output feature extension", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { baseTx := baseTx baseTx.Ins = nil baseTx.Outs = []*avax.TransferableOutput{ { Asset: asset, Out: &output, }, } tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{}, )) return tx }, err: errIncompatibleFx, }, { name: "unknown asset", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(nil, database.ErrNotFound) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: database.ErrNotFound, }, { name: "not an asset", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) tx := txs.Tx{ Unsigned: &baseTx, } state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&tx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &baseTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: errNotAnAsset, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) state := test.stateFunc(ctrl) tx := test.txFunc(require) err = tx.Unsigned.Visit(&SemanticVerifier{ Backend: backend, State: state, Tx: tx, }) require.ErrorIs(err, test.err) }) } } func TestSemanticVerifierExportTx(t *testing.T) { ctx := newContext(t) ctrl := gomock.NewController(t) validatorState := validators.NewMockState(ctrl) validatorState.EXPECT().GetSubnetID(gomock.Any(), ctx.CChainID).AnyTimes().Return(ctx.SubnetID, nil) ctx.ValidatorState = validatorState typeToFxIndex := make(map[reflect.Type]int) secpFx := &secp256k1fx.Fx{} parser, err := txs.NewCustomParser( typeToFxIndex, new(mockable.Clock), logging.NoWarn{}, []fxs.Fx{ secpFx, }, ) require.NoError(t, err) codec := parser.Codec() txID := ids.GenerateTestID() utxoID := avax.UTXOID{ TxID: txID, OutputIndex: 2, } asset := avax.Asset{ ID: ids.GenerateTestID(), } inputSigner := secp256k1fx.Input{ SigIndices: []uint32{ 0, }, } fxInput := secp256k1fx.TransferInput{ Amt: 12345, Input: inputSigner, } input := avax.TransferableInput{ UTXOID: utxoID, Asset: asset, In: &fxInput, } baseTx := txs.BaseTx{ BaseTx: avax.BaseTx{ Ins: []*avax.TransferableInput{ &input, }, }, } exportTx := txs.ExportTx{ BaseTx: baseTx, DestinationChain: ctx.CChainID, } backend := &Backend{ Ctx: ctx, Config: &feeConfig, Fxs: []*fxs.ParsedFx{ { ID: secp256k1fx.ID, Fx: secpFx, }, }, TypeToFxIndex: typeToFxIndex, Codec: codec, FeeAssetID: ids.GenerateTestID(), Bootstrapped: true, } require.NoError(t, secpFx.Bootstrapped()) outputOwners := secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ keys[0].Address(), }, } output := secp256k1fx.TransferOutput{ Amt: 12345, OutputOwners: outputOwners, } utxo := avax.UTXO{ UTXOID: utxoID, Asset: asset, Out: &output, } unsignedCreateAssetTx := txs.CreateAssetTx{ States: []*txs.InitialState{{ FxIndex: 0, }}, } createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } tests := []struct { name string stateFunc func(*gomock.Controller) states.Chain txFunc func(*require.Assertions) *txs.Tx err error }{ { name: "valid", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: nil, }, { name: "assetID mismatch", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) utxo := utxo utxo.Asset.ID = ids.GenerateTestID() state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: errAssetIDMismatch, }, { name: "not allowed input feature extension", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: errIncompatibleFx, }, { name: "invalid signature", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[1]}, }, )) return tx }, err: secp256k1fx.ErrWrongSig, }, { name: "missing UTXO", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(nil, database.ErrNotFound) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: database.ErrNotFound, }, { name: "invalid UTXO amount", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) output := output output.Amt-- utxo := utxo utxo.Out = &output state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: secp256k1fx.ErrMismatchedAmounts, }, { name: "not allowed output feature extension", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { exportTx := exportTx exportTx.Ins = nil exportTx.ExportedOuts = []*avax.TransferableOutput{ { Asset: asset, Out: &output, }, } tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{}, )) return tx }, err: errIncompatibleFx, }, { name: "unknown asset", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(nil, database.ErrNotFound) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: database.ErrNotFound, }, { name: "not an asset", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) tx := txs.Tx{ Unsigned: &baseTx, } state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&tx, nil) return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) return tx }, err: errNotAnAsset, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) state := test.stateFunc(ctrl) tx := test.txFunc(require) err = tx.Unsigned.Visit(&SemanticVerifier{ Backend: backend, State: state, Tx: tx, }) require.ErrorIs(err, test.err) }) } } func TestSemanticVerifierExportTxDifferentSubnet(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) ctx := newContext(t) validatorState := validators.NewMockState(ctrl) validatorState.EXPECT().GetSubnetID(gomock.Any(), ctx.CChainID).AnyTimes().Return(ids.GenerateTestID(), nil) ctx.ValidatorState = validatorState typeToFxIndex := make(map[reflect.Type]int) secpFx := &secp256k1fx.Fx{} parser, err := txs.NewCustomParser( typeToFxIndex, new(mockable.Clock), logging.NoWarn{}, []fxs.Fx{ secpFx, }, ) require.NoError(err) codec := parser.Codec() txID := ids.GenerateTestID() utxoID := avax.UTXOID{ TxID: txID, OutputIndex: 2, } asset := avax.Asset{ ID: ids.GenerateTestID(), } inputSigner := secp256k1fx.Input{ SigIndices: []uint32{ 0, }, } fxInput := secp256k1fx.TransferInput{ Amt: 12345, Input: inputSigner, } input := avax.TransferableInput{ UTXOID: utxoID, Asset: asset, In: &fxInput, } baseTx := txs.BaseTx{ BaseTx: avax.BaseTx{ Ins: []*avax.TransferableInput{ &input, }, }, } exportTx := txs.ExportTx{ BaseTx: baseTx, DestinationChain: ctx.CChainID, } backend := &Backend{ Ctx: ctx, Config: &feeConfig, Fxs: []*fxs.ParsedFx{ { ID: secp256k1fx.ID, Fx: secpFx, }, }, TypeToFxIndex: typeToFxIndex, Codec: codec, FeeAssetID: ids.GenerateTestID(), Bootstrapped: true, } require.NoError(secpFx.Bootstrapped()) outputOwners := secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ keys[0].Address(), }, } output := secp256k1fx.TransferOutput{ Amt: 12345, OutputOwners: outputOwners, } utxo := avax.UTXO{ UTXOID: utxoID, Asset: asset, Out: &output, } unsignedCreateAssetTx := txs.CreateAssetTx{ States: []*txs.InitialState{{ FxIndex: 0, }}, } createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) tx := &txs.Tx{ Unsigned: &exportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) err = tx.Unsigned.Visit(&SemanticVerifier{ Backend: backend, State: state, Tx: tx, }) require.ErrorIs(err, verify.ErrMismatchedSubnetIDs) } func TestSemanticVerifierImportTx(t *testing.T) { ctrl := gomock.NewController(t) ctx := newContext(t) validatorState := validators.NewMockState(ctrl) validatorState.EXPECT().GetSubnetID(gomock.Any(), ctx.CChainID).AnyTimes().Return(ctx.SubnetID, nil) ctx.ValidatorState = validatorState baseDBManager := manager.NewMemDB(version.Semantic1_0_0) m := atomic.NewMemory(prefixdb.New([]byte{0}, baseDBManager.Current().Database)) ctx.SharedMemory = m.NewSharedMemory(ctx.ChainID) typeToFxIndex := make(map[reflect.Type]int) fx := &secp256k1fx.Fx{} parser, err := txs.NewCustomParser( typeToFxIndex, new(mockable.Clock), logging.NoWarn{}, []fxs.Fx{ fx, }, ) require.NoError(t, err) codec := parser.Codec() utxoID := avax.UTXOID{ TxID: ids.GenerateTestID(), OutputIndex: 2, } asset := avax.Asset{ ID: ids.GenerateTestID(), } outputOwners := secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ keys[0].Address(), }, } baseTx := txs.BaseTx{ BaseTx: avax.BaseTx{ NetworkID: constants.UnitTestID, BlockchainID: ctx.ChainID, Outs: []*avax.TransferableOutput{{ Asset: asset, Out: &secp256k1fx.TransferOutput{ Amt: 1000, OutputOwners: outputOwners, }, }}, }, } input := avax.TransferableInput{ UTXOID: utxoID, Asset: asset, In: &secp256k1fx.TransferInput{ Amt: 12345, Input: secp256k1fx.Input{ SigIndices: []uint32{0}, }, }, } unsignedImportTx := txs.ImportTx{ BaseTx: baseTx, SourceChain: ctx.CChainID, ImportedIns: []*avax.TransferableInput{ &input, }, } importTx := &txs.Tx{ Unsigned: &unsignedImportTx, } require.NoError(t, importTx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[0]}, }, )) backend := &Backend{ Ctx: ctx, Config: &feeConfig, Fxs: []*fxs.ParsedFx{ { ID: secp256k1fx.ID, Fx: fx, }, }, TypeToFxIndex: typeToFxIndex, Codec: codec, FeeAssetID: ids.GenerateTestID(), Bootstrapped: true, } require.NoError(t, fx.Bootstrapped()) output := secp256k1fx.TransferOutput{ Amt: 12345, OutputOwners: outputOwners, } utxo := avax.UTXO{ UTXOID: utxoID, Asset: asset, Out: &output, } utxoBytes, err := codec.Marshal(txs.CodecVersion, utxo) require.NoError(t, err) peerSharedMemory := m.NewSharedMemory(ctx.CChainID) inputID := utxo.InputID() require.NoError(t, peerSharedMemory.Apply(map[ids.ID]*atomic.Requests{ctx.ChainID: {PutRequests: []*atomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ keys[0].PublicKey().Address().Bytes(), }, }}}})) unsignedCreateAssetTx := txs.CreateAssetTx{ States: []*txs.InitialState{{ FxIndex: 0, }}, } createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } tests := []struct { name string stateFunc func(*gomock.Controller) states.Chain txFunc func(*require.Assertions) *txs.Tx expectedErr error }{ { name: "valid", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil).AnyTimes() return state }, txFunc: func(*require.Assertions) *txs.Tx { return importTx }, expectedErr: nil, }, { name: "not allowed input feature extension", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil).AnyTimes() return state }, txFunc: func(*require.Assertions) *txs.Tx { return importTx }, expectedErr: errIncompatibleFx, }, { name: "invalid signature", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil).AnyTimes() return state }, txFunc: func(require *require.Assertions) *txs.Tx { tx := &txs.Tx{ Unsigned: &unsignedImportTx, } require.NoError(tx.SignSECP256K1Fx( codec, [][]*secp256k1.PrivateKey{ {keys[1]}, }, )) return tx }, expectedErr: secp256k1fx.ErrWrongSig, }, { name: "not allowed output feature extension", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ Unsigned: &unsignedCreateAssetTx, } state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil).AnyTimes() return state }, txFunc: func(require *require.Assertions) *txs.Tx { importTx := unsignedImportTx importTx.Ins = nil importTx.ImportedIns = []*avax.TransferableInput{ &input, } tx := &txs.Tx{ Unsigned: &importTx, } require.NoError(tx.SignSECP256K1Fx( codec, nil, )) return tx }, expectedErr: errIncompatibleFx, }, { name: "unknown asset", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(nil, database.ErrNotFound) return state }, txFunc: func(*require.Assertions) *txs.Tx { return importTx }, expectedErr: database.ErrNotFound, }, { name: "not an asset", stateFunc: func(ctrl *gomock.Controller) states.Chain { state := states.NewMockChain(ctrl) tx := txs.Tx{ Unsigned: &baseTx, } state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(&tx, nil) return state }, txFunc: func(*require.Assertions) *txs.Tx { return importTx }, expectedErr: errNotAnAsset, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) state := test.stateFunc(ctrl) tx := test.txFunc(require) err := tx.Unsigned.Visit(&SemanticVerifier{ Backend: backend, State: state, Tx: tx, }) require.ErrorIs(err, test.expectedErr) }) } }
33,694
https://github.com/albyho/Tubumu.Utils/blob/master/Models/Page.cs
Github Open Source
Open Source
MIT
null
Tubumu.Utils
albyho
C#
Code
77
226
using System.Collections.Generic; namespace Tubumu.Utils.Models { /// <summary> /// 分页 /// </summary> /// <typeparam name="T"></typeparam> public class Page<T> { /// <summary> /// 列表 /// </summary> public List<T> List { get; set; } /// <summary> /// 元素总数 /// </summary> public int TotalItemCount { get; set; } /// <summary> /// 总分页数 /// </summary> public int TotalPageCount { get; set; } public Page(List<T> list, int totalItemCount, int totalPageCount) { List = list; TotalItemCount = totalItemCount; TotalPageCount = totalPageCount; } } }
18,779
https://github.com/SNC6SI/BlfLoad/blob/master/BlfExtractor.c
Github Open Source
Open Source
Apache-2.0
2,021
BlfLoad
SNC6SI
C
Code
639
2,566
#include "mex.h" #include <tchar.h> /* RTL */ #include <stdio.h> #include <windows.h> #include "binlog.h" /* BL */ #include <math.h> #define STRICT /* WIN32 */ static BYTE dlcMapping[17] = {0,1,2,3,4,5,6,7,8,12,16,20,24,32,48,64}; int read_statistics(LPCTSTR pFileName, VBLFileStatisticsEx* pstatistics) { HANDLE hFile; BOOL bSuccess; hFile = BLCreateFile( pFileName, GENERIC_READ); if ( INVALID_HANDLE_VALUE == hFile) { return -1; } BLGetFileStatisticsEx( hFile, pstatistics); if ( !BLCloseHandle( hFile)) { return -1; } return bSuccess ? 0 : -1; } int read_info( LPCTSTR pFileName, LPDWORD pRead, double* candata_, double* canmsgid_, double* canchannel_, double* cantime_) { HANDLE hFile; VBLObjectHeaderBase base; VBLCANMessage message; VBLCANMessage2 message2; VBLCANFDMessage64 messageFD; unsigned int i; BOOL bSuccess; if ( NULL == pRead) { return -1; } *pRead = 0; /* open file */ hFile = BLCreateFile( pFileName, GENERIC_READ); if ( INVALID_HANDLE_VALUE == hFile) { return -1; } bSuccess = TRUE; /* read base object header from file */ while ( bSuccess && BLPeekObject( hFile, &base)) { switch ( base.mObjectType) { case BL_OBJ_TYPE_CAN_MESSAGE: /* read CAN message */ message.mHeader.mBase = base; bSuccess = BLReadObjectSecure( hFile, &message.mHeader.mBase, sizeof(message)); /* free memory for the CAN message */ if( bSuccess) { for(i=0;i<8;i++) *(candata_ + (*pRead)*64 + i) = (double)message.mData[i]; *(canmsgid_ + (*pRead)) = (double)message.mID; *(canchannel_ + (*pRead)) = (double)message.mChannel; if(message.mHeader.mObjectFlags==BL_OBJ_FLAG_TIME_ONE_NANS) *(cantime_ + (*pRead)) = ((double)message.mHeader.mObjectTimeStamp)/1000000000; else *(cantime_ + (*pRead)) = ((double)message.mHeader.mObjectTimeStamp)/100000; BLFreeObject( hFile, &message.mHeader.mBase); *pRead += 1; } break; case BL_OBJ_TYPE_CAN_MESSAGE2: /* read CAN message */ message2.mHeader.mBase = base; bSuccess = BLReadObjectSecure( hFile, &message2.mHeader.mBase, sizeof(message2)); /* free memory for the CAN message */ if( bSuccess) { for(i=0;i<8;i++) *(candata_ + (*pRead)*64 + i) = (double)message2.mData[i]; *(canmsgid_ + (*pRead)) = (double)message2.mID; *(canchannel_ + (*pRead)) = (double)message2.mChannel; if(message2.mHeader.mObjectFlags==BL_OBJ_FLAG_TIME_ONE_NANS) *(cantime_ + (*pRead)) = ((double)message2.mHeader.mObjectTimeStamp)/1000000000; else *(cantime_ + (*pRead)) = ((double)message2.mHeader.mObjectTimeStamp)/100000; BLFreeObject( hFile, &message2.mHeader.mBase); *pRead += 1; } break; case BL_OBJ_TYPE_CAN_FD_MESSAGE_64: messageFD.mHeader.mBase = base; bSuccess = BLReadObjectSecure( hFile, &messageFD.mHeader.mBase, sizeof(messageFD)); if( bSuccess) { for(i=0;i<dlcMapping[messageFD.mDLC];i++) *(candata_ + (*pRead)*64 + i) = (double)messageFD.mData[i]; *(canmsgid_ + (*pRead)) = (double)messageFD.mID; *(canchannel_ + (*pRead)) = (double)messageFD.mChannel; if(messageFD.mHeader.mObjectFlags==BL_OBJ_FLAG_TIME_ONE_NANS) *(cantime_ + (*pRead)) = ((double)messageFD.mHeader.mObjectTimeStamp)/1000000000; else *(cantime_ + (*pRead)) = ((double)messageFD.mHeader.mObjectTimeStamp)/100000; BLFreeObject( hFile, &messageFD.mHeader.mBase); *pRead += 1; } break; case BL_OBJ_TYPE_ENV_INTEGER: case BL_OBJ_TYPE_ENV_DOUBLE: case BL_OBJ_TYPE_ENV_STRING: case BL_OBJ_TYPE_ENV_DATA: case BL_OBJ_TYPE_ETHERNET_FRAME: case BL_OBJ_TYPE_APP_TEXT: default: /* skip all other objects */ bSuccess = BLSkipObject( hFile, &base); break; } //mexPrintf("%s%u\n", "count: ", *pRead); } /* close file */ if ( !BLCloseHandle( hFile)) { return -1; } return bSuccess ? 0 : -1; } void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // define DWORD msgcnt; double *candata, *cantime, *canmsgid, *canchannel; LPCTSTR pFileName; char *filetoread; size_t filenamelen; int filestatus; double needmemorysize; double *PWin; double PW; double *pswitchFlag; unsigned char switchFlag = 0; int result_statistic, result_read; VBLFileStatisticsEx statistics = { sizeof( statistics)}; // filename filenamelen = mxGetN(prhs[0])*sizeof(mxChar)+1; filetoread = mxMalloc(filenamelen); filestatus = mxGetString(prhs[0], filetoread, (mwSize)filenamelen); pFileName = filetoread; // PW if (nrhs<2) { return; }else { PW = 789456.0F; PWin = mxGetPr(prhs[1]); if (!((*PWin - PW)<2)) { return; } } if (nrhs==3) { pswitchFlag = mxGetPr(prhs[2]); switchFlag = (unsigned char)(*pswitchFlag); } // print author infos if(switchFlag!=1U) { char *blfversion ="1.3.0"; mexPrintf("%s\n", "BlfLoad -- Loads a CANoe/CANalyzer Data file into a Matlab Structure."); mexPrintf("%s%s\t", "Version: ", blfversion); mexPrintf("%s\t%s\n\n", "by Shen, Chenghao", "snc6si@gmail.com"); } mexPrintf("%s%s\n", "Loading File: ", pFileName); // read blf statistics to determine output matrix size result_statistic = 0; result_statistic = read_statistics( pFileName, &statistics); if(switchFlag!=1U) { //print statistics info mexPrintf("%s%u%s\n\n", "The blf file contains ", statistics.mObjectCount, " can(fd) messages"); needmemorysize = ((double)statistics.mObjectCount)*(8+1+1+1)*8/1024/1024; //mexPrintf("%s%f%s\n", "This requires ", needmemorysize, " Mb Matlab Memory"); } // plhs[0]: candata plhs[0] = mxCreateDoubleMatrix (64,statistics.mObjectCount , mxREAL); candata = mxGetPr(plhs[0]); // plhs[1]: canmsgid plhs[1] = mxCreateDoubleMatrix (1,statistics.mObjectCount , mxREAL); canmsgid = mxGetPr(plhs[1]); // plhs[2]: canchannel plhs[2] = mxCreateDoubleMatrix (1,statistics.mObjectCount , mxREAL); canchannel = mxGetPr(plhs[2]); // plhs[3]: camtime plhs[3] = mxCreateDoubleMatrix (1,statistics.mObjectCount , mxREAL); cantime = mxGetPr(plhs[3]); result_read = 0; result_read = read_info( pFileName, &msgcnt, candata, canmsgid, canchannel, cantime); mxSetN(plhs[0],msgcnt); mxSetN(plhs[1],msgcnt); mxSetN(plhs[2],msgcnt); mxSetN(plhs[3],msgcnt); // free filetoread, which is created using mxMalloc mxFree(filetoread); }
42,481
https://github.com/SayanBan/HackerRank-30-Days-of-code/blob/master/Day 01/Data Types.rb
Github Open Source
Open Source
MIT
2,019
HackerRank-30-Days-of-code
SayanBan
Ruby
Code
82
168
i = 4 d = 4.0 s = 'HackerRank ' # Declare second integer, double, and String variables. # Read and save an integer, double, and String to your variables. num2= gets.chomp.to_i sum= i+num2 puts "#{sum}" # Print the sum of both integer variables on a new line. num3= gets.chomp.to_f sum= d+num3 puts "#{sum}" # Print the sum of the double variables on a new line. # Concatenate and print the String variables on a new line name=gets.chomp puts "#{s}" + "#{name}"
11,832
https://github.com/chronolaw/ngx_ansic_dev/blob/master/t/ngx_http_ndg_thread_module.t
Github Open Source
Open Source
BSD-2-Clause
2,022
ngx_ansic_dev
chronolaw
Perl
Code
93
250
# Copyright (c) 2018 by chrono # # sudo cpan Test::Nginx # export PATH=/opt/nginx/sbin:$PATH # prove t/var.t #use Test::Nginx::Socket 'no_plan'; use Test::Nginx::Socket; repeat_each(1); plan tests => repeat_each() * (blocks() * 2); run_tests(); __DATA__ === TEST 1 : thread --- main_config thread_pool xxx threads=2; --- config location = /thread { ndg_thread xxx; } --- request GET /thread --- response_body chomp hello nginx thread --- error_log thread task 0 ok === TEST 2 : no threadpool --- config location = /thread { ndg_thread xxx; } --- request GET /thread --- ignore_response --- error_log ngx_thread_pool_get failed
28,033