repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
lioder/LampManager | ERPClient/src/main/java/blservice/goodsblservice/GoodsInfo.java | <filename>ERPClient/src/main/java/blservice/goodsblservice/GoodsInfo.java
package blservice.goodsblservice;
import java.util.ArrayList;
import po.GoodsPO;
import util.ResultMessage;
import vo.GoodsIdentityVO;
import vo.GoodsVO;
/**
* Created on 2017/11/5
* @author 巽
*
*/
public interface GoodsInfo {
/**
* 得到所有商品的信息
* @return 包含所有商品的VO的链表
*/
public ArrayList<GoodsVO> getAllGoods();
/**
* 得到所有商品的ID、名称和型号
* @return 包含所有商品的ID、名称和型号的VO的链表
*/
public ArrayList<GoodsIdentityVO> getAllGoodsIdentity();
/**
* 根据商品ID得到商品的进价
* @param ID 商品ID
* @return 商品进价
*/
public Double getBuyingPriceByID(String ID);
/**
* 根据商品ID得到商品的销售价
* @param ID 商品ID
* @return 商品销售价
*/
public Double getRetailPriceByID(String ID);
/**
* 根据商品ID得到商品
* @param ID 商品的ID
* @return 商品
*/
public GoodsPO getGoodsByID(String ID);
/**
* 根据商品ID更新商品最近进价
* @param goodsID 商品ID
* @param recentBuyingPrice 新的最近进价
* @return SUCCESS:更新成功<br>
* FAILED:更新失败(网络错误)<br>
* NOT_EXIST:商品不存在
*/
public ResultMessage updateRecentBuyingPrice(String goodsID, double recentBuyingPrice);
/**
* 根据商品ID更新商品最近零售价
* @param goodsID 商品ID
* @param recentRetailPrice 新的最近零售价
* @return SUCCESS:更新成功<br>
* FAILED:更新失败(网络错误)<br>
* NOT_EXIST:商品不存在
*/
public ResultMessage updateRecentRetailPrice(String goodsID, double recentRetailPrice);
}
|
sermonis/autodesk-forge-api-node-js-client | src/model/JobSvfOutputPayloadAdvanced.js | <filename>src/model/JobSvfOutputPayloadAdvanced.js
/**
* Forge SDK
* The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering.
*
* OpenAPI spec version: 0.1.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* 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.
*/
module.exports = (function () {
'use strict';
var ApiClient = require('../ApiClient');
/**
* The JobSvfOutputPayloadAdvanced model module.
* @module model/JobSvfOutputPayloadAdvanced
*/
/**
* Constructs a <code>JobSvfOutputPayloadAdvanced</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/JobSvfOutputPayloadAdvanced} obj Optional instance to populate.
* @return {module:model/JobSvfOutputPayloadAdvanced} The populated <code>JobSvfOutputPayloadAdvanced</code> instance.
*/
var constructFromObject = function (data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('conversionMethod'))
obj.conversionMethod = ApiClient.convertToType(data.conversionMethod, 'String');
if (data.hasOwnProperty('buildingStoreys'))
obj.buildingStoreys = ApiClient.convertToType(data.buildingStoreys, 'String');
if (data.hasOwnProperty('spaces'))
obj.spaces = ApiClient.convertToType(data.spaces, 'String');
if (data.hasOwnProperty('openingElements'))
obj.openingElements = ApiClient.convertToType(data.openingElements, 'String');
if (data.hasOwnProperty('generateMasterViews'))
obj.generateMasterViews = ApiClient.convertToType(data.generateMasterViews, 'Boolean');
if (data.hasOwnProperty('materialMode'))
obj.materialMode = ApiClient.convertToType(data.materialMode, 'String');
if (data.hasOwnProperty('hiddenObjects'))
obj.hiddenObjects = ApiClient.convertToType(data.hiddenObjects, 'Boolean');
if (data.hasOwnProperty('basicMaterialProperties'))
obj.basicMaterialProperties = ApiClient.convertToType(data.basicMaterialProperties, 'Boolean');
if (data.hasOwnProperty('autodeskMaterialProperties'))
obj.autodeskMaterialProperties = ApiClient.convertToType(data.autodeskMaterialProperties, 'Boolean');
if (data.hasOwnProperty('timelinerProperties'))
obj.timelinerProperties = ApiClient.convertToType(data.timelinerProperties, 'Boolean');
}
return obj;
};
/**
* Constructs a new <code>JobSvfOutputPayloadAdvanced</code>.
* @alias module:model/JobSvfOutputPayloadAdvanced
* @class
* @param {Object} theData The plain JavaScript object bearing properties of interest.
* @param {module:model/JobSvfOutputPayloadAdvanced} obj Optional instance to populate.
*/
// param conversionMethod { module: model / JobSvfOutputPayloadAdvanced.ConversionMethodEnum } An option to be specified when the input file type is IFC.
// param buildingStoreys { module: model / JobSvfOutputPayloadAdvanced.IfcOptionsEnum } An option to be specified when the input file type is IFC.
// param spaces { module: model / JobSvfOutputPayloadAdvanced.IfcOptionsEnum } An option to be specified when the input file type is IFC.
// param openingElements { module: model / JobSvfOutputPayloadAdvanced.IfcOptionsEnum } An option to be specified when the input file type is IFC.
// param generateMasterViews { Boolean } An option to be specified when the input file type is Revit.
// param materialMode { module: model / JobSvfOutputPayloadAdvanced.MaterialModeEnum } An option to be specified when the input file type is Revit.
// param hiddenObjects { Boolean } An option to be specified when the input file type is Navisworks.
// param basicMaterialProperties { Boolean } An option to be specified when the input file type is Navisworks.
// param autodeskMaterialProperties { Boolean } An option to be specified when the input file type is Navisworks.
// param timelinerProperties { Boolean } An option to be specified when the input file type is Navisworks.
var exports = function (theData, obj) {
var _this = this;
// _this.conversionMethod = conversionMethod;
// _this.buildingStoreys = buildingStoreys;
// _this.spaces = spaces;
// _this.openingElements = openingElements;
// _this.generateMasterViews = generateMasterViews;
// _this.materialMode = materialMode;
// _this.hiddenObjects = hiddenObjects;
// _this.basicMaterialProperties = basicMaterialProperties;
// _this.autodeskMaterialProperties = autodeskMaterialProperties;
// _this.timelinerProperties = timelinerProperties;
return constructFromObject(theData, obj || _this);
};
/**
* Constructs a <code>JobSvfOutputPayloadAdvanced</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/JobSvfOutputPayloadAdvanced} obj Optional instance to populate.
* @return {module:model/JobSvfOutputPayloadAdvanced} The populated <code>JobSvfOutputPayloadAdvanced</code> instance.
*/
exports.constructFromObject = constructFromObject;
/**
* An option to be specified when the input file type is IFC. Specifies what IFC loader to use during translation. Available options are:
* - legacy - Use the Navisworks IFC loader.
* - modern - Use the newer Revit IFC loader.
* If both switchLoader and conversionMethod are specified, Model Derivative uses the conversionMethod parameter. If conversionMethod is not specified, Model Derivative uses the switchLoader parameter.
* @member {module:model/JobSvfOutputPayloadAdvanced.ConversionMethodEnum} conversionMethod
*/
exports.prototype.conversionMethod = undefined;
/**
* An option to be specified when the input file type is IFC. Specifies how stories are translated. Available options are:
* - hide - (default) storeys are extracted but not visible by default.
* - show - storeys are extracted and are visible by default.
* - skip - storeys are not translated.
* Note These options are applicable only when conversionMethod is set to modern.
* @member {module:model/JobSvfOutputPayloadAdvanced.IfcOptionsEnum} buildingStoreys
*/
exports.prototype.buildingStoreys = 'hide';
/**
* An option to be specified when the input file type is IFC. Specifies how spaces are translated. Available options are:
* - hide - (default) spaces are translated but are not visible by default.
* - show - spaces are translated and are visible by default.
* - skip - spaces are not translated.
* Note These options are applicable only when conversionMethod is set to modern.
* @member {module:model/JobSvfOutputPayloadAdvanced.IfcOptionsEnum} spaces
*/
exports.prototype.spaces = 'hide';
/**
* An option to be specified when the input file type is IFC. Specifies how openings are translated. Available options are:
* - hide - (default) openings are translated but are not visible by default.
* - show - openings are translated and are visible by default.
* - skip - openings are not translated.
* Note These options are applicable only when conversionMethod is set to modern.
* @member {module:model/JobSvfOutputPayloadAdvanced.IfcOptionsEnum} openingElements
*/
exports.prototype.openingElements = 'hide';
/**
* An option to be specified when the input file type is Revit. Generates master views when translating from the Revit input format to SVF. This option is ignored for all other input formats. This attribute defaults to false.
* @member {Boolean} generateMasterViews
* @default false
*/
exports.prototype.generateMasterViews = false;
/**
* An option to be specified when the input file type is Revit. Specifies the materials to apply to the generated SVF derivatives. Available options are:
* - auto - (Default) Use the current setting of the default view of the input file.
* - basic - Use basic materials.
* - autodesk - Use Autodesk materials.
* @member {module:model/JobSvfOutputPayloadAdvanced.MaterialModeEnum} materialMode
*/
exports.prototype.materialMode = 'auto';
/**
* An option to be specified when the input file type is Navisworks. true: Extract hidden objects from the input file. false: (Default) Do not extract hidden objects from the input file.
* @member {Boolean} hiddenObjects
* @default false
*/
exports.prototype.hiddenObjects = false;
/**
* An option to be specified when the input file type is Navisworks. true: Extract properties for basic materials. false: (Default) Do not extract properties for basic materials.
* @member {Boolean} basicMaterialProperties
* @default false
*/
exports.prototype.basicMaterialProperties = false;
/**
* An option to be specified when the input file type is Navisworks. true: Extract properties for Autodesk materials. false: (Default) Do not extract properties for Autodesk materials.
* @member {Boolean} autodeskMaterialProperties
* @default false
*/
exports.prototype.autodeskMaterialProperties = false;
/**
* An option to be specified when the input file type is Navisworks. true: Extract timeliner properties. false: (Default) Do not extract timeliner properties.
* @member {Boolean} timelinerProperties
* @default false
*/
exports.prototype.timelinerProperties = false;
/**
* Allowed values for the <code>materialMode</code> property.
* @enum {String}
* @readonly
*/
exports.ConversionMethodEnum = {
/**
* value: "legacy"
* @const
*/
"legacy": "legacy",
/**
* value: "modern"
* @const
*/
"modern": "modern",
};
/**
* Allowed values for the <code>materialMode</code> property.
* @enum {String}
* @readonly
*/
exports.MaterialModeEnum = {
/**
* value: "auto"
* @const
*/
"auto": "auto",
/**
* value: "basic"
* @const
*/
"basic": "basic",
/**
* value: "auto"
* @const
*/
"autodesk": "autodesk",
};
/**
* Allowed values for the <code>buildingStoreys</code> <code>spaces</code> <code>openingElements</code> property.
* @enum {String}
* @readonly
*/
exports.IfcOptionsEnum = {
/**
* value: "hide"
* @const
*/
"hide": "hide",
/**
* value: "show"
* @const
*/
"show": "show",
/**
* value: "skip"
* @const
*/
"skip": "skip",
};
return exports;
}());
|
AtjonTV/Python-1.4 | Lib/grep.py | # 'grep'
import regex
from regex_syntax import *
import string
opt_show_where = 0
opt_show_filename = 0
opt_show_lineno = 1
def grep(pat, *files):
return ggrep(RE_SYNTAX_GREP, pat, files)
def egrep(pat, *files):
return ggrep(RE_SYNTAX_EGREP, pat, files)
def emgrep(pat, *files):
return ggrep(RE_SYNTAX_EMACS, pat, files)
def ggrep(syntax, pat, files):
if len(files) == 1 and type(files[0]) == type([]):
files = files[0]
global opt_show_filename
opt_show_filename = (len(files) != 1)
syntax = regex.set_syntax(syntax)
try:
prog = regex.compile(pat)
finally:
syntax = regex.set_syntax(syntax)
for filename in files:
fp = open(filename, 'r')
lineno = 0
while 1:
line = fp.readline()
if not line: break
lineno = lineno + 1
if prog.search(line) >= 0:
showline(filename, lineno, line, prog)
fp.close()
def showline(filename, lineno, line, prog):
if line[-1:] == '\n': line = line[:-1]
if opt_show_lineno:
prefix = string.rjust(`lineno`, 3) + ': '
else:
prefix = ''
if opt_show_filename:
prefix = filename + ': ' + prefix
print prefix + line
if opt_show_where:
start, end = prog.regs()[0]
line = line[:start]
if '\t' not in line:
prefix = ' ' * (len(prefix) + start)
else:
prefix = ' ' * len(prefix)
for c in line:
if c <> '\t': c = ' '
prefix = prefix + c
if start == end: prefix = prefix + '\\'
else: prefix = prefix + '^'*(end-start)
print prefix
|
athenagroup/brxm | services-webfiles/src/test/java/org/onehippo/cms7/services/webfiles/jcr/WebFileBundleImplTest.java | <reponame>athenagroup/brxm<filename>services-webfiles/src/test/java/org/onehippo/cms7/services/webfiles/jcr/WebFileBundleImplTest.java<gh_stars>0
/*
* Copyright 2014-2015 <NAME>. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.cms7.services.webfiles.jcr;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import org.junit.Before;
import org.junit.Test;
import org.onehippo.cms7.services.webfiles.WebFile;
import org.onehippo.cms7.services.webfiles.WebFileNotFoundException;
import org.onehippo.repository.mock.MockNode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class WebFileBundleImplTest {
private WebFileBundleImpl bundle;
@Before
public void setUp() throws RepositoryException {
Node root = MockNode.root();
Node webFilesRoot = root.addNode("webfiles", "nt:folder");
Node css = webFilesRoot.addNode("css", "nt:folder");
final Node file = css.addNode("style.css", "nt:file");
file.addNode("jcr:content", "nt:resource");
bundle = new WebFileBundleImpl(root.getSession(), webFilesRoot);
}
@Test
public void nonExistingWebFilesDoNotExist() {
assertFalse(bundle.exists(null));
assertFalse(bundle.exists(""));
assertFalse(bundle.exists("/"));
assertFalse(bundle.exists("/noSuchWebFile"));
assertFalse(bundle.exists("/css/noSuchWebFile"));
}
@Test
public void existingFoldersAreNotAnExistingWebFile() {
assertFalse(bundle.exists("/css"));
assertFalse(bundle.exists("/css/"));
}
@Test
public void existingWebFileExists() {
assertTrue(bundle.exists("/css/style.css"));
}
@Test
public void relativePathDoesNotExist() {
assertFalse(bundle.exists("css/style.css"));
}
@Test(expected = WebFileNotFoundException.class)
public void getNullPath() {
bundle.get(null);
}
@Test(expected = WebFileNotFoundException.class)
public void getEmptyPath() {
bundle.get("");
}
@Test(expected = WebFileNotFoundException.class)
public void getRootPath() {
bundle.get("/");
}
@Test(expected = WebFileNotFoundException.class)
public void getNonExistingWebFile() {
bundle.get("/noSuchWebFile");
}
@Test(expected = WebFileNotFoundException.class)
public void getNonExistingWebFileInExistingFolder() {
bundle.get("/css/noSuchWebFile");
}
@Test(expected = WebFileNotFoundException.class)
public void getExistingFolder() {
bundle.get("/css");
}
@Test
public void getExistingWebFile() {
final WebFile webFile = bundle.get("/css/style.css");
assertNotNull(webFile);
assertEquals("/webfiles/css/style.css", webFile.getPath());
assertEquals("style.css", webFile.getName());
}
} |
nogproject/nog | backend/cmd/nogfsostad/nogfsostad.go | <filename>backend/cmd/nogfsostad/nogfsostad.go
// vim: sw=8
// Server `nogfsostad`; see NOE-13.
package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log"
"net"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/docopt/docopt-go"
"github.com/nogproject/nog/backend/internal/fsoauthz"
"github.com/nogproject/nog/backend/internal/grpcjwt"
"github.com/nogproject/nog/backend/internal/nogfsopb"
"github.com/nogproject/nog/backend/internal/nogfsostad"
"github.com/nogproject/nog/backend/internal/nogfsostad/acls"
"github.com/nogproject/nog/backend/internal/nogfsostad/discoveryd"
"github.com/nogproject/nog/backend/internal/nogfsostad/gits"
"github.com/nogproject/nog/backend/internal/nogfsostad/observer6"
"github.com/nogproject/nog/backend/internal/nogfsostad/privileges/daemons"
"github.com/nogproject/nog/backend/internal/nogfsostad/privileges/dialsududod"
"github.com/nogproject/nog/backend/internal/nogfsostad/privileges/dialudod"
"github.com/nogproject/nog/backend/internal/nogfsostad/privileges/sudoudod"
"github.com/nogproject/nog/backend/internal/nogfsostad/shadows"
"github.com/nogproject/nog/backend/internal/nogfsostad/statd"
"github.com/nogproject/nog/backend/internal/nogfsostad/tarttd"
"github.com/nogproject/nog/backend/internal/nogfsostad/testudod"
"github.com/nogproject/nog/backend/internal/nogfsostad/workflowproc"
"github.com/nogproject/nog/backend/pkg/mulog"
"github.com/nogproject/nog/backend/pkg/regexpx"
"github.com/nogproject/nog/backend/pkg/unixauth"
"github.com/nogproject/nog/backend/pkg/x509io"
"github.com/nogproject/nog/backend/pkg/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
)
// `xVersion` and `xBuild` are injected by the `Makefile`.
var (
xVersion string
xBuild string
version = fmt.Sprintf("nogfsostad-%s+%s", xVersion, xBuild)
)
// `qqBackticks()` translates double single quote to backtick.
func qqBackticks(s string) string {
return strings.Replace(s, "''", "`", -1)
}
var usage = qqBackticks(`Usage:
nogfsostad [options] [--prefix-init-limit=<limit>...]
[--repo-init-limit=<limit>...]
[--trim-host-root=<path>] [--shadow-root=<path>]
[--shadow-root-alt=<path>...]
--host=<host>... --prefix=<path>... <registry>...
Options:
--tls-cert=<pem> [default: /nog/ssl/certs/nogfsostad/combined.pem]
TLS certificate and corresponding private key, which is used when
connecting as a client to ''nogfsoregd'' and when listening as a
server with ''--bind-grpc''. PEM files can be concatenated like
''cat cert.pem privkey.pem > combined.pem''.
--tls-ca=<pem> [default: /nog/ssl/certs/nogfsostad/ca.pem]
Certificates that are accepted as CA for TLS connections. Multiple
PEM files can be concatenated.
--jwt-ca=<pem> [default: /nog/ssl/certs/nogfsostad/ca.pem]
X.509 CA for JWTs. Multiple PEM files can be concatenated.
--jwt-ou=<ou> [default: nogfsoiam]
Required OU of JWT signing key X.509 Subject.
--sys-jwt=<path> [default: /nog/jwt/tokens/nogfsostad.jwt]
Path to JWT that is used for system gRPCs.
--jwt-unix-domain=<domain>
The domain that is expected in a JWT ''xcrd'' claim. If unset,
services that require a local Unix user will be disabled.
--udod-socket-dir=<dir>
If set, ''nogfsostad'' will connect to ''nogfsostaudod-path'' daemons
via Unix domain sockets in the specified directory, instead of using
''sudo'' to start ''nogfsostaudod-fd'' processes when needed.
--sududod-socket=<path>
If set, ''nogfsostad'' will connect to ''nogfsostasududod'' via a Unix
domain socket at the specified path to start ''nogfsostaudod-fd''
processes when needed, instead of starting them directly via ''sudo''.
--session-name=<hostname> [default: localhost]
The hostname used during TLS handshake when establishing a callback
session from ''nogfsoregd''. The name must be an X.509 Subject
Alternative Name of ''--tls-cert''.
--nogfsoregd=<addr> [default: localhost:7550]
--shutdown-timeout=<duration> [default: 20s]
Time to wait after receiving a shutdown signal to give clients a chance
to gracefully disconnect and background tasks a chance to gracefully
quit before forcing exit. The shutdown signals are SIGTERM and SIGINT.
--prefix=<path>
Limits processing to repos whose global paths are below one of the
prefixes.
--host=<host>
Repos that pass the prefix filter must be on one of the hosts.
--trim-host-root=<path>
Directory to remove from the start of a host path when mapping it to a
shadow path.
--shadow-root=<path> [default: /nogfso/shadow]
Directory for new shadow repositories.
--shadow-root-alt=<path>
Alternative shadow root directories. ''nogfsostad'' initializes new
shadow repositories below ''--shadow-root''. But it accepts existing
repositories also below alternative shadow roots.
--archive-repo-spool=<path>
Spool directory for archive repo processing. The directory must exist,
it must be writable by ''nogfsostad'', and it must be on the same
filesystem as the realdirs, so that ''rename()'' can be used to swap
placeholders and realdirs.
--unarchive-repo-spool=<path>
Spool directory for unarchive repo processing. The directory must
exist, it must be writable by ''nogfsostad'', and it must be on the
same filesystem as the realdirs, so that ''rename()'' can be used to
swap placeholders and realdirs.
--git-fso-program=<path> [default: /go/src/github.com/nogproject/nog/backend/bin/git-fso]
--gitlab=<addr> [default: http://localhost:80]
Use ''no'' to disable publishing shadow repos to GitLab.
--gitlab-token=<path> [default: /etc/gitlab/root.token]
--log=<logger> [default: prod]
Specifies the logger: ''prod'', ''dev'', or ''mu''.
--observer=<version> [default: v6]
The implementation for monitoring the registry:
* ''v6'': the default since 2018-12.
Older versions have been removed:
* ''v5'' (removed): an experiment in 2018-11.
* ''v4'' (removed): the default from 2018-07 to 2018-11.
* ''v3'' (removed): an experiment in 2018-07.
* ''v2'' (removed): an experiment in 2018-07.
* ''v1'' (removed): was used until 2018-07.
See source Git history for details.
--init-limit-max-files=<count> [default: 2k]
Limits number of files during repo init. If the host path contains
more files, init will be refused. Suffixes ''k'', ''m'', ''g'', ''t''.
--init-limit-max-size=<size> [default: 5G]
Limits data size during repo init. If the host path contains more
data, init will be refused. Suffixes ''k'', ''m'', ''g'', ''t''.
--prefix-init-limit=<limit>
Init limits for repos below a prefix, overriding the global limits.
The prefix must be a directory. ''<limit>'' is specified as
''<global-path-prefix>:<max-files>:<max-size>''. The option can be
repeated to specify limits for multiple prefixes.
--repo-init-limit=<limit>
Per-repo limits, overriding prefix and global limits. ''<limit>''
is specified as ''<global-path>:<max-files>:<max-size>''. The option
can be repeated to specify limits for multiple repos.
--bind-grpc=<addr>
Enables a gRPC server on ''<addr>'', which may be useful for debugging.
The recommended address is ''0.0.0.0:7552''.
--git-gc-scan-start=<wait-duration> [default: 20m]
Enables ''git gc'' on the shadow repos at startup after a wait
duration. Use ''0'' to disable.
--git-gc-scan-every=<interval> [default: 240h]
Enables ''git gc'' at regular intervals in the background on the shadow
repos. Use ''0'' to disable.
--stat-author=<author>
Git author for background stat commits.
Example: ''<NAME> <<EMAIL>>''.
--git-committer=<author>
Git committer for shadow repo commits.
Example: ''nogfsostad <<EMAIL>>''.
--stat-scan-start=<wait-duration> [default: 10m]
Enables ''git-fso stat --mtime-range-only'' on all repos at startup
after a wait duration. Use ''0'' to disable.
--stat-scan-every=<interval> [default: 24h]
Enables ''git-fso stat --mtime-range-only'' on all repos at regular
intervals in the background. Use ''0'' to disable.
--stdtools-projects-root=<path>
Host path to Stdtools projects root.
`)
var (
clientAliveInterval = 40 * time.Second
clientAliveWithoutStream = true
enforceMinAliveInterval = 30 * time.Second
enforcePermitAliveWithoutStream = true
serverAliveInterval = 40 * time.Second
)
type Logger interface {
Infow(msg string, kv ...interface{})
Warnw(msg string, kv ...interface{})
Errorw(msg string, kv ...interface{})
Fatalw(msg string, kv ...interface{})
}
var lg Logger = mulog.Logger{}
func main() {
args := argparse()
var err error
switch args["--log"].(string) {
case "prod":
lg, err = zap.NewProduction()
case "dev":
lg, err = zap.NewDevelopment()
case "mu":
lg = mulog.Logger{}
default:
err = fmt.Errorf("Invalid --log option.")
}
if err != nil {
log.Fatal(err)
}
cert, err := x509io.LoadCombinedCert(args["--tls-cert"].(string))
if err != nil {
lg.Fatalw("Failed to load --tls-cert.", "err", err)
}
ca, err := x509io.LoadCABundle(args["--tls-ca"].(string))
if err != nil {
lg.Fatalw("Failed to load --tls-ca.", "err", err)
}
jwtCa, err := x509io.LoadCABundle(args["--jwt-ca"].(string))
if err != nil {
lg.Fatalw("Failed to load --jwt-ca.", "err", err)
}
authn := grpcjwt.NewRSAAuthn(jwtCa, args["--jwt-ou"].(string))
var domain string
var authnUnix *unixauth.UserAuthn
if arg, ok := args["--jwt-unix-domain"].(string); ok {
domain = arg
authnUnix = &unixauth.UserAuthn{
ContextAuthenticator: authn,
Domain: arg,
}
}
authz := fsoauthz.CreateScopeAuthz(lg)
sysRPCCreds, err := grpcjwt.Load(args["--sys-jwt"].(string))
if err != nil {
lg.Fatalw("Failed to load --sys-jwt", "err", err)
}
lg.Infow("nogfsostad started.")
conn, err := grpc.Dial(
args["--nogfsoregd"].(string),
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: ca,
})),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: clientAliveInterval,
PermitWithoutStream: clientAliveWithoutStream,
}),
)
if err != nil {
lg.Fatalw("Failed to dial nogfsoregd.", "err", err)
}
defer func() {
err := conn.Close()
if err != nil {
lg.Errorw(
"Failed to close nogfsoregd conn.", "err", err,
)
}
}()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM)
signal.Notify(sigs, syscall.SIGINT)
var isShutdown int32
cfg := shadows.Config{
ShadowRoot: args["--shadow-root"].(string),
ShadowRootAlternatives: args["--shadow-root-alt"].([]string),
GitFsoProgram: args["--git-fso-program"].(string),
}
if arg, ok := args["--trim-host-root"].(string); ok {
cfg.TrimHostRoot = arg
}
if arg, ok := args["--git-committer"].(statd.User); ok {
cfg.GitCommitter = shadows.User(arg)
}
shadow, err := shadows.New(lg, cfg)
if err != nil {
lg.Fatalw(
"Failed to create shadow module.",
"err", err,
)
}
var gitlab *gits.Gitlab
if args["--gitlab"] == nil {
lg.Infow("GitLab disabled.")
} else {
gl, err := gits.NewGitlab(&gits.GitlabConfig{
Addr: args["--gitlab"].(string),
TokenPath: args["--gitlab-token"].(string),
})
if err != nil {
lg.Fatalw(
"Failed to create GitLab module.",
"err", err,
)
}
gitlab = gl
}
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
daemons := daemons.New(lg)
wg.Add(1)
go func() {
err := daemons.Run(ctx)
if err != context.Canceled {
lg.Fatalw("daemons.Run() failed.", "err", err)
}
if atomic.LoadInt32(&isShutdown) == 0 {
lg.Fatalw("Unexpected daemons.Run() cancel.")
}
wg.Done()
}()
var nogfsostadPrivileges nogfsostad.Privileges
var testudodPrivileges testudod.Privileges
var aclsPrivileges acls.UdoBashPrivileges
var workflowprocPrivileges workflowproc.Privileges
if sock, ok := args["--sududod-socket"].(string); ok {
lg.Infow(
"Using nogfsostaudo-fd via nogfsostasududod.",
"socket", sock,
)
privs := dialsududod.New(daemons, sock)
nogfsostadPrivileges = privs
testudodPrivileges = privs
aclsPrivileges = privs
workflowprocPrivileges = privs
} else if sockDir, ok := args["--udod-socket-dir"].(string); ok {
lg.Infow(
"Using nogfsostaudod-path.",
"socketDir", sockDir,
)
privs := dialudod.New(daemons, sockDir)
nogfsostadPrivileges = privs
testudodPrivileges = privs
aclsPrivileges = privs
workflowprocPrivileges = privs
} else {
lg.Infow(
"Using Sudo nogfsostaudod-fd.",
)
privs := sudoudod.New(daemons)
nogfsostadPrivileges = privs
testudodPrivileges = privs
aclsPrivileges = privs
workflowprocPrivileges = privs
}
initLimits := nogfsostad.NewInitLimits(&nogfsostad.InitLimitsConfig{
MaxFiles: args["--init-limit-max-files"].(uint64),
MaxBytes: args["--init-limit-max-size"].(uint64),
PrefixLimits: args["--prefix-init-limit"].([]nogfsostad.PathInitLimit),
RepoLimits: args["--repo-init-limit"].([]nogfsostad.PathInitLimit),
})
useUdo := nogfsostad.UseUdo{
// archive-repo and unarchive-repo use udo(root) for rename.
// The configuration is currently hard-coded. We would expose
// it as a command argument if we wanted to use direct rename
// in the future.
Rename: true,
}
broadcaster := nogfsostad.NewBroadcaster(lg, conn, sysRPCCreds)
proc := nogfsostad.NewProcessor(
lg, initLimits, shadow, broadcaster,
nogfsostadPrivileges, useUdo,
)
switch args["--observer"] {
case "v6":
lg.Infow("Started observer v6.")
// Observer v6 uses initializer v4!
initializer4 := nogfsostad.NewRepoInitializer4(
lg,
proc,
conn, sysRPCCreds,
args["--host"].([]string),
shadow, broadcaster, gitlab,
)
obs6 := observer6.New(lg, &observer6.Config{
Registries: args["<registry>"].([]string),
Prefixes: args["--prefix"].([]string),
Conn: conn,
SysRPCCreds: sysRPCCreds,
Initializer: initializer4,
Processor: proc,
})
wg.Add(1)
go func() {
err := obs6.Watch(ctx)
if err != context.Canceled {
lg.Fatalw(
"Observer quit with unexpected error.",
"err", err,
)
}
if atomic.LoadInt32(&isShutdown) == 0 {
lg.Fatalw("Unexpected observer shutdown.")
}
wg.Done()
}()
}
archiveRepoSpool := ""
unarchiveRepoSpool := ""
if arg, ok := args["--archive-repo-spool"].(string); ok {
archiveRepoSpool = arg
lg.Infow(
"Enabled archive-repo spool dir.",
"archiveRepoSpool", archiveRepoSpool,
)
}
if arg, ok := args["--unarchive-repo-spool"].(string); ok {
unarchiveRepoSpool = arg
lg.Infow(
"Enabled unarchive-repo spool dir.",
"unarchiveRepoSpool", unarchiveRepoSpool,
)
}
aclPropagator := acls.NewUdoBash(aclsPrivileges)
workflowProc := workflowproc.New(lg, &workflowproc.Config{
Registries: args["<registry>"].([]string),
Prefixes: args["--prefix"].([]string),
Conn: conn,
SysRPCCreds: sysRPCCreds,
RepoProcessor: proc,
Privileges: workflowprocPrivileges,
AclPropagator: aclPropagator,
ArchiveRepoSpool: archiveRepoSpool,
UnarchiveRepoSpool: unarchiveRepoSpool,
})
wg.Add(1)
go func() {
err := workflowProc.Run(ctx)
if err != context.Canceled {
lg.Fatalw(
"Unexpected workflow processor error.",
"err", err,
)
}
if atomic.LoadInt32(&isShutdown) == 0 {
lg.Fatalw("Unexpected workflow processor shutdown.")
}
wg.Done()
}()
stasrv := nogfsostad.NewStatServer(lg, authn, authz, proc, sysRPCCreds)
// DEPRECATED: See comment at `listener` below.
gsrv := grpc.NewServer(
grpc.Creds(credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: ca,
ClientAuth: tls.RequireAndVerifyClientCert,
})),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: enforceMinAliveInterval,
PermitWithoutStream: enforcePermitAliveWithoutStream,
}),
grpc.KeepaliveParams(keepalive.ServerParameters{
Time: serverAliveInterval,
}),
)
nogfsopb.RegisterStatServer(gsrv, stasrv)
wg.Add(1)
go func() {
err := stasrv.Process(ctx, conn)
if err != context.Canceled {
lg.Fatalw("Statd process failed.", "err", err)
}
if atomic.LoadInt32(&isShutdown) == 0 {
lg.Fatalw("Unexpected statd process cancel.")
}
wg.Done()
}()
// Don't register with `gsrv` but only with session.
gitnogd := nogfsostad.NewGitNogServer(lg, authn, authz, proc)
tarttd := tarttd.New(lg, authn, authz, proc)
var testUdoD nogfsopb.TestUdoServer
if authnUnix == nil || testudodPrivileges == nil {
lg.Infow("Disabled nogfsostaudod.")
} else {
testUdoD = testudod.New(
lg,
authn, domain, authnUnix, authz,
proc, testudodPrivileges,
)
}
stdtoolsProjectsRoot, ok := args["--stdtools-projects-root"].(string)
if ok {
lg.Infow(
"Enabled Stdtools project discovery.",
"projectsRoot", stdtoolsProjectsRoot,
)
} else {
lg.Infow("Disabled Stdtools project discovery.")
}
discoveryd := discoveryd.New(lg, conn, &discoveryd.Config{
Authenticator: authn,
Authorizer: authz,
SysRPCCreds: sysRPCCreds,
Registries: args["<registry>"].([]string),
Prefixes: args["--prefix"].([]string),
Hosts: args["--host"].([]string),
StdtoolsProjectsRoot: stdtoolsProjectsRoot,
})
wg.Add(1)
go func() {
err := discoveryd.Watch(ctx)
if err != context.Canceled {
lg.Fatalw("discoveryd.Watch() failed.", "err", err)
}
if atomic.LoadInt32(&isShutdown) == 0 {
lg.Fatalw("Unexpected discoveryd.Watch() cancel.")
}
wg.Done()
}()
// DEPRECATED: The gRPC listener is disabled by default. All gRPCs use
// reverse gRPC via `nogfsoregd`. The listener may be useful for
// debugging, so we keep it for now. But we could remove it at any
// time.
var listener net.Listener
if addr, ok := args["--bind-grpc"].(string); ok {
addrType := "tcp"
if strings.HasPrefix(addr, "/") {
addrType = "unix"
_ = os.Remove(addr)
}
lis, err := net.Listen(addrType, addr)
if err != nil {
lg.Fatalw("Listen failed.", "family", addrType, "addr", addr)
}
lg.Infow("gRPC listening.", "family", addrType, "addr", addr)
listener = lis
} else {
lg.Infow("gRPC listening disabled.")
}
var wg2 sync.WaitGroup
ctx2, cancel2 := context.WithCancel(context.Background())
sessionCfg := &nogfsostad.SessionConfig{
Prefixes: args["--prefix"].([]string),
Hosts: args["--host"].([]string),
InitLimits: initLimits,
SessionName: args["--session-name"].(string),
TransportCredentials: credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: ca,
ClientAuth: tls.RequireAndVerifyClientCert,
}),
Authenticator: authn,
Authorizer: authz,
SysRPCCreds: sysRPCCreds,
}
session := nogfsostad.NewSession(
lg,
stasrv, gitnogd, gitnogd, discoveryd, tarttd, testUdoD,
sessionCfg,
)
wg2.Add(1)
go func() {
err := session.Process(ctx2, conn)
if err != context.Canceled {
lg.Fatalw("Session process failed.", "err", err)
}
if atomic.LoadInt32(&isShutdown) == 0 {
lg.Fatalw("Unexpected session process cancel.")
}
wg2.Done()
}()
if listener != nil {
wg2.Add(1)
go func() {
err := gsrv.Serve(listener)
if atomic.LoadInt32(&isShutdown) > 0 {
wg2.Done()
return
}
log.Fatal(err)
}()
}
startGitGcScans(args, &wg2, ctx2, proc)
startStatScans(args, &wg2, ctx2, proc)
sig := <-sigs
atomic.StoreInt32(&isShutdown, 1)
done := make(chan struct{})
go func() {
cancel2()
gsrv.GracefulStop()
wg2.Wait()
lg.Infow("Completed level 2 shutdown.")
cancel()
wg.Wait()
lg.Infow("Completed level 1 shutdown.")
close(done)
}()
d := args["--shutdown-timeout"].(time.Duration)
timeout := time.NewTimer(d)
lg.Infow("Started graceful shutdown.", "sig", sig, "timeout", d)
select {
case <-timeout.C:
gsrv.Stop()
lg.Warnw("Timeout; forced shutdown.")
case <-done:
lg.Infow("Completed graceful shutdown.")
}
}
func startGitGcScans(
args map[string]interface{},
wg *sync.WaitGroup,
ctx context.Context,
proc *nogfsostad.Processor,
) {
start, startYes := args["--git-gc-scan-start"].(time.Duration)
if startYes && start == 0 {
startYes = false
}
every, everyYes := args["--git-gc-scan-every"].(time.Duration)
if everyYes && every == 0 {
everyYes = false
}
if !startYes && !everyYes {
return
}
switch {
case startYes && everyYes:
lg.Infow(
"Enabled initial and regular git gc scans.",
"start", start,
"every", every,
)
case startYes:
lg.Infow(
"Enabled initial git gc scan.",
"start", start,
)
case everyYes:
lg.Infow(
"Enabled regular git gc scans.",
"every", every,
)
}
wg.Add(1)
go func() {
defer wg.Done()
gitGcScan(ctx, proc, start, every)
}()
}
func gitGcScan(
ctx context.Context,
proc *nogfsostad.Processor,
scanStart, scanEvery time.Duration,
) {
if scanStart != 0 {
select {
case <-ctx.Done():
return
case <-time.NewTimer(scanStart).C:
}
lg.Infow("Started initial git gc scan.")
err := proc.GitGcAll(ctx)
if err == context.Canceled {
return
}
if err != nil {
lg.Warnw("Initial git gc scan failed.", "err", err)
} else {
lg.Infow("Completed initial git gc scan.")
}
}
if scanEvery == 0 {
return
}
tick := time.NewTicker(scanEvery)
for {
select {
case <-ctx.Done():
tick.Stop()
return
case <-tick.C:
lg.Infow("Started regular git gc scan.")
err := proc.GitGcAll(ctx)
if err == context.Canceled {
continue
}
if err != nil {
lg.Warnw(
"Regular git gc scan failed.",
"err", err,
)
} else {
lg.Infow("Completed regular git gc scan.")
}
}
}
}
func startStatScans(
args map[string]interface{},
wg *sync.WaitGroup,
ctx context.Context,
proc *nogfsostad.Processor,
) {
start, startYes := args["--stat-scan-start"].(time.Duration)
if startYes && start == 0 {
startYes = false
}
every, everyYes := args["--stat-scan-every"].(time.Duration)
if everyYes && every == 0 {
everyYes = false
}
if !startYes && !everyYes {
return
}
author, ok := args["--stat-author"].(statd.User)
if !ok {
lg.Warnw("Stat scans disabled: missing --stat-author.")
return
}
switch {
case startYes && everyYes:
lg.Infow(
"Enabled initial and regular stat scans.",
"start", start,
"every", every,
)
case startYes:
lg.Infow(
"Enabled initial stat scan.",
"start", start,
)
case everyYes:
lg.Infow(
"Enabled regular stat scans.",
"every", every,
)
}
wg.Add(1)
go func() {
defer wg.Done()
statScan(ctx, proc, start, every, author)
}()
}
func statScan(
ctx context.Context,
proc *nogfsostad.Processor,
scanStart, scanEvery time.Duration,
author statd.User,
) {
if scanStart != 0 {
select {
case <-ctx.Done():
return
case <-time.NewTimer(scanStart).C:
}
lg.Infow("Started initial stat scan.")
err := proc.StatMtimeRangeOnlyAllRepos(ctx, author)
if err == context.Canceled {
return
}
if err != nil {
lg.Warnw("Initial stat scan failed.", "err", err)
} else {
lg.Infow("Completed initial stat scan.")
}
}
if scanEvery == 0 {
return
}
tick := time.NewTicker(scanEvery)
for {
select {
case <-ctx.Done():
tick.Stop()
return
case <-tick.C:
lg.Infow("Started regular stat scan.")
err := proc.StatMtimeRangeOnlyAllRepos(ctx, author)
if err == context.Canceled {
continue
}
if err != nil {
lg.Warnw(
"Regular stat scan failed.",
"err", err,
)
} else {
lg.Infow("Completed regular stat scan.")
}
}
}
}
func argparse() map[string]interface{} {
const autoHelp = true
const noOptionFirst = false
args, err := docopt.Parse(
usage, nil, autoHelp, version, noOptionFirst,
)
if err != nil {
lg.Fatalw("docopt failed", "err", err)
}
for _, k := range []string{
"--shutdown-timeout",
"--git-gc-scan-start",
"--git-gc-scan-every",
"--stat-scan-start",
"--stat-scan-every",
} {
if arg, ok := args[k].(string); ok {
d, err := time.ParseDuration(arg)
if err != nil {
lg.Fatalw(
fmt.Sprintf("Invalid %s", k),
"err", err,
)
}
args[k] = d
}
}
for _, k := range []string{
"--init-limit-max-files",
"--init-limit-max-size",
} {
if v, err := parseUint64Si(args[k].(string)); err != nil {
msg := fmt.Sprintf("Invalid %s.", k)
lg.Fatalw(msg, "err", err)
} else {
args[k] = v
}
}
for _, k := range []string{
"--stat-author",
"--git-committer",
} {
if arg, ok := args[k].(string); ok {
name, email, err := parseUser(arg)
if err != nil {
lg.Fatalw(
fmt.Sprintf("Invalid %s", k),
"err", err,
)
}
args[k] = statd.User{
Name: name,
Email: email,
}
}
}
if args["--repo-init-limit"], err = parsePathInitLimits(
args["--repo-init-limit"].([]string),
); err != nil {
lg.Fatalw("Failed to parse --repo-init-limit.", "err", err)
}
if args["--prefix-init-limit"], err = parsePathInitLimits(
args["--prefix-init-limit"].([]string),
); err != nil {
lg.Fatalw("Failed to parse --prefix-init-limit.", "err", err)
}
if args["--gitlab"].(string) == "no" {
args["--gitlab"] = nil
}
if arg := args["--observer"].(string); !isValidObserverVersion(arg) {
lg.Fatalw("Invalid --observer.")
}
return args
}
func isValidObserverVersion(v string) bool {
return v == "v6"
}
func parsePathInitLimits(args []string) ([]nogfsostad.PathInitLimit, error) {
limits := make([]nogfsostad.PathInitLimit, 0)
for _, arg := range args {
lim, err := parsePathInitLimit(arg)
if err != nil {
return nil, err
}
limits = append(limits, lim)
}
return limits, nil
}
func parsePathInitLimit(arg string) (lim nogfsostad.PathInitLimit, err error) {
fields := strings.Split(arg, ":")
if len(fields) != 3 {
err := errors.New("wrong number of fields")
return lim, err
}
lim.Path = fields[0]
lim.MaxFiles, err = parseUint64Si(fields[1])
if err != nil {
return lim, err
}
lim.MaxBytes, err = parseUint64Si(fields[2])
if err != nil {
return lim, err
}
return lim, err
}
var siMap = map[string]uint64{
"k": 1 << 10,
"m": 1 << 20,
"g": 1 << 30,
"t": 1 << 40,
}
func parseUint64Si(s string) (uint64, error) {
s = strings.ToLower(s)
m := uint64(1)
for suf, mult := range siMap {
if strings.HasSuffix(s, suf) {
m = mult
s = s[0 : len(s)-len(suf)]
break
}
}
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
if v < 0 {
err := fmt.Errorf("must be positive, got %d", v)
return 0, err
}
return uint64(v) * m, nil
}
// Example:
// `A U Thor <<EMAIL>>` -> (`A U Thor`, `<EMAIL>`).
var rgxUser = regexp.MustCompile(regexpx.Verbose(`
^
( [^<]+ )
\s
< ( [^>]+ ) >
$
`))
func parseUser(user string) (name, email string, err error) {
m := rgxUser.FindStringSubmatch(user)
if m == nil {
err := fmt.Errorf("does not match `%s`", rgxUser)
return "", "", err
}
return m[1], m[2], nil
}
|
cr88192/bgbtech_btsr1arch | bgbcc22/autohead.c | <reponame>cr88192/bgbtech_btsr1arch
/*
Written by <NAME>
This tool is placed into the public domain.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int doc, pds, amod, prx;
int symchar(int c) //AH:proxy
{
if((c>='a') && (c<='z'))return(1);
if((c>='A') && (c<='Z'))return(1);
if((c>='0') && (c<='9'))return(1);
if(c=='_')return(1);
return(0);
}
char *id_arch()
{
#ifdef __i386__
return("x86");
#endif
#ifdef __x86_64__
return("x64");
#endif
#ifdef _M_IX86
return("x86");
#endif
#ifdef _M_X64
return("x64");
#endif
#ifdef _M_PPC
return("ppc");
#endif
return("unk");
}
char *id_wsuf()
{
#ifdef __i386__
return("32");
#endif
#ifdef __x86_64__
return("64");
#endif
#ifdef _M_IX86
return("32");
#endif
#ifdef _M_X64
return("64");
#endif
#ifdef _M_PPC
return("P32");
#endif
#ifdef _M_PPC64
return("P64");
#endif
return("");
}
void prx_def(char *buf)
{
char tb[1024], tbn[1024], tty[1024];
char *s, *t, *t1, *sa;
int ind;
s=buf; t=tb;
#ifdef _MSC_VER
sprintf(t, "__declspec(dllexport) "); t+=strlen(t);
#endif
t1=tty;
while(symchar(*s))*t1++=*s++;
*t1++=0;
sprintf(t, "%s", tty); t+=strlen(t);
while(*s && (*s<=' '))*t++=*s++;
ind=0;
while(*s=='*') { *t++=*s++; ind++; }
t1=tbn;
while(*s && symchar(*s))*t1++=*s++;
*t1++=0;
sprintf(t, "(*_iproxy_%s)", tbn); t+=strlen(t);
sa=s;
while(*s)*t++=*s++;
*t++=0;
printf("%s;\n", tb);
t=tb;
sprintf(tb, "%s\n\t{ ", buf); t+=strlen(t);
if(strcmp(tty, "void") || ind)
{ sprintf(t, "return "); t+=strlen(t); }
sprintf(t, "_iproxy_%s(", tbn); t+=strlen(t);
s=sa;
while(s && *s!=')')
{
while(*s && (*s!=')') && (*s!=','))s++;
while(!symchar(*(s-1)))s--;
while(symchar(*(s-1)))s--;
if(!strncmp(s, "void)", 5))break;
while(symchar(*s))*t++=*s++;
while(*s && (*s!=')') && (*s!=','))s++;
if(*s==',') { s++; *t++=','; *t++=' '; }
}
sprintf(t, "); }\n"); t+=strlen(t);
printf("%s\n", tb);
}
int main(int argc, char *argv[])
{
int i, j, l, isapi;
FILE *fd;
char *buf, *buf2, *buf3, *buf4;
char *s, *s2, *t;
char *cat, *api;
buf=malloc(16384);
buf2=malloc(16384);
buf3=malloc(1024);
buf4=malloc(1024);
doc=0; pds=0; amod=0; prx=0;
api=NULL;
for(i=1; i<argc; i++)
{
if(argv[i][0]=='-')
{
if(!strcmp(argv[i], "-doc"))
{
doc=1;
cat=argv[i+1];
i++;
continue;
}
if(!strcmp(argv[i], "-pds"))
{
pds=1;
cat=argv[i+1];
i++;
continue;
}
if(!strcmp(argv[i], "-api"))
{
api=argv[i+1];
i++;
continue;
}
if(!strcmp(argv[i], "-apionly"))
{
api=argv[i+1]; amod=1;
i++;
continue;
}
if(!strcmp(argv[i], "-noapi"))
{
api=argv[i+1]; amod=2;
i++;
continue;
}
if(!strcmp(argv[i], "-proxy"))
{
prx=1;
continue;
}
if(!strcmp(argv[i], "-idarch"))
{
printf("%s", id_arch());
exit(0);
}
if(!strcmp(argv[i], "-idwsuf"))
{
printf("%s", id_wsuf());
exit(0);
}
fprintf(stderr, "Unknown option '%s'\n", argv[i]);
exit(-1);
}
fd=fopen(argv[i], "rt");
if(!fd)continue;
printf("//AHSRC:%s\n", argv[i]);
l=0;
while(!feof(fd))
{
fflush(stdout);
memset(buf, 0, 256);
fgets(buf, 255, fd);
l++;
s=buf;
while(*s && (*s!='\r') && (*s!='\n'))s++;
if(*s=='\r')*s=0;
if(*s=='\n')*s=0;
s=buf;
while(*s && (*s<=' '))s++;
if(!strncmp(s, "//AH:", 5))
{
// fprintf(stderr, "//AH tag %s %d\n",
// argv[i], l);
s+=5;
while(*s && (*s<=' '))s++;
if(!strcmp(s, "skip"))break;
}
if(pds)if(!strncmp(s, "//PDSCAT:", 9))
{
s+=9;
t=buf3;
while(*s)*t++=*s++;
*t++=0;
cat=strdup(buf3);
}
if(pds)if(!strncmp(s, "//PDS:", 6))
{
s+=6;
while(*s && (*s<=' '))s++;
t=buf3;
while(*s && strncmp(s, "::", 2))
{
if((s[0]=='\\') && (s[1]<=' '))
{
fgets(buf, 255, fd);
s=buf;
while(*s && (*s<=' '))s++;
if(!strncmp(s, "//", 2))s+=2;
continue;
}
if(*s=='\r')break;
if(*s=='\n')break;
*t++=*s++;
}
*t++=0;
if(!strncmp(s, "::", 2))s+=2;
t=buf4;
while(*s)
{
if((s[0]=='\\') && (s[1]<=' '))
{
fgets(buf, 255, fd);
s=buf;
while(*s && (*s<=' '))s++;
if(!strncmp(s, "//", 2))s+=2;
continue;
}
if(*s=='\r')break;
if(*s=='\n')break;
*t++=*s++;
}
*t++=0;
printf(
"/*--\n"
"Cat %s\n"
"Text\n"
"\t%s\n"
"\t%s\n"
"--*/\n",
cat, buf3, buf4);
}
if(pds)continue;
s=buf;
isapi=0;
if(api)
{
if(!strncmp(s, api, strlen(api)))
{
if(amod==2)continue;
s+=strlen(api);
while(*s && (*s<=' '))s++;
isapi=1;
}else
{
if(amod==1)continue;
}
}
if(!strncmp(s, "static", strlen("static")))
continue;
if(*s<=' ')continue;
while(symchar(*s))s++;
while(*s && (*s<=' '))s++;
while(*s=='*')s++;
if(!*s || (*s=='('))continue;
while(*s && symchar(*s))s++;
if(((*s=='=') || (*s==';')) && isapi)
{
//special case: API variables are exported
t=s;
while(*s && (*s!='/'))s++;
if(!strncmp(s, "//AH:", 5))
{
s+=5;
while(*s && (*s<=' '))s++;
if(!strcmp(s, "ignore"))continue;
}
s=t;
*s=0;
if(!doc)printf("%s;\n", buf);
continue;
}
if(*s==' ')s++;
if(*s!='(')continue;
t=s;
while(*s && (*s!='/'))s++;
if(!strncmp(s, "//AH:", 5))
{
// fprintf(stderr, "//AH tag %s %d\n",
// argv[i], l);
s+=5;
while(*s && (*s<=' '))s++;
if(!strcmp(s, "ignore"))continue;
}
s=t;
if(*s=='(')s++;
j=1;
while(j)
{
if(!*s)
{
memset(buf2, 0, 256);
fgets(buf2, 255, fd);
l++;
t=buf2;
while(*t && (*t<=' '))t++;
s2=t;
t=s;
while(*s2 && (*s2!='\n'))*t++=*s2++;
*t++=' ';
*t++=0;
}else
{
if(*s=='(')j++;
if(*s==')')j--;
s++;
}
}
t=s;
while(*s && (*s!='/'))s++;
if(!strncmp(s, "//AH:", 5))
{
fprintf(stderr, "//AH tag %s %d\n",
argv[i], l);
s+=5;
while(*s && (*s<=' '))s++;
if(!strncmp(s, "ignore", 6))continue;
if(prx && strncmp(s, "proxy", 5))continue;
if(!strncmp(s, "proxy", 5))isapi=2;
}else
{
if(prx)continue;
}
s=t;
if(*s==')')s++;
*s=0;
if(doc)
{
printf(
"/*--\n"
"Cat %s\n"
"Text\n"
"\t%s;\n"
"\t%s:%d\n"
"--*/\n",
cat, buf, argv[i], l);
}else
{
if(prx) { prx_def(buf); continue; }
if(isapi==2) printf("/*AHPRX:*/ ", buf);
printf("%s;\n", buf);
}
}
fclose(fd);
}
return(0);
}
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | platform/lib/all-deps/com/google/gwt/dev/jjs/impl/LongCastNormalizer.java | /*
* Copyright 2008 Google 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.google.gwt.dev.jjs.impl;
import com.google.gwt.dev.jjs.ast.Context;
import com.google.gwt.dev.jjs.ast.JBinaryOperation;
import com.google.gwt.dev.jjs.ast.JBinaryOperator;
import com.google.gwt.dev.jjs.ast.JConditional;
import com.google.gwt.dev.jjs.ast.JDeclarationStatement;
import com.google.gwt.dev.jjs.ast.JExpression;
import com.google.gwt.dev.jjs.ast.JMethod;
import com.google.gwt.dev.jjs.ast.JMethodCall;
import com.google.gwt.dev.jjs.ast.JModVisitor;
import com.google.gwt.dev.jjs.ast.JNewArray;
import com.google.gwt.dev.jjs.ast.JParameter;
import com.google.gwt.dev.jjs.ast.JPrimitiveType;
import com.google.gwt.dev.jjs.ast.JProgram;
import com.google.gwt.dev.jjs.ast.JReturnStatement;
import com.google.gwt.dev.jjs.ast.JType;
import java.util.List;
/**
* Synthesize explicit casts to and from the primitive long type where such a
* cast would have been implicit. The explicit casts serve as markers for
* {@link ImplementCastsAndTypeChecks}.
*/
public class LongCastNormalizer {
/**
* Synthesize casts to longs and from long to trigger conversions.
*/
private class ImplicitCastVisitor extends JModVisitor {
private JMethod currentMethod;
private final JPrimitiveType longType;
public ImplicitCastVisitor(JPrimitiveType longType) {
this.longType = longType;
}
@Override
public void endVisit(JBinaryOperation x, Context ctx) {
JType lhsType = x.getLhs().getType();
JType rhsType = x.getRhs().getType();
JType resultType = x.getType();
JBinaryOperator op = x.getOp();
if (program.isJavaLangString(resultType)) {
// Don't mess with concat.
return;
}
if (lhsType == JPrimitiveType.BOOLEAN
&& (op == JBinaryOperator.AND || op == JBinaryOperator.OR)) {
// Don't mess with if rewriter.
return;
}
// Special case: shift operators always coerce a long RHS to int.
if (op.isShiftOperator()) {
if (rhsType == longType) {
rhsType = program.getTypePrimitiveInt();
}
} else if (lhsType == longType || rhsType == longType) {
// We must coerce lhs and rhs to the same type, either long or a float.
// Assume a long type.
JType coerceTo = longType;
// But double / float takes precedence over long.
JPrimitiveType floatType = program.getTypePrimitiveFloat();
JPrimitiveType doubleType = program.getTypePrimitiveDouble();
// See if the lhs can coerce the rhs
if ((lhsType == floatType || lhsType == doubleType)) {
coerceTo = lhsType;
}
if (op.isAssignment()) {
// In an assignment, the lhs must coerce the rhs
coerceTo = lhsType;
} else if ((rhsType == floatType || rhsType == doubleType)) {
coerceTo = rhsType;
}
lhsType = rhsType = coerceTo;
}
JExpression newLhs = checkAndReplace(x.getLhs(), lhsType);
JExpression newRhs = checkAndReplace(x.getRhs(), rhsType);
if (newLhs != x.getLhs() || newRhs != x.getRhs()) {
JBinaryOperation binOp =
new JBinaryOperation(x.getSourceInfo(), resultType, op, newLhs, newRhs);
ctx.replaceMe(binOp);
}
}
@Override
public void endVisit(JConditional x, Context ctx) {
JExpression newThen = checkAndReplace(x.getThenExpr(), x.getType());
JExpression newElse = checkAndReplace(x.getElseExpr(), x.getType());
if (newThen != x.getThenExpr() || newElse != x.getElseExpr()) {
JConditional newCond =
new JConditional(x.getSourceInfo(), x.getType(), x.getIfTest(), newThen, newElse);
ctx.replaceMe(newCond);
}
}
@Override
public void endVisit(JDeclarationStatement x, Context ctx) {
JExpression init = x.getInitializer();
if (init != null) {
init = checkAndReplace(init, x.getVariableRef().getType());
if (init != x.getInitializer()) {
JDeclarationStatement newStmt =
new JDeclarationStatement(x.getSourceInfo(), x.getVariableRef(), init);
ctx.replaceMe(newStmt);
}
}
}
@Override
public void endVisit(JMethod x, Context ctx) {
currentMethod = null;
}
@Override
public void endVisit(JMethodCall x, Context ctx) {
List<JParameter> params = x.getTarget().getParams();
for (int i = 0; i < params.size(); ++i) {
JParameter param = params.get(i);
JExpression arg = x.getArgs().get(i);
JExpression newArg = checkAndReplace(arg, param.getType());
if (arg != newArg) {
x.setArg(i, newArg);
madeChanges();
}
}
}
@Override
public void endVisit(JNewArray x, Context ctx) {
JType elementType = x.getArrayType().getElementType();
List<JExpression> initializers = x.getInitializers();
if (initializers != null) {
for (int i = 0; i < initializers.size(); ++i) {
JExpression initializer = initializers.get(i);
JExpression newInitializer = checkAndReplace(initializer, elementType);
if (initializer != newInitializer) {
initializers.set(i, newInitializer);
madeChanges();
}
}
}
}
@Override
public void endVisit(JReturnStatement x, Context ctx) {
JExpression expr = x.getExpr();
if (expr != null) {
JExpression newExpr = checkAndReplace(expr, currentMethod.getType());
if (expr != newExpr) {
ctx.replaceMe(newExpr.makeReturnStatement());
}
}
}
@Override
public boolean visit(JMethod x, Context ctx) {
currentMethod = x;
return true;
}
/**
* Returns an explicit cast if the target type is long and the input
* expression is not a long, or if the target type is floating point and the
* expression is a long. TODO(spoon): there is no floating point in this
* method; update the comment
*/
private JExpression checkAndReplace(JExpression arg, JType targetType) {
if (targetType != longType && arg.getType() != longType) {
return arg;
}
return Simplifier.cast(targetType, arg);
}
}
public static void exec(JProgram program) {
new LongCastNormalizer(program).execImpl();
}
private final JProgram program;
private LongCastNormalizer(JProgram program) {
this.program = program;
}
private void execImpl() {
ImplicitCastVisitor visitor = new ImplicitCastVisitor(program.getTypePrimitiveLong());
visitor.accept(program);
}
}
|
jaroslawziolkowski/aurelia-share | public/jspm_packages/npm/core-js@2.1.0/modules/es6.typed.int32-array.js | <reponame>jaroslawziolkowski/aurelia-share<filename>public/jspm_packages/npm/core-js@2.1.0/modules/es6.typed.int32-array.js
/* */
require('./_typed-array')('Int32', 4, function(init) {
return function Int32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
|
bburan/psiexperiment | psi/controller/calibration/make_speaker_calibration.py | import argparse
import tables as tb
import pylab as pl
from psi.controller.calibration import util
if __name__ == '__main__':
desc = 'Convert to speaker calibration'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('filename', type=str, help='filename')
parser.add_argument('smoothing', type=float)
args = parser.parse_args()
with tb.open_file(args.filename, 'a') as fh:
fs = fh.root._v_attrs['fs']
output_gain = fh.root._v_attrs['output_gain']
mic_sens = fh.root._v_attrs['ref_mic_sens']
discard = fh.root._v_attrs['discard']
n = fh.root._v_attrs['n']
a = fh.root.a.read()
b = fh.root.b.read()
ar = fh.root.a_response.read()[discard:, 0]
br = fh.root.b_response.read()[discard:, 0]
freq, vrms, phase = util.golay_tf(a, b, ar, br, fs)
vrms = vrms.mean(axis=0)
phase = phase.mean(axis=0)
_, sig_vrms, _ = util.golay_tf(a, b, a, b, fs)
# actual output of speaker
spl = util.db(vrms)-util.db(mic_sens)-util.db(20e-6)
# correct speaker output so it represents gain of 0 and Vrms=1
norm_spl = spl-output_gain-util.db(sig_vrms)
# Calculate sensitivity of speaker as dB (Vrms/Pa)
sens = -norm_spl-util.db(20e-6)
sens_smoothed = util.freq_smooth(freq, sens, args.smoothing)
if 'smoothed_sensitivity' in fh.root:
fh.root.smoothed_sensitivity._f_remove()
if 'smoothed_phase' in fh.root:
fh.root.smoothed_phase._f_remove()
node = fh.create_array(fh.root, 'smoothed_sensitivity', sens_smoothed)
node._v_attrs['smoothing'] = args.smoothing
node = fh.create_array(fh.root, 'smoothed_phase', sens)
node._v_attrs['smoothing'] = args.smoothing
pl.semilogx(freq, sens, 'k-')
pl.semilogx(freq, sens_smoothed, 'r-', lw=2)
pl.show()
|
w2k31984/Selenium_WebDriver_Python | Selenium_WebDriver/Find_Element_by_name2.py | import time
from selenium import webdriver
def main():
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://www.google.com/')
time.sleep(2)
driver.find_element_by_name('q').send_keys('selenium')
input()
if __name__ == '__main__':
main() |
touxiong88/92_mediatek | hardware/ril/mtk-ril/mtk_mcc_table.h | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
{202,2}, //Greece
{204,2}, //Netherlands (Kingdom of the)
{206,2}, //Belgium
{208,2}, //France
{212,2}, //Monaco (Principality of)
{213,2}, //Andorra (Principality of)
{214,2}, //Spain
{216,2}, //Hungary (Republic of)
{218,2}, //Bosnia and Herzegovina
{219,2}, //Croatia (Republic of)
{220,2}, //Serbia and Montenegro
{222,2}, //Italy
{225,2}, //Vatican City State
{226,2}, //Romania
{228,2}, //Switzerland (Confederation of)
{230,2}, //Czech Republic
{231,2}, //Slovak Republic
{232,2}, //Austria
{234,2}, //United Kingdom of Great Britain and Northern Ireland
{235,2}, //United Kingdom of Great Britain and Northern Ireland
{238,2}, //Denmark
{240,2}, //Sweden
{242,2}, //Norway
{244,2}, //Finland
{246,2}, //Lithuania (Republic of)
{247,2}, //Latvia (Republic of)
{248,2}, //Estonia (Republic of)
{250,2}, //Russian Federation
{255,2}, //Ukraine
{257,2}, //Belarus (Republic of)
{259,2}, //Moldova (Republic of)
{260,2}, //Poland (Republic of)
{262,2}, //Germany (Federal Republic of)
{266,2}, //Gibraltar
{268,2}, //Portugal
{270,2}, //Luxembourg
{272,2}, //Ireland
{274,2}, //Iceland
{276,2}, //Albania (Republic of)
{278,2}, //Malta
{280,2}, //Cyprus (Republic of)
{282,2}, //Georgia
{283,2}, //Armenia (Republic of)
{284,2}, //Bulgaria (Republic of)
{286,2}, //Turkey
{288,2}, //Faroe Islands
{289,2}, //Abkhazia (Georgia)
{290,2}, //Greenland (Denmark)
{292,2}, //San Marino (Republic of)
{293,2}, //Slovenia (Republic of)
{294,2}, //The Former Yugoslav Republic of Macedonia
{295,2}, //Liechtenstein (Principality of)
{297,2}, //Montenegro (Republic of)
{302,3}, //Canada
{308,2}, //Saint Pierre and Miquelon (Collectivit territoriale de la Rpublique franaise)
{310,3}, //United States of America
{311,3}, //United States of America
{312,3}, //United States of America
{313,3}, //United States of America
{314,3}, //United States of America
{315,3}, //United States of America
{316,3}, //United States of America
{330,2}, //Puerto Rico
{332,2}, //United States Virgin Islands
{334,3}, //Mexico
{338,3}, //Jamaica
{340,2}, //Guadeloupe (French Department of)
{342,3}, //Barbados
{344,3}, //Antigua and Barbuda
{346,3}, //Cayman Islands
{348,3}, //British Virgin Islands
{350,2}, //Bermuda
{352,2}, //Grenada
{354,2}, //Montserrat
{356,2}, //Saint Kitts and Nevis
{358,2}, //Saint Lucia
{360,2}, //Saint Vincent and the Grenadines
{362,2}, //Netherlands Antilles
{363,2}, //Aruba
{364,2}, //Bahamas (Commonwealth of the)
{365,3}, //Anguilla
{366,2}, //Dominica (Commonwealth of)
{368,2}, //Cuba
{370,2}, //Dominican Republic
{372,2}, //Haiti (Republic of)
{374,2}, //Trinidad and Tobago
{376,2}, //Turks and Caicos Islands
{400,2}, //Azerbaijani Republic
{401,2}, //Kazakhstan (Republic of)
{402,2}, //Bhutan (Kingdom of)
{404,2}, //India (Republic of)
{405,2}, //India (Republic of)
{410,2}, //Pakistan (Islamic Republic of)
{412,2}, //Afghanistan
{413,2}, //Sri Lanka (Democratic Socialist Republic of)
{414,2}, //Myanmar (Union of)
{415,2}, //Lebanon
{416,2}, //Jordan (Hashemite Kingdom of)
{417,2}, //Syrian Arab Republic
{418,2}, //Iraq (Republic of)
{419,2}, //Kuwait (State of)
{420,2}, //Saudi Arabia (Kingdom of)
{421,2}, //Yemen (Republic of)
{422,2}, //Oman (Sultanate of)
{423,2}, //Palestine
{424,2}, //United Arab Emirates
{425,2}, //Israel (State of)
{426,2}, //Bahrain (Kingdom of)
{427,2}, //Qatar (State of)
{428,2}, //Mongolia
{429,2}, //Nepal
{430,2}, //United Arab Emirates
{431,2}, //United Arab Emirates
{432,2}, //Iran (Islamic Republic of)
{434,2}, //Uzbekistan (Republic of)
{436,2}, //Tajikistan (Republic of)
{437,2}, //Kyrgyz Republic
{438,2}, //Turkmenistan
{440,2}, //Japan
{441,2}, //Japan
{450,2}, //Korea (Republic of)
{452,2}, //Viet Nam (Socialist Republic of)
{454,2}, //Hong Kong, China
{455,2}, //Macao, China
{456,2}, //Cambodia (Kingdom of)
{457,2}, //Lao People's Democratic Republic
{460,2}, //China (People's Republic of)
{461,2}, //China (People's Republic of)
{466,2}, //Taiwan, China
{467,2}, //Democratic People's Republic of Korea
{470,2}, //Bangladesh (People's Republic of)
{472,2}, //Maldives (Republic of)
{502,2}, //Malaysia
{505,2}, //Australia
{510,2}, //Indonesia (Republic of)
{514,2}, //Democratic Republic of Timor-Leste
{515,2}, //Philippines (Republic of the)
{520,2}, //Thailand
{525,2}, //Singapore (Republic of)
{528,2}, //Brunei Darussalam
{530,2}, //New Zealand
{534,2}, //Northern Mariana Islands (Commonwealth of the)
{535,2}, //Guam
{536,2}, //Nauru (Republic of)
{537,2}, //Papua New Guinea
{539,2}, //Tonga (Kingdom of)
{540,2}, //Solomon Islands
{541,2}, //Vanuatu (Republic of)
{542,2}, //Fiji (Republic of)
{543,2}, //Wallis and Futuna (Territoire franais d'outre-mer)
{544,2}, //American Samoa
{545,2}, //Kiribati (Republic of)
{546,2}, //New Caledonia (Territoire franais d'outre-mer)
{547,2}, //French Polynesia (Territoire franais d'outre-mer)
{548,2}, //Cook Islands
{549,2}, //Samoa (Independent State of)
{550,2}, //Micronesia (Federated States of)
{551,2}, //Marshall Islands (Republic of the)
{552,2}, //Palau (Republic of)
{602,2}, //Egypt (Arab Republic of)
{603,2}, //Algeria (People's Democratic Republic of)
{604,2}, //Morocco (Kingdom of)
{605,2}, //Tunisia
{606,2}, //Libya (Socialist People's Libyan Arab Jamahiriya)
{607,2}, //Gambia (Republic of the)
{608,2}, //Senegal (Republic of)
{609,2}, //Mauritania (Islamic Republic of)
{610,2}, //Mali (Republic of)
{611,2}, //Guinea (Republic of)
{612,2}, //Cte d'Ivoire (Republic of)
{613,2}, //Burkina Faso
{614,2}, //Niger (Republic of the)
{615,2}, //Togolese Republic
{616,2}, //Benin (Republic of)
{617,2}, //Mauritius (Republic of)
{618,2}, //Liberia (Republic of)
{619,2}, //Sierra Leone
{620,2}, //Ghana
{621,2}, //Nigeria (Federal Republic of)
{622,2}, //Chad (Republic of)
{623,2}, //Central African Republic
{624,2}, //Cameroon (Republic of)
{625,2}, //Cape Verde (Republic of)
{626,2}, //Sao Tome and Principe (Democratic Republic of)
{627,2}, //Equatorial Guinea (Republic of)
{628,2}, //Gabonese Republic
{629,2}, //Congo (Republic of the)
{630,2}, //Democratic Republic of the Congo
{631,2}, //Angola (Republic of)
{632,2}, //Guinea-Bissau (Republic of)
{633,2}, //Seychelles (Republic of)
{634,2}, //Sudan (Republic of the)
{635,2}, //Rwanda (Republic of)
{636,2}, //Ethiopia (Federal Democratic Republic of)
{637,2}, //Somali Democratic Republic
{638,2}, //Djibouti (Republic of)
{639,2}, //Kenya (Republic of)
{640,2}, //Tanzania (United Republic of)
{641,2}, //Uganda (Republic of)
{642,2}, //Burundi (Republic of)
{643,2}, //Mozambique (Republic of)
{645,2}, //Zambia (Republic of)
{646,2}, //Madagascar (Republic of)
{647,2}, //Reunion (French Department of)
{648,2}, //Zimbabwe (Republic of)
{649,2}, //Namibia (Republic of)
{650,2}, //Malawi
{651,2}, //Lesotho (Kingdom of)
{652,2}, //Botswana (Republic of)
{653,2}, //Swaziland (Kingdom of)
{654,2}, //Comoros (Union of the)
{655,2}, //South Africa (Republic of)
{657,2}, //Eritrea
{702,2}, //Belize
{704,2}, //Guatemala (Republic of)
{706,2}, //El Salvador (Republic of)
{708,3}, //Honduras (Republic of)
{710,2}, //Nicaragua
{712,2}, //Costa Rica
{714,2}, //Panama (Republic of)
{716,2}, //Peru
{722,3}, //Argentine Republic
{724,2}, //Brazil (Federative Republic of)
{730,2}, //Chile
{732,3}, //Colombia (Republic of)
{734,2}, //Venezuela (Bolivarian Republic of)
{736,2}, //Bolivia (Republic of)
{738,2}, //Guyana
{740,2}, //Ecuador
{742,2}, //French Guiana (French Department of)
{744,2}, //Paraguay (Republic of)
{746,2}, //Suriname (Republic of)
{748,2}, //Uruguay (Eastern Republic of)
{750,2} //Falkland Islands (Malvinas)
|
crupest/cru | src/ui/mapper/Mapper.cpp | <reponame>crupest/cru<filename>src/ui/mapper/Mapper.cpp
#include "cru/ui/mapper/Mapper.hpp"
#include <typeindex>
namespace cru::ui::mapper {
MapperBase::MapperBase(std::type_index type_index)
: type_index_(std::move(type_index)) {}
} // namespace cru::ui::mapper
|
lionheart1022/koding | go/src/vendor/github.com/siesta/neo4j/relationship.go | <gh_stars>0
package neo4j
import (
"encoding/json"
"errors"
"fmt"
)
// Relationship struct
type Relationship struct {
ID string
StartNodeID string
EndNodeID string
Type string
Data map[string]interface{}
Payload *RelationshipResponse
}
// RelationshipResponse struct returned from Neo4J server
type RelationshipResponse struct {
Start string `json:"start"`
Property string `json:"property"`
Self string `json:"self"`
Properties string `json:"properties"`
Type string `json:"type"`
End string `json:"end"`
Data map[string]interface{} `json:"data"`
}
// GetRelationshipTypes queries Neo4J for all relationships
func (neo4j *Neo4j) GetRelationshipTypes() ([]string, error) {
url := fmt.Sprintf("%s/types", neo4j.RelationshipURL)
var result = make([]string, 0)
response, err := neo4j.doRequest("GET", url, "")
if err != nil {
return result, err
}
err = json.Unmarshal([]byte(response), &result)
if err != nil {
return result, err
}
return result, err
}
func (r *Relationship) mapBatchResponse(neo4j *Neo4j, data interface{}) (bool, error) {
// because data is a map, convert back to Json
encodedData, err := jsonEncode(data)
result, err := r.decode(neo4j, encodedData)
return result, err
}
func (r *Relationship) getBatchQuery(operation string) (map[string]interface{}, error) {
query := make(map[string]interface{})
switch operation {
case BatchGet:
query, err := prepareRelationshipGetBatchMap(r)
return query, err
case BatchUpdate:
query, err := prepareRelationshipUpdateBatchMap(r)
return query, err
case BatchCreate:
query, err := prepareRelationshipCreateBatchMap(r)
return query, err
case BatchDelete:
query, err := prepareRelationshipDeleteBatchMap(r)
return query, err
case BatchCreateUnique:
query, err := prepareRelationshipCreateUniqueBatchMap(r)
return query, err
}
return query, nil
}
func prepareRelationshipGetBatchMap(r *Relationship) (map[string]interface{}, error) {
query := make(map[string]interface{})
if r.ID == "" {
return query, errors.New("Id not valid")
}
query["method"] = "GET"
query["to"] = fmt.Sprintf("/relationship/%s", r.ID)
return query, nil
}
func prepareRelationshipDeleteBatchMap(r *Relationship) (map[string]interface{}, error) {
query := make(map[string]interface{})
if r.ID == "" {
return query, errors.New("Id not valid")
}
query["method"] = "DELETE"
query["to"] = fmt.Sprintf("/relationship/%s", r.ID)
return query, nil
}
func prepareRelationshipCreateBatchMap(r *Relationship) (map[string]interface{}, error) {
query := make(map[string]interface{})
if r.StartNodeID == "" {
return query, errors.New("Start Node Id not valid")
}
if r.EndNodeID == "" {
return query, errors.New("End Node Id not valid")
}
if r.Type == "" {
return query, errors.New("Relationship type is not valid")
}
url := fmt.Sprintf("/node/%s/relationships", r.StartNodeID)
endNodeURL := fmt.Sprintf("/node/%s", r.EndNodeID)
return map[string]interface{}{
"method": "POST",
"to": url,
"body": map[string]interface{}{
"to": endNodeURL,
"type": r.Type,
"data": r.Data,
},
}, nil
}
func prepareRelationshipCreateUniqueBatchMap(r *Relationship) (map[string]interface{}, error) {
query := make(map[string]interface{})
if r.StartNodeID == "" {
return query, errors.New("Start Node Id not valid")
}
if r.EndNodeID == "" {
return query, errors.New("End Node Id not valid")
}
if r.Type == "" {
return query, errors.New("Relationship type is not valid")
}
startURL := fmt.Sprintf("/node/%s", r.StartNodeID)
endNodeURL := fmt.Sprintf("/node/%s", r.EndNodeID)
return map[string]interface{}{
"method": "POST",
"to": "/index/relationship",
"body": map[string]interface{}{
"start": startURL,
"end": endNodeURL,
"type": r.Type,
"properties": r.Data,
},
}, nil
}
func prepareRelationshipUpdateBatchMap(r *Relationship) (map[string]interface{}, error) {
query := make(map[string]interface{})
if r.ID == "" {
return query, errors.New("Id not valid")
}
query = map[string]interface{}{
"method": "PUT",
"to": fmt.Sprintf("/relationship/%s/properties", r.ID),
"body": r.Data,
}
return query, nil
}
// GetOutgoingRelationships queries outgoing relationships for a node
func (neo4j *Neo4j) GetOutgoingRelationships(node *Node) ([]Relationship, error) {
res, err := getRelationships(neo4j, node, "out")
return res, err
}
// GetAllRelationships queries all relationships for a node
func (neo4j *Neo4j) GetAllRelationships(node *Node) ([]Relationship, error) {
res, err := getRelationships(neo4j, node, "all")
return res, err
}
// GetIncomingRelationships queries incoming realtionships for a node
func (neo4j *Neo4j) GetIncomingRelationships(node *Node) ([]Relationship, error) {
res, err := getRelationships(neo4j, node, "in")
return res, err
}
// GetOutgoingTypedRelationships queries TYPED outgoing relationships for a node
func (neo4j *Neo4j) GetOutgoingTypedRelationships(node *Node, relType string) ([]Relationship, error) {
res, err := getRelationships(neo4j, node, fmt.Sprintf("out/%s", relType))
return res, err
}
// GetAllTypedRelationships queries all TYPED relationships for a node
func (neo4j *Neo4j) GetAllTypedRelationships(node *Node, relType string) ([]Relationship, error) {
res, err := getRelationships(neo4j, node, fmt.Sprintf("all/%s", relType))
return res, err
}
// GetIncomingTypedRelationships queries TYPED incoming realtionships for a node
func (neo4j *Neo4j) GetIncomingTypedRelationships(node *Node, relType string) ([]Relationship, error) {
res, err := getRelationships(neo4j, node, fmt.Sprintf("in/%s", relType))
return res, err
}
func getRelationships(neo4j *Neo4j, node *Node, direction string) ([]Relationship, error) {
if node.ID == "" {
return nil, errors.New("Id is not given")
}
customReq := &ManuelBatchRequest{}
customReq.To = fmt.Sprintf("/node/%s/relationships/%s", node.ID, direction)
neo4j.NewBatch().Get(customReq).Execute()
result := []Relationship{}
err := neo4j.GetManualBatchResponse(customReq, &result)
if err != nil {
return nil, err
}
return result, nil
}
func (r *Relationship) encodeData() (string, error) {
result, err := jsonEncode(r.Data)
return result, err
}
func (r *Relationship) decode(neo4j *Neo4j, data string) (bool, error) {
payload := &RelationshipResponse{}
// Map json to our RelationshipResponse struct
err := json.Unmarshal([]byte(data), payload)
if err != nil {
return false, err
}
// Map returning result to our relationship struct
err = mapRelationship(neo4j, r, payload)
if err != nil {
return false, err
}
return true, nil
}
func mapRelationship(neo4j *Neo4j, relationship *Relationship, payload *RelationshipResponse) error {
relationshipID, err := getIDFromURL(neo4j.RelationshipURL, payload.Self)
if err != nil {
return err
}
startNodeID, err := getIDFromURL(neo4j.NodeURL, payload.Start)
if err != nil {
return err
}
endNodeID, err := getIDFromURL(neo4j.NodeURL, payload.End)
if err != nil {
return err
}
relationship.ID = relationshipID
relationship.StartNodeID = startNodeID
relationship.EndNodeID = endNodeID
relationship.Type = payload.Type
relationship.Data = payload.Data
relationship.Payload = payload
return nil
}
|
fhoffa/bqtail | stage/load/schema.go | <reponame>fhoffa/bqtail<filename>stage/load/schema.go
package load
import (
"context"
"github.com/pkg/errors"
"github.com/viant/bqtail/base"
"github.com/viant/bqtail/service/bq"
"github.com/viant/bqtail/shared"
"google.golang.org/api/bigquery/v2"
)
func (j *Job) updateSchemaIfNeeded(ctx context.Context, tableReference *bigquery.TableReference, service bq.Service) error {
var err error
var table *bigquery.Table
hasTransientTemplate := false
transient := j.Rule.Dest.Transient
if j.Rule.Dest.Schema.Template != "" {
templateRef, err := base.NewTableReference(j.Rule.Dest.Schema.Template)
if err != nil {
return errors.Wrapf(err, "invalid template: %v", j.Rule.Dest.Schema.Template)
}
table, err = service.Table(ctx, templateRef)
if err != nil {
return errors.Wrapf(err, "fail to get template table: %v", j.Rule.Dest.Schema.Template)
}
table.TableReference, _ = base.NewTableReference(j.DestTable)
if err = service.CreateTableIfNotExist(ctx, table, true); err != nil {
return errors.Wrapf(err, "failed to create table: %v", base.EncodeTableReference(tableReference, false))
}
j.DestSchema = table
}
if j.Rule.Dest.Schema.Autodetect {
j.Load.Schema = nil
j.Load.DestinationTable = tableReference
j.Load.Autodetect = true
return nil
}
if transient != nil {
datasetRef := &bigquery.DatasetReference{ProjectId: j.ProjectID, DatasetId: transient.Dataset}
if err := service.CreateDatasetIfNotExist(ctx, transient.Region, datasetRef); err != nil {
return errors.Wrapf(err, "failed to create transient dataset: %v", transient.Dataset)
}
j.Load.WriteDisposition = shared.WriteDispositionTruncate
if hasTransientTemplate = transient.Template != ""; hasTransientTemplate {
transientTempRef, err := base.NewTableReference(transient.Template)
if err != nil {
return errors.Wrapf(err, "failed to create table from transient.Template: %v", transient.Template)
}
if table, err = service.Table(ctx, transientTempRef); err != nil {
return errors.Wrapf(err, "failed to get template table: %v", base.EncodeTableReference(transientTempRef, false))
}
j.TempSchema = table
}
}
if table == nil && !hasTransientTemplate && !j.Rule.Dest.Schema.Autodetect {
if table, err = service.Table(ctx, tableReference); err != nil {
return errors.Wrapf(err, "failed to get table: %v", base.EncodeTableReference(tableReference, false))
}
j.DestSchema = table
}
if j.TempSchema != nil {
j.updateSchema(j.TempSchema)
} else if j.DestSchema != nil {
j.updateSchema(j.DestSchema)
}
return nil
}
func (j *Job) updateSchema(table *bigquery.Table) {
if table != nil {
j.Load.Schema = table.Schema
if table.TimePartitioning != nil {
j.Load.TimePartitioning = table.TimePartitioning
j.Load.TimePartitioning.RequirePartitionFilter = false
}
if table.RangePartitioning != nil {
j.Load.RangePartitioning = table.RangePartitioning
}
if table.Clustering != nil {
j.Load.Clustering = table.Clustering
}
}
}
|
vsch/idea-markdown | src/main/java/com/vladsch/md/nav/psi/element/MdOrderedList.java | // Copyright (c) 2015-2020 <NAME> <<EMAIL>> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element;
import com.vladsch.md.nav.actions.handlers.util.PsiEditContext;
import org.jetbrains.annotations.NotNull;
public interface MdOrderedList extends MdList {
int itemOrdinalOffset(boolean skipFirst, @NotNull PsiEditContext editContext);
}
|
botttos/PalmGine | 3D Engine/AK/Plugins/AkDelay/Sources/AudioEngineFX/AkDelayFXParams.h | /*******************************************************************************
The content of this file includes portions of the AUDIOKINETIC Wwise Technology
released in source code form as part of the SDK installer package.
Commercial License Usage
Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
may use this file in accordance with the end user license agreement provided
with the software or, alternatively, in accordance with the terms contained in a
written agreement between you and Audiokinetic Inc.
Version: v2017.2.6 Build: 6636
Copyright (c) 2006-2018 Audiokinetic Inc.
*******************************************************************************/
//////////////////////////////////////////////////////////////////////
//
// AkDelayFXParams.h
//
// Shared parameter implementation for Delay FX.
//
//////////////////////////////////////////////////////////////////////
#ifndef _AK_DELAYFXPARAMS_H_
#define _AK_DELAYFXPARAMS_H_
#include <AK/SoundEngine/Common/IAkPlugin.h>
// Parameters IDs for the Wwise or RTPC.
// Those IDs map to the AudioEnginePropertyID attributes in the XML property definition
static const AkPluginParamID AK_DELAYFXPARAM_DELAYTIME_ID = 0;
static const AkPluginParamID AK_DELAYFXPARAM_FEEDBACK_ID = 1; // RTPC
static const AkPluginParamID AK_DELAYFXPARAM_WETDRYMIX_ID = 2; // RTPC
static const AkPluginParamID AK_DELAYFXPARAM_OUTPUTGAIN_ID = 3; // RTPC
static const AkPluginParamID AK_DELAYFXPARAM_FEEDBACKENABLED_ID = 4; // RTPC
static const AkPluginParamID AK_DELAYFXPARAM_PROCESSLFE_ID = 5;
static const AkPluginParamID AK_DELAYFXPARAM_NUM = 6;
// Default parameter values
#define DELAYFXPARAM_DELAYTIME_DEF (0.5f) // secs
#define DELAYFXPARAM_FEEDBACK_DEF (0.f) // Percent
#define DELAYFXPARAM_WETDRYMIX_DEF (50.f) // Percent
#define DELAYFXPARAM_OUTPUTLEVEL_DEF (0.f) // dBFS
#define DELAYFXPARAM_FEEDBACKENABLED_DEF (false) // Disabled
#define DELAYFXPARAM_PROCESSLFE_DEF (true)
static const AkReal32 ONEOVER_DELAYFXPARAM_PERCENT_MAX = 0.01f;
struct AkDelayRTPCParams
{
AkReal32 fFeedback;
AkReal32 fWetDryMix;
AkReal32 fOutputLevel;
bool bFeedbackEnabled;
bool bHasChanged;
};
struct AkDelayNonRTPCParams
{
AkReal32 fDelayTime;
bool bProcessLFE;
bool bHasChanged;
};
struct AkDelayFXParams
{
AkDelayRTPCParams RTPC;
AkDelayNonRTPCParams NonRTPC;
} AK_ALIGN_DMA;
class CAkDelayFXParams
: public AK::IAkPluginParam
, public AkDelayFXParams
{
public:
/// Constructor.
CAkDelayFXParams( );
/// Copy constructor.
CAkDelayFXParams( const CAkDelayFXParams & in_rCopy );
/// Destructor.
~CAkDelayFXParams();
/// Create parameter node duplicate.
IAkPluginParam * Clone( AK::IAkPluginMemAlloc * in_pAllocator );
/// Parameter node initialization.
AKRESULT Init(
AK::IAkPluginMemAlloc * in_pAllocator,
const void * in_pParamsBlock,
AkUInt32 in_ulBlockSize
);
/// Parameter node termination.
AKRESULT Term( AK::IAkPluginMemAlloc * in_pAllocator );
/// Parameter block set.
AKRESULT SetParamsBlock(
const void *in_pParamsBlock,
AkUInt32 in_ulBlockSize
);
/// Update a single parameter.
AKRESULT SetParam(
AkPluginParamID in_ParamID,
const void * in_pValue,
AkUInt32 in_ulParamSize
);
};
#endif // _AK_DELAYFXPARAMS_H_
|
MichielDHont1/denizen_forge | src/main/java/com/denizen_forge/denizen/objects/properties/material/MaterialDrags.java | package com.denizenscript.denizen.objects.properties.material;
import com.denizenscript.denizen.objects.MaterialTag;
import com.denizenscript.denizencore.objects.Mechanism;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.properties.Property;
import com.denizenscript.denizencore.objects.properties.PropertyParser;
import com.denizenscript.denizencore.utilities.Deprecations;
import org.bukkit.block.data.type.BubbleColumn;
@Deprecated
public class MaterialDrags implements Property {
public static boolean describes(ObjectTag material) {
return material instanceof MaterialTag
&& ((MaterialTag) material).hasModernData()
&& ((MaterialTag) material).getModernData() instanceof BubbleColumn;
}
public static MaterialDrags getFrom(ObjectTag _material) {
if (!describes(_material)) {
return null;
}
else {
return new MaterialDrags((MaterialTag) _material);
}
}
public static final String[] handledMechs = new String[] {
"drags"
};
private MaterialDrags(MaterialTag _material) {
material = _material;
}
MaterialTag material;
public static void registerTags() {
PropertyParser.<MaterialDrags>registerTag("drags", (attribute, material) -> {
Deprecations.materialDrags.warn(attribute.context);
return new ElementTag(material.isDrag());
});
}
public BubbleColumn getBubbleColumn() {
return (BubbleColumn) material.getModernData();
}
public boolean isDrag() {
return getBubbleColumn().isDrag();
}
@Override
public String getPropertyString() {
return String.valueOf(isDrag());
}
@Override
public String getPropertyId() {
return "drags";
}
@Override
public void adjust(Mechanism mechanism) {
if (mechanism.matches("drags") && mechanism.requireBoolean()) {
Deprecations.materialDrags.warn(mechanism.context);
getBubbleColumn().setDrag(mechanism.getValue().asBoolean());
}
}
}
|
TencentCloud/tencentcloud-sdk-cpp-intl-en | tke/include/tencentcloud/tke/v20180525/model/NodeCountSummary.h | <reponame>TencentCloud/tencentcloud-sdk-cpp-intl-en
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#ifndef TENCENTCLOUD_TKE_V20180525_MODEL_NODECOUNTSUMMARY_H_
#define TENCENTCLOUD_TKE_V20180525_MODEL_NODECOUNTSUMMARY_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/tke/v20180525/model/ManuallyAdded.h>
#include <tencentcloud/tke/v20180525/model/AutoscalingAdded.h>
namespace TencentCloud
{
namespace Tke
{
namespace V20180525
{
namespace Model
{
/**
* Node statistics list
*/
class NodeCountSummary : public AbstractModel
{
public:
NodeCountSummary();
~NodeCountSummary() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取Nodes that are manually managed
Note: this field may return `null`, indicating that no valid value is obtained.
* @return ManuallyAdded Nodes that are manually managed
Note: this field may return `null`, indicating that no valid value is obtained.
*/
ManuallyAdded GetManuallyAdded() const;
/**
* 设置Nodes that are manually managed
Note: this field may return `null`, indicating that no valid value is obtained.
* @param ManuallyAdded Nodes that are manually managed
Note: this field may return `null`, indicating that no valid value is obtained.
*/
void SetManuallyAdded(const ManuallyAdded& _manuallyAdded);
/**
* 判断参数 ManuallyAdded 是否已赋值
* @return ManuallyAdded 是否已赋值
*/
bool ManuallyAddedHasBeenSet() const;
/**
* 获取Nodes that are automatically managed
Note: this field may return `null`, indicating that no valid value is obtained.
* @return AutoscalingAdded Nodes that are automatically managed
Note: this field may return `null`, indicating that no valid value is obtained.
*/
AutoscalingAdded GetAutoscalingAdded() const;
/**
* 设置Nodes that are automatically managed
Note: this field may return `null`, indicating that no valid value is obtained.
* @param AutoscalingAdded Nodes that are automatically managed
Note: this field may return `null`, indicating that no valid value is obtained.
*/
void SetAutoscalingAdded(const AutoscalingAdded& _autoscalingAdded);
/**
* 判断参数 AutoscalingAdded 是否已赋值
* @return AutoscalingAdded 是否已赋值
*/
bool AutoscalingAddedHasBeenSet() const;
private:
/**
* Nodes that are manually managed
Note: this field may return `null`, indicating that no valid value is obtained.
*/
ManuallyAdded m_manuallyAdded;
bool m_manuallyAddedHasBeenSet;
/**
* Nodes that are automatically managed
Note: this field may return `null`, indicating that no valid value is obtained.
*/
AutoscalingAdded m_autoscalingAdded;
bool m_autoscalingAddedHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TKE_V20180525_MODEL_NODECOUNTSUMMARY_H_
|
SPC-Some-Polish-Coders/PopHead | src/Terminal/terminal.cpp | <filename>src/Terminal/terminal.cpp
#include "pch.hpp"
#include "terminal.hpp"
#include "game.hpp"
#include "Scenes/sceneManager.hpp"
#include "ECS/System.hpp"
#include "ECS/Components/charactersComponents.hpp"
#include "ECS/Components/physicsComponents.hpp"
#include "ECS/Components/graphicsComponents.hpp"
#include "ECS/Components/itemComponents.hpp"
#include "ECS/Components/debugComponents.hpp"
#include "ECS/Systems/zombieSystem.hpp"
#include "ECS/Systems/hostileCollisions.hpp"
#include "ECS/entityUtil.hpp"
#include "Audio/musicPlayer.hpp"
#include "Audio/soundPlayer.hpp"
#include "Renderer/renderer.hpp"
#include "Renderer/API/font.hpp"
#include "GUI/xmlGuiParser.hpp"
#include "Utilities/cast.hpp"
namespace ph::Terminal {
static std::string content;
static std::deque<std::string> lastCommands;
static bool isVisible = false;
static sf::Window* window;
static ph::SceneManager* sceneManager;
static i32 indexOfCurrentLastCommand = -1;
static std::deque<ph::OutputLine> outputLines;
static const Vec2 vector2ArgumentError = {-1, -1};
typedef void (*ExecuteCommandFunction)(void);
static std::unordered_map<std::string, ExecuteCommandFunction> commandsMap;
static sf::Color errorRedColor = {255, 25, 33};
static sf::Color infoLimeColor = {127, 244, 44};
#ifndef PH_DISTRIBUTION
struct ResetGuiLive
{
float timeFromReset = 0.f;
float resetFrequency = 0.2f;
bool isActive = false;
};
static ResetGuiLive resetGuiLive;
#endif
static Vec2 handleGetVector2ArgumentError()
{
pushOutputLine({"Incorrect argument! Argument has to be a number.", errorRedColor});
return vector2ArgumentError;
}
static Vec2 getVector2Argument()
{
const std::string numbers("1234567890-");
if(content.find_first_of(numbers) == std::string::npos)
return handleGetVector2ArgumentError();
const size_t xArgumentPositionInCommand = content.find_first_of(numbers);
const size_t xArgumentEndPositionInCommand = content.find(' ', xArgumentPositionInCommand);
const size_t xArgumentLength = xArgumentEndPositionInCommand - xArgumentPositionInCommand;
std::string xArgument = content.substr(xArgumentPositionInCommand, xArgumentLength);
const float positionX = std::strtof(xArgument.c_str(), Null);
const size_t yArgumentPositionInCommand = content.find_first_of(numbers, xArgumentEndPositionInCommand + 1);
if(yArgumentPositionInCommand == std::string::npos)
return handleGetVector2ArgumentError();
const size_t yArgumentEndPositionInCommand = content.find_first_not_of(numbers, yArgumentPositionInCommand);
const size_t yArgumentLength = yArgumentEndPositionInCommand - yArgumentPositionInCommand;
const std::string yArgument = content.substr(yArgumentPositionInCommand, yArgumentLength);
const float positionY = std::strtof(yArgument.c_str(), Null);
return Vec2(positionX, positionY);
}
static float getSingleFloatArgument()
{
const size_t spacePosition = content.find_last_of(' ');
const size_t valueStartPos = spacePosition + 1;
const size_t valueLength = content.size() - valueStartPos;
const std::string value = content.substr(valueStartPos, valueLength);
return std::strtof(value.c_str(), Null);
}
static bool commandContains(const char c)
{
return content.find(c) != std::string::npos;
}
static bool commandContains(const char* c)
{
return content.find(c) != std::string::npos;
}
static void executeCommand()
{
// find command without arguments
size_t argumentPosition = content.find(' ');
if(argumentPosition == std::string::npos)
argumentPosition = content.size();
const std::string commandWithoutArguments = content.substr(0, argumentPosition);
// execute command
auto found = commandsMap.find(commandWithoutArguments);
if(found != commandsMap.end())
(*found->second)();
else
pushOutputLine({"Entered command wasn't recognised. Enter 'help' to see available commands.", sf::Color::Red});
}
static void executeInfoMessage()
{
pushOutputLine({"This is terminal. Enter 'help' to see available commands.", sf::Color(50, 50, 255)});
}
static void executeHistory()
{
auto& commandsHistory = lastCommands;
std::deque<std::string>::reverse_iterator it = commandsHistory.rbegin();
for(; it != commandsHistory.rend(); ++it)
pushOutputLine({"- " + *it, infoLimeColor});
pushOutputLine({"Ten last used commands: ", sf::Color::White});
}
static void executeHelp()
{
pushOutputLine({});
pushOutputLine({"fz @C9999 freeze zombies @CO @S31", infoLimeColor});
pushOutputLine({"history @C9999 show last commands @CO @S31 currentpos @C9999 output player's position @CO @S32 view @C9999 change player's camera size", infoLimeColor});
pushOutputLine({"give @C9999 player gets an item @CO @S31 tp @C9999 teleport @CO @S32 m @C9999 move player", infoLimeColor});
pushOutputLine({"setvolume @S31 mute @C9999 mute audio @CO @S32 unmute @C9999 unmute audio", infoLimeColor});
pushOutputLine({"gts @C9999 go to scene @CO @S31 r @C9999 reset scene @CO @S32 clear @C9999 clear terminal output", infoLimeColor});
pushOutputLine({"pause @C9999 pause game @CO @S31 rgui @C9999 reset gui @CO @S32 rguilive @C9999 reset gui all the time", infoLimeColor});
pushOutputLine({"rguilivefreq @C9999 set gui reset frequency", infoLimeColor});
pushOutputLine({"nofocusupdate @CO @S31 gm @C9999 god mode @CO @S32 pf @C9999 player flying", infoLimeColor});
pushOutputLine({"@C9509 TO LEARN MORE DETAILS ABOUT THE COMMAND USE @CO? @C9509 For example: @COgts ?", infoLimeColor});
}
static void executeGotoScene()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C2919 Example: @C9609 gts sewage@CO goes to sewage scene of file sewage.xml"});
pushOutputLine({"@C9609 gts@CO takes one argument which is name of the scene file without extension."});
}
else
{
size_t spacePosition = content.find_first_of(' ') + 1;
const std::string scenePath = "scenes/" + content.substr(spacePosition, content.size()) + ".xml";
sceneManager->replaceScene(scenePath);
}
}
static void executeReset()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C9609 r stay@CO reloads the current scene and spawns player in his current position."});
pushOutputLine({"@C9609 r@CO reloads the current scene."});
}
else
{
if(commandContains("stay"))
sceneManager->replaceScene(sceneManager->getCurrentSceneFilePath(), getPlayerPos());
else
sceneManager->replaceScene(sceneManager->getCurrentSceneFilePath());
}
}
static void executePause()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"More precisly it calls system::System::setPause(!commandContains(\"off\"))"});
pushOutputLine({"@C9609 pause off@CO Unpauses the game"});
pushOutputLine({"@C9609 pause@CO Pauses the game"});
}
else
{
system::System::setPause(!commandContains("off"));
}
}
static void executeResetGui()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C9609 rgui@CO reloads current scene gui from file, doesn't take arguments"});
}
else
{
size_t spacePosition = content.find_first_of(' ') + 1;
Xml sceneFile;
sceneFile.loadFromFile(sceneManager->getCurrentSceneFilePath());
const auto sceneLinksNode = *sceneFile.getChild("scenelinks");
if(const auto guiNode = sceneLinksNode.getChild("gui"))
{
const std::string filepath = "scenes/gui/" + guiNode->getAttribute("filename")->toString();
XmlGuiParser guiParser;
guiParser.parseGuiXml(filepath);
}
}
}
static void executeClear()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C9609clear@CO clears terminal output area, doesn't take arguments"});
}
else
{
for(i32 i = 0; i < 20; ++i)
pushOutputLine({""});
}
}
static void executeTeleportPoint()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C2919 Example: @C9609tp cave1"});
pushOutputLine({"@C2919 Example: @C9609tp start"});
pushOutputLine({"@C9609tp@CO teleports player to specified teleport point"});
}
else
{
size_t spacePosition = content.find_first_of(' ') + 1;
const std::string teleportPointName = content.substr(spacePosition, content.size());
auto& registry = sceneManager->getScene().getRegistry();
Vec2 newPos;
bool tpExists = false;
registry.view<component::TeleportPoint, component::BodyRect>().each([&]
(auto tp, auto body)
{
if(tp.name == teleportPointName)
{
newPos = body.pos;
tpExists = true;
}
});
if(tpExists)
{
auto& body = getPlayerBodyRef();
body.pos = newPos;
}
}
}
static void executeTeleport()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C2919 Example: @C9609tp 100"});
pushOutputLine({"@C2919 Example: @C9609tp -100 2000"});
pushOutputLine({"@C2919 Example: @C9609tp here"});
pushOutputLine({"It takes 1 parameter(a, a) or 2 parameters (x, y)"});
pushOutputLine({"If player is not on the scene it doesn't do anything"});
pushOutputLine({"@C9609tp@CO teleports player to absolute coordinate"});
pushOutputLine({"@C9609tp here@CO teleports player to current pos (in reality sets kind of teleportation point)"});
}
else
{
auto& playerBody = getPlayerBodyRef();
if(commandContains("here"))
{
auto herePos = content.find("here");
content.erase(herePos);
content += std::to_string(playerBody.x);
content += " ";
content += std::to_string(playerBody.y);
}
Vec2 newPosition = getVector2Argument();
if(newPosition == vector2ArgumentError)
return;
playerBody.pos = newPosition;
}
}
static void executeMove()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C2919 Example: @C9609m 100"});
pushOutputLine({"@C2919 Example: @C9609m -100 2000"});
pushOutputLine({"It takes 1 parameter(a, a) or 2 parameters (x, y)"});
pushOutputLine({"If player is not on the scene it doesn't do anything"});
pushOutputLine({"@C9609m@CO teleports player to relative coordinate"});
}
else
{
Vec2 moveOffset = getVector2Argument();
auto& body = getPlayerBodyRef();
body.pos += moveOffset;
}
}
static void executeGive()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C2919 Example: @C9609give bullet 100"});
pushOutputLine({"It takes 2 parameters (number of items, item name)"});
pushOutputLine({"@C9609give@CO puts given number of given item in player's inventory"});
}
else
{
if(commandContains("bullet"))
{
i32 numberOfItems = Cast<i32>(getSingleFloatArgument());
auto& registry = sceneManager->getScene().getRegistry();
registry.view<component::Player, component::Bullets>().each([numberOfItems]
(auto, auto& bullets)
{
bullets.numOfPistolBullets += numberOfItems;
bullets.numOfShotgunBullets += numberOfItems;
});
}
else
{
pushOutputLine({"Type of item is unknown!", errorRedColor});
}
}
}
static void executeCurrentPos()
{
if(commandContains('?'))
{
pushOutputLine({""});
pushOutputLine({"@C9609currentpos@CO Outputs player's position to terminal"});
}
else
{
pushOutputLine({"player position: " + castToString(getPlayerPos()), infoLimeColor});
}
}
static void setAudioMuted(bool mute)
{
if(commandContains("music"))
{
MusicPlayer::setVolume(mute ? 0.f : 50.f);
}
else if(commandContains("sound"))
{
SoundPlayer::setVolume(mute ? 0.f : 15.f);
}
else
{
MusicPlayer::setVolume(mute ? 0.f : 50.f);
SoundPlayer::setVolume(mute ? 0.f : 15.f);
}
}
static void executeMute()
{
if(commandContains('?'))
{
pushOutputLine({});
pushOutputLine({"@C9609mute sound @CO mutes only sound"});
pushOutputLine({"@C9609mute music @CO mutes only music"});
pushOutputLine({"@C9609mute @CO mutes audio"});
}
else
{
setAudioMuted(true);
}
}
static void executeUnmute()
{
if(commandContains('?'))
{
pushOutputLine({});
pushOutputLine({"@C9609unmute sound @CO unmutes only sound"});
pushOutputLine({"@C9609unmute music @CO unmutes only music"});
pushOutputLine({"@C9609unmute @CO unmutes audio"});
}
else
{
setAudioMuted(false);
}
}
static void executeSetVolume()
{
if(commandContains('?'))
{
pushOutputLine({});
pushOutputLine({"@C9609 setvolume sound @CO sets sound volume"});
pushOutputLine({"@C9609 setvolume music @CO sets music volume"});
pushOutputLine({"@C9609 setvolume @CO sets audio volume"});
}
else
{
const float newVolume = getSingleFloatArgument();
if(!(commandContains('0')) && newVolume == 0 || newVolume > 100)
{
pushOutputLine({"Incorrect volume value! Enter value from 0 to 100", sf::Color::Red});
return;
}
if(commandContains("music"))
{
MusicPlayer::setVolume(newVolume);
}
else if(commandContains("sound"))
{
SoundPlayer::setVolume(newVolume);
}
else
{
MusicPlayer::setVolume(newVolume);
SoundPlayer::setVolume(newVolume);
}
}
}
static void executeFontDebug()
{
if(commandContains('?'))
{
pushOutputLine({});
pushOutputLine({"@C9609 fontd off @CO disables font debug"});
pushOutputLine({"@C9609 fontd @CO enables font debug"});
}
else
{
if(commandContains("off") && FontDebugRenderer::isActive())
FontDebugRenderer::shutDown();
else if(!FontDebugRenderer::isActive())
FontDebugRenderer::init("joystixMonospace.ttf", 50);
}
}
static void executeNoFocusUpdate()
{
if(commandContains('?'))
{
pushOutputLine({});
pushOutputLine({"@C9609 nofocusupdate off@CO disables updating game if game's window doesn't have focus"});
pushOutputLine({"@C9609 nofocusupdate@CO enables updating game if game's window doesn't have focus"});
}
else
{
Game::setNoFocusUpdate(!commandContains("off"));
}
}
static void executeFreezeZombies()
{
system::ZombieSystem::freezeZombies = !commandContains("off");
}
static void executeGodMode()
{
system::HostileCollisions::godMode = !commandContains("off");
}
static void executePlayerFlying()
{
auto& registry = sceneManager->getScene().getRegistry();
auto playerEntity = getPlayerEntity();
if(playerEntity == entt::null)
return;
using namespace component;
if(commandContains("off"))
registry.assign_or_replace<KinematicCollisionBody>(playerEntity, 3.f);
else if(registry.has<KinematicCollisionBody>(playerEntity))
registry.remove<KinematicCollisionBody>(playerEntity);
}
#ifndef PH_DISTRIBUTION
static void executeResetGuiLive()
{
if(commandContains('?'))
{
pushOutputLine({});
pushOutputLine({"you can change rguilivefreq with @C9609 rguilivefreq @CO command"});
pushOutputLine({"@C9609 rguilive off@CO disables loading gui from file once for rguilivefreq seconds"});
pushOutputLine({"@C9609 rguilive@CO enables loading gui from file once for rguilivefreq seconds"});
}
else
{
resetGuiLive.isActive = !commandContains("off");
Game::setNoFocusUpdate(resetGuiLive.isActive);
}
}
static void executeResetGuiLiveFrequency()
{
if(commandContains('?'))
{
pushOutputLine({});
pushOutputLine({"@C2919 Example: @C9609 rguilivefreq 0.5@CO sets rguilive freq to 0.5 seconds"});
pushOutputLine({"@C9609 rguilivefreq@CO takes one floating point argument and sets rguilivefreq"});
}
else
{
resetGuiLive.resetFrequency = getSingleFloatArgument();
}
}
#endif
static void updateCommands(float dt)
{
#ifndef PH_DISTRIBUTION
if(resetGuiLive.isActive)
{
resetGuiLive.timeFromReset += dt;
if(resetGuiLive.timeFromReset > resetGuiLive.resetFrequency)
{
executeResetGui();
resetGuiLive.timeFromReset = 0.f;
}
}
#endif
}
void handleEvent(sf::Event e)
{
if(isVisible && e.type == sf::Event::TextEntered)
{
char key = Cast<char>(e.text.unicode);
if(!iscntrl(key))
content += key;
}
if(e.type == sf::Event::KeyPressed)
{
if(e.key.code == sf::Keyboard::Tab && e.key.control)
{
isVisible = !isVisible;
window->setKeyRepeatEnabled(isVisible);
system::System::setPause(isVisible);
}
if(!isVisible)
return;
switch(e.key.code)
{
case sf::Keyboard::BackSpace: {
if(content.size() > 0)
content.pop_back();
} break;
case sf::Keyboard::Enter: {
executeCommand();
indexOfCurrentLastCommand = -1;
if(content.size() != 0)
{
lastCommands.emplace_front(content);
if(lastCommands.size() > 10)
lastCommands.pop_back();
}
content.clear();
} break;
case sf::Keyboard::Up: {
if(indexOfCurrentLastCommand + 1 < Cast<i32>(lastCommands.size()))
{
++indexOfCurrentLastCommand;
if(indexOfCurrentLastCommand >= 0)
content = lastCommands[indexOfCurrentLastCommand];
}
} break;
case sf::Keyboard::Down: {
if(indexOfCurrentLastCommand > -1)
{
--indexOfCurrentLastCommand;
if(indexOfCurrentLastCommand == -1)
content.clear();
else
content = lastCommands[indexOfCurrentLastCommand];
}
} break;
}
}
}
void pushOutputLine(const OutputLine& line)
{
if(outputLines.size() >= 14)
outputLines.pop_back();
outputLines.emplace_front(line);
}
void init(sf::Window* w, SceneManager* sm)
{
window = w;
sceneManager = sm;
commandsMap["tp"] = &executeTeleport;
commandsMap["tpp"] = &executeTeleportPoint;
commandsMap["give"] = &executeGive;
commandsMap["currentpos"] = &executeCurrentPos;
commandsMap["mute"] = &executeMute;
commandsMap["unmute"] = &executeUnmute;
commandsMap["setvolume"] = &executeSetVolume;
commandsMap["history"] = &executeHistory;
commandsMap["help"] = &executeHelp;
commandsMap["clear"] = &executeClear;
commandsMap["gts"] = &executeGotoScene;
commandsMap["r"] = &executeReset;
commandsMap["pause"] = &executePause;
commandsMap["rgui"] = &executeResetGui;
commandsMap["m"] = &executeMove;
commandsMap["fontd"] = &executeFontDebug;
commandsMap["nofocusupdate"] = &executeNoFocusUpdate;
commandsMap["fz"] = &executeFreezeZombies;
commandsMap["gm"] = &executeGodMode;
commandsMap["pf"] = &executePlayerFlying;
commandsMap[""] = &executeInfoMessage;
#ifndef PH_DISTRIBUTION
commandsMap["rguilive"] = &executeResetGuiLive;
commandsMap["rguilivefreq"] = &executeResetGuiLiveFrequency;
#endif
// read terminalInit.txt file
std::ifstream file;
file.open("terminalInit.txt");
if(file.is_open())
{
while(!file.eof())
{
getline(file, content);
executeCommand();
}
file.close();
}
}
void update(float dt)
{
updateCommands(dt);
if(isVisible)
{
Renderer::submitQuad(Null, Null, &sf::Color(0, 0, 0, 230), Null, {0.f, 660.f}, {1920.f, 420.f}, 5, 0.f, {},
ProjectionType::gui, false);
Renderer::submitQuad(Null, Null, &sf::Color::Black, Null, {0.f, 720.f}, {1920.f, 5.f},
4, 0.f, {}, ProjectionType::gui, false);
Renderer::submitText(content.c_str(), "LiberationMono-Bold.ttf", {5.f, 660.f},
50.f, sf::Color::White, 0, ProjectionType::gui, false);
float posY = 723.f;
for(size_t i = 0; i < outputLines.size(); ++i, posY += 25.f)
Renderer::submitTextArea(outputLines[i].text.c_str(), "LiberationMono.ttf", {5.f, posY}, 1920.f, TextAligment::left,
25.f, outputLines[i].color, 0, ProjectionType::gui, false);
}
}
}
|
techyfatih/nuzlog | src/components/body/menu/options/CatchesModal.js | import React from 'react';
import { Modal, Button,
FormGroup, InputGroup, FormControl, ControlLabel } from 'react-bootstrap';
import { connect } from 'react-redux';
import StickyTable from 'components/other/StickyTable';
import PokeSlot from 'components/pokemon/slot/PokeSlot';
import { switchBox, switchSlot, failCatch } from 'actions';
class CatchesModal extends React.Component {
constructor() {
super();
this.state = {location: ''};
this.handleEnter = this.handleEnter.bind(this);
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleEnter() {
this.setState({location: ''});
this.input.focus();
}
handleClick(slot) {
const {onHide, onSwitchBox, onSwitchSlot} = this.props;
if (slot.party >= 0) {
onHide();
onSwitchBox(1);
onSwitchSlot(1, slot.party);
} else if (slot.pc >= 0) {
onHide();
onSwitchBox(2);
onSwitchSlot(2, slot.pc);
} else if (slot.cemetery >= 0) {
onHide();
onSwitchBox(3);
onSwitchSlot(3, slot.cemetery);
}
}
handleSubmit(e) {
this.props.onFailCatch(this.state.location);
this.setState({location: ''});
e.preventDefault();
}
render() {
const {location} = this.state;
return (
<Modal show={this.props.show}
onEnter={this.handleEnter} onHide={this.props.onHide}>
<Modal.Header closeButton><h2>Catches</h2></Modal.Header>
<Modal.Body>
<StickyTable>
<StickyTable.THead>
<tr>
<th width='50%'>Location</th>
<th width='50%'>Catch</th>
</tr>
</StickyTable.THead>
<StickyTable.TBody height='400px'>
{this.props.pokemon.map((pokemon, index) => {
//const slot = pokemon.slot;
return (
<tr key={index}>
<td width='50%'>{pokemon.location}</td>
<td width='50%'>
{pokemon.species ? /*(
<Button onClick={() => this.handleClick(slot)}>*/
<PokeSlot pokemon={pokemon} />
/*{slot ? (
slot.party >= 0 ?
'Party: ' + (parseInt(slot.party) + 1) :
slot.pc >= 0 ?
'PC: ' + (parseInt(slot.pc) + 1) :
slot.cemetery >= 0 ?
'Cemetery: ' + (parseInt(slot.cemetery) + 1) : ''
) : ''}
</Button>
)*/ : <span>Failed catch</span>}
</td>
</tr>
)
})}
</StickyTable.TBody>
</StickyTable>
<br />
<form onSubmit={this.handleSubmit}>
<FormGroup>
<ControlLabel>Record Failed Catch:</ControlLabel>
<InputGroup>
<FormControl placeholder='Enter location' value={location}
onChange={e => this.setState({location: e.target.value})}
inputRef={ref => this.input = ref} />
<InputGroup.Button>
<Button type='submit' bsStyle='danger' disabled={!location}>
Record
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
</form>
</Modal.Body>
</Modal>
);
}
}
const mapStateToProps = state => {
return {
pokemon: state.pokemon
};
};
const mapDispatchToProps = dispatch => {
return {
onSwitchBox: box => dispatch(switchBox(box)),
onSwitchSlot: (box, slot) => dispatch(switchSlot(box, slot)),
onFailCatch: location => dispatch(failCatch(location))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(CatchesModal); |
pritamkhose/PritamJava | src/JavaTpoint/Multithreading/TestMultitasking1.java | //Program of performing single task by multiple threads
package JavaTpoint.Multithreading;
public class TestMultitasking1 extends Thread{
public void run(){
System.out.println("task one");
}
public static void main(String args[]){
TestMultitasking1 t1=new TestMultitasking1();
TestMultitasking1 t2=new TestMultitasking1();
TestMultitasking1 t3=new TestMultitasking1();
t1.start();
t2.start();
t3.start();
}
} |
notion7171/seniorJob | seniorjob/src/main/java/com/company/resume/service/ResumeVO.java | package com.company.resume.service;
import org.springframework.web.multipart.MultipartFile;
import lombok.Data;
@Data
public class ResumeVO { //이력서필수
private String resume_no; //이력서번호
private String resume_name; //이름
private String resume_birth; //생년월일
private String resume_email; //이메일
private String resume_phone; //휴대폰번호
private String resume_address; //주소
private String resume_school; //학교명
private String resume_area; //지역
private String resume_start; //입학일
private String resume_end; //졸업일
private String id; //아이디
private String collection; //지도내용
private String image; //이미지
private MultipartFile uploadFile; //이미지 업로드
private String resume_title; //이력서 제목
private String resume_major; //전공
//양소민 추가
private String mentorId; //멘토아이디
}
|
PableteProgramming/download | extern/gtk/gdk/broadway/broadway-protocol.h | #ifndef __BROADWAY_PROTOCOL_H__
#define __BROADWAY_PROTOCOL_H__
#include <glib.h>
typedef struct {
gint32 x, y;
gint32 width, height;
} BroadwayRect;
typedef enum { /* Sync changes with broadway.js and node_type_is_container() */
BROADWAY_NODE_TEXTURE = 0,
BROADWAY_NODE_CONTAINER = 1,
BROADWAY_NODE_COLOR = 2,
BROADWAY_NODE_BORDER = 3,
BROADWAY_NODE_OUTSET_SHADOW = 4,
BROADWAY_NODE_INSET_SHADOW = 5,
BROADWAY_NODE_ROUNDED_CLIP = 6,
BROADWAY_NODE_LINEAR_GRADIENT = 7,
BROADWAY_NODE_SHADOW = 8,
BROADWAY_NODE_OPACITY = 9,
BROADWAY_NODE_CLIP = 10,
BROADWAY_NODE_TRANSFORM = 11,
BROADWAY_NODE_DEBUG = 12,
BROADWAY_NODE_REUSE = 13,
} BroadwayNodeType;
typedef enum { /* Sync changes with broadway.js */
BROADWAY_NODE_OP_INSERT_NODE = 0,
BROADWAY_NODE_OP_REMOVE_NODE = 1,
BROADWAY_NODE_OP_MOVE_AFTER_CHILD = 2,
BROADWAY_NODE_OP_PATCH_TEXTURE = 3,
BROADWAY_NODE_OP_PATCH_TRANSFORM = 4,
} BroadwayNodeOpType;
static const char *broadway_node_type_names[] G_GNUC_UNUSED = {
"TEXTURE",
"CONTAINER",
"COLOR",
"BORDER",
"OUTSET_SHADOW",
"INSET_SHADOW",
"ROUNDED_CLIP",
"LINEAR_GRADIENT",
"SHADOW",
"OPACITY",
"CLIP",
"TRANSFORM",
"DEBUG",
"REUSE",
};
typedef enum {
BROADWAY_EVENT_ENTER = 0,
BROADWAY_EVENT_LEAVE = 1,
BROADWAY_EVENT_POINTER_MOVE = 2,
BROADWAY_EVENT_BUTTON_PRESS = 3,
BROADWAY_EVENT_BUTTON_RELEASE = 4,
BROADWAY_EVENT_TOUCH = 5,
BROADWAY_EVENT_SCROLL = 6,
BROADWAY_EVENT_KEY_PRESS = 7,
BROADWAY_EVENT_KEY_RELEASE = 8,
BROADWAY_EVENT_GRAB_NOTIFY = 9,
BROADWAY_EVENT_UNGRAB_NOTIFY = 10,
BROADWAY_EVENT_CONFIGURE_NOTIFY = 11,
BROADWAY_EVENT_SCREEN_SIZE_CHANGED = 12,
BROADWAY_EVENT_FOCUS = 13,
BROADWAY_EVENT_ROUNDTRIP_NOTIFY = 14,
} BroadwayEventType;
typedef enum {
BROADWAY_OP_GRAB_POINTER = 0,
BROADWAY_OP_UNGRAB_POINTER = 1,
BROADWAY_OP_NEW_SURFACE = 2,
BROADWAY_OP_SHOW_SURFACE = 3,
BROADWAY_OP_HIDE_SURFACE = 4,
BROADWAY_OP_RAISE_SURFACE = 5,
BROADWAY_OP_LOWER_SURFACE = 6,
BROADWAY_OP_DESTROY_SURFACE = 7,
BROADWAY_OP_MOVE_RESIZE = 8,
BROADWAY_OP_SET_TRANSIENT_FOR = 9,
BROADWAY_OP_DISCONNECTED = 10,
BROADWAY_OP_SURFACE_UPDATE = 11,
BROADWAY_OP_SET_SHOW_KEYBOARD = 12,
BROADWAY_OP_UPLOAD_TEXTURE = 13,
BROADWAY_OP_RELEASE_TEXTURE = 14,
BROADWAY_OP_SET_NODES = 15,
BROADWAY_OP_ROUNDTRIP = 16,
} BroadwayOpType;
typedef struct {
guint32 type;
guint32 serial;
guint64 time;
} BroadwayInputBaseMsg;
typedef struct {
BroadwayInputBaseMsg base;
guint32 mouse_surface_id; /* The real surface, not taking grabs into account */
guint32 event_surface_id;
gint32 root_x;
gint32 root_y;
gint32 win_x;
gint32 win_y;
guint32 state;
} BroadwayInputPointerMsg;
typedef struct {
BroadwayInputPointerMsg pointer;
guint32 mode;
} BroadwayInputCrossingMsg;
typedef struct {
BroadwayInputPointerMsg pointer;
guint32 button;
} BroadwayInputButtonMsg;
typedef struct {
BroadwayInputPointerMsg pointer;
gint32 dir;
} BroadwayInputScrollMsg;
typedef struct {
BroadwayInputBaseMsg base;
guint32 touch_type;
guint32 event_surface_id;
guint32 sequence_id;
guint32 is_emulated;
gint32 root_x;
gint32 root_y;
gint32 win_x;
gint32 win_y;
guint32 state;
} BroadwayInputTouchMsg;
typedef struct {
BroadwayInputBaseMsg base;
guint32 surface_id;
guint32 state;
gint32 key;
} BroadwayInputKeyMsg;
typedef struct {
BroadwayInputBaseMsg base;
gint32 res;
} BroadwayInputGrabReply;
typedef struct {
BroadwayInputBaseMsg base;
gint32 id;
gint32 x;
gint32 y;
gint32 width;
gint32 height;
} BroadwayInputConfigureNotify;
typedef struct {
BroadwayInputBaseMsg base;
gint32 id;
guint32 tag;
guint32 local;
} BroadwayInputRoundtripNotify;
typedef struct {
BroadwayInputBaseMsg base;
guint32 width;
guint32 height;
guint32 scale;
} BroadwayInputScreenResizeNotify;
typedef struct {
BroadwayInputBaseMsg base;
gint32 id;
} BroadwayInputDeleteNotify;
typedef struct {
BroadwayInputBaseMsg base;
gint32 new_id;
gint32 old_id;
} BroadwayInputFocusMsg;
typedef union {
BroadwayInputBaseMsg base;
BroadwayInputPointerMsg pointer;
BroadwayInputCrossingMsg crossing;
BroadwayInputButtonMsg button;
BroadwayInputScrollMsg scroll;
BroadwayInputTouchMsg touch;
BroadwayInputKeyMsg key;
BroadwayInputGrabReply grab_reply;
BroadwayInputConfigureNotify configure_notify;
BroadwayInputRoundtripNotify roundtrip_notify;
BroadwayInputDeleteNotify delete_notify;
BroadwayInputScreenResizeNotify screen_resize_notify;
BroadwayInputFocusMsg focus;
} BroadwayInputMsg;
typedef enum {
BROADWAY_REQUEST_NEW_SURFACE,
BROADWAY_REQUEST_FLUSH,
BROADWAY_REQUEST_SYNC,
BROADWAY_REQUEST_QUERY_MOUSE,
BROADWAY_REQUEST_DESTROY_SURFACE,
BROADWAY_REQUEST_SHOW_SURFACE,
BROADWAY_REQUEST_HIDE_SURFACE,
BROADWAY_REQUEST_SET_TRANSIENT_FOR,
BROADWAY_REQUEST_MOVE_RESIZE,
BROADWAY_REQUEST_GRAB_POINTER,
BROADWAY_REQUEST_UNGRAB_POINTER,
BROADWAY_REQUEST_FOCUS_SURFACE,
BROADWAY_REQUEST_SET_SHOW_KEYBOARD,
BROADWAY_REQUEST_UPLOAD_TEXTURE,
BROADWAY_REQUEST_RELEASE_TEXTURE,
BROADWAY_REQUEST_SET_NODES,
BROADWAY_REQUEST_ROUNDTRIP,
} BroadwayRequestType;
typedef struct {
guint32 size;
guint32 serial;
guint32 type;
} BroadwayRequestBase, BroadwayRequestFlush, BroadwayRequestSync, BroadwayRequestQueryMouse;
typedef struct {
BroadwayRequestBase base;
guint32 id;
} BroadwayRequestDestroySurface, BroadwayRequestShowSurface, BroadwayRequestHideSurface, BroadwayRequestFocusSurface;
typedef struct {
BroadwayRequestBase base;
guint32 id;
guint32 tag;
} BroadwayRequestRoundtrip;
typedef struct {
BroadwayRequestBase base;
guint32 id;
guint32 parent;
} BroadwayRequestSetTransientFor;
typedef struct {
BroadwayRequestBase base;
guint32 id;
guint32 offset;
guint32 size;
} BroadwayRequestUploadTexture;
typedef struct {
BroadwayRequestBase base;
guint32 id;
} BroadwayRequestReleaseTexture;
typedef struct {
BroadwayRequestBase base;
guint32 id;
guint32 data[1];
} BroadwayRequestSetNodes;
typedef struct {
BroadwayRequestBase base;
guint32 id;
guint32 owner_events;
guint32 event_mask;
guint32 time_;
} BroadwayRequestGrabPointer;
typedef struct {
BroadwayRequestBase base;
guint32 time_;
} BroadwayRequestUngrabPointer;
typedef struct {
BroadwayRequestBase base;
gint32 x;
gint32 y;
guint32 width;
guint32 height;
} BroadwayRequestNewSurface;
typedef struct {
BroadwayRequestBase base;
guint32 id;
guint32 with_move;
gint32 x;
gint32 y;
guint32 width;
guint32 height;
} BroadwayRequestMoveResize;
typedef struct {
BroadwayRequestBase base;
guint32 show_keyboard;
} BroadwayRequestSetShowKeyboard;
typedef union {
BroadwayRequestBase base;
BroadwayRequestNewSurface new_surface;
BroadwayRequestFlush flush;
BroadwayRequestSync sync;
BroadwayRequestRoundtrip roundtrip;
BroadwayRequestQueryMouse query_mouse;
BroadwayRequestDestroySurface destroy_surface;
BroadwayRequestShowSurface show_surface;
BroadwayRequestHideSurface hide_surface;
BroadwayRequestSetTransientFor set_transient_for;
BroadwayRequestMoveResize move_resize;
BroadwayRequestGrabPointer grab_pointer;
BroadwayRequestUngrabPointer ungrab_pointer;
BroadwayRequestFocusSurface focus_surface;
BroadwayRequestSetShowKeyboard set_show_keyboard;
BroadwayRequestUploadTexture upload_texture;
BroadwayRequestReleaseTexture release_texture;
BroadwayRequestSetNodes set_nodes;
} BroadwayRequest;
typedef enum {
BROADWAY_REPLY_EVENT,
BROADWAY_REPLY_SYNC,
BROADWAY_REPLY_QUERY_MOUSE,
BROADWAY_REPLY_NEW_SURFACE,
BROADWAY_REPLY_GRAB_POINTER,
BROADWAY_REPLY_UNGRAB_POINTER
} BroadwayReplyType;
typedef struct {
guint32 size;
guint32 in_reply_to;
guint32 type;
} BroadwayReplyBase, BroadwayReplySync;
typedef struct {
BroadwayReplyBase base;
guint32 id;
} BroadwayReplyNewSurface;
typedef struct {
BroadwayReplyBase base;
guint32 status;
} BroadwayReplyGrabPointer, BroadwayReplyUngrabPointer;
typedef struct {
BroadwayReplyBase base;
guint32 surface;
gint32 root_x;
gint32 root_y;
guint32 mask;
} BroadwayReplyQueryMouse;
typedef struct {
BroadwayReplyBase base;
BroadwayInputMsg msg;
} BroadwayReplyEvent;
typedef union {
BroadwayReplyBase base;
BroadwayReplyEvent event;
BroadwayReplyQueryMouse query_mouse;
BroadwayReplyNewSurface new_surface;
BroadwayReplyGrabPointer grab_pointer;
BroadwayReplyUngrabPointer ungrab_pointer;
} BroadwayReply;
#endif /* __BROADWAY_PROTOCOL_H__ */
|
clienthax/Deobfuscator | deps/jode/obfuscator/modules/MultiIdentifierMatcher.java | <filename>deps/jode/obfuscator/modules/MultiIdentifierMatcher.java
/* MultiIdentifierMatcher Copyright (C) 1999-2002 <NAME>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: MultiIdentifierMatcher.java.in,v 1.1.2.2 2002/05/28 17:34:17 hoenicke Exp $
*/
package jode.obfuscator.modules;
import java.util.Collection;
import jode.obfuscator.Identifier;
import jode.obfuscator.IdentifierMatcher;
import jode.obfuscator.OptionHandler;
public class MultiIdentifierMatcher implements IdentifierMatcher, OptionHandler {
/**
* Useful constant for giving to the constructor.
*/
public static boolean OR = true;
/**
* Useful constant for giving to the constructor.
*/
public static boolean AND = false;
IdentifierMatcher[] matchers;
boolean isOr;
/**
* Create an empty MultiIdentifierMatcher.
*/
public MultiIdentifierMatcher() {
this.matchers = new IdentifierMatcher[0];
}
/**
* Create an IdentifierMatcher out of other matchers.
*
* @param isOr
* if true, match should return the logical (shortcut) or of the
* underlying matchers, if false it returns the logical and.
* @param matchers
* the underlying matchers
*/
public MultiIdentifierMatcher(boolean isOr, IdentifierMatcher[] matchers) {
this.isOr = isOr;
this.matchers = matchers;
}
public void setOption(String option, Collection values) {
if (option.equals("or")) {
isOr = true;
matchers = (IdentifierMatcher[]) values
.toArray(new IdentifierMatcher[values.size()]);
} else if (option.equals("and")) {
isOr = false;
matchers = (IdentifierMatcher[]) values
.toArray(new IdentifierMatcher[values.size()]);
} else
throw new IllegalArgumentException("Invalid option `" + option
+ "'.");
}
public boolean matches(Identifier ident) {
for (int i = 0; i < matchers.length; i++) {
if (matchers[i].matches(ident) == isOr)
return isOr;
}
return !isOr;
}
public boolean matchesSub(Identifier ident, String name) {
for (int i = 0; i < matchers.length; i++) {
if (matchers[i].matchesSub(ident, name) == isOr)
return isOr;
}
return !isOr;
}
public String getNextComponent(Identifier ident) {
if (isOr == AND) {
for (int i = 0; i < matchers.length; i++) {
String next = matchers[i].getNextComponent(ident);
if (next != null && matchesSub(ident, next))
return next;
}
return null;
}
// OR case
String next = null;
for (int i = 0; i < matchers.length; i++) {
if (!matchesSub(ident, null))
continue;
if (next != null
&& !matchers[i].getNextComponent(ident).equals(next))
return null;
next = matchers[i].getNextComponent(ident);
if (next == null)
return null;
}
return next;
}
}
|
18862241347/BaseTest | BaseTest/Commons/XLNotificationConstant.h | //
// XLNotificationConstant.h
// LoveBaby
//
// Created by 蒋玉顺 on 15/8/3.
// Copyright (c) 2015年 YeGuo. All rights reserved.
//
#import <Foundation/NSString.h>
// 登录用户退出登录,切换到登录页面
UIKIT_EXTERN NSString *SWITCH_TO_LOGINVC;
// TabBar切换界面
UIKIT_EXTERN NSString *TABBAR_SELECTVC;
// 推送通知跳转页面
UIKIT_EXTERN NSString *NOTIFICATION_JPush_Jump;
// 获取购物车数量
UIKIT_EXTERN NSString *NOTIFICATION_CARTNUM;
|
Skycelot/plicanterra | sources/client-service/src/main/java/ru/skycelot/plicanterra/rest/core/SearchResultWriter.java | package ru.skycelot.plicanterra.rest.core;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import ru.skycelot.plicanterra.crud.transfer.search.SearchResult;
/**
*
*/
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class SearchResultWriter implements MessageBodyWriter<SearchResult> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type == SearchResult.class && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
}
@Override
public long getSize(SearchResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return convertToJson(t).length();
}
@Override
public void writeTo(SearchResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
entityStream.write(convertToJson(t).getBytes("UTF8"));
}
private String convertToJson(SearchResult instance) {
try {
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
String result = writer.writeValueAsString(instance);
return result;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
DeFBeD/zap-android | app/src/main/java/DefBed/DefWallet/lnd/RemoteLndWatchtowerService.java | <filename>app/src/main/java/DefBed/DefWallet/lnd/RemoteLndWatchtowerService.java
package DefBed.DefWallet.lnd;
import com.github.lightningnetwork.lnd.watchtowerrpc.WatchtowerGrpc;
import io.grpc.CallCredentials;
import io.grpc.Channel;
import io.reactivex.rxjava3.core.Single;
public class RemoteLndWatchtowerService implements LndWatchtowerService {
private WatchtowerGrpc.WatchtowerStub asyncStub;
public RemoteLndWatchtowerService(Channel channel, CallCredentials callCredentials) {
asyncStub = WatchtowerGrpc.newStub(channel).withCallCredentials(callCredentials);
}
@Override
public Single<com.github.lightningnetwork.lnd.watchtowerrpc.GetInfoResponse> getInfo(com.github.lightningnetwork.lnd.watchtowerrpc.GetInfoRequest request) {
return DefaultSingle.createDefault(emitter -> asyncStub.getInfo(request, new RemoteLndSingleObserver<>(emitter)));
}
} |
sasa-fajkovic/invoice-sequence | src/main/java/com/example/invoice/dto/UserDTO.java | package com.example.invoice.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UserDTO {
private Long id;
private String username;
private Boolean isActive;
}
|
RommelTJ/RockJVMScalaExercises-beginners | src/lectures/part3fp/MapFlatmapFilterFor.scala | package lectures.part3fp
object MapFlatmapFilterFor extends App {
// Scala List.
val list = List(1, 2, 3)
println(list)
println(list.head)
println(list.tail)
// Map
println(list.map(_ + 1))
println(list.map(_ + " is a number"))
// Filter
println(list.filter(_ % 2 == 0))
// Flatmap
val toPair = (x: Int) => List(x, x + 1)
println(list)
println(toPair)
println(list.flatMap(toPair))
// Print all combinations between two lists
val numbers = List(1, 2, 3, 4)
val characters = List('a', 'b', 'c', 'd')
val colors = List("Black", "White")
// "Iterating" in Scala.
val combinations = numbers.flatMap(n => characters.flatMap(c => colors.map(color => s"$c$n$color")))
println(combinations)
// Foreach
list.foreach(println)
// for-comprehensions (easier to read)
val forCombinations = for {
n <- numbers if n % 2 == 0 // Guard, aka a filter
c <- characters
color <- colors
} yield s"$c$n$color"
println(forCombinations)
// For-comprehension with side-effect (equivalent to foreach here)
for {
n <- numbers
} println(n)
// Syntax overload
list.map { x =>
x * 2
}
println(list)
}
|
DDoS/Golite | programs/invalid/syntax/MultiPck.go | // More than one packages
package main
package mains
func main() {
}
|
gmingchen/java-im | slipper-service/src/main/java/com/slipper/service/conversation/dto/ConversationDto.java | <reponame>gmingchen/java-im<gh_stars>1-10
package com.slipper.service.conversation.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.slipper.service.message.dto.PrivateMessageDto;
import com.slipper.service.user.dto.UserBasicDto;
import lombok.Data;
import java.util.Date;
/**
* 聊天会话DTO
*
* @author gumingchen
* @email <EMAIL>
* @date 1995-08-30 00:00:00
*/
@Data
public class ConversationDto {
private Long id;
/**
* 发送者
*/
private UserBasicDto from;
/**
* 接收者
*/
private UserBasicDto to;;
/**
* 消息
*/
private PrivateMessageDto message;
/**
* 类型:1-私聊 2-群聊
*/
private Integer type;
/**
* 未读数量
*/
@JsonProperty("unread_count")
private Integer unreadCount;
/**
* 创建时间
*/
@JsonProperty("created_at")
private Date createdAt;
}
|
arthurdysart/LeetCode | 0088_merge_sorted_array/python_source.py | # -*- coding: utf-8 -*-
"""
Leetcode - Merge Sorted Array
https://leetcode.com/problems/merge-sorted-array/
Created on Mon Jan 14 14:05:13 2019
@author: <NAME>
"""
# REQUIRED MODULES
import json
import sys
# FUNCTION DEFINITIONS
class Solution:
"""
Iterative traversal of first input array.
Time complexity: O(n + m)
- Amortized traverse first and second list elements
Space complexity: O(1)
- Update first array in-place
"""
def merge_sort_arr(self, a, m, b, n):
"""
Combines and sorts elements from both input arrays in-place.
:param list[int] a: first array of integer values
:param int m: number of elements in first array
:param list[int] b: second array of integer values
:param int n: number of elements in second array
:return: None
:rtype: None
"""
if not b:
return None
while (m > 0 and
n > 0):
# Iterate while remaining indicies in both arrays
if a[m - 1] < b[n - 1]:
# Insert target value and shifted values into first array
a[m:] = [b[n - 1]] + a[m:-1]
# Decrement counter for first array
n -= 1
else:
# Decrement counter for second array
m -= 1
if n > 0:
# Insert remaining elements before first array elements
a[:] = b[:n] + a[:-n]
return None
class Solution1:
"""
Iterative traversal of first input array.
Time complexity: O(n + m)
- Amortized traverse first and second list elements
Space complexity: O(1)
- Update first array in-place
"""
def merge_sort_arr(self, a, m, b, n):
"""
Combines and sorts elements from both input arrays in-place.
:param list[int] a: first array of integer values
:param int m: number of elements in first array
:param list[int] b: second array of integer values
:param int n: number of elements in second array
:return: None
:rtype: None
"""
if not b:
return None
i = 0
j = 0
while m > 0 and n > 0:
if a[i] > b[j]:
# Insert target element into first array
self.insert_shift_arr(i, j, a, b)
# Update index pointer and counter for second array
j += 1
n -= 1
else:
# Update counter for first array
m -= 1
# Increment index pointer for first array
i += 1
while n > 0:
# Insert target element into first array
a[i] = b[j]
# Update counter for second array
n -= 1
# Increment index pointers for both arrays
i += 1
j += 1
return None
def insert_shift_arr(self, i, j, a, b):
"""
Combines and sorts elements from both input arrays in-place.
:param int i: target index in first array
:param int j: target index in second array
:param list[int] a: first array of integer values
:param list[int] b: second array of integer values
:return: None
:rtype: None
"""
p = b[j]
for x in range(i, len(a), 1):
a[x], p = p, a[x]
return None
class Input:
def stdin(self, sys_stdin):
"""
Imports standard input.
:param _io.TextIOWrapper sys_stdin: standard input
:return: input arrays and their number of elements
:rtype: list[int], int, list[int], int
"""
return [json.loads(x)
for x
in sys_stdin]
## MAIN MODULE
if __name__ == "__main__":
# Imports standard input
a, m, b, n = Input()\
.stdin(sys.stdin)
# Evaluates solution
Solution()\
.merge_sort_arr(a, m, b, n)
print(json.dumps(a))
## END OF FILE |
Ricoshallow/DolphinWeb | server/web/js/subConns.js | $(document).ready(function () {
bindGrid()
});
var bindGrid = function () {
var nodeUrl = GetFullUrl(window.location.host);
var controller = new ControllerServer(nodeUrl);
var subConnsRes = controller.runSync("pnodeRun(def(){return getStreamingStat().subConns})");
if (subConnsRes.resultCode === "1") {
alert(subConnsRes.msg);
} else {
var valueList = subConnsRes.object[0].value;
var ent = []
console.log(subConnsRes);
for (var j = 0; j < valueList[0].value.length; j++) {
var obj = {}
for (var i = 0, len = valueList.length; i < len; i++) {
obj[valueList[i].name] = valueList[i].value[j]
}
ent.push(obj)
}
// console.log(ent);
$(`#dataTable`).jsGrid({
width: "98%",
// height: "400px",
data: ent,
resize: true,
fields: [{
name: "publisher",
type: "text",
width: 80,
align: "center",
itemTemplate: function (value, item) {
// console.log(item);
return `<p>${item.publisher}</p>`
}
},
{
name: "cumMsgCount",
type: "text",
width: 80,
align: "center",
itemTemplate: function (value, item) {
// console.log(item);
return `<p>${item.cumMsgCount}</p>`
}
},
{
name: "cumMsgLatency",
type: "text",
width: 80,
align: "center",
itemTemplate: function (value, item) {
// console.log(item);
return `<p>${item.cumMsgLatency}</p>`
}
},
{
name: "lastMsgLatency",
type: "text",
width: 80,
align: "center",
itemTemplate: function (value, item) {
// console.log(item);
return `<p>${item.lastMsgLatency}</p>`
}
},
{
name: "lastUpdate",
type: "text",
width: 80,
align: "center",
itemTemplate: function (value, item) {
// console.log(item);
return `<p>${item.lastUpdate}</p>`
}
},
{
name: "node",
type: "text",
width: 50,
align: "center",
itemTemplate: function (value, item) {
// console.log(item);
return `<p>${item.node}</p>`
}
},
]
})
}
} |
Cine-Master/backend | project/src/main/java/com/cinemaster/backend/data/entity/Seat.java | package com.cinemaster.backend.data.entity;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "seat")
public class Seat {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "seat_row")
private String row;
@Column(name = "seat_column")
private String column;
@Column(name = "seat_type")
@Enumerated(EnumType.STRING)
private Type seatType;
@ManyToOne
private Room room;
@OneToMany(mappedBy = "seat")
private List<Booking> bookings;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRow() {
return row;
}
public void setRow(String row) {
this.row = row;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public Type getSeatType() {
return seatType;
}
public void setSeatType(Type seatType) {
this.seatType = seatType;
}
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
public List<Booking> getBookings() {
return bookings;
}
public void setBookings(List<Booking> bookings) {
this.bookings = bookings;
}
public enum Type {STANDARD, PREMIUM, VIP}
}
|
Mattlk13/innoextract-android | Service/jni/libiconv-1.13.1/lib/canonical_local.h | (int)(long)&((struct stringpool_t *)0)->stringpool_str271,
(int)(long)&((struct stringpool_t *)0)->stringpool_str664,
|
beeminder-capstone/Nectar | db/migrate/20160519212602_add_password_to_credential.rb | =begin
* Created by PSU Beeminder Capstone Team on 3/12/2017.
* Copyright (c) 2017 PSU Beeminder Capstone Team
* This code is available under the "MIT License".
* Please see the file LICENSE in this distribution for license terms.
=end
class AddPasswordToCredential < ActiveRecord::Migration[5.0]
def change
add_column :credentials, :password, :string, null: false, default: ""
end
end
|
mythoss/midpoint | gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/page/admin/task/component/TaskEnvironmentalPerformancePanel.java | /*
* Copyright (C) 2021 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.gui.impl.page.admin.task.component;
import com.evolveum.midpoint.gui.impl.page.admin.AbstractObjectMainPanel;
import com.evolveum.midpoint.gui.impl.page.admin.ObjectDetailsModels;
import com.evolveum.midpoint.gui.impl.page.admin.task.TaskDetailsModel;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.application.PanelDisplay;
import com.evolveum.midpoint.web.application.PanelInstance;
import com.evolveum.midpoint.web.application.PanelType;
import com.evolveum.midpoint.web.component.progress.StatisticsDtoModel;
import com.evolveum.midpoint.web.component.progress.StatisticsPanel;
import com.evolveum.midpoint.web.page.admin.server.RefreshableTabPanel;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ContainerPanelConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType;
import org.apache.wicket.Component;
import java.util.Collection;
import java.util.Collections;
/**
* @author semancik
*/
@PanelType(name = "environmentalPerformance")
@PanelInstance(identifier = "environmentalPerformance", applicableForType = TaskType.class, childOf = TaskPerformancePanel.class,
display = @PanelDisplay(label = "pageTask.environmentalPerformance.title", order = 50))
public class TaskEnvironmentalPerformancePanel extends AbstractObjectMainPanel<TaskType, TaskDetailsModel> implements RefreshableTabPanel {
private static final long serialVersionUID = 1L;
private static final String ID_STATISTICS_PANEL = "statisticsPanel";
private static final Trace LOGGER = TraceManager.getTrace(TaskEnvironmentalPerformancePanel.class);
public TaskEnvironmentalPerformancePanel(String id, TaskDetailsModel taskWrapperModel, ContainerPanelConfigurationType config) {
super(id, taskWrapperModel, config);
setOutputMarkupId(true);
}
protected void initLayout() {
StatisticsDtoModel statisticsDtoModel = new StatisticsDtoModel(getObjectWrapperModel());
StatisticsPanel statisticsPanel = new StatisticsPanel(ID_STATISTICS_PANEL, statisticsDtoModel);
add(statisticsPanel);
}
@Override
public Collection<Component> getComponentsToUpdate() {
return Collections.<Component>singleton(this);
}
}
|
thewonderidiot/lachesis | firmware/lachesis/src/crc.h | #ifndef _CRC_H_
#define _CRC_H_
#include "xil_types.h"
uint8_t crc8(uint8_t crc, uint8_t *data, uint32_t length);
#endif//_CRC_H_
|
Skretzo/MonteMedia | src/org.monte.demo.screenrecorder/org/monte/demo/screenrecorder/CommandlineRecorderMain.java | <reponame>Skretzo/MonteMedia<filename>src/org.monte.demo.screenrecorder/org/monte/demo/screenrecorder/CommandlineRecorderMain.java
/* @(#)CommandlineRecorderMain.java
* Copyright © 2017 <NAME>, Switzerland. MIT License.
*/
package org.monte.demo.screenrecorder;
import org.monte.media.screenrecorder.ScreenRecorder;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
/**
* {@code CommandlineRecorderMain}.
*
* @author <NAME>
* @version $Id$
*/
public class CommandlineRecorderMain {
/**
* FIXME - Add commandline arguments for recording time.
*
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
GraphicsConfiguration gc = GraphicsEnvironment//
.getLocalGraphicsEnvironment()//
.getDefaultScreenDevice()//
.getDefaultConfiguration();
// FIXME - Implement me
ScreenRecorder sr = new ScreenRecorder(
gc/*,
"QuickTime", 24,
ScreenRecorder.CursorEnum.BLACK,
30, 15,
44100*/);
sr.start();
Thread.sleep(5000);
sr.stop();
}
}
|
ds201891/choco-solver | solver/src/main/java/org/chocosolver/solver/constraints/nary/automata/structure/regular/StoredDirectedMultiGraph.java | /*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2020, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver.constraints.nary.automata.structure.regular;
import gnu.trove.set.hash.TIntHashSet;
import gnu.trove.stack.TIntStack;
import gnu.trove.stack.array.TIntArrayStack;
import org.chocosolver.memory.IEnvironment;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.nary.automata.structure.Node;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.util.iterators.DisposableIntIterator;
import org.chocosolver.util.objects.StoredIndexedBipartiteSet;
import org.chocosolver.util.objects.StoredIndexedBipartiteSetWithOffset;
import org.jgrapht.graph.DirectedMultigraph;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: julien
* Mail: julien.menana{at}emn.fr
* Date: Nov 4, 2009
* Time: 1:07:19 PM
*/
public class StoredDirectedMultiGraph {
private int[] starts;
private int[] offsets;
private TIntStack stack = new TIntArrayStack();
private StoredIndexedBipartiteSetWithOffset[] supports;
private class Nodes {
private int[] states;
private int[] layers;
private StoredIndexedBipartiteSetWithOffset[] outArcs;
private StoredIndexedBipartiteSetWithOffset[] inArcs;
}
private class Arcs {
private int[] values;
private int[] dests;
private int[] origs;
}
private Nodes GNodes;
private Arcs GArcs;
public StoredDirectedMultiGraph(IEnvironment environment, DirectedMultigraph<Node, Arc> graph,
int[] starts, int[] offsets, int supportLength) {
this.starts = starts;
this.offsets = offsets;
this.GNodes = new Nodes();
this.GArcs = new Arcs();
TIntHashSet[] sups = new TIntHashSet[supportLength];
this.supports = new StoredIndexedBipartiteSetWithOffset[supportLength];
Set<Arc> arcs = graph.edgeSet();
GArcs.values = new int[arcs.size()];
GArcs.dests = new int[arcs.size()];
GArcs.origs = new int[arcs.size()];
for (Arc a : arcs) {
GArcs.values[a.id] = a.value;
GArcs.dests[a.id] = a.dest.id;
GArcs.origs[a.id] = a.orig.id;
int idx = starts[a.orig.layer] + a.value - offsets[a.orig.layer];
if (sups[idx] == null)
sups[idx] = new TIntHashSet();
sups[idx].add(a.id);
}
for (int i = 0; i < sups.length; i++) {
if (sups[i] != null)
supports[i] = new StoredIndexedBipartiteSetWithOffset(environment, sups[i].toArray());
}
Set<Node> nodes = graph.vertexSet();
GNodes.outArcs = new StoredIndexedBipartiteSetWithOffset[nodes.size()];
GNodes.inArcs = new StoredIndexedBipartiteSetWithOffset[nodes.size()];
GNodes.layers = new int[nodes.size()];
GNodes.states = new int[nodes.size()];
for (Node n : nodes) {
GNodes.layers[n.id] = n.layer;
GNodes.states[n.id] = n.state;
int i;
Set<Arc> outarc = graph.outgoingEdgesOf(n);
if (!outarc.isEmpty()) {
int[] out = new int[outarc.size()];
i = 0;
for (Arc a : outarc) {
out[i++] = a.id;
}
GNodes.outArcs[n.id] = new StoredIndexedBipartiteSetWithOffset(environment, out);
}
Set<Arc> inarc = graph.incomingEdgesOf(n);
if (!inarc.isEmpty()) {
int[] in = new int[inarc.size()];
i = 0;
for (Arc a : inarc) {
in[i++] = a.id;
}
GNodes.inArcs[n.id] = new StoredIndexedBipartiteSetWithOffset(environment, in);
}
}
}
//***********************************************************************************
// EXTERNAL METHODS
//***********************************************************************************
public boolean hasSupport(int i, int j) {
StoredIndexedBipartiteSetWithOffset sup = getSupport(i,j);
return sup != null && !sup.isEmpty();
}
public void clearSupports(int idxVar, int val, Propagator<IntVar> p) throws ContradictionException {
clearSupports(getSupport(idxVar, val), p);
}
//***********************************************************************************
// INTERNAL METHODS
//***********************************************************************************
private int getIdx(int i, int j) {
return starts[i] + j - offsets[i];
}
protected final StoredIndexedBipartiteSetWithOffset getSupport(int i, int j) {
return supports[getIdx(i, j)];
}
private void removeArc(Propagator<IntVar> propagator) throws ContradictionException {
while (stack.size() > 0) {
int arcId = stack.pop();
int orig = GArcs.origs[arcId];
int dest = GArcs.dests[arcId];
int layer = GNodes.layers[orig];
int value = GArcs.values[arcId];
StoredIndexedBipartiteSetWithOffset support = getSupport(layer, value);
support.remove(arcId);
if (support.isEmpty()) {
IntVar var = propagator.getVar(layer);
try {
var.removeValue(value, propagator);
} catch (ContradictionException ex) {
stack.clear();
throw ex;
}
}
DisposableIntIterator it;
StoredIndexedBipartiteSetWithOffset out = GNodes.outArcs[orig];
StoredIndexedBipartiteSetWithOffset in;
out.remove(arcId);
if (GNodes.layers[orig] > 0 && out.isEmpty()) {
in = GNodes.inArcs[orig];
if (in != null) {
it = in.getIterator();
while (it.hasNext()) {
int id = it.next();
stack.push(id);
}
it.dispose();
}
}
in = GNodes.inArcs[dest];
in.remove(arcId);
if (GNodes.layers[dest] < propagator.getNbVars() && in.isEmpty()) {
out = GNodes.outArcs[dest];
if (out != null) {
it = out.getIterator();
while (it.hasNext()) {
int id = it.next();
stack.push(id);
}
it.dispose();
}
}
}
}
private void clearSupports(StoredIndexedBipartiteSet supports, Propagator<IntVar> p) throws ContradictionException {
if (supports != null) {
DisposableIntIterator it = supports.getIterator();
while (it.hasNext()) {
int arcId = it.next();
stack.push(arcId);
}
it.dispose();
removeArc(p);
}
}
@Override
public String toString() {
StringBuilder st = new StringBuilder();
int nb = 0;
for (int i = 0; i < supports.length; i++) {
if (supports[i] != null && !supports[i].isEmpty()) {
nb++;
}
}
st.append("nb: ").append(nb).append("\n");
for (int i = 0; i < supports.length; i++) {
if (supports[i] != null && !supports[i].isEmpty()) {
DisposableIntIterator it = supports[i].getIterator();
while (it.hasNext()) {
int arcId = it.next();
st.append(arcId).append(",");
}
it.dispose();
st.append("\n");
}
}
return st.toString();
}
}
|
solution9th/S3Adapter | internal/to/to.go | <filename>internal/to/to.go
package to
import (
"bytes"
"context"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
)
var errValueNotSet = fmt.Errorf("value not set")
// UnmarshalRequest unmarshals the REST request to struct
func UnmarshalRequest(ctx context.Context, r *http.Request, v interface{}) (string, error) {
v1 := reflect.Indirect(reflect.ValueOf(v))
return unmarshal(ctx, r, v1)
}
func unmarshal(ctx context.Context, r *http.Request, v reflect.Value) (string, error) {
for i := 0; i < v.NumField(); i++ {
var err error
m, field := v.Field(i), v.Type().Field(i)
if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) {
continue
}
if !m.IsValid() {
continue
}
name := field.Tag.Get("locationName")
if name == "" {
name = field.Name
}
switch field.Tag.Get("location") {
case "header":
err = unmarshalHeader(ctx, m, r.Header.Get(name), field.Tag)
if err != nil {
return field.Name, err
}
case "headers":
prefix := field.Tag.Get("locationName")
err = unmarshalHeaderMap(ctx, m, r.Header, prefix)
if err != nil {
return field.Name, err
}
case "querystring":
err = unmarshalQuery(ctx, m, r.URL.Query().Get(name), field.Tag)
if err != nil {
return field.Name, err
}
}
}
return "", unmarshalBody(ctx, r, v)
}
// MarshalResponse marshal struct to REST response
func MarshalResponse(ctx context.Context, w http.ResponseWriter, v interface{}) error {
v1 := reflect.Indirect(reflect.ValueOf(v))
return marshal(ctx, w, v1)
}
func marshal(ctx context.Context, w http.ResponseWriter, v reflect.Value) error {
if !v.CanAddr() {
return nil
}
for i := 0; i < v.NumField(); i++ {
m, field := v.Field(i), v.Type().Field(i)
if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) {
continue
}
if (m.Kind() != reflect.Struct && m.IsNil()) || !m.IsValid() {
continue
}
name := field.Tag.Get("locationName")
if name == "" {
name = field.Name
}
switch field.Tag.Get("location") {
case "header":
err := marshalHeader(ctx, w.Header(), m, name, field.Tag)
if err != nil {
return err
}
case "headers":
err := marshalHeaderMap(ctx, m, w.Header(), field.Tag)
if err != nil {
return err
}
}
}
return marshalBody(ctx, w, v)
}
func marshalBody(ctx context.Context, w http.ResponseWriter, v reflect.Value) error {
field, ok := v.Type().FieldByName("_")
if !ok {
return nil
}
payloadName := field.Tag.Get("payload")
if payloadName == "" {
return nil
}
pfield, _ := v.Type().FieldByName(payloadName)
ptag := pfield.Tag.Get("type")
payload := reflect.Indirect(v.FieldByName(payloadName))
if !payload.IsValid() || payload.Interface() == nil {
return nil
}
if ptag == "" || ptag == "structure" {
var buf bytes.Buffer
buf.WriteString(xml.Header)
err := xmlutil.BuildXML(payload.Interface(), xml.NewEncoder(&buf))
if err != nil {
return err
}
w.Write(buf.Bytes())
return nil
}
switch reader := payload.Interface().(type) {
case io.ReadSeeker:
data, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
w.Write(data)
case io.ReadCloser:
data, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
w.Write(data)
case []byte:
w.Write(reader)
case string:
w.Write([]byte(reader))
default:
return fmt.Errorf("unknown payload type %s", payload.Type())
}
return nil
}
func marshalHeader(ctx context.Context, h http.Header, v reflect.Value, headerName string, tag reflect.StructTag) error {
str, err := convertType(v, tag)
if err == errValueNotSet {
return nil
} else if err != nil {
return err
}
headerName = strings.TrimSpace(headerName)
str = strings.TrimSpace(str)
h.Add(headerName, str)
return nil
}
func marshalHeaderMap(ctx context.Context, v reflect.Value, header http.Header, tag reflect.StructTag) error {
prefix := tag.Get("locationName")
for _, key := range v.MapKeys() {
str, err := convertType(v.MapIndex(key), tag)
if err == errValueNotSet {
continue
} else if err != nil {
return err
}
keyStr := strings.TrimSpace(key.String())
str = strings.TrimSpace(str)
header.Add(prefix+keyStr, str)
}
return nil
}
func unmarshalHeaderMap(ctx context.Context, v reflect.Value, headers http.Header, prefix string) error {
switch v.Interface().(type) {
case map[string]*string:
out := map[string]*string{}
for k, v := range headers {
k = http.CanonicalHeaderKey(k)
if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) {
out[k[len(prefix):]] = &v[0]
}
}
v.Set(reflect.ValueOf(out))
}
return nil
}
// when has => _ struct{} `type:"structure" payload:"LegalHold"`
func unmarshalBody(ctx context.Context, r *http.Request, v reflect.Value) error {
field, ok := v.Type().FieldByName("_")
if !ok {
return nil
}
payloadName := field.Tag.Get("payload")
if payloadName == "" {
return nil
}
pfield, _ := v.Type().FieldByName(payloadName)
ptag := pfield.Tag.Get("type")
// 嵌入 struct 暂不解决
if ptag == "" || ptag == "structure" {
return nil
}
payload := v.FieldByName(payloadName)
if !payload.IsValid() {
return nil
}
switch payload.Interface().(type) {
case []byte:
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
payload.Set(reflect.ValueOf(b))
case *string:
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
str := string(b)
payload.Set(reflect.ValueOf(&str))
default:
switch payload.Type().String() {
case "io.ReadCloser":
payload.Set(reflect.ValueOf(r.Body))
case "io.ReadSeeker":
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
payload.Set(reflect.ValueOf(bytes.NewReader(b)))
// payload.Set(reflect.ValueOf(ioutil.NopCloser(bytes.NewReader(b))))
default:
io.Copy(ioutil.Discard, r.Body)
defer r.Body.Close()
err := fmt.Errorf("unknown payload type %s", payload.Type())
return err
}
}
return nil
}
func unmarshalHeader(ctx context.Context, v reflect.Value, header string, tag reflect.StructTag) error {
if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) {
return nil
}
return setValue(ctx, v, header, tag)
}
func unmarshalQuery(ctx context.Context, v reflect.Value, params string, tag reflect.StructTag) error {
if params == "" {
return nil
}
return setValue(ctx, v, params, tag)
}
func setValue(ctx context.Context, v reflect.Value, param string, tag reflect.StructTag) error {
switch v.Interface().(type) {
case *string:
v.Set(reflect.ValueOf(¶m))
case []byte:
b, err := base64.StdEncoding.DecodeString(param)
if err != nil {
return err
}
v.Set(reflect.ValueOf(&b))
case *bool:
b, err := strconv.ParseBool(param)
if err != nil {
return err
}
v.Set(reflect.ValueOf(&b))
case *int64:
i, err := strconv.ParseInt(param, 10, 64)
if err != nil {
return err
}
v.Set(reflect.ValueOf(&i))
case *float64:
f, err := strconv.ParseFloat(param, 64)
if err != nil {
return err
}
v.Set(reflect.ValueOf(&f))
case *time.Time:
format := tag.Get("timestampFormat")
if len(format) == 0 {
format = protocol.RFC822TimeFormatName
}
t, err := protocol.ParseTime(format, param)
if err != nil {
return err
}
v.Set(reflect.ValueOf(&t))
case aws.JSONValue:
escaping := protocol.NoEscape
if tag.Get("location") == "header" {
escaping = protocol.Base64Escape
}
m, err := protocol.DecodeJSONValue(param, escaping)
if err != nil {
return err
}
v.Set(reflect.ValueOf(m))
default:
err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
return err
}
return nil
}
func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) {
v = reflect.Indirect(v)
if !v.IsValid() {
return "", errValueNotSet
}
switch value := v.Interface().(type) {
case string:
str = value
case []byte:
str = base64.StdEncoding.EncodeToString(value)
case bool:
str = strconv.FormatBool(value)
case int64:
str = strconv.FormatInt(value, 10)
case float64:
str = strconv.FormatFloat(value, 'f', -1, 64)
case time.Time:
format := tag.Get("timestampFormat")
if len(format) == 0 {
format = protocol.RFC822TimeFormatName
if tag.Get("location") == "querystring" {
format = protocol.ISO8601TimeFormatName
}
}
str = protocol.FormatTime(format, value)
case aws.JSONValue:
if len(value) == 0 {
return "", errValueNotSet
}
escaping := protocol.NoEscape
if tag.Get("location") == "header" {
escaping = protocol.Base64Escape
}
str, err = protocol.EncodeJSONValue(value, escaping)
if err != nil {
return "", fmt.Errorf("unable to encode JSONValue, %v", err)
}
default:
err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type())
return "", err
}
return str, nil
}
|
HieuMinh0609/kafka-maxwell | src/test/java/com/zendesk/maxwell/schema/ddl/DDLIntegrationTest.java | <filename>src/test/java/com/zendesk/maxwell/schema/ddl/DDLIntegrationTest.java
package com.zendesk.maxwell.schema.ddl;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zendesk.maxwell.AbstractMaxwellTest;
import com.zendesk.maxwell.schema.Schema;
import com.zendesk.maxwell.schema.SchemaCapturer;
public class DDLIntegrationTest extends AbstractMaxwellTest {
@Before
public void setUp() throws Exception {
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
}
private Schema testIntegration(String alters[]) throws SQLException, SchemaSyncError, IOException {
SchemaCapturer capturer = new SchemaCapturer(server.getConnection());
Schema topSchema = capturer.capture();
server.executeList(Arrays.asList(alters));
for ( String alterSQL : alters) {
List<SchemaChange> changes = SchemaChange.parse("shard_1", alterSQL);
if ( changes != null ) {
for ( SchemaChange change : changes ) {
topSchema = change.apply(topSchema);
}
}
}
Schema bottomSchema = capturer.capture();
List<String> diff = topSchema.diff(bottomSchema, "followed schema", "recaptured schema");
assertThat(StringUtils.join(diff.iterator(), "\n"), diff.size(), is(0));
return topSchema;
}
@Test
public void testAlter() throws SQLException, SchemaSyncError, IOException, InterruptedException {
String sql[] = {
"create table shard_1.testAlter ( id int(11) unsigned default 1, str varchar(255) )",
"alter table shard_1.testAlter add column barbar tinyint",
"alter table shard_1.testAlter rename to shard_1.`freedonia`",
"rename table shard_1.`freedonia` to shard_1.ducksoup, shard_1.ducksoup to shard_1.`nananana`",
"alter table shard_1.nananana drop column barbar",
"create table shard_2.weird_rename ( str mediumtext )",
"alter table shard_2.weird_rename rename to lowball", // renames to shard_1.lowball
"create table shard_1.testDrop ( id int(11) )",
"drop table shard_1.testDrop"
};
testIntegration(sql);
}
@Test
public void testAlterDatabase() throws Exception {
String sql[] = {
"create DATABASE test_db default character set='utf8'",
"alter schema test_db collate = 'binary'",
"alter schema test_db character set = 'latin2'"
};
testIntegration(sql);
}
@Test
public void testDrop() throws SQLException, SchemaSyncError, IOException, InterruptedException {
String sql[] = {
"create table shard_1.testAlter ( id int(11) unsigned default 1, str varchar(255) )",
"drop table if exists lasdkjflaskd.laskdjflaskdj",
"drop table shard_1.testAlter"
};
testIntegration(sql);
}
@Test
public void testCreateAndDropDatabase() throws Exception {
String sql[] = {
"create DATABASE test_db default character set='utf8'",
"create DATABASE if not exists test_db",
"create DATABASE test_db_2",
"drop DATABASE test_db"
};
testIntegration(sql);
}
@Test
public void testCreateTableLike() throws Exception {
String sql[] = {
"create TABLE `source_tbl` ( str varchar(255) character set latin1, redrum bigint(20) unsigned ) default charset 'latin1'",
"create TABLE `dest_tbl` like `source_tbl`",
"create database test_like default charset 'utf8'",
"create table `test_like`.`foo` LIKE `shard_1`.`source_tbl`"
};
testIntegration(sql);
}
@Test
public void testCreateIfNotExists() throws Exception {
String sql[] = {
"create TABLE IF NOT EXISTS `duplicateTable` (id int(11) unsigned primary KEY)",
"create TABLE IF NOT EXISTS `duplicateTable` ( str varchar(255) )",
};
testIntegration(sql);
}
@Test
public void testDatabaseEncoding() throws SQLException, SchemaSyncError, IOException {
String sql[] = {
"create DATABASE test_latin1 character set='latin1'",
"create TABLE `test_latin1`.`latin1_table` ( id int(11) unsigned, str varchar(255) )",
"create TABLE `test_latin1`.`utf8_table` ( id int(11) unsigned, "
+ "str_utf8 varchar(255), "
+ "str_latin1 varchar(255) character set latin1) charset 'utf8'"
};
testIntegration(sql);
}
@Test
public void testPKs() throws SQLException, SchemaSyncError, IOException {
String sql[] = {
"create TABLE `test_pks` ( id int(11) unsigned primary KEY, str varchar(255) )",
"create TABLE `test_pks_2` ( id int(11) unsigned, str varchar(255), primary key(id, str) )",
"create TABLE `test_pks_3` ( id int(11) unsigned primary KEY, str varchar(255) )",
"create TABLE `test_pks_4` ( id int(11) unsigned primary KEY, str varchar(255) )",
"alter TABLE `test_pks_3` drop primary key, add primary key(str)",
"alter TABLE `test_pks_4` drop primary key"
};
testIntegration(sql);
}
@Test
public void testIntX() throws Exception {
String sql[] = {
"create TABLE `test_int1` ( id int1 )",
"create TABLE `test_int2` ( id INT2 )",
"create TABLE `test_int3` ( id int3 )",
"create TABLE `test_int4` ( id int4 )",
"create TABLE `test_int8` ( id int8 )"
};
testIntegration(sql);
}
@Test
public void testYearWithLength() throws Exception {
String sql[] = {
"create TABLE `test_year` ( id year(4) )"
};
testIntegration(sql);
}
@Test
public void testBooleans() throws Exception {
String sql[] = {
"create TABLE `test_boolean` ( b1 bool, b2 boolean )"
};
testIntegration(sql);
}
@Test
public void testReals() throws Exception {
String sql[] = {
"create TABLE `test_reals` ( r1 REAL, b2 REAL (2,2) )"
};
testIntegration(sql);
}
@Test
public void testNumericNames() throws Exception {
String sql[] = {
"create TABLE shard_1.20151214_foo ( r1 REAL, b2 REAL (2,2) )",
"create TABLE shard_1.20151214 ( r1 REAL, b2 REAL (2,2) )"
};
testIntegration(sql);
}
@Test
public void testLongStringColumns() throws Exception {
String sql[] = {
"create TABLE t1( a long varchar character set 'utf8' )",
"create TABLE t2( a long varbinary )",
"create TABLE t3( a long binary character set 'latin1' default NULL )"
};
testIntegration(sql);
}
}
|
TomCreeper/goldmine | default_cogs/custom_commands.py | <filename>default_cogs/custom_commands.py
"""Nice and easy... custom commands!"""
import util.commands as commands
from .cog import Cog
class CustomCommands(Cog):
"""Nice and easy... custom commands!"""
@commands.command(aliases=['ny', 'nyet', 'noty'])
async def notyet(self):
"""Not yet, coming Soon™!"""
await self.bot.say('⚠ Not finished yet!')
def setup(bot):
bot.add_cog(CustomCommands(bot))
|
ssh-user/star_control | src/public/js/gui/menuScene/create.js | // create.js
// cache
let container, cacheTextelem = [];
/**
* Create the server scene and place it to root container.
* @param { Array<String> } elements elements menu
* @param { Number } active active element
*/
function draw(PIXI, root, wHeight, wWidth, elements, active) {
// container for progress bar scene
container = new PIXI.Container();
// add background to scene
let background = new PIXI.Sprite(PIXI.loader.resources["credits-img"].texture);
background.width = wWidth;
background.height = wHeight;
container.addChild(background);
// iterate income data and create element on each
for (let i = 0, x = 0; i < elements.length; ++i, ++x) {
if (i == active)
_createMenuElement(elements[i], true, 20, 50 + 30 * x);
else
_createMenuElement(elements[i], false, 20, 50 + 30 * x);
};
// add to global
root.addChild(container);
};
/**
* Update data in server scene.
* @param { Number } active menu element
*/
function update(active) {
for (let index = 0; index < cacheTextelem.length; index++) {
if (index == active) {
cacheTextelem[index].style.fill = "yellow";
} else {
cacheTextelem[index].style.fill = "black";
};
};
};
function pause() {
container.visible = false;
};
function resume() {
container.visible = true;
};
function clear() {
// remove menu elements
for (const elem of cacheTextelem) {
if (elem.destroy)
elem.destroy();
};
for (const elem of container.children) {
if (elem.destroy)
elem.destroy();
};
container.parent.removeChild(container);
};
export {
draw,
update,
pause,
resume,
clear
};
function _createMenuElement(title, active, x = 0, y = 0) {
let sprite = new PIXI.Sprite(PIXI.loader.resources["menu-elem"].texture);
let text = new PIXI.Text(title, {
fontSize: 12,
fontStyle: "italic",
fontVariant: "small-caps",
fontWeight: "bold"
});
let cont = new PIXI.Container();
if (active)
text.style.fill = "yellow";
else
text.style.fill = "black";
sprite.width = 150;
sprite.height = 25;
text.x = (sprite.width - text.width) / 2;
text.y = (sprite.height - text.height) / 3;
cont.x = x;
cont.y = y;
cont.addChild(sprite);
cont.addChild(text);
// to comfort change in future
cacheTextelem.push(text);
container.addChild(cont);
}; |
TaleShenHua/Cronus | src/main/java/ink/ptms/cronus/command/impl/CommandItem.java | <reponame>TaleShenHua/Cronus
package ink.ptms.cronus.command.impl;
import ink.ptms.cronus.Cronus;
import ink.ptms.cronus.command.CronusCommand;
import ink.ptms.cronus.util.Utils;
import io.izzel.taboolib.module.command.base.*;
import io.izzel.taboolib.module.locale.TLocale;
import io.izzel.taboolib.util.item.Items;
import io.izzel.taboolib.util.item.inventory.MenuBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.NumberConversions;
import java.util.stream.Collectors;
/**
* @Author 坏黑
* @Since 2019-05-31 22:10
*/
@BaseCommand(name = "CronusItem", aliases = {"cItem", "ci"}, permission = "*")
public class CommandItem extends CronusCommand {
@SubCommand
BaseSubCommand list = new BaseSubCommand() {
@Override
public String getDescription() {
return "查看任务物品";
}
@Override
public void onCommand(CommandSender sender, Command command, String s, String[] args) {
if (!Cronus.getCronusService().isNonHooked()) {
normal(sender, "该功能已被其他插件代替.");
} else {
if (Cronus.getCronusService().getItemStorage().getItems().isEmpty()) {
error(sender, "空空如也.");
return;
}
normal(sender, "任务物品: " + Cronus.getCronusService().getItemStorage().getItems().stream().map(i -> "§8" + i + "§r").collect(Collectors.joining(", ")));
}
}
};
@SubCommand
BaseSubCommand give = new BaseSubCommand() {
@Override
public Argument[] getArguments() {
return new Argument[] {
new Argument("名称", () -> Cronus.getCronusService().getItemStorage().getItems()), new Argument("玩家", false), new Argument("数量", false)
};
}
@Override
public String getDescription() {
return "获取任务物品";
}
@Override
public void onCommand(CommandSender sender, Command command, String s, String[] args) {
if (!Cronus.getCronusService().isNonHooked()) {
normal(sender, "该功能已被其他插件代替.");
} else {
ItemStack item = Cronus.getCronusService().getItemStorage().getItem(args[0]);
if (Items.isNull(item)) {
error(sender, "物品 &7" + args[0] + " &c无效.");
return;
}
Player player;
if (args.length > 1) {
player = Bukkit.getPlayerExact(args[1]);
if (player == null) {
error(sender, "玩家 &7" + args[1] + " &c离线.");
return;
}
} else if (sender instanceof Player) {
player = (Player) sender;
} else {
error(sender, "缺少玩家参数.");
return;
}
if (args.length > 2) {
item.setAmount(NumberConversions.toInt(args[2]));
}
Utils.addItem(player, item);
}
}
};
@SubCommand
BaseSubCommand save = new BaseSubCommand() {
@Override
public Argument[] getArguments() {
return new Argument[] {
new Argument("名称")
};
}
@Override
public String getDescription() {
return "储存任务物品";
}
@Override
public void onCommand(CommandSender sender, Command command, String s, String[] args) {
if (!Cronus.getCronusService().isNonHooked()) {
normal(sender, "该功能已被其他插件代替.");
} else {
if (Utils.isNull(((Player) sender).getItemInHand())) {
error(sender, "无效物品.");
return;
}
Cronus.getCronusService().getItemStorage().addItem(args[0], ((Player) sender).getItemInHand());
normal(sender, "物品 &f" + args[0] + " &7已储存.");
}
}
@Override
public CommandType getType() {
return CommandType.PLAYER;
}
};
@SubCommand
BaseSubCommand delete = new BaseSubCommand() {
@Override
public Argument[] getArguments() {
return new Argument[] {
new Argument("名称", () -> Cronus.getCronusService().getItemStorage().getItems())
};
}
@Override
public String getDescription() {
return "删除任务物品";
}
@Override
public void onCommand(CommandSender sender, Command command, String s, String[] args) {
if (!Cronus.getCronusService().isNonHooked()) {
normal(sender, "该功能已被其他插件代替.");
} else {
Cronus.getCronusService().getItemStorage().delItem(args[0]);
normal(sender, "物品 &f" + args[0] + " &7已删除.");
}
}
};
@SubCommand
BaseSubCommand importGui = new BaseSubCommand() {
@Override
public String getLabel() {
return "import";
}
@Override
public String getDescription() {
return "批量储存任务物品";
}
@Override
public void onCommand(CommandSender sender, Command command, String s, String[] args) {
if (!Cronus.getCronusService().isNonHooked()) {
normal(sender, "该功能已被其他插件代替.");
} else {
((Player) sender).playSound(((Player) sender).getLocation(), Sound.BLOCK_CHEST_OPEN, 1f, 1f);
((Player) sender).openInventory(MenuBuilder.builder(Cronus.getInst())
.title("物品导入")
.rows(3)
.items()
.close(e -> {
for (ItemStack itemStack : e.getInventory()) {
if (Items.isNull(itemStack)) {
continue;
}
String name = TLocale.Translate.setUncolored(Items.getName(itemStack));
Cronus.getCronusService().getItemStorage().addItem(name, itemStack);
normal(sender, "物品 &f" + name + " &7已储存.");
Utils.addItem((Player) sender, itemStack);
}
}).build());
}
}
};
}
|
lidashuang1996/p6e_germ_java | p6e-germ-oauth2/src/main/java/com/p6e/germ/oauth2/cache/IP6eCacheClient.java | package com.p6e.germ.oauth2.cache;
/**
* @author lidashuang
* @version 1.0
*/
public interface IP6eCacheClient {
/** 客户端名称 */
String CLIENT_NAME = "P6E:DB:CLIENT:";
/** 客户端缓存的过期时间 */
long CLIENT_TIME = 3600;
/**
* 添加客户端缓存
* @param key 缓存名称
* @param value 缓存内容
*/
public void set(String key, String value);
/**
* 删除客户端缓存
* @param key 缓存名称
*/
public void del(String key);
/**
* 获取客户端缓存
* @param key 缓存名称
* @return 缓存内容
*/
public String get(String key);
}
|
metux/chromium-deb | base/sys_info_fuchsia.cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/sys_info.h"
#include <magenta/syscalls.h>
namespace base {
// static
int64_t SysInfo::AmountOfPhysicalMemory() {
return mx_system_get_physmem();
}
// static
int SysInfo::NumberOfProcessors() {
return mx_system_get_num_cpus();
}
} // namespace base
|
medismailben/llvm-project | compiler-rt/test/sanitizer_common/TestCases/Linux/closedir.c | // Check that closedir(NULL) is ok.
// RUN: %clang -O2 %s -o %t && %run %t
#include <sys/types.h>
#include <dirent.h>
int main() { closedir(0); }
|
peacetrue/peacetrue | peacetrue-associate/src/main/java/com/github/peacetrue/associate/AssociatedSourceBuilderImpl.java | <gh_stars>10-100
package com.github.peacetrue.associate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
/**
* @author xiayx
*/
public class AssociatedSourceBuilderImpl implements AssociatedSourceBuilder {
private Map<Key, AssociatedSource> cache = new HashMap<>();
@Override
@SuppressWarnings("unchecked")
public <I, D, R> AssociatedSource<I, D, R> buildAssociatedSource(Function<I, D> findAssociate, Function<D, R> format) {
return cache.computeIfAbsent(new Key(findAssociate, null, format),
key -> new AssociatedSource<I, D, R>() {
public D findAssociate(I id) {
return findAssociate.apply(id);
}
public R format(D data) {
return format.apply(data);
}
});
}
@Override
@SuppressWarnings("unchecked")
public <I, D, R> CollectionAssociatedSource<I, D, R> buildCollectionAssociatedSource(Function<Collection<I>, Collection<D>> findAssociate, Function<D, I> resolveId, Function<D, R> format) {
return (CollectionAssociatedSource<I, D, R>)
cache.computeIfAbsent(new Key(findAssociate, resolveId, format),
key -> new CollectionAssociatedSource<I, D, R>() {
public Collection<D> findCollectionAssociate(Collection<I> ids) {
return findAssociate.apply(ids);
}
public I resolveId(D data) {
return resolveId.apply(data);
}
public R format(D data) {
return format.apply(data);
}
});
}
private static class Key {
private Function findAssociate;
private Function resolveId;
private Function format;
public Key(Function findAssociate, Function resolveId, Function format) {
this.findAssociate = Objects.requireNonNull(findAssociate);
this.resolveId = resolveId;
this.format = Objects.requireNonNull(format);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Key)) return false;
Key other = (Key) obj;
return Objects.equals(findAssociate, other.findAssociate)
& Objects.equals(resolveId, other.resolveId)
& Objects.equals(format, other.format);
}
}
}
|
simpleton/profilo | cpp/jni/NativeTraceWriter.h | /**
* Copyright 2004-present, Facebook, 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.
*/
#pragma once
#include <fbjni/fbjni.h>
#include <profilo/writer/TraceWriter.h>
namespace fbjni = facebook::jni;
namespace facebook {
namespace profilo {
namespace writer {
struct JNativeTraceWriterCallbacks:
public fbjni::JavaClass<JNativeTraceWriterCallbacks> {
static constexpr const char* kJavaDescriptor =
"Lcom/facebook/profilo/writer/NativeTraceWriterCallbacks;";
void onTraceStart(int64_t trace_id, int32_t flags, std::string file);
void onTraceEnd(int64_t trace_id, uint32_t crc);
void onTraceAbort(int64_t trace_id, AbortReason abortReason);
};
class NativeTraceWriter : public fbjni::HybridClass<NativeTraceWriter> {
public:
constexpr static auto kJavaDescriptor =
"Lcom/facebook/profilo/writer/NativeTraceWriter;";
static fbjni::local_ref<jhybriddata> initHybrid(
fbjni::alias_ref<jclass>,
std::string trace_folder,
std::string trace_prefix,
int bufferSize,
fbjni::alias_ref<JNativeTraceWriterCallbacks> callbacks
);
static void registerNatives();
void loop();
void submit(TraceBuffer::Cursor cursor, int64_t trace_id);
private:
friend HybridBase;
NativeTraceWriter(
std::string trace_folder,
std::string trace_prefix,
size_t bufferSize,
fbjni::alias_ref<JNativeTraceWriterCallbacks> callbacks
);
std::shared_ptr<TraceCallbacks> callbacks_;
writer::TraceWriter writer_;
};
} // namespace writer
} // namespace profilo
} // namespace facebook
|
iKimee/musicXML | Pod/musicFramework/core/elements/AccordionHigh.cpp | // MusicXML Class Library
// Copyright (c) by <NAME>
// Distributed under the MIT License
#include "../../core/elements/AccordionHigh.h"
#include "../../core/FromXElement.h"
#include <iostream>
namespace mx
{
namespace core
{
AccordionHigh::AccordionHigh() : ElementInterface() {}
bool AccordionHigh::hasAttributes() const { return false; }
bool AccordionHigh::hasContents() const { return false; }
std::ostream& AccordionHigh::streamAttributes( std::ostream& os ) const { return os; }
std::ostream& AccordionHigh::streamName( std::ostream& os ) const { os << "accordion-high"; return os; }
std::ostream& AccordionHigh::streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const
{
MX_UNUSED( indentLevel );
isOneLineOnly = true;
return os;
}
bool AccordionHigh::fromXElement( std::ostream& message, xml::XElement& xelement )
{
MX_UNUSED( message );
MX_UNUSED( xelement );
return true;
}
}
}
|
EdgarLiu2/java_leetcode | src/main/java/edgar/try_new/rabbitmq/Sample3Publisher.java | <filename>src/main/java/edgar/try_new/rabbitmq/Sample3Publisher.java
package edgar.try_new.rabbitmq;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import edgar.util.RabbitMQUtil;
public class Sample3Publisher {
public static final String EXCHANGE_CONFIG_KEY = "edgar.rabbitmq.exchange1";
public static void main(String[] args) throws IOException, TimeoutException {
RabbitMQUtil rabbitMQ = new RabbitMQUtil(EXCHANGE_CONFIG_KEY);
String exchangeName = rabbitMQ.getChannelName();
try (Channel channel = rabbitMQ.createExchangeSenderChannel()) {
// publish a message to the queue
String message = "info: Hello World!";
channel.basicPublish(exchangeName, "", null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}
rabbitMQ.closeConnection();
}
}
|
ohtu-aikavali2/aikavali2-front | src/tests/components/common/ReviewPopup.test.js | <gh_stars>0
import React from 'react'
import { shallow } from 'enzyme'
import { ReviewPopup } from '../../../app/components/common/ReviewPopup'
import AlertWindow from '../../../app/components/common/AlertWindow'
import LikertScale from 'likert-react'
describe ('<ReviewPopup />', () => {
let popup, props
beforeAll(() => {
props = {
toggle: jest.fn(),
submit: jest.fn()
}
popup = shallow(<ReviewPopup {...props} />)
})
it('renders self', () => {
expect(popup.find('.popupContainer').length).toBe(1)
})
it('renders AlertWindow with LikertScale component inside it', () => {
const alertWindow = popup.find(AlertWindow)
expect(alertWindow.length).toBe(1)
expect(alertWindow.children().find(LikertScale).length).toBe(1)
})
it('LikertScale click calls props.submit', () => {
const scale = popup.find(LikertScale)
expect(props.submit).toHaveBeenCalledTimes(0)
scale.simulate('click')
expect(props.submit).toHaveBeenCalledTimes(1)
props.submit.mockClear()
})
})
|
martinlehoux/django_bike | apps/account/migrations/0005_profile_default_sport.py | # Generated by Django 3.2 on 2021-04-20 10:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("account", "0004_auto_20200906_1211"),
]
operations = [
migrations.AddField(
model_name="profile",
name="default_sport",
field=models.CharField(
blank=True,
choices=[("biking", "Biking"), ("running", "Running")],
max_length=32,
null=True,
),
),
]
|
eagletmt/procon | poj/1/1119.cc | <reponame>eagletmt/procon<filename>poj/1/1119.cc
#include <iostream>
#include <cstdio>
#include <sstream>
#include <vector>
#include <map>
#include <cmath>
#include <cctype>
using namespace std;
string f(const string& s)
{
string t;
for (string::const_iterator it = s.begin(); it != s.end(); ++it) {
if (isalnum(*it)) {
t += toupper(*it);
}
}
return t;
}
void words(map<string, int>& dict, const string& line)
{
istringstream iss(line);
for (string w; iss >> w;) {
const string v = f(w);
if (!v.empty()) {
++dict[v];
}
}
}
int main()
{
static const string TERM = "----------";
map<string, int> dict;
for (string line; getline(cin, line) && line != TERM;) {
words(dict, line);
}
for (string line; getline(cin, line) && line != TERM;) {
map<string, int> d;
words(d, line);
while (getline(cin, line) && line != TERM) {
words(d, line);
}
double score = 0.0;
for (map<string, int>::const_iterator it = dict.begin(); it != dict.end(); ++it) {
score += sqrt(it->second * d[it->first]);
}
printf("%.2f\n", score);
}
return 0;
} |
ericfan/spring-integration-5.x-fb2g | xml-split-aggregate/src/main/java/com/example/splitaggregate/splitter/SearchRequestSplitter.java | package com.example.splitaggregate.splitter;
import org.springframework.integration.splitter.AbstractMessageSplitter;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Map;
@Component
public class SearchRequestSplitter extends AbstractMessageSplitter {
@Override
protected Object splitMessage(Message<?> message) {
return Arrays.asList("a", "b", "c", 1, 2);
}
@Override
protected void addHeaders(Message<?> message, Map<String, Object> headers) {
headers.put("customAttr", "CustomHeader");
}
@Override
protected boolean willAddHeaders(Message<?> message) {
return true;
}
}
|
ark100/multi-os-engine | moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/uikit/enums/UITextDropPerformer.java | package apple.uikit.enums;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NUInt;
@Generated
public final class UITextDropPerformer {
@Generated
private UITextDropPerformer() {
}
@Generated @NUInt public static final long View = 0x0000000000000000L;
@Generated @NUInt public static final long Delegate = 0x0000000000000001L;
} |
GrieferAtWork/KOS | src/kernel/include/kernel/user.h | <reponame>GrieferAtWork/KOS<gh_stars>1-10
/* Copyright (c) 2018 Griefer@<EMAIL> *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
#ifndef GUARD_KERNEL_INCLUDE_KERNEL_USER_H
#define GUARD_KERNEL_INCLUDE_KERNEL_USER_H 1
#include <hybrid/compiler.h>
#include <kos/types.h>
#include <hybrid/host.h>
#if defined(__i386__) || defined(__x86_64__)
#include <i386-kos/user.h>
#else
#error "Unsupported Architecture"
#endif
DECL_BEGIN
#ifdef __CC__
/* Validate user-pointers for being allowed to be used for the specified operations.
* Since the kernel is allowed to access memory that is marked as `PROT_NOUSER',
* user-pointers passed from user-space must be checked for the same restrictions.
* In order words: If the user passes a pointer that is part of kernel-space,
* these functions are used to deny the user access to such memory.
* @throw E_SEGFAULT: User-space has not been granted access to the given address range. */
FUNDEF void KCALL validate_user(UNCHECKED USER void const *base, size_t num_bytes);
FUNDEF void KCALL validate_userm(UNCHECKED USER void const *base, size_t num_items, size_t item_size_in_bytes);
FUNDEF void KCALL validate_readable(UNCHECKED USER void const *base, size_t num_bytes);
FUNDEF void KCALL validate_readablem(UNCHECKED USER void const *base, size_t num_items, size_t item_size_in_bytes);
FUNDEF void KCALL validate_writable(UNCHECKED USER void *base, size_t num_bytes);
FUNDEF void KCALL validate_writablem(UNCHECKED USER void *base, size_t num_items, size_t item_size_in_bytes);
FUNDEF void KCALL validate_executable(UNCHECKED USER void const *base);
/* Same as the function above, but also accept `NULL' */
FUNDEF void KCALL validate_readable_opt(UNCHECKED USER void const *base, size_t num_bytes);
FUNDEF void KCALL validate_readablem_opt(UNCHECKED USER void const *base, size_t num_items, size_t item_size_in_bytes);
FUNDEF void KCALL validate_writable_opt(UNCHECKED USER void *base, size_t num_bytes);
FUNDEF void KCALL validate_writablem_opt(UNCHECKED USER void *base, size_t num_items, size_t item_size_in_bytes);
FUNDEF void KCALL validate_executable_opt(UNCHECKED USER void const *base);
/* Search for the end of the given user-space string.
* Search stops when an unmapped page is encountered, or if
* the string extends into memory that the user does not have
* access permissions for.
* Upon such an error, an `E_SEGFAULT' is thrown. Otherwise,
* the length of the string (in bytes) is returned. */
FUNDEF size_t KCALL user_strlen(UNCHECKED USER char const *base);
#endif /* __CC__ */
DECL_END
#endif /* !GUARD_KERNEL_INCLUDE_KERNEL_USER_H */
|
MiniGod/CommunityFundIS-web | src/routes/reset/ResetOne.js | import React from 'react';
import PropTypes from 'prop-types';
import { Grid, Image, Form, Segment, Button, Message } from 'semantic-ui-react';
import ReCAPTCHA from 'react-google-recaptcha';
import Link from '../../components/Link';
import { logError } from '../../logger';
export default class Reset extends React.Component {
static propTypes = { redirect: PropTypes.string };
static defaultProps = { redirect: null };
static contextTypes = { fetch: PropTypes.func };
state = {
email: '',
error: null,
showSuccess: false,
googleToken: null,
isSending: false,
};
handleChange = (e, { name, value }) => this.setState({ [name]: value });
handleCaptcha(googleToken) {
this.setState(
{
...this.state,
googleToken,
},
() => {
this.handleSubmit();
},
);
}
async handleSubmit() {
const { email, googleToken } = this.state;
if (!googleToken) {
this.setState({
...this.state,
isSending: true,
});
this.captcha.reset();
this.captcha.execute();
return false;
}
const response = await this.context.fetch('/api/reset', {
method: 'POST',
body: JSON.stringify({
email,
googleToken,
}),
});
let data = {
error: 'Something went wrong',
};
try {
data = await response.json();
} catch (e) {
logError(e);
}
if (data.success) {
this.setState({
showSuccess: true,
error: null,
isSending: false,
googleToken: null,
});
} else {
this.setState({
error: data.error,
isSending: false,
googleToken: null,
});
}
return true;
}
render() {
const { redirect } = this.props;
const { email, error, showSuccess, isSending } = this.state;
return (
<div
style={{
height: '100%',
minHeight: '100vh',
background: '#f7f7f7',
}}
>
<Grid
textAlign="center"
style={{ height: '100%', minHeight: '100vh', margin: 0 }}
verticalAlign="middle"
>
<Grid.Column style={{ maxWidth: 450 }} mobile={14}>
<Image
as={Link}
to="/"
src="/logos/transparent_logo.png"
size="medium"
style={{
margin: 'auto',
marginBottom: '1.4em',
cursor: 'pointer',
}}
/>
{redirect === 'error' && (
<Message
error
header="Something went wrong"
content="You could try to reset your password again"
/>
)}
{redirect === 'invalid' && (
<Message
error
header="Invalid or expired link"
content="You could try to reset your password again"
/>
)}
{showSuccess && (
<Message
success
header="Reset successful"
content={`Please check ${email} for instructions`}
/>
)}
{!showSuccess && (
<Form size="large" error={!!error}>
<Message error content={error} size="tiny" />
<Segment stacked>
<Form.Input
fluid
icon="user"
name="email"
iconPosition="left"
placeholder="E-mail address"
onChange={(...args) => this.handleChange(...args)}
value={email}
/>
<Button
color="teal"
fluid
size="large"
onClick={() => this.handleSubmit()}
loading={isSending}
>
Reset
</Button>
</Segment>
<ReCAPTCHA
size="invisible"
ref={el => {
this.captcha = el;
}}
sitekey="<KEY>"
onChange={e => this.handleCaptcha(e)}
/>
</Form>
)}
</Grid.Column>
</Grid>
</div>
);
}
}
|
cyy1991/Common-Cplusplus-DataStructures-Implementations | Stacks/expression evaluation/infix to prefix using one STACK/validating.cpp | #include <iostream>
#include <string>
using namespace std;
#include "stack.cpp"
int isValid ( string );
int isOpeningBracket ( char );
int isClosingBracket ( char );
string evaluateToPrefix ( string );
int isOperand ( char );
int isOperator ( char );
int precedence ( char );
void main ( )
{
string s ( "A * B / C" );
try
{
if ( isValid ( s ) )
cout << "Valid" << endl;
else
cout << "Invalid" << endl;
cout << evaluateToPostfix ( s ) << endl;
}
catch ( exception & e )
{
cout << "Execption occurred : " << e.what ( ) << endl;
}
}
int isValid ( string str )
{
int i = 0;
Stack<int> s;
while ( str[i] != '\0' )
{
if ( isOpeningBracket ( str[i] ) )
s.push ( str[i] );
else if ( isClosingBracket ( str[i] ) )
{
if ( s.isEmpty ( ) )
return 0;
else if ( s.stackTop ( ) == '(' )
s.pop ( );
else
return 0;
}
i++;
}
if ( s.isEmpty ( ) )
return 1;
return 0;
}
string evaluateToPrefix ( string str )
{
Stack<char> stack;
string result;
int i = str.length ( );
while ( i >= 0 )
{
if ( isOperand ( str[i] ) )
{
string temp= str[i] + result;
result = temp;
}
else if ( isOpeningBracket ( str[i] ) )
stack.push ( str[i] );
else if ( isOperator ( str[i] ) )
{
while ( !stack.isEmpty ( ) && precedence ( stack.stackTop ( ) ) >=
precedence ( str[i] ) )
{
char character = stack.pop ( );
if ( !isOpeningBracket ( character ) )
{
string s = character + result;
result = s;
}
}
if ( !isClosingBracket ( str[i] ) )
{
stack.push ( str[i] );
}
}
i--;
}
while ( !stack.isEmpty ( ) )
{
string s= stack.pop ( ) + result;
result = s;
}
return result;
}
int precedence ( char ch )
{
if ( ch == '(' || ch == ')' )
return 0;
else if ( ch == '=' )
return 1;
else if ( ch == '+' || ch == '-' )
return 2;
else if ( ch == '/' || ch == '%' || ch == '*' )
return 3;
return -1;
}
int isOperand ( char ch )
{
return ( ch >= 'A' && ch <= 'z' );
}
int isOperator ( char ch )
{
return ( ch >= '!' && ch <= '/' );
}
int isOpeningBracket ( char ch )
{
if ( ch == '(' )
return 1;
return 0;
}
int isClosingBracket ( char ch )
{
if ( ch == ')' )
return 1;
return 0;
} |
myvyang/intellij-community | platform/platform-impl/src/com/intellij/ide/util/ElementsChooser.java | <filename>platform/platform-impl/src/com/intellij/ide/util/ElementsChooser.java
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.ide.util;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.table.TableCellRenderer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @see ChooseElementsDialog
*/
public class ElementsChooser<T> extends MultiStateElementsChooser<T, Boolean> {
private static final BooleanMarkStateDescriptor MARK_STATE_DESCRIPTOR = new BooleanMarkStateDescriptor();
public interface ElementsMarkListener<T> {
void elementMarkChanged(T element, boolean isMarked);
}
public ElementsChooser(final boolean elementsCanBeMarked) {
super(elementsCanBeMarked, ElementsChooser.<T>getMarkStateDescriptor());
}
public ElementsChooser(List<T> elements, boolean marked) {
super(elements, marked, ElementsChooser.<T>getMarkStateDescriptor());
}
public void addElementsMarkListener(ElementsMarkListener<T> listener) {
addElementsMarkListener(new ElementsMarkStateListenerAdapter<T>(listener));
}
public void removeElementsMarkListener(ElementsMarkListener<T> listener) {
removeElementsMarkListener(new ElementsMarkStateListenerAdapter<T>(listener));
}
public void addElement(T element, final boolean isMarked) {
addElement(element, getMarkState(isMarked));
}
/**
* Check if element is marked
*
* @param element an element to test
* @return true if element is marked
*/
public boolean isElementMarked(T element) {
return getElementMarkState(element);
}
/**
* Update element mark
*
* @param element an element to test
* @param marked a new value of mark.
*/
public void setElementMarked(T element, boolean marked) {
setElementMarkState(element, getMarkState(marked));
}
public void addElement(T element, final boolean isMarked, ElementProperties elementProperties) {
addElement(element, getMarkState(isMarked), elementProperties);
}
public void setElements(List<T> elements, boolean marked) {
setElements(elements, getMarkState(marked));
}
public void markElements(Collection<T> elements) {
markElements(elements, Boolean.TRUE);
}
@NotNull
public List<T> getMarkedElements() {
Map<T, Boolean> elementMarkStates = getElementMarkStates();
List<T> elements = new ArrayList<T>();
for (Map.Entry<T, Boolean> entry : elementMarkStates.entrySet()) {
if (entry.getValue()) {
elements.add(entry.getKey());
}
}
return elements;
}
public void invertSelection() {
final int count = getElementCount();
for (int i = 0; i < count; i++) {
T type = getElementAt(i);
setElementMarked(type, !isElementMarked(type));
}
}
public void setAllElementsMarked(boolean marked) {
setAllElementsMarked(getMarkState(marked));
}
private static Boolean getMarkState(boolean marked) {
return marked;
}
@SuppressWarnings("unchecked")
private static <T> MarkStateDescriptor<T, Boolean> getMarkStateDescriptor() {
return MARK_STATE_DESCRIPTOR;
}
private static class BooleanMarkStateDescriptor<T> implements MarkStateDescriptor<T, Boolean> {
@NotNull
@Override
public Boolean getDefaultState(@NotNull T element) {
return Boolean.FALSE;
}
@NotNull
@Override
public Boolean getNextState(@NotNull T element, @NotNull Boolean state) {
return !state;
}
@Nullable
@Override
public Boolean getNextState(@NotNull Map<T, Boolean> elementsWithStates) {
boolean currentlyMarked = true;
for (Boolean state : elementsWithStates.values()) {
currentlyMarked = state;
if (!currentlyMarked) {
break;
}
}
return !currentlyMarked;
}
@Override
public boolean isMarked(@NotNull Boolean state) {
return state;
}
@Nullable
@Override
public Boolean getMarkState(@Nullable Object value) {
return value instanceof Boolean ? ((Boolean)value) : null;
}
@Nullable
@Override
public TableCellRenderer getMarkRenderer() {
return null;
}
}
private static class ElementsMarkStateListenerAdapter<T> implements ElementsMarkStateListener<T, Boolean> {
private final ElementsMarkListener<T> myListener;
public ElementsMarkStateListenerAdapter(ElementsMarkListener<T> listener) {
myListener = listener;
}
@Override
public void elementMarkChanged(T element, Boolean markState) {
myListener.elementMarkChanged(element, markState);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ElementsMarkStateListenerAdapter that = (ElementsMarkStateListenerAdapter)o;
if (!myListener.equals(that.myListener)) return false;
return true;
}
@Override
public int hashCode() {
return myListener.hashCode();
}
}
}
|
johncrossman/datacultures | db/migrate/20150119161808_add_thumbnail_to_attachments.rb | class AddThumbnailToAttachments < ActiveRecord::Migration
def change
add_column :attachments, :thumbnail_url, :string
end
end
|
ciren/benchmarks | src/test/scala/benchmarks/dimension/Generators.scala | <filename>src/test/scala/benchmarks/dimension/Generators.scala
// package benchmarks
// package dimension
// import scalaz._
// import Scalaz._
// import scalaz.scalacheck.ScalaCheckBinding._
// import shapeless._
// import org.scalacheck._
// import org.scalacheck.Gen.Choose
// object Generators {
// def c[A:Choose](l: A, u: A) = Gen.choose(l, u)
// def gen1[A:Choose](l: A, u: A): Gen[Dimension1[A]] =
// c(l, u).map(Sized(_))
// def gen2[A:Choose](l: A, u: A): Gen[Dimension2[A]] =
// (c(l, u) |@| c(l, u)) { (a, b) => Sized(a, b) }
// def gen2D[A:Choose](d1: (A, A), d2: (A, A)) =
// (c(d1._1, d1._2) |@| c(d2._1, d2._2)) { (a, b) => Sized(a, b) }
// def gen3[A:Choose](l: A, u: A) =
// (c(l, u) |@| c(l, u) |@| c(l, u)) { Sized(_, _, _) }
// def gen3D[A:Choose](d1: (A, A), d2: (A, A), d3: (A, A)) =
// (c(d1._1, d1._2) |@| c(d2._1, d2._2) |@| c(d3._1, d3._2)) { Sized(_, _, _) }
// def gen4[A:Choose](l: A, u: A): Gen[Dimension4[A]] =
// (c(l, u) |@| c(l, u) |@| c(l, u) |@| c(l,u)) { Sized(_, _, _, _) }
// def gen5[A:Choose](l: A, u: A) =
// (c(l, u) |@| c(l, u) |@| c(l, u) |@| c(l, u) |@| c(l, u)) { Sized(_, _, _, _, _) }
// def gen6[A:Choose](l: A, u: A) =
// (c(l, u) |@| c(l, u) |@| c(l, u) |@| c(l, u) |@| c(l, u) |@| c(l, u)) {
// Sized(_, _, _, _, _, _)
// }
// def gen10[A:Choose](l: A, u: A): Gen[Dimension[_10,A]] =
// for {
// xs <- Gen.containerOfN[Vector,A](10, c(l, u))
// } yield Sized.wrap[IndexedSeq[A],_10](xs)
// def gen16[A:Choose](l: A, u: A): Gen[Dimension[_16,A]] =
// for {
// xs <- Gen.containerOfN[Vector,A](16, c(l, u))
// } yield Sized.wrap[IndexedSeq[A],_16](xs)
// def gen30[A:Choose](l: A, u: A): Gen[Dimension[_30,A]] =
// for {
// xs <- Gen.containerOfN[Vector,A](30, c(l, u))
// } yield Sized.wrap[IndexedSeq[A],_30](xs)
// def gen50[A:Choose](l: A, u: A): Gen[Dimension[_50,A]] =
// for {
// xs <- Gen.containerOfN[Vector,A](50, c(l, u))
// } yield Sized.wrap[IndexedSeq[A],_50](xs)
// def genSized[A:Choose](l: A, u: A): Gen[Dimension[_10,A]] =
// for {
// xs <- Gen.containerOfN[Vector,A](10, c(l, u))
// } yield Sized.wrap(xs)
// def genConst[A:Choose](v: A) = genSized(v, v)
// }
|
Laughs-In-Flowers/warhola | lib/canvas/measure.go | package canvas
import (
"fmt"
"image"
"math"
"strconv"
"strings"
"github.com/Laughs-In-Flowers/warhola/lib/util/mth"
"golang.org/x/image/math/fixed"
)
// An interface of tools for examining, manipulating, and measuring a rectangle.
type Measure interface {
PP(string) float64
SetPP(string, float64)
Height() float64
Width() float64
Radius() float64
Distance(string, Moint, Moint) float64
Anchor(string) Moint
SetAnchor(string, MointFunc)
}
type measure struct {
*anchored
r *image.Rectangle
ppu string
pp, ppi, ppc, ppm float64
}
var (
defaultPPU string = "cm" // points per unit
defaultPP float64 = 118 // points per
AvailablePPU []string = []string{defaultPPU, "mm", "inch"} //
)
func newMeasure(r *image.Rectangle, ppIn float64, ppu string) *measure {
m := &measure{
r: r,
ppu: ppu,
pp: ppIn,
}
m.anchored = newAnchored(m)
m.SetPP(m.ppu, m.pp)
return m
}
// Returns points per unit of measurement (inch,cm,mm,or nonspecific default)
func (m *measure) PP(pp string) float64 {
switch pp {
case "inch", "in":
return m.ppi
case "centimeter", "cm":
return m.ppc
case "millimeter", "mm":
return m.ppm
}
return float64(m.pp)
}
func (m *measure) SetPP(ppu string, pp float64) {
m.pp = pp
switch strings.ToLower(ppu) {
case "cm", "centimeter":
m.ppc = m.pp
m.ppm = m.pp / 10
m.ppi = m.ppc * 2.54
case "mm", "millimeter":
m.ppm = pp
m.ppc = m.ppm * 10
m.ppi = m.ppc * 2.54
case "in", "inch":
m.ppi = m.pp
m.ppc = m.pp / 2.54
m.ppm = m.ppc / 10
}
}
// Returns the height as a float64.
func (m *measure) Height() float64 {
b := m.r.Bounds()
return float64(b.Dy())
}
// Returns the width as a float64.
func (m *measure) Width() float64 {
b := m.r.Bounds()
return float64(b.Dx())
}
// Returns the radius as a float64.
func (m *measure) Radius() float64 {
return m.Height() / 2
}
func distance(p1, p2 Moint) float64 {
return math.Sqrt(math.Pow((p2.X-p1.X), 2) + math.Pow((p2.Y-p1.Y), 2))
}
// Returns the float64 distance between two provided Points for the provided unit.
func (m *measure) Distance(u string, p1, p2 Moint) float64 {
switch u {
case "inch":
return dINCH(m, p1, p2)
case "cm":
return dCM(m, p1, p2)
case "mm":
return dMM(m, p1, p2)
}
return distance(p1, p2)
}
func dINCH(m *measure, p1, p2 Moint) float64 {
d := distance(p1, p2)
return d / m.ppi
}
func dCM(m *measure, p1, p2 Moint) float64 {
d := distance(p1, p2)
return d / m.ppc
}
func dMM(m *measure, p1, p2 Moint) float64 {
d := distance(p1, p2)
return d / m.ppm
}
// A function type that takes a Measure and returns a Point.
type MointFunc func(f Measure) Moint
// A struct encapsulating a specific point derived by relationship function.
type anchor struct {
fn MointFunc
tag string
}
// Produces a new Anchor from the provided tag and point function.
func newAnchor(tag string, fn MointFunc) *anchor {
return &anchor{fn, tag}
}
type anchored struct {
m *measure
has []*anchor
}
func newAnchored(m *measure) *anchored {
a := &anchored{
m: m,
has: make([]*anchor, 0),
}
a.SetAnchor(
"origin",
func(Measure) Moint { return Moint{0, 0} },
)
a.SetAnchor(
"center",
func(mm Measure) Moint { return Moint{mm.Width() / 2, mm.Height() / 2} },
)
a.SetAnchor(
"bound",
func(mm Measure) Moint { return Moint{mm.Width(), mm.Height()} },
)
return a
}
func (a *anchored) getAnchor(tag string) *anchor {
for _, aa := range a.has {
if aa.tag == tag {
return aa
}
}
return nil
}
// Gets an anchor point corresponding to provided tag. No available anchor
// returns a zeroed Moint.
func (a *anchored) Anchor(tag string) Moint {
if aa := a.getAnchor(tag); aa != nil {
return aa.fn(a.m)
}
return ZM
}
// Sets an Anchor.
func (a *anchored) SetAnchor(tag string, fn MointFunc) {
aa := newAnchor(tag, fn)
a.has = append(a.has, aa)
}
// A struct encompassing a 2D float64 X - Y coordinate for measurement.
// Functionality is paralell to image.Point, but not an interface.
type Moint struct {
X, Y float64
}
var ZM Moint = Moint{0, 0}
// Returns a fixed.Point26_6 representation of Point.
func (p Moint) Fixed() fixed.Point26_6 {
return mth.Fixp(p.X, p.Y)
}
// Returns the distance from point to other point.
func (p Moint) Distance(o Moint) float64 {
return math.Hypot(p.X-o.X, p.Y-o.Y)
}
// Interpolate other Point to provided float64.
func (p Moint) Interpolate(o Moint, t float64) Moint {
x := p.X + (o.X-p.X)*t
y := p.Y + (o.Y-p.Y)*t
return Moint{x, y}
}
//
func (p Moint) IPoint() image.Point {
return image.Point{
int(math.Round(p.X)),
int(math.Round(p.Y)),
}
}
//
func ToMoint(ip image.Point) Moint {
return Moint{float64(ip.X), float64(ip.Y)}
}
// Add other Point to this Point.
func (p Moint) Add(o Moint) Moint {
return Moint{p.X + o.X, p.Y + o.Y}
}
//
func (p Moint) Div(k float64) Moint {
return Moint{p.X / k, p.Y / k}
}
//
func (p Moint) Eq(o Moint) bool {
return p.X == o.X && p.Y == o.Y
}
//
func (p Moint) In(r image.Rectangle) bool {
rmX, rmY := float64(r.Min.X), float64(r.Min.Y)
rxX, rxY := float64(r.Max.X), float64(r.Max.Y)
return rmX <= p.X && p.X < rxX &&
rmY <= p.Y && p.Y < rxY
}
//
func (p Moint) Mod(r image.Rectangle) Moint {
rMin := ToMoint(r.Min)
w, h := float64(r.Dx()), float64(r.Dy())
mp := p.Sub(rMin)
mp.X = math.Mod(mp.X, w)
if mp.X < 0 {
mp.X += w
}
mp.Y = math.Mod(mp.Y, h)
if mp.Y < 0 {
mp.Y += h
}
return mp.Add(rMin)
}
//
func (p Moint) Mul(k float64) Moint {
return Moint{p.X * k, p.Y * k}
}
//
func (p Moint) String() string {
x := strconv.FormatFloat(p.X, 'f', 4, 64)
y := strconv.FormatFloat(p.Y, 'f', 4, 64)
return fmt.Sprintf("(%s,%s)", x, y)
}
// Subtract other Moint from this Moint
func (p Moint) Sub(o Moint) Moint {
return Moint{p.X - o.X, p.Y - o.Y}
}
|
liu-xiao-ke/KRenderer | src/Integrators/SimpleIntegrator.cpp | <reponame>liu-xiao-ke/KRenderer
#include<nori/integrator.h>
NORI_NAMESPACE_BEGIN
class SimpleIntegrator : public Integrator {
public:
SimpleIntegrator(const PropertyList& props) {
lightPos = props.getPoint("position");
lightE = props.getColor("energy");
}
Color3f Li(const Scene* scene, Sampler* sampler, const Ray3f& ray) const {
Intersection its;
if (!scene->rayIntersect(ray, its))
return Color3f(0.0f);
Vector3f shadowRayDir = lightPos - its.p;
Ray3f shadowRay(its.p, shadowRayDir.normalized());
float cosine = shadowRayDir.normalized().dot(its.shFrame.n.normalized());
float v = scene->rayIntersect(shadowRay) ? 0.0f : 1.0f;
float d = shadowRayDir.norm();
Color3f li = lightE * std::fmax(0.0f, cosine) * v * INV_PI * INV_PI / (4 * d * d);
return li.clamp();
}
std::string toString() const {
return tfm::format(
"SimpleIntegrator["
" light position = \"%s\","
" light energy = \"%s\""
"]", lightPos, lightE);
}
protected:
Point3f lightPos;
Color3f lightE;
};
NORI_REGISTER_CLASS(SimpleIntegrator, "simple")
NORI_NAMESPACE_END |
Oxydros/Volt | Volt/src/Volt/Graphics/OpenGL/Shader.cpp | #include "vpch.h"
#include "Volt/Graphics/OpenGL/Shader.hpp"
#include <glad/glad.h>
namespace Volt::Graphics::OpenGL
{
GLuint CompileShader(GLchar const *src, GLenum shaderType, int &success, char *infoLog)
{
GLuint vertexShaderID = glCreateShader(shaderType);
if (vertexShaderID == 0)
{
success = 0;
std::strncpy(infoLog, "Call to glCreateShader failed", 512);
return -1;
}
glShaderSource(vertexShaderID, 1, &src, NULL);
glCompileShader(vertexShaderID);
glGetShaderiv(vertexShaderID, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShaderID, 512, NULL, infoLog);
}
return vertexShaderID;
}
Shader::Shader(std::string const &shaderPath)
: m_shaderPath(shaderPath) ,m_programId(0)
{
std::string vertexSrc, pixelSrc;
Shader::GetSourcesFromFile(shaderPath, vertexSrc, pixelSrc);
int success;
char infoLog[512];
GLuint vertexShaderID = CompileShader(vertexSrc.c_str(), GL_VERTEX_SHADER, success, infoLog);
if (!success)
{
VOLT_ASSERT(false, "Error while compiling vertex shader : {}", infoLog);
}
GLuint pixelShaderID = CompileShader(pixelSrc.c_str(), GL_FRAGMENT_SHADER, success, infoLog);
if (!success)
{
VOLT_ASSERT(false, "Error while compiling pixel shader : {}", infoLog);
}
m_programId = glCreateProgram();
glAttachShader(m_programId, vertexShaderID);
glAttachShader(m_programId, pixelShaderID);
glLinkProgram(m_programId);
glGetProgramiv(m_programId, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(m_programId, 512, NULL, infoLog);
VOLT_ASSERT(false, "Error while LINKING shaders in program : {}", infoLog);
}
glDeleteShader(vertexShaderID);
glDeleteShader(pixelShaderID);
}
Shader::~Shader()
{
glDeleteProgram(m_programId);
}
void Shader::Bind()
{
glUseProgram(m_programId);
}
void Shader::Reload()
{
std::string vertexSrc, pixelSrc;
VOLT_DEB("Reloading shader {}...", m_shaderPath);
Shader::GetSourcesFromFile(m_shaderPath, vertexSrc, pixelSrc);
int success;
char infoLog[512];
GLuint vertexShaderID = CompileShader(vertexSrc.c_str(), GL_VERTEX_SHADER, success, infoLog);
if (!success)
{
VOLT_DEB("Error while compiling vertex shader : {}", infoLog);
return;
}
GLuint pixelShaderID = CompileShader(pixelSrc.c_str(), GL_FRAGMENT_SHADER, success, infoLog);
if (!success)
{
VOLT_DEB("Error while compiling pixel shader : {}", infoLog);
return;
}
//Re-create program
glDeleteProgram(m_programId);
uint32_t new_program = glCreateProgram();
glAttachShader(new_program, vertexShaderID);
glAttachShader(new_program, pixelShaderID);
glLinkProgram(new_program);
glGetProgramiv(new_program, GL_LINK_STATUS, &success);
glDeleteShader(vertexShaderID);
glDeleteShader(pixelShaderID);
if(!success) {
glGetProgramInfoLog(new_program, 512, NULL, infoLog);
VOLT_DEB("Error while LINKING shaders in program : {}", infoLog);
return;
}
glDeleteProgram(m_programId);
VOLT_DEB("Shader successfully recompiled");
m_programId = new_program;
}
//Quick and dirty to setup camera system asap
void Shader::SetInt(std::string const &uniform_name, int value)
{
int uniformLocation = glGetUniformLocation(m_programId, uniform_name.c_str());
VOLT_ASSERT(uniformLocation != -1, "Unable to find uniform {} in shader", uniform_name);
glUniform1i(uniformLocation, value);
}
void Shader::SetFloat(std::string const &uniform_name, float value)
{
int uniformLocation = glGetUniformLocation(m_programId, uniform_name.c_str());
VOLT_ASSERT(uniformLocation != -1, "Unable to find uniform {} in shader", uniform_name);
glUniform1f(uniformLocation, value);
}
void Shader::SetVec3f(std::string const &uniform_name, glm::vec3 const &value)
{
int uniformLocation = glGetUniformLocation(m_programId, uniform_name.c_str());
VOLT_ASSERT(uniformLocation != -1, "Unable to find uniform {} in shader", uniform_name);
glUniform3f(uniformLocation, value.x, value.y, value.z);
}
void Shader::SetVec4f(std::string const &uniform_name, glm::vec4 const &value)
{
int uniformLocation = glGetUniformLocation(m_programId, uniform_name.c_str());
VOLT_ASSERT(uniformLocation != -1, "Unable to find uniform {} in shader", uniform_name);
glUniform4f(uniformLocation, value.x, value.y, value.z, value.w);
}
void Shader::SetMat3f(std::string const &uniform_name, glm::mat3 const &value)
{
int uniformLocation = glGetUniformLocation(m_programId, uniform_name.c_str());
VOLT_ASSERT(uniformLocation != -1, "Unable to find uniform {} in shader", uniform_name);
glUniformMatrix3fv(uniformLocation, 1, GL_FALSE, &value[0][0]);
}
void Shader::SetMat4f(std::string const &uniform_name, glm::mat4 const &value)
{
int uniformLocation = glGetUniformLocation(m_programId, uniform_name.c_str());
VOLT_ASSERT(uniformLocation != -1, "Unable to find uniform {} in shader", uniform_name);
glUniformMatrix4fv(uniformLocation, 1, GL_FALSE, &value[0][0]);
}
}
Volt::Graphics::Shader::ShaderPtr Volt::Graphics::Shader::CreateShader(std::string const &shaderFile)
{
return std::make_unique<Volt::Graphics::OpenGL::Shader>(shaderFile);
} |
mindthegab/symphony-java-toolkit | symphony-api-spring-boot-starter/src/main/java/com/github/deutschebank/symphony/spring/api/ApiInstanceFactory.java | package com.github.deutschebank.symphony.spring.api;
import javax.net.ssl.TrustManager;
import com.github.deutschebank.symphony.spring.api.properties.PodProperties;
import com.symphony.api.id.SymphonyIdentity;
/**
* Interface providing an {@link ApiInstance}. Provides the {@link ApiInstance} for a single Symphony pod.
*
* @author robmoffat
*
*/
public interface ApiInstanceFactory {
public ApiInstance createApiInstance(SymphonyIdentity id, PodProperties pp, TrustManager[] trustManagers) throws Exception;
}
|
secure-software-engineering/CogniCrypt-IntelliJ | src/main/java/de/fraunhofer/iem/icognicrypt/IdeSupport/projects/Outputs/IOutputFinderInternal.java | <reponame>secure-software-engineering/CogniCrypt-IntelliJ
package de.fraunhofer.iem.icognicrypt.IdeSupport.projects.Outputs;
import com.intellij.openapi.project.Project;
import de.fraunhofer.iem.icognicrypt.exceptions.CogniCryptException;
import org.jetbrains.annotations.NotNull;
import javax.naming.OperationNotSupportedException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Set;
interface IOutputFinderInternal
{
@NotNull Iterable<File> GetOutputFiles(Project project) throws OperationNotSupportedException, IOException, CogniCryptException;
@NotNull Iterable<File> GetOutputFiles(Project project, Set<OutputFinderOptions.Flags> options) throws CogniCryptException, IOException, OperationNotSupportedException;
@NotNull Iterable<File> GetOutputFilesFromDialog(Project project);
}
|
CleverCloud/clevercloud-go | clevercloud/model_deployment_info_view.go | /*
* Clever-Cloud API
*
* Public API for managing Clever-Cloud data and products
*
* API version: 1.0.1
* Contact: <EMAIL>
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package clevercloud
// DeploymentInfoView struct for DeploymentInfoView
type DeploymentInfoView struct {
Shutdownable bool `json:"shutdownable,omitempty"`
Type string `json:"type,omitempty"`
RepoState string `json:"repoState,omitempty"`
Url string `json:"url,omitempty"`
HttpUrl string `json:"httpUrl,omitempty"`
}
|
nark/magicbox | db/migrate/20201212012937_notification_become_notifiable.rb | class NotificationBecomeNotifiable < ActiveRecord::Migration[5.2]
def change
rename_column :notifications, :alert_id, :notifiable_id
add_column :notifications, :notifiable_type, :string, default: "Alert"
end
end
|
rudylee/expo | ios/Pods/Headers/Public/ABI36_0_0ExpoKit/ABI36_0_0EXScopedFacebook.h | <filename>ios/Pods/Headers/Public/ABI36_0_0ExpoKit/ABI36_0_0EXScopedFacebook.h
// Copyright 2015-present 650 Industries. All rights reserved.
#if __has_include(<ABI36_0_0EXFacebook/ABI36_0_0EXFacebook.h>)
#import <Foundation/Foundation.h>
#import <ABI36_0_0EXFacebook/ABI36_0_0EXFacebook.h>
#import <ABI36_0_0UMCore/ABI36_0_0UMAppLifecycleListener.h>
#import <ABI36_0_0UMCore/ABI36_0_0UMModuleRegistryConsumer.h>
@interface ABI36_0_0EXScopedFacebook : ABI36_0_0EXFacebook <ABI36_0_0UMAppLifecycleListener, ABI36_0_0UMModuleRegistryConsumer>
- (instancetype)initWithExperienceId:(NSString *)experienceId andParams:(NSDictionary *)params;
@end
#endif
|
pvtbox/pvtbox-android | app/src/main/java/net/pvtbox/android/ui/start/AddToPvtboxActivity.java | package net.pvtbox.android.ui.start;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import net.pvtbox.android.R;
import net.pvtbox.android.application.Const;
import net.pvtbox.android.tools.ShareActivityHelper;
/**
*
* Pvtbox. Fast and secure file transfer & sync directly across your devices.
* Copyright © 2020 Pb Private Cloud Solutions Ltd.
*
* 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.
*
**/
public class AddToPvtboxActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
setTheme(R.style.AppTheme_PBNoActionBar);
super.onCreate(savedInstanceState);
Intent intent = getIntent();
ShareActivityHelper.handleShareIntent(intent, this);
intent.putExtra(Const.SHARING_ENABLE, false);
intent.setComponent(new ComponentName(this, StartActivity.class));
startActivity(intent);
finish();
}
}
|
SpartanRefactoring/spartanizer | spartanizer-plugin/src/main/java/il/org/spartan/spartanizer/research/nanos/methods/DoNothingReturnThis.java | <reponame>SpartanRefactoring/spartanizer
package il.org.spartan.spartanizer.research.nanos.methods;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import il.org.spartan.spartanizer.research.nanos.common.JavadocMarkerNanoPattern;
/** Method returning this without doing anything else
* @author <NAME> */
public class DoNothingReturnThis extends JavadocMarkerNanoPattern {
private static final long serialVersionUID = 0x5971968DD518FBE0L;
@Override protected boolean prerequisites(final MethodDeclaration ¢) {
return hazOneStatement(¢)//
&& returnsThis(¢);
}
@Override public Category category() {
return Category.Default;
}
}
|
fanofsherlock/Object_Oriented_Designs | src/main/java/designs/bank/Transactions/TransactionType.java | package designs.bank.Transactions;
public enum TransactionType {
WITHDRAW, DEPOSIT;
@Override
public String toString() {
return this.name();
}
}
|
kibertoad/swampmachine-scripting | src/main/java/net/kiberion/swampmachine/templating/mustache/MustacheTemplate.java | <reponame>kibertoad/swampmachine-scripting
package net.kiberion.swampmachine.templating.mustache;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import com.github.mustachejava.Mustache;
import net.kiberion.swampmachine.templating.api.Template;
/**
* Mustache-based template implementation.
*
* @author kibertoad
* @see <a href="https://github.com/spullara/mustache.java</a>
*/
public class MustacheTemplate implements Template {
private final Mustache mustache;
public MustacheTemplate(Mustache mustache) {
this.mustache = mustache;
}
@Override
public String eval(Map<String, Object> variableMap) {
try (Writer writer = new StringWriter()) {
mustache.execute(writer, variableMap);
writer.flush();
return writer.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
|
osgvsun/lubanlou | usercenter-front/src/main/resources/static/modules/openReservation/myAppointmentDetail.js | <reponame>osgvsun/lubanlou
layui.use(['form', 'element', 'laydate', 'laypage', 'table', 'layer'], function() {
var $ = layui.jquery,
admin = layui.admin,
form = layui.form,
element = layui.element,
laydate = layui.laydate,
laypage = layui.laypage,
table = layui.table,
layer = layui.layer;
//向世界问个好
//layer.msg('');
form.render(null, 'myappointmentdetailbox');
let obj = {};
if (detail) {
obj = JSON.parse(detail);
}
//信息
form.val('myappointmentdetailbox', {
"type": obj.appTypeName,
"person": obj.appUser,
"tel": obj.appUserPhone,
"info": obj.appReason,
"lab": obj.deviceName,
"date": obj.appDate,
"time": obj.appTime,
"state": obj.appStutas
});
}); |
zhangyifei/mud | d/changan/npc/huangyi.c | <reponame>zhangyifei/mud<filename>d/changan/npc/huangyi.c
//huangyi.c
inherit NPC;
#include <ansi.h>
void create()
{
set_name(HIY "黄衣" NOR, ({ "<NAME>" }) );
set("title", CYN "群玉八娇" NOR);
set("gender", "女性" );
set("age", 22);
set("str", 30);
set("per", 40);
set("long", @LONG
一个全身上下穿着黄装,领露酥胸的美女.
LONG
);
set("combat_exp", 10);
set("attitude", "friendly");
setup();
set("chat_chance", 15);
set("chat_msg", ({
"黄衣说道:我说湘湘妹子,你就从了吧!干我们这行有什么不好的,吃好的,穿好的,要什么有什么!\n",
"黄衣叹道:唉!已经劝了这丫头三天了,我这张嘴都磨破了,她就是不出去接客!\n",
"黄衣对湘湘说道:你就乖乖儿的听我的话吧!别指望有谁会来救你出去了!\n",
}) );
setup();
carry_object(__DIR__"obj/skirt")->wear();
}
int accept_fight(object me)
{
command("say 小女子哪里是您的对手?");
return 0;
}
int accept_kill(object me)
{
object ob;
if (is_fighting()) return 1;
if (query("called")) return 1;
command("say 要杀人了,快来人救命啊!");
ob = present("bao biao");
if (! ob)
{
seteuid(getuid());
ob=new(__DIR__"baobiao");
ob->move(environment());
}
message_vision(HIC "\n忽然从门外冲进来几个保镖,对$N"
HIC "大喊一声“干什么?在这儿闹事,想"
"找死吗?\n\n" NOR, me);
ob->kill_ob(me);
ob->set_leader(me);
me->kill_ob(ob);
set("called", 1);
call_out("regenerate", 200);
return 0;
}
int regenerate()
{
set("called", 0);
return 1;
}
|
LineGames/Leggiero | Engine/Modules/LUI/Element/UIElementSingleSimpleButton.h | <gh_stars>10-100
////////////////////////////////////////////////////////////////////////////////
// Element/UIElementSingleSimpleButton.h (Leggiero/Modules - LegacyUI)
//
// Single button element to process simple interaction
////////////////////////////////////////////////////////////////////////////////
#ifndef __LM_LUI__ELEMENT__UI_ELEMENT_SINGLE_SIMPLE_BUTTON_H
#define __LM_LUI__ELEMENT__UI_ELEMENT_SINGLE_SIMPLE_BUTTON_H
// Leggiero.Basic
#include <Basic/LeggieroBasic.h>
// Standard Library
#include <functional>
#include <memory>
// Leggiero.Utility
#include <Utility/Sugar/EnumClass.h>
// Leggiero.Graphics
#include <Graphics/Common/GLColor.h>
// Leggiero.LegacyUI
#include "../Common/UICommonTypes.h"
#include "../UIObject.h"
namespace Leggiero
{
namespace LUI
{
// Forward Declarations
class UIManager;
class ValuedTouchComponent;
class UITouch;
namespace Element
{
// Simple UI Button
class SingleSimpleButton
: public UIObject
{
public:
enum class StateType
{
kNormal = 0x0,
kPushed = 0x1,
kActive = 0x2,
kDisabled = 0x4,
};
public:
// Rendering Controller Definition for interaction
class RenderingController
{
public:
virtual void UpdateFrameSelf(GameTimeClockType::duration frameInterval, StateType currentState) { }
virtual void FrameGraphicPrepare(const UIRenderer &renderer, UIVector2D offsetPosition, const IUIClipping &effectiveClipping) { }
};
public:
using OnClickHandlerType = std::function<void(std::shared_ptr<SingleSimpleButton>)>;
public:
SingleSimpleButton(std::shared_ptr<UIManager> ownerManager, UICoordinateType touchWidth, UICoordinateType touchHeight,
OnClickHandlerType onClick = ms_dummyOnClickHandler,
std::shared_ptr<RenderingController> renderingController = nullptr);
SingleSimpleButton(std::shared_ptr<UIManager> ownerManager, UICoordinateType touchWidth, UICoordinateType touchHeight, UICoordinateType touchCoverWidth, UICoordinateType touchCoverHeight,
OnClickHandlerType onClick = ms_dummyOnClickHandler,
std::shared_ptr<RenderingController> renderingController = nullptr);
virtual ~SingleSimpleButton();
protected:
SingleSimpleButton(std::shared_ptr<UIManager> ownerManager);
public: // UIObject
virtual std::shared_ptr<UIObject> Clone() const override;
virtual void _UpdateFrameSelf(GameTimeClockType::duration frameInterval) override;
virtual void FrameGraphicPrepare(const UIRenderer &renderer, UIVector2D offsetPosition, const IUIClipping &effectiveClipping) override;
public:
void SetOnClickHandler(OnClickHandlerType handler) { m_onClickHandlerFunc = handler; }
void DiscardOnClickHandler() { m_onClickHandlerFunc = ms_dummyOnClickHandler; }
void SetRenderingController(std::shared_ptr<RenderingController> controller);
bool IsActiveState() const { return m_isActive; }
void SetIsActive(bool isActive) { m_isActive = isActive; }
public:
void SetTouchWidth(UICoordinateType width);
void SetTouchHeight(UICoordinateType height);
protected:
void _OnTouchDown(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time, bool isCoveredByDescendant);
void _OnTouchIn(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time, bool isFirstIn, bool isCoveredByDescendant);
void _OnTouchOut(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time);
void _OnTouchCovered(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time);
void _OnTouchCancel(std::shared_ptr<UITouch> touch, GameTimeClockType::time_point time);
void _OnTouchUp(std::shared_ptr<UITouch> touch, UICoordinateType x, UICoordinateType y, GameTimeClockType::time_point time);
void _OnPrimaryTouchLose(std::shared_ptr<UITouch> touch);
void _SetTouchPressedState(bool isPressed);
protected:
UICoordinateType m_width;
UICoordinateType m_height;
UICoordinateType m_coverWidth;
UICoordinateType m_coverHeight;
protected:
std::shared_ptr<UIObject> m_touchVirtualObject;
std::shared_ptr<RenderingController> m_renderingController;
protected:
static OnClickHandlerType ms_dummyOnClickHandler;
OnClickHandlerType m_onClickHandlerFunc;
std::shared_ptr<UITouch> m_processingTouch;
bool m_isPressed;
bool m_isActive;
};
MAKE_ENUM_FLAG(SingleSimpleButton::StateType);
}
}
}
#endif
|
seeclong/apollo | modules/map/tools/map_datachecker/server/main.cc | <filename>modules/map/tools/map_datachecker/server/main.cc
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/cyber.h"
#include "modules/map/tools/map_datachecker/server/worker.h"
int main(int argc, char** argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
AINFO << "cyber init";
if (apollo::cyber::Init(argv[0])) {
AINFO << "init succeed";
} else {
AERROR << "init failed";
}
google::SetStderrLogging(FLAGS_minloglevel);
AINFO << "starting worker";
apollo::hdmap::Mapdatachecker worker;
if (!worker.Start()) {
AFATAL << "Start Mapdatachecker Failed!";
return -1;
}
apollo::cyber::WaitForShutdown();
return 0;
}
|
andyguwc/flask-hackernews-clone | flask_hackernews_clone/blueprints/user/forms.py | <gh_stars>0
# -*- coding: utf-8 -*-
"""User forms."""
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, Email, EqualTo, Length
from .models import User
class EditProfileForm(FlaskForm):
first_name = StringField("First name", validators=[Length(0, 30)])
last_name = StringField("Last name", validators=[Length(0, 30)])
about = TextAreaField("About me")
submit = SubmitField("Submit")
|
4finance/micro-infra-spring | micro-infra-spring-base/src/main/java/com/ofg/infrastructure/web/logging/HttpDataFactory.java | <gh_stars>100-1000
package com.ofg.infrastructure.web.logging;
import com.ofg.infrastructure.web.logging.wrapper.HttpServletRequestLoggingWrapper;
import com.ofg.infrastructure.web.logging.wrapper.HttpServletResponseLoggingWrapper;
import feign.Request;
import feign.Response;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import static com.ofg.infrastructure.web.logging.HttpDataExtractor.extractContent;
import static com.ofg.infrastructure.web.logging.HttpDataExtractor.extractHeaders;
import static com.ofg.infrastructure.web.logging.HttpDataExtractor.extractMethod;
import static com.ofg.infrastructure.web.logging.HttpDataExtractor.extractPath;
import static com.ofg.infrastructure.web.logging.HttpDataExtractor.extractResponseCode;
import static com.ofg.infrastructure.web.logging.HttpDataExtractor.extractStatus;
import static com.ofg.infrastructure.web.logging.HttpDataExtractor.extractUrl;
class HttpDataFactory {
static HttpData createHttpData(HttpRequest request, byte[] content){
return new HttpData(extractHeaders(request),
extractUrl(request),
extractPath(request),
extractMethod(request),
new String(content));
}
static HttpData createHttpData(HttpServletRequestLoggingWrapper request){
return new HttpData(extractHeaders(request),
extractUrl(request),
extractPath(request),
extractMethod(request),
extractContent(request));
}
static HttpData createHttpData(Request request) {
return new HttpData(extractHeaders(request),
extractUrl(request),
extractPath(request),
extractMethod(request),
extractContent(request));
}
static HttpData createHttpData(HttpServletResponseLoggingWrapper response){
return new HttpData(extractHeaders(response),
extractStatus(response),
extractContent(response));
}
static HttpData createHttpData(ClientHttpResponse response){
return new HttpData(response.getHeaders().toSingleValueMap(),
extractResponseCode(response),
extractContent(response));
}
static HttpData createHttpData(Response response) {
return new HttpData(extractHeaders(response), extractStatus(response), extractContent(response));
}
}
|
mooreliu/SalesMarket | app/src/main/java/com/mooreliu/widget/BaseActivity.java | package com.mooreliu.widget;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import com.mooreliu.AppContext;
import com.mooreliu.R;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.squareup.leakcanary.RefWatcher;
/**
* Activity 基础类
* Created by liuyi on 15/8/29.
*/
public abstract class BaseActivity extends ActionBarActivity {
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle onSavedInstance) {
super.onCreate(onSavedInstance);
AppContext.setActiveContext(this);
}
@Override
public void setContentView(int layoutId) {
super.setContentView(layoutId);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
findView();
initView();
setOnClick();
setStatusBarView();
}
public void setToolBarTitle(String title) {
if (!TextUtils.isEmpty(title)) mToolbar.setTitle(title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
setBackListener();
}
protected void setBackListener() {
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setBackEvent();
}
});
}
/**
* 设置返回按钮的事件,默认是返回到前一个界面
*/
protected void setBackEvent() {
onBackPressed();
}
/**
* 设置状态栏的颜色,目前只是在4.4上面有效
*/
protected void setStatusBarView() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setNavigationBarTintEnabled(false);
tintManager.setTintColor(getResources().getColor(R.color.DodgerBlue));
}
}
protected abstract void findView();
protected abstract void initView();
protected abstract void setOnClick();
@Override
protected void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = AppContext.getRefWatcher(this);
refWatcher.watch(this);
}
}
|
Tupiet/nsmbw-mod | Kamek/tools/NewerSMBW-LLVM/include/llvm/MC/MCInstrAnalysis.h | //===-- llvm/MC/MCInstrAnalysis.h - InstrDesc target hooks ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MCInstrAnalysis class which the MCTargetDescs can
// derive from to give additional information to MC.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
namespace llvm {
class MCInstrAnalysis {
protected:
friend class Target;
const MCInstrInfo *Info;
public:
MCInstrAnalysis(const MCInstrInfo *Info) : Info(Info) {}
virtual ~MCInstrAnalysis() {}
virtual bool isBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isBranch();
}
virtual bool isConditionalBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isConditionalBranch();
}
virtual bool isUnconditionalBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isUnconditionalBranch();
}
virtual bool isIndirectBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isIndirectBranch();
}
virtual bool isCall(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isCall();
}
virtual bool isReturn(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isReturn();
}
virtual bool isTerminator(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isTerminator();
}
/// evaluateBranch - Given a branch instruction try to get the address the
/// branch targets. Return true on success, and the address in Target.
virtual bool
evaluateBranch(const MCInst &Inst, uint64_t Addr, uint64_t Size,
uint64_t &Target) const;
};
}
|
dmytrov/stochasticcontrol | code/optotrak/datarecorder.py | <filename>code/optotrak/datarecorder.py
import time
import gc
from threading import Thread
import wrapt
import numpy as np
import optotrak.ndiapiconstants
import optotrak.databuffer as db
from utils.realtimeclock import rtc
import logging
import utils.logger as ulog
import gp.equations as gpe
ndi = optotrak.ndiapiconstants.NDI
class OptotrakRealtimeData(object):
"""
Single frame data storage
"""
def __init__(self, framenr, data, timestamp):
self.framenr = framenr
self.data = data
self.timestamp = timestamp
def as_numpy(self):
return np.array(self.data)
class TimestampedDataBuffer(db.DataBuffer):
def __init__(self, capacity=1, dataclass=OptotrakRealtimeData):
super(TimestampedDataBuffer, self).__init__(capacity, dataclass)
@wrapt.synchronized
def select_values_by_timestamp(self, t=0.0, halfnsamples=2):
"""
Returns 2*halfnsamples
---------------------------------> t
| | | | |
t
"""
#t = rtc() + dt # requested data timestamp
i = 0
while i < len(self.buffer) and self.buffer[i].timestamp < t:
i += 1
i0 = max(0, i-halfnsamples)
i1 = min(len(self.buffer), i+halfnsamples)
res = self.buffer[i0:i1]
return res
class OptotrakDataRecorder(object):
def __init__(self, optotrak=None):
self.optotrak = optotrak
self.realtimedatabuffer = TimestampedDataBuffer(capacity=10, dataclass=OptotrakRealtimeData)
self.pullingthread = None
self.pullingthreadactiveflag = False
self.nplog = None
self._verbose = False
self._sleep_period = None
@property
def sleep_period(self):
return self._sleep_period
@sleep_period.setter
def sleep_period(self, value):
self._sleep_period = value
@property
def verbose(self):
return self._verbose
@verbose.setter
def verbose(self, value):
self._verbose = value
def init_optotrak(self, nplogfilename=None):
if nplogfilename is None:
nplogfilename = "datarecorder.pkl"
self.nplog = ulog.setup_numpy_logger(__name__, nplogfilename=nplogfilename)
try:
res = self.optotrak.TransputerLoadSystem("system")
if res != 0: raise IOError(res)
time.sleep(1.0)
res = self.optotrak.TransputerInitializeSystem(ndi.OPTO_LOG_ERRORS_FLAG)
if res != 0: raise IOError(res)
res = self.optotrak.OptotrakLoadCameraParameters("standard")
if res != 0: raise IOError(res)
except IOError as err:
print("OptotrakDataRecorder: failed to init with error: {}".format(self.optotrak.OptotrakGetErrorString()))
print("OptotrakDataRecorder: shutting down Optotrak after the error...")
self.optotrak.OptotrakDeActivateMarkers()
self.optotrak.TransputerShutdownSystem()
raise
def setup_optotrak_collection(self, nummarkers=4, collecttime=10.0,
datafps=120, buffer_capacity=10,
stream_push_mode=0,
datafilename=None):
"""
Optotrak collection must be setup last
"""
if datafilename is None:
datafilename = "REC#001.OPT"
self.realtimedatabuffer.capacity = buffer_capacity
try:
res = self.optotrak.OptotrakSetupCollection(
nummarkers, # Number of markers in the collection.
float(datafps), # Frequency to collect data frames at.
2500.0, # Marker frequency for marker maximum on-time.
30, # Dynamic or Static Threshold value to use.
160, # Minimum gain code amplification to use.
stream_push_mode, # Stream mode for the data buffers.
0.35, # Marker Duty Cycle to use.
7.0, # Voltage to use when turning on markers.
collecttime, # Number of seconds of data to collect.
0.0, # Number of seconds to pre-trigger data by.
ndi.OPTOTRAK_BUFFER_RAW_FLAG | ndi.OPTOTRAK_GET_NEXT_FRAME_FLAG)
if res != 0: raise IOError(res)
time.sleep(1.0)
res = self.optotrak.OptotrakActivateMarkers()
if res != 0: raise IOError(res)
res = self.optotrak.DataBufferInitializeFile(ndi.OPTOTRAK, datafilename.encode("ascii", "ignore"))
if res != 0: raise IOError(res)
except IOError as err:
print("OptotrakDataRecorder: failed to setup Optotrak collection with error: {}".format(self.optotrak.OptotrakGetErrorString()))
print("OptotrakDataRecorder: shutting down Optotrak after the error...")
self.optotrak.OptotrakDeActivateMarkers()
self.optotrak.TransputerShutdownSystem()
raise
def setup_odau_collection(self, numchannels=4, collecttime=10.0,
odauID=ndi.ODAU1,
analog_gain=1, # divider for [-10, 10] Volts range
digital_port_mode=ndi.ODAU_DIGITAL_PORT_OFF,
collection_frequency=5000.0,
scan_frequqncy=90000.0,
stream_push_mode=0,
datafilename=None):
"""
ODAU collection must be setup first
"""
if datafilename is None:
datafilename = "REC#001.ODAU"
try:
res = self.optotrak.OdauSetupCollection(
odauID, # Id the ODAU the parameters are for.
numchannels, # Number of analog channels to collect.
analog_gain, # Gain to use for the analog channels.
digital_port_mode, # Mode for the Digital I/O port.
float(collection_frequency), # Frequency to collect data frames at.
float(scan_frequqncy), # Frequency to sample the channels at within one frame.
stream_push_mode, # Stream mode for the data buffers.
float(collecttime), # Number of seconds of data to collect.
0.0, # Number of seconds to pre-trigger data by.
0)
if res != 0: raise IOError(res)
res = self.optotrak.DataBufferInitializeFile(odauID, datafilename.encode("ascii", "ignore"))
if res != 0: raise IOError(res)
except IOError as err:
print("OptotrakDataRecorder: failed to setup ODAU collection with error: {}".format(self.optotrak.OptotrakGetErrorString()))
print("OptotrakDataRecorder: shutting down Optotrak after the error...")
self.optotrak.OptotrakDeActivateMarkers()
self.optotrak.TransputerShutdownSystem()
raise
def _pulling_thread_function(self):
try:
gc.disable()
self.pullingthreadactiveflag = True
res = self.optotrak.DataBufferStart()
if res != 0: raise Exception(res)
res = self.optotrak.RequestLatest3D()
if res != 0: raise Exception(res)
callcounterDataBufferWriteData = 0
uSpoolComplete = False
t0 = time.time()
prevFramenumber = 0
while not uSpoolComplete:
(res, uRealtimeDataReady, uSpoolComplete,
uSpoolStatus, nFrames) = self.optotrak.DataBufferWriteData()
if res != 0: raise Exception(res)
callcounterDataBufferWriteData += 1
if uRealtimeDataReady:
timestamp = rtc()
(res, uFrameNumber, uElements, uFlags,
p3dData) = self.optotrak.DataReceiveLatest3D()
if res != 0: raise Exception(res)
if self.verbose:
print("Frame Number: ", uFrameNumber)
print("Elements : ", uElements)
print("Flags : ", uFlags)
print(p3dData)
framesdelta = uFrameNumber - prevFramenumber
prevFramenumber = uFrameNumber
if framesdelta != 1:
print("Frame: {}. SKIPPED FRAMES: {}".format(uFrameNumber, framesdelta-1))
realtimedata = OptotrakRealtimeData(uFrameNumber, p3dData, timestamp)
self.realtimedatabuffer.add(realtimedata)
self.nplog.info(ulog.NPRecord("realtimedata", realtimedata))
res = self.optotrak.RequestLatest3D()
if res != 0: raise Exception(res)
if not self.pullingthreadactiveflag:
res = self.optotrak.DataBufferStop()
if res != 0: raise Exception(res)
uRealtimeDataReady = 0
if self._sleep_period is not None:
time.sleep(self._sleep_period)
t1 = time.time()
dt = t1 - t0
print("OptotrakDataRecorder: pulling complete.")
print("DataBufferWriteData: {} calls/sec".format(callcounterDataBufferWriteData/dt))
except IOError as err:
print("OptotrakDataRecorder: failed to pull with error: {}".format(self.optotrak.OptotrakGetErrorString()))
raise
finally:
gc.enable()
print("OptotrakDataRecorder: shutting down Optotrak...")
self.optotrak.OptotrakDeActivateMarkers()
self.optotrak.TransputerShutdownSystem()
print("OptotrakDataRecorder: thread finished")
def start_pulling_thread(self):
self.pullingthread = Thread(target=self._pulling_thread_function)
self.pullingthread.start()
def stop_pulling_thread(self):
if self.pullingthread is not None:
self.pullingthreadactiveflag = False
self.pullingthread.join()
def waitfillbuffer(self):
while self.realtimedatabuffer.is_empty() and self.pullingthread is not None and self.pullingthread.isAlive():
time.sleep(0.1)
return not self.realtimedatabuffer.is_empty()
def select_values_by_timestamp(self, t=0.0, halfnsamples=3):
if self.pullingthread is not None and self.pullingthread.isAlive():
samples = self.realtimedatabuffer.select_values_by_timestamp(t, halfnsamples)
x = [sample.timestamp for sample in samples]
y = [sample.data for sample in samples]
return (x, y)
else:
return (None, None)
def get_value_by_timestamp(self, t, halfnsamples=3):
x, y = self.select_values_by_timestamp(t, halfnsamples)
if x is not None:
return OptotrakDataRecorder.GP_prediction(x, y, t).tolist()
else:
return None
def get_value_by_now_plus_dt(self, dt):
return self.get_value_by_timestamp(rtc() + dt)
def shutdown_on_disconnect(self):
return True
@classmethod
def GP_prediction(cls, x, y, xstar, visibleonly=True):
d = len(y[0])
x = np.array([x]).T
y = np.array([np.ravel(yi) for yi in y])
if visibleonly:
ibad = y < -1e20
ma = np.ma.array(y, mask=ibad)
ms = np.mean(ma, axis=0)
y[ibad] = (np.ones_like(y) * ms[np.newaxis, :])[ibad]
value = gpe.conditional(x, y, np.array([[xstar]]))
if visibleonly:
ibad = value < -1e20
value[ibad] = np.nan
j = np.ones_like(value) * ms[np.newaxis, :]
value[j.mask] = np.nan
value = np.reshape(value, [d, -1])
return value
|
ephemeralin/vpiliugin | chapter_002/src/test/java/ru/job4j/tracker/TrackerPostgresTest.java | package ru.job4j.tracker;
import org.junit.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by ephemeralin on 21.05.17.
*/
public class TrackerPostgresTest {
/**
* Tracker test instance.
*/
private TrackerPostgres tracker;
/**
* Prepare test environment.
*/
@BeforeClass
public static void prepareTestEnvironment() {
createTestDatabase();
}
/**
* Prepare test tracker.
*/
@Before
public void prepareTestTracker() {
String resourcesPath = "resources/tracker_test/";
this.tracker = new TrackerPostgres(resourcesPath);
try {
this.tracker.initConnection();
this.tracker.prepare();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Create test database.
*/
public static void createTestDatabase() {
String script = "CREATE DATABASE tracker_test"
+ " WITH "
+ " OWNER = postgres"
+ " ENCODING = 'UTF8'"
+ " CONNECTION LIMIT = -1;";
try {
executeScript(script);
System.out.println("Test database created SUCCESSFULLY.");
} catch (SQLException e) {
System.out.println("Test database create FAILED.");
e.printStackTrace();
}
}
/**
* Drop test database.
*/
public static void dropTestDatabase() {
String script = "DROP DATABASE tracker_test;";
try {
executeScript(script);
System.out.println("Test database drop SUCCESS.");
} catch (SQLException e) {
System.out.println("Test database drop FAILED.");
e.printStackTrace();
}
}
/**
* Execute script.
*
* @param script the script
* @throws SQLException the sql exception
*/
public static void executeScript(String script) throws SQLException {
Connection connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/", "postgres",
"password");
Statement statement = connection.createStatement();
statement.executeUpdate(script);
if (connection != null) {
connection.close();
}
}
/**
* When add new item then tracker has same item.
* Test for methods: add, findAll
*/
@Test
public void whenAddNewItemThenTrackerHasSameItem() {
Item item = new Item("test1", "test item 1", "test description");
tracker.add(item);
assertThat(tracker.findAll().get(0).getName(), is("test item 1"));
}
/**
* When delete first item then tracker does not have any items.
* Test for methods: add, delete
*/
@Test
public void whenDeleteFirstItemThenTrackerDoesNotHaveItems() {
Item item = new Item("test1", "test item 1", "test description");
tracker.add(item);
tracker.delete(item);
assertThat(tracker.findAll().size(), is(0));
}
/**
* When find by name then tracker returns the item.
* Test for methods: add, findByName
*/
@Test
public void whenFindByNameThenTrackerReturnsItem() {
Item item = new Item("test1", "test item 1", "test description");
tracker.add(item);
assertThat(tracker.findByName("test item 1").get(0).toString(), is(item.toString()));
}
/**
* When find by ID then tracker returns the item.
* Test for methods: add, findByID
*/
@Test
public void whenFindByIDThenTrackerReturnsItem() {
Item item = new Item("test1", "test item 1", "test description");
tracker.add(item);
assertThat(tracker.findByID("test1").toString(), is(item.toString()));
}
/**
* When update Item then item is updated.
* Test for methods: add, update
*/
@Test
public void whenUpdateItemThenTrackerReturnsItem() {
Item item1 = new Item("test1", "test item 1", "test description 1");
tracker.add(item1);
Item item2 = new Item("test2", "test item 2", "test description 2");
tracker.add(item2);
Item itemUpdated = new Item("test2", "updated item", "updated description");
tracker.update(itemUpdated);
assertThat(tracker.findAll().get(1).getName(), is("updated item"));
}
/**
* Release test environment.
*/
@After
public void releaseTestEnvironment() {
tracker.deleteAll();
tracker.closeConnection();
}
/**
* Delete test environment.
*/
@AfterClass
public static void deleteTestEnvironment() {
dropTestDatabase();
}
}
|
GuillermoHernan/fil-s | src/libfilsc/SymbolScope.cpp | /// <summary>
/// Implementation of symbol scope: stores the symbols used in the compiled program
/// in a hierarchical way.
/// </summary>
#include "pch.h"
#include "SymbolScope.h"
Ref<SymbolScope> SymbolScope::create(Ref<SymbolScope> parent)
{
return refFromNew(new SymbolScope(parent));
}
/// <summary>
/// Adds a new symbol
/// </summary>
/// <param name="name">Name of the symbol.</param>
/// <param name="node">AST node in which the symbol is defined.</param>
void SymbolScope::add(const std::string& name, Ref<AstNode> node)
{
assert(!name.empty());
assert(m_symbols.count(name) == 0);
m_symbols[name] = node;
}
/// <summary>
/// Checks if the name is already in scope. Checks parent scopes.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
bool SymbolScope::contains(const std::string& name, bool checkParents)const
{
if (m_symbols.count(name) > 0)
return true;
else if (checkParents && m_parent.notNull())
return m_parent->contains(name, true);
else
return false;
}
/// <summary>
/// Looks for a symbols.
/// </summary>
/// <param name="name"></param>
/// <param name="solveAlias">If true, alias nodes are not returned. Instead,
/// the alias is solved and its destination node is returned.</param>
/// <returns></returns>
Ref<AstNode> SymbolScope::get(const std::string& name, bool solveAlias)const
{
auto it = m_symbols.find(name);
if (it == m_symbols.end())
{
if (m_parent.notNull())
return m_parent->get(name, solveAlias);
else
return Ref<AstNode>();
}
else
{
auto node = it->second;
if (solveAlias)
{
if (node->getType() == AST_TYPEDEF)
{
assert(node->childExists(0));
node = node->children().front();
if (node->getType() == AST_TYPE_NAME)
node = this->get(node->getName(), true);
}
}
return node;
}
}
SymbolScope::SymbolScope(Ref<SymbolScope> parent) : m_parent(parent)
{
}
SymbolScope::~SymbolScope()
{
}
|
enyciaa/apollo-android | apollo-runtime/src/main/java/com/apollographql/apollo/fetcher/ResponseFetcher.java | package com.apollographql.apollo.fetcher;
import com.apollographql.apollo.api.internal.ApolloLogger;
import com.apollographql.apollo.interceptor.ApolloInterceptor;
/**
* A ResponseFetcher is an {@link ApolloInterceptor} inserted at the beginning of a request chain.
* It can control how a request is fetched by configuring {@link com.apollographql.apollo.interceptor.FetchOptions}.
*
* See {@link ApolloResponseFetchers} for a basic set of fetchers.
*/
public interface ResponseFetcher {
/**
* @param logger A {@link ApolloLogger} to log relevant fetch information.
* @return The {@link ApolloInterceptor} that executes the fetch logic.
*/
ApolloInterceptor provideInterceptor(ApolloLogger logger);
}
|
fengzhongye/LogiAM | log-agent/log-agent-engine/src/main/java/com/didichuxing/datachannel/agent/engine/component/Component.java | package com.didichuxing.datachannel.agent.engine.component;
import com.didichuxing.datachannel.agent.common.api.ComponentStatus;
/**
* @description: 组件抽象类
* @author: huangjw
* @Date: 19/6/28 18:02
*/
public abstract class Component {
private int status = ComponentStatus.RUNNING.getStatus();
public abstract boolean start();
public abstract boolean stop(boolean force);
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
|
lechium/tvOS10Headers | Applications/TVMusic/TVMusicRemoteController.h | <reponame>lechium/tvOS10Headers<gh_stars>1-10
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
#import "MPNowPlayingPlaybackQueueDataSource.h"
@class NSString, TVMusicMediaRemoteCommandHandler;
@interface TVMusicRemoteController : NSObject <MPNowPlayingPlaybackQueueDataSource>
{
_Bool _active; // 8 = 0x8
TVMusicMediaRemoteCommandHandler *_commandHandler; // 16 = 0x10
}
+ (id)sharedInstance; // IMP=0x0000000100076318
@property(retain, nonatomic) TVMusicMediaRemoteCommandHandler *commandHandler; // @synthesize commandHandler=_commandHandler;
@property(nonatomic, getter=isActive) _Bool active; // @synthesize active=_active;
- (void).cxx_destruct; // IMP=0x0000000100078934
- (id)_mediaItemForOffset:(long long)arg1; // IMP=0x000000010007877c
- (id)contentItemIdentifierForOffset:(long long)arg1; // IMP=0x0000000100078550
- (id)contentItemForOffset:(long long)arg1; // IMP=0x000000010007830c
- (void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void *)arg4; // IMP=0x0000000100078148
- (void)_mediaItemMetadataChanged:(id)arg1; // IMP=0x0000000100078078
- (long long)_handleLikeOrDislikeCommand:(id)arg1 like:(_Bool)arg2; // IMP=0x0000000100077ce0
- (void)_handleDislikeCommand:(id)arg1 completionHandler:(CDUnknownBlockType)arg2; // IMP=0x0000000100077c5c
- (void)_handleLikeCommand:(id)arg1 completionHandler:(CDUnknownBlockType)arg2; // IMP=0x0000000100077bd8
- (void)_handleAddItemToLibrary:(id)arg1 completionHandler:(CDUnknownBlockType)arg2; // IMP=0x00000001000778f8
- (void)_handleCreateRadioStationQueueCommand:(id)arg1 completionHandler:(CDUnknownBlockType)arg2; // IMP=0x00000001000774bc
- (void)_handleInsertIntoPlaybackQueueCommand:(id)arg1 completionHandler:(CDUnknownBlockType)arg2; // IMP=0x0000000100076f5c
- (void)_handleSetPlaybackQueueCommand:(id)arg1 completionHandler:(CDUnknownBlockType)arg2; // IMP=0x0000000100076bf0
- (void)_unRegisterCommands; // IMP=0x0000000100076a20
- (void)_registerCommands; // IMP=0x000000010007680c
- (void)stop; // IMP=0x0000000100076680
- (void)start; // IMP=0x00000001000764f8
- (void)dealloc; // IMP=0x000000010007642c
- (id)init; // IMP=0x0000000100076398
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
Capeia/capeia | src/public/author/__generated__/Author_author.graphql.js | /**
* @flow
*/
/* eslint-disable */
'use strict';
/*::
import type {ConcreteFragment} from 'relay-runtime';
export type Author_author = {|
+name: string;
+type: ?string;
+degree: ?string;
+affiliation: {|
+institute: ?{|
+name: ?string;
|};
|};
+slug: string;
+donations: ?{|
+received: ?{|
+edges: $ReadOnlyArray<{|
+node: ?{| |};
|}>;
|};
|};
+rewards: ?{|
+edges: $ReadOnlyArray<{|
+node: ?{| |};
|}>;
|};
|};
*/
const fragment /*: ConcreteFragment*/ = {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "Author_author",
"selections": [
{
"kind": "ScalarField",
"alias": null,
"args": null,
"name": "name",
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"args": null,
"name": "type",
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"args": null,
"name": "degree",
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"args": null,
"concreteType": "Affiliation",
"name": "affiliation",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"args": null,
"concreteType": "Institute",
"name": "institute",
"plural": false,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"args": null,
"name": "name",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"args": null,
"name": "slug",
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"args": null,
"concreteType": "Donations",
"name": "donations",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 5,
"type": "Int"
},
{
"kind": "Literal",
"name": "page",
"value": 1,
"type": "Int"
}
],
"concreteType": "DonationConnection",
"name": "received",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"args": null,
"concreteType": "DonationEdge",
"name": "edges",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"args": null,
"concreteType": "Donation",
"name": "node",
"plural": false,
"selections": [
{
"kind": "FragmentSpread",
"name": "DonorFeed_donations",
"args": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "received{\"first\":5,\"page\":1}"
}
],
"storageKey": null
},
{
"kind": "LinkedField",
"alias": null,
"args": [
{
"kind": "Literal",
"name": "active",
"value": true,
"type": "Boolean"
},
{
"kind": "Literal",
"name": "first",
"value": 3,
"type": "Int"
}
],
"concreteType": "RewardConnection",
"name": "rewards",
"plural": false,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"args": null,
"concreteType": "RewardEdge",
"name": "edges",
"plural": true,
"selections": [
{
"kind": "LinkedField",
"alias": null,
"args": null,
"concreteType": "Reward",
"name": "node",
"plural": false,
"selections": [
{
"kind": "FragmentSpread",
"name": "RewardList_rewards",
"args": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "rewards{\"active\":true,\"first\":3}"
},
{
"kind": "FragmentSpread",
"name": "UserAvatar_user",
"args": null
},
{
"kind": "FragmentSpread",
"name": "AuthorText_author",
"args": null
}
],
"type": "User"
};
module.exports = fragment;
|
kem709394/mango | src/main/java/com/mango/sys/controller/SysMailController.java | package com.mango.sys.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mango.common.DictConstants;
import com.mango.controller.BaseController;
import com.mango.common.JsonResult;
import com.mango.sys.entity.SysMail;
import com.mango.sys.service.SysMailService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.websocket.server.PathParam;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author kem
* @since 2019-08-01
*/
@Controller
@RequestMapping("/v1/sys")
public class SysMailController extends BaseController {
private final SysMailService sysMailService;
@Autowired
public SysMailController(SysMailService sysMailService) {
this.sysMailService = sysMailService;
}
@ApiOperation(value="邮件分页查询", notes="邮件分页查询")
@ApiImplicitParams({
@ApiImplicitParam(name = "Token", value = "授权证书", required = true, dataType = "String", paramType = "header"),
@ApiImplicitParam(name = "current", value = "分页的页码", required = true, dataType = "Integer", paramType = "query"),
@ApiImplicitParam(name = "size", value = "分页的行数", required = true, dataType = "Integer", paramType = "query"),
@ApiImplicitParam(name = "filter", value = "查询条件", required = true, dataType = "String", paramType = "query")
})
@GetMapping("mail")
@RequiresPermissions("sys:mail:find")
public @ResponseBody
JSONObject find(@PathParam("current")int current, @PathParam("size")int size, @PathParam("filter")String filter) {
Page<SysMail> page = new Page<>();
page.setSize(size);
page.setCurrent(current);
QueryWrapper<SysMail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("is_deleted",false);
byte[] bytes = Base64.getDecoder().decode(filter);
JSONObject filterItem= JSON.parseObject(new String(bytes, StandardCharsets.UTF_8));
if(filterItem.containsKey("subject")){
queryWrapper.like("subject","%"+filterItem.getString("subject")+"%");
}
if(filterItem.containsKey("state")){
queryWrapper.eq("state",filterItem.getString("state"));
}
if (filterItem.containsKey("dateRange")) {
JSONArray dateRange=filterItem.getJSONArray("dateRange");
queryWrapper.between("create_time" ,dateRange.getDate(0),dateRange.getDate(1));
}
queryWrapper.orderByDesc("create_time");
IPage<SysMail> data = sysMailService.page(page, queryWrapper);
return JsonResult.page(data.getRecords(),data.getTotal());
}
@ApiOperation(value="获取邮件详细", notes="获取邮件详细")
@ApiImplicitParams({
@ApiImplicitParam(name = "Token", value = "授权证书", required = true, dataType = "String", paramType = "header"),
@ApiImplicitParam(name = "id", value = "邮件ID", required = true, dataType = "Long", paramType = "path")
})
@GetMapping("mail/{id}")
@RequiresPermissions("sys:mail:detail")
public @ResponseBody
JSONObject detail(@PathVariable("id") Long id) {
SysMail mail=sysMailService.getById(id);
return JsonResult.info(mail);
}
@ApiOperation(value="添加邮件实例", notes="添加邮件实例")
@ApiImplicitParams({
@ApiImplicitParam(name = "Token", value = "授权证书", required = true, dataType = "String", paramType = "header"),
@ApiImplicitParam(name = "subject", value = "主题", required = true, dataType = "String", paramType = "body"),
@ApiImplicitParam(name = "content", value = "内容", required = true, dataType = "String", paramType = "body"),
@ApiImplicitParam(name = "attachment", value = "附件", dataType = "JSONArray", paramType = "body"),
@ApiImplicitParam(name = "inline", value = "插图", dataType = "JSONArray", paramType = "body"),
@ApiImplicitParam(name = "toSite", value = "接收地址", required = true, dataType = "JSONArray", paramType = "body"),
@ApiImplicitParam(name = "ccSite", value = "抄送地址", dataType = "JSONArray", paramType = "body")
})
@PostMapping("mail")
@RequiresPermissions("sys:mail:create")
public @ResponseBody
JSONObject create(@RequestBody JSONObject params) {
SysMail mail=new SysMail();
mail.setSubject(params.getString("subject"));
mail.setContent(params.getString("content"));
mail.setAttachment(params.getJSONArray("attachment"));
mail.setInline(params.getJSONArray("inline"));
mail.setToSite(params.getJSONArray("toSite"));
mail.setCcSite(params.getJSONArray("ccSite"));
mail.setCreatorId(getUserId());
mail.setCreateTime(LocalDateTime.now());
mail.setState(DictConstants.MAIL_STATE_NONE);
mail.setCounter(0);
mail.setIsDeleted(false);
sysMailService.save(mail);
return JsonResult.ok();
}
@ApiOperation(value="修改邮件实例", notes="修改邮件实例")
@ApiImplicitParams({
@ApiImplicitParam(name = "Token", value = "授权证书", required = true, dataType = "String", paramType = "header"),
@ApiImplicitParam(name = "id", value = "邮件ID", required = true, dataType = "Long", paramType = "path"),
@ApiImplicitParam(name = "cancel", value = "撤销操作", dataType = "boolean", paramType = "body"),
@ApiImplicitParam(name = "retry", value = "重发操作", dataType = "boolean", paramType = "body")
})
@PutMapping("mail/{id}")
@RequiresPermissions("sys:mail:update")
public @ResponseBody
JSONObject update(@PathVariable("id") Long id, @RequestBody JSONObject params) {
SysMail mail=sysMailService.getById(id);
if(params.containsKey("cancel")){
if(mail.getState().equals(DictConstants.MAIL_STATE_NONE)||mail.getState().equals(DictConstants.MAIL_STATE_FAIL)){
mail.setState(DictConstants.MAIL_STATE_CANCEL);
sysMailService.updateById(mail);
return JsonResult.ok();
}else{
return JsonResult.fail("操作失败");
}
} else if(params.containsKey("retry")) {
if(mail.getState().equals(DictConstants.MAIL_STATE_CANCEL)||mail.getState().equals(DictConstants.MAIL_STATE_FAIL)){
mail.setState(DictConstants.MAIL_STATE_NONE);
mail.setCounter(0);
sysMailService.updateById(mail);
return JsonResult.ok();
}else{
return JsonResult.fail("操作失败");
}
} else {
return JsonResult.fail("非法操作");
}
}
@ApiOperation(value="删除邮件实例", notes="删除邮件实例")
@ApiImplicitParams({
@ApiImplicitParam(name = "Token", value = "授权证书", required = true, dataType = "String", paramType = "header"),
@ApiImplicitParam(name = "ids", value = "邮件ID", required = true, dataType = "JSONArray", paramType = "body"),
})
@DeleteMapping("mail")
@RequiresPermissions("sys:mail:delete")
public @ResponseBody
JSONObject delete(@RequestBody JSONArray ids) {
List<SysMail> list=new ArrayList<>();
for(int i=0;i<ids.size();i++){
SysMail item=new SysMail();
item.setId(ids.getLong(i));
item.setIsDeleted(true);
list.add(item);
}
sysMailService.updateBatchById(list);
return JsonResult.ok();
}
}
|
700software/ts-code-generator | dist/definitions/base/BasePropertyDefinition.js | <gh_stars>0
"use strict";
var __extends = (this && this.__extends)/* istanbul ignore next */ || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var utils_1 = require("./../../utils");
var NamedDefinition_1 = require("./NamedDefinition");
var OptionalDefinition_1 = require("./OptionalDefinition");
var ReadonlyableDefinition_1 = require("./ReadonlyableDefinition");
var TypedDefinition_1 = require("./TypedDefinition");
var BaseDefinition_1 = require("./BaseDefinition");
var BasePropertyDefinition = (function (_super) {
__extends(BasePropertyDefinition, _super);
function BasePropertyDefinition() {
_super.apply(this, arguments);
}
return BasePropertyDefinition;
}(BaseDefinition_1.BaseDefinition));
exports.BasePropertyDefinition = BasePropertyDefinition;
utils_1.applyMixins(BasePropertyDefinition, BaseDefinition_1.BaseDefinition, [NamedDefinition_1.NamedDefinition, OptionalDefinition_1.OptionalDefinition, TypedDefinition_1.TypedDefinition, ReadonlyableDefinition_1.ReadonlyableDefinition]);
//# sourceMappingURL=BasePropertyDefinition.js.map
|
78182648/blibli-go | app/job/main/spy/dao/memcache.go | package dao
import (
"context"
"fmt"
"go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_partitionKey = "p_%s_%d"
)
// pingMC ping memcache.
func (d *Dao) pingMC(ctx context.Context) (err error) {
conn := d.mc.Get(ctx)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 0}); err != nil {
log.Error("conn.Store(set,ping,1) error(%v)", err)
}
return
}
func partitionCacheKey(e string, p int32) string {
return fmt.Sprintf(_partitionKey, e, p)
}
// OffsetCache .
func (d *Dao) OffsetCache(ctx context.Context, event string, p int32) (offset int64, err error) {
var (
key = partitionCacheKey(event, p)
conn = d.mc.Get(ctx)
)
defer conn.Close()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("conn.Get(get,%d) error(%v)", p, err)
return
}
if err = conn.Scan(reply, &offset); err != nil {
log.Error("reply.Scan(%s) error(%v)", string(reply.Value), err)
}
return
}
// SetOffsetCache .
func (d *Dao) SetOffsetCache(ctx context.Context, event string, p int32, offset int64) (err error) {
var (
key = partitionCacheKey(event, p)
conn = d.mc.Get(ctx)
)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: key, Object: offset, Expiration: 0, Flags: memcache.FlagJSON}); err != nil {
log.Error("conn.Set(%s,%d) error(%v)", key, offset, err)
}
return
}
|
aditgoyal19/Tropical-Go-Kart-Bananas | GameJam_v3.2/GameEngineBase/externals/Havok/includes/Source/Common/Base/Types/Geometry/Aabb16/hkAabb16.h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_AABB_16_H
#define HK_AABB_16_H
/// Aabb using 15 bit storage (highest bit cannot be used), you can use the hkIntspaceUtil to convert back and forth this class.
struct hkAabb16
{
public:
//+version(0)
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CDINFO, hkAabb16 );
HK_DECLARE_REFLECTION();
//hkAabb16(){}
HK_FORCE_INLINE friend hkBool32 operator < (const hkAabb16& a, const hkAabb16& b ){ return a.m_min[0] < b.m_min[0]; }
template<typename KeyType>
HK_FORCE_INLINE void setKey(KeyType key);
HK_FORCE_INLINE void getKey(hkUint16& key) const;
HK_FORCE_INLINE void getKey(hkUint32& key) const;
HK_FORCE_INLINE void setEmpty();
HK_FORCE_INLINE void set( const hkAabb16& other);
HK_FORCE_INLINE bool isEmpty() const;
HK_FORCE_INLINE bool isEqual(const hkAabb16& testAabb) const;
HK_FORCE_INLINE void setEmptyKeyUnchanged();
HK_FORCE_INLINE bool isValid() const;
HK_FORCE_INLINE void getExtent(hkUint16 extent[3]) const;
HK_FORCE_INLINE hkUint16 getMajorExtent() const;
HK_FORCE_INLINE hkBool32 disjoint(const hkAabb16& testAabb) const;
HK_FORCE_INLINE hkBool32 overlaps(const hkUint16 p[3]) const;
HK_FORCE_INLINE hkBool32 overlaps(const hkAabb16& testAabb) const;
HK_FORCE_INLINE void includePoint( hkUint16 c[3] );
HK_FORCE_INLINE void includeAabb( const hkAabb16& in );
/// Set this to the extent of all input aabbs.
void setExtents( const hkAabb16* aabbsIn, int numAabbsIn );
/// Set this to the extent of all input aabb centers, assumes that the bit 16 of the input aabbs is cleared
void setExtentsOfCenters( const hkAabb16* aabbsIn, int numAabbsIn );
/// Sets this to the intersection of aabb0 and aabb1.
void setIntersection( const hkAabb16& aabb0, const hkAabb16& aabb1 );
/// Sets this to the union of aabb0 and aabb1.
HK_FORCE_INLINE void setUnion( const hkAabb16& aabb0, const hkAabb16& aabb1 );
/// returns true if test AABB is fully inside this, touching the border is allowed
HK_FORCE_INLINE hkBool32 contains( const hkAabb16& testAabb ) const;
/// returns true if test AABB is fully inside this and is not touching the border
HK_FORCE_INLINE hkBool32 containsDontTouch( const hkAabb16& testAabb ) const;
/// returns (min+max)/2
HK_FORCE_INLINE void getCenter(hkUint16 c[3]) const;
/// returns (min+max) faster than getCenter()
HK_FORCE_INLINE void getCenter2(hkUint32 c[3]) const;
/// returns (min+max) faster than getCenter()
HK_FORCE_INLINE void getCenter2(hkVector4& c) const;
/// returns (max-min) faster than getCenter()
HK_FORCE_INLINE void getExtents(hkVector4& e) const;
static HK_FORCE_INLINE hkUint32 yzDisjoint( const hkAabb16& a, const hkAabb16& b );
public:
hkUint16 m_min[3];
hkUint16 m_key;
hkUint16 m_max[3];
hkUint16 m_key1;
};
#include <Common/Base/Types/Geometry/Aabb16/hkAabb16.inl>
#endif // HK_AABB_16_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20130718)
*
* Confidential Information of Havok. (C) Copyright 1999-2013
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
|
fugeritaetas/morozko-lib | java14-morozko/org.morozko.java.mod.db/src/org/morozko/java/mod/db/backup/adaptor/BackupAdaptorWrapper.java | package org.morozko.java.mod.db.backup.adaptor;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Properties;
import org.morozko.java.core.lang.helpers.ClassHelper;
import org.morozko.java.core.xml.dom.DOMUtils;
import org.morozko.java.mod.db.backup.BackupAdaptor;
import org.morozko.java.mod.db.backup.DefaultBackupAdaptor;
import org.w3c.dom.Element;
public class BackupAdaptorWrapper implements BackupAdaptor {
private BackupAdaptor wrapped;
public BackupAdaptorWrapper() {
this.wrapped = null;
}
public void set(PreparedStatement ps, ResultSetMetaData rsmd, Object obj, int index) throws SQLException {
this.wrapped.set(ps, rsmd, obj, index);
}
public Object get(ResultSet rs, ResultSetMetaData rsmd, int index) throws SQLException {
return this.wrapped.get(rs, rsmd, index);
}
public void setWrapped(BackupAdaptor wrapped) {
this.wrapped = wrapped;
}
public BackupAdaptor getWrapped() {
return wrapped;
}
public void configure(Element config) throws Exception {
Properties atts = DOMUtils.attributesToProperties( config );
String wrappedAdaptor = atts.getProperty( "wrapped" );
if ( wrappedAdaptor != null ) {
this.setWrapped( (BackupAdaptor)ClassHelper.newInstance( wrappedAdaptor ) );
this.getWrapped().configure( config );
} else {
this.setWrapped( DefaultBackupAdaptor.DEFAULT );
}
}
}
|
iam-Legend/Project-Assembly | Source/FactoryGame/Equipment/FGBuildGunBuild.h | // Copyright 2016 <NAME>. All Rights Reserved.
#pragma once
#include "Engine/StaticMesh.h"
#include "Array.h"
#include "GameFramework/Actor.h"
#include "SubclassOf.h"
#include "UObject/Class.h"
#include "FGBuildGun.h"
#include "../ItemAmount.h"
#include "FGBuildGunBuild.generated.h"
USTRUCT()
struct FConnectionRepresentation
{
GENERATED_BODY()
FConnectionRepresentation() :
mConnectionRepresentation( nullptr ),
mConnectionComponent( nullptr )
{
}
FConnectionRepresentation( class UFGConnectionComponent* connectionComponent, class UStaticMeshComponent * connectionRepresentation ) :
mConnectionComponent(connectionComponent),
mConnectionRepresentation(connectionRepresentation)
{
}
UPROPERTY()
class UFGConnectionComponent* mConnectionComponent;
UPROPERTY()
class UStaticMeshComponent* mConnectionRepresentation;
};
USTRUCT()
struct FFactoryClearanceData
{
GENERATED_BODY()
FFactoryClearanceData() :
Factory( nullptr ),
ClearanceComponent( nullptr )
{
}
FFactoryClearanceData( class AFGBuildableFactory* inFactory, class UStaticMeshComponent* inClearanceComponent ) :
Factory( inFactory ),
ClearanceComponent( inClearanceComponent )
{
}
UPROPERTY()
class AFGBuildableFactory* Factory;
UPROPERTY()
class UStaticMeshComponent* ClearanceComponent;
UPROPERTY()
TArray< FConnectionRepresentation > mConnectionComponents;
};
/**
* Build guns build state.
*/
UCLASS()
class FACTORYGAME_API UFGBuildGunStateBuild : public UFGBuildGunState
{
GENERATED_BODY()
public:
/** Ctor */
UFGBuildGunStateBuild();
/** Replication. */
virtual void GetLifetimeReplicatedProps( TArray< FLifetimeProperty >& OutLifetimeProps ) const override;
virtual void PreNetReceive() override;
// Begin UFGBuildGunState
virtual void BeginState_Implementation() override;
virtual void EndState_Implementation() override;
virtual void TickState_Implementation( float deltaTime ) override;
virtual void PrimaryFire_Implementation() override;
virtual void SecondaryFire_Implementation() override;
virtual void ScrollDown_Implementation() override;
virtual void ScrollUp_Implementation() override;
virtual void ChangeScrollMode_Implementation() override;
virtual void ChangeNoSnapMode_Implementation() override;
virtual void ChangeGuideLinesSnapMode_Implementation( bool enabled ) override;
// End UFGBuildGunState
/**
* Set the recipe to build.
* must be called from the local player (client).
*/
void SetActiveRecipe( TSubclassOf< class UFGRecipe > recipe );
/** Get the current descriptor, null if no descriptor is set. */
UFUNCTION( BlueprintPure, Category = "BuildGunState|Build" )
TSubclassOf< class UFGItemDescriptor > GetDescriptor() const;
/** Returns the cost for building the hologram. */
UFUNCTION( BlueprintPure, Category = "BuildGunState|Build" )
TArray< FItemAmount > GetHologramCost() const;
/** Returns the hologram; null if hologram not spawned. */
UFUNCTION( BlueprintPure, Category = "BuildGunState|Build" )
class AFGHologram* GetHologram() const;
/** Spawns a child hologram. */
class AFGHologram* SpawnChildHologram( AFGHologram* parent, TSubclassOf< class UFGRecipe > recipe );
protected:
/** Called whenever the hologram is udpated **/
UFUNCTION()
void OnRep_Hologram();
/**
* Resets any changes made to the hologram.
* @note Must be called on the server.
*/
UFUNCTION( BlueprintCallable, Category = "BuildGunState|Build" )
void ResetHologram();
/**
* Let blueprint know when we get a new descriptor, the new descriptor may be null.
*/
UFUNCTION( BlueprintImplementableEvent, Category = "BuildGunState|Build" )
void OnActiveDescriptorChanged();
/**
* Let blueprint know we performed a multi-step placement.
* @param isFinalStep - true if this was the last step, the thing is now built. Hologram is no longer guaranteed to exist on the the client.
*/
UFUNCTION( BlueprintImplementableEvent, Category = "BuildGunState|Build" )
void OnMultiStepPlacement( bool isFinalStep );
/**
* Let blueprint know we reset the multi-step placement.
*/
UFUNCTION( BlueprintImplementableEvent, Category = "BuildGunState|Build" )
void OnResetHologram();
/** Helper to notify the client. */
UFUNCTION( Client, Reliable )
void Client_OnResetHologram();
/** Helper to notify the client that something was built */
UFUNCTION( Client, Reliable )
void Client_OnBuildableConstructed( TSubclassOf< UFGItemDescriptor > desc );
private:
/** Spawn a hologram. */
void SpawnHologram();
/** Spawn specific holograms. */
class AFGHologram* SpawnBuildableHologram( TSubclassOf< class UFGRecipe > recipe );
class AFGHologram* SpawnVehicleHologram( TSubclassOf< class UFGRecipe > recipe );
/** Remove the current hologram. */
void RemoveHologram();
/** Setup the clearance for our current hologram */
void SetupHologramClearanceDetection();
/** Remove the clearance from our current hologram */
void CleanupHologramClearanceDetection( AFGHologram* hologram );
/** Save/clear/restore the scroll values for the hologram. */
void SaveHologramScrollValues();
void ClearHologramScrollValues();
void RestoreHologramScrollValues();
UFUNCTION()
void BeginClearanceOverlap( UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult );
UFUNCTION()
void EndClearanceOverlap( UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex );
private:
/** Stored values between hologram builds on how the hologram was scrolled */
TArray< int32 > mScrollModeValues;
/** Stored no snap flag between hologram builds. */
bool mNoSnapMode;
/** Stored flag for whether hologram builds should snap to guide lines */
bool mSnapToGuideLinesMode;
/** Recipe to activate when state is entered. */
UPROPERTY()
TSubclassOf< class UFGRecipe > mPendingRecipe;
/**
* The currently active recipe, this decides which action will be used.
* Not replicated as the client sets it locally and then tells the server to set it.
*/
UPROPERTY()
TSubclassOf< class UFGRecipe > mActiveRecipe;
/** The hologram that the client had before changing it's hologram due to replication, no UPROPERTY as it should only live from PreNetReceive to OnRep_Hologram */
class AFGHologram* mInternalPrevClientHologram;
/** The hologram to build. */
UPROPERTY( ReplicatedUsing=OnRep_Hologram )
class AFGHologram* mHologram;
/** The actor to replace (dismantle) when upgrading. */
UPROPERTY( Replicated )
class AActor* mUpgradedActor;
/** Moves the clearance box collision to where we are aiming */
void UpdateClearanceData();
/** Contains all the proximate clearances volumes */
UPROPERTY()
TArray< FFactoryClearanceData > mProximateClearances;
/** Component that finds close clearances of nearby buildings and visualize them */
//@todo G2 2019-04-10 An improvement here would be to make this a component that can keep track of detected
// overlaps so the state does not contain this easily self contained logic.
UPROPERTY()
class UBoxComponent* mClearanceDetector;
};
|
riag23/AdaptiveCards | source/macos/AdaptiveCards/AdaptiveCards-bridge/AutoGenerated/Models/ACSDateTimePreparsedToken.h | // DO NOT EDIT - Auto generated
// Generated with objc_viewmodel_header.j2
#ifndef ACSDateTimePreparsedToken_IMPORTED
#define ACSDateTimePreparsedToken_IMPORTED
#import <Foundation/Foundation.h>
#ifdef __cplusplus
#import "DateTimePreparsedToken.h"
using namespace AdaptiveCards;
#endif
#import "ACSDateTimePreparsedTokenFormat.h"
enum ACSDateTimePreparsedTokenFormat: NSUInteger;
@interface ACSDateTimePreparsedToken : NSObject
#ifdef __cplusplus
- (instancetype _Nonnull)initWithDateTimePreparsedToken:(const std::shared_ptr<DateTimePreparsedToken>)cppObj;
#endif
- (NSString * _Nullable)getText;
- (ACSDateTimePreparsedTokenFormat)getFormat;
- (NSNumber * _Nullable)getDay;
- (NSNumber * _Nullable)getMonth;
- (NSNumber * _Nullable)getYear;
@end
#endif
|
bc-hwang/TEST | backend/src/main/java/com/dataus/deverse/domain/board/controller/TagController.java | <gh_stars>1-10
package com.dataus.deverse.domain.board.controller;
import com.dataus.deverse.domain.board.service.TagService;
import com.dataus.deverse.domain.board.service.impl.TagServiceImpl;
import com.dataus.deverse.domain.board.vo.PostCategoryType;
import com.dataus.deverse.global.pagination.Pagination;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/tag")
public class TagController {
private final TagService tagService;
public TagController(TagServiceImpl tagServiceImpl) {
this.tagService = tagServiceImpl;
}
@GetMapping(value="popular")
public ResponseEntity<?> getPopularTag(
@RequestParam(value="category", required=false, defaultValue="ALL") String category,
@RequestParam(value="page", required=false, defaultValue="1") int pageNo,
@RequestParam(value="size", required=false, defaultValue="10") int pageSize,
@RequestParam(value="keyword", required=false, defaultValue="") String searchKeyword
) {
Pagination page = new Pagination();
page.setCategory(PostCategoryType.valueOf(category.toUpperCase()));
page.setCurrentPageNo(pageNo);
page.setRecordsPerPage(pageSize);
page.setSearchKeyword(
(searchKeyword.indexOf('#') == 0) ? searchKeyword.substring(1) : searchKeyword
);
return ResponseEntity.ok(
tagService.getPopularTag(page)
);
}
@GetMapping(value="search")
public ResponseEntity<?> getSearchTag(
@RequestParam(value="page", required=false, defaultValue="1") int pageNo,
@RequestParam(value="size", required=false, defaultValue="10") int pageSize,
@RequestParam(value="keyword", required=false, defaultValue="") String searchKeyword
) {
Pagination page = new Pagination();
page.setCurrentPageNo(pageNo);
page.setRecordsPerPage(pageSize);
page.setSearchKeyword(
(searchKeyword.indexOf('#') == 0) ? searchKeyword.substring(1) : searchKeyword
);
return ResponseEntity.ok(
tagService.getSearchTag(page)
);
}
}
|
SP2FET/MuditaOS-1 | module-apps/apps-common/popups/data/PopupData.hpp | <reponame>SP2FET/MuditaOS-1
// Copyright (c) 2017-2021, Mudita <NAME>.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <SwitchData.hpp>
#include <module-audio/Audio/AudioCommon.hpp>
namespace gui
{
class VolumePopupData : public SwitchData
{
public:
explicit VolumePopupData(const audio::Volume volume, const audio::Context audioContext)
: SwitchData(), volume{volume}, audioContext{audioContext}
{}
[[nodiscard]] auto getVolume() const noexcept -> audio::Volume
{
return volume;
}
[[nodiscard]] auto getAudioContext() const noexcept -> audio::Context
{
return audioContext;
}
private:
const audio::Volume volume;
const audio::Context audioContext;
};
class ModesPopupData : public SwitchData
{
public:
explicit ModesPopupData(sys::phone_modes::PhoneMode phoneMode, bool flightMode)
: SwitchData(), phoneMode{phoneMode}, isFlightModeEnabled(flightMode)
{}
[[nodiscard]] auto getPhoneMode() const noexcept -> sys::phone_modes::PhoneMode
{
return phoneMode;
}
[[nodiscard]] auto getFlightMode() const noexcept -> bool
{
return isFlightModeEnabled;
}
private:
const sys::phone_modes::PhoneMode phoneMode;
const bool isFlightModeEnabled;
};
} // namespace gui
|
radomely/node-practice | 09_REST/004_CORS_Example/api/main.js | <gh_stars>0
var express = require('express');
var app = express();
var path = require('path');
var port = 8080;
var bodyParser = require('body-parser');
// подключение модуля для обработки запросов
var apiHandler = require('./api_handler');
// middleware для обработки данных запросов в формате JSON
app.use(bodyParser.json());
// middleware для использования CORS
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var router = express.Router();
// загрузка всех элементов из бд
router.get('/', apiHandler.loadItems)
// выбор элемента
router.get('/:id', apiHandler.getItemById);
// создание элемента
router.post('/new', apiHandler.createItem);
// обновление элемента (редактирование)
router.put('/:id', apiHandler.updateItem);
// удаление элемента
router.delete('/:id', apiHandler.removeItem);
app.use('/api', router);
app.listen(port, function () {
console.log('app running on port ' + port);
}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.