text stringlengths 1 1.05M |
|---|
#!/usr/bin/env bash
: '
Android debloating script
Usage: ./android_cleanup.sh
Note: Phone should be connected by usb and debugging mode enabled under Developer options.
./packages_to_remove.txt file should list apps to remove (1 per line); modify as needed.
ARGS:
None: N/A
Output:
None: N/A
DESCRIPTION:
A script for debloating android Huawei device (nova 2 Plus) using adb shell;
Remove list of unnecessary preinstalled apps from Google, Huawei, Facebook, and other junk;
the list is in file packages_to_remove.txt and can be modified;
Basic apps like contacts, dialer, filemanger, notes, musicplayer, etc. are replaced by
open-source _simplemobiletools_ available on F-Droid. Change these if you prefer other apps.
J.A., xrzfyvqk_k1jw@pm.me
'
cat > package_urls.txt << EOF
https://f-droid.org/repo/rkr.simplekeyboard.inputmethod_84.apk
https://f-droid.org/repo/com.simplemobiletools.filemanager.pro_103.apk
https://f-droid.org/repo/com.simplemobiletools.notes.pro_82.apk
https://f-droid.org/repo/com.simplemobiletools.musicplayer_86.apk
https://f-droid.org/repo/com.simplemobiletools.dialer_23.apk
https://f-droid.org/repo/com.simplemobiletools.flashlight_47.apk
https://f-droid.org/repo/com.simplemobiletools.contacts.pro_82.apk
https://f-droid.org/repo/com.simplemobiletools.gallery.pro_341.apk
https://dist.torproject.org/torbrowser/10.5.3/tor-browser-10.5.3-android-armv7-multi.apk # tor browser (firefox) for android
EOF
sed 's/.*\///g' package_urls.txt > packages_to_add.txt
wget -P /tmp/app_downloads -i package_urls.txt
for i in $(cat packages_to_add.txt); do
echo installing package "$i" ...
adb install /tmp/app_downloads/"$i"
done
for i in $(cat ./packages_to_remove.txt); do
echo uninstalling package "$i" ...
adb shell pm uninstall --user 0 "$i"
done
rm packages_to_add.txt package_urls.txt
rm -r /tmp/app_downloads/
echo 'Done cleaning!'
|
-------------------------------------------------------------------------------
--
-- Script: save_sqlplus_settings.sql
-- Purpose: to reset sqlplus settings
--
-- Copyright: (c) Ixora Pty Ltd
-- Author: <NAME>
--
-------------------------------------------------------------------------------
set termout off
store set sqlplus_settings replace
clear breaks
clear columns
clear computes
set feedback off
set verify off
set termout on
set define "&"
|
<reponame>aut-ce/CE304-OS-Lab<gh_stars>1-10
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <time.h>
/*
* here we are going to see a normal distribution from binomial distribution for a large n
*/
const int k = 10; // create 10 process then wait for their results
int gen();
void print_his(int[25]);
int main() {
int n;
int i, j;
int his[25];
for (i = 0; i < 25; i++) {
his[i] = 0;
}
scanf("%d", &n);
for (i = 0; i < n; i += k) {
for (j = 0; j < k; j++) {
srand(i + j + time(0));
pid_t pid = fork();
if (pid == 0) {
int ret = gen();
exit(ret + 12);
} else if (pid > 0) {
} else {
perror("fork failed");
}
}
for (j = 0; j < k; j++) {
int ret;
wait(&ret);
ret = WEXITSTATUS(ret);
his[ret]++;
}
}
print_his(his);
}
// print_his print the histogram chart of the collected data
void print_his(int his[25]) {
int i, j;
for (i = 0; i < 25; i++) {
printf("%d: ", i - 12);
for (j = 0; j < his[i]; j++) {
printf("*");
}
printf("\n");
}
}
// gen generates 12 numbers between 0 to 100 then compare them with 49 and return a counter with
// the following conditions
// if n <= 49 => count--
// if n > 49 => count++
int gen() {
int count = 0;
int i;
for (i = 0; i < 12; i++) {
int n = rand() % 100;
if (n <= 49) {
count--;
} else {
count++;
}
}
return count;
}
|
<reponame>Thiagosilvaguitar/Guitarflix
import React from 'react';
function ButtonLink(props){
//props => { className: "O que alguem passar"}
console.log(props)
return(
<a href="{props.href}" className={props.className}>
{props.children}
</a>
);
}
export default ButtonLink; |
scons platform=switch target=debug $@ -j8
|
struct PriorityQueue<T> {
heap: Vec<(T, i32)>,
}
impl<T> PriorityQueue<T> {
fn new() -> Self {
PriorityQueue { heap: Vec::new() }
}
fn parent(k: usize) -> usize {
k / 2
}
fn enqueue(&mut self, element: T, priority: i32) {
self.heap.push((element, priority));
let mut i = self.heap.len() - 1;
while i > 0 && self.heap[i].1 > self.heap[PriorityQueue::<T>::parent(i)].1 {
self.heap.swap(i, PriorityQueue::<T>::parent(i));
i = PriorityQueue::<T>::parent(i);
}
}
fn dequeue(&mut self) -> Option<T> {
if self.heap.is_empty() {
return None;
}
let max_element = self.heap.swap_remove(0).0;
if !self.heap.is_empty() {
self.heapify(0);
}
Some(max_element)
}
fn heapify(&mut self, mut i: usize) {
loop {
let left = 2 * i + 1;
let right = 2 * i + 2;
let mut largest = i;
if left < self.heap.len() && self.heap[left].1 > self.heap[largest].1 {
largest = left;
}
if right < self.heap.len() && self.heap[right].1 > self.heap[largest].1 {
largest = right;
}
if largest != i {
self.heap.swap(i, largest);
i = largest;
} else {
break;
}
}
}
} |
#!/bin/sh
for arg; do
case $arg in
DESTDIR=*) DESTDIR=${arg#DESTDIR=};;
esac;
done
# program
install -bC --mode=0644 geeksqlite.conf $DESTDIR/etc/geeksqlite
install -bC --mode=0755 geeksqlite $DESTDIR/usr/bin/geeksqlite
mkdir -p $DESTDIR/usr/lib/geeksqlite
install -bC --mode=0755 geeksqlite.py $DESTDIR/usr/lib/geeksqlite
install -bC --mode=0755 dist.py $DESTDIR/usr/lib/geeksqlite
install -bC --mode=0755 filedialog.py $DESTDIR/usr/lib/geeksqlite
mkdir -p $DESTDIR/usr/lib/geeksqlite/interface
install -bC --mode=0644 interface/*.glade $DESTDIR/usr/lib/geeksqlite/interface
# docs
install -bC --mode=0644 README $DESTDIR/usr/share/doc/geeksqlite/README
install -bC --mode=0644 ./geeksqlite.1.gz $DESTDIR/usr/man/man1/geeksqlite.1.gz
# desktop
install -bC --mode=0755 geeksqlite.desktop $DESTDIR/usr/share/applications/geeksqlite.desktop
install -bC --mode=0644 ./geeksqlite.xpm $DESTDIR/usr/share/pixmaps/geeksqlite.xpm
# localization
install -bC --mode=0644 language/de/LC_MESSAGES/geeksqlite.mo $DESTDIR/usr/share/locale/de/LC_MESSAGES/geeksqlite.mo
install -bC --mode=0644 language/en/LC_MESSAGES/geeksqlite.mo $DESTDIR/usr/share/locale/en/LC_MESSAGES/geeksqlite.mo
install -bC --mode=0644 language/eo/LC_MESSAGES/geeksqlite.mo $DESTDIR/usr/share/locale/eo/LC_MESSAGES/geeksqlite.mo
|
#!/bin/sh
FLASK_APP=app.py flask run
|
# stop erubis from printing it's version number all the time
require 'stringio'
old_stdout = $stdout
$stdout = StringIO.new
require 'erubis/helpers/rails_helper'
$stdout = old_stdout
module RailsXss
class Erubis < ::Erubis::Eruby
def add_preamble(src)
src << "@output_buffer = ActiveSupport::SafeBuffer.new;"
end
def add_text(src, text)
return if text.empty?
src << "@output_buffer.safe_concat('" << escape_text(text) << "');"
end
BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/
def add_expr_literal(src, code)
if code =~ BLOCK_EXPR
src << "@output_buffer.safe_concat((" << $1 << ").to_s);"
else
src << '@output_buffer << ((' << code << ').to_s);'
end
end
def add_expr_escaped(src, code)
src << '@output_buffer << ' << escaped_expr(code) << ';'
end
def add_postamble(src)
src << '@output_buffer.to_s'
end
end
end
Erubis::Helpers::RailsHelper.engine_class = RailsXss::Erubis
Erubis::Helpers::RailsHelper.show_src = false
|
#
# Copyright (c) 2019 ISP RAS (http://www.ispras.ru)
# Ivannikov Institute for System Programming of the Russian Academy of Sciences
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import json
import os
from urllib.parse import unquote
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.generic.base import TemplateView, View
from django.views.generic.detail import SingleObjectMixin, DetailView
from django.views.generic.list import ListView
from bridge.vars import VIEW_TYPES, DECISION_STATUS, PRIORITY, DECISION_WEIGHT, JOB_ROLES, ERRORS, PRESET_JOB_TYPE
from bridge.utils import BridgeException
from bridge.CustomViews import DataViewMixin, StreamingResponseView
from tools.profiling import LoggedCallMixin
from users.models import User
from jobs.models import Job, JobFile, UploadedJobArchive, PresetJob, FileSystem, UserRole
from service.models import Decision
from jobs.configuration import StartDecisionData
from jobs.Download import (
get_jobs_to_download, JobFileGenerator, DecisionConfGenerator, JobArchiveGenerator, JobsArchivesGen
)
from jobs.JobTableProperties import JobsTreeTable, PresetChildrenTree
from jobs.preset import get_preset_dir_list, preset_job_files_tree_json
from jobs.utils import (
months_choices, years_choices, is_preset_changed, get_roles_form_data, get_core_link,
get_unique_job_name, get_unique_decision_name, JobAccess, DecisionAccess, CompareFileSet, JSTreeConverter
)
from jobs.ViewJobData import ViewJobData
from reports.coverage import DecisionCoverageStatistics
from reports.utils import FilesForCompetitionArchive
from service.serializers import ProgressSerializerRO
class JobsTree(LoginRequiredMixin, LoggedCallMixin, DataViewMixin, TemplateView):
template_name = 'jobs/tree.html'
def get_context_data(self, **kwargs):
return {
'users': User.objects.all(),
'can_create': self.request.user.can_create_jobs,
'statuses': DECISION_STATUS[1:], 'weights': DECISION_WEIGHT,
'priorities': list(reversed(PRIORITY)),
'months': months_choices(), 'years': years_choices(),
'TableData': JobsTreeTable(self.get_view(VIEW_TYPES[1]))
}
class PresetJobPage(LoginRequiredMixin, LoggedCallMixin, DataViewMixin, DetailView):
template_name = 'jobs/presetJob.html'
model = PresetJob
def get_context_data(self, **kwargs):
context = super(PresetJobPage, self).get_context_data(**kwargs)
if self.object.type != PRESET_JOB_TYPE[1][0]:
raise Http404
context.update({
'can_create': self.request.user.can_create_jobs,
'parents': self.object.get_ancestors(),
'children': PresetChildrenTree(self.object).children,
'files': preset_job_files_tree_json(self.object)
})
return context
class CreateJobFormPage(LoginRequiredMixin, LoggedCallMixin, TemplateView):
template_name = 'jobs/jobForm.html'
def get_context_data(self, **kwargs):
if not self.request.user.can_create_jobs:
raise BridgeException(code=407)
preset_job = get_object_or_404(
PresetJob.objects.exclude(type=PRESET_JOB_TYPE[0][0]), pk=self.kwargs['preset_id']
)
return {
'title': _('Job Creating'), 'job_roles': JOB_ROLES, 'cancel_url': reverse('jobs:tree'),
'confirm': {'title': _('Create'), 'url': reverse('jobs:api-create-job'), 'method': 'POST'},
'initial': {
'name': get_unique_job_name(preset_job),
'preset_dirs': get_preset_dir_list(preset_job),
'roles': json.dumps(get_roles_form_data(), ensure_ascii=False),
}
}
class EditJobFormPage(LoginRequiredMixin, LoggedCallMixin, DetailView):
model = Job
template_name = 'jobs/jobForm.html'
def get_context_data(self, **kwargs):
if not JobAccess(self.request.user, self.object).can_edit:
raise BridgeException(code=400)
return {
'title': _('Job Editing'), 'job_roles': JOB_ROLES, 'cancel_url': reverse('jobs:job', args=[self.object.id]),
'confirm': {
'title': _('Save'), 'url': reverse('jobs:api-update-job', args=[self.object.id]), 'method': 'PUT'
},
'initial': {
'name': self.object.name,
'preset_dirs': get_preset_dir_list(self.object.preset),
'roles': json.dumps(get_roles_form_data(self.object), ensure_ascii=False),
}
}
class JobPage(LoginRequiredMixin, LoggedCallMixin, DataViewMixin, DetailView):
model = Job
template_name = 'jobs/jobPage.html'
def get_queryset(self):
queryset = super(JobPage, self).get_queryset()
return queryset.select_related('author')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Check view access
context['job_access'] = JobAccess(self.request.user, self.object)
if not context['job_access'].can_view:
raise PermissionDenied(ERRORS[400])
context['parents'] = self.object.preset.get_ancestors(include_self=True).only('id', 'name', 'type')
context['user_roles'] = UserRole.objects.filter(job=self.object).select_related('user')\
.order_by('user__first_name', 'user__last_name', 'user__username')
context['preset_changed'] = is_preset_changed(self.object)
context['decisions'] = Decision.objects.filter(job=self.object).exclude(status=DECISION_STATUS[0][0])\
.select_related('configuration').order_by('-start_date')
return context
class DecisionFormPage(LoginRequiredMixin, LoggedCallMixin, DetailView):
template_name = 'jobs/decisionCreateForm.html'
model = Job
pk_url_kwarg = 'job_id'
def get_context_data(self, **kwargs):
if not JobAccess(self.request.user, self.object).can_decide:
raise BridgeException(_("You don't have an access to create job version"))
context = super(DecisionFormPage, self).get_context_data(**kwargs)
preset_job = self.object.preset.get_ancestors(include_self=True).filter(type=PRESET_JOB_TYPE[1][0]).first()
other_decisions = Decision.objects.filter(job=self.object).order_by('id')\
.exclude(status=DECISION_STATUS[0][0]).only('id', 'title', 'start_date')
context.update({
'job': self.object,
'unique_name': get_unique_decision_name(self.object),
'cancel_url': reverse('jobs:job', args=[self.object.id]),
'files_data': preset_job_files_tree_json(preset_job),
'current_conf': settings.DEF_KLEVER_CORE_MODE,
'start_data': StartDecisionData(self.request.user),
'other_decisions': other_decisions
})
return context
class DecisionCopyFormPage(LoginRequiredMixin, LoggedCallMixin, DetailView):
template_name = 'jobs/decisionCreateForm.html'
def get_queryset(self):
return Decision.objects.select_related('job')
def get_context_data(self, **kwargs):
if not JobAccess(self.request.user, self.object.job).can_decide:
raise BridgeException(_("You don't have an access to create job version"))
context = super(DecisionCopyFormPage, self).get_context_data(**kwargs)
decision_files = json.dumps(JSTreeConverter().make_tree(
list(FileSystem.objects.filter(decision=self.object).values_list('name', 'file__hash_sum'))
), ensure_ascii=False)
other_decisions = Decision.objects.filter(job=self.object.job).order_by('id')\
.exclude(status=DECISION_STATUS[0][0]).only('id', 'title', 'start_date')
context.update({
'job': self.object.job,
'unique_name': get_unique_decision_name(self.object.job),
'base_decision': self.object,
'cancel_url': reverse('jobs:decision', args=[self.object.id]),
'files_data': decision_files,
'start_data': StartDecisionData(self.request.user, base_decision=self.object),
'other_decisions': other_decisions
})
return context
class DecisionRestartPage(LoginRequiredMixin, LoggedCallMixin, DetailView):
template_name = 'jobs/restartDecision.html'
def get_queryset(self):
return Decision.objects.select_related('job')
def get_context_data(self, **kwargs):
if not DecisionAccess(self.request.user, self.object).can_restart:
raise BridgeException(_("You don't have an access to restart this decision"))
context = super(DecisionRestartPage, self).get_context_data(**kwargs)
other_decisions = Decision.objects.filter(job=self.object.job).order_by('id') \
.exclude(status=DECISION_STATUS[0][0]).only('id', 'title', 'start_date')
context.update({
'start_data': StartDecisionData(self.request.user, base_decision=self.object),
'other_decisions': other_decisions
})
return context
class DecisionPage(LoginRequiredMixin, LoggedCallMixin, DataViewMixin, DetailView):
model = Decision
template_name = 'jobs/viewDecision/main.html'
def get_queryset(self):
queryset = super(DecisionPage, self).get_queryset()
return queryset.select_related('job', 'job__author', 'operator', 'scheduler')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Decision access
context['access'] = DecisionAccess(self.request.user, self.object)
if not context['access'].can_view:
raise PermissionDenied(_("You don't have an access to this decision"))
# Decision files
context['files'] = json.dumps(JSTreeConverter().make_tree(
list(FileSystem.objects.filter(decision=self.object).values_list('name', 'file__hash_sum'))
), ensure_ascii=False)
# Other job decisions
context['other_decisions'] = Decision.objects.filter(job=self.object.job)\
.exclude(id=self.object.id).exclude(status=DECISION_STATUS[0][0])\
.select_related('configuration').order_by('-start_date')
# Decision progress and core report link
context['progress'] = ProgressSerializerRO(instance=self.object, context={'request': self.request}).data
context['core_link'] = get_core_link(self.object)
# Decision coverages
context['Coverage'] = DecisionCoverageStatistics(self.object)
context['parents'] = self.object.job.preset.get_ancestors(include_self=True)
# Verification results
context['reportdata'] = ViewJobData(self.request.user, self.get_view(VIEW_TYPES[2]), self.object)
return context
class LatestDecisionPage(View):
def get(self, request, job_id):
decision = Decision.objects.filter(job_id=job_id).order_by('-start_date').only('id').first()
if not decision:
raise Http404
return HttpResponseRedirect(reverse('jobs:decision', args=[decision.id]))
class DecisionsFilesComparison(LoginRequiredMixin, LoggedCallMixin, TemplateView):
template_name = 'jobs/comparison.html'
def get_context_data(self, **kwargs):
try:
decision1 = Decision.objects.select_related('job').get(id=self.kwargs['decision1_id'])
decision2 = Decision.objects.select_related('job').get(id=self.kwargs['decision2_id'])
except Job.DoesNotExist:
raise BridgeException(code=405)
if not DecisionAccess(self.request.user, decision1).can_view or \
not DecisionAccess(self.request.user, decision2).can_view:
raise BridgeException(code=401)
return {'decision1': decision1, 'decision2': decision2, 'data': CompareFileSet(decision1, decision2).data}
class DownloadJobFileView(LoginRequiredMixin, LoggedCallMixin, SingleObjectMixin, StreamingResponseView):
model = JobFile
slug_url_kwarg = 'hash_sum'
slug_field = 'hash_sum'
def get_filename(self):
return unquote(self.request.GET.get('name', 'filename'))
def get_generator(self):
return JobFileGenerator(self.get_object())
class DownloadConfigurationView(LoginRequiredMixin, LoggedCallMixin, SingleObjectMixin, StreamingResponseView):
def get_queryset(self):
return Decision.objects.select_related('configuration')
def get_generator(self):
instance = self.get_object()
if not JobAccess(self.request.user, instance.job).can_view:
raise BridgeException(code=400)
return DecisionConfGenerator(instance)
class JobsUploadingStatus(LoginRequiredMixin, LoggedCallMixin, ListView):
template_name = 'jobs/UploadingStatus.html'
def get_queryset(self):
return UploadedJobArchive.objects.filter(author=self.request.user).select_related('job').order_by('-start_date')
class DownloadFilesForCompetition(LoginRequiredMixin, LoggedCallMixin, SingleObjectMixin, StreamingResponseView):
model = Decision
def get_generator(self):
decision = self.get_object()
if not DecisionAccess(self.request.user, decision).can_download_verifier_files:
raise BridgeException(code=400)
if 'filters' not in self.request.GET:
raise BridgeException()
return FilesForCompetitionArchive(decision, json.loads(self.request.GET['filters']))
class DecisionProgress(LoginRequiredMixin, LoggedCallMixin, DetailView):
model = Decision
template_name = 'jobs/viewDecision/progress.html'
def get_context_data(self, **kwargs):
context = super(DecisionProgress, self).get_context_data(**kwargs)
# Decision progress and core report link
context['decision'] = self.object
context['progress'] = ProgressSerializerRO(instance=self.object, context={'request': self.request}).data
context['core_link'] = get_core_link(self.object)
return context
class DecisionResults(LoginRequiredMixin, LoggedCallMixin, DataViewMixin, DetailView):
model = Decision
template_name = 'jobs/DecisionResults.html'
def get_context_data(self, **kwargs):
return {'reportdata': ViewJobData(self.request.user, self.get_view(VIEW_TYPES[2]), self.object)}
class DownloadJobView(LoginRequiredMixin, LoggedCallMixin, SingleObjectMixin, StreamingResponseView):
model = Job
def get_generator(self):
instance = self.get_object()
decisions_ids = self.request.GET.getlist('decision')
if decisions_ids:
for decision in Decision.objects.filter(job=instance, id__in=decisions_ids).select_related('job'):
if not DecisionAccess(self.request.user, decision).can_download:
raise BridgeException(code=408, back=reverse('jobs:job', args=[instance.id]))
return JobArchiveGenerator(instance, decisions_ids)
if not JobAccess(self.request.user, instance).can_download:
raise BridgeException(code=400, back=reverse('jobs:job', args=[instance.id]))
return JobArchiveGenerator(instance)
class DownloadJobsListView(LoginRequiredMixin, LoggedCallMixin, StreamingResponseView):
def get_generator(self):
jobs_to_download = get_jobs_to_download(
self.request.user,
json.loads(unquote(self.request.GET['jobs'])),
json.loads(unquote(self.request.GET['decisions']))
)
return JobsArchivesGen(jobs_to_download)
|
<reponame>ibm-silvergate/nodejs-twitter-crawler
/**
* Copyright 2015-2016 IBM Corp. 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.
*/
'use strict';
const _ = require('underscore'),
isNaN = _.isNaN,
isString = _.isString,
isArray = _.isArray,
isObject = _.isObject,
extend = _.extendOwn,
keys = _.keys,
isUndefined = _.isUndefined;
module.exports = class {
constructor(credentials) {
this._credentials = this.sanitize(credentials);
}
isEnabled(c) {
return isUndefined(c.enabled) || c.enabled;
}
enabled(credentials) {
return credentials.filter(this.isEnabled);
}
all() {
return this.enabled(this._credentials);
}
validType(credentials) {
return isArray(credentials) || isObject(credentials);
}
validateCredential(credential, i) {
const fields = {'consumer_key': false, 'consumer_secret': false, 'access_token_key': true, 'access_token_secret': true};
keys(fields).forEach((field) => {
if (credential[field]) {
if (!isString(credential[field])) {
throw new Error(`Field '${field}' on credential nº ${i} must be a string`);
}
} else {
if (fields[field]) {
throw new Error(`Missing field '${field}' on credential nº ${i}`);
}
}
});
}
validateCredentials(credentials) {
credentials.forEach(this.validateCredential);
}
hasEnabledCredentials(credentials) {
return this.enabled(credentials).length > 0;
}
sanitize(credentials) {
if (isUndefined(credentials))
throw new Error('You must provide credentials');
if (!this.validType(credentials))
throw new Error('You must provide a single set of credentials or an array of credentials');
const _credentials = isArray(credentials) ? credentials : [credentials];
this.validateCredentials(_credentials);
if (!this.hasEnabledCredentials(_credentials)) {
throw new Error('All your credentials are marked as disabled');
}
return _credentials;
}
};
|
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# shellcheck source=scripts/in_container/_in_container_script_init.sh
. "$( dirname "${BASH_SOURCE[0]}" )/_in_container_script_init.sh"
setup_provider_packages
echo
echo "Testing if all classes in import packages can be imported"
echo
if [[ ${INSTALL_AIRFLOW_VERSION=""} == "" ]]; then
echo
echo "${COLOR_RED_ERROR} You have to specify airflow version to install - might be from PyPI or local wheels ${COLOR_RESET}"
echo
exit 1
fi
if (($# < 1)); then
echo
echo "${COLOR_RED_ERROR} Missing installation type (whl/tar.gz) as first argument ${COLOR_RESET}"
echo
exit 2
fi
INSTALL_TYPE=${1}
readonly INSTALL_TYPE
if [[ ${INSTALL_TYPE} != "whl" && ${INSTALL_TYPE} != "tar.gz" ]]; then
echo
echo "${COLOR_RED_ERROR} Wrong install type ${INSTALL_TYPE}. Should be 'whl' or 'tar.gz' ${COLOR_RESET}"
echo
exit 3
fi
if [[ ${INSTALL_AIRFLOW_VERSION} == "wheel" ]]; then
echo
echo "Installing the airflow prepared from wheels"
echo
uninstall_airflow
install_airflow_from_wheel
else
uninstall_airflow
install_released_airflow_version "${INSTALL_AIRFLOW_VERSION}" "[all]"
fi
install_remaining_dependencies
if [[ ${INSTALL_TYPE} == "whl" ]]; then
install_all_provider_packages_from_wheels
elif [[ ${INSTALL_TYPE} == "tar.gz" ]]; then
install_all_provider_packages_from_tar_gz_files
else
echo
echo "${COLOR_RED_ERROR} Wrong package type ${1}. Should be whl or tar.gz ${COLOR_RESET}"
echo
exit 1
fi
import_all_provider_classes
function discover_all_provider_packages() {
echo
echo Listing available providers via 'airflow providers list'
echo
airflow providers list
local expected_number_of_providers=60
local actual_number_of_providers
actual_number_of_providers=$(airflow providers list --output table | grep -c apache-airflow-providers | xargs)
if [[ ${actual_number_of_providers} != "${expected_number_of_providers}" ]]; then
echo
echo "${COLOR_RED_ERROR} Number of providers installed is wrong ${COLOR_RESET}"
echo "Expected number was '${expected_number_of_providers}' and got '${actual_number_of_providers}'"
echo
echo "Either increase the number of providers if you added one or diagnose and fix the problem."
echo
fi
}
function discover_all_hooks() {
echo
echo Listing available hooks via 'airflow providers hooks'
echo
airflow providers hooks
local expected_number_of_hooks=33
local actual_number_of_hooks
actual_number_of_hooks=$(airflow providers hooks --output table | grep -c conn_id | xargs)
if [[ ${actual_number_of_hooks} != "${expected_number_of_hooks}" ]]; then
echo
echo "${COLOR_RED_ERROR} Number of hooks registered is wrong ${COLOR_RESET}"
echo "Expected number was '${expected_number_of_hooks}' and got '${actual_number_of_hooks}'"
echo
echo "Either increase the number of hooks if you added one or diagnose and fix the problem."
echo
fi
}
function discover_all_extra_links() {
echo
echo Listing available extra links via 'airflow providers links'
echo
airflow providers links
local expected_number_of_extra_links=4
local actual_number_of_extra_links
actual_number_of_extra_links=$(airflow providers links --output table | grep -c ^airflow.providers | xargs)
if [[ ${actual_number_of_extra_links} != "${expected_number_of_extra_links}" ]]; then
echo
echo "${COLOR_RED_ERROR} Number of links registered is wrong ${COLOR_RESET}"
echo "Expected number was '${expected_number_of_extra_links}' and got '${actual_number_of_extra_links}'"
echo
echo "Either increase the number of links if you added one or diagnose and fix the problem."
echo
fi
}
if [[ ${BACKPORT_PACKAGES} != "true" ]]; then
discover_all_provider_packages
discover_all_hooks
discover_all_extra_links
fi
|
<filename>server/tests/integration/http/appointmentsRoutes-test.js
const assert = require("assert");
const httpTests = require("../../utils/httpTests");
const { administrator } = require("../../../src/common/roles");
const { sampleAppointment, sampleUpdateAppointment } = require("../../data/samples");
const { Appointment } = require("../../../src/common/model");
const roles = require("../../../src/common/roles");
const { referrers } = require("../../../src/common/model/constants/referrers");
httpTests(__filename, ({ startServer }) => {
it("Vérifie qu'on peut consulter la liste des rdvs en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser, components } = await startServer();
// Add item
await components.appointments.createAppointment({
candidat_id: sampleAppointment.candidat_id,
etablissement_id: sampleAppointment.etablissement_id,
formation_id: sampleAppointment.formation_id,
motivations: sampleAppointment.motivations,
referrer: sampleAppointment.referrer,
});
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const response = await httpClient.get("/api/appointment/appointments", { headers: bearerToken });
// Check API response
assert.deepStrictEqual(response.status, 200);
assert.ok(response.data.appointments);
assert.deepStrictEqual(response.data.appointments.length, 1);
assert.ok(response.data.pagination);
});
it("Vérifie qu'on peut consulter la liste en détail des rdvs en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser, components } = await startServer();
const candidat = await components.users.createUser("Marc", "N/A", {
firstname: "firstname",
lastname: "password",
phone: "",
email: "<EMAIL>",
role: roles.candidat,
});
// Add item
await components.appointments.createAppointment({
id_rco_formation: sampleAppointment.id_rco_formation,
candidat_id: candidat._id,
etablissement_id: sampleAppointment.etablissement_id,
formation_id: sampleAppointment.formation_id,
motivations: sampleAppointment.motivations,
referrer: referrers.LBA.code,
});
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const response = await httpClient.get("/api/appointment/appointments/details", { headers: bearerToken });
// Check API response
assert.deepStrictEqual(response.status, 200);
assert.ok(response.data.appointments);
assert.ok(response.data.pagination);
});
it("Vérifie qu'on peut décompter les rdvs en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser, components } = await startServer();
// Add item
await components.appointments.createAppointment({
candidat_id: sampleAppointment.candidat_id,
etablissement_id: sampleAppointment.etablissement_id,
formation_id: sampleAppointment.formation_id,
motivations: sampleAppointment.motivations,
referrer: sampleAppointment.referrer,
});
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const response = await httpClient.get("/api/appointment/appointments/count", { headers: bearerToken });
// Check API response
assert.deepStrictEqual(response.status, 200);
assert.deepStrictEqual(response.data, { total: 1 });
});
it("Vérifie qu'on peut ajouter un rdv en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser } = await startServer();
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const response = await httpClient.post("/api/appointment/", sampleAppointment, { headers: bearerToken });
// Check API Response
assert.deepStrictEqual(response.status, 200);
assert.ok(response.data._id);
assert.deepStrictEqual(response.data.candidat_id, sampleAppointment.candidat_id);
assert.deepStrictEqual(response.data.etablissement_id, sampleAppointment.etablissement_id);
assert.deepStrictEqual(response.data.formation_id, sampleAppointment.formation_id);
assert.deepStrictEqual(response.data.motivations, sampleAppointment.motivations);
assert.deepStrictEqual(response.data.referrer, sampleAppointment.referrer);
// Check query db
const found = await Appointment.findById(response.data._id);
assert.deepStrictEqual(found.candidat_id, sampleAppointment.candidat_id);
assert.deepStrictEqual(found.etablissement_id, sampleAppointment.etablissement_id);
assert.deepStrictEqual(found.formation_id, sampleAppointment.formation_id);
assert.deepStrictEqual(found.motivations, sampleAppointment.motivations);
assert.deepStrictEqual(found.referrer, sampleAppointment.referrer);
});
it("Vérifie qu'on peut récupérer un rdv avec une requete en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser, components } = await startServer();
// Add item
await components.appointments.createAppointment({
candidat_id: sampleAppointment.candidat_id,
etablissement_id: sampleAppointment.etablissement_id,
formation_id: sampleAppointment.formation_id,
motivations: sampleAppointment.motivations,
referrer: sampleAppointment.referrer,
});
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const response = await httpClient.get(
"/api/appointment/",
{ headers: bearerToken },
{ data: { etablissement_id: sampleAppointment.etablissement_id } }
);
// Check API Response
assert.deepStrictEqual(response.status, 200);
assert.ok(response.data._id);
assert.deepStrictEqual(response.data.candidat_id, sampleAppointment.candidat_id);
assert.deepStrictEqual(response.data.etablissement_id, sampleAppointment.etablissement_id);
assert.deepStrictEqual(response.data.formation_id, sampleAppointment.formation_id);
assert.deepStrictEqual(response.data.motivations, sampleAppointment.motivations);
assert.deepStrictEqual(response.data.referrer, sampleAppointment.referrer);
});
it("Vérifie qu'on peut récupérer un rdv par son id en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser } = await startServer();
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const addedResponse = await httpClient.post("/api/appointment/", sampleAppointment, { headers: bearerToken });
// Check API Response
assert.deepStrictEqual(addedResponse.status, 200);
assert.ok(addedResponse.data._id);
assert.deepStrictEqual(addedResponse.data.candidat_id, sampleAppointment.candidat_id);
assert.deepStrictEqual(addedResponse.data.etablissement_id, sampleAppointment.etablissement_id);
assert.deepStrictEqual(addedResponse.data.formation_id, sampleAppointment.formation_id);
assert.deepStrictEqual(addedResponse.data.motivations, sampleAppointment.motivations);
assert.deepStrictEqual(addedResponse.data.referrer, sampleAppointment.referrer);
// Check query db
const getByIdResponse = await httpClient.get(`/api/appointment/${addedResponse.data._id}`, {
headers: bearerToken,
});
assert.deepStrictEqual(getByIdResponse.status, 200);
assert.deepStrictEqual(getByIdResponse.data.candidat_id, sampleAppointment.candidat_id);
assert.deepStrictEqual(getByIdResponse.data.etablissement_id, sampleAppointment.etablissement_id);
assert.deepStrictEqual(getByIdResponse.data.formation_id, sampleAppointment.formation_id);
assert.deepStrictEqual(getByIdResponse.data.motivations, sampleAppointment.motivations);
assert.deepStrictEqual(getByIdResponse.data.referrer, sampleAppointment.referrer);
});
it("Vérifie qu'on peut mettre à jour un rdv par son id en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser } = await startServer();
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const addedResponse = await httpClient.post("/api/appointment/", sampleAppointment, { headers: bearerToken });
// Check API Response
assert.deepStrictEqual(addedResponse.status, 200);
assert.ok(addedResponse.data._id);
assert.deepStrictEqual(addedResponse.data.candidat_id, sampleAppointment.candidat_id);
assert.deepStrictEqual(addedResponse.data.etablissement_id, sampleAppointment.etablissement_id);
assert.deepStrictEqual(addedResponse.data.formation_id, sampleAppointment.formation_id);
assert.deepStrictEqual(addedResponse.data.motivations, sampleAppointment.motivations);
assert.deepStrictEqual(addedResponse.data.referrer, sampleAppointment.referrer);
// Check query db
const updateResponse = await httpClient.put(`/api/appointment/${addedResponse.data._id}`, sampleUpdateAppointment, {
headers: bearerToken,
});
assert.deepStrictEqual(updateResponse.status, 200);
assert.deepStrictEqual(updateResponse.data.candidat_id, sampleUpdateAppointment.candidat_id);
assert.deepStrictEqual(updateResponse.data.etablissement_id, sampleUpdateAppointment.etablissement_id);
assert.deepStrictEqual(updateResponse.data.formation_id, sampleUpdateAppointment.formation_id);
assert.deepStrictEqual(updateResponse.data.motivations, sampleUpdateAppointment.motivations);
assert.deepStrictEqual(updateResponse.data.referrer, sampleUpdateAppointment.referrer);
});
it("Vérifie qu'on peut supprimer un parametre de widget par son id en tant qu'admin via la Route", async () => {
const { httpClient, createAndLogUser } = await startServer();
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const addedResponse = await httpClient.post("/api/appointment/", sampleAppointment, { headers: bearerToken });
// Check API Response
assert.deepStrictEqual(addedResponse.status, 200);
assert.ok(addedResponse.data._id);
assert.deepStrictEqual(addedResponse.data.candidat_id, sampleAppointment.candidat_id);
assert.deepStrictEqual(addedResponse.data.etablissement_id, sampleAppointment.etablissement_id);
assert.deepStrictEqual(addedResponse.data.formation_id, sampleAppointment.formation_id);
assert.deepStrictEqual(addedResponse.data.motivations, sampleAppointment.motivations);
assert.deepStrictEqual(addedResponse.data.referrer, sampleAppointment.referrer);
// Check query db
const deleteResponse = await httpClient.delete(`/api/appointment/${addedResponse.data._id}`, {
headers: bearerToken,
});
assert.deepStrictEqual(deleteResponse.status, 200);
// Check deletion
const found = await Appointment.findById(addedResponse.data._id);
assert.strictEqual(found, null);
});
it("Vérifie qu'on peut exporter les rendez-vous en csv", async () => {
const { httpClient, createAndLogUser, components } = await startServer();
const candidat = await components.users.createUser("Jean", "N/A", {
firstname: "firstname",
lastname: "password",
phone: "",
email: "<EMAIL>",
role: roles.candidat,
});
await components.appointments.createAppointment({
id_rco_formation: sampleAppointment.id_rco_formation,
candidat_id: candidat._id,
etablissement_id: sampleAppointment.etablissement_id,
formation_id: sampleAppointment.formation_id,
motivations: sampleAppointment.motivations,
referrer: referrers.LBA.code,
});
const bearerToken = await createAndLogUser("userAdmin", "password", { role: administrator });
const response = await httpClient.get("/api/appointment/appointments/details/export", { headers: bearerToken });
// Check API response
assert.deepStrictEqual(response.status, 200);
});
});
|
import { Field, Int } from 'some-library'; // Import necessary decorators and types
export class ItemPaginationInput extends PaginatedInput {
getPaginatedItems<T>(items: T[]): T[] {
const { take, skip } = this;
if (take <= 0) {
return items.slice(skip);
} else {
return items.slice(skip, skip + take);
}
}
} |
# generated from colcon_bash/shell/template/package.bash.em
# This script extends the environment for this package.
# a bash script is able to determine its own path if necessary
if [ -z "$COLCON_CURRENT_PREFIX" ]; then
# the prefix is two levels up from the package specific share directory
_colcon_package_bash_COLCON_CURRENT_PREFIX="$(builtin cd "`dirname "${BASH_SOURCE[0]}"`/../.." > /dev/null && pwd)"
else
_colcon_package_bash_COLCON_CURRENT_PREFIX="$COLCON_CURRENT_PREFIX"
fi
# function to source another script with conditional trace output
# first argument: the path of the script
# additional arguments: arguments to the script
_colcon_package_bash_source_script() {
if [ -f "$1" ]; then
if [ -n "$COLCON_TRACE" ]; then
echo ". \"$1\""
fi
. "$@"
else
echo "not found: \"$1\"" 1>&2
fi
}
# source sh script of this package
_colcon_package_bash_source_script "$_colcon_package_bash_COLCON_CURRENT_PREFIX/share/deepracer_simulation_environment/package.sh"
unset _colcon_package_bash_source_script
unset _colcon_package_bash_COLCON_CURRENT_PREFIX
|
<gh_stars>0
package ping
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Ping shows that our service is up
func Ping(c *gin.Context) {
c.String(http.StatusOK, "pong")
}
|
#!/bin/bash
# spoke1
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke1/managedclusterviews/cgu-default-subscription-cluster-logging-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"cluster-logging","namespace":"openshift-logging"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-aaaa1","namespace":"openshift-logging","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke1/managedclusterviews/cgu-default-subscription-local-storage-operator-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"openshift-local-storage","namespace":"openshift-local-storage"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-aaaa2","namespace":"openshift-local-storage","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke1/managedclusterviews/cgu-default-subscription-performance-addon-operator-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"performance-addon-operator","namespace":"openshift-performance-addon-operator"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-aaaa3","namespace":"openshift-performance-addon-operator","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke1/managedclusterviews/cgu-default-subscription-ptp-operator-subscription-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"ptp-operator-subscription","namespace":"openshift-ptp"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-aaaa4","namespace":"openshift-ptp","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke1/managedclusterviews/cgu-default-subscription-sriov-network-operator-subscription-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"sriov-network-operator-subscription","namespace":"openshift-sriov-network-operator"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-aaaa5","namespace":"openshift-sriov-network-operator","resourceVersion":"1528358"}}}}}'
# spoke2
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke2/managedclusterviews/cgu-default-subscription-cluster-logging-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"cluster-logging","namespace":"openshift-logging"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-bbbb1","namespace":"openshift-logging","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke2/managedclusterviews/cgu-default-subscription-local-storage-operator-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"openshift-local-storage","namespace":"openshift-local-storage"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-bbbb2","namespace":"openshift-local-storage","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke2/managedclusterviews/cgu-default-subscription-performance-addon-operator-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"performance-addon-operator","namespace":"openshift-performance-addon-operator"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-bbbb3","namespace":"openshift-performance-addon-operator","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke2/managedclusterviews/cgu-default-subscription-ptp-operator-subscription-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"ptp-operator-subscription","namespace":"openshift-ptp"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-bbbb4","namespace":"openshift-ptp","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke2/managedclusterviews/cgu-default-subscription-sriov-network-operator-subscription-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"sriov-network-operator-subscription","namespace":"openshift-sriov-network-operator"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-bbbb5","namespace":"openshift-sriov-network-operator","resourceVersion":"1528358"}}}}}'
# spoke5
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke5/managedclusterviews/cgu-default-subscription-cluster-logging-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"cluster-logging","namespace":"openshift-logging"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-cccc1","namespace":"openshift-logging","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke5/managedclusterviews/cgu-default-subscription-local-storage-operator-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"openshift-local-storage","namespace":"openshift-local-storage"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-cccc2","namespace":"openshift-local-storage","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke5/managedclusterviews/cgu-default-subscription-performance-addon-operator-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"performance-addon-operator","namespace":"openshift-performance-addon-operator"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-cccc3","namespace":"openshift-performance-addon-operator","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke5/managedclusterviews/cgu-default-subscription-ptp-operator-subscription-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"ptp-operator-subscription","namespace":"openshift-ptp"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-cccc4","namespace":"openshift-ptp","resourceVersion":"1528358"}}}}}'
curl -k -s -X PATCH -H "Accept: application/json, */*" \
-H "Content-Type: application/merge-patch+json" \
http://localhost:8001/apis/view.open-cluster-management.io/v1beta1/namespaces/spoke5/managedclusterviews/cgu-default-subscription-sriov-network-operator-subscription-kuttl/status \
--data '{"status":{"conditions":[{"lastTransitionTime":"2022-01-28T17:57:00Z","message":"Watching resources successfully", "reason":"GetResourceProcessing","status":"True","type":"Processing"}],"result":{"apiVersion":"apiVersion:operators.coreos.com\/v1alpha1","kind":"Subscription","metadata":{"name":"sriov-network-operator-subscription","namespace":"openshift-sriov-network-operator"},"status":{"state":"UpgradePending","installPlanRef":{"apiVersion":"operators.coreos.com\/v1alpha1","kind":"InstallPlan","name":"install-cccc5","namespace":"openshift-sriov-network-operator","resourceVersion":"1528358"}}}}}'
|
fn layout(
&mut self,
ctx: &mut LayoutCtx,
bc: &BoxConstraints,
data: &String,
) {
// Your implementation of the layout algorithm goes here
// Calculate the layout based on the provided constraints and text content
// Update the internal state of the layout structure accordingly
// Ensure that the layout respects the provided constraints and handles the text content optimally
} |
readonly LDAP_DOMAIN=thesimpsons.com
readonly LDAP_ORGANISATION="The Simpsons"
readonly LDAP_BINDDN="cn=admin,dc=thesimpsons,dc=com"
readonly LDAP_SECRET=password
|
#include <bits/stdc++.h>
using namespace std;
// Function to remove all occurrences of a particular element
// from the array
void remove_element(int arr[], int n, int element)
{
int i, j, k;
for (i = 0; i < n; i++) {
if (arr[i] == element) {
for (j = i; j < n - 1; j++) {
arr[j] = arr[j + 1];
}
n--;
i--;
}
}
cout << "New array: ";
for (k = 0; k < n; k++) {
cout << arr[k] << " ";
}
}
int main()
{
int nums[] = { 2, 3, 4, 5, 3, 3, 3, 6 };
int n = sizeof(nums) / sizeof(nums[0]);
int element = 3;
remove_element(nums, n, element);
return 0;
} |
import { ready } from './ready.js'
ready(async () => {
const menus = document.querySelectorAll('.profile-menu, .more-menu')
const page = document.querySelector('body')
for (const button of document.querySelectorAll(
'.profile-button, .close-button, .more-button-small-screen'
)) {
button.addEventListener('click', event => {
event.preventDefault()
page.classList.toggle('no-scroll-small-screen')
for (const menu of menus) {
menu.classList.toggle('menu-open')
}
})
}
})
|
#!/bin/sh
IMAGE_NAME=centr
CONTAINER_NAME=centr_instance
RUNNING=$(docker inspect --format="{{ .State.Running }}" $CONTAINER_NAME)
# container don't exist
if [ $? -eq 1 ]; then
echo "container already killed"
else
if [ "$RUNNING" == "true" ]; then
docker stop $CONTAINER_NAME
fi
docker rm -f $CONTAINER_NAME
fi
# clean all
if [ "$1" == "all" ]; then
docker rmi IMAGE_NAME
fi
|
from typing import List
def shortestToChar(S: str, C: str) -> List[int]:
n = len(S)
ret = [0] * n
prev = float('-inf')
# Forward pass to calculate distances to the right
for i in range(n):
if S[i] == C:
prev = i
ret[i] = i - prev
# Backward pass to update distances to the left
prev = float('inf')
for i in range(n - 1, -1, -1):
if S[i] == C:
prev = i
ret[i] = min(ret[i], prev - i)
return ret |
#!/bin/bash
##########################################################################
#Aqueduct - Compliance Remediation Content
#Copyright (C) 2011,2012
# Vincent C. Passaro (vincent.passaro@gmail.com)
# Shannon Mitchell (shannon.mitchell@fusiontechnology-llc.com)
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor,
#Boston, MA 02110-1301, USA.
##########################################################################
##################### Fusion Technology LLC #############################
# By Shannon Mitchell #
# Fusion Technology LLC #
# Shannon[.]Mitchell[@]fusiontechnology-llc[.]com #
# www.fusiontechnology-llc.com #
##################### Fusion Technology LLC #############################
#
# _____________________________________________________________________
# | Version | Change Information | Author | Date |
# |__________|_______________________|____________________|____________|
# | 1.0 | Initial Script | Shannon Mitchell | 15-jul-2012|
# | | Creation | | |
# |__________|_______________________|____________________|____________|
#
#######################DISA INFORMATION##################################
# Group ID (Vulid): V-22363
# Group Title: GEN001901
# Rule ID: SV-37305r1_rule
# Severity: medium
# Rule Version (STIG-ID): GEN001901
# Rule Title: Local initialization files' library search paths must
# contain only absolute paths.
#
# Vulnerability Discussion: The library search path environment
# variable(s) contain a list of directories for the dynamic linker to
# search to find libraries. If this path includes the current working
# directory or other relative paths, libraries in these directories may be
# loaded instead of system libraries. This variable is formatted as a
# colon-separated list of directories. If there is an empty entry, such as
# a leading or trailing colon, or two consecutive colons, this is
# interpreted as the current working directory. Paths starting with a
# slash (/) are absolute paths.
#
# Responsibility: System Administrator
# IAControls: ECSC-1
#
# Check Content:
#
# Verify local initialization files have library search path containing
# only absolute paths.
# Procedure:
# cut -d: -f6 /etc/passwd |xargs -n1 -IDIR find DIR -name ".*" -type f
# -maxdepth 1 -exec grep -H LD_LIBRARY_PATH {} \;
# This variable is formatted as a colon-separated list of directories. If
# there is an empty entry, such as a leading or trailing colon, or two
# consecutive colons, this is a finding. If an entry begins with a
# character other than a slash (/) this is a relative path, this is a
# finding.
#
# Fix Text:
#
# Edit the local initialization file and remove the relative path entry
# from the library search path variable.
#######################DISA INFORMATION##################################
# Global Variables
PDI=GEN001901
# Start-Lockdown
# This is looking for the local init files such as the .bash_profile, .bashrc..
# and so on for the PATH variable excluding the .bash_history.
for HOMEDIR in `awk -F ':' '{print $6}' /etc/passwd | sort | uniq`
do
# find files beginning with a . within existing home directories
if [ -e $HOMEDIR ]
then
for INITFILE in `find $HOMEDIR -maxdepth 1 -type f -name "\.*" ! -name '.bash_history'`
do
## Check bash style settings
# Remove leading colons
egrep 'LD_LIBRARY_PATH=:' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e 's/LD_LIBRARY_PATH=:/LD_LIBRARY_PATH=/g' $INITFILE
fi
# remove trailing colons
egrep 'LD_LIBRARY_PATH=.*:\"*\s*$' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e 's/\(LD_LIBRARY_PATH=.*\):\(\"*\s*$\)/\1\2/g' $INITFILE
fi
# remove begin/end colons with no data
egrep 'LD_LIBRARY_PATH=.*::.*' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e '/LD_LIBRARY_PATH=/s/::/:/g' $INITFILE
fi
# remove anything that doesn't start with a $ or /
egrep 'LD_LIBRARY_PATH="' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
egrep 'LD_LIBRARY_PATH="[^$/]' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e '/LD_LIBRARY_PATH/s/="[^$/][^:]*:*/="/g' $INITFILE
fi
else
# remove anything that doesn't start with a $ or /
egrep 'LD_LIBRARY_PATH=[^$/]' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e '/LD_LIBRARY_PATH/s/=[^$/][^:]*:*/=/g' $INITFILE
fi
fi
egrep 'LD_LIBRARY_PATH=.*:[^$/:][^:]*\s*' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e '/LD_LIBRARY_PATH=/s/:[^$/:][^:]*//g' $INITFILE
fi
## Check csh style settings
# Remove leading colons
egrep 'setenv LD_LIBRARY_PATH ":' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e 's/setenv LD_LIBRARY_PATH ":/setenv LD_LIBRARY_PATH "/g' $INITFILE
fi
# remove trailing colons
egrep 'setenv LD_LIBRARY_PATH ".*:"' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e 's/\(setenv LD_LIBRARY_PATH ".*\):\("\)/\1\2/g' $INITFILE
fi
# remove begin/end colons with no data
egrep 'setenv LD_LIBRARY_PATH ".*::.*' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e '/setenv LD_LIBRARY_PATH/s/::/:/g' $INITFILE
fi
# remove anything that doesn't start with a $ or /
egrep 'setenv LD_LIBRARY_PATH ".*:[^$/:][^:]*\s*' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e '/setenv LD_LIBRARY_PATH/s/:[^$/:][^:"]*//g' $INITFILE
fi
egrep 'setenv LD_LIBRARY_PATH "[^$/]' $INITFILE > /dev/null
if [ $? -eq 0 ]
then
sed -i -e '/setenv LD_LIBRARY_PATH/s/"[^$/][^:"]*:*/"/g' $INITFILE
fi
done
fi
done
|
<reponame>ucodkr/gopdf
package gopdf
import (
"fmt"
"io"
)
//OutlinesObj : outlines dictionary
type OutlinesObj struct { //impl IObj
getRoot func() *GoPdf
index int
first int
last int
count int
lastObj *OutlineObj
}
func (o *OutlinesObj) init(funcGetRoot func() *GoPdf) {
o.getRoot = funcGetRoot
o.first = -1
o.last = -1
}
func (o *OutlinesObj) getType() string {
return "Outlines"
}
func (o *OutlinesObj) write(w io.Writer, objID int) error {
content := "<<\n"
content += fmt.Sprintf("\t/Type /%s\n", o.getType())
content += fmt.Sprintf("\t/Count %d\n", o.count)
if o.first >= 0 {
content += fmt.Sprintf("\t/First %d 0 R\n", o.first)
}
if o.last >= 0 {
content += fmt.Sprintf("\t/Last %d 0 R\n", o.last)
}
content += ">>\n"
if _, err := io.WriteString(w, content); err != nil {
return err
}
return nil
}
func (o *OutlinesObj) SetIndexObjOutlines(index int) {
o.index = index
}
func (o *OutlinesObj) AddOutline(dest int, title string) {
oo := &OutlineObj{title: title, dest: dest, parent: o.index, prev: o.last, next: -1}
o.last = o.getRoot().addObj(oo) + 1
if o.first <= 0 {
o.first = o.last
}
if o.lastObj != nil {
o.lastObj.next = o.last
}
o.lastObj = oo
o.count++
}
// AddOutlinesWithPosition add outlines with position
func (o *OutlinesObj) AddOutlinesWithPosition(dest int, title string, y float64) *OutlineObj {
oo := &OutlineObj{title: title, dest: dest, parent: o.index, prev: o.last, next: -1, height: y}
o.last = o.getRoot().addObj(oo) + 1
if o.first <= 0 {
o.first = o.last
}
if o.lastObj != nil {
o.lastObj.next = o.last
}
o.lastObj = oo
o.count++
oo.index = o.last
return oo
}
func (o *OutlinesObj) Count() int {
return o.count
}
// OutlineObj include attribute of outline
type OutlineObj struct { //impl IObj
title string
index int
dest int
parent int
prev int
next int
first int
last int
height float64
}
func (o *OutlineObj) init(funcGetRoot func() *GoPdf) {
}
func (o *OutlineObj) SetFirst(first int) {
o.first = first
}
func (o *OutlineObj) SetLast(last int) {
o.last = last
}
func (o *OutlineObj) SetPrev(prev int) {
o.prev = prev
}
func (o *OutlineObj) SetNext(next int) {
o.next = next
}
func (o *OutlineObj) SetParent(parent int) {
o.parent = parent
}
func (o *OutlineObj) GetIndex() int {
return o.index
}
func (o *OutlineObj) getType() string {
return "Outline"
}
//func (o *OutlineObj) write(w io.Writer, objID int) error {
// io.WriteString(w, "<<\n")
// fmt.Fprintf(w, " /Parent %d 0 R\n", o.parent)
// if o.prev >= 0 {
// fmt.Fprintf(w, " /Prev %d 0 R\n", o.prev)
// }
// if o.next >= 0 {
// fmt.Fprintf(w, " /Next %d 0 R\n", o.next)
// }
// fmt.Fprintf(w, " /Dest [ %d 0 R /XYZ null null null ]\n", o.dest)
// fmt.Fprintf(w, " /Title <FEFF%s>\n", encodeUtf8(o.title))
// io.WriteString(w, ">>\n")
// return nil
//}
func (o *OutlineObj) write(w io.Writer, objID int) error {
io.WriteString(w, "<<\n")
fmt.Fprintf(w, " /Parent %d 0 R\n", o.parent)
if o.prev >= 0 {
fmt.Fprintf(w, " /Prev %d 0 R\n", o.prev)
}
if o.next >= 0 {
fmt.Fprintf(w, " /Next %d 0 R\n", o.next)
}
if o.first > 0 {
fmt.Fprintf(w, " /First %d 0 R\n", o.first)
}
if o.last > 0 {
fmt.Fprintf(w, " /Last %d 0 R\n", o.last)
}
fmt.Fprintf(w, " /Dest [ %d 0 R /XYZ 90 %f 0 ]\n", o.dest, o.height)
fmt.Fprintf(w, " /Title <FEFF%s>\n", encodeUtf8(o.title))
io.WriteString(w, ">>\n")
return nil
}
// OutlineNode is a node of outline
type OutlineNode struct {
Obj *OutlineObj
Children []*OutlineNode
}
// OutlineNodes are all nodes of outline
type OutlineNodes []*OutlineNode
// Parse parse outline nodes
func (objs OutlineNodes) Parse() {
for i, obj := range objs {
if i == 0 {
obj.Obj.SetPrev(-1)
} else {
obj.Obj.SetNext(objs[i-1].Obj.GetIndex())
}
if i == len(objs)-1 {
obj.Obj.SetNext(-1)
} else {
obj.Obj.SetNext(objs[i+1].Obj.GetIndex())
}
obj.Parse()
}
}
// Parse parse outline
func (obj OutlineNode) Parse() {
if obj.Children == nil || len(obj.Children) == 0 {
return
}
for i, children := range obj.Children {
if i == 0 {
obj.Obj.SetFirst(children.Obj.GetIndex())
children.Obj.SetPrev(-1)
}
if i == len(obj.Children)-1 {
obj.Obj.SetLast(children.Obj.GetIndex())
children.Obj.SetNext(-1)
}
if i != 0 {
children.Obj.SetPrev(obj.Children[i-1].Obj.GetIndex())
}
if i != len(obj.Children)-1 {
children.Obj.SetNext(obj.Children[i+1].Obj.GetIndex())
}
children.Obj.SetParent(obj.Obj.GetIndex())
children.Parse()
}
}
|
<reponame>m-nakagawa/sample<filename>jena-3.0.1/jena-sdb/src/main/java/org/apache/jena/sdb/sql/SDBConnection.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.sdb.sql;
import static java.sql.ResultSet.CONCUR_READ_ONLY;
import static java.sql.ResultSet.TYPE_FORWARD_ONLY;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.sql.DataSource;
import org.apache.jena.graph.TransactionHandler ;
import org.apache.jena.sdb.core.Generator ;
import org.apache.jena.sdb.core.Gensym ;
import org.apache.jena.sdb.core.SDBConstants ;
import org.apache.jena.sdb.graph.TransactionHandlerSDB ;
import org.apache.jena.shared.Command ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* An SDBConnection is the abstraction of the link between client
* application and the database.
* There can be many Store's per connection.
*/
public class SDBConnection
{
static private Logger log = LoggerFactory.getLogger(SDBConnection.class) ;
static private Generator gen = Gensym.create("connection-") ;
private Connection sqlConnection = null ;
TransactionHandler transactionHandler = null ;
String label = gen.next() ;
String jdbcURL = "unset" ;
// Defaults
public static boolean logSQLExceptions = true ;
public static boolean logSQLStatements = false ;
public static boolean logSQLQueries = false ;
private boolean thisLogSQLExceptions = logSQLExceptions ;
private boolean thisLogSQLStatements = logSQLStatements ;
private boolean thisLogSQLQueries = logSQLQueries ;
public SDBConnection(DataSource ds) throws SQLException
{
this(ds.getConnection()) ;
}
public SDBConnection(String url, String user, String password)
{
this(SDBConnectionFactory.createSqlConnection(url, user, password)) ;
setLabel(url) ;
setJdbcURL(url) ;
}
public SDBConnection(Connection jdbcConnection)
{
this(jdbcConnection, null) ;
}
public SDBConnection(Connection jdbcConnection, String url)
{
sqlConnection = jdbcConnection ;
transactionHandler = new TransactionHandlerSDB(this) ;
if ( url != null ) setJdbcURL(url) ;
}
public static SDBConnection none()
{
return new SDBConnection(JDBC.jdbcNone, null, null) ;
}
public boolean hasSQLConnection() { return sqlConnection != null ; }
public TransactionHandler getTransactionHandler() { return transactionHandler ; }
public ResultSetJDBC execQuery(String sqlString) throws SQLException
{ return execQuery(sqlString, SDBConstants.jdbcFetchSizeOff) ; }
public ResultSetJDBC execQuery(String sqlString, int fetchSize) throws SQLException
{
if ( loggingSQLStatements() || loggingSQLQueries() )
writeLog("execQuery", sqlString) ;
Connection conn = getSqlConnection() ;
try {
//Statement s = conn.createStatement() ; // Managed by ResultSetJDBC
// These are needed for MySQL when trying for row-by-row fetching
// and they are gemnerally true so set them always.
Statement s = conn.createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY) ; // Managed by ResultSetJDBC
// MySQL : Integer.MIN_VALUE
if ( fetchSize != SDBConstants.jdbcFetchSizeOff )
{
/* MySQL: streaming if:
* stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);
*/
s.setFetchSize(fetchSize) ;
}
return new ResultSetJDBC(s, s.executeQuery(sqlString)) ;
} catch (SQLException ex)
{
exception("execQuery", ex, sqlString) ;
throw ex ;
}
catch (RuntimeException ex)
{ throw ex ; }
}
public Object executeInTransaction(Command c) { return getTransactionHandler().executeInTransaction(c) ; }
public Object executeSQL(final SQLCommand c)
{
try {
return c.execute(getSqlConnection()) ;
} catch (SQLException ex)
{
exception("SQL", ex) ;
throw new SDBExceptionSQL(ex) ;
}
}
public int execUpdate(String sqlString) throws SQLException
{
if ( loggingSQLStatements() )
writeLog("execUpdate", sqlString) ;
Connection conn = getSqlConnection() ;
try ( Statement s = conn.createStatement() ) {
return s.executeUpdate(sqlString) ;
} catch (SQLException ex)
{
exception("execUpdate", ex, sqlString) ;
throw ex ;
}
}
/** Execute a statement, return the result set if there was one, else null */
public ResultSetJDBC exec(String sqlString) throws SQLException
{
if ( loggingSQLStatements() )
writeLog("exec", sqlString) ;
Connection conn = getSqlConnection() ;
Statement s = null ;
try {
s = conn.createStatement() ;
boolean r = s.execute(sqlString) ;
if ( r )
return new ResultSetJDBC(s, s.getResultSet()) ;
RS.close(s) ;
return null ;
}
// catch (SQLSyntaxErrorException ex) // Java 6
// {
// exception("exec", ex, sqlString) ;
// throw ex ;
// }
catch (SQLException ex)
{
RS.close(s) ;
exception("exec", ex, sqlString) ;
throw ex ;
}
}
/** Execute a statement, return the result set if there was one, else null. */
public ResultSetJDBC execSilent(String sqlString)
{
if ( loggingSQLStatements() )
writeLog("execSilent", sqlString) ;
Connection conn = getSqlConnection() ;
Statement s = null ;
try {
s = conn.createStatement() ;
boolean r = s.execute(sqlString) ;
if ( r )
return new ResultSetJDBC(s, s.getResultSet()) ;
} catch (SQLException ex) {}
// Close if did not return a ResultSetJDBC
RS.close(s) ;
return null ;
}
/** Prepare a statement **/
public PreparedStatement prepareStatement(String sqlString) throws SQLException {
if ( loggingSQLStatements() )
writeLog("prepareStatement", sqlString) ;
Connection conn = getSqlConnection() ;
try {
PreparedStatement ps = conn.prepareStatement(sqlString);
return ps;
} catch (SQLException ex) {
exception("prepareStatement", ex, sqlString) ;
throw ex;
}
}
/** Close a prepared statement **/
public void closePreparedStatement(PreparedStatement ps) throws SQLException {
if ( loggingSQLStatements() )
writeLog("closePrepareStatement", ps.toString()) ;
if ( ps == null )
return ;
try {
ps.close() ;
} catch (SQLException ex) {
exception("closePrepareStatement", ex, ps.toString()) ;
throw ex;
}
}
/** Get the names of the application tables */
public List<String> getTableNames()
{
return TableUtils.getTableNames(getSqlConnection()) ;
}
// public ResultSet metaData(String sqlString) throws SQLException
// {
// try {
// Connection conn = getSqlConnection() ;
// DatabaseMetaData dbmd = conn.getMetaData() ;
// ResultSet rsMD = dbmd.getTables(null, null, null, null) ;
// return rsMD ;
// } catch (SQLException e)
// {
// exception("metaData", e) ;
// throw e ;
// }
// }
public Connection getSqlConnection()
{
// Potential pool point.
return sqlConnection ;
}
public void close()
{
Connection connection = getSqlConnection() ;
try {
if ( connection != null && ! connection.isClosed() )
connection.close() ;
} catch (SQLException ex){
log.warn("Problems closing SQL connection", ex) ;
}
}
@Override
public String toString() { return getLabel() ; }
public boolean loggingSQLExceptions() { return thisLogSQLExceptions ;
}
public void setLogSQLExceptions(boolean thisLogSQLExceptions)
{
this.thisLogSQLExceptions = thisLogSQLExceptions ;
}
public boolean loggingSQLQueries() { return thisLogSQLQueries ; }
public void setLogSQLQueries(boolean thisLogSQLQueries)
{
this.thisLogSQLQueries = thisLogSQLQueries ;
}
public boolean loggingSQLStatements() { return thisLogSQLStatements ; }
public void setLogSQLStatements(boolean thisLogSQLStatements)
{
this.thisLogSQLStatements = thisLogSQLStatements ;
}
public String getLabel()
{
return label ;
}
public void setLabel(String label)
{
this.label = label ;
}
public String getJdbcURL()
{
return jdbcURL ;
}
public void setJdbcURL(String jdbcURL)
{
this.jdbcURL = jdbcURL ;
}
static Logger sqlLog = log ; // LoggerFactory.getLogger("SQL") ; // Remember to turn on in log4j.properties.
private void exception(String who, SQLException ex, String sqlString)
{
if ( this.loggingSQLExceptions() )
sqlLog.warn(who+": SQLException\n"+ex.getMessage()+"\n"+sqlString+"\n") ;
}
private void exception(String who, SQLException ex)
{
if ( this.loggingSQLExceptions() )
sqlLog.warn(who+": SQLException\n"+ex.getMessage()) ;
}
private void writeLog(String who, String sqlString)
{
if ( sqlLog.isInfoEnabled() )
sqlLog.info(who+"\n\n"+sqlString+"\n") ;
}
}
|
package com.example.api;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.util.JsonValidator;
import com.example.util.ResponseBuilder;
@RestController
@RequestMapping("/api")
public class DataProcessingController {
private static final Logger logger = LoggerFactory.getLogger(DataProcessingController.class);
@RequestMapping(value = "/processData", method = RequestMethod.POST)
public ResponseEntity<String> processData(@RequestBody String inputData, HttpServletRequest request) {
// Validate the incoming JSON data
if (!JsonValidator.isValidJson(inputData)) {
logger.error("Invalid JSON format in the input data");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ResponseBuilder.buildErrorResponse("Invalid JSON format"));
}
// Process the input data and generate the response
String processedData = processInputData(inputData);
// Return the processed data in the response
return ResponseEntity.ok(processedData);
}
private String processInputData(String inputData) {
// Implement the logic to process the input data
// Example: Convert JSON to object, perform calculations, etc.
return "Processed data: " + inputData;
}
} |
package net.community.chest.dom.proxy;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import org.w3c.dom.Element;
import net.community.chest.lang.ExceptionUtil;
import net.community.chest.reflect.AttributeAccessor;
import net.community.chest.reflect.AttributeMethodType;
import net.community.chest.reflect.ClassUtil;
import net.community.chest.util.map.ClassNameMap;
/**
* <P>Copyright 2007 as per GPLv2</P>
*
* @param <V> The type of objects being reflected
* @author <NAME>.
* @since Dec 10, 2007 1:21:30 PM
*/
public class ReflectiveAttributesProxy<V> extends AbstractReflectiveProxy<V,Method> {
public String getDuplicateAttributeKey (final String name, final Method m)
{
final Class<?>[] pars=(null == m) ? null : m.getParameterTypes();
final Class<?> pType=((null == pars) || (pars.length <= 0)) ? null : pars[0];
final String pName=(null == pType) ? null : pType.getSimpleName();
if ((null == pName) || (pName.length() <= 0))
return name;
return name + pName;
}
protected Map<String,Method> addDuplicateMethod (final Map<String,Method> oMap, final String name, final Method m)
{
Map<String,Method> sMap=oMap;
final String key=getDuplicateAttributeKey(name, m);
if ((null == key) || (key.length() <= 0))
return sMap; // OK, though not recommended
if (null == sMap)
sMap = new TreeMap<String,Method>(String.CASE_INSENSITIVE_ORDER);
final Method prev=sMap.put(key, m);
if (prev != null)
throw new IllegalStateException("addDuplicateMethod(" + name + ") same key=" + key);
return sMap;
}
/**
* @return TRUE=if found duplicate setter(s) during {@link #extractSettersMap(Class)}
* processing then use the getter's return type to resolve the correct setter.
* <B>Note: </B>only <U>one</U> such getter must exist, otherwise an exception will
* be thrown. If FALSE, the a 'virtual' attribute name is generated by appending
* the attribute type <U>simple</U> name to the base name
* @see #addDuplicateMethod(Map, String, Method)
* using the getter
*/
public boolean isResolveSetterByGetter ()
{
return true;
}
private Map<String,Method> _gettersMap /* =null */;
protected Map<String,Method> updateGettersMap (final String attrName, final Method gMethod)
{
if ((attrName != null) && (attrName.length() > 0) && (gMethod != null))
{
synchronized(this)
{
if (null == _gettersMap)
_gettersMap = new TreeMap<String, Method>(String.CASE_INSENSITIVE_ORDER);
_gettersMap.put(attrName, gMethod);
}
}
return _gettersMap;
}
/**
* Called if {@link #isResolveSetterByGetter()} is TRUE
* @param valsClass The values class
* @param sMethod The duplicate setter method
* @return The actual {@link Method} to be used
*/
protected Method resolveSetterByGetter (final Class<V> valsClass, final Method sMethod)
{
final Class<?>[] pars=sMethod.getParameterTypes();
if ((null == pars) || (pars.length != 1))
throw new IllegalStateException("resolveSetterByGetter(" + valsClass.getName() + ")[" + sMethod + "] illegal number of parameters");
final Class<?> aType=pars[0];
// TODO don't rely on the setter parameter type - in case 'boolean' override exists as well as non-boolean
final AttributeMethodType mType=ClassUtil.isBooleanCompatible(aType) ? AttributeMethodType.PREDICATE : AttributeMethodType.GETTER;
final String aName=AttributeMethodType.SETTER.getPureAttributeName(sMethod),
gName=mType.getAccessorName(aName);
try
{
final Method gMethod=valsClass.getMethod(gName);
final Class<?> gType=gMethod.getReturnType();
if (Void.TYPE.isAssignableFrom(gType) || Void.class.isAssignableFrom(gType))
throw new IllegalStateException("resolveSetterByGetter(" + valsClass.getName() + ")[" + gMethod + "] void getter return type");
// take advantage of the opportunity
updateGettersMap(aName, gMethod);
// check if lucky enough to have the correct setter in hand
if (gType == aType)
return sMethod;
return valsClass.getMethod(sMethod.getName(), gType);
}
catch(NoSuchMethodException e)
{
return null; // OK if method not found
}
catch(Exception e)
{
throw ExceptionUtil.toRuntimeException(e);
}
}
protected Map<String,Method> handleDuplicateMethods (final Class<V> valsClass,
final Map<String,Method> orgMap,
final Collection<? extends Method> dups)
{
if ((null == dups) || (dups.size() <= 0))
return orgMap;
Map<String,Method> sMap=orgMap;
if (isResolveSetterByGetter())
{
Map<String,Method> xMap=null;
for (final Method m : dups)
{
final String name=AttributeMethodType.SETTER.getPureAttributeName(m);
if ((null == name) || (name.length() <= 0))
continue; // should not happen
sMap.remove(name);
if ((xMap != null) && xMap.containsKey(name))
continue; // skip if already handled it
final Method sMethod=resolveSetterByGetter(valsClass, m);
if (null == sMethod)
continue;
if (null == xMap)
xMap = new TreeMap<String, Method>(String.CASE_INSENSITIVE_ORDER);
if (xMap.put(name,sMethod) != null)
throw new IllegalStateException("handleDuplicateMethods(" + valsClass.getName() + ")[" + sMethod + "] overrides existing setter");
}
if ((xMap != null) && (xMap.size() > 0))
sMap.putAll(xMap);
}
else
{
for (final Method m : dups)
{
final String name=AttributeMethodType.SETTER.getPureAttributeName(m);
if ((null == name) || (name.length() <= 0))
continue; // should not happen
final Method last=sMap.remove(name); // remove the last mapping
if (last != null) // if removed something, then re-map it
sMap = addDuplicateMethod(sMap, name, last);
sMap = addDuplicateMethod(sMap, name, m);
}
}
return sMap;
}
protected Map<String,Method> extractSettersMap (final Class<V> valsClass)
{
/*
* Special handling for some setters with same name - we "rename" their
* attributes to something (hopefully) unique
*/
final Collection<? extends Method> sl=AttributeMethodType.getAccessibleSetters(valsClass);
final int numSetters=(null == sl) ? 0 : sl.size();
if (numSetters <= 0)
return null;
Map<String,Method> sMap=null;
Collection<Method> dups=null;
for (final Method m : sl)
{
final String name=AttributeMethodType.SETTER.getPureAttributeName(m);
if ((null == name) || (name.length() <= 0))
continue; // should not happen
if (null == sMap)
sMap = new TreeMap<String,Method>(String.CASE_INSENSITIVE_ORDER);
final Method prev=sMap.put(name, m);
if (prev != null)
{
if (null == dups)
dups = new LinkedList<Method>();
dups.add(prev);
}
}
return handleDuplicateMethods(valsClass, sMap, dups);
}
/*
* @see net.community.chest.dom.transform.AbstractReflectiveProxy#extractAccessorsMap(java.lang.Class)
*/
@Override
protected Map<String,Method> extractAccessorsMap (Class<V> valsClass)
{
return extractSettersMap(valsClass);
}
public Map<String,Method> getSettersMap ()
{
return getAccessorsMap();
}
public void setSettersMap (Map<String,Method> settersMap)
{
setAccessorsMap(settersMap);
}
/**
* Automatically ignore {@link Object#getClass()} "attribute"
*/
public static final String CLASS_ATTR="class";
public static final Class<?> loadElementClass (final Element elem) throws Exception
{
final String clsPath=(null == elem) ? null : elem.getAttribute(CLASS_ATTR);
if ((null == clsPath) || (clsPath.length() <= 0))
return null;
return ClassUtil.loadClassByName(clsPath);
}
/*
* @see net.community.chest.dom.proxy.AbstractReflectiveProxy#handleUnknownAttribute(java.lang.Object, java.lang.String, java.lang.String, java.util.Map)
*/
@Override
protected V handleUnknownAttribute (V src, String name, String value, Map<String, ? extends Method> accsMap) throws Exception
{
if (CLASS_ATTR.equalsIgnoreCase(name))
return src;
return super.handleUnknownAttribute(src, name, value, accsMap);
}
protected V updateObjectResourceAttribute (final V src, final String aName, final String aValue, final Class<?> t, final Method setter) throws Exception
{
final Object o=loadObjectResourceAttribute(src, aName, aValue, t);
setter.invoke(src, o);
return src;
}
protected V updateObjectResourceAttribute (final V src, final String aName, final String aValue, final Method setter) throws Exception
{
return updateObjectResourceAttribute(src, aName, aValue, AttributeMethodType.SETTER.getAttributeType(setter), setter);
}
protected V updateObjectAttribute (final V src, final String aName, final String aValue,
final Class<?> aType, final Method setter) throws Exception
{
final Object objValue=getObjectAttributeValue(src, aName, aValue, aType);
setter.invoke(src, objValue);
return src;
}
/*
* @see net.community.chest.dom.transform.AbstractReflectiveProxy#updateObjectAttribute(java.lang.Object, java.lang.String, java.lang.String, java.lang.reflect.AccessibleObject)
*/
@Override
protected V updateObjectAttribute (final V src, final String aName, final String aValue, final Method setter) throws Exception
{
final Class<?>[] pars=(null == setter) ? null : setter.getParameterTypes();
final Class<?> aType=((null == pars) || (pars.length != 1)) ? null : pars[0];
return updateObjectAttribute(src, aName, aValue, aType, setter);
}
/*
* @see net.community.chest.dom.transform.AbstractReflectiveProxy#getAttributeRetriever(java.lang.Object, java.lang.String, java.lang.Class)
*/
@Override
public Method getAttributeRetriever (final V src, final String attrName, final Class<?> aType) throws Exception
{
if ((null == attrName) || (attrName.length() <= 0) || (null == aType))
return null;
Method gMethod=null;
synchronized(this)
{
if ((gMethod=((null == _gettersMap) || (_gettersMap.size() <= 0)) ? null : _gettersMap.get(attrName)) != null)
return gMethod;
}
Class<?> vClass=getValuesClass();
if ((null == vClass) && (src != null))
vClass = src.getClass();
if (null == vClass)
return null;
final String aName=AttributeMethodType.getAdjustedAttributeName(attrName);
final AttributeMethodType mType=ClassUtil.isBooleanCompatible(aType) ? AttributeMethodType.PREDICATE : AttributeMethodType.GETTER;
final String mthName=mType.getAccessorName(aName);
if (null == (gMethod=vClass.getMethod(mthName)))
throw new IllegalStateException("getAttributeRetriever(" + attrName + ")[" + aType.getName() + "] no retriever");
final Class<?> gType=gMethod.getReturnType();
if (Void.TYPE.isAssignableFrom(gType) || Void.class.isAssignableFrom(gType))
throw new IllegalStateException("getAttributeRetriever(" + attrName + ")[" + gMethod + "] void getter return type");
updateGettersMap(aName, gMethod);
return gMethod;
}
/*
* @see net.community.chest.dom.transform.AbstractReflectiveProxy#getAttributeValue(java.lang.Object, java.lang.String, java.lang.Class)
*/
@Override
public Object getAttributeValue (final V src, final String attrName, final Class<?> aType) throws Exception
{
final Method gm=getAttributeRetriever(src, attrName, aType);
final Object o=gm.invoke(src, AttributeAccessor.EMPTY_OBJECTS_ARRAY);
return o;
}
/*
* @see net.community.chest.dom.transform.AbstractReflectiveProxy#resolveAccessorType(java.lang.reflect.AccessibleObject)
*/
@Override
public Class<?> resolveAccessorType (final Method m)
{
final Class<?>[] pars=(null == m) ? null : m.getParameterTypes();
final Class<?> pType=((null == pars) || (pars.length != 1)) ? null : pars[0];
return pType;
}
private static ClassNameMap<ReflectiveAttributesProxy<?>> _proxiesMap /* =null */;
public static final synchronized ClassNameMap<ReflectiveAttributesProxy<?>> getRegisteredDefaultProxies ()
{
if (null == _proxiesMap)
_proxiesMap = new ClassNameMap<ReflectiveAttributesProxy<?>>();
return _proxiesMap;
}
public static final ReflectiveAttributesProxy<?> getDefaultClassProxy (
final Class<?> pc, final Class<?> baseClass)
{
final ClassNameMap<? extends ReflectiveAttributesProxy<?>> pm=
(null == pc) ? null : getRegisteredDefaultProxies();
if ((null == pm) || (pm.size() <= 0))
return null;
for (Class<?> cc=pc; ; )
{
final ReflectiveAttributesProxy<?> p;
synchronized(pm)
{
if ((p=pm.get(cc)) != null)
return p;
}
if (null == (cc=cc.getSuperclass()))
break; // reached the top
if (baseClass != null)
{
if (!baseClass.isAssignableFrom(cc))
break;
}
}
return null;
}
public static final ReflectiveAttributesProxy<?> getDefaultClassProxy (
final Class<?> pc, final Class<?> baseClass, final ReflectiveAttributesProxy<?> defProxy)
{
final ReflectiveAttributesProxy<?> p=getDefaultClassProxy(pc, baseClass);
if (null == p)
return defProxy;
if ((null == defProxy) || (defProxy == p))
return p;
// if got different proxy than default, prefer the more specific one
final Class<?> ppc=p.getValuesClass(), dpc=defProxy.getValuesClass();
if (ppc.isAssignableFrom(dpc)) // proxy is "weaker" than default
return defProxy;
return p;
}
public static final ReflectiveAttributesProxy<?> getDefaultClassProxy (
final Class<?> pc, final ReflectiveAttributesProxy<?> defProxy)
{
return getDefaultClassProxy(pc, null, defProxy);
}
public static final ReflectiveAttributesProxy<?> getDefaultClassProxy (final Class<?> pc)
{
return getDefaultClassProxy(pc, null, null);
}
public static final ReflectiveAttributesProxy<?> getDefaultObjectProxy (
final Object o, final Class<?> baseClass, final ReflectiveAttributesProxy<?> defProxy)
{
return getDefaultClassProxy((null == o) ? null : o.getClass(), baseClass, defProxy);
}
public static final ReflectiveAttributesProxy<?> getDefaultObjectProxy (
final Object o, final Class<?> baseClass)
{
return getDefaultObjectProxy(o, baseClass, null);
}
public static final ReflectiveAttributesProxy<?> getDefaultObjectProxy (final Object o)
{
return getDefaultObjectProxy(o, null);
}
/**
* Registers a default proxy for the values class of the provided proxy
* @param pc The {@link Class} - ignored if null
* @param proxy The {@link ReflectiveAttributesProxy} to register as default
* (ignored if null)
* @return Previous registered instance for this class - <code>null</code>
* if none
*/
public static final ReflectiveAttributesProxy<?> registerDefaultProxy (final Class<?> pc, final ReflectiveAttributesProxy<?> proxy)
{
if ((null == pc) || (null == proxy))
return null;
final ClassNameMap<ReflectiveAttributesProxy<?>> pm=getRegisteredDefaultProxies();
final ReflectiveAttributesProxy<?> prev;
synchronized(pm)
{
prev = pm.put(pc, proxy);
}
return prev;
}
/**
* Registers a default proxy for the values class of the provided proxy
* @param proxy The {@link ReflectiveAttributesProxy} to register as default
* for its {@link ReflectiveAttributesProxy#getValuesClass()}
* @return Previous registered instance for this class - <code>null</code>
* if none
*/
public static final ReflectiveAttributesProxy<?> registerDefaultProxy (final ReflectiveAttributesProxy<?> proxy)
{
return registerDefaultProxy((null == proxy) ? null : proxy.getValuesClass(), proxy);
}
public ReflectiveAttributesProxy (Class<V> objClass, boolean registerAsDefault)
throws IllegalArgumentException, IllegalStateException
{
super(objClass, Method.class);
if (registerAsDefault)
{
final ReflectiveAttributesProxy<?> prev=registerDefaultProxy(objClass, this);
if (prev != null)
throw new IllegalStateException("<init>#registerDefaultProxy(" + objClass.getName() + ") previous instance registered:" + prev.getClass().getName());
}
}
public ReflectiveAttributesProxy (Class<V> objClass) throws IllegalArgumentException
{
this(objClass, false);
}
}
|
#!/usr/bin/env bash
#
# Glusterfs volume check
# Depends on ssh connectivity between bastion and master node
# Nagios states
NAGIOS_STATE_OK=0
NAGIOS_STATE_WARNING=1
NAGIOS_STATE_CRITICAL=2
NAGIOS_STATE_UNKNOWN=3
CHECK_STATUS=$NAGIOS_STATE_UNKNOWN
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# create a temporary KUBECONFIG to avoid polluting the global environment
export KUBECONFIG=$(mktemp)
# create temp directory
TMPDIR=$(mktemp -d)
if [[ ! -f /dev/shm/secret/testuser_credentials ]]; then
echo "Cannot find test user credentials in /dev/shm/secret/testuser_credentials"
exit 1
fi
# login to openshift cluster
IFS='|' read -r api_url username password < /dev/shm/secret/testuser_credentials
oc login $api_url --username $username --password $password &> /dev/null
# First get the list of volumes from openshift and gluster
OPENSHIFT_VOLUME_FILE=$TMPDIR/volumes.openshift
GLUSTERFS_VOLUME_FILE=$TMPDIR/volumes.glusterfs
# get the volumes from openshift
oc get pv -o json | jq '.items[] | .spec.glusterfs.path' -r | grep -v null > $OPENSHIFT_VOLUME_FILE 2>/dev/null
# get the volumes from heketi
oc rsh -n glusterfs deploymentconfig.apps.openshift.io/heketi-storage heketi-cli volume list | awk '{print $NF}' | cut -c 6- | grep -o vol_[a-z0-9]* > $GLUSTERFS_VOLUME_FILE 2>/dev/null
# Sanity check, test if we have volume listings
if [ ! -f $OPENSHIFT_VOLUME_FILE ] || [ ! -f $GLUSTERFS_VOLUME_FILE ]; then
exit $CHECK_STATUS
fi
# Sort volume lists for easier diff
sort $OPENSHIFT_VOLUME_FILE > $OPENSHIFT_VOLUME_FILE.sorted
sort $GLUSTERFS_VOLUME_FILE > $GLUSTERFS_VOLUME_FILE.sorted
# Get diff on volume listings
EXTRA_VOLUMES_ON_OPENSHIFT="$(diff $OPENSHIFT_VOLUME_FILE.sorted $GLUSTERFS_VOLUME_FILE.sorted --changed-group-format='%<' --unchanged-group-format='')"
EXTRA_VOLUMES_ON_GLUSTERFS="$(diff $OPENSHIFT_VOLUME_FILE.sorted $GLUSTERFS_VOLUME_FILE.sorted --changed-group-format='%>' --unchanged-group-format='')"
# report volume counts as performance metrics
PERF_OPENSHIFT_TOTAL=$(cat $OPENSHIFT_VOLUME_FILE | wc -l)
PERF_GLUSTERFS_TOTAL=$(cat $GLUSTERFS_VOLUME_FILE | wc -l)
PERF_OPENSHIFT_COUNT=$(echo -n "$EXTRA_VOLUMES_ON_OPENSHIFT" | grep -c '^')
PERF_GLUSTERFS_COUNT=$(echo -n "$EXTRA_VOLUMES_ON_GLUSTERFS" | grep -c '^')
if [ "${EXTRA_VOLUMES_ON_OPENSHIFT}" = "${EXTRA_VOLUMES_ON_GLUSTERFS}" ]; then
echo "OK | openshift_volumes=$PERF_OPENSHIFT_TOTAL, gluster_volumes=$PERF_GLUSTERFS_TOTAL, extra_volumes_openshift=$PERF_OPENSHIFT_COUNT, extra_volumes_gluster=$PERF_GLUSTERFS_COUNT"
CHECK_STATUS=$NAGIOS_STATE_OK
else
CHECK_STATUS=$NAGIOS_STATE_WARNING
# -z requires gnu sed v4.2.2. It's used here to format output nicely.
#
# Opsview truncates the output to 1024 characters, which means we can print
# only about 20 volumes without truncating performance data. To ensure perf
# data gets delivered even if gluster list is long (more likely than other
# way around), truncate gluster list to 700 characters.
EXTRA_VOLUMES_ON_GLUSTERFS_CUT="${EXTRA_VOLUMES_ON_GLUSTERFS::700}, <truncated>"
echo "volumes unique to openshift: [$EXTRA_VOLUMES_ON_OPENSHIFT] volumes unique to heketi: [$EXTRA_VOLUMES_ON_GLUSTERFS_CUT] | openshift_volumes=$PERF_OPENSHIFT_TOTAL, gluster_volumes=$PERF_GLUSTERFS_TOTAL, extra_volumes_openshift=$PERF_OPENSHIFT_COUNT, extra_volumes_gluster=$PERF_GLUSTERFS_COUNT" | sed -z 's/\n/, /g'
fi
ret=$CHECK_STATUS
rm -f $KUBECONFIG
rm $TMPDIR/*
rmdir $TMPDIR
exit $ret |
<reponame>vchoudhari45/codingcargo
package com.vc.medium
object L406 {
object PeopleSorting extends Ordering[Array[Int]] {
def compare(x: Array[Int], y: Array[Int]): Int = {
val cmp = y(0).compareTo(x(0))
if(cmp == 0) x(1).compareTo(y(1)) else cmp
}
}
def reconstructQueue(people: Array[Array[Int]]): Array[Array[Int]] = {
scala.util.Sorting.quickSort(people)(PeopleSorting)
people.indices.foreach(i => {
val desiredIndex = people(i)(1)
move(desiredIndex, i)
})
def move(desiredIndex: Int, currentIndex: Int): Unit = {
val e = people(currentIndex)
(currentIndex until desiredIndex by - 1).foreach(i => {
people(i) = people(i - 1)
})
people(desiredIndex) = e
}
people
}
} |
<gh_stars>0
// Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2012 The Apache Software Foundation
//
// 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 org.apache.tapestry5.ioc.junit;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.apache.tapestry5.ioc.ObjectCreator;
import org.apache.tapestry5.ioc.ScopeConstants;
import org.apache.tapestry5.ioc.ServiceBuilderResources;
import org.apache.tapestry5.ioc.def.ContributionDef;
import org.apache.tapestry5.ioc.def.DecoratorDef;
import org.apache.tapestry5.ioc.def.ModuleDef;
import org.apache.tapestry5.ioc.def.ServiceDef;
/**
* Test ModuleDef implementation based on a {@link Map}
*/
@SuppressWarnings("rawtypes")
public class MapModuleDef implements ModuleDef {
private final Map<String, Object> map;
public MapModuleDef(Map<String, Object> map) {
super();
this.map = map;
}
@Override
public Class getBuilderClass() {
return null;
}
@Override
public Set<ContributionDef> getContributionDefs() {
return Collections.emptySet();
}
@Override
public Set<DecoratorDef> getDecoratorDefs() {
return Collections.emptySet();
}
@Override
public String getLoggerName() {
return "MapModuleDef";
}
@Override
public Set<String> getServiceIds() {
return map.keySet();
}
@Override
public ServiceDef getServiceDef(String serviceId) {
return new MapServiceDef(map, serviceId);
}
public static class MapServiceDef implements ServiceDef {
private final Map<String, Object> map;
private final String serviceId;
public MapServiceDef(Map<String, Object> map, String serviceId) {
super();
this.map = map;
this.serviceId = serviceId;
}
@Override
public ObjectCreator createServiceCreator(ServiceBuilderResources resources) {
return new ObjectCreator() {
@Override
public Object createObject() {
return map.get(serviceId);
}
};
}
@Override
public String getServiceId() {
return serviceId;
}
@Override
public Set<Class> getMarkers() {
return Collections.emptySet();
}
@Override
public Class getServiceInterface() {
return map.get(serviceId).getClass();
}
@Override
public String getServiceScope() {
return ScopeConstants.DEFAULT;
}
@Override
public boolean isEagerLoad() {
return false;
}
}
}
|
<reponame>y-yao/pyscf_arrow
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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.
#
# Author: <NAME> <<EMAIL>>
#
'''
Restricted open-shell Kohn-Sham for periodic systems at a single k-point
'''
import time
import numpy
import pyscf.dft
from pyscf.pbc.scf import rohf as pbcrohf
from pyscf.lib import logger
from pyscf.pbc.dft import rks
from pyscf.pbc.dft import uks
get_veff = uks.get_veff
class ROKS(pbcrohf.ROHF):
'''UKS class adapted for PBCs.
This is a literal duplication of the molecular UKS class with some `mol`
variables replaced by `cell`.
'''
def __init__(self, cell, kpt=numpy.zeros(3)):
pbcrohf.ROHF.__init__(self, cell, kpt)
rks._dft_common_init_(self)
def dump_flags(self):
pbcrohf.ROHF.dump_flags(self)
logger.info(self, 'XC functionals = %s', self.xc)
self.grids.dump_flags()
get_veff = get_veff
energy_elec = pyscf.dft.uks.energy_elec
define_xc_ = rks.define_xc_
density_fit = rks._patch_df_beckegrids(pbcrohf.ROHF.density_fit)
mix_density_fit = rks._patch_df_beckegrids(pbcrohf.ROHF.mix_density_fit)
if __name__ == '__main__':
from pyscf.pbc import gto
cell = gto.Cell()
cell.unit = 'A'
cell.atom = 'C 0., 0., 0.; C 0.8917, 0.8917, 0.8917'
cell.a = '''0. 1.7834 1.7834
1.7834 0. 1.7834
1.7834 1.7834 0. '''
cell.basis = 'gth-szv'
cell.pseudo = 'gth-pade'
cell.verbose = 7
cell.output = '/dev/null'
cell.build()
mf = ROKS(cell)
print(mf.kernel())
|
def largest_product(new_list):
counter = 0
answer = 0
new_list = []
for item in new_list:
new_list[counter] = item[0] * item[1]
for answer in new_list:
if answer < item:
answer = item
return answer |
<gh_stars>100-1000
var share_count = 0;
Page({
data: {},
onLoad: function(t) {
getApp().page.onLoad(this, t);
},
onShow: function() {
getApp().page.onShow(this);
var e = this;
getApp().core.showLoading({
mask: !0
}), getApp().request({
url: getApp().api.default.coupon_list,
success: function(t) {
0 == t.code && e.setData({
coupon_list: t.data.list
});
},
complete: function() {
getApp().core.hideLoading();
}
});
},
receive: function(t) {
var o = this, e = t.target.dataset.index;
getApp().core.showLoading({
mask: !0
}), o.hideGetCoupon || (o.hideGetCoupon = function(t) {
var e = t.currentTarget.dataset.url || !1;
o.setData({
get_coupon_list: null
}), e && getApp().core.navigateTo({
url: e
});
}), getApp().request({
url: getApp().api.coupon.receive,
data: {
id: e
},
success: function(t) {
0 == t.code && o.setData({
get_coupon_list: t.data.list,
coupon_list: t.data.coupon_list
});
},
complete: function() {
getApp().core.hideLoading();
}
});
},
closeCouponBox: function(t) {
this.setData({
get_coupon_list: ""
});
},
goodsList: function(t) {
var e = t.currentTarget.dataset.goods, o = [];
for (var a in e) o.push(e[a].id);
getApp().core.navigateTo({
url: "/pages/list/list?goods_id=" + o
});
}
}); |
#!/usr/bin/env bash
rm -f tab_*.ps tab_*.pdf
outfile=table_70_85.pdf
GFlow=0.7
GFhigh=0.85
time12a="10,15,20,25,30,35,40,50,60,70,80,90"
time12b="25,30,35,40,50,60,70,80,90,100,120,140"
time12c="40,50,60,70,80,90,100,120,140,160,180,210"
time12d="60,70,80,90,100,120,140,160,180,210,240,270"
time12e="90,100,120,140,160,180,210,240,270,300,330,360"
dgas6=o2
dgas21=ean50
dgas36=ean32
dgas57=21/45@57
dgas72=18/55@72
bgas30=ean32
bgas36=30/30
bgas39=25/35
bgas57=18/45
bgas72=15/55
bgas90=10/65
opt="-r 9.0 -f $GFlow,$GFhigh"
num=0
num=$(($num+1))
file="tab_$num.ps"
#ps header
./deco --hdr > $file
#tables
echo "($bgas30 1/2: 15m - 21m) heading" >> $file
./deco $opt -d 15 -g "$bgas30,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 16 -g "$bgas30,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 17 -g "$bgas30,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 18 -g "$bgas30,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 21 -g "$bgas30,[$dgas6]" -t $time12d -p >> $file
#ps join
./deco --jnr >> $file
#tables
echo "($bgas30 2/2: 24m - 33m) heading" >> $file
./deco $opt -d 24 -g "$bgas30,[$dgas6]" -t $time12c -p >> $file
./deco $opt -d 27 -g "$bgas30,[$dgas6]" -t $time12c -p >> $file
./deco $opt -d 30 -g "$bgas30,[$dgas6]" -t $time12c -p >> $file
./deco $opt -d 33 -g "$bgas30,[$dgas6]" -t $time12c -p >> $file
#ps footer
./deco --ftr >> $file
num=$(($num + 1))
file="tab_$num.ps"
#ps header
./deco --hdr > $file
#tables
echo "($bgas36 1/2: 15m - 21m) heading" >> $file
./deco $opt -d 15 -g "$bgas36,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 16 -g "$bgas36,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 17 -g "$bgas36,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 18 -g "$bgas36,[$dgas6]" -t $time12e -p >> $file
./deco $opt -d 21 -g "$bgas36,[$dgas6]" -t $time12d -p >> $file
#ps join
./deco --jnr >> $file
#tables
echo "($bgas36 2/2: 24m - 33m) heading" >> $file
./deco $opt -d 24 -g "$bgas36,[$dgas6]" -t $time12c -p >> $file
./deco $opt -d 27 -g "$bgas36,[$dgas6]" -t $time12c -p >> $file
./deco $opt -d 30 -g "$bgas36,[$dgas6]" -t $time12c -p >> $file
./deco $opt -d 33 -g "$bgas36,[$dgas6]" -t $time12c -p >> $file
#ps footer
./deco --ftr >> $file
case `uname` in
Darwin)
for f in ./tab_*.ps; do pstopdf $f; done
/System/Library/Automator/Combine\ PDF\ Pages.action/Contents/Resources/join.py --output $outfile tab_*.pdf
;;
Linux)
for f in ./tab_*.ps; do ps2pdf -sPAPERSIZE=a4 $f; done
pdfunite tab_*.pdf $outfile
;;
*)
echo "Only MacOS and Linux will work ¯\_(ツ)_/¯"
exit 1
;;
esac
rm -f tab_*.ps tab_*.pdf |
#!/usr/bin/env bash
RELATIVE_DIR=`dirname "$0"`
echo $RELATIVE_DIR
. $RELATIVE_DIR/build.sh
docker rm test_plugin
docker run -v "$(pwd)":/opt --name test_plugin pyengine/aws-cloud-services:1.0
# docker exec -ti test_plugin /bin/bash |
package tree.statements;
import tree.DefaultTreeNode;
import tree.TreeNode;
import tree.declarations.TDeclaration;
import tree.expressions.TExpression;
import tree.symbols.TSFor;
import tree.symbols.TSParLeft;
import tree.symbols.TSParRight;
public class TIterationStatementF extends TIterationStatement {
public TIterationStatementF(TIterationStatementF node) {
super(node);
}
public boolean isDeclaration() {
return getExprDecl1() instanceof TDeclaration;
}
public boolean isExpressionStatement() {
return getExprDecl1() instanceof TExpressionStatement;
}
public TreeNode getExprDecl1() {
return getChild(2);
}
public void setExprDecl1(DefaultTreeNode node) {
setChild(2, node);
}
public TExpressionStatement getExpr2() {
return (TExpressionStatement) getChild(3);
}
public TExpression getExpr3() {
if (getNChildren() == 6)
return null;
return (TExpression) getChild(4);
}
public TIterationStatementF(TSFor fo, TSParLeft par_left, TExpressionStatement estat1, TExpressionStatement estat2, TSParRight par_right, TStatement statement) {
addChild(fo);
addChild(par_left);
addChild(estat1);
addChild(estat2);
addChild(par_right);
addChild(statement);
}
public TIterationStatementF(TSFor fo, TSParLeft par_left, TExpressionStatement estat1, TExpressionStatement estat2, TExpression expr, TSParRight par_right, TStatement statement) {
addChild(fo);
addChild(par_left);
addChild(estat1);
addChild(estat2);
addChild(expr);
addChild(par_right);
addChild(statement);
}
public TIterationStatementF(TSFor fo, TSParLeft par_left, TDeclaration decl, TExpressionStatement estat, TSParRight par_right, TStatement statement) {
addChild(fo);
addChild(par_left);
addChild(decl);
addChild(estat);
addChild(par_right);
addChild(statement);
}
public TIterationStatementF(TSFor fo, TSParLeft par_left, TDeclaration decl, TExpressionStatement estat, TExpression expr, TSParRight par_right, TStatement statement) {
addChild(fo);
addChild(par_left);
addChild(decl);
addChild(estat);
addChild(expr);
addChild(par_right);
addChild(statement);
}
}
|
<filename>src/globals.d.ts<gh_stars>0
/* eslint-disable import/export */
declare module "tailwind.macro" {
export default function tw(a: TemplateStringsArray): string
}
declare module "react-table/lib/hoc/foldableTable" {
import { Column, TableProps } from "react-table"
interface FoldableColumn<T> extends Column<T> {
foldable?: boolean
}
interface FoldableTableProps<D = any> extends TableProps<D> {
columns: FoldableColumn<D>[]
}
export default function foldableTable<D>(
a: React.ComponentType
): React.ComponentType<Partial<FoldableTableProps<D>>>
}
declare module "uuid/v4" {
export default function uuid(): string
}
|
<filename>EEG/process_MAHNOB_HCI/MAHNOB_HCI_EEG_example.py
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 13:41:58 2018
@author: <NAME>
"""
"""
This is an example for processing EEG data in MAHNOB_HCI dataset using the function in ../process_facial_expression/processing script
Note that the dataset's format should be same as the format performed in 'dataset' folder
The MAHNOB_HCI dataset contains 20 trials for each subject.
In this example, a leave-one-out cross validation is performed for each subject.
This is an example for leave-one-trial-out cross validation
"""
import sys
sys.path.append('../process_EEG')
import EEG_tool
if __name__ == '__main__':
root_path = '../../dataset/' + 'MAHNOB_HCI/'
#for each subject we train 20 model
for subject_id in range(1, 21):
#calculate accuracy
acc_valence, acc_arousal = 0, 0
subject_path = root_path + str(subject_id) + '/'
#each trial has one change to become validation set. leave-one-trial out
for validation_trial_id in range(1, 21):
EEG_model = EEG_tool.EEG_model()
#use other 19 trial as train set
for train_trial_id in range(1, 21):
#can't put the validation trial into train set
if train_trial_id == validation_trial_id:
continue
#load train data
path = subject_path + 'trial_' + str(train_trial_id) + '/'
EEG_model.add_one_trial_data(path, preprocessed=False)
#feed data to model
EEG_model.train()
#validation on one trial
path = subject_path + 'trial_' + str(validation_trial_id) + '/'
#predict one trial
valence_correct, arousal_correct = EEG_model.predict_one_trial(path)
acc_valence += 1 if valence_correct else 0
acc_arousal += 1 if arousal_correct else 0
print (valence_correct, arousal_correct)
print ('subject: ' + str(subject_id))
print (acc_valence/20., acc_arousal/20.) |
<filename>benchmarks/2_scc/python_igraph.py<gh_stars>1-10
from igraph import *
import time
import sys
filename = sys.argv[1]
g = Graph.Read(filename, format="edges")
start = time.monotonic()
scc_all = g.components(mode=STRONG)
print(time.monotonic() - start, "secs")
print(len(scc_all))
|
<reponame>ThomZz/hexo-theme-doc
'use strict';
const requestController = require('../request');
describe('controllers.request', () => {
it('should transform the context as expected', () => {
const headerParam = {
name: 'headerParam',
in: 'header',
description: 'description',
required: 'true',
type: 'string',
format: 'format',
};
const pathParam = {
name: 'pathParam',
in: 'path',
description: 'description',
required: 'true',
type: 'string',
format: 'format',
};
const queryParam = {
name: 'queryParam',
in: 'query',
description: 'description',
required: 'true',
type: 'string',
format: 'format',
};
const formDataParam = {
name: 'formDataParam',
in: 'formData',
description: 'description',
required: 'true',
type: 'string',
format: 'format',
};
const bodyParam = {
name: 'bodyParam',
in: 'body',
description: 'description',
required: 'true',
type: 'string',
format: 'format',
};
const ctx = {
operations: [ {} ],
operation: {
summary: 'A nice summary',
description: 'A nice description',
parameters: [
headerParam,
pathParam,
queryParam,
formDataParam,
bodyParam
],
tags: [],
produces: [],
responses: {},
verb: 'get',
path: '/path',
title: 'title',
}
};
const {request} = requestController(ctx);
expect(request).toBeInstanceOf(Object);
expect(Object.keys(request).length).toBe(5);
expect(request.header[0]).toBe(headerParam);
expect(request.path[0]).toBe(pathParam);
expect(request.query[0]).toBe(queryParam);
expect(request.formData[0]).toBe(formDataParam);
expect(request.body[0]).toBe(bodyParam);
});
});
|
<filename>db/migrate/20160531143901_create_device_statistics.rb<gh_stars>1-10
class CreateDeviceStatistics < ActiveRecord::Migration
def change
create_table :device_statistics do |t|
t.integer :device_id
t.datetime :timestamp
t.string :label
t.decimal :value
t.string :format
t.timestamps null: false
end
add_index :device_statistics, :device_id
add_index :device_statistics, [:device_id, :label]
end
end
|
export MAVENDIR=/opt/apache-maven-3.0.5
export PATH="$PATH:$MAVENDIR/bin"
# Leave my user name out of the META-INF/MANIFEST.MF Built-By field.
alias mvn='mvn -Duser.name=""'
|
<filename>css-style-config/webpack.config.js<gh_stars>0
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
//aqui van los loaders
{
//test: que tipo de archivo quiero reconocer (en regex)
//use: que loader se va a encargar del tipo de extension de archivo
test: /\.css$/,
// use: [
// { loader: "style-loader" }, // Agrega el css al DOM en un <style>
// { loader: "css-loader" }, // interpreta los archivos css en js via import
// ]
//primero se ejecuta el css loader y luego style loader
use: [ 'style-loader', 'css-loader' ]
}
]
}
} |
module CandidateInterface
class ApplyFromFindPage
attr_accessor :course, :provider
def initialize(provider_code:, course_code:)
@provider_code = provider_code
@course_code = course_code
@can_apply_on_apply = false
@course_on_find = false
@course = nil
@provider = nil
end
def determine_whether_course_is_on_find_or_apply
@provider = Provider.find_by!(code: @provider_code)
@course = provider.courses.current_cycle.where(exposed_in_find: true).find_by!(code: @course_code)
if @course&.open_on_apply? && pilot_open?
@can_apply_on_apply = true
@course_on_find = true
elsif @course.present?
@course_on_find = true
end
rescue ActiveRecord::RecordNotFound
@course = fetch_course_from_api
@course_on_find = true if @course.present?
end
def can_apply_on_apply?
@can_apply_on_apply
end
def course_on_find?
@course_on_find
end
private
def pilot_open?
FeatureFlag.active?('pilot_open')
end
def fetch_course_from_api
Rails.cache.fetch ['course-public-api-request', @provider_code, @course_code], expires_in: 5.minutes do
course = TeacherTrainingPublicAPI::Course.fetch(@provider_code, @course_code)
course.sites if course # cache subsequent calls to #sites too (this method is memoized)
course
end
end
end
end
|
#!/bin/bash
# use this to run one experiment
for traindata in 500 #1000 250 #nx
do
#for decay in 0.0 0.025 0.05 0.075 0.1 0.125 0.15 0.175 0.2 0.225 0.25 0.275 0.3 0.35 0.4 0.45 0.5
for decay in 0.0 #0.275 0.3 0.35 0.4 0.45 0.5
#for decay in 0.0
do
export traindata
export decay
#for HLN in 50 75 100 150 200 250 300 350 400 450 490 500 510 550 600 700 800 900 1000 1500 2000 3000 4000 5000 7000 10000
for HLN in 500
#for HLN in 500 1000
do
export HLN
#for run in 1 2 3 4 5 6 7 8 9 10
for run in 1
do
./Random.sh
done
done
done
done
|
/**
* Copyright 2014 isandlaTech
*
* 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 org.cohorte.pyboot.api;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a basic component
*
* @author <NAME>
*/
public class ComponentBean {
/** ComponentBean factory name (type) */
private final String pFactory;
/** Instance name */
private final String pName;
/** Instance properties */
private final Map<String, Object> pProperties = new HashMap<String, Object>();
/**
* Setup the component bean
*
* @param aFactory
* ComponentBean type
* @param aName
* Instance name
* @param aProperties
* Instance properties
*/
public ComponentBean(final String aFactory, final String aName,
final Map<String, Object> aProperties) {
pFactory = aFactory;
pName = aName;
if (aProperties != null) {
// Copy given properties
pProperties.putAll(aProperties);
}
}
/**
* @return the factory
*/
public String getFactory() {
return pFactory;
}
/**
* @return the name
*/
public String getName() {
return pName;
}
/**
* @return the properties
*/
public Map<String, Object> getProperties() {
return new HashMap<String, Object>(pProperties);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Component(name='" + pName + "', factory='" + pFactory + "')";
}
}
|
<reponame>schinmayee/nimbus<filename>applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Grids_Chimera_Interpolation/CELL_LOOKUP_CHIMERA.cpp
//#####################################################################
// Copyright 2005-2010, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Grids_Uniform/GRID.h>
#include <PhysBAM_Dynamics/Grids_Chimera_Interpolation/CELL_LOOKUP_CHIMERA.h>
#include <PhysBAM_Tools/Matrices/MATRIX_MXN.h>
#include <PhysBAM_Tools/Matrices/MATRIX_1X1.h>
#include <PhysBAM_Tools/Matrices/MATRIX_2X2.h>
#include <PhysBAM_Tools/Matrices/MATRIX_3X3.h>
#include <PhysBAM_Dynamics/Grids_Chimera_PDE_Linear/Parallel_Computation/LAPLACE_CHIMERA_GRID_MPI.h>
using namespace PhysBAM;
//#####################################################################
// Function operator()
//#####################################################################
template<class T_GRID> typename T_GRID::SCALAR CELL_LOOKUP_CHIMERA<T_GRID>::operator()(const GRID_CELL_INDEX& grid_cell_index) const
{
if(laplace_grid.Local_Grid(grid_cell_index.x)) return (*u(grid_cell_index.x))(grid_cell_index.y);
else return u_boundary(grid_cell_index.x)(laplace_grid.boundary_cell_indices_to_linear_index(grid_cell_index.x).Get(grid_cell_index.y));
}
//#####################################################################
// Function Valid
//#####################################################################
/*template<class T_GRID> bool CELL_LOOKUP_CHIMERA<T_GRID>::Valid(const GRID_CELL_INDEX& grid_cell_index) const
{
if(laplace_grid.Local_Grid(grid_cell_index.x)) return u_valid==0 || (*u_valid)(grid_cell_index.x)(grid_cell_index.y);
else return u_boundary_valid==0 || (*u_boundary_valid)(grid_cell_index.x).Contains(grid_cell_index.y);
}*/
//#####################################################################
#define INSTANTIATION_HELPER(T,D) \
template class CELL_LOOKUP_CHIMERA<GRID<VECTOR<T,D> > >;
INSTANTIATION_HELPER(float,1);
INSTANTIATION_HELPER(float,2);
INSTANTIATION_HELPER(float,3);
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
INSTANTIATION_HELPER(double,1);
INSTANTIATION_HELPER(double,2);
INSTANTIATION_HELPER(double,3);
#endif
|
#!/usr/bin/env bash
# Copyright 2019 The Knative 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.
NAME=hello
TARGET=${USER:-world}
# Create a sample Knative Service
cat <<EOF | kubectl apply -f -
apiVersion: serving.knative.dev/v1alpha1
kind: Service
metadata:
name: $NAME
spec:
template:
spec:
containers:
- image: gcr.io/knative-samples/helloworld-go
env:
- name: TARGET
value: $TARGET
EOF
# Wait for the Knative Service to be ready
while output=$(kubectl get ksvc $NAME); do
echo "$output"
echo $output | grep True >/dev/null && break
sleep 2
done
# Parse the URL from the knative service
URL=$(kubectl get ksvc $NAME | grep True | awk '{print $2}')
# Fetch it, accounting for possible istio race conditions
until curl -f $URL; do sleep 2; done
|
<filename>app/models/upvote.rb
class Upvote < ActiveRecord::Base
belongs_to :user
belongs_to :prop, counter_cache: true
validates :user_id, uniqueness: { scope: :prop_id }
validates :user_id, :prop_id, presence: true
validate :can_upvote?, on: :create
private
def can_upvote?
return unless user.present? && prop.users.include?(user)
errors.add(:user_id, "You can't upvote your own prop!")
end
end
|
#!/bin/bash
set -eu
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
cd $SCRIPT_DIR/../rfc/
curl -iL https://www.rfc-editor.org/in-notes/tar/RFC-all.zip -o RFC-all.zip
unzip -o RFC-all.zip -x "*.pdf" || true
|
// 3143. 가장 빠른 문자열 타이핑
// 2019.07.14
#include<iostream>
#include<string>
using namespace std;
int cnt;
string ReplaceAll(string &str, const string& from, const string& to)
{
size_t start_pos = 0; // string처음부터 검사
while ((start_pos = str.find(from, start_pos)) != string::npos) //from을 찾을 수 없을 때까지
{
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // 중복검사를 피하고 from.length() > to.length()인 경우를 위해서
cnt++;
}
return str;
}
int main()
{
int t;
cin >> t;
for (int testCase = 1; testCase <= t; testCase++)
{
cnt = 0;
string a, b;
cin >> a >> b;
string tmp = "";
string res = ReplaceAll(a, b, tmp);
int ans = res.size() + cnt;
cout << "#" << testCase << " " << ans << "\n";
}
return 0;
}
|
import shutil
def safe_remove_directory(path):
try:
shutil.rmtree(path)
except OSError as err:
print(f"Unable to delete directory {path} due to: {err}")
# Example usage
directory_path = '/path/to/directory'
safe_remove_directory(directory_path) |
/*───────────────────────────────────────────────────────────────────────────*\
│ Copyright (C) 2014 eBay Software Foundation │
│ │
│hh ,'""`. │
│ / _ _ \ 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. │
\*───────────────────────────────────────────────────────────────────────────*/
/*global describe, it*/
'use strict';
var assert = require('yeoman-generator').assert,
testutil = require('./util');
describe('kraken:app', function () {
// Disable timeout since we're doing multiple installs
this.timeout(Infinity);
it('creates an app which uses dust', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = 'dustjs';
base.prompt['componentPackager'] = 'bower';
base.prompt['cssModule'] = 'less';
base.prompt['i18n'] = false;
base.prompt['jsModule'] = false;
testutil.run(base, function (err) {
assert.file([
'public/templates/index.dust',
'public/templates/layouts/master.dust',
'public/templates/errors/404.dust',
'public/templates/errors/500.dust',
'public/templates/errors/503.dust',
'public/components/dustjs-linkedin/',
'public/components/dustjs-helpers/',
'tasks/dustjs.js'
]);
assert.fileContent([
['package.json', new RegExp(/\"dustjs-linkedin\"\:/)],
['package.json', new RegExp(/\"dustjs-helpers\"\:/)],
['package.json', new RegExp(/\"engine-munger\"\:/)],
['package.json', new RegExp(/\"grunt-dustjs\"\:/)],
['Gruntfile.js', new RegExp(/registerTask.*build.*dustjs/)],
['public/templates/layouts/master.dust', new RegExp(/(app\.css)/) ]
]);
done(err);
});
});
it('creates an app which does not have any view engine', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = false;
base.prompt['cssModule'] = false;
base.prompt['i18n'] = false;
base.prompt['jsModule'] = false;
testutil.run(base, function (err) {
assert.file([
'config/config.json',
'controllers/index.js'
]);
assert.noFile([
'.bowerrc'
]);
assert.fileContent([
['config/config.json', new RegExp(/^((?!fileNotFound)[\s\S])*$/)],
['config/config.json', new RegExp(/^((?!serverError)[\s\S])*$/)],
['controllers/index.js', new RegExp(/res.send/)],
['controllers/index.js', new RegExp(/^((?!res.render)[\s\S])*$/)]
]);
done(err);
});
});
it('creates an app which uses split packages for i18n', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = false;
base.prompt['i18n'] = 'i18n';
base.prompt['jsModule'] = false;
testutil.run(base, function (err) {
assert.file([
'locales/US/en/errors/404.properties',
'locales/US/en/errors/500.properties',
'locales/US/en/errors/503.properties'
]);
done(err);
});
});
it('creates an app which uses makara 2 for i18n', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = 'makara';
base.prompt['i18n'] = 'i18n';
base.prompt['jsModule'] = 'browserify';
testutil.run(base, function (err) {
assert.file([
'locales/US/en/errors/404.properties',
'locales/US/en/errors/500.properties',
'locales/US/en/errors/503.properties',
'public/templates/layouts/master.dust',
'public/templates/index.dust'
]);
assert.fileContent([
['package.json', new RegExp(/\"makara\"\:/)],
['tasks/dustjs.js', /public\/templates\//],
['Gruntfile.js', new RegExp(/registerTask.*build.*dustjs/)]
]);
done(err);
});
});
it('creates an app which uses less', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = false;
base.prompt['cssModule'] = 'less';
base.prompt['jsModule'] = false;
testutil.run(base, function (err) {
assert.file([
'public/css/app.less',
'tasks/less.js'
]);
assert.fileContent([
['package.json', new RegExp(/\"construx-less\"\:/)],
['package.json', new RegExp(/\"grunt-contrib-less\"\:/)]
]);
done(err);
});
});
it('creates an app which uses sass', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = false;
base.prompt['cssModule'] = 'sass';
base.prompt['jsModule'] = false;
testutil.run(base, function (err) {
assert.file([
'public/css/app.scss',
'tasks/sass.js'
]);
assert.fileContent([
['package.json', new RegExp(/\"construx-sass\"\:/)],
['package.json', new RegExp(/\"grunt-sass\"\:/)]
]);
done(err);
});
});
it('creates an app which uses stylus', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = false;
base.prompt['cssModule'] = 'stylus';
base.prompt['jsModule'] = false;
testutil.run(base, function (err) {
assert.file([
'public/css/app.styl',
'tasks/stylus.js'
]);
assert.fileContent([
['package.json', new RegExp(/\"construx-stylus\"\:/)],
['package.json', new RegExp(/\"grunt-contrib-stylus\"\:/)]
]);
done(err);
});
});
it('creates an app which uses requirejs', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = false;
base.prompt['cssModule'] = false;
base.prompt['jsModule'] = 'requirejs';
testutil.run(base, function (err) {
assert.file([
'tasks/requirejs.js'
]);
assert.fileContent([
['package.json', new RegExp(/\"requirejs\"\:/)],
['package.json', new RegExp(/\"grunt-contrib-requirejs\"\:/)],
['public/js/app.js', new RegExp(/require\(/)]
]);
done(err);
});
});
it('creates an app which uses browserify', function (done) {
var base = testutil.makeBase('app');
base.prompt['templateModule'] = false;
base.prompt['cssModule'] = false;
base.prompt['jsModule'] = 'browserify';
testutil.run(base, function (err) {
assert.file([
'tasks/browserify.js',
'public/js/app.js'
]);
assert.fileContent([
['package.json', new RegExp(/\"grunt-browserify\"\:/)]
]);
done(err);
});
});
});
|
/*
Copyright © 2020 <NAME> <EMAIL>
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 commands
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/heroiclabs/nakama-common/api"
log "github.com/micro/go-micro/v2/logger"
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/emptypb"
)
type TeamResult struct {
TeamNumber int
Votes int
}
type MatchResult struct {
UserID string
DiscordID string
ProofLink string
TeamNumber int
Win bool
Draw bool
DateTime time.Time
}
type MatchResultRequest struct {
MatchResult *MatchResult
MatchID string
}
func PrintMatchResults(matchState *MatchState) string {
return ExecuteTemplate(
`{{if .Results}}> Results:
{{range $index, $element := .Results}}> <@{{.DiscordID}}> {{if not .Draw }}**Team {{.TeamNumber}}** {{if .Win}}**Win**{{else}}**Lose**{{end}}{{else}}**Draw**{{end}} {{.ProofLink}} {{.DateTime | formatTimeAsDate}}
{{end}}`+"\n"+`{{end}}`,
matchState)
}
func createResult(cmdBuilder *commandsBuilder, cmd *cobra.Command, args []string, win bool, draw bool) error {
log.Infof("%+v\n", args)
account, err := cmdBuilder.nakamaCtx.Client.GetAccount(cmdBuilder.nakamaCtx.Ctx, &emptypb.Empty{})
if err != nil {
log.Error(err)
return err
}
matchID, _ := cmd.Flags().GetString("matchID")
var matchState *MatchState
if len(args) == 0 {
matchState, err = getLastUserMatchState(cmdBuilder, account, MATCH_COLLECTION)
}
proof, _ := cmd.Flags().GetString("proof")
if proof == "" {
if draw && len(args) == 2 {
proof = args[1]
}
if !draw && len(args) == 3 {
proof = args[2]
}
}
if proof != "" {
if !strings.HasPrefix(proof, "http") {
proof = "http://" + proof
}
if !IsValidUrl(proof) {
return fmt.Errorf("'%v' is not a valid url for the proof link", proof)
}
}
if matchID == "" {
if !draw && len(args) >= 2 {
matchState, err = getMatchState(cmdBuilder, args[1], MATCH_COLLECTION)
if err != nil {
log.Error(err)
return err
}
}
if draw && len(args) >= 1 {
matchState, err = getMatchState(cmdBuilder, args[0], MATCH_COLLECTION)
if err != nil {
log.Error(err)
return err
}
}
}
teamID, _ := cmd.Flags().GetInt("teamID")
if !draw {
if teamID == -1 && len(args) >= 1 {
teamID, err = strconv.Atoi(args[0])
if err == nil {
log.Error(err)
return err
}
}
if teamID == -1 {
teamID = GetTeamNumberFromUserAndMatch(account.User.Id, matchState)
}
if teamID < -1 || teamID > (len(matchState.Teams)-1) {
return fmt.Errorf("Incorrect team number %v", teamID)
}
}
if matchState == nil {
return fmt.Errorf("No match found for <@%v>", account.CustomId)
}
payload, _ := json.Marshal(MatchResultRequest{
MatchResult: &MatchResult{
UserID: account.User.Id,
DiscordID: account.CustomId,
TeamNumber: teamID,
Win: win,
Draw: draw,
ProofLink: proof,
},
MatchID: matchState.MatchID,
})
log.Infof("%+v\n", string(payload))
result, err := cmdBuilder.nakamaCtx.Client.RpcFunc(cmdBuilder.nakamaCtx.Ctx, &api.Rpc{Id: "MatchResult", Payload: string(payload)})
if err != nil {
log.Error(err)
return err
}
if result.Payload != "" {
fmt.Fprintf(cmd.OutOrStdout(), MarshalIndent(result.Payload))
}
return nil
}
func setupResultFlags(cmd *cobra.Command, isDraw bool) {
cmd.Flags().StringP("matchID", "m", "", "usage")
cmd.Flags().StringP("proof", "p", "", "Proof link **must** be a valid URL starting with **http** or **https**")
if !isDraw {
cmd.Flags().IntP("teamID", "t", -1, "Team #")
}
}
func getCmdResultWinCreate(cmdBuilder *commandsBuilder) *cobra.Command {
cmd := &cobra.Command{
Use: "win [teamID] [matchID] [proof_link]",
Aliases: []string{"victory"},
Short: "Report an early **win** before the match ends",
Long: `Report an early **win** before the match ends`,
RunE: func(cmd *cobra.Command, args []string) error {
return createResult(cmdBuilder, cmd, args, true, false)
},
}
setupResultFlags(cmd, false)
return cmd
}
func getCmdResultDrawCreate(cmdBuilder *commandsBuilder) *cobra.Command {
cmd := &cobra.Command{
Use: "draw [matchID] [proof_link]",
Aliases: []string{"victory"},
Short: "Report an early **draw** before the match ends",
Long: `Report an early **draw** before the match ends`,
RunE: func(cmd *cobra.Command, args []string) error {
return createResult(cmdBuilder, cmd, args, false, true)
},
}
setupResultFlags(cmd, true)
return cmd
}
func getCmdResultLossCreate(cmdBuilder *commandsBuilder) *cobra.Command {
cmd := &cobra.Command{
Use: "lose [teamID] [matchID] [proof_link]",
Aliases: []string{"ff", "loss"},
Short: "Report an early **loss** before the match ends",
Long: `Report an early **loss** before the match ends`,
RunE: func(cmd *cobra.Command, args []string) error {
return createResult(cmdBuilder, cmd, args, false, false)
},
}
setupResultFlags(cmd, false)
return cmd
}
|
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamPractice {
public static void main(String[] args) {
// IntStream.range(1, 10).forEach(System.out::println);
//熟悉 ifPresent 方法,如果为 null,可以什么都不执行
// Arrays.stream(new int[] {}).map(n -> 2*n + 1).average().ifPresent(e -> System.out.println("test"));
// 重点关注mapToInt方法
// Stream.of("a1", "a2", "a3")
// .map(s -> s.substring(1))
// .mapToInt(Integer::parseInt)
// .max()
// .ifPresent(System.out::println);
// mapToObj用法
// IntStream.range(1,4).mapToObj(e -> "a" + e).forEach(System.out::println);
// 流是链式执行的
// Stream.of("d2", "a2", "b1", "a3", "c").map(s ->{
// System.out.println("map:" + s);
// return s.toUpperCase();
// }).anyMatch(s -> {
// System.out.println("anyMatch: " + s);
// return s.startsWith("A");
// });
// 减少执行次数,把filter放在前面更合适
// 并行流
Arrays.asList("a1", "a2", "b1", "c2", "c1").parallelStream().filter(s -> {
System.out.format("filter: %s [%s]\n", s, Thread.currentThread().getName());
return true;
}).map(s -> {
System.out.format("map: %s [%s]\n", s, Thread.currentThread().getName());
return s.toUpperCase();
}).sorted((s1, s2) -> {
System.out.format("sorted: %s<>%s [%s]\n", s1, s2, Thread.currentThread().getName());
return s1.compareTo(s2);
}).forEach(s -> System.out.format("forEach: %s [%s]\n", s, Thread.currentThread().getName()));
}
} |
/// <reference types="cypress" />
/* global cy */
/* eslint-disable react/prop-types */
import React, { Component } from 'react';
import SeeThroughController from './SeeThroughController';
import SeeThrough from './SeeThrough';
import NoopClassWrapper from './NoopClassWrapper';
import ReactTestUtils from 'react-dom/test-utils';
import 'cypress-react-unit-test';
// From https://github.com/bahmutov/cypress-react-unit-test/issues/51
import * as ReactDOM from 'react-dom';
window.ReactDOM = ReactDOM;
const simpleString = 'Some Text';
// Helpers
beforeEach(() => {
// Mount something in the beginning so that expectBounds can use .render
// Using .render lets us expectBounds multiple times in one test
const style = `
* {
font: normal 12px Arial;
margin: 0;
}
`;
cy.mount(<CompNoopWrapper>TEMPORARY ELEMENT</CompNoopWrapper>, { style });
return cy.get(CompNoopWrapper);
});
/**
* @returns the minimal rectangle that covers all the given rectangles.
* If "rects" is empty, returns an empty rectangle at position (0, 0).
*/
function getMinimalCoveringRect(rects) {
if(rects.length === 0) {
return { x: 0, y: 0, width: 0, height: 0 };
}
// Figure out the min/max coordinates of all the rectangles
let minX = Number.POSITIVE_INFINITY,
minY = Number.POSITIVE_INFINITY,
maxX = Number.NEGATIVE_INFINITY,
maxY = Number.NEGATIVE_INFINITY;
for(const { x, y, width, height } of rects) {
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x + width);
maxY = Math.max(maxY, y + height);
}
// Compute the rectangle from the min/max coordinates
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
};
}
function expectBounds(element, expectedBounds) {
// Overrides the previous render
cy.render(<CompNoopWrapper>{ element }</CompNoopWrapper>);
// We need to wait for the SeeThroughController to have rendered a couple of times
return cy.wait(100).then(() => {
return cy.get(CompNoopWrapper).then(tree => {
const partialMask = ReactTestUtils.findRenderedComponentWithType(tree, NoopClassWrapper);
const bounds = getMinimalCoveringRect(partialMask.props.exclude);
expect(bounds).to.deep.equal(expectedBounds);
});
})
}
function expectNoCrash(element) {
// Overrides the previous render
cy.render(<CompNoopWrapper>{ element }</CompNoopWrapper>);
return cy.get(CompNoopWrapper);
}
function box(width, height) {
const style = {
width,
height,
overflow: 'hidden', // Allow boxes smaller than the single character we put in the box
};
// Text is intentionally included to make sure that SeeThrough handles text nodes correctly
return <div style={ style }>t</div>;
}
// Child wrappers
const FuncNoopWrapper = ({ children }) => children; // NOTE: You can't attach a ref to a functional component so any ref techniques will need to handle that
const FuncDivWrapper = ({ children }) => <div>{ children }</div>;
class CompNoopWrapper extends Component { render() { return this.props.children; } }
class CompDivWrapper extends Component { render() { return <div>{ this.props.children }</div>; } }
// Tests
describe('SeeThrough#active-doesnt-crash', () => {
it('handles no children', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY } />
);
});
it('handles a null child', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
{ null }
</SeeThrough>
);
});
it('handles many null children', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
{ null }
{ null }
</SeeThrough>
);
});
it('handles some null children', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
<FuncDivWrapper>{ simpleString }</FuncDivWrapper>
{ null }
<FuncDivWrapper>{ simpleString }</FuncDivWrapper>
<FuncNoopWrapper>{ simpleString }</FuncNoopWrapper>
{ null }
</SeeThrough>
);
});
it('handles a simple FuncNoopWrapper', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
<FuncNoopWrapper>
{ simpleString }
</FuncNoopWrapper>
</SeeThrough>
);
});
it('handles a simple FuncDivWrapper', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
<FuncDivWrapper>
{ simpleString }
</FuncDivWrapper>
</SeeThrough>
);
});
it('handles a simple CompNoopWrapper', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
<CompNoopWrapper>
{ simpleString }
</CompNoopWrapper>
</SeeThrough>
);
});
it('handles a simple CompDivWrapper', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
<CompDivWrapper>
{ simpleString }
</CompDivWrapper>
</SeeThrough>
);
});
it('handles lone text', () => {
expectNoCrash(
<SeeThrough active childSearchDepth={ Number.POSITIVE_INFINITY }>
{ simpleString }
</SeeThrough>
);
});
});
describe('SeeThrough#childSearchDepth#boxes', () => {
const boxes = childSearchDepth => (
<SeeThrough childSearchDepth={ childSearchDepth } active>
{ box(20, 20) }
<div style={{ display: 'inline-block' }}>
{ box(20, 20) }
</div>
{ box(20, 20) }
</SeeThrough>
);
it('should compute an empty rectangle for depth = 0', () => {
expectBounds(boxes(0), { x: 0, y: 0, width: 0, height: 0 });
});
it('should account for all boxes for depth > 0', () => {
// Cypress fun. expectBounds is async (with special CypressPromises) so to have multiple
// expectBounds in one test, we have to write our test this way.
cy.wrap(null)
.then(() => expectBounds(boxes(1), { x: 0, y: 0, width: 20, height: 60 }))
.then(() => expectBounds(boxes(2), { x: 0, y: 0, width: 20, height: 60 }))
.then(() => expectBounds(boxes(3), { x: 0, y: 0, width: 20, height: 60 }));
});
});
describe('SeeThrough#childSearchDepth#absoluteBoxes', () => {
const boxes = childSearchDepth => (
<SeeThrough childSearchDepth={ childSearchDepth } active>
{ box(20, 20) }
<div style={{ display: 'inline-block' }}>
<div style={{ position: 'absolute', top: 0, left: 0 }}>
<div style={{ position: 'fixed', top: 0, left: 0 }}>
{ box(300, 200) }
</div>
{ box(200, 160) }
</div>
</div>
{ box(20, 20) }
</SeeThrough>
);
it('should compute an empty rectangle for depth = 0', () => {
expectBounds(boxes(0), { x: 0, y: 0, width: 0, height: 0 });
});
it('should not see the absolute box at depth = 1', () => {
expectBounds(boxes(1), { x: 0, y: 0, width: 20, height: 40 });
});
it('should see the absolute box at depth = 2', () => {
expectBounds(boxes(2), { x: 0, y: 0, width: 200, height: 160 });
});
it('should see the fixed box at depth = 3', () => {
expectBounds(boxes(3), { x: 0, y: 0, width: 300, height: 200 });
});
});
describe('SeeThrough#childSearchDepth#edgeElements', () => {
it('should ignore the size of SVG children', () => {
expectBounds(
<SeeThrough childSearchDepth={ Number.POSITIVE_INFINITY } childTagsToSkip={ ['svg'] } active>
{ box(20, 20) }
<div style={{ display: 'inline-block' }}>
<svg viewBox='0 0 30 30' width='30' height='30'>
<circle cx='5000' cy='5000' r='5000' />
</svg>
</div>
</SeeThrough>,
{ x: 0, y: 0, width: 30, height: 50 },
);
});
it('should correctly compute the absolute bounding box for an SVG in an arbitrary position', () => {
expectBounds(
<SeeThrough childSearchDepth={ Number.POSITIVE_INFINITY } childTagsToSkip={ ['svg'] } active>
<div style={{ display: 'inline-block', marginTop: 500, marginLeft: 500 }}>
<svg viewBox='0 0 30 30' width='30' height='30'>
<circle cx='5000' cy='5000' r='5000' />
</svg>
</div>
</SeeThrough>,
{ x: 500, y: 500, width: 30, height: 30 },
);
});
});
describe('SeeThrough#childSearchDepth#textNodes', () => {
it('should correctly compute the size of text nodes', () => {
expectBounds(
<SeeThrough childSearchDepth={ Number.POSITIVE_INFINITY } active>
{ box(5, 5) }
This text should be longer than the box
</SeeThrough>,
{ x: 0, y: 0, width: 207, height: 19 },
);
});
});
describe('SeeThrough#multiple', () => {
it('should correctly compute the bounds of multiple active SeeThroughs', () => {
expectBounds(
<SeeThroughController>
<div style={{ display: 'inline-block' }}>
<SeeThrough active>
{ box(5, 5) }
</SeeThrough>
<SeeThrough active>
{ box(5, 5) }
</SeeThrough>
</div>
</SeeThroughController>,
{ x: 0, y: 0, width: 5, height: 10 },
);
});
});
|
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-11-29_23-59-58.wav 1638230398.742892 -10.324089
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-11-30_23-59-57.wav 1638316797.857131 -10.286642
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-01_23-59-56.wav 1638403196.974783 -10.385579
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-02_23-59-56.wav 1638489596.081180 -10.399182
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-03_23-59-55.wav 1638575995.187612 -10.373359
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-04_23-59-54.wav 1638662394.296926 -10.377996
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-05_23-59-53.wav 1638748793.406011 -10.413027
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-06_23-59-52.wav 1638835192.511207 -10.296142
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-07_23-59-51.wav 1638921591.628096 -10.392523
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-08_23-59-50.wav 1639007990.735451 -10.401091
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-09_23-59-49.wav 1639094389.842175 -10.384043
./freq-measure2.sh JJ1BDX_Z_9999kHz__2021-12-10_23-59-48.wav 1639180788.952859 -10.309056
|
import getUrlsFromPages from '../urlManipulation/getUrlsFromPages'
export default async function getUrlsFromPagesCLI(
url: string,
numberOfPages: number,
debug: boolean = false
): Promise<string[]> {
process.stdout.write(' Getting URLs from pages...')
let failures = 0
const urls: string[] = await getUrlsFromPages(
url,
numberOfPages,
(current, max, success) => {
if (!success) failures++
process.stdout.write(
`\r Getting URLs from pages... ${Math.round(
(current / max) * 100
)}% done (${current}/${max})${failures ? `. Failure happened ${failures} times` : ''}`
)
},
debug
).catch(Promise.reject)
process.stdout.write('\r✔ Getting URLS from pages... 100% done!\n')
return urls
}
|
<reponame>jcesarmobile/WebViewTests<filename>WebViewTests/AppDelegate.h<gh_stars>0
//
// AppDelegate.h
// WebViewTests
//
// Created by <NAME> on 28/11/17.
// Copyright © 2017 jcesarmobile. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
<filename>src/test/java/br/com/alinesolutions/anotaai/test/criptografia/CriptografiaTest.java<gh_stars>0
package br.com.alinesolutions.anotaai.test.criptografia;
import org.junit.Assert;
import org.junit.Test;
import br.com.alinesolutions.anotaai.infra.Criptografia;
public class CriptografiaTest {
@Test
public void testCriptografia() {
// teste_criptografia
String actual = "27352B8FFCA83E660FB974DD5CA3F61A7E4E1A0CAC1BB57CF244D371CAEDBCC2";
String senhaCriptografada = Criptografia.criptografar("teste_criptografia");
Assert.assertEquals(senhaCriptografada, actual);
}
}
|
export function insert(...value: any[]): (toArr: any, toPosition?: any, atIndex?: any) => Insert;
export function insertBefore(...value: any[]): (toArr: any, atIndex: any) => any;
export function insertAfter(...value: any[]): (toArr: any, atIndex: any) => any;
declare class Insert {
constructor(valArr: any, toArr: any);
valArr: any;
toArr: any;
first(): any[];
last(): any[];
before(index: any): any;
after(index: any): any;
}
export {};
|
package main.client.connector;
public interface Callback<T> {
public void call(T obj,Throwable exception);
} |
# frozen_string_literal: true
class Twords
# include ConfigAccessable to access shared configuration settings
module ConfigAccessible
module_function
# Provides a private method to access the shared config when included in a Module or Class
#
# @return [Twords::Configuration]
def config
Twords.config
end
end
end
|
<filename>src/components/notification/notification_event.tsx
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React, { FunctionComponent, ReactElement, createElement } from 'react';
import classNames from 'classnames';
import {
EuiNotificationEventMeta,
EuiNotificationEventMetaProps,
} from './notification_event_meta';
import {
EuiNotificationEventMessages,
EuiNotificationEventMessagesProps,
} from './notification_event_messages';
import {
EuiNotificationEventReadButton,
EuiNotificationEventReadButtonProps,
} from './notification_event_read_button';
import { EuiButtonEmpty, EuiButtonEmptyProps } from '../button';
import { EuiLink } from '../link';
import { EuiContextMenuItem, EuiContextMenuItemProps } from '../context_menu';
import { useGeneratedHtmlId } from '../../services';
import { EuiNotificationEventReadIcon } from './notification_event_read_icon';
export type EuiNotificationHeadingLevel = 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
export type EuiNotificationEventProps = Omit<
EuiNotificationEventMetaProps,
'onOpenContextMenu' | 'onRead' | 'eventName' | 'id'
> &
Omit<
EuiNotificationEventReadButtonProps,
'onClick' | 'color' | 'eventName' | 'isRead' | 'id'
> & {
/**
* A unique identifier
*/
id: string;
/**
* The title of the event.
*/
title: string;
/**
* The heading level of the title.
*/
headingLevel?: EuiNotificationHeadingLevel;
/**
* Returns the `id` and applies an `onClick` handler to the title.
*/
onClickTitle?: (id: string) => void;
/**
* The label of the primary action
*/
primaryAction?: string;
/**
* Apply more props to the `primaryAction` button. See #EuiPrimaryActionProps.
*/
primaryActionProps?: EuiButtonEmptyProps;
/**
* Returns the `id` and applies an `onClick` handler to the `primaryAction`.
*/
onClickPrimaryAction?: (id: string) => void;
/**
* Notification messages as an array of strings. More than one message wraps in an accordion.
*/
messages: EuiNotificationEventMessagesProps['messages'];
/**
* Shows an indicator of the read state of the event. Leave as `undefined` to hide the indicator.
*/
isRead?: boolean | undefined;
/**
* Returns the `id` and `isRead` state. Applies an `onClick` handler to the `read` indicator.
*/
onRead?: (id: string, isRead: boolean) => void;
/**
* Provided the `id` of the event must return an array of #EuiContextMenuItem elements.
*/
onOpenContextMenu?: (
id: string
) => Array<
ReactElement<EuiContextMenuItemProps, typeof EuiContextMenuItem>
>;
};
export const EuiNotificationEvent: FunctionComponent<EuiNotificationEventProps> = ({
id,
type,
severity,
badgeColor,
iconType,
iconAriaLabel,
time,
title,
isRead,
primaryAction,
primaryActionProps,
messages,
onRead,
onOpenContextMenu,
onClickTitle,
onClickPrimaryAction,
headingLevel = 'h2',
}) => {
const classes = classNames('euiNotificationEvent', {
'euiNotificationEvent--withReadState': typeof isRead === 'boolean',
});
const classesTitle = classNames('euiNotificationEvent__title', {
'euiNotificationEvent__title--isRead': isRead,
});
const randomHeadingId = useGeneratedHtmlId();
const titleProps = {
id: randomHeadingId,
className: classesTitle,
'data-test-subj': `${id}-notificationEventTitle`,
};
return (
<article aria-labelledby={randomHeadingId} className={classes} key={id}>
{typeof isRead === 'boolean' && (
<div className="euiNotificationEvent__readButton">
{!!onRead ? (
<EuiNotificationEventReadButton
isRead={isRead}
onClick={() => onRead(id, isRead)}
eventName={title}
id={id}
/>
) : (
<EuiNotificationEventReadIcon
id={id}
isRead={isRead}
eventName={title}
/>
)}
</div>
)}
<div className="euiNotificationEvent__content">
<EuiNotificationEventMeta
id={id}
type={type}
severity={severity}
badgeColor={badgeColor}
iconType={iconType}
iconAriaLabel={iconAriaLabel}
time={time}
onOpenContextMenu={
onOpenContextMenu ? () => onOpenContextMenu(id) : undefined
}
eventName={title}
/>
{onClickTitle ? (
<EuiLink onClick={() => onClickTitle(id)} {...titleProps}>
{createElement(headingLevel, null, title)}
</EuiLink>
) : (
createElement(headingLevel, titleProps, title)
)}
<EuiNotificationEventMessages messages={messages} eventName={title} />
{onClickPrimaryAction && primaryAction && (
<div className="euiNotificationEvent__primaryAction">
<EuiButtonEmpty
flush="left"
size="s"
{...primaryActionProps}
onClick={() => onClickPrimaryAction?.(id)}
data-test-subj={`${id}-notificationEventPrimaryAction`}
>
{primaryAction}
</EuiButtonEmpty>
</div>
)}
</div>
</article>
);
};
|
package com.cgs.kerberos.client.handle;
import java.util.Date;
import com.cgs.kerberos.bean.FirstRequest;
import com.cgs.kerberos.bean.FirstResponse;
import com.cgs.kerberos.bean.TgtResponse;
import com.cgs.kerberos.client.bean.FirstResponseWrapper;
import com.cgs.kerberos.exception.AesSecurityException;
import com.cgs.kerberos.exception.PasswordError;
import com.cgs.kerberos.util.SecurityUtil;
import com.cgs.kerberos.util.Serializer;
public class TgtClientAesProcessor implements TgtClientProcessor{
private ClientDatabaseProcessor databaseProcessor;
private Serializer serializer;
public void setSerializer(Serializer serializer) {
this.serializer = serializer;
}
public void setDatabaseProcessor(ClientDatabaseProcessor databaseProcessor) {
this.databaseProcessor = databaseProcessor;
}
public TgtClientAesProcessor(){
this.databaseProcessor=new FileClientDatabaseProcessor();
}
public TgtClientAesProcessor(String path){
this.databaseProcessor=new FileClientDatabaseProcessor(path);
}
public FirstResponseWrapper getTgtResponse(FirstResponse firstResponse) {
String password=databaseProcessor.getPassord();
byte[] bytes=firstResponse.getTgtReponse();
try{
bytes=SecurityUtil.decryptAes(bytes, password);
TgtResponse result=(TgtResponse) serializer.byte2Object(bytes);
FirstResponseWrapper firstResponseWrapper=new FirstResponseWrapper();
firstResponseWrapper.setTgt(firstResponse.getTgt());
firstResponseWrapper.setTgtResponse(result);
return firstResponseWrapper;
}catch(AesSecurityException e){
throw new PasswordError("Password is error;Client's password is different from KDC's your password");
}
}
public FirstRequest getFirstRequest(long lifeTime) {
String name=databaseProcessor.getName();
return getFirstRequest(name, lifeTime);
}
// public byte[] getFirstRequestByte(long lifeTime){
// FirstRequest firstRequest=getFirstRequest(lifeTime);
// byte[] bytes=serializer.object2Byte(firstRequest);
// return bytes;
// }
//
// public byte[] getFirstRequestByte(String name,long lifeTime){
// FirstRequest firstRequest=getFirstRequest(name,lifeTime);
// byte[] bytes=serializer.object2Byte(firstRequest);
// return bytes;
// }
public FirstRequest getFirstRequest(String name, long lifeTime) {
FirstRequest firstRequest=new FirstRequest();
firstRequest.setName(name);
firstRequest.setTimestamp(new Date());
firstRequest.setLifeTime(lifeTime);
return firstRequest;
}
}
|
#!/bin/bash
# Copyright (c) 2013-2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
BUILDDIR="/home/advantage/v6"
EXEEXT=""
# These will turn into comments if they were disabled when configuring.
ENABLE_WALLET=1
ENABLE_UTILS=1
ENABLE_BITCREDITD=1
REAL_BITCREDITD="$BUILDDIR/src/advantagecoind${EXEEXT}"
REAL_BITCREDITCLI="$BUILDDIR/src/advantagecoin-cli${EXEEXT}"
|
<filename>node_modules/react-icons-kit/typicons/arrowMinimise.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrowMinimise = void 0;
var arrowMinimise = {
"viewBox": "0 0 24 24",
"children": [{
"name": "path",
"attribs": {
"d": "M6.121 13c-.553 0-1 .448-1 1s.447 1 1 1h1.465l-3.293 3.293c-.391.391-.391 1.023 0 1.414.195.195.451.293.707.293s.512-.098.707-.293l3.414-3.414v1.707c0 .552.447 1 1 1s.879-.448.879-1v-5h-4.879zM7 11c.552 0 1-.448 1-1v-2h2c.553 0 1-.448 1-1s-.447-1-1-1h-3.999l-.001 4c0 .552.447 1 1 1zM17 13c-.553 0-1 .448-1 1v2h-2c-.553 0-1 .448-1 1s.447 1 1 1h4v-4c0-.552-.447-1-1-1zM18.293 4.293l-3.293 3.293v-1.586c0-.552-.447-1-1-1s-1 .448-1 1v5h5c.552 0 1-.448 1-1s-.447-1-1-1h-1.586l3.293-3.292c.391-.391.391-1.023 0-1.414s-1.023-.392-1.414-.001z"
},
"children": []
}]
};
exports.arrowMinimise = arrowMinimise; |
## GIT aliases
# I had to make these to ease working with git in projects that use commitizen,
# since it's kind of awkward to work both in a client like Fork and in terminal.
# Commitizen, actually related to both git and npm, but w/e
alias cz="git-cz" # -> Run Commitizen CLI
# Repository status
alias gs="git status" # -> Status
# Pushing/pulling in the current branch
alias gl="git pull" # -> Pull
alias gp="git push" # -> Push
# Resetting staged changes
alias gr="git reset --" # -> Unstage specified files
alias gra="git reset" # -> Unstage everything
alias grl="git reset --soft HEAD~1" # -> Softly reset the last commit
alias grc="git reset --soft" # (Hash) -> Softly reset specified commit
# Staging changes
alias gai="git add --interactive" # -> Stage changes interactively
alias gaa="git add ." # -> Stage all changes
alias gam="git add" # (...Files) -> Stage specified files
# Committing changes
alias gcd="git commit" # -> Commit staged changes using the default editor
alias gcm="git commit -m" # (Message) -> Commit staged changes inline
# Switching to branches/commits
alias gch="git checkout" # (Branch/Hash) -> Switch to a branch or commit
alias gcb="git checkout -b" # (Branch) -> Create a new branch and switch to it
# Pretty git log
GIT_LOG_FORMAT="%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset"
alias glg="git log --graph --pretty=format:'$GIT_LOG_FORMAT' --abbrev-commit"
|
<filename>community-modules/core/src/ts/widgets/agList.ts
import { AgAbstractField } from "./agAbstractField";
import { Component } from "./component";
import { PostConstruct } from "../context/context";
import { escapeString } from "../utils/string";
import { addCssClass, removeCssClass } from "../utils/dom";
import { findIndex } from "../utils/array";
import { KeyCode } from '../constants/keyCode';
import { setAriaSelected } from '../utils/aria';
export interface ListOption {
value: string;
text?: string;
}
export class AgList extends Component {
public static EVENT_ITEM_SELECTED = 'selectedItem';
private static ACTIVE_CLASS = 'ag-active-item';
private options: ListOption[] = [];
private itemEls: HTMLElement[] = [];
private highlightedEl: HTMLElement;
private value: string | null;
private displayValue: string | null;
constructor(private readonly cssIdentifier = 'default') {
super(/* html */`<div class="ag-list ag-${cssIdentifier}-list" role="listbox"></div>`);
}
@PostConstruct
private init(): void {
this.addManagedListener(this.getGui(), 'keydown', this.handleKeyDown.bind(this));
}
private handleKeyDown(e: KeyboardEvent): void {
const key = e.keyCode;
switch (key) {
case KeyCode.ENTER:
if (!this.highlightedEl) {
this.setValue(this.getValue());
} else {
const pos = this.itemEls.indexOf(this.highlightedEl);
this.setValueByIndex(pos);
}
break;
case KeyCode.DOWN:
case KeyCode.UP:
const isDown = key === KeyCode.DOWN;
let itemToHighlight: HTMLElement;
e.preventDefault();
if (!this.highlightedEl) {
itemToHighlight = this.itemEls[isDown ? 0 : this.itemEls.length - 1];
} else {
const currentIdx = this.itemEls.indexOf(this.highlightedEl);
let nextPos = currentIdx + (isDown ? 1 : -1);
nextPos = Math.min(Math.max(nextPos, 0), this.itemEls.length - 1);
itemToHighlight = this.itemEls[nextPos];
}
this.highlightItem(itemToHighlight);
break;
}
}
public addOptions(listOptions: ListOption[]): this {
listOptions.forEach(listOption => this.addOption(listOption));
return this;
}
public addOption(listOption: ListOption): this {
const { value, text } = listOption;
const sanitisedText = escapeString(text || value);
this.options.push({ value, text: sanitisedText });
this.renderOption(value, sanitisedText);
return this;
}
private renderOption(value: string, text: string): void {
const itemEl = document.createElement('div');
itemEl.setAttribute('role', 'option');
addCssClass(itemEl, 'ag-list-item');
addCssClass(itemEl, `ag-${this.cssIdentifier}-list-item`);
itemEl.innerHTML = `<span>${text}</span>`;
itemEl.tabIndex = -1;
this.itemEls.push(itemEl);
this.addManagedListener(itemEl, 'mouseover', () => this.highlightItem(itemEl));
this.addManagedListener(itemEl, 'mouseleave', () => this.clearHighlighted());
this.addManagedListener(itemEl, 'click', () => this.setValue(value));
this.getGui().appendChild(itemEl);
}
public setValue(value?: string, silent?: boolean): this {
if (this.value === value) {
this.fireItemSelected();
return this;
}
if (value == null) {
this.reset();
return this;
}
const idx = findIndex(this.options, option => option.value === value);
if (idx !== -1) {
const option = this.options[idx];
this.value = option.value;
this.displayValue = option.text != null ? option.text : option.value;
this.highlightItem(this.itemEls[idx]);
if (!silent) {
this.fireChangeEvent();
}
}
return this;
}
public setValueByIndex(idx: number): this {
return this.setValue(this.options[idx].value);
}
public getValue(): string | null {
return this.value;
}
public getDisplayValue(): string | null {
return this.displayValue;
}
public refreshHighlighted(): void {
this.clearHighlighted();
const idx = findIndex(this.options, option => option.value === this.value);
if (idx !== -1) {
this.highlightItem(this.itemEls[idx]);
}
}
private reset(): void {
this.value = null;
this.displayValue = null;
this.clearHighlighted();
this.fireChangeEvent();
}
private highlightItem(el: HTMLElement): void {
if (!el.offsetParent) { return; }
this.clearHighlighted();
this.highlightedEl = el;
addCssClass(this.highlightedEl, AgList.ACTIVE_CLASS);
setAriaSelected(this.highlightedEl, true);
this.highlightedEl.focus();
}
private clearHighlighted(): void {
if (!this.highlightedEl || !this.highlightedEl.offsetParent) { return; }
removeCssClass(this.highlightedEl, AgList.ACTIVE_CLASS);
setAriaSelected(this.highlightedEl, false);
this.highlightedEl = null;
}
private fireChangeEvent(): void {
this.dispatchEvent({ type: AgAbstractField.EVENT_CHANGED });
this.fireItemSelected();
}
private fireItemSelected(): void {
this.dispatchEvent({ type: AgList.EVENT_ITEM_SELECTED });
}
}
|
def sum_array(arr):
"""This function will find the sum of all elements in an array using recursion."""
# if the array is empty, return 0
if not arr:
return 0
# get the last element in the array
last = arr[-1]
# find the sum of the remainder of the array
remainder_sum = sum_array(arr[:-1])
# return the sum of the last element and the remainder of the array
return last + remainder_sum |
fn process_transactions(transactions: Vec<Transaction>) -> Result<(), Error> {
const BATCH: usize = 100; // Maximum batch size
let mut batch = Vec::new(); // Initialize an empty batch
let mut pb = ProgressBar::new(transactions.len() as u64); // Initialize progress bar
for transaction in transactions {
// Process each transaction
batch.push(transaction); // Add the transaction to the batch
if batch.len() >= BATCH {
// If the batch size exceeds the threshold, write the batch to the database
chain_db.write(&batch)?;
batch.clear(); // Clear the batch
}
pb.inc(1); // Increment the progress bar
}
if !batch.is_empty() {
// Write any remaining transactions to the database
chain_db.write(&batch)?;
}
Ok(()) // Return Ok if processing is successful
} |
package com.netcracker.ncstore.repository;
import com.netcracker.ncstore.model.ProductPrice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.Locale;
import java.util.UUID;
public interface ProductPriceRepository extends JpaRepository<ProductPrice, UUID> {
@Query("select p from ProductPrice p where p.product.id = ?1 and p.locale = ?2")
ProductPrice findByProductIDAndLocale(UUID id, Locale locale);
@Modifying
@Query("delete from ProductPrice p where p.product.id = ?1")
int deleteByProductId(UUID id);
} |
<reponame>Scrickers/Mitsuki
const Dispatcher = require("./dispatcher")
class Queue extends Map {
constructor(client, iterable) {
super(iterable);
this.client = client
}
async handle(node, track, message) {
track.user = message.author
const exist = this.get(message.guild.id)
if (!exist) {
const player = await node.joinVoiceChannel({
guildID: message.guild.id,
voiceChannelID: message.member.voice.channelID
})
const dispatcher = new Dispatcher({
client: this.client,
guild: message.guild,
message: message,
player
});
dispatcher.queue.push(track);
this.set(message.guild.id, dispatcher);
return dispatcher;
}
exist.queue.push(track);
return null;
}
}
module.exports = Queue
|
# !/bin/bash
VERSION=$1
BUILD=$2
DATE=`date +%Y-%m-%d`
PLATFORMS="macos linux"
if [[ -z $VERSION || -z $BUILD ]]; then
echo "Missing version or build"
exit 1
fi
for PLATFORM in $PLATFORMS; do
OUT="flint-$VERSION-snapshot-$DATE-$BUILD-$PLATFORM"
git tag -a $OUT -m "$PLATFORM $DATE development snapshot for $VERSION$BUILD"
done
|
#!/bin/bash
while getopts "s:t:b" opt; do
case $opt in
s)
src=$OPTARG
;;
t)
tgt=$OPTARG
;;
b)
if [ -z "$src" ] || [ -z "$tgt" ]; then
echo "Source and target directories are required."
exit 1
fi
if [ ! -d "$src" ]; then
echo "Source directory does not exist."
exit 1
fi
if [ ! -d "$tgt" ]; then
echo "Target directory does not exist. Creating target directory..."
mkdir -p "$tgt"
fi
cp -r "$src"/* "$tgt"
echo "Backup completed successfully."
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done |
<filename>src/components/App.js
import React from 'react'
import Signup from './Signup'
import { AuthProvider } from '../contexts/AuthContext'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import PrivateRoute from './PrivateRoute'
import GuestRoute from './GuestRoute'
import Header from './Header'
import Footer from './Footer'
import Home from './Home'
import CreateReview from './CreateReview'
import DisplayReview from './DisplayReview'
import Profile from './Profile'
import EditReview from './EditReview'
function App() {
return (
<Router>
<AuthProvider>
<Header />
<Switch>
<Route exact path="/" component={Home} />
<GuestRoute path="/signup" component={Signup} />
<PrivateRoute path="/createreview" component={CreateReview} />
<PrivateRoute path="/profile" component={Profile} />
<PrivateRoute exact path={'/shop/:id'} component={DisplayReview} />
<PrivateRoute exact path={'/review/edit/:id'} component={EditReview} />
</Switch>
<Footer />
</AuthProvider>
</Router>
)
}
export default App
|
import string
from panda3d.core import TextProperties, TextPropertiesManager, VBase4
from direct.showbase.PythonUtil import Functor
from direct.showbase.PythonUtil import report
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.DirectObject import *
from direct.distributed.ClockDelta import *
from direct.interval.IntervalGlobal import *
from direct.distributed.MsgTypes import *
from direct.distributed import DistributedNode
from direct.task import Task
from direct.gui import DirectLabel
from direct.actor import Actor
from direct.distributed import PyDatagram
from direct.gui.OnscreenText import OnscreenText
from direct.gui.DirectGui import DirectWaitBar, DGG
from direct.gui.DirectGui import *
from direct.fsm.StatePush import FunctionCall, StateVar
from otp.nametag import NametagGroup
from otp.nametag.NametagConstants import CFSpeech, CFQuicktalker, CFTimeout
from otp.avatar.DistributedPlayer import DistributedPlayer
from otp.otpbase import OTPLocalizer
from otp.otpbase import OTPGlobals
from otp.chat import ChatGlobals
from otp.otpgui import OTPDialog
from otp.avatar.Avatar import Avatar
from pirates.piratesbase import UserFunnel
from pirates.effects.LevelUpEffect import LevelUpEffect
from pirates.battle.DistributedBattleAvatar import DistributedBattleAvatar, MinimapBattleAvatar
from pirates.battle import WeaponGlobals
from pirates.battle.EnemySkills import *
from pirates.pirate.DistributedPirateBase import DistributedPirateBase
from pirates.pirate import Biped
from pirates.pirate.PAvatarHandle import PAvatarHandle
from pirates.demo import DemoGlobals
from pirates.quest.DistributedQuestAvatar import DistributedQuestAvatar
from pirates.world.LocationConstants import LocationIds
from pirates.piratesbase import PLocalizer
from pirates.piratesbase import PiratesGlobals
from pirates.piratesgui import PiratesGuiGlobals, NamePanelGui, PDialog
from pirates.piratesbase import TeamUtils
from pirates.minigame import Fish, FishingGlobals
from pirates.npc import Skeleton
from pirates.pirate import AvatarTypes
from pirates.effects.VoodooAura import VoodooAura
from pirates.uberdog.UberDogGlobals import InventoryType
from pirates.reputation import ReputationGlobals
import PlayerPirateGameFSM
from pirates.band import BandConstance
from pirates.band import DistributedBandMember
from pirates.world.DistributedGameArea import DistributedGameArea
from pirates.world.DistributedIsland import DistributedIsland
from pirates.speedchat import PSCDecoders
from pirates.battle import Consumable
from pirates.piratesbase import Freebooter
from pirates.uberdog.UberDogGlobals import *
from pirates.minigame import PotionGlobals
from pirates.battle import EnemyGlobals
from pirates.inventory import ItemGlobals
from pirates.pirate import AvatarTypes
from pirates.creature.Alligator import Alligator
from pirates.creature.Scorpion import Scorpion
from pirates.creature.Crab import Crab
from pirates.creature import DistributedCreature
from pirates.movement.MotionFSM import MotionFSM
from pirates.effects.WaterRipple import WaterRipple
from pirates.effects.WaterRippleWake import WaterRippleWake
from pirates.effects.WaterRippleSplash import WaterRippleSplash
from pirates.effects.HealSparks import HealSparks
from pirates.effects.HealRays import HealRays
from pirates.piratesgui import CrewIconSelector
from pirates.coderedemption import CodeRedemption
from pirates.pvp import PVPGlobals
from pirates.pirate import TitleGlobals
from pirates.effects.InjuredEffect import InjuredEffect
from otp.otpbase import OTPRender
from pirates.audio.SoundGlobals import loadSfx
from pirates.audio import SoundGlobals
from pirates.makeapirate import ClothingGlobals
from pirates.pirate import PlayerStateGlobals
from pirates.economy.StowawayGUI import StowawayGUI
import random
import copy
import time
from pirates.ai import HolidayGlobals
from math import sin
from math import cos
from math import pi
from pirates.piratesgui.DialMeter import DialMeter
from pirates.quest import QuestDB
from pirates.piratesbase import Freebooter
from pirates.inventory import ItemConstants
from pirates.util.BpDb import *
class bp:
bpdb = BpDb()
loginCfg = bpdb.bpPreset(iff = False, cfg = 'loginCfg', static = 1)
class DistributedPlayerPirate(DistributedPirateBase, DistributedPlayer, DistributedBattleAvatar, DistributedQuestAvatar, PAvatarHandle):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPirate')
wantBattle = base.config.GetBool('want-battle', 1)
deferrable = True
GoldFounderIcon = None
SilverFounderIcon = None
crewIconId = None
tempDoubleXPStatus = None
badgeIconDict = None
gmNameTag = None
confusedIcon = None
def __init__(self, cr):
try:
pass
except:
self.DistributedPirate_initialized = 1
self.onWelcomeWorld = False
if not self.GoldFounderIcon:
gui = loader.loadModel('models/gui/toplevel_gui')
self.GoldFounderIcon = gui.find('**/founders_coin').copyTo(NodePath('coinTop'))
self.GoldFounderIcon.setScale(2.7999999999999998)
self.SilverFounderIcon = gui.find('**/founders_silver_coin').copyTo(NodePath('coinTop'))
self.SilverFounderIcon.setScale(2.7999999999999998)
tpMgr = TextPropertiesManager.getGlobalPtr()
tpMgr.setGraphic('goldFounderIcon', self.GoldFounderIcon)
tpMgr.setGraphic('silverFounderIcon', self.SilverFounderIcon)
gold = TextProperties()
gold.setTextColor(1, 0.80000000000000004, 0.40000000000000002, 1)
tpMgr.setProperties('goldFounder', gold)
silver = TextProperties()
silver.setTextColor(0.75, 0.75, 0.75, 1)
tpMgr.setProperties('silverFounder', silver)
crewPurpleColor = TextProperties()
crewPurpleColor.setTextColor(0.90000000000000002, 0.5, 1.0, 1)
tpMgr.setProperties('crewPurple', crewPurpleColor)
afkGrayColor = TextProperties()
afkGrayColor.setTextColor(0.5, 0.5, 0.5, 1)
tpMgr.setProperties('afkGray', afkGrayColor)
injuredRedColor = TextProperties()
injuredRedColor.setTextColor(1.0, 0.0, 0.0, 1)
tpMgr.setProperties('injuredRed', injuredRedColor)
ignoredPinkColor = TextProperties()
ignoredPinkColor.setTextColor(1.0, 0.0, 1.0, 1)
tpMgr.setProperties('ignoredPink', ignoredPinkColor)
injuredRedTimerColor = TextProperties()
injuredRedTimerColor.setTextColor(1.0, 0.0, 0.0, 1)
injuredRedTimerColor.setTextScale(2.0)
tpMgr.setProperties('injuredRedTimer', injuredRedTimerColor)
if not self.tempDoubleXPStatus:
x2XPGui = loader.loadModel('models/gui/toplevel_gui')
self.x2XPIcon = gui.find('**/2xp')
self.x2XPIcon.setScale(4.5)
tpMgr.setGraphic('x2XPAwardIcon', self.x2XPIcon)
if not self.crewIconId:
self.crewIconId = True
crewIconGui = loader.loadModel(CrewIconSelector.CREW_ICON_BAM)
self.crewIconDict = { }
for (k, v) in CrewIconSelector.CREW_ICONS.iteritems():
np = crewIconGui.find('**/%s' % v)
self.crewIconDict[k] = np.copyTo(NodePath())
self.crewIconDict[k].setScale(8.8000000000000007)
if k == 1:
np = crewIconGui.find('**/icon_glow')
self.myCrewColorGlow = np.copyTo(self.crewIconDict[k])
self.myCrewColorGlow.setScale(1.25)
self.myCrewColorGlow.setColor(0, 1, 0, 1)
elif k == 2:
np = crewIconGui.find('**/icon_glow')
self.otherCrewColorGlow = np.copyTo(self.crewIconDict[k])
self.otherCrewColorGlow.setScale(1.25)
self.otherCrewColorGlow.setColor(1, 0, 0, 1)
tpMgr.setGraphic('crewIcon%s' % k, self.crewIconDict[k])
if not self.badgeIconDict:
self.badgeIconDict = { }
for titleId in TitleGlobals.TitlesDict.keys():
titleModel = loader.loadModel(TitleGlobals.getModelPath(titleId))
for rank in range(TitleGlobals.getMaxRank(titleId) + 1):
icName = TitleGlobals.getIconName(titleId, rank)
if not icName:
continue
icon = titleModel.find('**/' + icName)
if not icon or icon.isEmpty():
continue
imgScale = TitleGlobals.getScale(titleId)
icon.setScale(0.70999999999999996 * imgScale)
iconKey = 'badge-%s-%s' % (titleId, rank)
self.badgeIconDict[iconKey] = icon
tg = TextGraphic(icon, -0.25, 0.75, -0.31, 0.68999999999999995)
tpMgr.setGraphic(iconKey, tg)
if not self.gmNameTag:
self.gmNameTagIcon = loader.loadModel('models/gui/gmLogo_tflip')
self.gmNameTagIcon.setScale(2.5)
tpMgr.setGraphic('gmNameTagLogo', self.gmNameTagIcon)
gmGoldColor = TextProperties()
gmGoldColor.setTextColor(1, 0.90000000000000002, 0.69999999999999996, 1)
tpMgr.setProperties('goldGM', gmGoldColor)
gmRedColor = TextProperties()
gmRedColor.setTextColor(1.0, 0.10000000000000001, 0.10000000000000001, 1)
tpMgr.setProperties('redGM', gmRedColor)
gmGreenColor = TextProperties()
gmGreenColor.setTextColor(0.29999999999999999, 0.69999999999999996, 0.25, 1)
tpMgr.setProperties('greenGM', gmGreenColor)
gmBlueColor = TextProperties()
gmBlueColor.setTextColor(0.34999999999999998, 0.69999999999999996, 1, 1)
tpMgr.setProperties('blueGM', gmBlueColor)
gmWhiteColor = TextProperties()
gmWhiteColor.setTextColor(1, 1, 1, 1)
tpMgr.setProperties('whiteGM', gmWhiteColor)
if not self.confusedIcon:
self.confusedIcon = gui.find('**/pir_t_gui_but_chatIncomplete').copyTo(NodePath('confusedTop'))
self.confusedIcon.setScale(10.0)
tpMgr.setGraphic('confusedIcon', self.confusedIcon)
self.name = ''
self.title = ''
self.lastLoop = None
DistributedPirateBase.__init__(self, cr)
DistributedBattleAvatar.__init__(self, cr)
DistributedPlayer.__init__(self, cr)
DistributedQuestAvatar.__init__(self)
self.inPvp = False
self._inPvpSV = StateVar(self.inPvp)
self.inParlorGame = False
self._zombieSV = StateVar(self.zombie)
self.setPickable(1)
self.interactioneer = None
self.crewShip = None
self.crewShipId = 0
self.pendingSetCrewShip = None
self.activeShipId = 0
self.pendingTeleportMgr = None
self.crewInterest = None
self.captainId = 0
self.chestIcon = None
self.lootCarried = 0
self.inventoryId = 0
self.undead = 0
self.undeadStyle = ''
self.skeleton = None
self.stickyTargets = []
self.attuneEffect = None
self.avatarFriendsList = set()
self.playerFriendsList = set()
self.guildName = PLocalizer.GuildNoGuild
self.guildId = -1
self.guildRank = -1
self.defaultShard = 0
self.returnLocation = ''
self.currentIsland = ''
self.jailCellIndex = 0
self.beacon = None
self.teleportFriendDoId = 0
self._beaconVisibleSV = StateVar(False)
self._pvpTeamSV = StateVar(0)
self.teleportFlags = PiratesGlobals.TFInInitTeleport
self.teleportConfirmCallbacks = { }
self.questRewardFlags = 0
self.bandMember = None
self.gameAccess = OTPGlobals.AccessUnknown
self.founder = False
self.port = 0
self.waterRipple = None
self.waterWake = None
self.waterSplash = None
self.founderIcon = None
self.badge = None
self.shipBadge = None
self.lastPVPSinkTime = 0
self.lastShipPVPDecayTime = 0
self.infamySea = 0
self.lastPVPDefeatTime = 0
self.lastLandPVPDecayTime = 0
self.infamyLand = 0
self.isLookingForCrew = 0
self.tutorialState = 0
self.hasCrewIcon = 0
self.isAFK = False
self.status = 0
self.isPaid = False
self.populated = 0
self.updatePaidStatus()
self.tempDoubleXPStatus = 0
self.tempDoubleXPStatusMessaged = False
self.gmNameTagEnabled = 0
self.gmNameTagColor = 'whiteGM'
self.gmNameTagString = ''
self.BandId = None
self.cursed = False
self.injuredSetup = 0
self.injuredTimeLeft = 0
self.layingOnGround = 0
self.dizzyEffect = None
self.dizzyEffect2 = None
self.beingHealed = False
self.healEffects = []
self.healEffectIval = None
self.isPlundering = 0
self.isConfused = False
self.wlEnabled = False
self.initDazed()
self.creatureId = -1
self.creature = None
self.transformationEffect = None
self.transformationIval = None
self.gTransNodeFwdPt = None
self.cRay = None
self.cRayNode = None
self.lifter = None
self.alligatorSound = loadSfx(SoundGlobals.SFX_MINIGAME_POTION_FX_ALLIGATOR)
self.crabSound = loadSfx(SoundGlobals.SFX_MINIGAME_POTION_FX_CRAB)
self.scorpionSound = loadSfx(SoundGlobals.SFX_MINIGAME_POTION_FX_SCORPION)
self.genericTransformation = loadSfx(SoundGlobals.SFX_MINIGAME_POTION_FX_TRANFORMATION)
self.scaleChangeEffect = None
self.scaleChangeIval = None
self.isGiant = False
self.isTiny = False
self.growSound = loadSfx(SoundGlobals.SFX_MINIGAME_POTION_FX_GROW)
self.shrinkSound = loadSfx(SoundGlobals.SFX_MINIGAME_POTION_FX_SHRINK)
self.crazySkinColorEffect = None
self.crazySkinColorIval = None
self.transformSeqEffect = None
self.injuredFrame = None
self.ghostEffect = None
self.isGhost = 0
self.needRegenFlag = 0
self.bloodFireTime = 0.0
self.auraActivated = 0
self.auraIval = None
self.fishSwivel = NodePath('fishSwivel')
self.shownFish = None
self.shownFishSeq = None
self.popupDialog = None
self.injuredTrack = None
self._DistributedPlayerPirate__surpressedRepFlags = []
self._DistributedPlayerPirate__tutorialEnabled = True
self.swingTrack = None
def disable(self):
DistributedPirateBase.disable(self)
DistributedPlayer.disable(self)
DistributedBattleAvatar.disable(self)
self.exitDialogMode()
self.ignore('localAvatarEntersDialog')
self.ignore('localAvatarExitsDialog')
self.ignore('Local_Efficiency_Set')
self.stopBlink()
self.ignoreAll()
self._showBeaconFC.destroy()
self._decideBeaconFC.destroy()
self.hideBeacon()
self.show(invisibleBits = PiratesGlobals.INVIS_DEATH)
self.stopDizzyEffect()
if self.injuredFrame:
self.injuredFrame.destroy()
if self.auraIval:
self.auraIval.pause()
self.auraIval = None
if not self.isLocal():
if hasattr(base, 'localAvatar'):
base.localAvatar.playersNearby.pop(self.getDoId())
DistributedPlayerPirate._setCreatureTransformation(self, False, 0)
if self.transformationEffect:
self.transformationEffect.detachNode()
self.transformationEffect = None
if self.transformationIval:
self.transformationIval.clearToInitial()
self.transformationIval = None
self.isGiant = False
self.isTiny = False
if self.scaleChangeIval:
self.scaleChangeIval.clearToInitial()
self.scaleChangeIval = None
self.crazyColorSkin = False
if self.crazySkinColorIval:
self.crazySkinColorIval.clearToInitial()
self.crazySkinColorIval = None
if self.transformSeqEffect:
self.transformSeqEffect.detachNode()
self.transformSeqEffect = None
if self.consumable:
self.consumable.delete()
self.consumable = None
self.crewShip = None
if self.pendingSetCrewShip:
self.cr.relatedObjectMgr.abortRequest(self.pendingSetCrewShip)
self.pendingSetCrewShip = None
if self.attuneEffect:
self.attuneEffect.stopLoop()
self.attuneEffect = None
if self.waterRipple:
self.waterRipple.stopLoop()
self.waterRipple = None
if self.waterWake:
self.waterWake.stopLoop()
self.waterWake = None
if self.waterSplash:
self.waterSplash.stopLoop()
self.waterSplash = None
if self.healEffectIval:
self.healEffectIval.pause()
self.healEffectIval = None
for effect in self.healEffects:
effect.stopLoop()
self.healEffects = []
if self.pendingTeleportMgr:
base.cr.relatedObjectMgr.abortRequest(self.pendingTeleportMgr)
self.pendingTeleportMgr = None
taskMgr.remove(self.uniqueName('injuryDial'))
taskMgr.remove(self.uniqueName('createInvasionScoreboard'))
taskMgr.remove(self.uniqueName('bloodFireCharging'))
taskMgr.remove(self.uniqueName('decayInfamySea'))
taskMgr.remove(self.uniqueName('decayInfamyLand'))
self.port = 0
def delete(self):
try:
pass
except:
self.DistributedPlayerPirate_deleted = 1
DistributedPirateBase.delete(self)
DistributedPlayer.delete(self)
DistributedBattleAvatar.delete(self)
DistributedQuestAvatar.delete(self)
if self.skeleton:
self.skeleton.delete()
self.skeleton = None
if self.shownFish:
self.shownFish.destroy()
self.shownFish = None
if self.shownFishSeq:
self.shownFishSeq.pause()
self.shownFishSeq = None
def generate(self):
DistributedPirateBase.generate(self)
DistributedPlayer.generate(self)
DistributedBattleAvatar.generate(self)
self.setDefaultDNA()
self._decideBeaconFC = FunctionCall(self._decideShowBeacon, self._zombieSV, self._inPvpSV, self._pvpTeamSV)
self._decideBeaconFC.pushCurrentState()
self._showBeaconFC = FunctionCall(self._handleShowBeacon, self._beaconVisibleSV, self._pvpTeamSV)
self._showBeaconFC.pushCurrentState()
self.useStandardInteract()
self.setPlayerType(NametagGroup.CCNormal)
def sendAILog(self, errorString):
self.sendUpdate('submitErrorLog', [
errorString])
def useStandardInteract(self):
if not self.isLocal():
if self.getTeam() == localAvatar.getTeam():
allowInteract = False
else:
allowInteract = True
self.setInteractOptions(proximityText = '', mouseOver = 0, mouseClick = 0, isTarget = 1, allowInteract = allowInteract)
if hasattr(base, 'localAvatar'):
base.localAvatar.playersNearby[self.getDoId()] = (self.commonChatFlags, self.whitelistChatFlags)
if len(localAvatar.playersNearby) > 3:
level = base.localAvatar.getLevel()
if level >= 3:
inv = base.localAvatar.getInventory()
if inv:
if not inv.getStackQuantity(InventoryType.PlayerChat):
base.localAvatar.sendRequestContext(InventoryType.PlayerChat)
elif level >= 5 and not inv.getStackQuantity(InventoryType.PlayerProfiles):
base.localAvatar.sendRequestContext(InventoryType.PlayerProfiles)
elif level >= 6 and not inv.getStackQuantity(InventoryType.PlayerInvites):
base.localAvatar.sendRequestContext(InventoryType.PlayerInvites)
elif level >= 7 and not inv.getStackQuantity(InventoryType.TeleportToFriends):
base.localAvatar.sendRequestContext(InventoryType.TeleportToFriends)
elif level >= 8 and not inv.getStackQuantity(InventoryType.UseEmotes):
base.localAvatar.sendRequestContext(InventoryType.UseEmotes)
def setupInjured(self, timeStamp = None, MessageData = None):
if timeStamp == None:
timeStamp = globalClock.getFrameTime()
else:
self.injuredTimeStamp = globalClock.getFrameTime() - timeStamp
self.injuredTimeLeft = int(PiratesGlobals.REVIVE_TIME_OUT - self.injuredTimeStamp)
if not self.isLocal() and not localAvatar.isUndead():
self.acceptOnce('LocalAvatarIsZombie', self.setupInjured, [
None])
sphereScale = 5.0
if localAvatar.guiMgr.combatTray.tonicButton.getBestTonic(allowNone = 1):
self.setInteractOptions(proximityText = PLocalizer.InjuredHasTonic, sphereScale = sphereScale, diskRadius = 7, resetState = 0, offset = Point3(0, -1.5, 0))
else:
self.setInteractOptions(proximityText = PLocalizer.InjuredNeedTonic, sphereScale = sphereScale, diskRadius = 7, resetState = 0, offset = Point3(0, -1.5, 0))
avSphereRad = 1.3999999999999999
if hasattr(localAvatar.controlManager.currentControls, 'cWallSphereNodePath'):
avSphereRad = localAvatar.controlManager.currentControls.cWallSphereNodePath.getBounds().getRadius() + 0.050000000000000003
if self.getDistance(localAvatar) <= sphereScale + avSphereRad and self != localAvatar:
self.request('Proximity')
for index in range(InventoryType.begin_Consumables, InventoryType.end_Consumables):
inv = localAvatar.getInventory()
if inv:
messageName = 'inventoryQuantity-%s-%s' % (inv.doId, index)
self.ignore(messageName)
self.acceptOnce(messageName, self.setupInjured, [
None])
continue
self.injuredSetup = 1
taskMgr.add(self.resizeInjuryFrame, self.uniqueName('injuryDial'))
if not self.injuredFrame:
topGui = loader.loadModel('models/gui/toplevel_gui')
injuredIcon = topGui.find('**/pir_t_gui_gen_medical')
circleBase = topGui.find('**/pir_t_gui_frm_base_circle')
self.injuredFrame = DirectFrame(parent = NodePath(), relief = None, pos = (0.0, 0, 0.0), image = circleBase, image_scale = 2.3999999999999999)
self.injuredDial = DialMeter(parent = self.injuredFrame, meterColor = VBase4(1.0, 0.0, 0.0, 1), baseColor = VBase4(0.10000000000000001, 0.10000000000000001, 0.10000000000000001, 1), wantCover = 0, pos = (0.0, -0.01, 0.0), sortOrder = 1, scale = 0.90000000000000002)
(left, right, bottom, top) = self.injuredDial.getBounds()
tpMgr = TextPropertiesManager.getGlobalPtr()
self.injuredFrame.reparentTo(self.nametag3d)
self.injuredFrame.setZ(5.5)
self.injuredFrame.setBillboardPointEye(1)
self.injuredFrame.setLightOff()
innerFrame = DirectFrame(parent = self.injuredFrame, relief = None, pos = (0.0, -0.029999999999999999, 0.0), image = circleBase, image_scale = 1.8, sortOrder = 2)
icon = DirectFrame(parent = self.injuredFrame, relief = None, pos = (0.0, -0.040000000000000001, 0.0), image = injuredIcon, image_scale = 2.7000000000000002, sortOrder = 3)
knockoutLabel = DirectLabel(parent = self.injuredDial, relief = None, state = DGG.DISABLED, text = '\x01injuredRed\x01\n%s\x02\n' % PLocalizer.InjuredFlag, text_scale = PiratesGuiGlobals.TextScaleLarge * 5, text_align = TextNode.ACenter, text_shadow = PiratesGuiGlobals.TextShadow, text_font = PiratesGlobals.getPirateBoldOutlineFont(), pos = (0.0, 0, -0.40000000000000002), sortOrder = 4)
self.injuredDial.update(self.injuredTimeLeft, PiratesGlobals.REVIVE_TIME_OUT)
self.injuredFrame.show()
self.injuredFrame.setBin('fixed', 0)
self.refreshName()
def resizeInjuryFrame(self, task):
self.injuredFrame.setScale(1.0 + 0.029999999999999999 * camera.getDistance(self))
self.injuryCountDownTask()
return task.cont
def injuryCountDownTask(self, task = None):
localTime = globalClock.getFrameTime()
self.injuredTimeLeft = PiratesGlobals.REVIVE_TIME_OUT - localTime - self.injuredTimeStamp
if self.injuredTimeLeft < 0.0:
self.injuredTimeLeft = 0.0
self.injuredDial.update(self.injuredTimeLeft, PiratesGlobals.REVIVE_TIME_OUT)
def cleanupInjured(self, revived = 0):
self.useStandardInteract()
taskMgr.remove(self.uniqueName('injuryDial'))
if localAvatar.getInventory():
for index in range(InventoryType.begin_Consumables, InventoryType.end_Consumables):
messageName = 'inventoryQuantity-%s-%s' % (localAvatar.getInventory().doId, index)
self.ignore(messageName)
self.injuredSetup = 0
self.injuredFrame.hide()
self.refreshName()
def startHeadShakeIval(self):
self.startDizzyEffect()
self.headShakeIval = None
self.playHeadShake()
def startHeadShakeMixer(self):
self.startDizzyEffect()
self.headShakeIval = None
timeTillShake = 3.0 + random.random() * 6.0
taskMgr.doMethodLater(timeTillShake, self.doHeadShake, 'shake_head_while_injured_Task')
def playHeadShake(self):
if self.headShakeIval:
self.headShakeIval.pause()
self.headShakeIval = None
playAnim = random.choice([
'injured_idle_shakehead',
'injured_idle',
'injured_idle',
'injured_idle'])
self.headShakeIval = Sequence(self.actorInterval(playAnim, blendInT = 0.0, blendOutT = 0.0), Func(self.playHeadShake))
self.headShakeIval.start()
def doHeadShake(self, task):
self.play('injured_idle_shakehead')
timeTillShake = 3.0 + random.random() * 10.0
taskMgr.remove('shake_head_while_injured_Task')
taskMgr.doMethodLater(timeTillShake, self.doHeadShake, 'shake_head_while_injured_Task')
return task.done
def stopHeadShake(self):
if self.headShakeIval:
self.headShakeIval.pause()
self.headShakeIval = None
self.stopDizzyEffect()
taskMgr.remove('shake_head_while_injured_Task')
def startDizzyEffect(self):
if self.dizzyEffect:
return None
self.dizzyEffect = InjuredEffect.getEffect()
if self.dizzyEffect:
self.dizzyEffect.duration = 2.0
self.dizzyEffect.direction = 1
self.dizzyEffect.effectScale = 0.65000000000000002
if hasattr(self, 'headNode') and self.headNode:
self.dizzyEffect.reparentTo(self.headNode)
self.dizzyEffect.setHpr(0, 0, 90)
self.dizzyEffect.setPos(self.headNode, 0.59999999999999998, 0, 0)
else:
self.dizzyEffect.reparentTo(self)
self.dizzyEffect.setHpr(self, 0, 0, 0)
self.dizzyEffect.setPos(self, 0, 0, self.getHeight() + 0.5)
self.dizzyEffect.hide(OTPRender.ShadowCameraBitmask)
self.dizzyEffect.startLoop()
self.dizzyEffect2 = InjuredEffect.getEffect()
if self.dizzyEffect2:
self.dizzyEffect2.duration = 2.0
self.dizzyEffect2.direction = -1
self.dizzyEffect2.effectScale = 0.5
if hasattr(self, 'headNode') and self.headNode:
self.dizzyEffect2.reparentTo(self.headNode)
self.dizzyEffect2.setHpr(0, 120, 90)
self.dizzyEffect2.setPos(self.headNode, 0.84999999999999998, 0, 0)
else:
self.dizzyEffect2.reparentTo(self)
self.dizzyEffect2.setHpr(self, 120, 0, 0)
self.dizzyEffect2.setPos(self, 0, 0, self.getHeight() + 0.25)
self.dizzyEffect2.hide(OTPRender.ShadowCameraBitmask)
self.dizzyEffect2.startLoop()
def stopDizzyEffect(self):
if self.dizzyEffect:
self.dizzyEffect.stopLoop()
self.dizzyEffect = None
if self.dizzyEffect2:
self.dizzyEffect2.stopLoop()
self.dizzyEffect2 = None
def initDazed(self):
self.isDazed = False
self.dazedButtonBoolean = False
shipGui = loader.loadModel('models/gui/ship_battle')
self.dazedBar = DirectWaitBar(parent = base.a2dBottomCenter, frameSize = (-0.69999999999999996, 0.69999999999999996, -0.02, 0.02), relief = DGG.FLAT, image = shipGui.find('**/ship_battle_speed_bar*'), image_pos = (0.0, 0, 0.0), image_scale = (1.0, 1.0, 1.0), borderWidth = (0, 0), pos = (0.0, 0.0, 0.59999999999999998), frameColor = (1.0, 0.0, 0.0, 1.0), barColor = (0.0, 1.0, 0.0, 1.0))
self.dazedBar['value'] = 0
self.dazedBar.hide()
self.dazedTextNode = TextNode('DazedTextNode')
self.dazedTextNodePath = NodePath(self.dazedTextNode)
self.dazedTextNodePath.setPos(0.0, 0.0, 0.80000000000000004)
self.dazedTextNodePath.setScale(0.12)
self.dazedTextNode.setText(PLocalizer.DazedHelpText)
self.dazedTextNode.setTextColor(1.0, 1.0, 1.0, 1.0)
self.dazedTextNode.setAlign(TextNode.ACenter)
self.dazedTextNode.setFont(PiratesGlobals.getPirateFont())
self.dazedTextNodePath.reparentTo(base.a2dBottomCenter)
self.dazedTextNodePath.hide()
def setPirateDazed(self, isDazedBool):
if isDazedBool:
if not self.isDazed:
if self.gameFSM is None:
return None
self.isDazed = True
if self.isLocal():
self.accept('arrow_left', self.dazedButtonPressed, [
False])
self.accept('a', self.dazedButtonPressed, [
False])
self.accept('q', self.dazedButtonPressed, [
False])
self.accept('arrow_right', self.dazedButtonPressed, [
True])
self.accept('d', self.dazedButtonPressed, [
True])
self.accept('e', self.dazedButtonPressed, [
True])
if self.cameraFSM:
currentCamera = self.cameraFSM.getCurrentCamera()
if currentCamera:
currentCamera.disableInput()
self.dazedBar.show()
self.dazedTextNodePath.show()
if self.gameFSM.getCurrentOrNextState() == 'Cannon':
self.cannon.cgui.hideCannonControls()
taskMgr.add(self.shakeOffDazed, self.uniqueName('ShakeOffDazed'))
if base.mouseWatcherNode.hasMouse():
self.lastMousePos = Point2(base.mouseWatcherNode.getMouseX(), base.mouseWatcherNode.getMouseY())
else:
self.lastMousePos = Point2(0.0, 0.0)
self.shakeOffDazedCount = 0.0
self.dazedBar['value'] = 0
self.injuredTrack = self.getInjuredTrack()
self.injuredTrack.start()
self.startDizzyEffect()
taskMgr.doMethodLater(PiratesGlobals.DAZED_DURATION, self.setPirateDazed, self.uniqueName('EndDazed'), extraArgs = [
False])
else:
self.isDazed = False
if self.isLocal():
self.ignore('arrow_left')
self.ignore('a')
self.ignore('q')
self.ignore('arrow_right')
self.ignore('d')
self.ignore('e')
if self.cameraFSM:
currentCamera = self.cameraFSM.getCurrentCamera()
if currentCamera:
currentCamera.enableInput()
self.dazedTextNodePath.hide()
self.dazedBar.hide()
if self.gameFSM is None:
return None
if self.gameFSM.getCurrentOrNextState() == 'Cannon':
self.loop('kneel')
if self.cannon is not None and self.cannon.cgui is not None:
self.cannon.cgui.showCannonControls()
if self.injuredTrack:
self.injuredTrack.finish()
self.injuredTrack = None
self.stopDizzyEffect()
taskMgr.remove(self.uniqueName('EndDazed'))
taskMgr.remove(self.uniqueName('ShakeOffDazed'))
def dazedButtonPressed(self, bool):
if not self.isDazed:
return None
if bool == self.dazedButtonBoolean:
self.dazedButtonBoolean = not (self.dazedButtonBoolean)
self.shakeOffDazedCount += PiratesGlobals.DAZED_BUTTON_INCREMENT
def shakeOffDazed(self, task):
if not self.isDazed:
return None
if base.mouseWatcherNode.hasMouse():
currentMousePos = Point2(base.mouseWatcherNode.getMouseX(), base.mouseWatcherNode.getMouseY())
self.shakeOffDazedCount += (self.lastMousePos - currentMousePos).length()
self.dazedBar['value'] = int(100.0 * self.shakeOffDazedCount / PiratesGlobals.DAZED_SHAKEOFF_THRESHOLD)
if self.shakeOffDazedCount > PiratesGlobals.DAZED_SHAKEOFF_THRESHOLD:
self.setPirateDazed(False)
self.lastMousePos = currentMousePos
return Task.again
def getGetupTrack(self, timeStamp = 0.0):
av = self
def loopIdle():
av.loop('idle', blendDelay = 0.14999999999999999)
getupTrack = Parallel(Sequence(Wait(0.5), Func(loopIdle)), av.actorInterval('injured_standup', blendInT = 0.14999999999999999, blendOutT = 0.14999999999999999))
return getupTrack
def getInjuredTrack(self, timeStamp = 0.0):
av = self
def loopIdle():
av.loop('injured_idle', blendDelay = 0.14999999999999999)
def startSFX():
sfx = self.getSfx('death')
if sfx:
base.playSfx(sfx, node = self, cutoff = 100)
injuredTrack = Sequence(Parallel(Sequence(Wait(0.5), Func(loopIdle)), Func(startSFX), av.actorInterval('injured_fall', blendInT = 0.14999999999999999, blendOutT = 0.14999999999999999)))
return injuredTrack
def getDyingTrack(self, timeStamp):
av = self
animName = 'injured_idle_shakehead'
def stopSmooth():
if self.smoothStarted:
taskName = self.taskName('smooth')
taskMgr.remove(taskName)
self.smoothStarted = 0
def gotoRoam():
if av.getGameState() == 'Dying':
if av == localAvatar:
av.b_setGameState('LandRoam')
diedSound = loader.loadSfx('audio/sfx_doll_unattune.mp3')
diedSoundInterval = SoundInterval(diedSound, node = self)
duration = 1.0
deathIval = Parallel(diedSoundInterval, Func(self.setTransparency, 1), self.actorInterval(animName, blendInT = 0.14999999999999999, blendOutT = 0.14999999999999999), Sequence(LerpColorScaleInterval(self, duration, Vec4(1, 1, 1, 0), startColorScale = Vec4(1)), Func(self.hide, None, PiratesGlobals.INVIS_DEATH), Func(self.clearColorScale), Func(self.clearTransparency), Func(gotoRoam)))
return deathIval
def reportRevive(self, healerId):
healer = base.cr.doId2do.get(healerId)
if healer:
message = PLocalizer.InjuredHelped % (self.getName(), healer.getName())
base.talkAssistant.receiveGameMessage(message)
def faceDO(self, doId2Face):
do2face = base.cr.doId2do.get(doId2Face)
if do2face:
self.headsUp(do2face)
def startHealing(self, healTime):
self.acceptInteraction()
localAvatar.guiMgr.workMeter.updateText(PLocalizer.InjuredReviving)
localAvatar.guiMgr.workMeter.startTimer(healTime)
localAvatar.b_setGameState('Healing')
pos = localAvatar.getPos(self.headNode)
arm = self.headNode.attachNewNode('arm')
arm.lookAt(localAvatar)
oldParent = localAvatar.getParent()
localAvatar.wrtReparentTo(arm)
localAvatar.setH(localAvatar, 0)
radius = 3.5
aAngle = arm.getH()
if aAngle > 85.0 and aAngle < 140:
arm.setH(140)
elif aAngle <= 85.0 and aAngle > 30:
arm.setH(30)
localAvatar.setX(0)
localAvatar.setY(radius)
localAvatar.wrtReparentTo(oldParent)
localAvatar.setScale(1.0)
localAvatar.setShear(VBase3(0, 0, 0))
arm.removeNode()
localAvatar.setZ(self, 0)
localAvatar.headsUp(self.headNode)
localAvatar.sendCurrentPosition()
def stopHealing(self):
localAvatar.guiMgr.workMeter.stopTimer()
if localAvatar.getGameState() == 'Healing':
localAvatar.b_setGameState(localAvatar.gameFSM.defaultState)
def setBeingHealed(self, beingHealed):
self.beingHealed = beingHealed
def startHealEffects():
if base.options.getSpecialEffectsSetting() >= base.options.SpecialEffectsMedium:
healSparks = HealSparks.getEffect()
if healSparks:
healSparks.reparentTo(self)
healSparks.setPos(self, 0, -1, 0)
healSparks.setHpr(self, 0, 90, 0)
healSparks.setScale(1.5, 1.5, 2)
healSparks.setEffectColor(Vec4(0.29999999999999999, 1, 1, 0.29999999999999999))
healSparks.startLoop()
self.healEffects.append(healSparks)
if base.options.getSpecialEffectsSetting() >= base.options.SpecialEffectsHigh:
healRays = HealRays.getEffect()
if healRays:
healRays.reparentTo(self)
healRays.setPos(self, 0, -1, 0)
healRays.setHpr(self, 0, 90, 0)
healRays.setScale(0.75, 0.75, 2)
healRays.setEffectColor(Vec4(0.29999999999999999, 1, 1, 1))
healRays.startLoop()
self.healEffects.append(healRays)
if beingHealed:
self.healEffectIval = Sequence(Wait(3.0), Func(startHealEffects))
self.healEffectIval.start()
elif self.healEffectIval:
self.healEffectIval.pause()
self.healEffectIval = None
for effect in self.healEffects:
effect.stopLoop()
self.healEffects = []
def getBeingHealed(self):
return self.beingHealed
def requestExit(self):
DistributedBattleAvatar.requestExit(self)
self.stopHealing()
def _handleShowBeacon(self, showBeacon, pvpTeam):
if not self.isLocal():
if showBeacon:
self.showBeacon(pvpTeam)
else:
self.hideBeacon()
def _decideShowBeacon(self, isZombie, inPvp, pvpTeam):
if isZombie and inPvp:
pass
self._beaconVisibleSV.set(pvpTeam)
def setTeam(self, team):
DistributedBattleAvatar.setTeam(self, team)
if not self.isLocal():
if self.getTeam() == localAvatar.getTeam():
self.setAllowInteract(False)
else:
self.setAllowInteract(True)
def setPVPTeam(self, team):
if team and self.isLocal():
self.guiMgr.crewHUD.setHUDOff()
self.guiMgr.crewHUDTurnedOff = True
DistributedBattleAvatar.setPVPTeam(self, team)
self._pvpTeamSV.set(team)
def createGameFSM(self):
self.gameFSM = PlayerPirateGameFSM.PlayerPirateGameFSM(self)
def announceGenerate(self):
DistributedPirateBase.announceGenerate(self)
DistributedPlayer.announceGenerate(self)
DistributedBattleAvatar.announceGenerate(self)
self.accept('localAvatarEntersDialog', self.enterDialogMode)
self.accept('localAvatarExitsDialog', self.exitDialogMode)
self.accept('Local_Efficiency_Set', self.setEfficiency)
if localAvatar.duringDialog:
self.enterDialogMode()
self.setName(self.name)
if base.config.GetBool('disable-player-collisions', 1):
if self.battleTubeNodePaths:
for np in self.battleTubeNodePaths:
np.node().setIntoCollideMask(np.node().getIntoCollideMask() & ~(PiratesGlobals.WallBitmask))
if not self.isLocal():
self.collNode.setIntoCollideMask(np.node().getIntoCollideMask() & ~(PiratesGlobals.WallBitmask))
self.checkAttuneEffect()
if base.launcher.getPhaseComplete(4):
self.createConsumable()
else:
self.consumable = None
self.accept('phaseComplete-4', self.handlePhaseComplete, extraArgs = [
4])
self.initVisibleToCamera()
yieldThread('current Item')
self.setEfficiency(localAvatar.getEfficiency())
def handlePhaseComplete(self, phase):
if phase == 4:
self.createConsumable()
def createConsumable(self):
self.consumable = Consumable.Consumable(ItemGlobals.TONIC)
def setLocation(self, parentId, zoneId):
DistributedBattleAvatar.setLocation(self, parentId, zoneId)
def wrtReparentTo(self, parent):
DistributedBattleAvatar.wrtReparentTo(self, parent)
def setName(self, name):
DistributedBattleAvatar.setName(self, name)
self.refreshName()
def setCrewIcon(self, iconId):
self.sendUpdate('setCrewIconIndicator', [
iconId])
self.hasCrewIcon = iconId
self.setCrewIconIndicator(iconId)
def getCrewIcon(self):
return self.hasCrewIcon
def setCrewIconIndicator(self, iconId):
if self.getDoId() != localAvatar.getDoId() and iconId != 0:
if self.getDoId() not in localAvatar.guiMgr.crewHUD.crew:
iconId = 2
if iconId not in range(0, 3):
return None
self.hasCrewIcon = iconId
self.refreshName()
minimapObj = self.getMinimapObject()
if minimapObj:
pass
1
def setBadgeIcon(self, titleId, rank):
self.badge = (titleId, rank)
if titleId < 0 or rank < 0:
self.badge = None
self.refreshName()
def setShipBadgeIcon(self, titleId, rank):
self.shipBadge = (titleId, rank)
if titleId < 0 or rank < 0:
self.shipBadge = None
def sendRequestSetBadgeIcon(self, titleId, rank):
self.sendUpdate('requestBadgeIcon', [
titleId,
rank])
def sendRequestSetShipBadgeIcon(self, titleId, rank):
self.sendUpdate('requestShipBadgeIcon', [
titleId,
rank])
def setLastPVPSinkTime(self, timestamp):
self.lastPVPSinkTime = timestamp
def setLastShipPVPDecayTime(self, timestamp):
self.lastShipPVPDecayTime = timestamp
def setInfamySea(self, infamySea):
messenger.send('infamySeaUpdated', [
infamySea - self.infamySea])
self.infamySea = infamySea
self.setupInfamySeaDecay()
def getInfamySea(self):
return self.infamySea
def setupInfamySeaDecay(self):
timeNow = time.time()
taskMgr.remove(self.uniqueName('decayInfamySea'))
if not self.infamySea:
return None
if timeNow - self.lastPVPSinkTime < PVPGlobals.SHIP_PVP_SINK_TIME_MAX:
taskMgr.doMethodLater(PVPGlobals.SHIP_PVP_SINK_TIME_MAX - timeNow - self.lastPVPSinkTime, self.decayInfamySea, self.uniqueName('decayInfamySea'))
else:
taskMgr.doMethodLater(PVPGlobals.SHIP_PVP_SINK_TIME_NEXT, self.decayInfamySea, self.uniqueName('decayInfamySea'))
def decayInfamySea(self, task = None):
infamyToRemove = self.infamySea * PVPGlobals.SHIP_PVP_INFAMY_DEC_PERCENT + PVPGlobals.SHIP_PVP_INFAMY_DEC_FLAT
infamyToRemove = int(min(self.infamySea, infamyToRemove))
messenger.send('infamySeaUpdated', [
-infamyToRemove])
self.infamySea -= infamyToRemove
if self.infamySea:
taskMgr.doMethodLater(PVPGlobals.SHIP_PVP_SINK_TIME_NEXT, self.decayInfamySea, self.uniqueName('decayInfamySea'))
return Task.done
def setLastPVPDefeatTime(self, timestamp):
self.lastPVPDefeatTime = timestamp
def setLastLandPVPDecayTime(self, timestamp):
self.lastLandPVPDecayTime = timestamp
def setInfamyLand(self, infamyLand):
messenger.send('infamyLandUpdated', [
infamyLand - self.infamyLand])
self.infamyLand = infamyLand
self.setupInfamyLandDecay()
def getInfamyLand(self):
return self.infamyLand
def setupInfamyLandDecay(self):
timeNow = time.time()
taskMgr.remove(self.uniqueName('decayInfamyLand'))
if not self.infamyLand:
return None
if timeNow - self.lastPVPDefeatTime < PVPGlobals.LAND_PVP_DEFEAT_TIME_MAX:
taskMgr.doMethodLater(PVPGlobals.LAND_PVP_DEFEAT_TIME_MAX - timeNow - self.lastPVPDefeatTime, self.decayInfamyLand, self.uniqueName('decayInfamyLand'))
else:
taskMgr.doMethodLater(PVPGlobals.LAND_PVP_DEFEAT_TIME_NEXT, self.decayInfamyLand, self.uniqueName('decayInfamyLand'))
def decayInfamyLand(self, task = None):
infamyToRemove = self.infamyLand * PVPGlobals.LAND_PVP_INFAMY_DEC_PERCENT + PVPGlobals.LAND_PVP_INFAMY_DEC_FLAT
infamyToRemove = int(min(self.infamyLand, infamyToRemove))
messenger.send('infamyLandUpdated', [
-infamyToRemove])
self.infamyLand -= infamyToRemove
if self.infamyLand:
taskMgr.doMethodLater(PVPGlobals.LAND_PVP_DEFEAT_TIME_NEXT, self.decayInfamyLand, self.uniqueName('decayInfamyLand'))
return Task.done
def infamyRankSeaDecreaseMessage(self, oldRank, newRank):
oldRankName = PLocalizer.PVPTitleSeaRanks[oldRank]
newRankName = PLocalizer.PVPTitleSeaRanks[newRank]
message = PLocalizer.PVPSeaRankDecreaseMessage % (oldRankName, newRankName)
base.talkAssistant.receiveSystemMessage(message)
def infamyRankLandDecreaseMessage(self, oldRank, newRank):
oldRankName = PLocalizer.PVPTitleLandRanks[oldRank]
newRankName = PLocalizer.PVPTitleLandRanks[newRank]
message = PLocalizer.PVPLandRankDecreaseMessage % (oldRankName, newRankName)
base.talkAssistant.receiveSystemMessage(message)
def setStatus(self, status):
self.isLookingForCrew = status & PiratesGlobals.STATUS_LFG
self.isAFK = status & PiratesGlobals.STATUS_AFK
self.refreshName()
def d_refreshStatus(self):
status = 0
if self.isAFK:
status += PiratesGlobals.STATUS_AFK
if self.isLookingForCrew:
status += PiratesGlobals.STATUS_LFG
self.sendUpdate('setStatus', [
status])
def toggleLookingForCrewSign(self):
try:
localAvatar.guiMgr.crewHUD.toggleLookingForCrew()
except:
pass
def setLookingForCrew(self, state):
self.isLookingForCrew = state
self.refreshName()
self.d_refreshStatus()
def getLookingForCrew(self):
return self.isLookingForCrew
def b_setAFK(self, isAFK):
self.isAFK = isAFK
self.d_setAFK(isAFK)
self.refreshName()
self.d_refreshStatus()
def d_setAFK(self, isAFK):
self.sendUpdate('setAFK', [
isAFK])
def refreshName(self):
if not hasattr(base, 'localAvatar') or localAvatar.isDeleted():
return None
self.refreshStatusTray()
if hasattr(self, 'nametag'):
self.nametag.setName(self.getName())
self.nametag.setDisplayName(' ')
if self.guildName == '0' or self.guildName == '':
guildName = PLocalizer.GuildDefaultName % self.guildId
else:
guildName = self.guildName
nameText = self.getNameText()
if nameText:
level = self.getLevel()
if self.inPvp and self != localAvatar:
levelColor = self.cr.battleMgr.getExperienceColor(base.localAvatar, self)
else:
levelColor = '\x01white\x01'
x2XPTempAwardIndicator = ''
if self.tempDoubleXPStatus:
x2XPTempAwardIndicator = '\x05x2XPAwardIcon\x05'
if self.guildName == PLocalizer.GuildNoGuild:
text = '%s%s \x01smallCaps\x01%s%s%s%s\x02\x02' % (self.title, self.name, levelColor, PLocalizer.Lv, level, x2XPTempAwardIndicator)
else:
text = '%s%s \x01smallCaps\x01%s%s%s%s\x02\x02\n\x01guildName\x01%s\x02' % (self.title, self.name, levelColor, PLocalizer.Lv, level, x2XPTempAwardIndicator, guildName)
nameText['text'] = text
if Freebooter.getPaidStatus(self.doId):
if self.getFounder():
nameText['fg'] = (1, 1, 1, 1)
nameText['font'] = PiratesGlobals.getPirateOutlineFont()
if not base.config.GetBool('want-land-infamy', 0) or base.config.GetBool('want-sea-infamy', 0):
nameText['text'] = '\x05goldFounderIcon\x05 \x01goldFounder\x01%s\x02' % text
else:
nameText['text'] = '\x01goldFounder\x01%s\x02' % text
else:
nameText['fg'] = (0.40000000000000002, 0.29999999999999999, 0.94999999999999996, 1)
nameText['font'] = PiratesGlobals.getPirateOutlineFont()
else:
nameText['fg'] = (0.5, 0.5, 0.5, 1)
prefix = ''
if self.injuredSetup and 0:
if self.injuredTimeLeft:
prefix = '\x01injuredRedTimer\x01%s\x02\x01injuredRed\x01\n%s\x02\n' % PLocalizer.InjuredFlag
else:
prefix = '\x01injuredRed\x01%s\x02\n' % PLocalizer.InjuredFlag
elif base.cr.avatarFriendsManager.checkIgnored(self.doId):
prefix = '\x01ignoredPink\x01%s\x02\n' % PLocalizer.IngoredFlag
elif self.isAFK:
prefix = '\x01afkGray\x01%s\x02\n' % PLocalizer.AFKFlag
elif self.getLookingForCrew():
prefix = '\x01crewPurple\x01%s\x02\n' % PLocalizer.CrewLookingForAd
badges = ''
if self.isConfused:
prefix = '\x05confusedIcon\x05\n'
elif self.badge and Freebooter.getPaidStatus(self.doId):
if base.config.GetBool('want-land-infamy', 0) or base.config.GetBool('want-sea-infamy', 0):
if self.badge[0]:
textProp = TitleGlobals.Title2nametagTextProp[self.badge[0]]
if textProp == 'goldFounder':
if not Freebooter.getFounderStatus(self.doId):
pass
else:
badges += '\x01white\x01\x05badge-%s-%s\x05\x02 ' % (self.badge[0], 1)
nameText['text'] = '\x01%s\x01%s\x02' % (textProp, nameText['text'])
elif textProp:
badges += '\x01white\x01\x05badge-%s-%s\x05\x02 ' % (self.badge[0], self.badge[1])
nameText['text'] = '\x01%s\x01%s\x02' % (textProp, nameText['text'])
else:
badges += '\x01white\x01\x05badge-%s-%s\x05\x02 ' % (self.badge[0], self.badge[1])
nameText['text'] = prefix + badges + nameText['text']
if self.isInvisibleGhost() or self.isInvisible():
nameText['text'] = ''
if not self.isLocal():
return None
if self.getCrewIcon() and not (self.gmNameTagEnabled):
if self.getCrewIcon() != 2:
oldLabelText = nameText['text']
nameText['text'] = '\x01white\x01\x05crewIcon%s\x05\x02\n%s' % (self.hasCrewIcon, oldLabelText)
if self.gmNameTagEnabled and self.isGM():
if self.getCrewIcon():
nameText['text'] = '\x05gmNameTagLogo\x05\x01white\x01\x05crewIcon%s\x05\x02\n\x01%s\x01%s\x02\n%s' % (self.hasCrewIcon, self.getGMNameTagColor(), self.gmNameTagString, nameText['text'])
else:
nameText['text'] = '\x05gmNameTagLogo\x05\n\x01%s\x01%s\x02\n%s' % (self.getGMNameTagColor(), self.gmNameTagString, nameText['text'])
def setTutorialAck(self, tutorialAck):
self.tutorialAck = tutorialAck
def setEfficiency(self, efficiency):
if self.efficiency != efficiency:
self.efficiency = efficiency
if self.efficiency:
self.enableReducedMixing()
else:
self.enableMixing()
if self.getGameState() == 'Injured':
self.loop('injured_idle', blendDelay = 0.14999999999999999)
def b_setInInvasion(self, inInvasion):
self.d_setInInvasion(inInvasion)
self.setInInvasion(inInvasion)
def d_setInInvasion(self, inInvasion):
self.sendUpdate('setInInvasion', [
inInvasion])
def setInInvasion(self, inInvasion):
self.inInvasion = inInvasion
if inInvasion:
if not base.config.GetBool('disable-player-collisions', 1):
if self.battleTubeNodePaths:
for np in self.battleTubeNodePaths:
np.node().setIntoCollideMask(np.node().getIntoCollideMask() & ~(PiratesGlobals.WallBitmask))
if not self.isLocal():
self.collNode.setIntoCollideMask(np.node().getIntoCollideMask() & ~(PiratesGlobals.WallBitmask))
if not self.isLocal():
self.enableReducedMixing()
elif not base.config.GetBool('disable-player-collisions', 1):
if self.battleTubeNodePaths:
for np in self.battleTubeNodePaths:
np.node().setIntoCollideMask(np.node().getIntoCollideMask() | PiratesGlobals.WallBitmask)
if not self.isLocal():
self.collNode.setIntoCollideMask(np.node().getIntoCollideMask() | PiratesGlobals.WallBitmask)
if not self.isLocal():
self.enableMixing()
if self.getGameState() == 'Injured':
self.loop('injured_idle', blendDelay = 0.14999999999999999)
def getInventoryId(self):
return self.inventoryId
def setInventoryId(self, inventoryId):
self.inventoryId = inventoryId
def getInventory(self):
if not self:
return None
if not self.cr:
return None
inventory = self.cr.doId2do.get(self.inventoryId)
if inventory:
return inventory
else:
return None
def getFriendsListId(self):
pass
def setFriendsListId(self, friendsListId):
pass
def getFriendsList(self):
return self.avatarFriendsList
def getAvatarFriendsList(self):
return self.avatarFriendsList
def getPlayerFriendsList(self):
return self.playerFriendsList
def getName(self):
return self.title + self.name
def setGuildName(self, newname):
if newname == 'Null':
self.guildName = PLocalizer.GuildNoGuild
else:
self.guildName = newname
self.refreshName()
def getGuildName(self):
return self.guildName
def setGuildRank(self, rank):
self.guildRank = rank
def getGuildRank(self):
return self.guildRank
def getGuildId(self):
return self.guildId
def setGuildId(self, guildId):
self.guildId = guildId
def getCrewMemberId(self):
return self.crewMemberId
def setCrewMemberId(self, crewMemberId):
self.crewMemberId = crewMemberId
def getDinghyId(self):
return self.dinghyId
def setDinghyId(self, dinghyId):
self.dinghyId = dinghyId
def getDinghy(self):
return self.cr.doId2do.get(self.dinghyId)
def setDNAString(self, dnaString):
DistributedPirateBase.setDNAString(self, dnaString)
def b_setActiveShipId(self, shipId):
self.d_setActiveShipId(shipId)
self.setActiveShipId(shipId)
b_setActiveShipId = report(types = [
'frameCount',
'deltaStamp',
'args'], dConfigParam = 'shipboard')(b_setActiveShipId)
def d_setActiveShipId(self, shipId):
self.sendUpdate('setActiveShipId', [
shipId])
d_setActiveShipId = report(types = [
'frameCount',
'deltaStamp',
'args'], dConfigParam = 'shipboard')(d_setActiveShipId)
def setActiveShipId(self, shipId):
if shipId and localAvatar.getDoId() == self.getDoId():
messenger.send('localAvatarToSea')
elif not shipId and localAvatar.getDoId() == self.getDoId():
messenger.send('localAvatarToLand')
self.activeShipId = shipId
setActiveShipId = report(types = [
'deltaStamp',
'module',
'args'], dConfigParam = 'shipboard')(setActiveShipId)
def getActiveShip(self):
return self.cr.doId2do.get(self.activeShipId)
def getActiveShipId(self):
return self.activeShipId
def setCrewShipId(self, shipId):
if self.pendingSetCrewShip:
self.cr.relatedObjectMgr.abortRequest(self.pendingSetCrewShip)
self.pendingSetCrewShip = None
self.crewShipId = shipId
if shipId:
self.pendingSetCrewShip = self.cr.relatedObjectMgr.requestObjects([
shipId], eachCallback = self._setCrewShip)
messenger.send('localAvatarToSea')
else:
self._setCrewShip(None)
messenger.send('localAvatarToLand')
setCrewShipId = report(types = [
'deltaStamp',
'module',
'args'], dConfigParam = 'shipboard')(setCrewShipId)
def getCrewShipId(self):
return self.crewShipId
def _setCrewShip(self, ship):
self.crewShip = ship
_setCrewShip = report(types = [
'deltaStamp',
'module',
'args'], dConfigParam = 'shipboard')(_setCrewShip)
def getCrewShip(self):
return self.crewShip
def printShips(self):
print 'activeShip:\t', self.getActiveShipId(), self.getActiveShip()
print 'crewShip:\t', self.getCrewShipId(), self.getCrewShip()
print 'ship:\t\t', self.getShip(), self.getShip()
def getShipString(self):
return 'A: %s, C: %s, S: %s' % (self.getActiveShipId(), self.getCrewShipId(), self.getShipId())
def hpChange(self, quietly = 0):
DistributedBattleAvatar.hpChange(self, quietly)
def updateReputation(self, category, value):
DistributedBattleAvatar.updateReputation(self, category, value)
def useTargetedSkill(self, skillId, ammoSkillId, actualResult, targetId, areaIdList, attackerEffects, targetEffects, areaIdEffects, itemEffects, timestamp, pos, charge = 0, localSignal = 0):
targetEffects = list(targetEffects)
attackerEffects = list(attackerEffects)
DistributedBattleAvatar.useTargetedSkill(self, skillId, ammoSkillId, actualResult, targetId, areaIdList, attackerEffects, targetEffects, areaIdEffects, itemEffects, timestamp, pos, charge, localSignal)
def playSkillMovie(self, skillId, ammoSkillId, skillResult, charge = 0, targetId = 0, areaIdList = []):
DistributedBattleAvatar.playSkillMovie(self, skillId, ammoSkillId, skillResult, charge, targetId, areaIdList)
def forceTeleportStart(self, instanceName, tzDoId, thDoId, worldGridDoId, tzParent, tzZone):
def effectDoneCallback():
self.cr.teleportMgr.forceTeleportStart(instanceName, tzDoId, thDoId, worldGridDoId, tzParent, tzZone)
self.acceptOnce('avatarTeleportEffect-done', effectDoneCallback)
if self.cr.teleportMgr.stowawayEffect:
self.setGameState('TeleportOut', timestamp = None, localArgs = [
'someBogusEventName',
False])
self.controlManager.collisionsOff()
par = self.getParentObj()
uid = par.getUniqueId()
if uid == LocationIds.PORT_ROYAL_ISLAND:
self.setPos(par, -93.589600000000004, -362.238, 11.5197)
self.setHpr(par, -118.82299999999999, 0, 0)
elif uid == LocationIds.TORTUGA_ISLAND:
self.setPos(par, 19.7727, -460.67099999999999, 4.2405099999999996)
self.setHpr(par, -92.827299999999994, 0, 0)
elif uid == LocationIds.CUBA_ISLAND:
self.setPos(par, -194.761, -764.57299999999998, 4.0030299999999999)
self.setHpr(par, -172.74199999999999, 0, 0)
elif uid == LocationIds.DEL_FUEGO_ISLAND:
self.setPos(par, -1464.6199999999999, 385.61500000000001, 5.0097199999999997)
self.setHpr(par, -22.449000000000002, 0, 0)
def spiffyPlay():
self.play('stowaway_get_in_crate', blendOutT = 0.0)
teleportTrack = Parallel(Func(spiffyPlay), Sequence(Wait(0.59999999999999998), Func(base.transitions.fadeOut), Parallel(Sequence(Wait(0.5), SoundInterval(StowawayGUI.CrateShutSound, loop = 0)), Sequence(Wait(3.0), Func(base.cr.loadingScreen.show, waitForLocation = True, disableSfx = False)))))
teleportTrack.setDoneEvent('avatarTeleportEffect-done')
teleportTrack.start()
elif self.cr.teleportMgr.doEffect and not self.testTeleportFlag(PiratesGlobals.TFInInitTeleport):
pass
doEffect = not self.testTeleportFlag(PiratesGlobals.TFInWater)
if self.gameFSM.getCurrentOrNextState() != 'TeleportOut':
self.b_setGameState('TeleportOut', [
'avatarTeleportEffect-done',
doEffect])
else:
messenger.send('avatarTeleportEffect-done')
self.cr.teleportMgr.doEffect = True
forceTeleportStart = report(types = [
'deltaStamp',
'module',
'args'], dConfigParam = 'teleport')(forceTeleportStart)
def relayTeleportLoc(self, shardId, zoneId, teleportMgrDoId):
self.b_setDefaultShard(shardId)
self.cr.playingGameLocReceived(shardId, self.doId)
if self.pendingTeleportMgr:
base.cr.relatedObjectMgr.abortRequest(self.pendingTeleportMgr)
self.pendingTeleportMgr = None
self.pendingTeleportMgr = base.cr.relatedObjectMgr.requestObjects([
teleportMgrDoId], eachCallback = self.readyToTeleport)
relayTeleportLoc = report(types = [
'deltaStamp',
'module',
'args'], dConfigParam = 'teleport')(relayTeleportLoc)
def readyToTeleport(self, teleportMgr):
bp.loginCfg()
teleportMgr.initiateTeleport(self.teleportToType, self.teleportToName, shardId = self.getDefaultShard(), locationUid = self.returnLocation)
readyToTeleport = report(types = [
'deltaStamp',
'module'], dConfigParam = 'teleport')(readyToTeleport)
def requestActivityAccepted(self):
self.guiMgr.lookoutPage.requestActivityAccepted()
def lookoutMatchFound(self, timeToJoin, matchId):
self.guiMgr.lookoutPage.matchFound(matchId, timeToJoin)
def lookoutMatchFailed(self, restartRequest):
self.guiMgr.lookoutPage.matchFailed(restartRequest)
def lookoutFeedback(self, matchChance):
self.guiMgr.lookoutPage.matchChance(matchChance)
def beginningTeleport(self, instanceType, fromInstanceType, instanceName, gameType):
base.cr.loadingScreen.showTarget()
self.cr.teleportMgr.teleportHasBegun(instanceType, fromInstanceType, instanceName, gameType)
self.guiMgr.lookoutPage.matchTeleport()
def showContextTutPanel(self, contextId, number, type, part):
if self._DistributedPlayerPirate__tutorialEnabled == False:
return None
if self.isLocal() and self.isInInvasion():
return None
self.guiMgr.handleContextTutorial(contextId, number, type, part)
def enableTutorial(self):
self._DistributedPlayerPirate__tutorialEnabled = True
self.guiMgr.isTutEnabled = True
def disableTutorial(self):
self._DistributedPlayerPirate__tutorialEnabled = False
self.guiMgr.isTutEnabled = False
if self.guiMgr.contextTutPanel.isHidden() == False:
self.guiMgr.contextTutPanel.hide()
def informMissedLoot(self, lootType, reason):
pass
def setLootCarried(self, amt, maxCarry):
self.lootCarried = amt
def startTimer(self, time, timestamp, mode = None):
if config.GetBool('hide-gui', 0):
return None
if self == localAvatar:
self.timerTimestamp = timestamp
if time:
ts = globalClockDelta.localElapsedTime(timestamp)
newTime = time - ts
if newTime > 0:
if mode == PiratesGlobals.HIGHSEAS_ADV_START:
pass
elif mode in [
PiratesGlobals.SHIP_SELECTION_TIMER,
PiratesGlobals.SHIP_BOARD_TIMER,
PiratesGlobals.SHIP_DOCK_TIMER]:
self.guiMgr.setTimer(newTime, mode = mode)
else:
self.guiMgr.setTimer(newTime)
else:
self.guiMgr.timerExpired()
else:
self.guiMgr.timerExpired()
def cancelTimer(self, mode):
self.guiMgr.cancelTimer(mode)
def endMissionPanel(self, missionData, playerData):
if config.GetBool('hide-gui', 0):
return None
portName = ''
if base.localAvatar.ship and not base.localAvatar.ship.getSiegeTeam():
self.guiMgr.createHighSeasScoreboard(portName, missionData, playerData, base.localAvatar.ship)
def endInvasionPanel(self, holidayId, wonInvasion, repEarned, enemiesKilled, barricadesSaved, wavesCleared):
if config.GetBool('hide-gui', 0):
return None
taskMgr.doMethodLater(8.0, self.guiMgr.createInvasionScoreboard, self.uniqueName('createInvasionScoreboard'), [
holidayId,
wonInvasion,
repEarned,
enemiesKilled,
barricadesSaved,
wavesCleared])
def createTitle(self, textIndex):
base.localAvatar.guiMgr.createTitle(textIndex)
def sendCancelMission(self):
self.sendUpdate('cancelMission')
def loop(self, *args, **kwArgs):
if self.creature and len(args) > 1:
if args[0] in [
'spin_left',
'spin_right',
'run',
'strafe_left',
'strafe_right']:
args = ('walk', args[1])
self.creature.loop(*args, **args)
else:
Biped.Biped.loop(self, *args, **args)
def play(self, *args, **kwArgs):
Biped.Biped.play(self, *args, **args)
def pingpong(self, *args, **kwArgs):
Biped.Biped.pingpong(self, *args, **args)
def pose(self, *args, **kwArgs):
Biped.Biped.pose(self, *args, **args)
def stop(self, *args, **kwArgs):
Biped.Biped.stop(self, *args, **args)
def putAwayCurrentWeapon(self, blendInT = 0.10000000000000001, blendOutT = 0.10000000000000001):
self.setStickyTargets([])
return DistributedBattleAvatar.putAwayCurrentWeapon(self, blendInT, blendOutT)
def setStickyTargets(self, avList):
self.stickyTargets = avList
self.checkAttuneEffect()
localAvatar.guiMgr.attuneSelection.update()
def checkAttuneEffect(self):
if not self.isGenerated():
return None
if self.stickyTargets:
if not self.attuneEffect:
self.attuneEffect = VoodooAura.getEffect()
if self.attuneEffect:
self.attuneEffect.reparentTo(self.rightHandNode)
self.attuneEffect.setPos(0, 0, 0)
self.attuneEffect.particleDummy.reparentTo(self.rightHandNode)
self.attuneEffect.startLoop()
hasFriendly = 0
hasEnemies = 0
for targetId in self.stickyTargets:
target = self.cr.doId2do.get(targetId)
if target:
if TeamUtils.damageAllowed(self, target):
hasEnemies = 1
else:
hasFriendly = 1
TeamUtils.damageAllowed(self, target)
if hasFriendly and not hasEnemies:
self.attuneEffect.setEffectColor(Vec4(0.20000000000000001, 0.5, 0.10000000000000001, 1))
elif hasEnemies and not hasFriendly:
self.attuneEffect.setEffectColor(Vec4(0.20000000000000001, 0.10000000000000001, 0.5, 1))
elif hasEnemies and hasFriendly:
self.attuneEffect.setEffectColor(Vec4(0, 0.14999999999999999, 0.14999999999999999, 1))
elif self.attuneEffect:
self.attuneEffect.stopLoop()
self.attuneEffect = None
def getStickyTargets(self):
return self.stickyTargets
def addStickyTarget(self, avId):
if avId not in self.stickyTargets:
self.stickyTargets.append(avId)
self.setStickyTargets(self.stickyTargets)
localAvatar.guiMgr.attuneSelection.update()
def sendRequestRemoveStickyTargets(self, doIdList):
self.sendUpdate('requestRemoveEffects', [
doIdList])
def sendRequestRemoveEffects(self, doIdList):
self.sendUpdate('requestRemoveEffects', [
doIdList])
def hasStickyTargets(self):
return self.stickyTargets
def getFriendlyStickyTargets(self):
avIdList = []
for avId in self.stickyTargets:
av = self.cr.doId2do.get(avId)
if av:
if not TeamUtils.damageAllowed(av, self):
avIdList.append(avId)
TeamUtils.damageAllowed(av, self)
return avIdList
def getHostileStickyTargets(self):
avIdList = []
for avId in self.stickyTargets:
av = self.cr.doId2do.get(avId)
if av:
if TeamUtils.damageAllowed(self, av):
avIdList.append(avId)
TeamUtils.damageAllowed(self, av)
return avIdList
def sendRequestAuraDetection(self, doIdList):
self.sendUpdate('requestAuraDetection', [
doIdList])
def sendRequestRemoveAuraDetection(self):
self.sendUpdate('requestRemoveAuraDetection')
def sendClothingMessage(self, clothingId, colorId):
localAvatar.guiMgr.messageStack.showLoot([], gold = 0, collect = 0, card = 0, cloth = clothingId, color = colorId)
def sendLootMessage(self, lootId):
localAvatar.guiMgr.messageStack.showLoot([], gold = 0, collect = lootId)
def sendCardMessage(self, cardId):
localAvatar.guiMgr.messageStack.showLoot([], gold = 0, collect = 0, card = cardId)
def sendWeaponMessage(self, weapon):
localAvatar.guiMgr.messageStack.showLoot([], gold = 0, collect = 0, weapon = weapon)
def sendJewelryMessage(self, jewelryUID):
localAvatar.guiMgr.messageStack.showLoot([], gold = 0, collect = 0, jewel = jewelryUID)
def sendTattooMessage(self, tattooUID):
localAvatar.guiMgr.messageStack.showLoot([], gold = 0, collect = 0, tattoo = tattooUID)
def sendReputationMessage(self, targetId, categories, reputationList, basicPenalty, crewBonus, doubleXPBonus, holidayBonus, potionBonus):
target = base.cr.doId2do.get(targetId)
if target:
totalWeaponRep = 0
for i in range(len(categories)):
if categories[i] != InventoryType.OverallRep:
totalWeaponRep += reputationList[i]
continue
overallRep = 0
if categories.count(InventoryType.OverallRep):
overallRepIndex = categories.index(InventoryType.OverallRep)
overallRep = reputationList[overallRepIndex]
totalRep = max(totalWeaponRep, overallRep)
colorSetting = 4
if InventoryType.GeneralRep in categories:
colorSetting = 5
target.printExpText(totalRep, colorSetting, basicPenalty, crewBonus, doubleXPBonus, holidayBonus, potionBonus)
def sendRenownMessage(self, targetId, landRenown, seaRenown, killStreakLevel, killStreakBonus):
target = base.cr.doId2do.get(targetId)
renown = max(landRenown, seaRenown)
if target:
colorSetting = 7
if landRenown:
colorSetting = 8
if hasattr(target, 'printExpText'):
target.printExpText(renown, colorSetting, 0, 0, 0, 0, 0)
if self.getShip() and self.getShip().renownDisplay:
prevRank = TitleGlobals.getRank(TitleGlobals.ShipPVPTitle, self.getInfamySea())
newRank = TitleGlobals.getRank(TitleGlobals.ShipPVPTitle, self.getInfamySea() + renown)
if prevRank < newRank:
self.levelUpMsg(InventoryType.PVPTotalInfamySea, newRank, 0)
if killStreakLevel:
textTitle = PLocalizer.PVPSinkStreak1
if killStreakLevel == 1:
textTitle = PLocalizer.PVPSinkStreak1
elif killStreakLevel == 2:
textTitle = PLocalizer.PVPSinkStreak2
elif killStreakLevel == 3:
textTitle = PLocalizer.PVPSinkStreak3
textSecondarytitle = '+%d ' % (killStreakBonus,) + PLocalizer.PVPInfamySea
base.localAvatar.guiMgr.createTitle(textTitle)
base.localAvatar.guiMgr.createSecondaryTitle(textSecondarytitle)
elif self.isLocal() and self.guiMgr and self.guiMgr.pvpPanel and hasattr(self.guiMgr.pvpPanel, 'renownDisplay') and self.guiMgr.pvpPanel.renownDisplay:
prevRank = TitleGlobals.getRank(TitleGlobals.LandPVPTitle, self.getInfamyLand())
newRank = TitleGlobals.getRank(TitleGlobals.LandPVPTitle, self.getInfamyLand() + renown)
if prevRank < newRank:
self.levelUpMsg(InventoryType.PVPTotalInfamyLand, newRank, 0)
if killStreakLevel:
textTitle = PLocalizer.PVPSinkStreak1
textSecondarytitle = '+%d ' % (killStreakBonus,) + PLocalizer.PVPInfamySea
base.localAvatar.guiMgr.createTitle(textTitle)
base.localAvatar.guiMgr.createSecondaryTitle(textSecondarytitle)
if localAvatar.guiMgr and hasattr(localAvatar.guiMgr, 'titlesPage') and localAvatar.guiMgr.titlesPage:
taskMgr.doMethodLater(1.3999999999999999, localAvatar.guiMgr.titlesPage.refresh, 'titles-refresh', [])
self.refreshName()
def sendSalvageMessage(self, targetId, amount):
target = base.cr.doId2do.get(targetId)
if target:
colorSetting = 9
if hasattr(target, 'printExpText'):
target.printExpText(amount, colorSetting, 0, 0, 0, 0, 0)
self.refreshName()
def _DistributedPlayerPirate__cleanupPopupDialog(self, value = None):
if self.popupDialog:
self.popupDialog.destroy()
self.popupDialog = None
def sendFreeInventoryMessage(self, type):
if not self.popupDialog:
if type == InventoryType.ItemTypeWeapon or type == InventoryType.ItemTypeCharm:
text = PLocalizer.FreeWeaponInventoryMessage
elif type == InventoryType.ItemTypeClothing:
text = PLocalizer.FreeClothingInventoryMessage
elif type == InventoryType.ItemTypeJewelry:
text = PLocalizer.FreeJewelryInventoryMessage
elif type == InventoryType.ItemTypeTattoo:
text = PLocalizer.FreeTattooInventoryMessage
self.popupDialog = PDialog.PDialog(text = text, style = OTPDialog.Acknowledge, command = self._DistributedPlayerPirate__cleanupPopupDialog)
def sendFailedLootTradeMessage(self, tellAgain):
if tellAgain:
text = PLocalizer.FailedLootTradeTryAgainMessage
else:
text = PLocalizer.FailedLootTradeMessage
self.guiMgr.createWarning(text, PiratesGuiGlobals.TextFG6, duration = 10)
def setLevel(self, level):
DistributedBattleAvatar.setLevel(self, level)
self.refreshName()
def getLevel(self):
return self.level
def levelUpMsg(self, category, level, messageId):
isSupressed = category in self._DistributedPlayerPirate__surpressedRepFlags
if self.isLocal():
if isSupressed == False:
self.guiMgr.bufferLevelUpText(category, level)
messenger.send('weaponChange')
if self.isLocal():
messenger.send('localLevelUp')
if category == InventoryType.DefenseCannonRep:
messenger.send('defenseCannonLevelUp', [
level])
if isSupressed == False:
self.playLevelUpEffect()
def surpressRepFlag(self, flag):
self._DistributedPlayerPirate__surpressedRepFlags.append(flag)
def clearRepFlags(self):
self._DistributedPlayerPirate__surpressedRepFlags = []
def playLevelUpEffect(self):
effect = LevelUpEffect.getEffect()
if effect:
effect.reparentTo(self)
effect.particleDummy.reparentTo(self)
effect.setPos(0, 0, 0)
effect.play()
def b_setDefaultShard(self, defaultShard):
if self.defaultShard != defaultShard:
self.d_setDefaultShard(defaultShard)
self.setDefaultShard(defaultShard)
b_setDefaultShard = report(types = [
'frameCount',
'args'], dConfigParam = 'login')(b_setDefaultShard)
def d_setDefaultShard(self, defaultShard):
self.sendUpdate('setDefaultShard', [
defaultShard])
d_setDefaultShard = report(types = [
'frameCount',
'args'], dConfigParam = 'login')(d_setDefaultShard)
def setDefaultShard(self, defaultShard):
self.defaultShard = defaultShard
setDefaultShard = report(types = [
'frameCount',
'args'], dConfigParam = 'login')(setDefaultShard)
def getDefaultShard(self):
return self.defaultShard
getDefaultShard = report(types = [
'frameCount'], dConfigParam = 'login')(getDefaultShard)
def setDefaultZone(self, zone):
self.defaultZone = zone
def d_requestReturnLocation(self, locationDoId):
self.sendUpdate('requestReturnLocation', [
locationDoId])
d_requestReturnLocation = report(types = [
'frameCount',
'args'], dConfigParam = 'jail')(d_requestReturnLocation)
def setReturnLocation(self, returnLocation):
if __dev__ and not getBase().config.GetBool('login-location-used-setRetLoc', False):
bp.loginCfg()
ConfigVariableBool('login-location-used-setRetLoc').setValue(True)
config_location = getBase().config.GetString('login-location', '').lower()
config_location_uid = PLocalizer.LocationUids.get(config_location)
if config_location and config_location_uid:
returnLocation = config_location_uid
if returnLocation == '1142018473.22dxschafe':
returnLocation = LocationIds.DEL_FUEGO_ISLAND
self.returnLocation = returnLocation
setReturnLocation = report(types = [
'frameCount',
'args'], dConfigParam = 'jail')(setReturnLocation)
def getReturnLocation(self):
return self.returnLocation
getReturnLocation = report(types = [
'frameCount'], dConfigParam = 'jail')(getReturnLocation)
def d_requestCurrentIsland(self, locationDoId):
self.sendUpdate('requestCurrentIsland', [
locationDoId])
d_requestCurrentIsland = report(types = [
'frameCount',
'args'], dConfigParam = 'map')(d_requestCurrentIsland)
def setCurrentIsland(self, islandUid):
self.currentIsland = islandUid
setCurrentIsland = report(types = [
'frameCount',
'args'], dConfigParam = 'map')(setCurrentIsland)
def getCurrentIsland(self):
return self.currentIsland
getCurrentIsland = report(types = [
'frameCount'], dConfigParam = 'jail')(getCurrentIsland)
def setJailCellIndex(self, index):
self.jailCellIndex = index
if self.belongsInJail():
self.b_setTeleportFlag(PiratesGlobals.TFInJail)
else:
self.b_clearTeleportFlag(PiratesGlobals.TFInJail)
setJailCellIndex = report(types = [
'frameCount',
'args'], dConfigParam = 'jail')(setJailCellIndex)
def getJailCellIndex(self):
return self.jailCellIndex
getJailCellIndex = report(types = [
'frameCount'], dConfigParam = 'jail')(getJailCellIndex)
def belongsInJail(self):
return bool(self.jailCellIndex)
def addTransformationCollisions(self):
if self.cRay == None:
self.cRay = CollisionRay(0.0, 0.0, 4000.0, 0.0, 0.0, -1.0)
self.cRayNode = CollisionNode(self.taskName('cRay'))
self.cRayNode.addSolid(self.cRay)
self.cRayNode.setFromCollideMask(PiratesGlobals.FloorBitmask | PiratesGlobals.ShipFloorBitmask)
self.cRayNode.setIntoCollideMask(BitMask32.allOff())
self.cRayNode.setBounds(BoundingSphere())
self.cRayNode.setFinal(1)
self.cRayNodePath = self.attachNewNode(self.cRayNode)
self.creatureQueue = CollisionHandlerQueue()
base.cTrav.addCollider(self.cRayNodePath, self.creatureQueue)
def removeTransformationCollisions(self):
if self.cRayNodePath:
base.cTrav.removeCollider(self.cRayNodePath)
self.cRayNodePath.removeNode()
self.cRayNodePath = None
if self.cRayNode:
self.cRayNode = None
if self.cRay:
self.cRay = None
if self.creatureQueue:
self.creatureQueue = None
def transformationTrackTerrain(self, task):
if self.creatureTransformation:
base.cTrav.traverse(render)
if self.creatureQueue.getNumEntries() > 0:
self.creatureQueue.sortEntries()
collEntry = self.creatureQueue.getEntry(0)
self.floorNorm = collEntry.getInto().getNormal()
gNode = self.creature
if gNode and not gNode.isEmpty():
if self.gTransNodeFwdPt == None:
self.gTransNodeFwdPt = gNode.getRelativePoint(self, Point3(0, 1, 0))
gNode.headsUp(self.gTransNodeFwdPt, self.getRelativeVector(self.getParentObj(), self.floorNorm))
return Task.cont
def getCreatureTransformation(self):
return (self.creatureTransformation, self.creatureId)
def setupCreature(self, avatarType):
if not self.creature:
self.creature = DistributedCreature.CreatureTypes[avatarType.getNonBossType()]()
self.creature.setAvatarType(avatarType)
self.creature.getGeomNode().setH(-180)
parent = self.find('**/actorGeom')
self.creature.reparentTo(parent)
self.creature.loop('idle')
maxLevel = EnemyGlobals.getMinEnemyLevel(avatarType)
enemyScale = EnemyGlobals.getEnemyScaleByType(avatarType, maxLevel)
self.creature.setAvatarScale(self.creature.scale * enemyScale)
if base.options.getCharacterDetailSetting() == 0:
self.creature.getLODNode().forceSwitch(2)
def deleteCreature(self):
if self.creature:
self.creature.detachNode()
self.creature.delete()
self.creature = None
def _setCreatureTransformation(self, value, effectId):
if self.creatureTransformation == value:
return None
self.creatureTransformation = value
self.creatureId = effectId
geom = self.getGeomNode()
if value:
self.addTransformationCollisions()
taskMgr.add(self.transformationTrackTerrain, self.uniqueName('transformationTrackTerrain'))
if effectId == PotionGlobals.C_CRAB_TRANSFORM:
self.setupCreature(AvatarTypes.RockCrab)
elif effectId == PotionGlobals.C_ALLIGATOR_TRANSFORM:
self.setupCreature(AvatarTypes.Alligator)
elif effectId == PotionGlobals.C_SCORPION_TRANSFORM:
self.setupCreature(AvatarTypes.Scorpion)
self.deleteDropShadow()
geom.stash()
else:
self.removeTransformationCollisions()
taskMgr.remove(self.uniqueName('transformationTrackTerrain'))
geom.setHpr(Vec3(180, 0, 0))
self.initializeDropShadow()
self.deleteCreature()
geom.unstash()
def playTransformationToCreature(self, effectId):
JRSpawn = JRSpawn
import pirates.effects.JRSpawn
if self.transformationEffect:
self.transformationEffect.detachNode()
self.transformationEffect = None
if self.transformationIval:
self.transformationIval.clearToInitial()
self.transformationIval = None
self.transformationEffect = JRSpawn.getEffect()
if self.transformationEffect:
self.transformationEffect.reparentTo(self)
self.transformationEffect.setPos(0, 1, 0)
self.transformationIval = Sequence(Func(self.motionFSM.off), Func(self.transformationEffect.play), Func(self.play, 'death3'), Wait(1.7), Func(self._setCreatureTransformation, True, effectId), Func(self.motionFSM.on))
self.transformationIval.start()
def playTransformationToPirate(self, effectId):
JRSpawn = JRSpawn
import pirates.effects.JRSpawn
if self.transformationEffect:
self.transformationEffect.detachNode()
self.transformationEffect = None
if self.transformationIval:
self.transformationIval.clearToInitial()
self.transformationIval = None
self.transformationEffect = JRSpawn.getEffect()
if self.transformationEffect:
self.transformationEffect.reparentTo(self)
self.transformationEffect.setPos(0, 1, 0)
self.transformationIval = Sequence(name = 'transformationIval')
if self.doLongHumanTransform():
self.transformationIval.append(Func(self.motionFSM.off))
self.transformationIval.append(Func(self.transformationEffect.play))
self.transformationIval.append(Func(self._setCreatureTransformation, False, effectId))
if self.doLongHumanTransform():
self.transformationIval.append(Func(self.play, 'jail_standup', fromFrame = 65))
self.transformationIval.append(Wait(1.7))
self.transformationIval.append(Func(self.motionFSM.on))
self.transformationIval.start()
def doLongHumanTransform(self):
state = self.gameFSM.getCurrentOrNextState()
if state in ('WaterRoam', 'WaterTreasureRoam', 'TeleportOut', 'ShipBoarding', 'EnterTunnel'):
return False
else:
return True
def setCreatureTransformation(self, value, effectId):
if self.creatureTransformation == value:
return None
if value:
self.playTransformationToCreature(effectId)
else:
self.playTransformationToPirate(effectId)
def addTransformationCollisions(self):
if self.cRay == None:
self.cRay = CollisionRay(0.0, 0.0, 4000.0, 0.0, 0.0, -1.0)
self.cRayNode = CollisionNode(self.taskName('cRay'))
self.cRayNode.addSolid(self.cRay)
self.cRayNode.setFromCollideMask(PiratesGlobals.FloorBitmask | PiratesGlobals.ShipFloorBitmask)
self.cRayNode.setIntoCollideMask(BitMask32.allOff())
self.cRayNode.setBounds(BoundingSphere())
self.cRayNode.setFinal(1)
self.cRayNodePath = self.attachNewNode(self.cRayNode)
self.creatureQueue = CollisionHandlerQueue()
base.cTrav.addCollider(self.cRayNodePath, self.creatureQueue)
def removeTransformationCollisions(self):
if self.cRayNodePath:
base.cTrav.removeCollider(self.cRayNodePath)
self.cRayNodePath.removeNode()
self.cRayNodePath = None
if self.cRayNode:
self.cRayNode = None
if self.cRay:
self.cRay = None
if self.creatureQueue:
self.creatureQueue = None
def transformationTrackTerrain(self, task):
if self.gameFSM.state == 'WaterRoam':
self.creature.setP(0)
self.creature.setR(0)
return Task.cont
if not isinstance(self.getParentObj(), NodePath):
return Task.cont
if self.creatureTransformation:
base.cTrav.traverse(render)
if self.creatureQueue.getNumEntries() > 0:
self.creatureQueue.sortEntries()
collEntry = self.creatureQueue.getEntry(0)
self.floorNorm = collEntry.getInto().getNormal()
gNode = self.creature
if gNode and not gNode.isEmpty():
if self.gTransNodeFwdPt == None:
self.gTransNodeFwdPt = gNode.getRelativePoint(self, Point3(0, 1, 0))
gNode.headsUp(self.gTransNodeFwdPt, self.getRelativeVector(self.getParentObj(), self.floorNorm))
return Task.cont
def getCreatureTransformation(self):
return (self.creatureTransformation, self.creatureId)
def setupCreature(self, avatarType):
if not self.creature:
self.creature = DistributedCreature.CreatureTypes[avatarType.getNonBossType()]()
self.creature.setAvatarType(avatarType)
self.creature.getGeomNode().setH(-180)
parent = self.find('**/actorGeom')
self.creature.reparentTo(parent)
self.creature.loop('idle')
maxLevel = EnemyGlobals.getMinEnemyLevel(avatarType)
enemyScale = EnemyGlobals.getEnemyScaleByType(avatarType, maxLevel)
self.creature.setAvatarScale(self.creature.scale * enemyScale)
if base.options.getCharacterDetailSetting() == 0:
self.creature.getLODNode().forceSwitch(2)
self.creature.shadowPlacer.on()
def deleteCreature(self):
if self.creature:
self.creature.detachNode()
self.creature.delete()
self.creature = None
def _setCreatureTransformation(self, value, effectId):
if self.creatureTransformation == value:
return None
self.creatureTransformation = value
self.creatureId = effectId
geom = self.getGeomNode()
if value:
self.addTransformationCollisions()
taskMgr.add(self.transformationTrackTerrain, self.uniqueName('transformationTrackTerrain'))
if effectId == PotionGlobals.C_CRAB_TRANSFORM:
self.setupCreature(AvatarTypes.RockCrab)
elif effectId == PotionGlobals.C_ALLIGATOR_TRANSFORM:
self.setupCreature(AvatarTypes.BayouGator)
self.creature.setToNormal()
elif effectId == PotionGlobals.C_SCORPION_TRANSFORM:
self.setupCreature(AvatarTypes.Scorpion)
self.deleteDropShadow()
geom.stash()
self.motionFSM.avHeight = 1
else:
self.removeTransformationCollisions()
taskMgr.remove(self.uniqueName('transformationTrackTerrain'))
geom.setHpr(Vec3(180, 0, 0))
self.initializeDropShadow()
self.deleteCreature()
geom.unstash()
self.motionFSM.avHeight = 5
def playTransformationToCreature(self, effectId, timeSince = 0):
JRSpawn = JRSpawn
import pirates.effects.JRSpawn
if self.transformationEffect:
self.transformationEffect.detachNode()
self.transformationEffect = None
if self.transformationIval:
self.transformationIval.clearToInitial()
self.transformationIval = None
def startSFX(effectId):
sfx = None
if effectId == PotionGlobals.C_CRAB_TRANSFORM:
sfx = self.crabSound
elif effectId == PotionGlobals.C_ALLIGATOR_TRANSFORM:
sfx = self.alligatorSound
elif effectId == PotionGlobals.C_SCORPION_TRANSFORM:
sfx = self.scorpionSound
if sfx:
base.playSfx(sfx, node = self, cutoff = 100)
if timeSince > 1.5 or self.gameFSM.state not in [
'LandRoam',
'Battle']:
self.transformationIval = Func(self._setCreatureTransformation, True, effectId)
else:
self.transformationEffect = JRSpawn.getEffect()
if self.transformationEffect:
self.transformationEffect.reparentTo(self)
self.transformationEffect.setPos(0, 1, 0)
self.transformationIval = Sequence(Func(self.motionFSM.off, lock = True), Func(startSFX, effectId), Func(self.transformationEffect.play), Func(self.play, 'death3'), Wait(1.7), Func(self._setCreatureTransformation, True, effectId), Func(self.motionFSM.on, unlock = True))
self.transformationIval.start()
def playTransformationToPirate(self, effectId):
JRSpawn = JRSpawn
import pirates.effects.JRSpawn
def startSFX():
sfx = self.genericTransformation
if sfx:
base.playSfx(sfx, node = self, cutoff = 100)
if self.transformationEffect:
self.transformationEffect.detachNode()
self.transformationEffect = None
if self.transformationIval:
self.transformationIval.clearToInitial()
self.transformationIval = None
if self.gameFSM.state not in [
'LandRoam',
'Battle']:
self.transformationIval = Func(self._setCreatureTransformation, False, effectId)
else:
self.transformationEffect = JRSpawn.getEffect()
if self.transformationEffect:
self.transformationEffect.reparentTo(self)
self.transformationEffect.setPos(0, 1, 0)
self.transformationIval = Sequence(name = 'transformationIval')
if self.doLongHumanTransform():
self.transformationIval.append(Func(self.motionFSM.off))
self.transformationIval.append(Func(startSFX))
self.transformationIval.append(Func(self.transformationEffect.play))
self.transformationIval.append(Func(self._setCreatureTransformation, False, effectId))
if self.doLongHumanTransform():
self.transformationIval.append(Func(self.play, 'jail_standup', fromFrame = 65))
self.transformationIval.append(Wait(1.7))
self.transformationIval.append(Func(self.motionFSM.on))
self.transformationIval.start()
def doLongHumanTransform(self):
state = self.gameFSM.getCurrentOrNextState()
if state in ('WaterRoam', 'WaterTreasureRoam', 'TeleportOut', 'ShipBoarding', 'EnterTunnel'):
return False
else:
return True
def setCreatureTransformation(self, value, effectId, timeSince = 0):
if self.creatureTransformation == value:
return None
if value:
self.playTransformationToCreature(effectId, timeSince)
else:
self.playTransformationToPirate(effectId)
def addTransformationCollisions(self):
if self.cRay == None:
self.cRay = CollisionRay(0.0, 0.0, 4000.0, 0.0, 0.0, -1.0)
self.cRayNode = CollisionNode(self.taskName('cRay'))
self.cRayNode.addSolid(self.cRay)
self.cRayNode.setFromCollideMask(PiratesGlobals.FloorBitmask | PiratesGlobals.ShipFloorBitmask)
self.cRayNode.setIntoCollideMask(BitMask32.allOff())
self.cRayNode.setBounds(BoundingSphere())
self.cRayNode.setFinal(1)
self.cRayNodePath = self.attachNewNode(self.cRayNode)
self.creatureQueue = CollisionHandlerQueue()
base.cTrav.addCollider(self.cRayNodePath, self.creatureQueue)
def removeTransformationCollisions(self):
if self.cRayNodePath:
base.cTrav.removeCollider(self.cRayNodePath)
self.cRayNodePath.removeNode()
self.cRayNodePath = None
if self.cRayNode:
self.cRayNode = None
if self.cRay:
self.cRay = None
if self.creatureQueue:
self.creatureQueue = None
def transformationTrackTerrain(self, task):
if self.gameFSM.state == 'WaterRoam':
self.creature.setP(0)
self.creature.setR(0)
return Task.cont
if not isinstance(self.getParentObj(), NodePath):
return Task.cont
if self.creatureTransformation:
base.cTrav.traverse(render)
if self.creatureQueue.getNumEntries() > 0:
self.creatureQueue.sortEntries()
collEntry = self.creatureQueue.getEntry(0)
self.floorNorm = collEntry.getInto().getNormal()
gNode = self.creature
if gNode and not gNode.isEmpty():
if self.gTransNodeFwdPt == None:
self.gTransNodeFwdPt = gNode.getRelativePoint(self, Point3(0, 1, 0))
gNode.headsUp(self.gTransNodeFwdPt, self.getRelativeVector(self.getParentObj(), self.floorNorm))
return Task.cont
def getCreatureTransformation(self):
return (self.creatureTransformation, self.creatureId)
def setupCreature(self, avatarType):
if not self.creature:
self.creature = DistributedCreature.CreatureTypes[avatarType.getNonBossType()]()
self.creature.setAvatarType(avatarType)
self.creature.getGeomNode().setH(-180)
parent = self.find('**/actorGeom')
self.creature.reparentTo(parent)
self.creature.loop('idle')
maxLevel = EnemyGlobals.getMinEnemyLevel(avatarType)
enemyScale = EnemyGlobals.getEnemyScaleByType(avatarType, maxLevel)
self.creature.setAvatarScale(self.creature.scale * enemyScale)
if base.options.getCharacterDetailSetting() == 0:
self.creature.getLODNode().forceSwitch(2)
self.creature.shadowPlacer.on()
def deleteCreature(self):
if self.creature:
self.creature.detachNode()
self.creature.delete()
self.creature = None
def _setCreatureTransformation(self, value, effectId):
if self.creatureTransformation == value:
return None
self.creatureTransformation = value
self.creatureId = effectId
geom = self.getGeomNode()
if value:
self.addTransformationCollisions()
taskMgr.add(self.transformationTrackTerrain, self.uniqueName('transformationTrackTerrain'))
if effectId == PotionGlobals.C_CRAB_TRANSFORM:
self.setupCreature(AvatarTypes.RockCrab)
elif effectId == PotionGlobals.C_ALLIGATOR_TRANSFORM:
self.setupCreature(AvatarTypes.BayouGator)
self.creature.setToNormal()
elif effectId == PotionGlobals.C_SCORPION_TRANSFORM:
self.setupCreature(AvatarTypes.Scorpion)
self.deleteDropShadow()
geom.stash()
self.motionFSM.avHeight = 1
else:
self.removeTransformationCollisions()
taskMgr.remove(self.uniqueName('transformationTrackTerrain'))
geom.setHpr(Vec3(180, 0, 0))
self.initializeDropShadow()
self.deleteCreature()
geom.unstash()
self.motionFSM.avHeight = 5
def playTransformationToCreature(self, effectId, timeSince = 0):
JRSpawn = JRSpawn
import pirates.effects.JRSpawn
if self.transformationEffect:
self.transformationEffect.detachNode()
self.transformationEffect = None
if self.transformationIval:
self.transformationIval.clearToInitial()
self.transformationIval = None
def startSFX(effectId):
sfx = None
if effectId == PotionGlobals.C_CRAB_TRANSFORM:
sfx = self.crabSound
elif effectId == PotionGlobals.C_ALLIGATOR_TRANSFORM:
sfx = self.alligatorSound
elif effectId == PotionGlobals.C_SCORPION_TRANSFORM:
sfx = self.scorpionSound
if sfx:
base.playSfx(sfx, node = self, cutoff = 100)
if timeSince > 1.5 or self.gameFSM.state not in [
'LandRoam',
'Battle']:
self.transformationIval = Func(self._setCreatureTransformation, True, effectId)
else:
self.transformationEffect = JRSpawn.getEffect()
if self.transformationEffect:
self.transformationEffect.reparentTo(self)
self.transformationEffect.setPos(0, 1, 0)
self.transformationIval = Sequence(Func(self.motionFSM.off, lock = True), Func(startSFX, effectId), Func(self.transformationEffect.play), Func(self.play, 'death3'), Wait(1.7), Func(self._setCreatureTransformation, True, effectId), Func(self.motionFSM.on, unlock = True))
self.transformationIval.start()
def playTransformationToPirate(self, effectId):
JRSpawn = JRSpawn
import pirates.effects.JRSpawn
def startSFX():
sfx = self.genericTransformation
if sfx:
base.playSfx(sfx, node = self, cutoff = 100)
if self.transformationEffect:
self.transformationEffect.detachNode()
self.transformationEffect = None
if self.transformationIval:
self.transformationIval.clearToInitial()
self.transformationIval = None
if self.gameFSM.state not in [
'LandRoam',
'Battle']:
self.transformationIval = Func(self._setCreatureTransformation, False, effectId)
else:
self.transformationEffect = JRSpawn.getEffect()
if self.transformationEffect:
self.transformationEffect.reparentTo(self)
self.transformationEffect.setPos(0, 1, 0)
self.transformationIval = Sequence(name = 'transformationIval')
if self.doLongHumanTransform():
self.transformationIval.append(Func(self.motionFSM.off))
self.transformationIval.append(Func(startSFX))
self.transformationIval.append(Func(self.transformationEffect.play))
self.transformationIval.append(Func(self._setCreatureTransformation, False, effectId))
if self.doLongHumanTransform():
self.transformationIval.append(Func(self.play, 'jail_standup', fromFrame = 65))
self.transformationIval.append(Wait(1.7))
self.transformationIval.append(Func(self.motionFSM.on))
self.transformationIval.start()
def doLongHumanTransform(self):
state = self.gameFSM.getCurrentOrNextState()
if state in ('WaterRoam', 'WaterTreasureRoam', 'TeleportOut', 'ShipBoarding', 'EnterTunnel'):
return False
else:
return True
def setCreatureTransformation(self, value, effectId, timeSince = 0):
if self.creatureTransformation == value:
return None
if value:
self.playTransformationToCreature(effectId, timeSince)
else:
self.playTransformationToPirate(effectId)
def changeBodyType(self):
self.generateHuman(self.style.gender, self.masterHuman)
if self.motionFSM.state != 'Off':
self.motionFSM.off()
self.motionFSM.on()
def generateHuman(self, *args, **kwargs):
if base.cr.newsManager and base.cr.newsManager.getHoliday(HolidayGlobals.APRILFOOLS) == 1:
self.setJewelryZone5(10)
DistributedPirateBase.generateHuman(self, *args, **args)
self.getGeomNode().setScale(self.scale)
self.setHeight(self.height)
self.maintainEffects()
if self.potionStatusEffectManager:
self.potionStatusEffectManager.maintainEffects()
def maintainEffects(self):
if self.isInvisible():
self.activateInvisibleEffect()
if self.creatureTransformation:
self.getGeomNode().stash()
def setAvatarSkinCrazy(self, value, colorIndex = 0, timeSince = 0):
if self.crazyColorSkin == value:
return None
self.crazyColorSkin = value
self.crazySkinColorEffect = colorIndex
if self.crazyColorSkin == True:
self.setCrazyColorSkinIndex(colorIndex)
if self.crazySkinColorIval:
self.crazySkinColorIval.clearToInitial()
self.crazySkinColorIval = None
self.crazySkinColorIval = self.getTransformSequence(None, self.changeBodyType, [], timeSince)
self.crazySkinColorIval.start()
def setAvatarScale(self, scale):
if self.dropShadow:
self.dropShadow.setScale(scale)
Avatar.setAvatarScale(self, scale)
def playScaleChangeAnimation(self, scale, timeSince = 0):
if self.scaleChangeIval:
self.scaleChangeIval.clearToInitial()
self.scaleChangeIval = None
if scale < 1.0:
soundEffect = self.shrinkSound
elif scale > 1.0:
soundEffect = self.growSound
else:
soundEffect = self.genericTransformation
self.scaleChangeIval = self.getTransformSequence(soundEffect, self.setAvatarScale, [
scale], timeSince)
self.scaleChangeIval.start()
def getTransformSequence(self, sfx, func = None, args = [], timeSince = 0):
JRSpawn = JRSpawn
import pirates.effects.JRSpawn
if timeSince > 1.5 or self.gameFSM.state not in [
'LandRoam',
'Battle']:
return Func(func, *args)
seq = Sequence(name = self.uniqueName('transformationIval'))
if sfx == None:
sfx = self.genericTransformation
def startSFX(sfx):
if sfx:
base.playSfx(sfx, node = self, cutoff = 100)
self.transformSeqEffect = JRSpawn.getEffect()
if self.transformSeqEffect:
self.transformSeqEffect.reparentTo(self)
self.transformSeqEffect.setPos(0, 1, 0)
seq.append(Func(self.motionFSM.off, lock = True))
seq.append(Func(startSFX, sfx))
seq.append(Func(self.transformSeqEffect.play))
seq.append(Func(self.play, 'death3'))
seq.append(Wait(1.7))
if func is not None:
seq.append(Func(func, *args))
seq.append(Func(self.play, 'jail_standup', fromFrame = 65))
seq.append(Wait(2.25))
seq.append(Func(self.motionFSM.on, unlock = True))
return seq
def stopTransformAnims(self):
self.isGiant = False
self.isTiny = False
if self.scaleChangeIval:
self.scaleChangeIval.clearToInitial()
self.scaleChangeIval = None
self.crazyColorSkin = False
if self.crazySkinColorIval:
self.crazySkinColorIval.clearToInitial()
self.crazySkinColorIval = None
if self.transformSeqEffect:
self.transformSeqEffect.detachNode()
self.transformSeqEffect = None
self.setCrazyColorSkinIndex(0)
self.setAvatarScale(1.0)
self.changeBodyType()
if self.potionStatusEffectManager:
self.potionStatusEffectManager.stopTransformAnims()
if self.motionFSM.isLocked():
self.motionFSM.unlock()
def setZombie(self, value, cursed = False):
hiddenNode = self.getHiddenAncestor()
if hiddenNode:
pass
needToHide = hiddenNode.compareTo(self) == 0
if self.zombie == value:
return None
self.zombie = value
self.cursed = cursed
self.changeBodyType()
self._zombieSV.set(self.zombie)
if needToHide:
self.hide()
def isUndead(self):
return self.zombie
def respawn(self):
self.motionFSM.on()
self.unstashBattleCollisions()
self.startCompassEffect()
self.show(invisibleBits = PiratesGlobals.INVIS_DEATH)
def setWishName(self):
self.cr.sendWishName(self.doId, self.style.name)
def canTeleport(self):
return (self.teleportFlags & PiratesGlobals.TFNoTeleportOut).isZero()
def canTeleportTo(self):
return (self.teleportFlags & PiratesGlobals.TFNoTeleportTo).isZero()
def testTeleportFlag(self, flag):
return not (self.teleportFlags & flag).isZero()
def getNextTeleportConfirmFlag(self, currentFlag = None, flags = None):
if not currentFlag:
pass
currentFlag = BitMask32()
if not flags:
pass
flags = BitMask32(self.teleportFlags)
flags &= PiratesGlobals.TFNoTeleportOut
return flags.keepNextHighestBit(currentFlag)
def getNextTeleportToConfirmFlag(self, currentFlag = None, flags = None):
if not currentFlag:
pass
currentFlag = BitMask32()
if not flags:
pass
flags = BitMask32(self.teleportFlags)
flags &= PiratesGlobals.TFNoTeleportTo
return flags.keepNextHighestBit(currentFlag)
def getNoTeleportString(self, flag = None):
if not flag:
pass
flag = self.teleportFlags.keepNextHighestBit()
if not flag.isZero():
return PiratesGlobals.TFNoTeleportReasons.get(flag, '')
return ''
def getNoTeleportToString(self, flag = None):
if not flag:
pass
flag = self.teleportFlags.keepNextHighestBit()
if not flag.isZero():
return PiratesGlobals.TFNoTeleportToReasons.get(flag, '')
return ''
def confirmTeleport(self, callback, feedback = False):
if not self.canTeleport():
flag = self.getNextTeleportConfirmFlag()
while not flag.isZero():
(confirmFunc, confirmArgs) = self.teleportConfirmCallbacks.get(flag, (None, []))
if confirmFunc and confirmFunc('from', 0, 0, 0, 0, *confirmArgs):
flag = self.getNextTeleportConfirmFlag(flag)
continue
if feedback:
if self.guiMgr.mapPage:
self.guiMgr.mapPage.shardPanel.refreshCurrentShard()
self.guiMgr.createWarning(self.getNoTeleportString(flag), PiratesGuiGlobals.TextFG6, duration = 10)
callback(False)
return None
callback(True)
confirmTeleport = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(confirmTeleport)
def confirmTeleportTo(self, callback, avId, avName, bandMgrId, bandId, guildId):
flag = self.getNextTeleportToConfirmFlag()
while not flag.isZero():
(confirmFunc, confirmArgs) = self.teleportConfirmCallbacks.get(flag, (None, []))
if confirmFunc and confirmFunc('to', avId, bandMgrId, bandId, guildId, *confirmArgs):
flag = self.getNextTeleportToConfirmFlag(flag)
continue
callback(False, avId, flag)
return None
callback(True, avId, flag)
confirmTeleportTo = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(confirmTeleportTo)
def b_setTeleportFlag(self, flag, confirmCallback = None, confirmArgs = []):
self.b_setTeleportFlags(self.teleportFlags | flag, {
flag: (confirmCallback, confirmArgs) })
b_setTeleportFlag = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(b_setTeleportFlag)
def setTeleportFlag(self, flag, confirmCallback = None, confirmArgs = []):
self.setTeleportFlags(self.teleportFlags | flag, {
flag: (confirmCallback, confirmArgs) })
def b_clearTeleportFlag(self, flag):
self.b_setTeleportFlags(self.teleportFlags & ~flag, {
flag: (None, []) })
def clearTeleportFlag(self, flag):
self.setTeleportFlags(self.teleportFlags & ~flag, {
flag: (None, []) })
def b_setTeleportFlags(self, flags, confirmDict):
if self.teleportFlags != flags:
self.d_setTeleportFlags(flags)
self.setTeleportFlags(flags, confirmDict)
def d_setTeleportFlags(self, flags):
self.sendUpdate('setTeleportFlags', [
flags.getWord()])
def setTeleportFlags(self, flags, confirmDict = { }):
self.teleportFlags = BitMask32(flags)
b = BitMask32.bit(31)
while not b.isZero():
if (b & self.teleportFlags).isZero():
self.teleportConfirmCallbacks.pop(b, None)
elif b in confirmDict:
self.teleportConfirmCallbacks[b] = confirmDict[b]
b = b >> 1
def getTeleportFlags(self):
return self.teleportFlags
def decipherTeleportFlags(self):
iter = BitMask32(1)
print self.teleportFlags, '-' * 80
while iter.getWord():
if (iter & self.teleportFlags).getWord():
print '%-4s' % iter.getHighestOnBit()
if not self.getNoTeleportString(iter):
pass
print self.getNoTeleportToString(iter)
iter <<= 1
def sendTeleportQuery(self, sendToId, localBandMgrId, localBandId, localGuildId, localShardId):
self.d_teleportQuery(localAvatar.doId, localBandMgrId, localBandId, localGuildId, localShardId, sendToId)
sendTeleportQuery = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(sendTeleportQuery)
def d_teleportQuery(self, localAvId, localBandMgrId, localBandId, localGuildId, localShardId, sendToId):
self.sendUpdate('teleportQuery', [
localAvId,
localBandMgrId,
localBandId,
localGuildId,
localShardId], sendToId = sendToId)
d_teleportQuery = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(d_teleportQuery)
def teleportQuery(self, requesterId, requesterBandMgrId, requesterBandId, requesterGuildId, requesterShardId):
pass
teleportQuery = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(teleportQuery)
def sendTeleportResponse(self, available, shardId, instanceDoId, areaDoId, sendToId = None):
self.d_teleportResponse(available, shardId, instanceDoId, areaDoId, sendToId)
sendTeleportResponse = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(sendTeleportResponse)
def d_teleportResponse(self, available, shardId, instanceDoId, areaDoId, sendToId = None):
self.sendUpdate('teleportResponse', [
localAvatar.doId,
available,
shardId,
instanceDoId,
areaDoId], sendToId)
d_teleportResponse = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(d_teleportResponse)
def teleportResponse(self, avId, available, shardId, instanceDoId, areaDoId):
pass
teleportResponse = report(types = [
'deltaStamp',
'args'], dConfigParam = 'teleport')(teleportResponse)
def teleportTokenCheck(self, token):
inv = self.getInventory()
if bool(inv):
pass
return inv.getStackQuantity(token)
def hasIslandTeleportToken(self, islandUid):
token = InventoryType.getIslandTeleportToken(islandUid)
return self.teleportTokenCheck(token)
def confirmIslandTokenTeleport(self, toFrom, incomingAvid = 0, bandMgrId = 0, bandId = 0, guildId = 0, islandUid = ''):
if toFrom == 'from':
if self.hasIslandTeleportToken(islandUid) and self.returnLocation == islandUid and self.currentIsland == islandUid and self.cr.distributedDistrict.worldCreator.isPvpIslandByUid(islandUid) and base.config.GetBool('teleport-all', 0) and islandUid == LocationIds.PORT_ROYAL_ISLAND and self.getInventory():
pass
return not self.getInventory().getShipDoIdList()
else:
return True
def confirmNotSameAreaTeleport(self, toFrom, incomingAvid = 0, bandMgrId = 0, bandId = 0, guildId = 0, islandUid = ''):
if toFrom == 'from':
try:
if self.getParentObj().getUniqueId() == islandUid:
return False
except AttributeError:
pass
return True
else:
return True
def confirmNotSameAreaTeleportToPlayer(self, toFrom, incomingAvid = 0, bandMgrId = 0, bandId = 0, guildId = 0, areaDoId = 0):
if toFrom == 'from':
try:
if self.getParentObj().doId == areaDoId:
return False
except AttributeError:
pass
return True
else:
return True
def confirmSwimmingTeleport(self, toFrom, incomingAvid = 0, bandMgrId = 0, bandId = 0, guildId = 0):
if toFrom == 'from':
return True
else:
return True
def setBandId(self, bandmanager, bandId):
if bandId:
self.BandId = (bandmanager, bandId)
else:
self.BandId = None
def getBandId(self):
return self.BandId
def isOnline(self):
return True
def isUnderstandable(self):
return True
def setPvp(self, value):
self.inPvp = value
self._inPvpSV.set(value)
def setParlorGame(self, value):
self.inParlorGame = value
if self.inParlorGame and self.isLocal():
self.guiMgr.crewHUD.setHUDOff()
self.guiMgr.crewHUDTurnedOff = True
def d_setBandPvp(self, value):
self.sendUpdate('setBandPvp', [
value])
def d_setBandParlor(self, value):
self.sendUpdate('setBandParlor', [
value])
def d_setBandDisconnect(self, value):
self.sendUpdate('setBandDisconnect', [
value])
def checkQuestRewardFlag(self, flag):
return not (self.questRewardFlags & flag).isZero()
def setQuestRewardFlags(self, flags):
self.questRewardFlags = BitMask32(flags)
def getQuestRewardFlags(self):
return self.questRewardFlags
def spentSkillPoint(self, category):
self.guiMgr.combatTray.skillTray.rebuildSkillTray()
self.guiMgr.combatTray.initCombatTray()
def resetSkillPoints(self, skillId):
self.guiMgr.combatTray.skillTray.rebuildSkillTray()
self.guiMgr.combatTray.initCombatTray()
def requestLookoutInvite(self, inviterId, inviterName, activityCategory, activityType, options):
if self.isLocal() and inviterId != localAvatar.doId:
self.guiMgr.lookoutPage.requestInvite(inviterName, activityCategory, activityType, options)
def unlimitedInviteNotice(self, activityCategory):
self.guiMgr.lookoutPage.unlimitedInviteNotice(activityCategory)
def scrubTalk(self, message, mods):
scrubbed = 0
text = copy.copy(message)
for mod in mods:
index = mod[0]
length = (mod[1] - mod[0]) + 1
newText = text[0:index] + length * '\x07' + text[index + length:]
text = newText
words = text.split(' ')
newwords = []
spaceCount = 0
for word in words:
if word == '':
spaceCount += 1
else:
spaceCount = 0
if word == '' and spaceCount > 10:
continue
if word == '':
newwords.append(word)
continue
if word[0] == '\x07':
newwords.append('\x01WLDisplay\x01' + random.choice(PLocalizer.WhitelistScrubList) + '\x02')
scrubbed = 1
continue
if base.whiteList.isWord(word):
newwords.append(word)
continue
newwords.append('\x01WLDisplay\x01' + word + '\x02')
scrubbed = 1
newText = ' '.join(newwords)
return (newText, scrubbed)
def b_setSCEmote(self, emoteId):
self.setSCEmote(emoteId)
self.d_setSCEmote(emoteId)
def d_setSCEmote(self, emoteId):
self.sendUpdate('setSCEmote', [
emoteId])
def setSCEmote(self, emoteId):
if self.doId in base.localAvatar.ignoreList:
return None
base.talkAssistant.receiveOpenSpeedChat(ChatGlobals.SPEEDCHAT_EMOTE, emoteId, self.doId)
def b_setSpeedChatQuest(self, questInt, msgType, taskNum):
qId = QuestDB.getQuestIdFromQuestInt(questInt)
quest = self.getQuestById(qId)
if quest:
taskState = quest.getTaskStates()[taskNum]
self.setSpeedChatQuest(questInt, msgType, taskNum, taskState)
self.d_setSpeedChatQuest(questInt, msgType, taskNum, taskState)
def d_setSpeedChatQuest(self, questInt, msgType, taskNum, taskState):
self.sendUpdate('setSpeedChatQuest', [
questInt,
msgType,
taskNum,
taskState])
def setSpeedChatQuest(self, questInt, msgType, taskNum, taskState):
if self.doId in base.localAvatar.ignoreList:
return None
chatString = PSCDecoders.decodeSCQuestMsgInt(questInt, msgType, taskNum, taskState)
if chatString:
self.setChatAbsolute(chatString, CFSpeech | CFQuicktalker | CFTimeout)
base.talkAssistant.receiveOpenTalk(self.doId, self.getName(), None, None, chatString)
def whisperSCQuestTo(self, questInt, msgType, taskNum, sendToId):
messenger.send('wakeup')
self.sendUpdate('setWhisperSCQuest', [
self.doId,
questInt,
msgType,
taskNum], sendToId)
def setWhisperSCQuest(self, fromId, questInt, msgType, taskNum):
if fromId in base.localAvatar.ignoreList:
return None
fromHandle = base.cr.identifyAvatar(fromId)
if fromHandle:
fromName = fromHandle.getName()
else:
return None
chatString = PSCDecoders.decodeSCQuestMsgInt(questInt, msgType, taskNum)
base.talkAssistant.receiveWhisperTalk(fromId, fromName, None, None, self.doId, self.getName(), chatString)
def getAccess(self):
if Freebooter.AllAccessHoliday:
return 2
else:
return self.getGameAccess()
def setAccess(self, access):
self.setGameAccess(access)
def setGameAccess(self, access):
self.gameAccess = access
self.refreshName()
def getGameAccess(self):
return self.gameAccess
def setFounder(self, founder):
self.founder = founder
self.refreshName()
def getFounder(self):
return self.founder
def useBestTonic(self):
self.sendUpdate('useBestTonic', [])
def useTonic(self, tonicId):
self.sendUpdate('useTonic', [
tonicId])
def setPort(self, islandId):
self.port = islandId
if self.ship:
self.ship.checkAbleDropAnchor()
setPort = report(types = [
'frameCount',
'args'], dConfigParam = 'port')(setPort)
def clearPort(self, islandId):
if islandId == self.port:
self.port = 0
if self.ship:
self.ship.checkAbleDropAnchor()
clearPort = report(types = [
'frameCount',
'args'], dConfigParam = 'port')(clearPort)
def getPort(self):
return self.port
def enableWaterEffect(self):
if base.options.getSpecialEffectsSetting() < base.options.SpecialEffectsMedium:
return None
if not self.waterRipple:
self.waterRipple = WaterRipple.getEffect()
if self.waterRipple:
self.waterRipple.reparentTo(self)
self.waterRipple.startLoop()
if not self.waterWake:
self.waterWake = WaterRippleWake.getEffect()
if self.waterWake:
self.waterWake.reparentTo(self)
self.waterWake.startLoop()
if not self.waterSplash:
self.waterSplash = WaterRippleSplash.getEffect()
if self.waterSplash:
self.waterSplash.reparentTo(self)
self.waterSplash.startLoop()
def disableWaterEffect(self):
if base.options.getSpecialEffectsSetting() < base.options.SpecialEffectsMedium:
return None
if self.waterRipple:
self.waterRipple.stopLoop()
self.waterRipple = None
if self.waterWake:
self.waterWake.stopLoop()
self.waterWake = None
if self.waterSplash:
self.waterSplash.stopLoop()
self.waterSplash = None
def adjustWaterEffect(self, offset, forwardSpeed = 0.0, rotateSpeed = 0.0, slideSpeed = 0.0):
if base.options.getSpecialEffectsSetting() < base.options.SpecialEffectsMedium:
return None
if forwardSpeed == 0.0 and slideSpeed == 0.0:
if not self.waterRipple:
self.waterRipple = WaterRipple.getEffect()
if self.waterRipple:
self.waterRipple.reparentTo(self)
self.waterRipple.startLoop()
if self.waterWake:
self.waterWake.stopLoop()
self.waterWake = None
if self.waterSplash:
self.waterSplash.stopLoop()
self.waterSplash = None
elif not self.waterWake:
self.waterWake = WaterRippleWake.getEffect()
if self.waterWake:
self.waterWake.reparentTo(self)
self.waterWake.startLoop()
if not self.waterSplash:
self.waterSplash = WaterRippleSplash.getEffect()
if self.waterSplash:
self.waterSplash.reparentTo(self)
self.waterSplash.startLoop()
if self.waterRipple:
self.waterRipple.stopLoop()
self.waterRipple = None
if rotateSpeed != 0.0 and self.waterRipple:
self.waterRipple.disturbRipple()
if self.waterRipple:
self.waterRipple.setZ(offset)
if self.waterWake:
self.waterWake.setY(forwardSpeed / 9.5)
self.waterWake.setX(slideSpeed / 9.0)
self.waterWake.setZ(offset)
if self.waterSplash:
self.waterSplash.setX(slideSpeed / 20.0)
self.waterSplash.setZ(offset - 0.75)
def setCompositeDNA(self, *dna):
counter = 0
dclass = base.cr.dclassesByName['DistributedPlayerPirate']
field = dclass.getFieldByName('setCompositeDNA').asMolecularField()
for i in xrange(field.getNumAtomics()):
subField = field.getAtomic(i)
args = dna[counter:counter + subField.getNumElements()]
counter += subField.getNumElements()
getattr(self.style, subField.getName())(*args)
def announceClothingChange(self, *dna):
if self.isLocal():
return None
counter = 0
dclass = base.cr.dclassesByName['DistributedPlayerPirate']
field = dclass.getFieldByName('announceClothingChange').asMolecularField()
for i in xrange(field.getNumAtomics()):
subField = field.getAtomic(i)
args = dna[counter:counter + subField.getNumElements()]
counter += subField.getNumElements()
getattr(self.style, subField.getName())(*args)
self.generateHuman(self.style.getGender(), self.masterHuman)
self.motionFSM.off()
self.motionFSM.on()
def tryOnTattoo(self, tattooItem, location):
flipIt = 0
if location == 0:
equipFunction = self.setTattooChest
elif location == 1:
equipFunction = self.setTattooZone2
elif location == 2:
equipFunction = self.setTattooZone3
flipIt = 1
elif location == 3:
equipFunction = self.setTattooZone4
elif location == 4:
equipFunction = self.setTattooZone5
elif location == 5:
equipFunction = self.setTattooZone6
elif location == 6:
equipFunction = self.setTattooZone7
elif location == 7:
equipFunction = self.setTattooZone8
if tattooItem:
gender = self.style.getGender()
itemId = tattooItem.getId()
rarity = ItemGlobals.getRarity(itemId)
if rarity != ItemConstants.CRUDE and not Freebooter.getPaidStatus(base.localAvatar.getDoId()):
equipFunction(0, 0, 0, 0, 0, 0)
elif gender == 'm':
tattooId = ItemGlobals.getMaleModelId(itemId)
if flipIt:
tattooOrientation = ItemGlobals.getOrientation(ItemGlobals.getMaleOrientation2(itemId))
else:
tattooOrientation = ItemGlobals.getOrientation(ItemGlobals.getMaleOrientation(itemId))
else:
tattooId = ItemGlobals.getFemaleModelId(itemId)
if flipIt:
tattooOrientation = ItemGlobals.getOrientation(ItemGlobals.getFemaleOrientation2(itemId))
else:
tattooOrientation = ItemGlobals.getOrientation(ItemGlobals.getFemaleOrientation(itemId))
offsetx = tattooOrientation[0]
offsety = tattooOrientation[1]
scale = tattooOrientation[2]
rotate = tattooOrientation[3]
S = Vec2(1 / float(scale), 1 / float(scale))
Iv = Vec2(offsetx, offsety)
Vm = Vec2(sin(rotate * pi / 180.0), cos(rotate * pi / 180.0))
Vms = Vec2(Vm[0] * S[0], Vm[1] * S[1])
Vn = Vec2(Vm[1], -Vm[0])
Vns = Vec2(Vn[0] * S[0], Vn[1] * S[1])
F = Vec2(-Vns.dot(Iv) + 0.5, -Vms.dot(Iv) + 0.5)
color = 0
equipFunction(tattooId, F[0], F[1], S[0], rotate, color)
else:
equipFunction(0, 0, 0, 0, 0, 0)
self.doRegeneration()
def tryOnJewelry(self, jewelryItem, location):
equipFunction = None
if location == 0:
equipFunction = self.setJewelryZone3
elif location == 1:
equipFunction = self.setJewelryZone4
elif location == 2:
equipFunction = self.setJewelryZone1
elif location == 3:
equipFunction = self.setJewelryZone2
elif location == 4:
equipFunction = self.setJewelryZone5
elif location == 5:
equipFunction = self.setJewelryZone6
elif location == 6:
equipFunction = self.setJewelryZone7
elif location == 7:
equipFunction = self.setJewelryZone8
if equipFunction:
if jewelryItem != None:
gender = self.style.getGender()
itemId = jewelryItem.getId()
rarity = ItemGlobals.getRarity(itemId)
if rarity != ItemConstants.CRUDE and not Freebooter.getPaidStatus(base.localAvatar.getDoId()):
equipFunction(0, 0, 0)
elif gender == 'f':
modelIndex = ItemGlobals.getFemaleModelId(itemId)
else:
modelIndex = ItemGlobals.getMaleModelId(itemId)
equipFunction(modelIndex, ItemGlobals.getPrimaryColor(itemId), ItemGlobals.getSecondaryColor(itemId))
else:
equipFunction(0, 0, 0)
self.doRegeneration()
def requestClothesList(self):
self.sendUpdate('requestClothesList', [])
def receiveClothesList(self, clothesList):
messenger.send('received_clothes_list', [
clothesList])
def removeClothes(self, clothingType):
gender = self.style.getGender()
underwearTable = ClothingGlobals.UNDERWEAR.get(gender)
if underwearTable:
underwearTuple = underwearTable.get(clothingType, (0, 0, 0))
self.wearClothing(clothingType, underwearTuple[0], underwearTuple[1], underwearTuple[2])
def tryOnClothes(self, location, itemTuple):
gender = self.style.getGender()
rarity = ItemGlobals.getRarity(itemTuple[1])
if gender == 'f':
modelIndex = ItemGlobals.getFemaleModelId(itemTuple[1])
textureIndex = ItemGlobals.getFemaleTextureId(itemTuple[1])
else:
modelIndex = ItemGlobals.getMaleModelId(itemTuple[1])
textureIndex = ItemGlobals.getMaleTextureId(itemTuple[1])
colorIndex = itemTuple[3]
if (modelIndex == -1 or rarity != ItemConstants.CRUDE) and not Freebooter.getPaidStatus(base.localAvatar.getDoId()):
underwearTable = ClothingGlobals.UNDERWEAR.get(gender)
if underwearTable:
underwearTuple = underwearTable.get(location, (0, 0, 0))
modelIndex = underwearTuple[0]
textureIndex = underwearTuple[1]
colorIndex = underwearTuple[2]
else:
modelId = 0
texId = 0
colorId = 0
self.wearClothing(location, modelIndex, textureIndex, colorIndex)
def wearClothing(self, location, modelId, texId, colorId):
takenOff = 0
topColors = self.getStyle().getClothesTopColor()
botColors = self.getStyle().getClothesBotColor()
colorHat = self.getStyle().getHatColor()
colorShirt = topColors[0]
colorVest = topColors[1]
colorCoat = topColors[2]
colorPant = botColors[0]
colorSash = botColors[1]
colorShoe = botColors[2]
if location == ClothingGlobals.HAT:
self.getStyle().setClothesHat(modelId, texId)
colorHat = colorId
elif location == ClothingGlobals.SHIRT:
self.getStyle().setClothesShirt(modelId, texId)
colorShirt = colorId
elif location == ClothingGlobals.VEST:
self.getStyle().setClothesVest(modelId, texId)
colorVest = colorId
elif location == ClothingGlobals.COAT:
self.getStyle().setClothesCoat(modelId, texId)
colorCoat = colorId
elif location == ClothingGlobals.PANT:
self.getStyle().setClothesPant(modelId, texId)
colorPant = colorId
elif location == ClothingGlobals.BELT:
self.getStyle().setClothesBelt(modelId, texId)
colorSash = colorId
elif location == ClothingGlobals.SOCK:
self.getStyle().setClothesSock(modelId, texId)
elif location == ClothingGlobals.SHOE:
self.getStyle().setClothesShoe(modelId, texId)
colorShoe = colorId
if modelId == -1:
underwearTable = ClothingGlobals.UNDERWEAR.get(gender)
if underwearTable:
underwearTuple = underwearTable.get(location, (0, 0, 0))
modelId = underwearTuple[0]
texId = underwearTuple[1]
colorId = underwearTuple[2]
self.getStyle().setHatColor(colorHat)
self.getStyle().setClothesTopColor(colorShirt, colorVest, colorCoat)
self.getStyle().setClothesBotColor(colorPant, colorSash, colorShoe)
self.setClothesFromList(self.getClothesComposite())
self.doRegeneration()
def getClothesComposite(self):
clothesComposite = [
self.getStyle().getHatIdx(),
self.getStyle().getHatTexture(),
self.getStyle().getHatColor()] + self.getStyle().getClothesShirt() + self.getStyle().getClothesVest() + self.getStyle().getClothesCoat() + self.getStyle().getClothesBelt() + self.getStyle().getClothesPant() + self.getStyle().getClothesShoe() + self.getStyle().getClothesTopColor() + self.getStyle().getClothesBotColor()
return tuple(clothesComposite)
def setClothesFromList(self, dna):
counter = 0
dclass = base.cr.dclassesByName['DistributedPlayerPirate']
field = dclass.getFieldByName('setClothes').asMolecularField()
for i in xrange(field.getNumAtomics()):
subField = field.getAtomic(i)
args = dna[counter:counter + subField.getNumElements()]
counter += subField.getNumElements()
getattr(self.style, subField.getName())(*args)
messenger.send(self.uniqueName('accessoriesUpdate'))
def cueRegenerate(self, force = 0):
if self.gameFSM.state in [
'LandRoam',
'Battle',
'WaterRoam',
'Off']:
self.doRegeneration()
else:
self.needRegenFlag = 1
def askRegen(self):
if self.needRegenFlag:
self.doRegeneration()
def doRegeneration(self):
self.needRegenFlag = 0
if self.isLocal():
cameraPos = camera.getPos()
camOff = localAvatar.cameraFSM.getFPSCamera().camOffset
localAvatar.guiMgr.combatTray.endButtonCharge()
self.generateHuman(self.style.getGender(), self.masterHuman)
self.motionFSM.off()
self.motionFSM.on()
messenger.send(self.uniqueName('accessoriesUpdate'))
if self.isLocal():
camera.setPos(cameraPos)
localAvatar.cameraFSM.getFPSCamera().camOffset = camOff
def setClothes2(self, *dna):
if hasattr(self, 'clothingEquipBufferDict') and len(self.clothingEquipBufferDict.keys()) > 0:
return None
elif dna == self.getClothesComposite():
pass
else:
self.setClothesFromList(dna)
def setClothes(self, *dna):
counter = 0
dclass = base.cr.dclassesByName['DistributedPlayerPirate']
field = dclass.getFieldByName('setClothes').asMolecularField()
for i in xrange(field.getNumAtomics()):
subField = field.getAtomic(i)
args = dna[counter:counter + subField.getNumElements()]
counter += subField.getNumElements()
getattr(self.style, subField.getName())(*args)
messenger.send(self.uniqueName('accessoriesUpdate'))
def setHair(self, *dna):
counter = 0
dclass = base.cr.dclassesByName['DistributedPlayerPirate']
field = dclass.getFieldByName('setHair').asMolecularField()
for i in xrange(field.getNumAtomics()):
subField = field.getAtomic(i)
args = dna[counter:counter + subField.getNumElements()]
counter += subField.getNumElements()
getattr(self.style, subField.getName())(*args)
self.generateHuman(self.style.getGender(), self.masterHuman)
self.motionFSM.off()
self.motionFSM.on()
def setJewelry(self, *dna):
counter = 0
dclass = base.cr.dclassesByName['DistributedPlayerPirate']
field = dclass.getFieldByName('setJewelry').asMolecularField()
for i in xrange(field.getNumAtomics()):
subField = field.getAtomic(i)
args = dna[counter:counter + subField.getNumElements()]
counter += subField.getNumElements()
getattr(self.style, subField.getName())(*args)
messenger.send(self.uniqueName('jewelryUpdate'))
def setTattoos(self, *dna):
counter = 0
dclass = base.cr.dclassesByName['DistributedPlayerPirate']
field = dclass.getFieldByName('setTattoos').asMolecularField()
for i in xrange(field.getNumAtomics()):
subField = field.getAtomic(i)
args = dna[counter:counter + subField.getNumElements()]
counter += subField.getNumElements()
getattr(self.style, subField.getName())(*args)
messenger.send(self.uniqueName('tattooUpdate'))
def requestActivity(self, gameType, gameCategory, options, shipIds):
self.sendUpdate('requestActivity', [
gameType,
gameCategory,
options,
shipIds])
def requestInvitesResp(self, invitees, numFailed):
if len(invitees) > 0:
self.guiMgr.lookoutPage.requestInvitesResponse(invitees)
elif self.guiMgr.lookoutPage.currentInviteRequiresInvitees():
self.guiMgr.lookoutPage.restoreOrCancelSearch()
if numFailed == 0:
if DistributedBandMember.DistributedBandMember.getBandMember(localAvatar.doId):
self.guiMgr.messageStack.addTextMessage(PLocalizer.LookoutInviteIgnore, icon = ('lookout', None))
else:
self.guiMgr.messageStack.addTextMessage(PLocalizer.LookoutInviteNeedCrew, icon = ('lookout', None))
else:
self.guiMgr.lookoutPage.requestInvitesResponse([])
if numFailed > 0:
self.guiMgr.messageStack.addTextMessage(PLocalizer.LookoutInviteFail % numFailed, icon = ('lookout', None))
def getTutorialState(self):
return self.tutorialState
def updateClientTutorialStatus(self, val):
self.tutorialState = val
def getIsPaid(self):
self.updatePaidStatus()
return self.isPaid
def updatePaidStatus(self):
pStatus = self.getGameAccess()
if pStatus == 2 or pStatus == 0:
self.isPaid = True
else:
self.isPaid = False
def initVisibleToCamera(self):
if self is not localAvatar and localAvatar.getSoloInteraction():
self.hideFromCamera()
else:
self.showToCamera()
def hideFromCamera(self):
self.accept('showOtherAvatars', self.showToCamera)
self.node().adjustDrawMask(BitMask32.allOff(), base.cam.node().getCameraMask(), BitMask32.allOff())
def showToCamera(self):
self.accept('hideOtherAvatars', self.hideFromCamera)
self.node().adjustDrawMask(base.cam.node().getCameraMask(), BitMask32.allOff(), BitMask32.allOff())
def submitCodeToServer(self, code):
if code:
base.cr.codeRedemption.redeemCode(code)
def getNameText(self):
return DistributedPirateBase.getNameText(self)
def setOnWelcomeWorld(self, value):
self.onWelcomeWorld = value
def setTempDoubleXPReward(self, value):
if not self.tempDoubleXPStatusMessaged:
self.tempDoubleXPStatusMessaged = True
if self.getDoId() == localAvatar.getDoId() and value != 0:
(h, m) = self.getHoursAndMinutes(value)
base.localAvatar.guiMgr.messageStack.addModalTextMessage(PLocalizer.TEMP_DOUBLE_REP % (h, m), seconds = 45, priority = 0, color = PiratesGuiGlobals.TextFG14)
elif value > self.tempDoubleXPStatus:
(h, m) = self.getHoursAndMinutes(value)
base.localAvatar.guiMgr.messageStack.addModalTextMessage(PLocalizer.TEMP_DOUBLE_REP % (h, m), seconds = 45, priority = 0, color = PiratesGuiGlobals.TextFG14)
self.tempDoubleXPStatus = value
self.x2XPIcon.setPos(0.29999999999999999, 0, -0.14999999999999999)
self.refreshName()
def getTempDoubleXPReward(self):
return self.tempDoubleXPStatus
def setLastAttackTime(self, timestamp):
self.lastAttackTime = globalClockDelta.localElapsedTime(timestamp)
def getHoursAndMinutes(self, seconds):
t = int(seconds)
(minutes, seconds) = divmod(t, 60)
(hours, minutes) = divmod(minutes, 60)
return [
hours,
minutes]
def setGMNameTagState(self, state):
self.gmNameTagEnabled = state
def setGMNameTagString(self, nameTagString):
self.gmNameTagString = nameTagString
def getGMNameTagString(self):
return self.gmNameTagString
def setGMNameTagColor(self, color):
self.gmNameTagColor = color
def getGMNameTagColor(self):
return self.gmNameTagColor
def updateGMNameTag(self, state, color, tagString):
if color == 'gold':
color = 'goldGM'
elif color == 'red':
color = 'redGM'
elif color == 'green':
color = 'greenGM'
elif color == 'blue':
color = 'blueGM'
else:
color = 'whiteGM'
self.setGMNameTagState(state)
self.setGMNameTagColor(color)
self.setGMNameTagString(tagString)
self.refreshName()
def nameTag3dInitialized(self):
DistributedPirateBase.nameTag3dInitialized(self)
self.refreshName()
def b_updateGMNameTag(self, state, color, tagString):
self.d_updateGMNameTag(state, color, tagString)
self.updateGMNameTag(state, color, tagString)
def d_updateGMNameTag(self, state, color, tagString):
self.sendUpdate('updateGMNameTag', [
state,
color,
tagString])
def getShortName(self):
return self.getName()
def setTalk(self, fromAV, fromAC, avatarName, chat, mods, flags):
if not hasattr(self, 'isGM') or not self.isGM():
if not self.isConfused:
DistributedPlayer.setTalk(self, fromAV, fromAC, avatarName, chat, mods, flags)
else:
(newText, scrubbed) = self.scrubTalk(chat, mods)
if base.talkAssistant.isThought(newText):
base.talkAssistant.receiveThought(fromAV, avatarName, fromAC, None, newText, scrubbed)
else:
base.talkAssistant.receiveOpenTalk(fromAV, avatarName, fromAC, None, newText, scrubbed)
else:
base.talkAssistant.receiveGMTalk(fromAV, avatarName, fromAC, None, chat, 0)
def getBroadcastPeriod(self):
period = localAvatar.getPosHprBroadcastPeriod()
if period == None:
return PiratesGlobals.AI_MOVEMENT_PERIOD
else:
return period
def setPlundering(self, plunderingId):
self.isPlundering = plunderingId
def getPlundering(self):
return self.isPlundering
def setPopulated(self, state):
self.populated = state
def isPopulated(self):
return self.populated
def sendRequestContext(self, context, part = 0):
self.sendUpdate('requestContext', [
context,
part])
def sendRequestSeenContext(self, context):
self.sendUpdate('requestSeenContext', [
context])
def sendRequestChangeTutType(self, type, off):
self.sendUpdate('requestChangeTutType', [
type,
off])
def removeContext(self, context, number = 0):
if self.guiMgr:
contextTutPanel = self.guiMgr.contextTutPanel
if number:
if contextTutPanel.isFilled() and self.guiMgr.contextTutPanel.getContext() == context and self.guiMgr.contextTutPanel.getNumber() == number:
contextTutPanel.closePanel()
elif contextTutPanel.isFilled() and self.guiMgr.contextTutPanel.getContext() == context:
contextTutPanel.closePanel()
def setCommonChatFlags(self, commonChatFlags):
DistributedPlayer.setCommonChatFlags(self, commonChatFlags)
if hasattr(base, 'localAvatar') and base.localAvatar.playersNearby.has_key(self.getDoId()):
base.localAvatar.playersNearby[self.getDoId()] = (commonChatFlags, base.localAvatar.playersNearby[self.getDoId()][1])
def setWhitelistChatFlags(self, whitelistChatFlags):
DistributedPlayer.setWhitelistChatFlags(self, whitelistChatFlags)
if hasattr(base, 'localAvatar') and base.localAvatar.playersNearby.has_key(self.getDoId()):
base.localAvatar.playersNearby[self.getDoId()] = (base.localAvatar.playersNearby[self.getDoId()][0], whitelistChatFlags)
def requestConfusedText(self, wlEnabled):
self.isConfused = True
self.wlEnabled = wlEnabled
self.clearChat()
self.refreshName()
taskMgr.doMethodLater(5.0, self.removeConfusedText, self.uniqueName('removeConfusedText'))
def removeConfusedText(self, task):
self.isConfused = False
self.refreshName()
def handleArrivedOnShip(self, ship):
DistributedBattleAvatar.handleArrivedOnShip(self, ship)
ship.playerPirateArrived(self)
handleArrivedOnShip = report(types = [
'args'], dConfigParam = 'dteleport')(handleArrivedOnShip)
def handleLeftShip(self, ship):
DistributedBattleAvatar.handleLeftShip(self, ship)
ship.playerPirateLeft(self)
handleLeftShip = report(types = [
'args'], dConfigParam = 'dteleport')(handleLeftShip)
def d_boardShip(self, ship, boardingSpot):
self.sendUpdate('boardShip', [
ship,
boardingSpot])
d_boardShip = report(types = [
'args'], dConfigParam = 'dteleport')(d_boardShip)
def boardShip(self, ship, boardingSpot):
pass
boardShip = report(types = [
'args'], dConfigParam = 'dteleport')(boardShip)
def d_swingToShip(self, fromShip, toShip, boardingSpot, timestamp):
self.sendUpdate('swingToShip', [
fromShip,
toShip,
boardingSpot,
timestamp])
d_swingToShip = report(types = [
'args'], dConfigParam = 'dteleport')(d_swingToShip)
def swingToShip(self, fromShip, toShip, boardingSpot, timestamp, playRate = 0.59999999999999998):
fromShip = self.cr.getDo(fromShip)
ship = self.cr.getDo(toShip)
if fromShip == None or ship == None:
return None
if self.swingTrack:
self.swingTrack.pause()
self.swingTrack = None
self.swingTrack = self.createSwingTrack(fromShip, ship, boardingSpot)
elapsed = globalClockDelta.localElapsedTime(timestamp)
self.swingTrack.start(elapsed, playRate = playRate)
swingToShip = report(types = [
'args'], dConfigParam = 'dteleport')(swingToShip)
def createSwingTrack(self, fromShip, ship, boardingSpot):
boardingNode = ship.getBoardingLocator(boardingSpot)
topNode = ship.model.modelRoot.attachNewNode(self.uniqueName('rope-top'))
topNode.setZ(200)
avStartPos = self.getPos(ship.model.modelRoot)
avEndPos = boardingNode.getPos(ship.model.modelRoot)
midNode = ship.model.modelRoot.attachNewNode(self.uniqueName('rope-mid'))
midNodeStartPos = ((topNode.getPos() + avStartPos) * 0.5 + (topNode.getPos() + avEndPos) * 0.5) * 0.5
midNodeEndPos = (topNode.getPos() + avEndPos) * 0.5
midNode.setPos(midNodeStartPos)
(rope, ropeActor) = self.getRope()
rope.setup(3, ((None, Point3(0)), (midNode, Point3(0)), (topNode, Point3(0))))
rope.reparentTo(self.rightHandNode)
rope.hide()
ropeActor.reparentTo(self.rightHandNode)
ropeActor.hide()
swingDuration = self.getDuration('swing_aboard', fromFrame = 45, toFrame = 75)
cameraDuration = self.getDuration('swing_aboard', fromFrame = 27, toFrame = 45)
swingTrack = Sequence(Func(self.wrtReparentTo, fromShip.model.modelRoot), Func(self.lookAt, ship), Func(self.setP, 0), Func(self.setR, 0), Parallel(self.actorInterval('swing_aboard', startFrame = 27, endFrame = 45, blendOutT = 0), self.getSwingCameraOut(cameraDuration)), Func(self.wrtReparentTo, ship.model.modelRoot), Func(self.setP, 0), Func(self.setR, 0), Func(rope.show), Func(ropeActor.show), Parallel(self.actorInterval('swing_aboard', startFrame = 45, endFrame = 75, blendInT = 0, blendOutT = 0), ropeActor.actorInterval('swing_aboard', startFrame = 0, endFrame = 30), ProjectileInterval(self, endPos = avEndPos, duration = swingDuration, gravityMult = 6), LerpPosInterval(midNode, pos = midNodeEndPos, duration = swingDuration), self.getSwingCameraIn(swingDuration)), Func(ropeActor.detachNode), Func(topNode.detachNode), Func(midNode.detachNode), Func(rope.detachNode))
return swingTrack
createSwingTrack = report(types = [
'args'], dConfigParam = 'dteleport')(createSwingTrack)
def getSwingCameraOut(self, duration):
return Wait(duration)
def getSwingCameraIn(self, duration):
return Wait(duration)
def bloodFireChange(self, increase):
if increase:
if self.bloodFireTime <= 0.0:
startTimer = True
self.taskTime = 0
if self.isLocal():
self.guiMgr.combatTray.showBloodFire()
else:
startTimer = False
maxBloodFire = ItemGlobals.BLOOD_FIRE_MAX * ItemGlobals.BLOOD_FIRE_TIMER
if self.bloodFireTime + ItemGlobals.BLOOD_FIRE_TIMER < maxBloodFire:
self.bloodFireTime += ItemGlobals.BLOOD_FIRE_TIMER
if startTimer:
taskMgr.add(self.bloodFireCharging, self.uniqueName('bloodFireCharging'), priority = 40)
def bloodFireCharging(self, task):
if not (self.currentWeapon) or ItemGlobals.getType(self.currentWeaponId) != ItemGlobals.SWORD:
return Task.done
self.bloodFireTime -= task.time - self.taskTime
if self.isLocal():
self.guiMgr.combatTray.updateBloodFire(self.bloodFireTime)
self.currentWeapon.setFlameIntensity(self.bloodFireTime / ItemGlobals.BLOOD_FIRE_TIMER * ItemGlobals.BLOOD_FIRE_MAX)
if self.bloodFireTime <= 0.0:
self.bloodFireTime = 0.0
if self.isLocal():
self.guiMgr.combatTray.hideBloodFire()
return Task.done
self.taskTime = task.time
return Task.cont
def clearBloodFire(self):
taskMgr.remove(self.uniqueName('bloodFireCharging'))
self.bloodFireTime = 0.0
if self.isLocal():
self.guiMgr.combatTray.clearBloodFire()
def setAuraActivated(self, auraActivated):
if not (self.currentWeapon) or ItemGlobals.getType(self.currentWeaponId) != ItemGlobals.STAFF:
self.auraActivated = False
return None
if auraActivated == EnemySkills.STAFF_TOGGLE_AURA_WARDING:
self.auraIval = self.currentWeapon.getWardingAura(self)
elif auraActivated == EnemySkills.STAFF_TOGGLE_AURA_NATURE:
self.auraIval = self.currentWeapon.getNatureAura(self)
elif auraActivated == EnemySkills.STAFF_TOGGLE_AURA_DARK:
self.auraIval = self.currentWeapon.getDarkAura(self)
elif self.auraIval:
self.auraIval.pause()
self.auraIval = None
self.currentWeapon.stopAuraEffects()
if self.auraIval:
self.auraIval.start()
self.auraActivated = auraActivated
def getAuraActivated(self):
return self.auraActivated
def considerEnableMovement(self):
if self.getGameState() in ('PVPComplete', 'Off'):
return None
else:
return DistributedBattleAvatar.considerEnableMovement(self)
def getMinimapObject(self):
if not (self.minimapObj) and not self.isDisabled():
self.minimapObj = MinimapPlayerPirate(self)
if self.minimapObj:
if DistributedBandMember.DistributedBandMember.areSameCrew(self.doId, localAvatar.doId):
self.minimapObj.joinedCrew()
else:
self.minimapObj.leftCrew()
return self.minimapObj
def setIsTracked(self, questId):
self.isTracked = False
if self.minimapObj:
self.minimapObj.setIsTracked(self.isTracked)
def d_requestShowOffFish(self, collectionId):
if config.GetBool('want-show-off-fish', 0):
self.sendUpdate('requestShowOffFish', [
collectionId])
def showOffFish(self, collectionId, weight):
fishData = FishingGlobals.CollectionToData[collectionId]
if self.shownFish:
self.shownFish.destroy()
self.shownFish = Fish.Fish(None, fishData, 0, trophy = weight)
self.fishSwivel.reparentTo(self.leftHandNode)
self.shownFish.reparentTo(self.fishSwivel)
mouthTrans = self.shownFish.mouthJoint.getTransform(self.shownFish).getInverse()
self.shownFish.setTransform(mouthTrans)
self.fishSwivel.setHpr(180, 0, -90)
def setEmote(self, emoteId):
DistributedBattleAvatar.setEmote(self, emoteId)
def playEmote(self, emoteId):
if base.cr.avatarFriendsManager.checkIgnored(self.doId):
return None
else:
DistributedBattleAvatar.playEmote(self, emoteId)
def canIdleSplashEver(self):
return True
def canIdleSplash(self):
return self.getCurrentAnim() == 'idle'
def enterDialogMode(self):
self.hide(invisibleBits = PiratesGlobals.INVIS_DIALOG)
def exitDialogMode(self):
self.show(invisibleBits = PiratesGlobals.INVIS_DIALOG)
def rewardNotify(self, rewardCat, rewardId):
if base.config.GetBool('black-pearl-repeat-reward', 1) == 1:
def showRewardPanel(task = None):
rewardSkillId = ItemGlobals.getUseSkill(rewardId)
rewardName = PLocalizer.getInventoryTypeName(rewardSkillId)
if rewardCat and rewardId:
rewardText = PLocalizer.BlackPearlRewardSuccess % rewardName
else:
rewardText = PLocalizer.BlackPearlRewardFailure % rewardName
localAvatar.guiMgr.messageStack.addTextMessage(rewardText, seconds = 30, icon = ('friends', None))
self.acceptOnce('highSeasScoreBoardClose', showRewardPanel)
class MinimapPlayerPirate(MinimapBattleAvatar):
DEFAULT_COLOR = VBase4(0.10000000000000001, 0.5, 1.0, 0.69999999999999996)
def __init__(self, avatar):
MinimapBattleAvatar.__init__(self, avatar)
self.inCrew = False
def _addedToMap(self, map):
self.accept(BandConstance.BandMembershipChange, self.bandUpdated)
def _removedFromMap(self, map):
self.ignore(BandConstance.BandMembershipChange)
def bandUpdated(self, member, removed):
if member.avatarId == self.worldNode.getDoId():
if removed:
self.leftCrew()
else:
self.joinedCrew()
def joinedCrew(self):
self.inCrew = True
self.setIconColor()
def leftCrew(self):
self.inCrew = False
self.setIconColor()
def setIconColor(self, color = None):
if self.inCrew:
if not color:
pass
MinimapBattleAvatar.setIconColor(self, VBase4(0.90000000000000002, 0.5, 0.94999999999999996, 1))
elif not color:
pass
MinimapBattleAvatar.setIconColor(self, VBase4(0.10000000000000001, 0.5, 1.0, 0.69999999999999996))
|
<reponame>aerobit/SimpleMenu
package com.aerobit.simplemenu.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import java.awt.*;
public class GButton {
private GuiNewMainMenu gui;
private int x, y, width, height, hoverOffset;
public int id;
private String text;
private FontRenderer fr;
public GButton(GuiNewMainMenu gui, int x, int y, int width, int height, String text, int id) {
this.gui = gui;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.text = text;
this.id = id;
hoverOffset = 0;
fr = Minecraft.getMinecraft().fontRenderer;
}
public void drawButton(int mouseX, int mouseY) {
boolean hovering = isHovering(mouseX, mouseY);
if (hovering) {
if (hoverOffset < 10) {
hoverOffset += 1;
}
} else {
if (hoverOffset > 0) {
hoverOffset -= 1;
}
}
Color colorBack = (new Color(0, 0, 0, 150));
Color colorText = (new Color(255, 255, 255, 255));
Gui.drawRect(x + hoverOffset, y, x + width + hoverOffset, y + height, colorBack.getRGB());
fr.drawString(text, x + hoverOffset + 4, y + 4, colorText.getRGB(), false);
}
public void onMouseClick(int mouseX, int mouseY) {
if (isHovering(mouseX, mouseY)) gui.buttonAction(this.id);
}
public boolean isHovering(int mouseX, int mouseY) {
return mouseX >= x && mouseY >= y && mouseX <= x + width && mouseY <= y + height;
}
}
|
<reponame>UpcraftLP/Rift<gh_stars>100-1000
package org.dimdev.rift.mixin.hook;
import com.mojang.brigadier.AmbiguityConsumer;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import org.dimdev.rift.listener.CommandAdder;
import org.dimdev.riftloader.RiftLoader;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(Commands.class)
public class MixinCommands {
// Workaround for https://github.com/SpongePowered/Mixin/issues/267
@Redirect(method = "<init>", at = @At(value = "INVOKE", target = "Lcom/mojang/brigadier/CommandDispatcher;findAmbiguities(Lcom/mojang/brigadier/AmbiguityConsumer;)V"))
public void findAmbiguities(CommandDispatcher<CommandSource> dispatcher, AmbiguityConsumer<CommandSource> consumer) {
for (CommandAdder commandAdder : RiftLoader.instance.getListeners(CommandAdder.class)) {
commandAdder.registerCommands(dispatcher);
}
dispatcher.findAmbiguities(consumer);
}
}
|
#!/bin/bash
jekyll build
jekyll serve
|
#!/bin/sh
set -eu
/usr/bin/env python3 "$@" -Dq='2**521 - 1' -Dmodulus_bytes='52.1' -Da24='121665'
|
Page = Struct.new(:fpath, :above_text, :below_text, :weight)
DIR_PATH = ARGV[0] || "."
# TODO: Hard code
WEIGHT_START = 10
# TODO: Hard code
WEIGHT_STEP = 10
md_names = Dir.entries(DIR_PATH).reject{|f| [".", ".."].include?(f)}
md_paths = md_names.map{|f| File.join(DIR_PATH, f)}
pages = md_paths.map{|md_path|
lines = File.read(md_path).each_line.to_a
weight_reg = %r{weight\s*=\s*(\d+)}
idx = lines.index{|l| l.match(weight_reg)}
if idx.nil?
STDERR.puts("Error: weight = <number> is not found in #{md_path}")
exit(1)
end
weight = lines[idx].match(weight_reg)[1].to_i
above_text = lines[0..idx-1].join
below_text = lines[idx+1..-1].join
Page.new(
md_path,
above_text,
below_text,
weight
)
}
weight = WEIGHT_START
pages.sort{|p1, p2| [p1.weight, p1.fpath] <=> [p2.weight, p2.fpath]}.each{|page|
puts("====== #{page.fpath} ======")
puts("#{page.weight} => #{weight}")
# Create new-weighted text
md_text = page.above_text + "weight = #{weight}\n" + page.below_text
# Rewirte
File.write(page.fpath, md_text)
weight += WEIGHT_STEP
}
|
<filename>Code Challenges/python/sock_merch.py
# 2020.04.25 ?
import math
import os
import random
import re
import sys
# (user)problem: we know the color of each sock
# but we do not know (need to know)
# how many matching pairs there are
# solution(product):
# use [].count(i)
# to get the number of appearances
# if that number is mod%2=0
# add that number to the pair list
# if not, add that number -i
# ignore n
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
number_of_matching_pairs = 0
# make a list of colors
color_list = set(ar)
print(color_list)
# iterate though list of colors, and find out how many occurances
for color in color_list:
occurences = ar.count(color)
if occurences % 2 == 0:
print("if", occurences)
number_of_matching_pairs += occurences / 2
else:
number_of_matching_pairs += (occurences - 1) / 2
print("else", occurences)
return int(number_of_matching_pairs)
sockMerchant(0, [10, 20, 20, 10, 10, 30, 50, 10, 20])
|
namespace App\Repositories\Contracts;
interface CustomerRepositoryInterface
{
public function createCustomer(array $customerData): int;
public function getCustomer(int $customerId): array;
public function updateCustomer(int $customerId, array $updatedCustomerData): bool;
public function deleteCustomer(int $customerId): bool;
} |
<reponame>Travis-Richards/game
/** This is the top level class for the wall generator.
* All this does is create the window and the wall generator.
* @see WallGeneratorView WallGeneratorView
* @see WallGenerator
* */
public class WallGeneratorApp {
public static void main(String[] args) {
new WallGeneratorView(new WallGenerator());
}
}
|
<reponame>yujunje11526061/mmall<filename>LearnSpring/src/main/java/initAndDestroy/Bean2.java
package initAndDestroy;
public class Bean2 {
public void onInit(){
System.out.println("Initializing");
}
public void onInit2(){
System.out.println("Initializing by onInit2 method");
}
public void onDestroy(){
System.out.println("Destroying");
}
public void onDestroy2(){
System.out.println("Destroying by onDestroy2 method");
}
}
|
require('flow-remove-types/register');
const _ = require('lodash');
const config = require('config');
const fetchCmsMeta = require('../src/helpers/fetchCmsMeta');
// Initialize JSON RPC.
fetchCmsMeta().then(res => {
const mapped = {};
res.forEach(([map, jsonRpcResponse]) => {
Object.keys(map).forEach(variableName => {
const variableValue = _.get(jsonRpcResponse, [
'result',
...map[variableName].split('.'),
]);
mapped[variableName] = variableValue;
});
});
Object.assign(process.env, mapped);
const app = require('../src/helpers/app'); // eslint-disable-line global-require
app.listen(config.get('app.port'));
});
|
<filename>grpc/sink.pb.go
// Code generated by protoc-gen-go.
// source: sink.proto
// DO NOT EDIT!
/*
Package sink is a generated protocol buffer package.
It is generated from these files:
sink.proto
It has these top-level messages:
Payload
Void
*/
package sink
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type Payload struct {
Payload []byte `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"`
}
func (m *Payload) Reset() { *m = Payload{} }
func (m *Payload) String() string { return proto.CompactTextString(m) }
func (*Payload) ProtoMessage() {}
func (*Payload) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
type Void struct {
}
func (m *Void) Reset() { *m = Void{} }
func (m *Void) String() string { return proto.CompactTextString(m) }
func (*Void) ProtoMessage() {}
func (*Void) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func init() {
proto.RegisterType((*Payload)(nil), "sink.Payload")
proto.RegisterType((*Void)(nil), "sink.Void")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion3
// Client API for Sink service
type SinkClient interface {
Sink(ctx context.Context, in *Payload, opts ...grpc.CallOption) (*Void, error)
SinkStream(ctx context.Context, opts ...grpc.CallOption) (Sink_SinkStreamClient, error)
}
type sinkClient struct {
cc *grpc.ClientConn
}
func NewSinkClient(cc *grpc.ClientConn) SinkClient {
return &sinkClient{cc}
}
func (c *sinkClient) Sink(ctx context.Context, in *Payload, opts ...grpc.CallOption) (*Void, error) {
out := new(Void)
err := grpc.Invoke(ctx, "/sink.Sink/Sink", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sinkClient) SinkStream(ctx context.Context, opts ...grpc.CallOption) (Sink_SinkStreamClient, error) {
stream, err := grpc.NewClientStream(ctx, &_Sink_serviceDesc.Streams[0], c.cc, "/sink.Sink/SinkStream", opts...)
if err != nil {
return nil, err
}
x := &sinkSinkStreamClient{stream}
return x, nil
}
type Sink_SinkStreamClient interface {
Send(*Payload) error
CloseAndRecv() (*Void, error)
grpc.ClientStream
}
type sinkSinkStreamClient struct {
grpc.ClientStream
}
func (x *sinkSinkStreamClient) Send(m *Payload) error {
return x.ClientStream.SendMsg(m)
}
func (x *sinkSinkStreamClient) CloseAndRecv() (*Void, error) {
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
m := new(Void)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// Server API for Sink service
type SinkServer interface {
Sink(context.Context, *Payload) (*Void, error)
SinkStream(Sink_SinkStreamServer) error
}
func RegisterSinkServer(s *grpc.Server, srv SinkServer) {
s.RegisterService(&_Sink_serviceDesc, srv)
}
func _Sink_Sink_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Payload)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SinkServer).Sink(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/sink.Sink/Sink",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SinkServer).Sink(ctx, req.(*Payload))
}
return interceptor(ctx, in, info, handler)
}
func _Sink_SinkStream_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(SinkServer).SinkStream(&sinkSinkStreamServer{stream})
}
type Sink_SinkStreamServer interface {
SendAndClose(*Void) error
Recv() (*Payload, error)
grpc.ServerStream
}
type sinkSinkStreamServer struct {
grpc.ServerStream
}
func (x *sinkSinkStreamServer) SendAndClose(m *Void) error {
return x.ServerStream.SendMsg(m)
}
func (x *sinkSinkStreamServer) Recv() (*Payload, error) {
m := new(Payload)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var _Sink_serviceDesc = grpc.ServiceDesc{
ServiceName: "sink.Sink",
HandlerType: (*SinkServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Sink",
Handler: _Sink_Sink_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "SinkStream",
Handler: _Sink_SinkStream_Handler,
ClientStreams: true,
},
},
Metadata: fileDescriptor0,
}
func init() { proto.RegisterFile("sink.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 120 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x2a, 0xce, 0xcc, 0xcb,
0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0xb1, 0x95, 0x94, 0xb9, 0xd8, 0x03, 0x12,
0x2b, 0x73, 0xf2, 0x13, 0x53, 0x84, 0x24, 0xb8, 0xd8, 0x0b, 0x20, 0x4c, 0x09, 0x46, 0x05, 0x46,
0x0d, 0x9e, 0x20, 0x18, 0x57, 0x89, 0x8d, 0x8b, 0x25, 0x2c, 0x3f, 0x33, 0xc5, 0x28, 0x82, 0x8b,
0x25, 0x18, 0xa8, 0x49, 0x48, 0x19, 0x4a, 0xf3, 0xea, 0x81, 0xcd, 0x83, 0x1a, 0x20, 0xc5, 0x05,
0xe1, 0x82, 0x94, 0x2a, 0x31, 0x08, 0x69, 0x73, 0x71, 0x81, 0x14, 0x05, 0x97, 0x14, 0xa5, 0x26,
0xe6, 0xe2, 0x55, 0xaa, 0xc1, 0x98, 0xc4, 0x06, 0x76, 0x93, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff,
0xdc, 0xcd, 0x28, 0xab, 0xa1, 0x00, 0x00, 0x00,
}
|
#include "ThreadPool.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Thunk : In computer programming, a thunk is a subroutine that is created, often automatically,
to assist a call to another subroutine. Thunks are primarily used to represent an additional
calculation that a subroutine needs to execute, or to call a routine that does not support the
usual calling mechanism. http://en.wikipedia.org/wiki/Thunk */
typedef struct {
ThreadPool *pThreadPool; // pointeur sur l'objet ThreadPool
int ThreadNum; // Numéro du thread, de 0 à n
} threadArg;
void *Thunk(void *arg) {
threadArg *pThreadArg = (threadArg *)arg;
ThreadPool *pThreadPool;
pThreadPool = static_cast<ThreadPool*>(pThreadArg->pThreadPool);
pThreadPool->MyThreadRoutine(pThreadArg->ThreadNum);
}
/* void ThreadPool(unsigned int nThread)
Ce constructeur doit initialiser le thread pool. En particulier, il doit initialiser les variables
de conditions et mutex, et démarrer tous les threads dans ce pool, au nombre spécifié par nThread.
IMPORTANT! Vous devez initialiser les variables de conditions et le mutex AVANT de créer les threads
qui les utilisent. Sinon vous aurez des bugs difficiles à comprendre comme des threads qui ne débloque
jamais de phtread_cond_wait(). */
ThreadPool::ThreadPool(unsigned int nThread) {
// Cette fonction n'est pas complète! Il vous faut la terminer!
// Initialisation des membres
PoolDoitTerminer = false;
nThreadActive = nThread;
bufferValide = true;
buffer = 0;
// Initialisation du mutex et des variables de conditions.
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&CondThreadRienAFaire,0);
pthread_cond_init(&CondProducteur,0);
// Création des threads. Je vous le donne gratuit, car c'est un peu plus compliqué que vu en classe.
pTableauThread = new pthread_t[nThread];
threadArg *pThreadArg = new threadArg[nThread];
int i;
for (i=0; i < nThread; i++) {
pThreadArg[i].ThreadNum = i;
pThreadArg[i].pThreadPool = this;
printf("ThreadPool(): en train de creer thread %d\n",i);
int status = pthread_create(&pTableauThread[i], NULL, Thunk, (void *)&pThreadArg[i]);
if (status != 0) {
printf("oops, pthread a retourne le code d'erreur %d\n",status);
exit(-1);
}
}
}
/* Destructeur ThreadPool::~ThreadPool()
Ce destructeur doit détruire les mutex et variables de conditions. */
ThreadPool::~ThreadPool() {
// À compléter
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&CondProducteur);
pthread_cond_destroy(&CondThreadRienAFaire);
delete [] pTableauThread;
}
/* void ThreadPool::MyThreadRoutine(int myID)
Cette méthode est celle qui tourne pour chacun des threads crées dans le constructeur, et qui est
appelée par la fontion thunk. Cette méthode est donc effectivement le code du thread consommateur,
qui ne doit quitter qu’après un appel à la méthode Quitter(). Si le buffer est vide, MyThreadRoutine
doit s'arrêter (en utilisant une variable de condition). Le travail à accomplir est un sleep() d'une
durée spécifiée dans le buffer.
*/
void ThreadPool::MyThreadRoutine(int myID) {
// À compléter
printf("Thread %d commence!\n", myID);
while (!PoolDoitTerminer) {
pthread_mutex_lock(&mutex);
if (!bufferValide) {
pthread_cond_wait(&CondThreadRienAFaire,&mutex);
}
if(!PoolDoitTerminer) {
printf("Thread %d récupère l'item %d!\n",myID,buffer);
int currentBuffer = buffer;
bufferValide = false;
pthread_cond_signal(&CondProducteur);
pthread_cond_signal(&CondThreadRienAFaire);
pthread_mutex_unlock(&mutex);
printf("Thread %d va dormir %d sec.\n",myID,currentBuffer);
sleep(currentBuffer);
}
}
printf("############ Thread %d termine!################\n",myID);
}
/* void ThreadPool::Inserer(unsigned int newItem)
Cette méthode est appelée par le thread producteur pour mettre une tâche à exécuter dans le buffer
(soit le temps à dormir pour un thread). Si le buffer est marqué comme plein, il faudra dormir
sur une variable de condition. */
void ThreadPool::Inserer(unsigned int newItem) {
// À compléter
pthread_mutex_lock(&mutex);
if (bufferValide) {
pthread_cond_wait(&CondProducteur,&mutex);
}
bufferValide = true;
buffer = newItem;
pthread_cond_signal(&CondThreadRienAFaire);
pthread_mutex_unlock(&mutex);
}
/* void ThreadPool::Quitter()
Cette fonction est appelée uniquement par le producteur, pour indiquer au thread pool qu’il n’y
aura plus de nouveaux items qui seront produits. Il faudra alors que tous les threads terminent
de manière gracieuse. Cette fonction doit bloquer jusqu’à ce que tous ces threads MyThreadRoutine
terminent, incluant ceux qui étaient bloqués sur une variable de condition. */
void ThreadPool::Quitter() {
// À compléter
pthread_mutex_lock(&mutex);
while (bufferValide) {
pthread_cond_wait(&CondThreadRienAFaire,&mutex);
}
PoolDoitTerminer = true;
pthread_cond_broadcast(&CondThreadRienAFaire);
pthread_mutex_unlock(&mutex);
for (int i = 0; i < nThreadActive; i++) {
pthread_join(pTableauThread[i],NULL);
}
}
|
#!/bin/bash
#SBATCH -J Act_tanh_1
#SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de
#SBATCH --mail-type=FAIL
#SBATCH -e /work/scratch/se55gyhe/log/output.err.%j
#SBATCH -o /work/scratch/se55gyhe/log/output.out.%j
#SBATCH -n 1 # Number of cores
#SBATCH --mem-per-cpu=6000
#SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins
#module load intel python/3.5
python3 /home/se55gyhe/Act_func/sequence_tagging/arg_min/PE-my.py tanh 318 Adadelta 2 0.2939969418351199 0.9870825748903842 rnormal 0.3
|
class ReproStack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
import unittest
class TestReproStack(unittest.TestCase):
def test_stack_operations(self):
stack = ReproStack()
self.assertTrue(stack.is_empty())
self.assertEqual(stack.size(), 0)
stack.push(5)
stack.push('hello')
stack.push(True)
self.assertFalse(stack.is_empty())
self.assertEqual(stack.size(), 3)
self.assertEqual(stack.pop(), True)
self.assertEqual(stack.pop(), 'hello')
self.assertEqual(stack.pop(), 5)
self.assertTrue(stack.is_empty())
self.assertEqual(stack.size(), 0)
self.assertIsNone(stack.pop())
if __name__ == '__main__':
unittest.main() |
# import necessary libraries
import rsa
# generate a pair of public/private keys
public_key, private_key = rsa.newkeys(1024)
# encode the message with the public key
message = 'Hello, World!'
encrypted_message = rsa.encrypt(message.encode(), public_key)
# decrypt the message with the private key
decrypted_message = rsa.decrypt(encrypted_message, private_key).decode()
print(decrypted_message) # prints 'Hello, World!' |
<reponame>jocstech/ultimate-backend
import {Entity} from '@juicycleff/repo-orm';
import {AuthResponseDto} from '../dtos/response';
import {BaseEntity} from './base-entity';
import {
BillingSettingEmbed,
TenantMemberEmbed,
TenantSettingsEmbed,
} from './embeded';
@Entity({name: 'tenant'})
export class TenantEntity extends BaseEntity<AuthResponseDto> {
name: string;
normalizedName!: string;
settings?: TenantSettingsEmbed;
billing?: BillingSettingEmbed;
members: TenantMemberEmbed[];
currentPlan!: string;
}
|
<filename>db/migrate/20121018210156_add_index_on_repository_id_and_event_type_to_builds.rb
class AddIndexOnRepositoryIdAndEventTypeToBuilds < ActiveRecord::Migration
def change
add_index :builds, [:repository_id, :event_type]
end
end
|
<filename>Tic-Tac-Toe/src/checkBoard.cpp
#include "checkBoard.hpp"
checkBoard::checkBoard()
{
//does nothing
}
int checkBoard::checkPos(std::string* spots)
{
if(spots[0] == spots[1] && spots[1] == spots[2])
{
return 1;
}
else if(spots[3] == spots[4] && spots[4] == spots[5])
{
return 1;
}
else if(spots[6] == spots[7] && spots[7] == spots[8])
{
return 1;
}
else if(spots[0] == spots[3] && spots[3] == spots[6])
{
return 1;
}
else if(spots[1] == spots[4] && spots[4] == spots[7])
{
return 1;
}
else if(spots[2] == spots[5] && spots[5] == spots[8])
{
return 1;
}
else if(spots[0] == spots[4] && spots[4] == spots[8])
{
return 1;
}
else if(spots[2] == spots[4] && spots[4] == spots[6])
{
return 1;
}
else if(spots[0] != "1" && spots[1] != "2" && spots[2] != "3" && spots[3] != "4" && spots[4] != "5" && spots[5] != "6" && spots[6] != "7" && spots[7] != "8" && spots[8] != "9")
{
return 2;
}
else
{
return 0;
}
}
|
<filename>Extras/at 1.py
#Faça um algoritmo que receba dois números e exiba o resultado da sua soma.
n = [float,float,0]
for i in range(2):
n[i] = float(input("Insira o N%s: " % str(i+1)))
n[2] += n[i]
print("A soma é: " + str(n[2])) |
module Isomorfeus
module Installer
class << self
# application options
attr_reader :app_class
attr_accessor :database
attr_accessor :framework
attr_accessor :isomorfeus_module
attr_reader :project_dir
attr_reader :project_name
attr_accessor :rack_server
attr_accessor :rack_server_name
attr_reader :roda_app_class
attr_reader :roda_app_path
attr_accessor :source_dir
# installer options
attr_reader :options
def set_project_names(pro_dir)
@project_dir = pro_dir
@project_name = pro_dir.underscore
@app_class = @project_name.camelize + 'App'
@roda_app_class = @project_name.camelize + 'RodaApp'
@roda_app_path = @project_name + '_roda_app'
end
def options=(options)
Isomorfeus::Installer::OptionsMangler.mangle_options(options)
@options = options
end
def add_rack_server(name, props)
rack_servers[name] = props
end
def rack_servers
@rack_servers ||= {}
end
def sorted_rack_servers
rack_servers.keys.sort
end
# installer paths
def base_path
@base_path ||= File.realpath(File.join(File.dirname(File.realpath(__FILE__)), 'installer'))
end
def templates_path
@templates_path ||= File.realpath(File.join(File.dirname(File.realpath(__FILE__)), 'installer', 'templates'))
end
end
end
end
|
const Client = require('../../libs/http-wrapper/src').Client;
const httpUtils = require('../../libs/http-wrapper/src').httpUtils;
const CrlServer = require('../CrlServer');
const cleanUp = require('./testCleanUp');
new CrlServer();
let client1 = new Client();
let client2 = new Client();
let config = {
'endpoint': 'http://localhost:8080/channels'
};
function deleteMessage(client, channelUid, responseBody) {
client.delete(`${config.endpoint}/${channelUid}/msg/${responseBody.id}`, function (response) {
if (response.statusCode === 200) {
console.log('client1: ', `Deleted message with id ${responseBody.id} from Message Queue`);
}
cleanUp('channels');
});
}
function getMessage(client, channelUid) {
client.get(`${config.endpoint}/${channelUid}/msg`, function (response) {
if (response.statusCode !== 200) {
console.error(response.statusMessage);
} else {
console.log('client1: ', `GET on ${config.endpoint}/${channelUid}/msg`);
console.log('client1: ', 'Waiting...');
httpUtils.setDataHandler(response, function (error, body) {
if (error) {
console.error(error);
} else {
const responseBody = JSON.parse(body);
console.log('client1: ', `READ message: ${responseBody.content}`);
console.log('client1: ', `Deleting consumed message ${responseBody.id}`);
deleteMessage(client, channelUid, responseBody);
}
});
}
});
}
function sendMessage(client, channelUid) {
const messageContent = {
'message': 'hello world',
'type': 'string'
};
const requestConfig = {
body: messageContent,
headers: {
'Content-Type': 'application/json'
}
};
client.post(`${config.endpoint}/${channelUid}`, requestConfig, function (response) {
if (response.statusCode !== 201) {
console.error(console.error(response.statusMessage));
} else {
console.log('client2: ', `Wrote message in ${channelUid}`);
}
});
}
client1.post(config.endpoint, {}, function (response) {
if (response.statusCode === 200) {
console.log('client1: ', `Created channel`);
}
httpUtils.setDataHandler(response, function (error, channelUid) {
if (error) {
console.error(error);
} else {
console.log('client1: ', `Got channel with UID ${channelUid}`);
getMessage(client1, channelUid);
console.log('client2: ', `Writing message in ${channelUid}`);
sendMessage(client2, channelUid);
}
});
});
|
#!/bin/bash
#SBATCH -J Act_tanh_1
#SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de
#SBATCH --mail-type=FAIL
#SBATCH -e /work/scratch/se55gyhe/log/output.err.%j
#SBATCH -o /work/scratch/se55gyhe/log/output.out.%j
#SBATCH -n 1 # Number of cores
#SBATCH --mem-per-cpu=2000
#SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins
#module load intel python/3.5
python3 /home/se55gyhe/Act_func/progs/meta.py tanh 1 sgd 4 0.41186226239657975 478 0.013919639129579407 glorot_uniform PE-infersent
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.