repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
mfranzil/Programmazione1UniTN | exercises/IF_THEN_ELSE_SWITCH/minimo2.cc | using namespace std;
#include <iostream>
int main ()
{
int x, y, z;
cout << "Dammi tre interi x, y e z: ";
cin >> x >> y >> z;
cout << "Il minimo tra " << x << ", " << y << " e " << z << " e' ";
if (x<=y && x<=z)
cout << x;
else if (y<=x && y<=z)
cout << y;
else
cout << z;
cout << endl;
return 0;
}
|
Pentacode-IAFA/Quad-Remeshing | libs/quadwild/libs/libigl/include/igl/cgal/remesh_self_intersections.h | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2014 <NAME> <<EMAIL>>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#ifndef IGL_REMESH_SELF_INTERSECTIONS_H
#define IGL_REMESH_SELF_INTERSECTIONS_H
#include <igl/igl_inline.h>
#include "RemeshSelfIntersectionsParam.h"
#include <Eigen/Dense>
#ifdef MEX
# include <mex.h>
# include <cassert>
# undef assert
# define assert( isOK ) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(C_STR(__FILE__<<":"<<__LINE__<<": failed assertion `"<<#isOK<<"'"<<std::endl) ) )
#endif
namespace igl
{
// Given a triangle mesh (V,F) compute a new mesh (VV,FF) which is the same
// as (V,F) except that any self-intersecting triangles in (V,F) have been
// subdivided (new vertices and face created) so that the self-intersection
// contour lies exactly on edges in (VV,FF). New vertices will appear in
// original faces or on original edges. New vertices on edges are "merged"
// only across original faces sharing that edge. This means that if the input
// triangle mesh is a closed manifold the output will be too.
//
// Inputs:
// V #V by 3 list of vertex positions
// F #F by 3 list of triangle indices into V
// params struct of optional parameters
// Outputs:
// VV #VV by 3 list of vertex positions
// FF #FF by 3 list of triangle indices into V
// IF #intersecting face pairs by 2 list of intersecting face pairs,
// indexing F
// J #FF list of indices into F denoting birth triangle
// IM #VV list of indices into VV of unique vertices.
//
// Known bugs: If an existing edge in (V,F) lies exactly on another face then
// any resulting additional vertices along that edge may not get properly
// connected so that the output mesh has the same global topology. This is
// because
//
// Example:
// // resolve intersections
// igl::remesh_self_intersections(V,F,params,VV,FF,IF,J,IM);
// // _apply_ duplicate vertex mapping IM to FF
// for_each(FF.data(),FF.data()+FF.size(),[&IM](int & a){a=IM(a);});
// // remove any vertices now unreferenced after duplicate mapping.
// igl::remove_unreferenced(VV,FF,SV,SF,UIM);
// // Now (SV,SF) is ready to extract outer hull
// igl::outer_hull(SV,SF,G,J,flip);
//
template <
typename DerivedV,
typename DerivedF,
typename DerivedVV,
typename DerivedFF,
typename DerivedIF,
typename DerivedJ,
typename DerivedIM>
IGL_INLINE void remesh_self_intersections(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedF> & F,
const RemeshSelfIntersectionsParam & params,
Eigen::PlainObjectBase<DerivedVV> & VV,
Eigen::PlainObjectBase<DerivedFF> & FF,
Eigen::PlainObjectBase<DerivedIF> & IF,
Eigen::PlainObjectBase<DerivedJ> & J,
Eigen::PlainObjectBase<DerivedIM> & IM);
}
#ifndef IGL_STATIC_LIBRARY
# include "remesh_self_intersections.cpp"
#endif
#endif
|
oswaldquek/pay-connector | src/main/java/uk/gov/pay/connector/gateway/model/response/BaseCaptureResponse.java | package uk.gov.pay.connector.gateway.model.response;
import uk.gov.pay.connector.gateway.PaymentGatewayName;
import static java.lang.String.format;
public interface BaseCaptureResponse extends BaseResponse {
String getTransactionId();
String stringify();
static BaseCaptureResponse fromTransactionId(String transactionId, PaymentGatewayName gatewayName) {
return new BaseCaptureResponse() {
@Override
public String getTransactionId() {
return transactionId;
}
@Override
public String stringify() {
return format("%s capture response: (transactionId: %s)", gatewayName.getName(), transactionId);
}
@Override
public String getErrorCode() {
return null;
}
@Override
public String getErrorMessage() {
return null;
}
};
}
}
|
WNPRC-EHR-Services/wnprc-modules | wnprc_billing/src/org/labkey/wnprc_billing/dataentry/NonAnimalChargesFormSection.java | package org.labkey.wnprc_billing.dataentry;
import org.labkey.api.ehr.EHRService;
import org.labkey.api.ehr.dataentry.SimpleFormSection;
import org.labkey.api.view.template.ClientDependency;
import java.util.Collections;
import java.util.List;
/**
* Class to administer Ext4JS component/panel for ehr_billing.miscCharges data entry for charges without animal id and project
*/
public class NonAnimalChargesFormSection extends SimpleFormSection {
public NonAnimalChargesFormSection()
{
this(EHRService.FORM_SECTION_LOCATION.Body);
}
public NonAnimalChargesFormSection(EHRService.FORM_SECTION_LOCATION location)
{
super("ehr_billing", "miscCharges", "Misc. Charges", "ehr-gridpanel", location);
_allowRowEditing = false;
addClientDependency(ClientDependency.supplierFromPath("wnprc_billing/model/sources/NonAnimalCharges.js"));
setConfigSources(Collections.singletonList("Task"));
}
@Override
public List<String> getTbarButtons()
{
List<String> defaultButtons = super.getTbarButtons();
// Remove the default buttons that don't make sense for charges Without animal ids
defaultButtons.remove("ADDANIMALS");
defaultButtons.remove("COPYFROMSECTION");
defaultButtons.remove("TEMPLATE");
return defaultButtons;
}
@Override
public List<String> getTbarMoreActionButtons()
{
List<String> defaultMoreActionButtons = super.getTbarMoreActionButtons();
defaultMoreActionButtons.remove("GUESSPROJECT");
defaultMoreActionButtons.remove("COPY_IDS");
return defaultMoreActionButtons;
}
}
|
benjaminchang23/jackson-street-problems | prac-cpp/pair_hash_0.cc | <reponame>benjaminchang23/jackson-street-problems<gh_stars>0
/**
* BlockingUnorderedMap.h
*
* Thread safe blocking unordered map
*/
#ifndef __BLOCKING_UNORDERED_MAP_H__
#define __BLOCKING_UNORDERED_MAP_H__
#include <functional>
#include <mutex>
#include <unordered_map>
template <typename Key, typename Value, typename Hash = std::hash<Key>>
class BlockingUnorderedMap
{
private:
std::mutex mutex_;
std::unordered_map<Key, Value, Hash> map_;
public:
decltype(auto) begin()
{
const std::lock_guard<std::mutex> lock(mutex_);
map_.begin();
}
decltype(auto) emplace(Key key, Value value)
{
const std::lock_guard<std::mutex> lock(mutex_);
return map_.emplace(key, value);
}
decltype(auto) erase(Key key)
{
const std::lock_guard<std::mutex> lock(mutex_);
return map_.erase(key);
}
decltype(auto) end()
{
const std::lock_guard<std::mutex> lock(mutex_);
map_.end();
}
bool find_and_replace(Key key, Value value)
{
const std::lock_guard<std::mutex> lock(mutex_);
if (map_.find(key) == map_.end())
return false;
map_.erase(key);
map_.emplace(key, value);
return true;
}
decltype(auto) find(Key key)
{
const std::lock_guard<std::mutex> lock(mutex_);
return map_.find(key);
}
bool count(Key key)
{
const std::lock_guard<std::mutex> lock(mutex_);
return map_.count(key);
}
size_t size()
{
const std::lock_guard<std::mutex> lock(mutex_);
size_t size = map_.size();
return size;
}
bool empty()
{
const std::lock_guard<std::mutex> lock(mutex_);
bool check = map_.empty();
return check;
}
};
#endif
struct CurrentJobPairHash
{
std::size_t operator() (const std::pair<const std::string, error_job_rep> &pair) const
{
std::size_t h1 = std::hash<std::string>()(pair.first);
std::size_t h2 = std::hash<error_job_rep>()(pair.second);
return h1 ^ h2;
}
};
// other file
BlockingUnorderedMap<std::string>, job_status_t, CurrentJobPairHash> current_jobs_;
|
Acidburn0zzz/SpiderOakMobileClient | src/collections/ShareRoomsCollections.js | <gh_stars>0
/**
* ShareRoomsCollection.js
*/
(function (spiderOakApp, window, undefined) {
"use strict";
var console = window.console || {};
console.log = console.log || function(){};
var Backbone = window.Backbone,
_ = window._,
$ = window.$;
var ppcb = spiderOakApp.PasswordProtectedCollectionBase;
spiderOakApp.ShareRoomsCollection = ppcb.extend({
model: spiderOakApp.ShareRoomModel,
initialize: function() {
this.url = ("https://" +
spiderOakApp.settings.getValue("server") +
"/share/");
},
hasByAttributes: function(share_id, room_key) {
return this.get(this.attributesToId(share_id, room_key));
},
attributesToId: function (share_id, room_key) {
return spiderOakApp.b32nibbler.encode(share_id) + "/" + room_key + "/";
},
which: "ShareRoomsCollection"
});
var ShareRoomsCollection = spiderOakApp.ShareRoomsCollection;
spiderOakApp.PublicShareRoomsCollection = ShareRoomsCollection.extend({
settingPrefix: "pubshares_",
model: spiderOakApp.PublicShareRoomModel,
initialize: function () {
var got = ShareRoomsCollection.prototype.initialize.call(this);
this.on("add", this.addHandler);
this.on("remove", this.removeHandler);
/** A hash of the public ShareRooms being visited, mapped to their
* local storage retention election. Retain is 0 or 1 for compactness.
* {"<b32(share_id)>/<room_key>": <retain?>, ...}
*/
if (! spiderOakApp.visitingPubShares) {
spiderOakApp.visitingPubShares = this.getRetainedRecords();
if (spiderOakApp.accountModel.getLoginState() === true) {
// Include the records from the anonymous collection, too:
spiderOakApp.visitingPubSharesAnon = this.getRetainedRecords(true);
}
else {
spiderOakApp.visitingPubSharesAnon = {};
}
}
return got;
},
reset: function (models, options) {
ShareRoomsCollection.prototype.reset.call(this, models, options);
spiderOakApp.visitingPubShares = null;
spiderOakApp.visitingPubSharesAnon = null;
},
/**
* Fetch public ShareRooms according to the recorded collection of
* those being visited.
*/
fetch: function (options) {
// Fetch according to the recorded list of those being visited.
var all = _.clone(spiderOakApp.visitingPubShares);
_.extend(all, spiderOakApp.visitingPubSharesAnon);
_.each(all, function (remember, modelId) {
var splat = modelId.split("/"),
share_id = spiderOakApp.b32nibbler.decode(splat[0]),
room_key = splat[1];
this.add({share_id: share_id,
room_key: room_key,
remember: remember,
beenSituated: true});
}.bind(this));
// addHandler does the fetch for each model.
},
addHandler: function(model, collection, options) {
var surroundingSuccess = options && options.success,
surroundingError = options && options.error;
var preserve = function (model) {
spiderOakApp.visitingPubShares[model.id] =
model.get("remember") ? 1 : 0;
// We always save to account for subtle changes, like remember status.
this.saveRetainedRecords();
}.bind(this);
_.extend(options, {
success: function(model, response, options) {
preserve(model);
if (surroundingSuccess) {
surroundingSuccess(model, response, options);
}
}.bind(this),
error: function(model, response, options) {
if (model.get("beenSituated")) {
preserve(model);
}
else {
this.remove(model);
if (surroundingError) {
surroundingError(model, response, options);
}
}
}.bind(this)
});
model.fetch(options);
},
removeHandler: function(model, collection, options) {
/* Do both current account and anonymous, independently.
This may mean removing an item from both - proper. */
if (spiderOakApp.visitingPubShares.hasOwnProperty(model.id)) {
delete spiderOakApp.visitingPubShares[model.id];
this.saveRetainedRecords();
}
if (spiderOakApp.visitingPubSharesAnon.hasOwnProperty(model.id)) {
delete spiderOakApp.visitingPubSharesAnon[model.id];
this.saveRetainedRecords(true);
}
},
getRetainedRecords: function(anonymous) {
var setting = spiderOakApp.settings.get(this.settingName(anonymous));
if (! setting) {
return {};
}
try {
return JSON.parse(setting.get("value"));
} catch (e) {
if (e instanceof SyntaxError) {
console.log("Removing malformed locally stored" +
" Public ShareRoom records: " +
setting.get("value"));
this.removeRetainedRecords(anonymous);
return {};
}
}
},
/** Update app ledger that tracks retaineds, and record in local storage.
*/
saveRetainedRecords: function(anonymous) {
var retain = {},
model,
they = (anonymous ?
spiderOakApp.visitingPubSharesAnon :
spiderOakApp.visitingPubShares);
_.each(they, function (value, key) {
model = this.get(key);
if (model && model.get("remember") !== value) {
// Update ledger with the model's new value:
they[key] = value = model.get("remember");
}
if (value) { retain[key] = value; }
}.bind(this));
spiderOakApp.settings.setOrCreate(this.settingName(anonymous),
JSON.stringify(retain),
1);
},
removeRetainedRecords: function(anonymous) {
spiderOakApp.settings.remove(this.settingName(anonymous));
},
/** Get the name of our setting object, per authenticated account.
*
* @param {object} anonymous true to force the name for non-authenticated
*/
settingName: function(anonymous) {
// "anonymous" should never collide with all-upper-case base32 names.
var name = "anonymous";
if (! anonymous) {
name = spiderOakApp.accountModel.get("b32username") || name;
}
return this.settingPrefix + name;
},
which: "PublicShareRoomsCollection"
});
spiderOakApp.MyShareRoomsCollection = ShareRoomsCollection.extend({
initialize: function () {
try {
return ShareRoomsCollection.prototype.initialize.call(this);
}
finally {
this.on("complete", this.completeHandler, this);
}
},
completeHandler: function(options) {
this.each(function (model) {
// Don't pass the options we get - they're for the collection.
model.fetch();
});
},
parse: function(resp, options) {
var sharerooms = [],
share_id_b32 = resp.share_id_b32,
share_id = resp.share_id;
_.each(resp.share_rooms, function(shareroom){
sharerooms.push({
preliminary: true,
url: share_id_b32 + "/" + shareroom.room_key + "/",
share_id_b32: share_id_b32,
share_id: share_id,
room_key: shareroom.room_key,
name: shareroom.room_name,
description: shareroom.room_description,
number_of_folders: shareroom.number_of_folders,
number_of_files: shareroom.number_of_files,
browse_url: shareroom.url
});
});
return sharerooms;
},
which: "MyShareRoomsCollection"
});
})(window.spiderOakApp = window.spiderOakApp || {}, window);
|
dh256/adventofcode | 2020/Day10/tests.py | import pytest
from Adapters import Adapters
test_data1 = [('test1.txt',22),('test2.txt',52)]
test_data2 = [('test1.txt',35),('test2.txt',220)]
test_data3 = [('test1.txt',8),('test2.txt',19208)]
@pytest.mark.parametrize("file_name,built_in",test_data1)
def test_built_in(file_name,built_in):
adapters=Adapters(file_name)
assert adapters.built_in == built_in
@pytest.mark.parametrize("file_name,answer",test_data2)
def test_part1(file_name,answer):
adapters=Adapters(file_name)
assert adapters.part1() == answer
@pytest.mark.parametrize("file_name,answer",test_data3)
def test_part2(file_name,answer):
adapters=Adapters(file_name)
assert adapters.part2() == answer |
DBatOWL/tutorials | spring-5-webflux/src/test/java/com/baeldung/spring/serverconfig/TimeoutLiveTest.java | package com.baeldung.spring.serverconfig;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import io.netty.channel.ChannelOption;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import reactor.netty.http.client.HttpClient;
import reactor.netty.tcp.TcpClient;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@DirtiesContext
public class TimeoutLiveTest {
private static final String BASE_URL = "https://localhost:8443";
private static final int TIMEOUT_MILLIS = 2000;
private WebTestClient webTestClient;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setup() throws SSLException {
webTestClient = WebTestClient.bindToServer(getConnector())
.baseUrl(BASE_URL)
.build();
}
@Test
public void shouldTimeout() {
exception.expect(ReadTimeoutException.class);
webTestClient.get()
.uri("/timeout/{timeout}", 3)
.exchange();
}
@Test
public void shouldNotTimeout() {
WebTestClient.ResponseSpec response = webTestClient.get()
.uri("/timeout/{timeout}", 1)
.exchange();
response.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("OK");
}
private ReactorClientHttpConnector getConnector() throws SSLException {
SslContext sslContext = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
TcpClient tcpClient = TcpClient
.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT_MILLIS)
.doOnConnected(connection -> {
connection.addHandlerLast(new ReadTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
connection.addHandlerLast(new WriteTimeoutHandler(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
});
HttpClient httpClient = HttpClient.from(tcpClient).secure(t -> t.sslContext(sslContext));
return new ReactorClientHttpConnector(httpClient);
}
}
|
krishna13052001/LeetCode | 334 Increasing Triplet Subsequence py3.py | #!/usr/bin/python3
"""
Given an unsorted array return whether an increasing subsequence of length 3
exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
Example 1:
Input: [1,2,3,4,5]
Output: true
Example 2:
Input: [5,4,3,2,1]
Output: false
"""
from typing import List
from bisect import bisect_left
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
"""
Patience sort
LIS dp with binary search
"""
F = [float('inf') for _ in range(3)]
for n in nums:
i = bisect_left(F, n)
if i >= 2:
return True
F[i] = n
return False
|
lsabella/baishu-admin | node_modules/@antv/scale/src/pow.js | <gh_stars>1-10
/**
* @fileOverview 使用pow进行度量计算
* @author <EMAIL>
*/
const Base = require('./base');
const Linear = require('./linear');
// 求以a为次幂,结果为b的基数,如 x^^a = b;求x
function calBase(a, b) {
const e = Math.E;
const value = Math.pow(e, Math.log(b) / a); // 使用换底公式求底
return value;
}
/**
* 度量的Pow计算
* @class Scale.Log
*/
class Pow extends Linear {
_initDefaultCfg() {
super._initDefaultCfg();
this.type = 'pow';
/**
* @override
* pow 的坐标点的个数控制在10个以下
* @type {Number}
*/
this.tickCount = 10;
/**
* 进行pow计算的基数
* @type {Number}
*/
this.exponent = 2;
}
/**
* @override
*/
calculateTicks() {
const self = this;
const exponent = self.exponent;
let min;
let max = Math.ceil(calBase(exponent, self.max));
if (self.min >= 0) {
min = Math.floor(calBase(exponent, self.min));
} else {
min = 0;
}
if (min > max) {
const tmp = max;
max = min;
min = tmp;
}
const count = max - min;
const tickCount = self.tickCount;
const avg = Math.ceil(count / tickCount);
const ticks = [];
for (let i = min; i < max + avg; i = i + avg) {
ticks.push(Math.pow(i, exponent));
}
return ticks;
}
// 获取度量计算时,value占的定义域百分比
_getScalePercent(value) {
const max = this.max;
const min = this.min;
if (max === min) {
return 0;
}
const exponent = this.exponent;
const percent = (calBase(exponent, value) - calBase(exponent, min)) / (calBase(exponent, max) - calBase(exponent, min));
return percent;
}
/**
* @override
*/
scale(value) {
const percent = this._getScalePercent(value);
const rangeMin = this.rangeMin();
const rangeMax = this.rangeMax();
return rangeMin + percent * (rangeMax - rangeMin);
}
/**
* @override
*/
invert(value) {
const percent = (value - this.rangeMin()) / (this.rangeMax() - this.rangeMin());
const exponent = this.exponent;
const max = calBase(exponent, this.max);
const min = calBase(exponent, this.min);
const tmp = percent * (max - min) + min;
return Math.pow(tmp, exponent);
}
}
Base.Pow = Pow;
module.exports = Pow;
|
lnkkerst/oj-codes | src/luogu/P1010/26444526_ac_100_14ms_800k_noO2.cpp | #include <bits/stdc++.h>
using namespace std;
void work(int n) {
int i = 0, cnt = 0, h[50];
while(n) {
if(n & 1) h[++cnt] = i;
n >>= 1, ++i;
}
while(cnt) {
if(h[cnt] < 3) {
if(h[cnt] == 1 && cnt != 1) cout << "2+";
else if(h[cnt] == 1) cout << "2";
if((!h[cnt] || h[cnt] == 2) && cnt != 1) cout << "2(" << h[cnt] << ")+";
else if(!h[cnt] || h[cnt] == 2) cout << "2(" << h[cnt] << ")";
--cnt;
}
else {
cout << "2(";
work(h[cnt--]);
if(cnt) cout << ")+";
else cout << ")";
}
}
}
int main() {
int n;
cin >> n;
work(n);
return 0;
} |
ZhanJunLiau/raven-java | raven/src/test/java/com/getsentry/raven/buffer/BufferTest.java | <filename>raven/src/test/java/com/getsentry/raven/buffer/BufferTest.java
package com.getsentry.raven.buffer;
import java.io.File;
public class BufferTest {
protected void delete(File dir) {
if (!dir.exists()) {
return;
}
if (dir.isDirectory()) {
for (File c : dir.listFiles()) {
delete(c);
}
}
if (!dir.delete()) {
throw new RuntimeException("Failed to delete dir: " + dir);
}
}
}
|
Mu-L/thymeleaf | src/main/java/org/thymeleaf/expression/Sets.java | /*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.expression;
import java.util.Collection;
import java.util.Set;
import org.thymeleaf.util.SetUtils;
/**
* <p>
* Expression Object for performing set operations inside Thymeleaf Standard Expressions.
* </p>
* <p>
* An object of this class is usually available in variable evaluation expressions with the name
* {@code #sets}.
* </p>
*
* @author <NAME>
*
* @since 1.0
*
*/
public final class Sets {
public Set<?> toSet(final Object target) {
return SetUtils.toSet(target);
}
public int size(final Set<?> target) {
return SetUtils.size(target);
}
public boolean isEmpty(final Set<?> target) {
return SetUtils.isEmpty(target);
}
public boolean contains(final Set<?> target, final Object element) {
return SetUtils.contains(target, element);
}
public boolean containsAll(final Set<?> target, final Object[] elements) {
return SetUtils.containsAll(target, elements);
}
public boolean containsAll(final Set<?> target, final Collection<?> elements) {
return SetUtils.containsAll(target, elements);
}
public Sets() {
super();
}
}
|
jonbonJoeB/epi | arrays/src/main/java/ComputeSpiralOrdering.java | <reponame>jonbonJoeB/epi
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComputeSpiralOrdering {
/*
5.18
*/
public static List<Integer> matrixInSpiralOrder(List<List<Integer>> squareMatrix) {
if (squareMatrix == null || squareMatrix.size() == 0 || squareMatrix.get(0).size() == 0) {
return Collections.emptyList();
}
final List<Integer> result = new ArrayList<>();
int topRow = 0, botRow = squareMatrix.size() - 1;
int leftCol = 0, rightCol = squareMatrix.get(0).size() - 1;
while (topRow <= botRow && leftCol <= rightCol) {
// Add top row from left to right
for (int i = leftCol; i <= rightCol; i++) {
result.add(squareMatrix.get(topRow).get(i));
}
topRow++;
// Add right col from top to bot
for (int i = topRow; i <= botRow; i++) {
result.add(squareMatrix.get(i).get(rightCol));
}
rightCol--;
if (topRow <= botRow) {
// Add bot row from right to left
for (int i = rightCol; i >= leftCol; i--) {
result.add(squareMatrix.get(botRow).get(i));
}
botRow--;
}
if (leftCol <= rightCol) {
// Add left col from bot to top
for (int i = botRow; i >= topRow; i--) {
result.add(squareMatrix.get(i).get(leftCol));
}
leftCol++;
}
}
return result;
}
}
|
rsachdeva/illuminatingdeposits-rest | usermgmt/usermgmtsvc_test.go | <filename>usermgmt/usermgmtsvc_test.go
// Adds test that starts a Http server and client tests the user mgmt service with http routing
package usermgmt_test
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"github.com/rsachdeva/illuminatingdeposits-rest/testserver"
"github.com/rsachdeva/illuminatingdeposits-rest/usermgmt/uservalue"
"github.com/stretchr/testify/require"
)
func TestServiceServer_CreateUser(t *testing.T) {
t.Parallel()
cr := testserver.InitRestHttpTLS(t, true)
client := cr.TestClient
address := cr.URL
fmt.Printf("address is %v\n", address)
url := fmt.Sprintf("%v/v1/users", address)
method := "POST"
usr := `{
"name": "<NAME>",
"email": "<EMAIL>",
"roles": ["USER"],
"password": "<PASSWORD>",
"password_confirm": "<PASSWORD>"}`
fmt.Println("usr is ", usr)
payload := strings.NewReader(usr)
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
// body, err := ioutil.ReadAll(res.Body)
// if err != nil {
// fmt.Println(err)
// return
// }
// fmt.Println("in string the body is", string(body))
var nu uservalue.User
decoder := json.NewDecoder(res.Body)
decoder.DisallowUnknownFields()
err = decoder.Decode(&nu)
require.Nil(t, err, "user decording should not give error")
fmt.Printf("nu is %v", nu)
require.NotNil(t, nu.Uuid, "UUID should not be nil")
require.Equal(t, "<EMAIL>", nu.Email)
}
|
Sirherobrine23/Dir819gpl_code | DIR819_v1.06/src/kernel/linux-2.6.36.x/drivers/net/eip93_drivers/quickSec/src/lib/sshutil/sshadt/sshadt.c | <gh_stars>1-10
/*
sshadt.c
Author: <NAME> <<EMAIL>>
Copyright:
Copyright (c) 2002, 2003 SFNT Finland Oy.
All rights reserved.
Created Wed Sep 8 17:41:05 1999.
*/
#include "sshincludes.h"
#include "sshadt_i.h"
#include "sshdebug.h"
#define SSH_DEBUG_MODULE "SshADT"
/******************************************************** Default callbacks. */
int ssh_adt_default_compare(const void *obj1, const void *obj2,
void *context)
{
if (obj1 < obj2) return -1;
if (obj1 > obj2) return 1;
return 0;
}
void *ssh_adt_default_duplicate(void *obj, void *context)
{
return obj;
}
void ssh_adt_default_copy(void *dst, size_t d_size,
const void *src, void *context)
{
SSH_DEBUG(9, ("Copying %d bytes from %p to %p.", d_size, src, dst));
memcpy(dst, src, d_size);
}
void ssh_adt_default_destroy(void *obj, void *context)
{
return;
}
void ssh_adt_default_init(void *obj, size_t size, void *context)
{
memset(obj, 0, size);
}
SshUInt32 ssh_adt_default_hash(const void *obj, void *context)
{
/* This kludge is here to remove a compilation warning on 64-bit
platforms. */
unsigned long ptr_num = (unsigned long) obj;
return (SshUInt32) ptr_num;
}
/**************************************** Initialize and destroy containers. */
static void set_default_values(SshADTStandardFields *f)
{
f->app_methods.compare = ssh_adt_default_compare;
f->app_methods.copy = ssh_adt_default_copy;
f->app_methods.duplicate = ssh_adt_default_duplicate;
f->app_methods.destr = ssh_adt_default_destroy;
f->app_methods.init = ssh_adt_default_init;
f->app_methods.hash = ssh_adt_default_hash;
f->app_methods.cleanup = NULL_FNPTR;
f->app_methods.map_attach = NULL_FNPTR;
f->app_methods.map_detach = NULL_FNPTR;
f->app_methods.context = NULL;
}
static Boolean init_toplevel_container(SshADTContainer c,
SshADTContainerType type,
va_list args)
{
SshADTArgumentType t;
SshADTContainerParsStruct pars, *ptr;
const SshADTStaticData *static_data;
SSH_PRECOND(type != NULL);
memset(&pars, 0, sizeof(pars));
set_default_values(&(pars.f));
ptr = &(pars);
ptr->type = type;
while ((t = va_arg(args, SshADTArgumentType)) != SSH_ADT_ARGS_END)
{
switch (t)
{
case SSH_ADT_CONTEXT:
ptr->f.app_methods.context = va_arg(args, void *);
SSH_DEBUG(9, ("Registered callback context @%p.",
ptr->f.app_methods.context));
break;
case SSH_ADT_COMPARE:
ptr->f.app_methods.compare = va_arg(args, SshADTCompareFunc);
SSH_DEBUG(9, ("Registered compare callback @%p.",
ptr->f.app_methods.compare));
break;
case SSH_ADT_COPY:
ptr->f.app_methods.copy = va_arg(args, SshADTCopyFunc);
SSH_DEBUG(9, ("Registered copy callback @%p.",
ptr->f.app_methods.copy));
break;
case SSH_ADT_DUPLICATE:
ptr->f.app_methods.duplicate = va_arg(args, SshADTDuplicateFunc);
SSH_DEBUG(9, ("Registered duplicate callback @%p.",
ptr->f.app_methods.duplicate));
break;
case SSH_ADT_DESTROY:
ptr->f.app_methods.destr = va_arg(args, SshADTDestroyFunc);
SSH_DEBUG(9, ("Registered destroy callback @%p.",
ptr->f.app_methods.destr));
break;
case SSH_ADT_HASH:
ptr->f.app_methods.hash = va_arg(args, SshADTHashFunc);
SSH_DEBUG(9, ("Registered hash callback @%p.",
ptr->f.app_methods.hash));
break;
case SSH_ADT_INIT:
ptr->f.app_methods.init = va_arg(args, SshADTInitFunc);
SSH_DEBUG(9, ("Registered init callback @%p.",
ptr->f.app_methods.init));
break;
case SSH_ADT_MAP_ATTACH:
ptr->f.app_methods.map_attach = va_arg(args, SshADTMapAttachFunc);
SSH_DEBUG(9, ("Registered map_attach callback @%p.",
ptr->f.app_methods.map_attach));
break;
case SSH_ADT_MAP_DETACH:
ptr->f.app_methods.map_detach = va_arg(args, SshADTMapDetachFunc);
SSH_DEBUG(9, ("Registered map_detach callback @%p.",
ptr->f.app_methods.map_detach));
break;
case SSH_ADT_CLEANUP:
ptr->f.app_methods.cleanup = va_arg(args, SshADTCleanupFunc);
SSH_DEBUG(9, ("Registered cleanup callback @%p.",
ptr->f.app_methods.cleanup));
break;
case SSH_ADT_SIZE:
ptr->flags |= SSH_ADT_FLAG_ALLOCATE;
ptr->f.default_object_size = va_arg(args, size_t);
break;
case SSH_ADT_HEADER:
ptr->flags |= SSH_ADT_FLAG_CONTAINED_HEADER;
ptr->f.header_offset = va_arg(args, SshUInt32);
break;
default:
SSH_NOTREACHED;
}
}
#ifdef _KERNEL
/* In kernel mode, objects must be concrete. (Also, if there is a
header structure at all, it must be inlined. This is checked in
the implementations because at least array does not need headers
and thus this restriction is void.) */
SSH_ASSERT(!(ptr->flags & SSH_ADT_FLAG_ALLOCATE));
#endif
static_data = pars.type;
return ((*(static_data->methods.container_init))(c, ptr));
}
SshADTContainer ssh_adt_create_generic(SshADTContainerType type, ...)
{
va_list args;
SshADTContainer c;
if (!(c = ssh_malloc(sizeof(*c))))
return NULL;
va_start(args, type);
if (init_toplevel_container(c, type, args) == FALSE)
{
ssh_free(c);
va_end(args);
return NULL;
}
else
{
va_end(args);
return c;
}
}
void ssh_adt_destroy(SshADTContainer container)
{
if (!container)
return;
(*(container->static_data->methods.destr))(container);
ssh_free(container);
}
#if 0
void ssh_adt_init_generic(SshADTContainer container,
SshADTContainerType type, ...)
{
va_list args;
va_start(args, type);
init_toplevel_container(container, type, args);
va_end(args);
}
void ssh_adt_uninit(SshADTContainer container)
{
SSH_ADT_CALL_DESTROY_HOOK(container, destr);
SSH_ADT_CALL(container, FALSE, container_uninit, (container));
ssh_free(container->hooks);
}
#endif
/************************************************************* Record magic. */
void *ssh_adt_duplicate_object(SshADTContainer container, void *object)
{
void *result;
SSH_ADT_CALL_APP_MANDATORY(container, duplicate,
(object, SSH_ADT_APPCTX(container)), result);
return result;
}
/******************************************************************** Hooks. */
int ssh_adt_initialize_hooks(SshADTContainer container)
{
ssh_free(container->hooks);
if (!(container->hooks = ssh_malloc(sizeof(*container->hooks))))
return 1;
container->hooks->insert = NULL_FNPTR;
container->hooks->detach = NULL_FNPTR;
container->hooks->map = NULL_FNPTR;
container->hooks->unmap = NULL_FNPTR;
container->hooks->reallocated = NULL_FNPTR;
container->hooks->destr = NULL_FNPTR;
return 0;
}
void ssh_adt_uninitialize_hooks(SshADTContainer container)
{
ssh_free(container->hooks);
container->hooks = NULL;
}
#ifndef SSH_ADT_WITH_MACRO_INTERFACE
#define SSH_ADT_INTERNAL_MACROS
#include "sshadt_impls.h"
#undef SSH_ADT_INTERNAL_MACROS
/****************************************************** Non-macro Interface. */
#define SSH_ADT_ASSERT_CONTAINER SSH_PRECOND(container != NULL)
#define SSH_ADT_ASSERT_EXTERNAL \
SSH_PRECOND(SSH_ADT_DEFAULT_SIZE(container) == 0)
#define SSH_ADT_ASSERT_INTERNAL \
SSH_PRECOND(SSH_ADT_DEFAULT_SIZE(container) != 0)
#define SSH_ADT_ASSERT_HANDLE SSH_PRECOND(handle != SSH_ADT_INVALID)
#define SSH_ADT_ASSERT_OBJECT SSH_PRECOND(object != NULL)
size_t ssh_adt_default_size(SshADTContainer container)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
return SSH_ADT_DEFAULT_SIZE(container);
}
void ssh_adt_clear(SshADTContainer container)
{
SSH_ADT_ASSERT_CONTAINER;
ssh_adt_clear__(container);
}
SshADTHandle ssh_adt_insert_at(SshADTContainer container,
SshADTRelativeLocation location,
SshADTHandle handle,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
SSH_ADT_ASSERT_HANDLE;
if (container->flags & SSH_ADT_FLAG_CONTAINED_HEADER)
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.insert_at != NULL_FNPTR);
return ssh_adt_insert_at__(container, location, handle, object);
}
SshADTHandle ssh_adt_insert_to(SshADTContainer container,
SshADTAbsoluteLocation location,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
if (container->flags & SSH_ADT_FLAG_CONTAINED_HEADER)
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.insert_to != NULL_FNPTR);
return ssh_adt_insert_to__(container, location, object);
}
SshADTHandle ssh_adt_insert(SshADTContainer container,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
if (container->flags & SSH_ADT_FLAG_CONTAINED_HEADER)
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.insert_to != NULL_FNPTR);
return ssh_adt_insert_to(container, SSH_ADT_DEFAULT, object);
}
SshADTHandle ssh_adt_duplicate_at(SshADTContainer container,
SshADTRelativeLocation location,
SshADTHandle handle,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
if (container->flags & SSH_ADT_FLAG_CONTAINED_HEADER)
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.insert_at != NULL_FNPTR);
return ssh_adt_insert_at(container, location, handle,
ssh_adt_duplicate_object(container, object));
}
SshADTHandle ssh_adt_duplicate_to(SshADTContainer container,
SshADTAbsoluteLocation location,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
if (container->flags & SSH_ADT_FLAG_CONTAINED_HEADER)
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.insert_to != NULL_FNPTR);
return ssh_adt_insert_to(container, location,
ssh_adt_duplicate_object(container, object));
}
SshADTHandle ssh_adt_duplicate(SshADTContainer container,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
if (container->flags & SSH_ADT_FLAG_CONTAINED_HEADER)
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.insert_to != NULL_FNPTR);
return ssh_adt_insert(container,
ssh_adt_duplicate_object(container, object));
}
SshADTHandle ssh_adt_alloc_n_at(SshADTContainer container,
SshADTRelativeLocation location,
SshADTHandle handle,
size_t size)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.alloc_n_at != NULL_FNPTR);
return ssh_adt_alloc_n_at__(container, location, handle, size);
}
SshADTHandle ssh_adt_alloc_n_to(SshADTContainer container,
SshADTAbsoluteLocation location,
size_t size)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ASSERT(container->static_data->methods.alloc_n_to != NULL_FNPTR);
return ssh_adt_alloc_n_to__(container, location, size);
}
SshADTHandle ssh_adt_alloc_at(SshADTContainer container,
SshADTRelativeLocation location,
SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.alloc_n_at != NULL_FNPTR);
return ssh_adt_alloc_n_at(container, location,
handle, SSH_ADT_DEFAULT_SIZE(container));
}
SshADTHandle ssh_adt_alloc_to(SshADTContainer container,
SshADTAbsoluteLocation location)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ASSERT(container->static_data->methods.alloc_n_to != NULL_FNPTR);
return ssh_adt_alloc_n_to(container, location,
SSH_ADT_DEFAULT_SIZE(container));
}
SshADTHandle ssh_adt_alloc_n(SshADTContainer container,
size_t size)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ASSERT(container->static_data->methods.alloc_n_to != NULL_FNPTR);
return ssh_adt_alloc_n_to(container, SSH_ADT_DEFAULT, size);
}
SshADTHandle ssh_adt_alloc(SshADTContainer container)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ASSERT(container->static_data->methods.alloc_n_to != NULL_FNPTR);
return ssh_adt_alloc_n(container, SSH_ADT_DEFAULT_SIZE(container));
}
SshADTHandle ssh_adt_put_n_at(SshADTContainer container,
SshADTRelativeLocation location,
SshADTHandle handle,
size_t size,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_HANDLE;
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.put_n_at != NULL_FNPTR);
return ssh_adt_put_n_at__(container, location, handle, size, object);
}
SshADTHandle ssh_adt_put_n_to(SshADTContainer container,
SshADTAbsoluteLocation location,
size_t size,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.put_n_to != NULL_FNPTR);
return ssh_adt_put_n_to__(container, location, size, object);
}
SshADTHandle ssh_adt_put_at(SshADTContainer container,
SshADTRelativeLocation location,
SshADTHandle handle,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_HANDLE;
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.put_n_at != NULL_FNPTR);
return ssh_adt_put_n_at(container, location, handle,
SSH_ADT_DEFAULT_SIZE(container), object);
}
SshADTHandle ssh_adt_put_to(SshADTContainer container,
SshADTAbsoluteLocation location,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.put_n_to != NULL_FNPTR);
return ssh_adt_put_n_to(container, location,
SSH_ADT_DEFAULT_SIZE(container), object);
}
SshADTHandle ssh_adt_put_n(SshADTContainer container,
size_t size,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.put_n_to != NULL_FNPTR);
return ssh_adt_put_n_to(container, SSH_ADT_DEFAULT, size, object);
}
SshADTHandle ssh_adt_put(SshADTContainer container,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_INTERNAL;
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.put_n_to != NULL_FNPTR);
return ssh_adt_put_n(container, SSH_ADT_DEFAULT_SIZE(container), object);
}
void *ssh_adt_get(SshADTContainer container, SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.get != NULL_FNPTR);
return ssh_adt_get__(container, handle);
}
size_t ssh_adt_num_objects(SshADTContainer container)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ASSERT(container->static_data->methods.num_objects != NULL_FNPTR);
return ssh_adt_num_objects__(container);
}
SshADTHandle ssh_adt_get_handle_to(SshADTContainer container,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
if (container->flags & (SSH_ADT_FLAG_CONTAINED_HEADER |
SSH_ADT_FLAG_ALLOCATE))
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.get_handle_to != NULL_FNPTR);
return ssh_adt_get_handle_to__(container, object);
}
SshADTHandle ssh_adt_get_handle_to_equal(SshADTContainer container,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
if (container->flags & (SSH_ADT_FLAG_CONTAINED_HEADER |
SSH_ADT_FLAG_ALLOCATE))
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.get_handle_to_equal !=
NULL_FNPTR);
return ssh_adt_get_handle_to_equal__(container, object);
}
void *ssh_adt_get_object_from_equal(SshADTContainer container,
void *object)
{
SSH_ADT_ASSERT_CONTAINER;
if (container->flags & (SSH_ADT_FLAG_CONTAINED_HEADER |
SSH_ADT_FLAG_ALLOCATE))
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.get_handle_to_equal !=
NULL_FNPTR);
return ssh_adt_get(container,
ssh_adt_get_handle_to_equal__(container, object));
}
SshADTHandle ssh_adt_next(SshADTContainer container, SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.next != NULL_FNPTR);
return ssh_adt_next__(container, handle);
}
SshADTHandle ssh_adt_previous(SshADTContainer container, SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.previous != NULL_FNPTR);
return ssh_adt_previous__(container, handle);
}
SshADTHandle ssh_adt_get_handle_to_location(SshADTContainer container,
SshADTAbsoluteLocation location)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ASSERT(container->static_data->methods.get_handle_to_location !=
NULL_FNPTR);
return ssh_adt_get_handle_to_location__(container, location);
}
void *ssh_adt_get_object_from_location(SshADTContainer container,
SshADTAbsoluteLocation location)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ASSERT(container->static_data->methods.get_handle_to_location !=
NULL_FNPTR);
return ssh_adt_get(container,
ssh_adt_get_handle_to_location__(container, location));
}
void *ssh_adt_detach(SshADTContainer container, SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.detach != NULL_FNPTR);
return ssh_adt_detach__(container, handle);
}
void *ssh_adt_detach_from(SshADTContainer container,
SshADTAbsoluteLocation location)
{
SshADTHandle handle;
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
SSH_ASSERT(container->static_data->methods.detach != NULL_FNPTR);
SSH_ASSERT(container->static_data->methods.get_handle_to_location !=
NULL_FNPTR);
handle = ssh_adt_get_handle_to_location(container, location);
SSH_ADT_ASSERT_HANDLE;
return ssh_adt_detach(container, handle);
}
void *ssh_adt_detach_object(SshADTContainer container,
void *object)
{
SshADTHandle handle;
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_EXTERNAL;
if (container->flags & (SSH_ADT_FLAG_CONTAINED_HEADER |
SSH_ADT_FLAG_ALLOCATE))
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.detach != NULL_FNPTR);
SSH_ASSERT(container->static_data->methods.get_handle_to != NULL_FNPTR);
handle = ssh_adt_get_handle_to(container, object);
SSH_ADT_ASSERT_HANDLE;
return ssh_adt_detach(container, handle);
}
void ssh_adt_delete(SshADTContainer container, SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.delet != NULL_FNPTR);
ssh_adt_delete__(container, handle);
}
void ssh_adt_delete_from(SshADTContainer container,
SshADTAbsoluteLocation location)
{
SshADTHandle handle;
SSH_ADT_ASSERT_CONTAINER;
SSH_ASSERT(container->static_data->methods.delet != NULL_FNPTR);
SSH_ASSERT(container->static_data->methods.get_handle_to_location !=
NULL_FNPTR);
handle = ssh_adt_get_handle_to_location(container, location);
SSH_ADT_ASSERT_HANDLE;
ssh_adt_delete(container, handle);
}
void ssh_adt_delete_object(SshADTContainer container,
void *object)
{
SshADTHandle handle;
SSH_ADT_ASSERT_CONTAINER;
if (container->flags & (SSH_ADT_FLAG_CONTAINED_HEADER |
SSH_ADT_FLAG_ALLOCATE))
SSH_ADT_ASSERT_OBJECT;
SSH_ASSERT(container->static_data->methods.delet != NULL_FNPTR);
SSH_ASSERT(container->static_data->methods.get_handle_to != NULL_FNPTR);
handle = ssh_adt_get_handle_to(container, object);
SSH_ADT_ASSERT_HANDLE;
ssh_adt_delete(container, handle);
}
SshADTHandle ssh_adt_enumerate_start(SshADTContainer container)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ASSERT(container->static_data->methods.enumerate_start != NULL_FNPTR);
return ssh_adt_enumerate_start__(container);
}
SshADTHandle ssh_adt_enumerate_next(SshADTContainer container,
SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.enumerate_next != NULL_FNPTR);
return ssh_adt_enumerate_next__(container, handle);
}
void *ssh_adt_map_lookup(SshADTContainer container, SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.map_lookup != NULL_FNPTR);
return ssh_adt_map_lookup__(container, handle);
}
void ssh_adt_map_attach(SshADTContainer container,
SshADTHandle handle, void *obj)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.map_attach != NULL_FNPTR);
ssh_adt_map_attach__(container, handle, obj);
}
/* (for ssh_adt_detach_i, see comment in sshadt_i.h) */
void *ssh_adt_detach_i(SshADTContainer container, SshADTHandle handle)
{
SSH_ADT_ASSERT_CONTAINER;
SSH_ADT_ASSERT_HANDLE;
SSH_ASSERT(container->static_data->methods.detach != NULL_FNPTR);
return ssh_adt_detach__(container, handle);
}
#endif /* !SSH_ADT_WITH_MACRO_INTERFACE */
|
danielbmancini/JHTP8_JCP8_Sol._Comentadas | 18/src/RecursivePalindromeTesting.java | <filename>18/src/RecursivePalindromeTesting.java
/*
exercise 18.14
*/
import java.util.Scanner;
public class RecursivePalindromeTesting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("(Insert candidate)\n");
char[] string = scanner.nextLine().replaceAll("[ .,?'!\":;]", "") //removes punctuation, white spaces and turns everything lower case
.toLowerCase().toCharArray();
System.out.println(testPalindrome(0, string.length - 1, string));
}
private static boolean testPalindrome(int lo, int hi, char[] candidate) {
boolean evenCase = (hi - lo == 1) && (candidate[lo] == candidate[hi]); //base case for candidates with an even length
if (lo == hi || evenCase)
return true;
else if (candidate[lo] == candidate[hi])
return testPalindrome(lo + 1, hi - 1, candidate);
return false;
}
}
|
npocmaka/Windows-Server-2003 | sdktools/rcdll/rc.c | <reponame>npocmaka/Windows-Server-2003<filename>sdktools/rcdll/rc.c
/***********************************************************************
* Microsoft (R) Windows (R) Resource Compiler
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* File Comments:
*
*
***********************************************************************/
#include "rc.h"
#include <setjmp.h>
#include <ddeml.h>
#define READ_MAX (MAXSTR+80)
#define MAX_CMD 256
#define cDefineMax 100
wchar_t resname[_MAX_PATH];
wchar_t *szRCPP[MAX_CMD];
BOOL fRcppAlloc[MAX_CMD];
/************************************************************************/
/* Define Global Variables */
/************************************************************************/
int __cdecl rcpp_main(int, wchar_t *[]);
SHORT ResCount; /* number of resources */
PTYPEINFO pTypInfo;
SHORT nFontsRead;
FONTDIR *pFontList;
FONTDIR *pFontLast;
TOKEN token;
int errorCount;
WCHAR tokenbuf[ MAXSTR + 1 ];
wchar_t exename[ _MAX_PATH ];
wchar_t fullname[ _MAX_PATH ];
wchar_t curFile[ _MAX_PATH ];
HANDLE hHeap = NULL;
PDLGHDR pLocDlg;
UINT mnEndFlagLoc; /* patch location for end of a menu. */
/* we set the high order bit there */
/* BOOL fLeaveFontDir; */
BOOL fVerbose; /* verbose mode (-v) */
BOOL fAFXSymbols;
BOOL fMacRsrcs;
BOOL fAppendNull;
BOOL fWarnInvalidCodePage;
BOOL fSkipDuplicateCtlIdWarning;
long lOffIndex;
WORD idBase;
BOOL fPreprocessOnly;
wchar_t szBuf[_MAX_PATH * 2];
wchar_t szPreProcessName[_MAX_PATH];
/* File global variables */
wchar_t inname[_MAX_PATH];
wchar_t *szTempFileName;
wchar_t *szTempFileName2;
PFILE fhBin;
PFILE fhInput;
/* array for include path stuff, initially empty */
wchar_t *pchInclude;
/* Substitute font name */
int nBogusFontNames;
WCHAR *pszBogusFontNames[16];
WCHAR szSubstituteFontName[MAXTOKSTR];
static jmp_buf jb;
extern ULONG lCPPTotalLinenumber;
/* Function prototypes for local functions */
HANDLE RCInit(void);
void RC_PreProcess(const wchar_t *);
void CleanUpFiles(void);
/*---------------------------------------------------------------------------*/
/* */
/* rc_main() - */
/* */
/*---------------------------------------------------------------------------*/
int __cdecl
rc_main(
int argc,
wchar_t *argv[],
char *argvA[]
)
{
wchar_t *r;
wchar_t *x;
wchar_t *s1;
wchar_t *s2;
wchar_t *s3;
int n;
wchar_t *pchIncludeT;
ULONG cchIncludeMax;
int fInclude = TRUE; /* by default, search INCLUDE */
int fIncludeCurrentFirst = TRUE; /* by default, add current dir to start of includes */
int cDefine = 0;
int cUnDefine = 0;
wchar_t *pszDefine[cDefineMax];
wchar_t *pszUnDefine[cDefineMax];
wchar_t szDrive[_MAX_DRIVE];
wchar_t szDir[_MAX_DIR];
wchar_t szFName[_MAX_FNAME];
wchar_t szExt[_MAX_EXT];
wchar_t szFullPath[_MAX_PATH];
wchar_t szIncPath[_MAX_PATH];
wchar_t buf[10];
wchar_t *szRC;
wchar_t **ppargv;
BOOL *pfRcppAlloc;
int rcpp_argc;
/* Set up for this run of RC */
if (_setjmp(jb)) {
return Nerrors;
}
hHeap = RCInit();
if (hHeap == NULL) {
fatal(1120, 0x01000000);
}
if (argvA != NULL) {
argv = UnicodeCommandLine(argc, argvA);
}
pchInclude = pchIncludeT = (wchar_t *) MyAlloc(_MAX_PATH * 2 * sizeof(wchar_t));
cchIncludeMax = _MAX_PATH*2;
szRC = argv[0];
/* process the command line switches */
while ((argc > 1) && (IsSwitchChar(*argv[1]))) {
switch (towupper(argv[1][1])) {
case L'?':
case L'H':
// Print out help, and quit
SendWarning(L"\n");
SET_MSG(10001, LVER_PRODUCTVERSION_STR);
SendWarning(Msg_Text);
SET_MSG(10002);
SendWarning(Msg_Text);
SET_MSG(20001);
SendWarning(Msg_Text);
return 0; /* can just return - nothing to cleanup, yet. */
case L'B':
if (towupper(argv[1][2]) == L'R') { /* base resource id */
unsigned long id;
if (isdigit(argv[1][3]))
argv[1] += 3;
else if (argv[1][3] == L':')
argv[1] += 4;
else {
argc--;
argv++;
if (argc <= 1)
goto BadId;
}
if (*(argv[1]) == 0)
goto BadId;
id = _wtoi(argv[1]);
if (id < 1 || id > 32767)
fatal(1210);
idBase = (WORD)id;
break;
BadId:
fatal(1209);
}
break;
case L'C':
/* Check for the existence of CodePage Number */
if (argv[1][2])
argv[1] += 2;
else {
argc--;
argv++;
}
/* Now argv point to first digit of CodePage */
if (!argv[1])
fatal(1204);
uiCodePage = _wtoi(argv[1]);
if (uiCodePage == 0)
fatal(1205);
/* Check if uiCodePage exist in registry. */
if (!IsValidCodePage (uiCodePage))
fatal(1206);
break;
case L'D':
/* if not attached to switch, skip to next */
if (argv[1][2])
argv[1] += 2;
else {
argc--;
argv++;
}
/* remember pointer to string */
pszDefine[cDefine++] = argv[1];
if (cDefine > cDefineMax) {
fatal(1105, argv[1]);
}
break;
case L'F':
switch (towupper(argv[1][2])) {
case L'O':
if (argv[1][3])
argv[1] += 3;
else {
argc--;
argv++;
}
if (argc > 1)
wcscpy(resname, argv[1]);
else
fatal(1101);
break;
default:
fatal(1103, argv[1]);
}
break;
case L'I':
/* add string to directories to search */
/* note: format is <path>\0<path>\0\0 */
/* if not attached to switch, skip to next */
if (argv[1][2])
argv[1] += 2;
else {
argc--;
argv++;
}
if (!argv[1])
fatal(1201);
if ((wcslen(argv[1]) + 1 + wcslen(pchInclude)) >= cchIncludeMax) {
cchIncludeMax = wcslen(pchInclude) + wcslen(argv[1]) + _MAX_PATH*2;
pchIncludeT = (wchar_t *) MyAlloc(cchIncludeMax * sizeof(wchar_t));
wcscpy(pchIncludeT, pchInclude);
MyFree(pchInclude);
pchInclude = pchIncludeT;
pchIncludeT = pchInclude + wcslen(pchIncludeT) + 1;
}
/* if not first switch, write over terminator with semicolon */
if (pchInclude != pchIncludeT)
pchIncludeT[-1] = L';';
/* copy the path */
while ((*pchIncludeT++ = *argv[1]++) != 0)
;
break;
case L'L':
/* if not attached to switch, skip to next */
if (argv[1][2])
argv[1] += 2;
else {
argc--;
argv++;
}
if (!argv[1])
fatal(1202);
if (swscanf(argv[1], L"%x", &language) != 1)
fatal(1203);
while (*argv[1]++ != 0)
;
break;
case L'M':
fMacRsrcs = TRUE;
goto MaybeMore;
case L'N':
fAppendNull = TRUE;
goto MaybeMore;
case L'P':
fPreprocessOnly = TRUE;
break;
case L'R':
goto MaybeMore;
case L'S':
// find out from BRAD what -S does
fAFXSymbols = TRUE;
break;
case L'U':
/* if not attached to switch, skip to next */
if (argv[1][2])
argv[1] += 2;
else {
argc--;
argv++;
}
/* remember pointer to string */
pszUnDefine[cUnDefine++] = argv[1];
if (cUnDefine > cDefineMax) {
fatal(1104, argv[1]);
}
break;
case L'V':
fVerbose = TRUE; // AFX doesn't set this
goto MaybeMore;
case L'W':
fWarnInvalidCodePage = TRUE; // Invalid Codepage is a warning, not an error.
goto MaybeMore;
case L'Y':
fSkipDuplicateCtlIdWarning = TRUE;
goto MaybeMore;
case L'X':
/* remember not to add INCLUDE path */
fInclude = FALSE;
// VC seems to feel the current dir s/b added first no matter what...
// If -X! is specified, don't do that.
if (argv[1][2] == L'!') {
fIncludeCurrentFirst = FALSE;
argv[1]++;
}
MaybeMore: /* check to see if multiple switches, like -xrv */
if (argv[1][2]) {
argv[1][1] = L'-';
argv[1]++;
continue;
}
break;
case L'Z':
/* if not attached to switch, skip to next */
if (argv[1][2])
argv[1] += 2;
else {
argc--;
argv++;
}
if (!argv[1])
fatal(1211);
s3 = wcschr(argv[1], L'/');
if (s3 == NULL)
fatal(1212);
*s3 = L'\0';
wcscpy(szSubstituteFontName, s3+1);
s1 = argv[1];
do {
s2 = wcschr(s1, L',');
if (s2 != NULL)
*s2 = L'\0';
if (wcslen(s1)) {
if (nBogusFontNames >= 16)
fatal(1213);
pszBogusFontNames[nBogusFontNames] = (WCHAR *) MyAlloc((wcslen(s1)+1) * sizeof(WCHAR));
wcscpy(pszBogusFontNames[nBogusFontNames], s1);
nBogusFontNames += 1;
}
if (s2 != NULL)
*s2++ = L',';
}
while (s1 = s2);
*s3 = L'/';
while (*argv[1]++ != 0)
;
break;
default:
fatal(1106, argv[1]);
}
/* get next argument or switch */
argc--;
argv++;
}
/* make sure we have at least one file name to work with */
if (argc != 2 || *argv[1] == L'\0')
fatal(1107);
if (fVerbose) {
SET_MSG(10001, LVER_PRODUCTVERSION_STR);
SendWarning(Msg_Text);
SET_MSG(10002);
SendWarning(Msg_Text);
SendWarning(L"\n");
}
// Support Multi Code Page
// If user did NOT indicate code in command line, we have to set Default
// for NLS Conversion
if (uiCodePage == 0) {
CHAR *pchCodePageString;
/* At first, search ENVIRONMENT VALUE */
if ((pchCodePageString = getenv("RCCODEPAGE")) != NULL) {
uiCodePage = atoi(pchCodePageString);
if (uiCodePage == 0 || !IsValidCodePage(uiCodePage)) {
fatal(1207);
}
} else {
// We use System ANSI Code page (ACP)
uiCodePage = GetACP();
}
}
uiDefaultCodePage = uiCodePage;
if (fVerbose) {
wprintf(L"Using codepage %d as default\n", uiDefaultCodePage);
}
/* If we have no extension, assumer .rc */
/* If .res extension, make sure we have -fo set, or error */
/* Otherwise, just assume file is .rc and output .res (or resname) */
_wsplitpath(argv[1], szDrive, szDir, szFName, szExt);
if (!(*szDir || *szDrive)) {
wcscpy(szIncPath, L".;");
} else {
wcscpy(szIncPath, szDrive);
wcscat(szIncPath, szDir);
wcscat(szIncPath, L";.;");
}
if ((wcslen(szIncPath) + 1 + wcslen(pchInclude)) >= cchIncludeMax) {
cchIncludeMax = wcslen(pchInclude) + wcslen(szIncPath) + _MAX_PATH*2;
pchIncludeT = (wchar_t *) MyAlloc(cchIncludeMax * sizeof(wchar_t));
wcscpy(pchIncludeT, pchInclude);
MyFree(pchInclude);
pchInclude = pchIncludeT;
pchIncludeT = pchInclude + wcslen(pchIncludeT) + 1;
}
pchIncludeT = (wchar_t *) MyAlloc(cchIncludeMax * sizeof(wchar_t));
if (fIncludeCurrentFirst) {
wcscpy(pchIncludeT, szIncPath);
wcscat(pchIncludeT, pchInclude);
} else {
wcscpy(pchIncludeT, pchInclude);
wcscat(pchIncludeT, L";");
wcscat(pchIncludeT, szIncPath);
}
MyFree(pchInclude);
pchInclude = pchIncludeT;
pchIncludeT = pchInclude + wcslen(pchIncludeT) + 1;
if (!szExt[0]) {
wcscpy(szExt, L".RC");
} else if (wcscmp(szExt, L".RES") == 0) {
fatal(1208);
}
_wmakepath(inname, szDrive, szDir, szFName, szExt);
if (fPreprocessOnly) {
_wmakepath(szPreProcessName, NULL, NULL, szFName, L".rcpp");
}
/* Create the name of the .RES file */
if (resname[0] == 0) {
// if building a Mac resource file, we use .rsc to match mrc's output
_wmakepath(resname, szDrive, szDir, szFName, fMacRsrcs ? L".RSC" : L".RES");
}
/* create the temporary file names */
szTempFileName = (wchar_t *) MyAlloc(_MAX_PATH * sizeof(wchar_t));
_wfullpath(szFullPath, resname, _MAX_PATH);
_wsplitpath(szFullPath, szDrive, szDir, NULL, NULL);
_wmakepath(szTempFileName, szDrive, szDir, L"RCXXXXXX", NULL);
_wmktemp (szTempFileName);
szTempFileName2 = (wchar_t *) MyAlloc(_MAX_PATH * sizeof(wchar_t));
_wmakepath(szTempFileName2, szDrive, szDir, L"RDXXXXXX", NULL);
_wmktemp(szTempFileName2);
ppargv = szRCPP;
pfRcppAlloc = fRcppAlloc;
*ppargv++ = L"RCPP";
*pfRcppAlloc++ = FALSE;
rcpp_argc = 1;
/* Open the .RES file (deleting any old versions which exist). */
if ((fhBin = _wfopen(resname, L"w+b")) == NULL) {
fatal(1109, resname);
}
if (fMacRsrcs)
MySeek(fhBin, MACDATAOFFSET, 0);
if (fVerbose) {
SET_MSG(10102, resname);
SendWarning(Msg_Text);
}
/* Set up for RCPP. This constructs the command line for it. */
*ppargv++ = _wcsdup(L"-CP");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
_itow(uiCodePage, buf, 10);
*ppargv++ = buf;
*pfRcppAlloc++ = FALSE;
rcpp_argc++;
*ppargv++ = _wcsdup(L"-f");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = _wcsdup(szTempFileName);
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = _wcsdup(L"-g");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
if (fPreprocessOnly) {
*ppargv++ = _wcsdup(szPreProcessName);
} else {
*ppargv++ = _wcsdup(szTempFileName2);
}
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = _wcsdup(L"-DRC_INVOKED");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
if (fAFXSymbols) {
*ppargv++ = _wcsdup(L"-DAPSTUDIO_INVOKED");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
}
if (fMacRsrcs) {
*ppargv++ = _wcsdup(L"-D_MAC");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
}
*ppargv++ = _wcsdup(L"-D_WIN32"); /* to be compatible with C9/VC++ */
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = _wcsdup(L"-pc\\:/");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = _wcsdup(L"-E");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
/* Parse the INCLUDE environment variable */
if (fInclude) {
*ppargv++ = _wcsdup(L"-I.");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
/* add seperator if any -I switches */
if (pchInclude != pchIncludeT)
pchIncludeT[-1] = L';';
/* read 'em */
x = _wgetenv(L"INCLUDE");
if (x == NULL) {
*pchIncludeT = L'\0';
} else {
if (wcslen(pchInclude) + wcslen(x) + 1 >= cchIncludeMax) {
cchIncludeMax = wcslen(pchInclude) + wcslen(x) + _MAX_PATH*2;
pchIncludeT = (wchar_t *) MyAlloc(cchIncludeMax * sizeof(wchar_t));
wcscpy(pchIncludeT, pchInclude);
MyFree(pchInclude);
pchInclude = pchIncludeT;
}
wcscat(pchInclude, x);
pchIncludeT = pchInclude + wcslen(pchInclude);
}
}
/* now put includes on the RCPP command line */
for (x = pchInclude ; *x ; ) {
r = x;
while (*x && *x != L';')
x = CharNextW(x);
/* mark if semicolon */
if (*x)
*x-- = 0;
if (*r != L'\0' && /* empty include path? */
*r != L'%' /* check for un-expanded stuff */
// && wcschr(r, L' ') == NULL /* check for whitespace */
) {
/* add switch */
*ppargv++ = _wcsdup(L"-I");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = _wcsdup(r);
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
}
/* was semicolon, need to fix for searchenv() */
if (*x) {
*++x = L';';
x++;
}
}
/* include defines */
for (n = 0; n < cDefine; n++) {
*ppargv++ = _wcsdup(L"-D");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = pszDefine[n];
*pfRcppAlloc++ = FALSE;
rcpp_argc++;
}
/* include undefine */
for (n = 0; n < cUnDefine; n++) {
*ppargv++ = _wcsdup(L"-U");
*pfRcppAlloc++ = TRUE;
rcpp_argc++;
*ppargv++ = pszUnDefine[n];
*pfRcppAlloc++ = FALSE;
rcpp_argc++;
}
if (rcpp_argc > MAX_CMD) {
fatal(1102);
}
if (fVerbose) {
/* echo the preprocessor command */
wprintf(L"RC:");
for (n = 0 ; n < rcpp_argc ; n++) {
wprintf(L" %s", szRCPP[n]);
}
wprintf(L"\n");
}
/* Add .rc with rcincludes into szTempFileName */
RC_PreProcess(inname);
/* Run the Preprocessor. */
if (rcpp_main(rcpp_argc, szRCPP) != 0)
fatal(1116);
// All done. Now free up the argv array.
for (n = 0 ; n < rcpp_argc ; n++) {
if (fRcppAlloc[n] == TRUE) {
free(szRCPP[n]);
}
}
if (fPreprocessOnly) {
swprintf(szBuf, L"Preprocessed file created in: %s\n", szPreProcessName);
quit(szBuf);
}
if (fVerbose)
wprintf(L"\n%s", inname);
if ((fhInput = _wfopen(szTempFileName2, L"rb")) == NULL_FILE)
fatal(2180);
if (!InitSymbolInfo())
fatal(22103);
LexInit (fhInput);
uiCodePage = uiDefaultCodePage;
ReadRF(); /* create .RES from .RC */
if (!TermSymbolInfo(fhBin))
fatal(22204);
if (!fMacRsrcs)
MyAlign(fhBin); // Pad end of file so that we can concatenate files
CleanUpFiles();
HeapDestroy(hHeap);
return Nerrors; // return success, not quitting.
}
/* RCInit
* Initializes this run of RC.
*/
HANDLE
RCInit(
void
)
{
Nerrors = 0;
uiCodePage = 0;
nFontsRead = 0;
szTempFileName = NULL;
szTempFileName2 = NULL;
lOffIndex = 0;
idBase = 128;
pTypInfo = NULL;
fVerbose = FALSE;
fMacRsrcs = FALSE;
// Clear the filenames
exename[0] = L'\0';
resname[0] = L'\0';
/* create growable local heap of 16MB minimum size */
return HeapCreate(HEAP_NO_SERIALIZE, 0, 0);
}
/*---------------------------------------------------------------------------*/
/* */
/* skipblanks() - */
/* */
/*---------------------------------------------------------------------------*/
wchar_t *
skipblanks(
wchar_t *pstr,
int fTerminate
)
{
/* search forward for first non-white character and save its address */
while (*pstr && iswspace(*pstr))
pstr++;
if (fTerminate) {
wchar_t *retval = pstr;
/* search forward for first white character and zero to extract word */
while (*pstr && !iswspace(*pstr))
pstr++;
*pstr = 0;
return retval;
} else {
return pstr;
}
}
/*---------------------------------------------------------------------------*/
/* */
/* RC_PreProcess() - */
/* */
/*---------------------------------------------------------------------------*/
void
RC_PreProcess(
const wchar_t *szname
)
{
PFILE fhout; /* fhout: is temp file with rcincluded stuff */
PFILE fhin;
wchar_t *wch_buf;
wchar_t *pwch;
wchar_t *pfilename;
wchar_t *szT;
UINT iLine = 0;
int fBlanks = TRUE;
INT fFileType;
wch_buf = (wchar_t *)MyAlloc(sizeof(wchar_t) * READ_MAX);
szT = (wchar_t *)MyAlloc(sizeof(wchar_t) * MAXSTR);
/* Open the .RC source file. */
wcscpy(Filename, szname);
fhin = _wfopen(szname, L"rb");
if (!fhin) {
fatal(1110, szname);
}
/* Open the temporary output file. */
fhout = _wfopen(szTempFileName, L"w+b");
if (!fhout) {
fatal(2180);
}
/* output the current filename for RCPP messages */
for (pwch=wch_buf ; *szname ; szname++) {
*pwch++ = *szname;
/* Hack to fix bug #8786: makes '\' to "\\" */
if (*szname == L'\\')
*pwch++ = L'\\';
}
*pwch++ = L'\0';
/* Output the current filename for RCPP messages */
MyWrite(fhout, L"#line 1\"", 8 * sizeof(wchar_t));
MyWrite(fhout, wch_buf, wcslen(wch_buf) * sizeof(wchar_t));
MyWrite(fhout, L"\"\r\n", 3 * sizeof(wchar_t));
/* Determine if the input file is Unicode */
fFileType = DetermineFileType (fhin);
/* Process each line of the input file. */
while (fgetl(wch_buf, READ_MAX, fFileType == DFT_FILE_IS_16_BIT, fhin)) {
/* keep track of the number of lines read */
Linenumber = iLine++;
if ((iLine & RC_PREPROCESS_UPDATE) == 0)
UpdateStatus(1, iLine);
/* Skip the Byte Order Mark and the leading bytes. */
pwch = wch_buf;
while (*pwch && (iswspace(*pwch) || *pwch == 0xFEFF))
pwch++;
/* if the line is a rcinclude line... */
if (strpre(L"rcinclude", pwch)) {
/* Get the name of the rcincluded file. */
pfilename = skipblanks(pwch + 9, TRUE);
MyWrite(fhout, L"#include \"", 10 * sizeof(WCHAR));
MyWrite(fhout, pfilename, wcslen(pfilename) * sizeof(WCHAR));
MyWrite(fhout, L"\"\r\n", 3 * sizeof(WCHAR));
} else if (strpre(L"#pragma", pwch)) {
WCHAR cSave;
pfilename = skipblanks(pwch + 7, FALSE);
if (strpre(L"code_page", pfilename)) {
pfilename = skipblanks(pfilename + 9, FALSE);
if (*pfilename == L'(') {
ULONG cp = 0;
pfilename = skipblanks(pfilename + 1, FALSE);
// really should allow hex/octal, but ...
if (iswdigit(*pfilename)) {
while (iswdigit(*pfilename)) {
cp = cp * 10 + (*pfilename++ - L'0');
}
pfilename = skipblanks(pfilename, FALSE);
} else if (strpre(L"default", pfilename)) {
cp = uiDefaultCodePage;
pfilename = skipblanks(pfilename + 7, FALSE);
}
if (cp == 0) {
error(4212, pfilename);
} else if (*pfilename != L')') {
error(4211);
} else if (cp == CP_WINUNICODE) {
if (fWarnInvalidCodePage) {
warning(4213);
} else {
fatal(4213);
}
} else if (!IsValidCodePage(cp)) {
if (fWarnInvalidCodePage) {
warning(4214);
} else {
fatal(4214);
}
} else {
uiCodePage = cp;
/* Copy the #pragma line to the temp file. */
MyWrite(fhout, pwch, wcslen(pwch) * sizeof(WCHAR));
MyWrite(fhout, L"\r\n", 2 * sizeof(WCHAR));
}
} else {
error(4210);
}
}
} else if (!*pwch) {
fBlanks = TRUE;
} else {
if (fBlanks) {
swprintf(szT, L"#line %d\r\n", iLine);
MyWrite(fhout, szT, wcslen(szT) * sizeof(WCHAR));
fBlanks = FALSE;
}
/* Copy the .RC line to the temp file. */
MyWrite(fhout, pwch, wcslen(pwch) * sizeof(WCHAR));
MyWrite(fhout, L"\r\n", 2 * sizeof(WCHAR));
}
}
lCPPTotalLinenumber = iLine;
Linenumber = 0;
uiCodePage = uiDefaultCodePage;
MyFree(wch_buf);
MyFree(szT);
fclose(fhout);
fclose(fhin);
}
/*---------------------------------------------------------------------------*/
/* */
/* quit() */
/* */
/*---------------------------------------------------------------------------*/
void quit(const wchar_t *wsz)
{
/* print out the error message */
if (wsz != NULL) {
SendWarning(L"\n");
SendError(wsz);
SendWarning(L"\n");
}
CleanUpFiles();
/* delete output file */
if (resname) {
_wremove(resname);
}
if (hHeap) {
HeapDestroy(hHeap);
}
Nerrors++;
longjmp(jb, Nerrors);
}
extern "C"
BOOL WINAPI Handler(DWORD fdwCtrlType)
{
if (fdwCtrlType == CTRL_C_EVENT) {
SendWarning(L"\n");
SET_MSG(20101);
SendWarning(Msg_Text);
CleanUpFiles();
HeapDestroy(hHeap);
/* Delete output file */
if (resname) {
_wremove(resname);
}
return(FALSE);
}
return(FALSE);
}
VOID
CleanUpFiles(
void
)
{
TermSymbolInfo(NULL_FILE);
// Close ALL files.
if (fhBin != NULL) {
fclose(fhBin);
}
if (fhInput != NULL) {
fclose(fhInput);
}
if (fhCode != NULL) {
fclose(fhCode);
}
p0_terminate();
// Clean up after font directory temp file
if (nFontsRead) {
_wremove(L"rc$x.fdr");
}
// Delete the temporary files
if (szTempFileName) {
_wremove(szTempFileName);
}
if (szTempFileName2) {
_wremove(szTempFileName2);
}
if (Nerrors > 0) {
_wremove(resname);
}
}
|
qhanke1992/mini-github | miniprogram/components/feedItem/feedItem.js | const utils = require('../../utils/util.js')
const notifUtils = require('../../utils/notifications.js')
Component({
properties: {
item: {
type: Object,
value: {}
}
},
methods: {
toUserPage: function(event) {
const username = this.data.item.actor.login
wx.navigateTo({
url: `/pages/user/user?username=${username}`
})
},
toFeedDetail: function (event) {
const formId = event.detail.formId
const feed = this.data.item
notifUtils.report({
formId,
enabled: true,
extra: { feed }
})
switch (feed.type) {
case 'IssuesEvent':
case 'IssueCommentEvent':
var issue = (feed.payload || {}).issue || {}
var url = issue.url
wx.navigateTo({
url: '/pages/issue-detail/issue-detail?url=' + url
})
break
case 'PullRequestEvent':
case 'PullRequestReviewEvent':
case 'PullRequestReviewCommentEvent':
var pullRequest = (feed.payload || {}).pull_request || {}
var url = pullRequest.issue_url
wx.navigateTo({
url: '/pages/issue-detail/issue-detail?url=' + url
})
break
case 'WatchEvent':
case 'ForkEvent':
case 'PushEvent':
case 'DeleteEvent':
var repo = utils.extractRepoName(feed.repo.url)
wx.navigateTo({
url: `/pages/repo-detail/repo-detail?repo=${repo}`
})
break
case 'ReleaseEvent':
var repo = feed.repo.name
wx.navigateTo({
url: `/pages/repo-detail/repo-detail?repo=${repo}`
})
break
default:
wx.showToast({
title: 'Coming Soon'
})
break
}
}
}
}) |
Justineo/vue-awesome-material | icons/timelapse.js | import Icon from 'vue-awesome/components/Icon'
Icon.register({
timelapse: {
paths: [
{
d: 'M16.24 7.76A5.974 5.974 0 0012 6v6l-4.24 4.24c2.34 2.34 6.14 2.34 8.49 0a5.99 5.99 0 00-.01-8.48zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z'
}
],
width: '24',
height: '24'
}
})
|
MisterZhouZhou/pythonLearn | hack/pcap/index.py | <gh_stars>1-10
import pcap
import dpkt
def captData():
pc = pcap.pcap('en0') # 注,参数可为网卡名,如eth0
pc.setfilter('tcp port 80') # 设置监听过滤器
for ptime, pdata in pc: # ptime为收到时间,pdata为收到数据
anlyCap(pdata)
def anlyCap(pdata):
p = dpkt.ethernet.Ethernet(pdata)
if p.data.__class__.__name__ == 'IP':
print(p.data.dst)
# ip = '%d.%d.%d.%d' % tuple(map(ord, list(p.data.dst)))
# if p.data.data.__class__.__name__ == 'TCP':
# if p.data.data.dport == 80:
# print(p.data.data.data) # http 要求的数据
captData() |
Florian1606/EnchereProjet | src/fr/formation/projet/enchere/bo/Utilisateur.java | package fr.formation.projet.enchere.bo;
import java.util.ArrayList;
import java.util.List;
public class Utilisateur {
private int noUtilisateur;
private static int cptUtilisateur = 0;
private String pseudo;
private String nom;
private String prenom;
private String email;
private String telephone;
private String rue;
private String codePostal;
private String ville;
private String motDePasse;
private Integer credit = 0;
private boolean administrateur;
private List<ArticleVendu> listeArticleVendu = new ArrayList<ArticleVendu>();
private String confirmation;
public Utilisateur() {
}
public Utilisateur(String pseudo, String nom, String prenom, String email, String telephone, String rue,
String codePostal, String ville, String motDePasse) {
super();
this.pseudo = pseudo;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.telephone = telephone;
this.rue = rue;
this.codePostal = codePostal;
this.ville = ville;
this.motDePasse = motDePasse;
this.administrateur = false;
}
public int getNoUtilisateur() {
return noUtilisateur;
}
public void setNoUtilisateur(int noUtilisateur) {
this.noUtilisateur = noUtilisateur;
}
public static int getCptUtilisateur() {
return cptUtilisateur;
}
public static void setCptUtilisateur(int cptUtilisateur) {
Utilisateur.cptUtilisateur = cptUtilisateur;
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getRue() {
return rue;
}
public void setRue(String rue) {
this.rue = rue;
}
public String getCodePostal() {
return codePostal;
}
public void setCodePostal(String codePostal) {
this.codePostal = codePostal;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getMotDePasse() {
return motDePasse;
}
public void setMotDePasse(String motDePasse) {
this.motDePasse = motDePasse;
}
public Integer getCredit() {
return credit;
}
public void setCredit(Integer credit) {
this.credit = credit;
}
public boolean isAdministrateur() {
return administrateur;
}
public void setAdministrateur(boolean administrateur) {
this.administrateur = administrateur;
}
public List<ArticleVendu> getListeArticleVendu() {
return listeArticleVendu;
}
public void setListeArticleVendu(List<ArticleVendu> listeArticleVendu) {
this.listeArticleVendu = listeArticleVendu;
}
public String getConfirmation() {
return confirmation;
}
public void setConfirmation(String confirmation) {
this.confirmation = confirmation;
}
@Override
public String toString() {
return "Utilisateur [noUtilisateur=" + noUtilisateur + ", pseudo=" + pseudo + ", nom=" + nom + ", prenom="
+ prenom + ", email=" + email + ", telephone=" + telephone + ", rue=" + rue + ", codePostal="
+ codePostal + ", ville=" + ville + ", motDePasse=" + motDePasse + ", credit=" + credit
+ ", administrateur=" + administrateur + ", listeArticleVendu=" + listeArticleVendu + "]";
}
}
|
stbly/gemp-swccg-public | gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/set207/dark/Card207_028.java | <gh_stars>10-100
package com.gempukku.swccgo.cards.set207.dark;
import com.gempukku.swccgo.cards.AbstractStarfighter;
import com.gempukku.swccgo.cards.conditions.HasPilotingCondition;
import com.gempukku.swccgo.cards.evaluators.InBattleEvaluator;
import com.gempukku.swccgo.common.*;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.modifiers.ImmuneToAttritionLessThanModifier;
import com.gempukku.swccgo.logic.modifiers.Modifier;
import com.gempukku.swccgo.logic.modifiers.TotalBattleDestinyModifier;
import java.util.LinkedList;
import java.util.List;
/**
* Set: Set 7
* Type: Starship
* Subtype: Starfighter
* Title: Meson Martinet
*/
public class Card207_028 extends AbstractStarfighter {
public Card207_028() {
super(Side.DARK, 3, 3, 3, null, 4, 4, 4, Title.Meson_Martinet, Uniqueness.UNIQUE);
setGameText("May add 2 pilots and 3 passengers. During battle, your total battle destiny is +1 for each pirate aboard. While Quiggold or Sidon piloting, immune to attrition < 5.");
addIcons(Icon.INDEPENDENT, Icon.NAV_COMPUTER, Icon.SCOMP_LINK, Icon.EPISODE_VII, Icon.VIRTUAL_SET_7);
addModelType(ModelType.FREIGHTER);
setPilotCapacity(2);
setPassengerCapacity(3);
setMatchingPilotFilter(Filters.or(Filters.Quiggold, Filters.Sidon));
}
@Override
protected List<Modifier> getGameTextWhileActiveInPlayModifiers(SwccgGame game, final PhysicalCard self) {
String playerId = self.getOwner();
List<Modifier> modifiers = new LinkedList<Modifier>();
modifiers.add(new ImmuneToAttritionLessThanModifier(self, new HasPilotingCondition(self, Filters.or(Filters.Quiggold, Filters.Sidon)), 5));
modifiers.add(new TotalBattleDestinyModifier(self, new InBattleEvaluator(self, Filters.and(Filters.pirate, Filters.aboard(self))), playerId));
return modifiers;
}
}
|
A-G-Angelopoulos/Tron | cmds/Moderator/unmute.js | <filename>cmds/Moderator/unmute.js
exports.data = {
name: 'Unmute',
description: 'Unmutes a specific user.',
group: 'Moderator',
command: 'unmute',
syntax: 'unmute [@name]',
author: 'TRX',
permissions: 3,
};
exports.func = async (message, args) => {
const OTS = require(`${message.client.config.folders.models}/mute.js`);
const log = require(`${message.client.config.folders.lib}/log.js`)(exports.data.name);
try{
if (args[0] == undefined) {
return message.reply('You did not provide a name.');
}
const Member = await message.client.findUser.func(args[0], message);
if (Member == null) {
return message.reply('User does not exist.');
}
const OTSSettings = await OTS.findOne({
where: {
guildId: message.channel.guild.id
}
});
if (!OTSSettings) {
return message.reply(`OTS Role has not been set up in ${message.guild.name}.`);
}
if (!Member.roles.cache.has(OTSSettings.roleId)) {
return message.reply('User is not muted!');
}
let botspam;
Member.roles.remove(OTSSettings.roleId);
await message.guild.channels.cache.forEach(async channel => {
if (channel.type == 'text') {
await channel.permissionOverwrites.forEach(overwrite => {
if (overwrite.id == Member.id) {
overwrite.delete();
}
});
}
if (channel.id == OTSSettings.botspamChannelId) {
botspam = channel;
}
});
message.reply(`${Member.user.tag} has been unmuted.`);
botspam.send(`${Member} You have been unmuted by ${message.author.tag}.`);
} catch (err) {
message.reply('Something went wrong.');
log.error(`Sorry ${message.author.tag} I could not remove the mute because of : ${err}`);
}
}; |
amyrebecca/caesar | app/models/conditions/disjunction.rb | module Conditions
class Disjunction
attr_reader :operations
def initialize(operations)
@operations = operations
end
def to_a
["or"] + @operations.map(&:to_a)
end
def apply(bindings)
@operations.reduce(false) { |memo, operation| memo || operation.apply(bindings) }
end
end
end
|
egraba/vbox_openbsd | VirtualBox-5.0.0/src/VBox/Runtime/testcase/tstNoCrt-1.cpp | /* $Id: tstNoCrt-1.cpp $ */
/** @file
* IPRT Testcase - Testcase for the No-CRT assembly bits.
*/
/*
* Copyright (C) 2008-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/nocrt/string.h>
#include <iprt/stream.h>
#include <iprt/initterm.h>
#include <iprt/string.h>
#ifdef RT_WITHOUT_NOCRT_WRAPPERS
# error "Build error."
#endif
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
#define TSTBUF_SIZE 8192
typedef struct TSTBUF
{
uint8_t abHeadFence[2048];
uint8_t abBuf[TSTBUF_SIZE];
uint8_t abTailFence[2048];
} TSTBUF, *PTSTBUF;
/*******************************************************************************
* Global Variables *
*******************************************************************************/
static unsigned g_cErrors = 0;
static void my_memset(void *pv, int ch, size_t cb)
{
uint8_t *pb = (uint8_t *)pv;
while (cb--)
*pb++ = ch;
}
static void my_memcheck(const void *pv, int ch, size_t cb, const char *pszDesc)
{
uint8_t *pb = (uint8_t *)pv;
while (cb--)
{
if (*pb != (uint8_t)ch)
{
g_cErrors++;
size_t off;
for (off = 1; off < cb && pb[off] != (uint8_t)ch; off++)
/* nandemonai */;
off--;
pb += off;
cb -= off;
if (off)
RTPrintf("tstNoCrt-1: %s: %p:%p - %02x instead of %02x\n",
pszDesc, (uintptr_t)pb - (uintptr_t)pv,
(uint8_t *)pb - (uint8_t *)pv + off, *pb, (uint8_t)ch);
else
RTPrintf("tstNoCrt-1: %s: %p - %02x instead of %02x\n",
pszDesc, (uint8_t *)pb - (uint8_t *)pv, *pb, (uint8_t)ch);
}
/* next*/
pb++;
}
}
static void TstBufInit(PTSTBUF pBuf, int ch)
{
my_memset(pBuf->abHeadFence, 0x55, sizeof(pBuf->abHeadFence));
my_memset(pBuf->abBuf, ch, sizeof(pBuf->abBuf));
my_memset(pBuf->abTailFence, 0x77, sizeof(pBuf->abHeadFence));
}
static void TstBufCheck(PTSTBUF pBuf, const char *pszDesc)
{
my_memcheck(pBuf->abHeadFence, 0x55, sizeof(pBuf->abHeadFence), pszDesc);
my_memcheck(pBuf->abTailFence, 0x77, sizeof(pBuf->abTailFence), pszDesc);
}
#if 0 /* enable this to test the testcase. */
# undef RT_NOCRT
# define RT_NOCRT(a) a
# ifdef _MSC_VER
# define mempcpy nocrt_mempcpy
# endif
#endif
int main()
{
/*
* Prologue.
*/
RTR3InitExeNoArguments(0);
RTPrintf("tstNoCrt-1: TESTING...\n");
/*
* Sanity.
*/
TSTBUF Buf1;
TstBufInit(&Buf1, 1);
my_memcheck(Buf1.abBuf, 1, TSTBUF_SIZE, "sanity buf1");
TstBufCheck(&Buf1, "sanity buf1");
TSTBUF Buf2;
TstBufInit(&Buf2, 2);
my_memcheck(Buf2.abBuf, 2, TSTBUF_SIZE, "sanity buf2");
TstBufCheck(&Buf2, "sanity buf2");
if (g_cErrors)
{
RTPrintf("tstNoCrt-1: FAILED - fatal sanity error\n");
return 1;
}
#define CHECK_CCH(expect) \
do \
{ \
if (cch != (expect)) \
{ \
RTPrintf("tstNoCrt-1(%d): cb=%zu expected=%zu\n", __LINE__, cch, (expect)); \
g_cErrors++; \
} \
} while (0)
size_t cch;
#define CHECK_PV(expect) \
do \
{ \
if (pv != (expect)) \
{ \
RTPrintf("tstNoCrt-1(%d): pv=%p expected=%p\n", __LINE__, pv, (expect)); \
g_cErrors++; \
} \
} while (0)
void *pv;
#define CHECK_DIFF(op) \
do \
{ \
if (!(iDiff op 0)) \
{ \
RTPrintf("tstNoCrt-1(%d): iDiff=%d expected: %s 0\n", __LINE__, iDiff, #op); \
g_cErrors++; \
} \
} while (0)
int iDiff;
static char s_szTest1[] = "0123456789abcdef";
static char s_szTest2[] = "0123456789abcdef";
static char s_szTest3[] = "fedcba9876543210";
/*
* memcpy.
*/
RTPrintf("tstNoCrt-1: memcpy\n");
TstBufInit(&Buf1, 1);
TstBufInit(&Buf2, 2);
pv = RT_NOCRT(memcpy)(Buf1.abBuf, Buf2.abBuf, TSTBUF_SIZE); CHECK_PV(Buf1.abBuf);
my_memcheck(Buf1.abBuf, 2, TSTBUF_SIZE, "memcpy1-dst");
my_memcheck(Buf2.abBuf, 2, TSTBUF_SIZE, "memcpy1-src");
TstBufCheck(&Buf1, "memcpy1");
TstBufCheck(&Buf2, "memcpy1");
TstBufInit(&Buf1, 3);
TstBufInit(&Buf2, 4);
pv = RT_NOCRT(memcpy)(Buf2.abBuf, Buf1.abBuf, TSTBUF_SIZE); CHECK_PV(Buf2.abBuf);
my_memcheck(Buf1.abBuf, 3, TSTBUF_SIZE, "memcpy2-dst");
my_memcheck(Buf2.abBuf, 3, TSTBUF_SIZE, "memcpy2-src");
TstBufCheck(&Buf1, "memcpy2");
TstBufCheck(&Buf2, "memcpy2");
TstBufInit(&Buf1, 5);
TstBufInit(&Buf2, 6);
pv = RT_NOCRT(memcpy)(Buf2.abBuf, Buf1.abBuf, 0); CHECK_PV(Buf2.abBuf);
my_memcheck(Buf1.abBuf, 5, TSTBUF_SIZE, "memcpy3-dst");
my_memcheck(Buf2.abBuf, 6, TSTBUF_SIZE, "memcpy3-src");
TstBufCheck(&Buf1, "memcpy3-dst");
TstBufCheck(&Buf2, "memcpy3-src");
for (unsigned off1 = 0; off1 <= 128; off1++)
{
for (unsigned off2 = 0; off2 <= 256; off2++)
{
char sz[32];
RTStrPrintf(sz, sizeof(sz), "memcpy4-%d-%d", off1, off2);
TstBufInit(&Buf1, 1);
TstBufInit(&Buf2, 2);
size_t cb = off2;
pv = RT_NOCRT(memcpy)(&Buf2.abBuf[off2], &Buf1.abBuf[off1], cb); CHECK_PV(&Buf2.abBuf[off2]);
my_memcheck(Buf1.abBuf, 1, TSTBUF_SIZE, sz);
my_memcheck(Buf2.abBuf, 2, off2, sz);
my_memcheck(&Buf2.abBuf[off2], 1, cb, sz);
my_memcheck(&Buf2.abBuf[off2 + cb], 2, TSTBUF_SIZE - cb - off2, sz);
TstBufCheck(&Buf1, sz);
TstBufCheck(&Buf2, sz);
}
}
/*
* mempcpy.
*/
RTPrintf("tstNoCrt-1: mempcpy\n");
TstBufInit(&Buf1, 1);
TstBufInit(&Buf2, 2);
pv = RT_NOCRT(mempcpy)(Buf1.abBuf, Buf2.abBuf, TSTBUF_SIZE); CHECK_PV(&Buf1.abBuf[TSTBUF_SIZE]);
my_memcheck(Buf1.abBuf, 2, TSTBUF_SIZE, "mempcpy1-dst");
my_memcheck(Buf2.abBuf, 2, TSTBUF_SIZE, "mempcpy1-src");
TstBufCheck(&Buf1, "mempcpy1");
TstBufCheck(&Buf2, "mempcpy1");
TstBufInit(&Buf1, 3);
TstBufInit(&Buf2, 4);
pv = RT_NOCRT(mempcpy)(Buf2.abBuf, Buf1.abBuf, TSTBUF_SIZE); CHECK_PV(&Buf2.abBuf[TSTBUF_SIZE]);
my_memcheck(Buf1.abBuf, 3, TSTBUF_SIZE, "mempcpy2-dst");
my_memcheck(Buf2.abBuf, 3, TSTBUF_SIZE, "mempcpy2-src");
TstBufCheck(&Buf1, "mempcpy2");
TstBufCheck(&Buf2, "mempcpy2");
TstBufInit(&Buf1, 5);
TstBufInit(&Buf2, 6);
pv = RT_NOCRT(mempcpy)(Buf2.abBuf, Buf1.abBuf, 0); CHECK_PV(Buf2.abBuf);
my_memcheck(Buf1.abBuf, 5, TSTBUF_SIZE, "mempcpy3-dst");
my_memcheck(Buf2.abBuf, 6, TSTBUF_SIZE, "mempcpy3-src");
TstBufCheck(&Buf1, "mempcpy3-dst");
TstBufCheck(&Buf2, "mempcpy3-src");
for (unsigned off1 = 0; off1 <= 128; off1++)
{
for (unsigned off2 = 0; off2 <= 256; off2++)
{
char sz[32];
RTStrPrintf(sz, sizeof(sz), "mempcpy4-%d-%d", off1, off2);
TstBufInit(&Buf1, 1);
TstBufInit(&Buf2, 2);
size_t cb = off2;
pv = RT_NOCRT(mempcpy)(&Buf2.abBuf[off2], &Buf1.abBuf[off1], cb); CHECK_PV(&Buf2.abBuf[off2 + cb]);
my_memcheck(Buf1.abBuf, 1, TSTBUF_SIZE, sz);
my_memcheck(Buf2.abBuf, 2, off2, sz);
my_memcheck(&Buf2.abBuf[off2], 1, cb, sz);
my_memcheck(&Buf2.abBuf[off2 + cb], 2, TSTBUF_SIZE - cb - off2, sz);
TstBufCheck(&Buf1, sz);
TstBufCheck(&Buf2, sz);
}
}
/*
* memmove.
*/
RTPrintf("tstNoCrt-1: memmove\n");
TstBufInit(&Buf1, 1);
TstBufInit(&Buf2, 2);
pv = RT_NOCRT(memmove)(Buf1.abBuf, Buf2.abBuf, TSTBUF_SIZE); CHECK_PV(Buf1.abBuf);
my_memcheck(Buf1.abBuf, 2, TSTBUF_SIZE, "memmove1-dst");
my_memcheck(Buf2.abBuf, 2, TSTBUF_SIZE, "memmove1-src");
TstBufCheck(&Buf1, "memmove1");
TstBufCheck(&Buf2, "memmove1");
TstBufInit(&Buf1, 3);
TstBufInit(&Buf2, 4);
pv = RT_NOCRT(memmove)(Buf2.abBuf, Buf1.abBuf, TSTBUF_SIZE); CHECK_PV(Buf2.abBuf);
my_memcheck(Buf1.abBuf, 3, TSTBUF_SIZE, "memmove2-dst");
my_memcheck(Buf2.abBuf, 3, TSTBUF_SIZE, "memmove2-src");
TstBufCheck(&Buf1, "memmove2");
TstBufCheck(&Buf2, "memmove2");
TstBufInit(&Buf1, 5);
TstBufInit(&Buf2, 6);
pv = RT_NOCRT(memmove)(Buf2.abBuf, Buf1.abBuf, 0); CHECK_PV(Buf2.abBuf);
my_memcheck(Buf1.abBuf, 5, TSTBUF_SIZE, "memmove3-dst");
my_memcheck(Buf2.abBuf, 6, TSTBUF_SIZE, "memmove3-src");
TstBufCheck(&Buf1, "memmove3-dst");
TstBufCheck(&Buf2, "memmove3-src");
for (unsigned off1 = 1; off1 <= 128; off1++)
{
for (unsigned off2 = 0; off2 <= 256; off2++)
{
/* forward */
char sz[32];
RTStrPrintf(sz, sizeof(sz), "memmove4-%d-%d", off1, off2);
TstBufInit(&Buf1, off1 + 1);
my_memset(Buf1.abBuf, off1, off1);
pv = RT_NOCRT(memmove)(Buf1.abBuf, &Buf1.abBuf[off2], TSTBUF_SIZE - off2); CHECK_PV(Buf1.abBuf);
if (off2 < off1)
{
unsigned cbLead = off1 - off2;
my_memcheck(Buf1.abBuf, off1, cbLead, sz);
my_memcheck(&Buf1.abBuf[cbLead], off1 + 1, TSTBUF_SIZE - cbLead, sz);
}
else
my_memcheck(Buf1.abBuf, off1 + 1, TSTBUF_SIZE, sz);
TstBufCheck(&Buf1, sz);
/* backward */
RTStrPrintf(sz, sizeof(sz), "memmove5-%d-%d", off1, off2);
TstBufInit(&Buf1, off1 + 1);
my_memset(&Buf1.abBuf[TSTBUF_SIZE - off1], off1, off1);
pv = RT_NOCRT(memmove)(&Buf1.abBuf[off2], Buf1.abBuf, TSTBUF_SIZE - off2); CHECK_PV(&Buf1.abBuf[off2]);
if (off2 < off1)
{
unsigned cbLead = off1 - off2;
my_memcheck(&Buf1.abBuf[TSTBUF_SIZE - cbLead], off1, cbLead, sz);
my_memcheck(Buf1.abBuf, off1 + 1, TSTBUF_SIZE - cbLead, sz);
}
else
my_memcheck(Buf1.abBuf, off1 + 1, TSTBUF_SIZE, sz);
TstBufCheck(&Buf1, sz);
/* small unaligned */
RTStrPrintf(sz, sizeof(sz), "memmove6-%d-%d", off1, off2);
TstBufInit(&Buf1, 1);
TstBufInit(&Buf2, 2);
size_t cb = off2;
pv = RT_NOCRT(memmove)(&Buf2.abBuf[off2], &Buf1.abBuf[off1], cb); CHECK_PV(&Buf2.abBuf[off2]);
my_memcheck(Buf1.abBuf, 1, TSTBUF_SIZE, sz);
my_memcheck(Buf2.abBuf, 2, off2, sz);
my_memcheck(&Buf2.abBuf[off2], 1, cb, sz);
my_memcheck(&Buf2.abBuf[off2 + cb], 2, TSTBUF_SIZE - cb - off2, sz);
TstBufCheck(&Buf1, sz);
TstBufCheck(&Buf2, sz);
}
}
/*
* memset
*/
RTPrintf("tstNoCrt-1: memset\n");
TstBufInit(&Buf1, 1);
pv = RT_NOCRT(memset)(Buf1.abBuf, 0, TSTBUF_SIZE); CHECK_PV(Buf1.abBuf);
my_memcheck(Buf1.abBuf, 0, TSTBUF_SIZE, "memset-1");
TstBufCheck(&Buf1, "memset-1");
TstBufInit(&Buf1, 1);
pv = RT_NOCRT(memset)(Buf1.abBuf, 0xff, TSTBUF_SIZE); CHECK_PV(Buf1.abBuf);
my_memcheck(Buf1.abBuf, 0xff, TSTBUF_SIZE, "memset-2");
TstBufCheck(&Buf1, "memset-2");
TstBufInit(&Buf1, 1);
pv = RT_NOCRT(memset)(Buf1.abBuf, 0xff, 0); CHECK_PV(Buf1.abBuf);
my_memcheck(Buf1.abBuf, 1, TSTBUF_SIZE, "memset-3");
TstBufCheck(&Buf1, "memset-3");
for (unsigned off = 0; off < 256; off++)
{
/* move start byte by byte. */
char sz[32];
RTStrPrintf(sz, sizeof(sz), "memset4-%d", off);
TstBufInit(&Buf1, 0);
pv = RT_NOCRT(memset)(&Buf1.abBuf[off], off, TSTBUF_SIZE - off); CHECK_PV(&Buf1.abBuf[off]);
my_memcheck(Buf1.abBuf, 0, off, sz);
my_memcheck(&Buf1.abBuf[off], off, TSTBUF_SIZE - off, sz);
TstBufCheck(&Buf1, sz);
/* move end byte by byte. */
RTStrPrintf(sz, sizeof(sz), "memset5-%d", off);
TstBufInit(&Buf1, 0);
pv = RT_NOCRT(memset)(Buf1.abBuf, off, TSTBUF_SIZE - off); CHECK_PV(Buf1.abBuf);
my_memcheck(Buf1.abBuf, off, TSTBUF_SIZE - off, sz);
my_memcheck(&Buf1.abBuf[TSTBUF_SIZE - off], 0, off, sz);
TstBufCheck(&Buf1, sz);
/* move both start and size byte by byte. */
RTStrPrintf(sz, sizeof(sz), "memset6-%d", off);
TstBufInit(&Buf1, 0);
pv = RT_NOCRT(memset)(&Buf1.abBuf[off], off, off); CHECK_PV(&Buf1.abBuf[off]);
my_memcheck(Buf1.abBuf, 0, off, sz);
my_memcheck(&Buf1.abBuf[off], off, off, sz);
my_memcheck(&Buf1.abBuf[off * 2], 0, TSTBUF_SIZE - off * 2, sz);
TstBufCheck(&Buf1, sz);
}
/*
* strcpy (quick smoke testing).
*/
RTPrintf("tstNoCrt-1: strcpy\n");
TstBufInit(&Buf1, 1);
const char *pszSrc = s_szTest1;
char *pszDst = (char *)&Buf1.abBuf[0];
pv = RT_NOCRT(strcpy)(pszDst, pszSrc);
CHECK_PV(pszDst);
TstBufCheck(&Buf1, "strcpy 1");
iDiff = RT_NOCRT(strcmp)(pszDst, pszSrc); CHECK_DIFF( == );
pszSrc = s_szTest1;
for (unsigned i = 0; i < sizeof(s_szTest1) / 2; i++)
{
pszSrc++;
TstBufInit(&Buf1, 2);
pszDst = (char *)&Buf1.abBuf[sizeof(Buf1.abBuf) - strlen(pszSrc) - 1];
pv = RT_NOCRT(strcpy)(pszDst, pszSrc);
CHECK_PV(pszDst);
TstBufCheck(&Buf1, "strcpy 3");
iDiff = RT_NOCRT(strcmp)(pszDst, pszSrc); CHECK_DIFF( == );
}
/*
* memchr & strchr.
*/
RTPrintf("tstNoCrt-1: memchr\n");
pv = RT_NOCRT(memchr)(&s_szTest1[0x00], 'f', sizeof(s_szTest1)); CHECK_PV(&s_szTest1[0xf]);
pv = RT_NOCRT(memchr)(&s_szTest1[0x0f], 'f', sizeof(s_szTest1)); CHECK_PV(&s_szTest1[0xf]);
pv = RT_NOCRT(memchr)(&s_szTest1[0x03], 0, sizeof(s_szTest1)); CHECK_PV(&s_szTest1[0x10]);
pv = RT_NOCRT(memchr)(&s_szTest1[0x10], 0, sizeof(s_szTest1)); CHECK_PV(&s_szTest1[0x10]);
pv = RT_NOCRT(memchr)(&s_szTest1, 0, ~(size_t)0); CHECK_PV(&s_szTest1[0x10]);
pv = RT_NOCRT(memchr)(&s_szTest1, 0, ~(size_t)1); CHECK_PV(&s_szTest1[0x10]);
pv = RT_NOCRT(memchr)(&s_szTest1, 0, ~(size_t)16); CHECK_PV(&s_szTest1[0x10]);
for (unsigned i = 0; i < sizeof(s_szTest1); i++)
for (unsigned j = 0; j <= i; j++)
{
pv = RT_NOCRT(memchr)(&s_szTest1[j], s_szTest1[i], sizeof(s_szTest1));
CHECK_PV(&s_szTest1[i]);
}
RTPrintf("tstNoCrt-1: strchr\n");
pv = RT_NOCRT(strchr)(&s_szTest1[0x00], 'f'); CHECK_PV(&s_szTest1[0xf]);
pv = RT_NOCRT(strchr)(&s_szTest1[0x0f], 'f'); CHECK_PV(&s_szTest1[0xf]);
pv = RT_NOCRT(strchr)(&s_szTest1[0x03], 0); CHECK_PV(&s_szTest1[0x10]);
pv = RT_NOCRT(strchr)(&s_szTest1[0x10], 0); CHECK_PV(&s_szTest1[0x10]);
for (unsigned i = 0; i < sizeof(s_szTest1); i++)
for (unsigned j = 0; j <= i; j++)
{
pv = RT_NOCRT(strchr)(&s_szTest1[j], s_szTest1[i]);
CHECK_PV(&s_szTest1[i]);
}
/*
* Some simple memcmp/strcmp checks.
*/
RTPrintf("tstNoCrt-1: memcmp\n");
iDiff = RT_NOCRT(memcmp)(s_szTest1, s_szTest1, sizeof(s_szTest1)); CHECK_DIFF( == );
iDiff = RT_NOCRT(memcmp)(s_szTest1, s_szTest2, sizeof(s_szTest1)); CHECK_DIFF( == );
iDiff = RT_NOCRT(memcmp)(s_szTest2, s_szTest1, sizeof(s_szTest1)); CHECK_DIFF( == );
iDiff = RT_NOCRT(memcmp)(s_szTest3, s_szTest3, sizeof(s_szTest1)); CHECK_DIFF( == );
iDiff = RT_NOCRT(memcmp)(s_szTest1, s_szTest3, sizeof(s_szTest1)); CHECK_DIFF( < );
iDiff = RT_NOCRT(memcmp)(s_szTest3, s_szTest1, sizeof(s_szTest1)); CHECK_DIFF( > );
iDiff = RT_NOCRT(memcmp)("1234", "1a34", 4); CHECK_DIFF( < );
RTPrintf("tstNoCrt-1: strcmp\n");
iDiff = RT_NOCRT(strcmp)(s_szTest1, s_szTest1); CHECK_DIFF( == );
iDiff = RT_NOCRT(strcmp)(s_szTest1, s_szTest2); CHECK_DIFF( == );
iDiff = RT_NOCRT(strcmp)(s_szTest2, s_szTest1); CHECK_DIFF( == );
iDiff = RT_NOCRT(strcmp)(s_szTest3, s_szTest3); CHECK_DIFF( == );
iDiff = RT_NOCRT(strcmp)(s_szTest1, s_szTest3); CHECK_DIFF( < );
iDiff = RT_NOCRT(strcmp)(s_szTest3, s_szTest1); CHECK_DIFF( > );
/*
* Some simple strlen checks.
*/
RTPrintf("tstNoCrt-1: strlen\n");
cch = RT_NOCRT(strlen)(""); CHECK_CCH(0);
cch = RT_NOCRT(strlen)("1"); CHECK_CCH(1);
cch = RT_NOCRT(strlen)("12"); CHECK_CCH(2);
cch = RT_NOCRT(strlen)("123"); CHECK_CCH(3);
cch = RT_NOCRT(strlen)("1234"); CHECK_CCH(4);
cch = RT_NOCRT(strlen)("12345"); CHECK_CCH(5);
cch = RT_NOCRT(strlen)(s_szTest1); CHECK_CCH(sizeof(s_szTest1) - 1);
cch = RT_NOCRT(strlen)(&s_szTest1[1]); CHECK_CCH(sizeof(s_szTest1) - 1 - 1);
cch = RT_NOCRT(strlen)(&s_szTest1[2]); CHECK_CCH(sizeof(s_szTest1) - 1 - 2);
cch = RT_NOCRT(strlen)(&s_szTest1[3]); CHECK_CCH(sizeof(s_szTest1) - 1 - 3);
cch = RT_NOCRT(strlen)(&s_szTest1[4]); CHECK_CCH(sizeof(s_szTest1) - 1 - 4);
cch = RT_NOCRT(strlen)(&s_szTest1[5]); CHECK_CCH(sizeof(s_szTest1) - 1 - 5);
cch = RT_NOCRT(strlen)(&s_szTest1[6]); CHECK_CCH(sizeof(s_szTest1) - 1 - 6);
cch = RT_NOCRT(strlen)(&s_szTest1[7]); CHECK_CCH(sizeof(s_szTest1) - 1 - 7);
cch = RT_NOCRT(strlen)(s_szTest2); CHECK_CCH(sizeof(s_szTest2) - 1);
cch = RT_NOCRT(strlen)(s_szTest3); CHECK_CCH(sizeof(s_szTest3) - 1);
/*
* Summary.
*/
if (!g_cErrors)
RTPrintf("tstNoCrt-1: SUCCESS\n");
else
RTPrintf("tstNoCrt-1: FAILURE - %d errors\n", g_cErrors);
return !!g_cErrors;
}
|
Dhruv-Techapps/xpath-finder-code | extension/src/background/_cipher.js | <filename>extension/src/background/_cipher.js<gh_stars>0
let cipher = (salt => {
if (!salt) {
throw new Error("Salt key is not provided");
}
let textToChars = text => text.split('').map(c => c.charCodeAt(0));
let byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
let applySaltToChar = code => textToChars(salt).reduce((a, b) => a ^ b, code);
return text => {
if (typeof text !== "string") {
throw new Error("Passed parameter is not string");
}
return text.split('').map(textToChars).map(applySaltToChar).map(byteHex).join('');
}
})(chrome.runtime.getManifest().key);
let decipher = (salt => {
if (!salt) {
throw new Error("Salt key is not provided");
}
let textToChars = text => text.split('').map(c => c.charCodeAt(0));
let saltChars = textToChars(salt);
let applySaltToChar = code => saltChars.reduce((a, b) => a ^ b, code);
return encoded => {
if (typeof encoded !== "string") {
throw new Error("Passed parameter is not string");
}
return encoded.match(/.{1,2}/g).map(hex => parseInt(hex, 16)).map(applySaltToChar).map(charCode => String.fromCharCode(charCode)).join('');
}
})(chrome.runtime.getManifest().key); |
robjacoby/wiz_khilafas | db/migrate/20160512053545_create_set_updated_at_function.rb | <filename>db/migrate/20160512053545_create_set_updated_at_function.rb<gh_stars>1-10
ROM::SQL.migration do
up do
sql = <<-SQL
CREATE OR REPLACE FUNCTION set_updated_at_column() RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ language 'plpgsql';
SQL
run sql
end
down do
run "DROP FUNCTION IF EXISTS set_updated_at_column();"
end
end
|
haribo0915/Judge-Girl | Spring-Boot/Spring-Boot-Commons/src/main/java/tw/waterball/judgegirl/springboot/configs/RedisConfig.java | package tw.waterball.judgegirl.springboot.configs;
import lombok.AllArgsConstructor;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;
import tw.waterball.judgegirl.springboot.profiles.productions.Redis;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* @author - <EMAIL>
*/
@Redis
@Setter
@Configuration
@ConfigurationProperties("judge-girl.redis")
public class RedisConfig {
private String host;
private int port;
private String password;
private String keyPrefix;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
var redisConfig = new RedisStandaloneConfiguration(host, port);
redisConfig.setPassword(password);
return new LettuceConnectionFactory(redisConfig);
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate(redisConnectionFactory);
redisTemplate.setKeySerializer(new JudgeGirlRedisSerializer(keyPrefix));
return redisTemplate;
}
@AllArgsConstructor
private static final class JudgeGirlRedisSerializer implements RedisSerializer<String> {
private final String keyPrefix;
@Override
public byte[] serialize(String s) throws SerializationException {
return (keyPrefix + s).getBytes(UTF_8);
}
@Override
public String deserialize(@Nullable byte[] bytes) throws SerializationException {
return bytes != null ? new String(bytes, keyPrefix.length(), bytes.length - keyPrefix.length(), UTF_8) : "";
}
}
}
|
MarginC/kame | netbsd/sys/arch/walnut/include/varargs.h | /* $NetBSD: varargs.h,v 1.1 2001/06/13 06:01:59 simonb Exp $ */
#include <powerpc/varargs.h>
|
toasterco/apiaiassistant | tests/test_widgets/test_base.py | <reponame>toasterco/apiaiassistant<filename>tests/test_widgets/test_base.py
import unittest
from apiai_assistant.widgets import GoogleAssistantWidget
class GoogleAssistantWidgetTestCase(unittest.TestCase):
def test_basic(self):
w = GoogleAssistantWidget()
self.assertEqual(w.platform, 'google')
self.assertEqual(w.render(), {'platform': 'google'})
if __name__ == '__main__':
unittest.main()
|
NASA-AMMOS/aerie-lander | src/main/java/gov/nasa/jpl/aerielander/activities/heatprobe/HeatProbeTemP.java | package gov.nasa.jpl.aerielander.activities.heatprobe;
import gov.nasa.jpl.aerie.merlin.framework.annotations.ActivityType;
import gov.nasa.jpl.aerie.merlin.framework.annotations.ActivityType.ControllableDuration;
import gov.nasa.jpl.aerie.merlin.framework.annotations.ActivityType.EffectModel;
import gov.nasa.jpl.aerie.merlin.framework.annotations.Export.Parameter;
import gov.nasa.jpl.aerie.merlin.protocol.types.Duration;
import gov.nasa.jpl.aerielander.Mission;
import static gov.nasa.jpl.aerie.merlin.framework.ModelActions.delay;
import static gov.nasa.jpl.aerie.merlin.protocol.types.Duration.MINUTE;
import static gov.nasa.jpl.aerielander.models.power.PowerModel.PelItem.HeatProbe_2424DC_BEE;
import static gov.nasa.jpl.aerielander.models.power.PowerModel.PelItem.HeatProbe_2424DC_EXT;
import static gov.nasa.jpl.aerielander.models.power.PowerModel.PelItem.HeatProbe_TEMA_BEE;
import static gov.nasa.jpl.aerielander.models.power.PowerModel.PelItem.HeatProbe_TEMA_EXT;
import static gov.nasa.jpl.aerielander.models.power.PowerModel.PelItem.HeatProbe_TEMP_BEE;
import static gov.nasa.jpl.aerielander.models.power.PowerModel.PelItem.HeatProbe_TEMP_EXT;
@ActivityType("HeatProbeTemP")
public final class HeatProbeTemP {
@Parameter
public Duration duration = Duration.of(1, MINUTE);
@Parameter
public boolean setNewSSATime = false;
@EffectModel
@ControllableDuration(parameterName = "duration")
public void run(final Mission mission) {
final var powerModel = mission.powerModel;
// If we ever implement scheduling, set new ssa time now
// if (setNewSSATime) mission.HeatProbeModel.setSSABegin(mission.clocks.getCurrentTime());
powerModel.setPelState(HeatProbe_TEMP_EXT, "on");
powerModel.setPelState(HeatProbe_TEMP_BEE, "on");
powerModel.setPelState(HeatProbe_TEMA_EXT, "on");
powerModel.setPelState(HeatProbe_TEMA_BEE, "on");
powerModel.setPelState(HeatProbe_2424DC_EXT, "on");
powerModel.setPelState(HeatProbe_2424DC_BEE, "on");
delay(duration);
powerModel.setPelState(HeatProbe_TEMP_EXT, "off");
powerModel.setPelState(HeatProbe_TEMP_BEE, "off");
powerModel.setPelState(HeatProbe_TEMA_EXT, "off");
powerModel.setPelState(HeatProbe_TEMA_BEE, "off");
powerModel.setPelState(HeatProbe_2424DC_EXT, "off");
powerModel.setPelState(HeatProbe_2424DC_BEE, "off");
}
}
|
lethunder/lumber | test-fixtures/mongo/nested-array-of-numbers-model.js | const { ObjectID } = require('mongodb');
const persons = [
{
_id: ObjectID(),
name: '<NAME>',
propArrayOfNumbers: [1, 2, 3],
},
];
module.exports = { persons };
|
kiran1235/phalitha | webui/app/models/mapping.rb | <gh_stars>0
class Mapping < ActiveRecord::Base
belongs_to :instance
has_one :property
has_many :mapping_fields
has_many :mappings_users
has_many :users, through: :mappings_users
validates :name, presence: true
validates :description, presence: true
validates :sourcetype, inclusion: { in: %w(xml database), message: "%{value} is not valid" }, presence: true
validates :sourcefilepath, presence: true, if: :is_xml?
validates :targetfilepath, presence: true, if: :is_xml?
validates :sourcefilename, presence: true, if: :is_xml?
validates :databasetype, presence: true, if: :is_database?
validates :hostname, presence: true, if: :is_database?
validates :portno, numericality: { only_integer: true }, presence: true, if: :is_database?
validates :databasename, presence: true, if: :is_database?
validates :username, presence: true, if: :is_database?
validates :accesscode, presence: true, if: :is_database?
validates :sourcename, presence: true, if: :is_database?
validates :targetname, presence: true, if: :is_database?
after_create :generate_access_point
def generate_access_point
self.update_column(:mapping_access_point,self.id.to_s.unpack('H*').join(""))
end
def valid_source_types
return ["xml","database"]
end
def is_xml?
if !sourcetype.nil?
return sourcetype == "xml"
end
end
def is_database?
if !sourcetype.nil?
return sourcetype == "database"
end
end
end
|
g2forge/gearbox | gb-command/src/test/java/com/g2forge/gearbox/command/proxy/method/ITestCommandInterface.java | package com.g2forge.gearbox.command.proxy.method;
public interface ITestCommandInterface extends ICommandInterface {}
|
liumapp/compiling-jvm | openjdk/jdk/test/sun/jvmstat/testlibrary/JavaProcess.java | /*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
*/
import java.io.*;
import java.util.Properties;
public class JavaProcess {
protected Process process = null;
private String classname;
private StringBuilder classArgs;
private StringBuilder javaOptions;
private static String java = System.getProperty("java.home")
+ File.separator + "bin"
+ File.separator + "java";
public JavaProcess(String classname) {
this(classname, "", "");
}
public JavaProcess(String classname, String classArgs) {
this(classname, "", classArgs);
}
public JavaProcess(String classname, String javaOptions, String classArgs) {
this.classname = classname;
this.javaOptions = new StringBuilder(javaOptions);
this.classArgs = new StringBuilder(classArgs);
}
/**
* add java options to the java command
*/
public void addOptions(String[] opts) {
if (javaOptions != null && javaOptions.length() > 0) {
javaOptions.append(" ");
}
for (int i = 0; i < opts.length; i++) {
if (i != 0) {
javaOptions.append(" ");
}
javaOptions.append(opts[i]);
}
}
/**
* add arguments to the class arguments
*/
public void addArguments(String[] args) {
if (classArgs != null && classArgs.length() > 0) {
classArgs.append(" ");
}
for (int i = 0; i < args.length; i++) {
if (i != 0) {
classArgs.append(" ");
}
classArgs.append(args[i]);
}
}
/**
* start the java process
*/
public void start() throws IOException {
if (process != null) {
return;
}
String javaCommand = java + " " + javaOptions + " "
+ classname + " " + classArgs;
System.out.println("exec'ing: " + javaCommand);
process = Runtime.getRuntime().exec(javaCommand);
}
/**
* destroy the java process
*/
public void destroy() {
if (process != null) {
process.destroy();
}
process = null;
}
public int exitValue() {
if (process != null) {
return process.exitValue();
}
throw new RuntimeException("exitValue called with process == null");
}
public InputStream getErrorStream() {
if (process != null) {
return process.getErrorStream();
}
throw new RuntimeException(
"getErrorStream() called with process == null");
}
public InputStream getInputStream() {
if (process != null) {
return process.getInputStream();
}
throw new RuntimeException(
"getInputStream() called with process == null");
}
public OutputStream getOutputStream() {
if (process != null) {
return process.getOutputStream();
}
throw new RuntimeException(
"getOutputStream() called with process == null");
}
public int waitFor() throws InterruptedException {
if (process != null) {
return process.waitFor();
}
throw new RuntimeException("waitFor() called with process == null");
}
}
|
DimchoLakov/JS-Applications | 04. SPA Applications - Exercise/02.Movies/static/js/likes.js | <reponame>DimchoLakov/JS-Applications
import { getUserId, getUserToken } from './login.js';
export async function getLikesCountByMovieId(id) {
try {
const response = await fetch(`http://localhost:3030/data/likes?where=movieId%3D%22${id}%22&distinct=_ownerId&count`);
const data = await response.json();
return data;
} catch (error) {
console.log(error.message);
alert(error.message);
}
}
export async function getUsersLikesByMovieId(id) {
try {
const response = await fetch(`http://localhost:3030/data/likes?where=movieId%3D%22${id}%22%20and%20_ownerId%3D%22${getUserId()}%22`);
const data = await response.json();
return data;
} catch (error) {
console.log(error.message);
alert(error.message);
}
}
export async function likeMovie(event) {
event.preventDefault();
let movieId = event.target.movieId;
try {
const response = await fetch('http://localhost:3030/data/likes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Authorization': getUserToken()
},
body: JSON.stringify({
movieId
})
});
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
let spanWithLike = event.target.parentNode.querySelector('#DetailsLikesSpan');
spanWithLike.style.display = 'block';
spanWithLike.textContent = `Liked ${await getLikesCountByMovieId(movieId)}`;
event.target.style.display = 'none';
} catch (error) {
console.log(error.message);
alert(error.message);
}
} |
jkeen/ember-stereo | addon/helpers/sound-is-loading.js | import StereoBaseIsHelper from 'ember-stereo/-private/helpers/is-helper';
import debugMessage from 'ember-stereo/-private/utils/debug-message';
/**
A helper to detect if a sound is loading.
```hbs
{{#if (sound-is-loading @identifier)}}
<p>This sound is currently loading</p>
{{else}}
<p>This sound is not currently loading</p>
{{/if}}
```
@class {{sound-is-loading}}
@type {Helper}
*/
/**
@method compute
@param {Any} identifier url, urls, url objects, promise that resolves to a url
@return {Boolean}
*/
export default class SoundIsLoading extends StereoBaseIsHelper {
name = 'sound-is-loading'
get result() {
debugMessage(this, `render = ${this.sound?.isLoaded}`)
return (this.sound && this.sound.isLoading) || this.isLoading
}
}
|
richardcyrus/nosh | seeders/20190129230035-create-user.js | // require('dotenv').config();
const bcrypt = require('bcrypt');
const salt = bcrypt.genSaltSync(parseInt(process.env.SALT_WORK_FACTOR));
const hash = bcrypt.hashSync(process.env.SEED_USER_PASSWORD, salt);
module.exports = {
up: async (queryInterface) => {
// await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
await queryInterface.bulkInsert(
'profiles',
[
{
radius: 3,
searchResults: 3,
gender: 'Female',
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
const profile = await queryInterface.sequelize.query(
'SELECT id from profiles'
);
await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
await queryInterface.bulkInsert(
'users',
[
{
provider: 'local',
displayName: '<NAME>',
lastName: 'Doe',
firstName: 'Jan',
email: '<EMAIL>',
password: <PASSWORD>,
profileId: profile[0][0].id,
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete('users', null, {});
},
};
|
Y-sir/spark-cn | sql/core/target/java/org/apache/spark/sql/execution/datasources/orc/OrcOutputWriter.java | <filename>sql/core/target/java/org/apache/spark/sql/execution/datasources/orc/OrcOutputWriter.java<gh_stars>0
package org.apache.spark.sql.execution.datasources.orc;
class OrcOutputWriter extends org.apache.spark.sql.execution.datasources.OutputWriter {
public OrcOutputWriter (java.lang.String path, org.apache.spark.sql.types.StructType dataSchema, org.apache.hadoop.mapreduce.TaskAttemptContext context) { throw new RuntimeException(); }
public void close () { throw new RuntimeException(); }
public void write (org.apache.spark.sql.catalyst.InternalRow row) { throw new RuntimeException(); }
}
|
deadsnakes/python2.3 | Demo/threads/find.py | # A parallelized "find(1)" using the thread module.
# This demonstrates the use of a work queue and worker threads.
# It really does do more stats/sec when using multiple threads,
# although the improvement is only about 20-30 percent.
# (That was 8 years ago. In 2002, on Linux, I can't measure
# a speedup. :-( )
# I'm too lazy to write a command line parser for the full find(1)
# command line syntax, so the predicate it searches for is wired-in,
# see function selector() below. (It currently searches for files with
# world write permission.)
# Usage: parfind.py [-w nworkers] [directory] ...
# Default nworkers is 4
import sys
import getopt
import string
import time
import os
from stat import *
import thread
# Work queue class. Usage:
# wq = WorkQ()
# wq.addwork(func, (arg1, arg2, ...)) # one or more calls
# wq.run(nworkers)
# The work is done when wq.run() completes.
# The function calls executed by the workers may add more work.
# Don't use keyboard interrupts!
class WorkQ:
# Invariants:
# - busy and work are only modified when mutex is locked
# - len(work) is the number of jobs ready to be taken
# - busy is the number of jobs being done
# - todo is locked iff there is no work and somebody is busy
def __init__(self):
self.mutex = thread.allocate()
self.todo = thread.allocate()
self.todo.acquire()
self.work = []
self.busy = 0
def addwork(self, func, args):
job = (func, args)
self.mutex.acquire()
self.work.append(job)
self.mutex.release()
if len(self.work) == 1:
self.todo.release()
def _getwork(self):
self.todo.acquire()
self.mutex.acquire()
if self.busy == 0 and len(self.work) == 0:
self.mutex.release()
self.todo.release()
return None
job = self.work[0]
del self.work[0]
self.busy = self.busy + 1
self.mutex.release()
if len(self.work) > 0:
self.todo.release()
return job
def _donework(self):
self.mutex.acquire()
self.busy = self.busy - 1
if self.busy == 0 and len(self.work) == 0:
self.todo.release()
self.mutex.release()
def _worker(self):
time.sleep(0.00001) # Let other threads run
while 1:
job = self._getwork()
if not job:
break
func, args = job
apply(func, args)
self._donework()
def run(self, nworkers):
if not self.work:
return # Nothing to do
for i in range(nworkers-1):
thread.start_new(self._worker, ())
self._worker()
self.todo.acquire()
# Main program
def main():
nworkers = 4
opts, args = getopt.getopt(sys.argv[1:], '-w:')
for opt, arg in opts:
if opt == '-w':
nworkers = string.atoi(arg)
if not args:
args = [os.curdir]
wq = WorkQ()
for dir in args:
wq.addwork(find, (dir, selector, wq))
t1 = time.time()
wq.run(nworkers)
t2 = time.time()
sys.stderr.write('Total time ' + `t2-t1` + ' sec.\n')
# The predicate -- defines what files we look for.
# Feel free to change this to suit your purpose
def selector(dir, name, fullname, stat):
# Look for world writable files that are not symlinks
return (stat[ST_MODE] & 0002) != 0 and not S_ISLNK(stat[ST_MODE])
# The find procedure -- calls wq.addwork() for subdirectories
def find(dir, pred, wq):
try:
names = os.listdir(dir)
except os.error, msg:
print `dir`, ':', msg
return
for name in names:
if name not in (os.curdir, os.pardir):
fullname = os.path.join(dir, name)
try:
stat = os.lstat(fullname)
except os.error, msg:
print `fullname`, ':', msg
continue
if pred(dir, name, fullname, stat):
print fullname
if S_ISDIR(stat[ST_MODE]):
if not os.path.ismount(fullname):
wq.addwork(find, (fullname, pred, wq))
# Call the main program
main()
|
lizhifuabc/spring-boot-learn | spring-boot-lombok/src/main/java/com/boot/lombok/example/NonNullExample.java | <reponame>lizhifuabc/spring-boot-learn
package com.boot.lombok.example;
import lombok.NonNull;
/**
* https://projectlombok.org/features/NonNull
*
* @author lizhifu
* @date 2020/12/29
*/
public class NonNullExample {
private String name;
public NonNullExample(@NonNull String name) {
this.name = name;
}
public NonNullExample(String name,String nam) {
if (name == null) {
throw new NullPointerException("person is marked @NonNull but is null");
}
this.name = name;
}
public static void main(String[] args) {
new NonNullExample(null);
}
}
|
wnbx/snail | snail/src/main/java/com/acgist/snail/context/NatContext.java | <reponame>wnbx/snail<gh_stars>0
package com.acgist.snail.context;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.acgist.snail.IContext;
import com.acgist.snail.config.SystemConfig;
import com.acgist.snail.net.stun.StunService;
import com.acgist.snail.net.upnp.UpnpClient;
import com.acgist.snail.net.upnp.UpnpServer;
import com.acgist.snail.net.upnp.UpnpService;
import com.acgist.snail.utils.NetUtils;
/**
* <p>NAT(内网穿透)上下文</p>
* <p>已是公网IP不会进行内网穿透</p>
* <p>优先使用UPNP进行端口映射,UPNP映射失败后使用STUN。</p>
*
* @author acgist
*/
public final class NatContext implements IContext {
private static final Logger LOGGER = LoggerFactory.getLogger(NatContext.class);
private static final NatContext INSTANCE = new NatContext();
public static final NatContext getInstance() {
return INSTANCE;
}
/**
* <p>内网穿透类型</p>
*
* @author acgist
*/
public enum Type {
/**
* <p>UPNP</p>
*/
UPNP,
/**
* <p>STUN</p>
*/
STUN,
/**
* <p>没有使用内网穿透</p>
*/
NONE;
}
/**
* <p>UPNP端口映射超时时间:{@value}</p>
*/
private static final int UPNP_TIMEOUT = SystemConfig.CONNECT_TIMEOUT_MILLIS;
/**
* <p>注册NAT执行周期</p>
* <p>如果NAT注册失败下次执行周期</p>
*/
private static final int NAT_INTERVAL = 10;
/**
* <p>内网穿透类型</p>
*/
private Type type = Type.NONE;
/**
* <p>UPNP等待锁</p>
*/
private final Object upnpLock = new Object();
/**
* <p>禁止创建实例</p>
*/
private NatContext() {
}
/**
* <p>注册NAT服务</p>
* <p>必须外部调用不能单例注册:导致不能唤醒</p>
*/
public void register() {
if(this.type != Type.NONE) {
LOGGER.debug("注册NAT服务成功:{}", this.type);
return;
}
LOGGER.debug("注册NAT服务");
if(NetUtils.localIPAddress(NetUtils.LOCAL_HOST_ADDRESS)) {
UpnpClient.newInstance().mSearch();
this.lockUpnp();
if(UpnpService.getInstance().useable()) {
LOGGER.debug("UPNP映射成功");
this.type = Type.UPNP;
} else {
LOGGER.debug("UPNP映射失败:使用STUN映射");
StunService.getInstance().mapping();
}
} else {
LOGGER.debug("已是公网IP地址:忽略NAT设置");
SystemConfig.setExternalIpAddress(NetUtils.LOCAL_HOST_ADDRESS);
}
if(this.type == Type.NONE) {
LOGGER.info("注册NAT服务下次执行时间:{}", NAT_INTERVAL);
SystemThreadContext.timer(NAT_INTERVAL, TimeUnit.SECONDS, this::register);
}
}
/**
* <p>获取内网穿透类型</p>
*
* @return 内网穿透类型
*/
public Type type() {
return this.type;
}
/**
* <p>设置STUN穿透类型</p>
*/
public void stun() {
this.type = Type.STUN;
}
/**
* <p>关闭NAT服务</p>
*/
public void shutdown() {
LOGGER.debug("关闭NAT服务");
if(this.type == Type.UPNP) {
UpnpService.getInstance().release();
UpnpServer.getInstance().close();
}
}
/**
* <p>添加UPNP等待锁</p>
*/
private void lockUpnp() {
synchronized (this.upnpLock) {
try {
this.upnpLock.wait(UPNP_TIMEOUT);
} catch (InterruptedException e) {
LOGGER.debug("线程等待异常", e);
Thread.currentThread().interrupt();
}
}
}
/**
* <p>释放UPNP等待锁</p>
*/
public void unlockUpnp() {
synchronized (this.upnpLock) {
this.upnpLock.notifyAll();
}
}
}
|
hoverjet/google-api-ruby-client | generated/google/apis/fusiontables_v2/classes.rb | # Copyright 2015 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.
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module FusiontablesV2
# Specifies the minimum and maximum values, the color, opacity, icon and weight
# of a bucket within a StyleSetting.
class Bucket
include Google::Apis::Core::Hashable
# Color of line or the interior of a polygon in #RRGGBB format.
# Corresponds to the JSON property `color`
# @return [String]
attr_accessor :color
# Icon name used for a point.
# Corresponds to the JSON property `icon`
# @return [String]
attr_accessor :icon
# Maximum value in the selected column for a row to be styled according to the
# bucket color, opacity, icon, or weight.
# Corresponds to the JSON property `max`
# @return [Float]
attr_accessor :max
# Minimum value in the selected column for a row to be styled according to the
# bucket color, opacity, icon, or weight.
# Corresponds to the JSON property `min`
# @return [Float]
attr_accessor :min
# Opacity of the color: 0.0 (transparent) to 1.0 (opaque).
# Corresponds to the JSON property `opacity`
# @return [Float]
attr_accessor :opacity
# Width of a line (in pixels).
# Corresponds to the JSON property `weight`
# @return [Fixnum]
attr_accessor :weight
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] unless args[:color].nil?
@icon = args[:icon] unless args[:icon].nil?
@max = args[:max] unless args[:max].nil?
@min = args[:min] unless args[:min].nil?
@opacity = args[:opacity] unless args[:opacity].nil?
@weight = args[:weight] unless args[:weight].nil?
end
end
# Specifies the details of a column in a table.
class Column
include Google::Apis::Core::Hashable
# Identifier of the base column. If present, this column is derived from the
# specified base column.
# Corresponds to the JSON property `baseColumn`
# @return [Google::Apis::FusiontablesV2::Column::BaseColumn]
attr_accessor :base_column
# Identifier for the column.
# Corresponds to the JSON property `columnId`
# @return [Fixnum]
attr_accessor :column_id
# JSON schema for interpreting JSON in this column.
# Corresponds to the JSON property `columnJsonSchema`
# @return [String]
attr_accessor :column_json_schema
# JSON object containing custom column properties.
# Corresponds to the JSON property `columnPropertiesJson`
# @return [String]
attr_accessor :column_properties_json
# Column description.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Format pattern.
# Acceptable values are DT_DATE_MEDIUMe.g Dec 24, 2008 DT_DATE_SHORTfor example
# 12/24/08 DT_DATE_TIME_MEDIUMfor example Dec 24, 2008 8:30:45 PM
# DT_DATE_TIME_SHORTfor example 12/24/08 8:30 PM DT_DAY_MONTH_2_DIGIT_YEARfor
# example 24/12/08 DT_DAY_MONTH_2_DIGIT_YEAR_TIMEfor example 24/12/08 20:30
# DT_DAY_MONTH_2_DIGIT_YEAR_TIME_MERIDIANfor example 24/12/08 8:30 PM
# DT_DAY_MONTH_4_DIGIT_YEARfor example 24/12/2008
# DT_DAY_MONTH_4_DIGIT_YEAR_TIMEfor example 24/12/2008 20:30
# DT_DAY_MONTH_4_DIGIT_YEAR_TIME_MERIDIANfor example 24/12/2008 8:30 PM
# DT_ISO_YEAR_MONTH_DAYfor example 2008-12-24 DT_ISO_YEAR_MONTH_DAY_TIMEfor
# example 2008-12-24 20:30:45 DT_MONTH_DAY_4_DIGIT_YEARfor example 12/24/2008
# DT_TIME_LONGfor example 8:30:45 PM UTC-6 DT_TIME_MEDIUMfor example 8:30:45 PM
# DT_TIME_SHORTfor example 8:30 PM DT_YEAR_ONLYfor example 2008
# HIGHLIGHT_UNTYPED_CELLSHighlight cell data that does not match the data type
# NONENo formatting (default) NUMBER_CURRENCYfor example $1234.56
# NUMBER_DEFAULTfor example 1,234.56 NUMBER_INTEGERfor example 1235
# NUMBER_NO_SEPARATORfor example 1234.56 NUMBER_PERCENTfor example 123,456%
# NUMBER_SCIENTIFICfor example 1E3 STRING_EIGHT_LINE_IMAGEDisplays thumbnail
# images as tall as eight lines of text STRING_FOUR_LINE_IMAGEDisplays thumbnail
# images as tall as four lines of text STRING_JSON_TEXTAllows JSON editing of
# text in UI STRING_LINKTreats cell as a link (must start with http:// or https:/
# /) STRING_ONE_LINE_IMAGEDisplays thumbnail images as tall as one line of text
# STRING_VIDEO_OR_MAPDisplay a video or map thumbnail
# Corresponds to the JSON property `formatPattern`
# @return [String]
attr_accessor :format_pattern
# Column graph predicate.
# Used to map table to graph data model (subject,predicate,object)
# See W3C Graph-based Data Model.
# Corresponds to the JSON property `graphPredicate`
# @return [String]
attr_accessor :graph_predicate
# The kind of item this is. For a column, this is always fusiontables#column.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Name of the column.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Type of the column.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
# List of valid values used to validate data and supply a drop-down list of
# values in the web application.
# Corresponds to the JSON property `validValues`
# @return [Array<String>]
attr_accessor :valid_values
# If true, data entered via the web application is validated.
# Corresponds to the JSON property `validateData`
# @return [Boolean]
attr_accessor :validate_data
alias_method :validate_data?, :validate_data
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@base_column = args[:base_column] unless args[:base_column].nil?
@column_id = args[:column_id] unless args[:column_id].nil?
@column_json_schema = args[:column_json_schema] unless args[:column_json_schema].nil?
@column_properties_json = args[:column_properties_json] unless args[:column_properties_json].nil?
@description = args[:description] unless args[:description].nil?
@format_pattern = args[:format_pattern] unless args[:format_pattern].nil?
@graph_predicate = args[:graph_predicate] unless args[:graph_predicate].nil?
@kind = args[:kind] unless args[:kind].nil?
@name = args[:name] unless args[:name].nil?
@type = args[:type] unless args[:type].nil?
@valid_values = args[:valid_values] unless args[:valid_values].nil?
@validate_data = args[:validate_data] unless args[:validate_data].nil?
end
# Identifier of the base column. If present, this column is derived from the
# specified base column.
class BaseColumn
include Google::Apis::Core::Hashable
# The id of the column in the base table from which this column is derived.
# Corresponds to the JSON property `columnId`
# @return [Fixnum]
attr_accessor :column_id
# Offset to the entry in the list of base tables in the table definition.
# Corresponds to the JSON property `tableIndex`
# @return [Fixnum]
attr_accessor :table_index
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@column_id = args[:column_id] unless args[:column_id].nil?
@table_index = args[:table_index] unless args[:table_index].nil?
end
end
end
# Represents a list of columns in a table.
class ColumnList
include Google::Apis::Core::Hashable
# List of all requested columns.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::FusiontablesV2::Column>]
attr_accessor :items
# The kind of item this is. For a column list, this is always fusiontables#
# columnList.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Token used to access the next page of this result. No token is displayed if
# there are no more pages left.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# Total number of columns for the table.
# Corresponds to the JSON property `totalItems`
# @return [Fixnum]
attr_accessor :total_items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] unless args[:items].nil?
@kind = args[:kind] unless args[:kind].nil?
@next_page_token = args[:next_page_token] unless args[:next_page_token].nil?
@total_items = args[:total_items] unless args[:total_items].nil?
end
end
# Represents a Geometry object.
class Geometry
include Google::Apis::Core::Hashable
# The list of geometries in this geometry collection.
# Corresponds to the JSON property `geometries`
# @return [Array<Object>]
attr_accessor :geometries
#
# Corresponds to the JSON property `geometry`
# @return [Object]
attr_accessor :geometry
# Type: A collection of geometries.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@geometries = args[:geometries] unless args[:geometries].nil?
@geometry = args[:geometry] unless args[:geometry].nil?
@type = args[:type] unless args[:type].nil?
end
end
# Represents an import request.
class Import
include Google::Apis::Core::Hashable
# The kind of item this is. For an import, this is always fusiontables#import.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# The number of rows received from the import request.
# Corresponds to the JSON property `numRowsReceived`
# @return [String]
attr_accessor :num_rows_received
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@kind = args[:kind] unless args[:kind].nil?
@num_rows_received = args[:num_rows_received] unless args[:num_rows_received].nil?
end
end
# Represents a line geometry.
class Line
include Google::Apis::Core::Hashable
# The coordinates that define the line.
# Corresponds to the JSON property `coordinates`
# @return [Array<Array<Float>>]
attr_accessor :coordinates
# Type: A line geometry.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@coordinates = args[:coordinates] unless args[:coordinates].nil?
@type = args[:type] unless args[:type].nil?
end
end
# Represents a LineStyle within a StyleSetting
class LineStyle
include Google::Apis::Core::Hashable
# Color of the line in #RRGGBB format.
# Corresponds to the JSON property `strokeColor`
# @return [String]
attr_accessor :stroke_color
# Represents a StyleFunction within a StyleSetting
# Corresponds to the JSON property `strokeColorStyler`
# @return [Google::Apis::FusiontablesV2::StyleFunction]
attr_accessor :stroke_color_styler
# Opacity of the line : 0.0 (transparent) to 1.0 (opaque).
# Corresponds to the JSON property `strokeOpacity`
# @return [Float]
attr_accessor :stroke_opacity
# Width of the line in pixels.
# Corresponds to the JSON property `strokeWeight`
# @return [Fixnum]
attr_accessor :stroke_weight
# Represents a StyleFunction within a StyleSetting
# Corresponds to the JSON property `strokeWeightStyler`
# @return [Google::Apis::FusiontablesV2::StyleFunction]
attr_accessor :stroke_weight_styler
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@stroke_color = args[:stroke_color] unless args[:stroke_color].nil?
@stroke_color_styler = args[:stroke_color_styler] unless args[:stroke_color_styler].nil?
@stroke_opacity = args[:stroke_opacity] unless args[:stroke_opacity].nil?
@stroke_weight = args[:stroke_weight] unless args[:stroke_weight].nil?
@stroke_weight_styler = args[:stroke_weight_styler] unless args[:stroke_weight_styler].nil?
end
end
# Represents a point object.
class Point
include Google::Apis::Core::Hashable
# The coordinates that define the point.
# Corresponds to the JSON property `coordinates`
# @return [Array<Float>]
attr_accessor :coordinates
# Point: A point geometry.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@coordinates = args[:coordinates] unless args[:coordinates].nil?
@type = args[:type] unless args[:type].nil?
end
end
# Represents a PointStyle within a StyleSetting
class PointStyle
include Google::Apis::Core::Hashable
# Name of the icon. Use values defined in http://www.google.com/fusiontables/
# DataSource?dsrcid=308519
# Corresponds to the JSON property `iconName`
# @return [String]
attr_accessor :icon_name
# Represents a StyleFunction within a StyleSetting
# Corresponds to the JSON property `iconStyler`
# @return [Google::Apis::FusiontablesV2::StyleFunction]
attr_accessor :icon_styler
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@icon_name = args[:icon_name] unless args[:icon_name].nil?
@icon_styler = args[:icon_styler] unless args[:icon_styler].nil?
end
end
# Represents a polygon object.
class Polygon
include Google::Apis::Core::Hashable
# The coordinates that define the polygon.
# Corresponds to the JSON property `coordinates`
# @return [Array<Array<Array<Float>>>]
attr_accessor :coordinates
# Type: A polygon geometry.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@coordinates = args[:coordinates] unless args[:coordinates].nil?
@type = args[:type] unless args[:type].nil?
end
end
# Represents a PolygonStyle within a StyleSetting
class PolygonStyle
include Google::Apis::Core::Hashable
# Color of the interior of the polygon in #RRGGBB format.
# Corresponds to the JSON property `fillColor`
# @return [String]
attr_accessor :fill_color
# Represents a StyleFunction within a StyleSetting
# Corresponds to the JSON property `fillColorStyler`
# @return [Google::Apis::FusiontablesV2::StyleFunction]
attr_accessor :fill_color_styler
# Opacity of the interior of the polygon: 0.0 (transparent) to 1.0 (opaque).
# Corresponds to the JSON property `fillOpacity`
# @return [Float]
attr_accessor :fill_opacity
# Color of the polygon border in #RRGGBB format.
# Corresponds to the JSON property `strokeColor`
# @return [String]
attr_accessor :stroke_color
# Represents a StyleFunction within a StyleSetting
# Corresponds to the JSON property `strokeColorStyler`
# @return [Google::Apis::FusiontablesV2::StyleFunction]
attr_accessor :stroke_color_styler
# Opacity of the polygon border: 0.0 (transparent) to 1.0 (opaque).
# Corresponds to the JSON property `strokeOpacity`
# @return [Float]
attr_accessor :stroke_opacity
# Width of the polyon border in pixels.
# Corresponds to the JSON property `strokeWeight`
# @return [Fixnum]
attr_accessor :stroke_weight
# Represents a StyleFunction within a StyleSetting
# Corresponds to the JSON property `strokeWeightStyler`
# @return [Google::Apis::FusiontablesV2::StyleFunction]
attr_accessor :stroke_weight_styler
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@fill_color = args[:fill_color] unless args[:fill_color].nil?
@fill_color_styler = args[:fill_color_styler] unless args[:fill_color_styler].nil?
@fill_opacity = args[:fill_opacity] unless args[:fill_opacity].nil?
@stroke_color = args[:stroke_color] unless args[:stroke_color].nil?
@stroke_color_styler = args[:stroke_color_styler] unless args[:stroke_color_styler].nil?
@stroke_opacity = args[:stroke_opacity] unless args[:stroke_opacity].nil?
@stroke_weight = args[:stroke_weight] unless args[:stroke_weight].nil?
@stroke_weight_styler = args[:stroke_weight_styler] unless args[:stroke_weight_styler].nil?
end
end
# Represents a response to a SQL statement.
class Sqlresponse
include Google::Apis::Core::Hashable
# Columns in the table.
# Corresponds to the JSON property `columns`
# @return [Array<String>]
attr_accessor :columns
# The kind of item this is. For responses to SQL queries, this is always
# fusiontables#sqlresponse.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# The rows in the table. For each cell we print out whatever cell value (e.g.,
# numeric, string) exists. Thus it is important that each cell contains only one
# value.
# Corresponds to the JSON property `rows`
# @return [Array<Array<Object>>]
attr_accessor :rows
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@columns = args[:columns] unless args[:columns].nil?
@kind = args[:kind] unless args[:kind].nil?
@rows = args[:rows] unless args[:rows].nil?
end
end
# Represents a StyleFunction within a StyleSetting
class StyleFunction
include Google::Apis::Core::Hashable
# Bucket function that assigns a style based on the range a column value falls
# into.
# Corresponds to the JSON property `buckets`
# @return [Array<Google::Apis::FusiontablesV2::Bucket>]
attr_accessor :buckets
# Name of the column whose value is used in the style.
# Corresponds to the JSON property `columnName`
# @return [String]
attr_accessor :column_name
# Gradient function that interpolates a range of colors based on column value.
# Corresponds to the JSON property `gradient`
# @return [Google::Apis::FusiontablesV2::StyleFunction::Gradient]
attr_accessor :gradient
# Stylers can be one of three kinds: "fusiontables#fromColumn if the column
# value is to be used as is, i.e., the column values can have colors in #
# RRGGBBAA format or integer line widths or icon names; fusiontables#gradient if
# the styling of the row is to be based on applying the gradient function on the
# column value; or fusiontables#buckets if the styling is to based on the bucket
# into which the the column value falls.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@buckets = args[:buckets] unless args[:buckets].nil?
@column_name = args[:column_name] unless args[:column_name].nil?
@gradient = args[:gradient] unless args[:gradient].nil?
@kind = args[:kind] unless args[:kind].nil?
end
# Gradient function that interpolates a range of colors based on column value.
class Gradient
include Google::Apis::Core::Hashable
# Array with two or more colors.
# Corresponds to the JSON property `colors`
# @return [Array<Google::Apis::FusiontablesV2::StyleFunction::Gradient::Color>]
attr_accessor :colors
# Higher-end of the interpolation range: rows with this value will be assigned
# to colors[n-1].
# Corresponds to the JSON property `max`
# @return [Float]
attr_accessor :max
# Lower-end of the interpolation range: rows with this value will be assigned to
# colors[0].
# Corresponds to the JSON property `min`
# @return [Float]
attr_accessor :min
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@colors = args[:colors] unless args[:colors].nil?
@max = args[:max] unless args[:max].nil?
@min = args[:min] unless args[:min].nil?
end
#
class Color
include Google::Apis::Core::Hashable
# Color in #RRGGBB format.
# Corresponds to the JSON property `color`
# @return [String]
attr_accessor :color
# Opacity of the color: 0.0 (transparent) to 1.0 (opaque).
# Corresponds to the JSON property `opacity`
# @return [Float]
attr_accessor :opacity
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@color = args[:color] unless args[:color].nil?
@opacity = args[:opacity] unless args[:opacity].nil?
end
end
end
end
# Represents a complete StyleSettings object. The primary key is a combination
# of the tableId and a styleId.
class StyleSetting
include Google::Apis::Core::Hashable
# The kind of item this is. A StyleSetting contains the style definitions for
# points, lines, and polygons in a table. Since a table can have any one or all
# of them, a style definition can have point, line and polygon style definitions.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Represents a PointStyle within a StyleSetting
# Corresponds to the JSON property `markerOptions`
# @return [Google::Apis::FusiontablesV2::PointStyle]
attr_accessor :marker_options
# Optional name for the style setting.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Represents a PolygonStyle within a StyleSetting
# Corresponds to the JSON property `polygonOptions`
# @return [Google::Apis::FusiontablesV2::PolygonStyle]
attr_accessor :polygon_options
# Represents a LineStyle within a StyleSetting
# Corresponds to the JSON property `polylineOptions`
# @return [Google::Apis::FusiontablesV2::LineStyle]
attr_accessor :polyline_options
# Identifier for the style setting (unique only within tables).
# Corresponds to the JSON property `styleId`
# @return [Fixnum]
attr_accessor :style_id
# Identifier for the table.
# Corresponds to the JSON property `tableId`
# @return [String]
attr_accessor :table_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@kind = args[:kind] unless args[:kind].nil?
@marker_options = args[:marker_options] unless args[:marker_options].nil?
@name = args[:name] unless args[:name].nil?
@polygon_options = args[:polygon_options] unless args[:polygon_options].nil?
@polyline_options = args[:polyline_options] unless args[:polyline_options].nil?
@style_id = args[:style_id] unless args[:style_id].nil?
@table_id = args[:table_id] unless args[:table_id].nil?
end
end
# Represents a list of styles for a given table.
class StyleSettingList
include Google::Apis::Core::Hashable
# All requested style settings.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::FusiontablesV2::StyleSetting>]
attr_accessor :items
# The kind of item this is. For a style list, this is always fusiontables#
# styleSettingList .
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Token used to access the next page of this result. No token is displayed if
# there are no more styles left.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# Total number of styles for the table.
# Corresponds to the JSON property `totalItems`
# @return [Fixnum]
attr_accessor :total_items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] unless args[:items].nil?
@kind = args[:kind] unless args[:kind].nil?
@next_page_token = args[:next_page_token] unless args[:next_page_token].nil?
@total_items = args[:total_items] unless args[:total_items].nil?
end
end
# Represents a table.
class Table
include Google::Apis::Core::Hashable
# Attribution assigned to the table.
# Corresponds to the JSON property `attribution`
# @return [String]
attr_accessor :attribution
# Optional link for attribution.
# Corresponds to the JSON property `attributionLink`
# @return [String]
attr_accessor :attribution_link
# Base table identifier if this table is a view or merged table.
# Corresponds to the JSON property `baseTableIds`
# @return [Array<String>]
attr_accessor :base_table_ids
# Default JSON schema for validating all JSON column properties.
# Corresponds to the JSON property `columnPropertiesJsonSchema`
# @return [String]
attr_accessor :column_properties_json_schema
# Columns in the table.
# Corresponds to the JSON property `columns`
# @return [Array<Google::Apis::FusiontablesV2::Column>]
attr_accessor :columns
# Description assigned to the table.
# Corresponds to the JSON property `description`
# @return [String]
attr_accessor :description
# Variable for whether table is exportable.
# Corresponds to the JSON property `isExportable`
# @return [Boolean]
attr_accessor :is_exportable
alias_method :is_exportable?, :is_exportable
# The kind of item this is. For a table, this is always fusiontables#table.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Name assigned to a table.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# SQL that encodes the table definition for derived tables.
# Corresponds to the JSON property `sql`
# @return [String]
attr_accessor :sql
# Encrypted unique alphanumeric identifier for the table.
# Corresponds to the JSON property `tableId`
# @return [String]
attr_accessor :table_id
# JSON object containing custom table properties.
# Corresponds to the JSON property `tablePropertiesJson`
# @return [String]
attr_accessor :table_properties_json
# JSON schema for validating the JSON table properties.
# Corresponds to the JSON property `tablePropertiesJsonSchema`
# @return [String]
attr_accessor :table_properties_json_schema
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@attribution = args[:attribution] unless args[:attribution].nil?
@attribution_link = args[:attribution_link] unless args[:attribution_link].nil?
@base_table_ids = args[:base_table_ids] unless args[:base_table_ids].nil?
@column_properties_json_schema = args[:column_properties_json_schema] unless args[:column_properties_json_schema].nil?
@columns = args[:columns] unless args[:columns].nil?
@description = args[:description] unless args[:description].nil?
@is_exportable = args[:is_exportable] unless args[:is_exportable].nil?
@kind = args[:kind] unless args[:kind].nil?
@name = args[:name] unless args[:name].nil?
@sql = args[:sql] unless args[:sql].nil?
@table_id = args[:table_id] unless args[:table_id].nil?
@table_properties_json = args[:table_properties_json] unless args[:table_properties_json].nil?
@table_properties_json_schema = args[:table_properties_json_schema] unless args[:table_properties_json_schema].nil?
end
end
# Represents a list of tables.
class TableList
include Google::Apis::Core::Hashable
# List of all requested tables.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::FusiontablesV2::Table>]
attr_accessor :items
# The kind of item this is. For table list, this is always fusiontables#
# tableList.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Token used to access the next page of this result. No token is displayed if
# there are no more pages left.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] unless args[:items].nil?
@kind = args[:kind] unless args[:kind].nil?
@next_page_token = args[:next_page_token] unless args[:next_page_token].nil?
end
end
# A background task on a table, initiated for time- or resource-consuming
# operations such as changing column types or deleting all rows.
class Task
include Google::Apis::Core::Hashable
# Type of the resource. This is always "fusiontables#task".
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Task percentage completion.
# Corresponds to the JSON property `progress`
# @return [String]
attr_accessor :progress
# false while the table is busy with some other task. true if this background
# task is currently running.
# Corresponds to the JSON property `started`
# @return [Boolean]
attr_accessor :started
alias_method :started?, :started
# Identifier for the task.
# Corresponds to the JSON property `taskId`
# @return [String]
attr_accessor :task_id
# Type of background task.
# Corresponds to the JSON property `type`
# @return [String]
attr_accessor :type
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@kind = args[:kind] unless args[:kind].nil?
@progress = args[:progress] unless args[:progress].nil?
@started = args[:started] unless args[:started].nil?
@task_id = args[:task_id] unless args[:task_id].nil?
@type = args[:type] unless args[:type].nil?
end
end
# Represents a list of tasks for a table.
class TaskList
include Google::Apis::Core::Hashable
# List of all requested tasks.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::FusiontablesV2::Task>]
attr_accessor :items
# Type of the resource. This is always "fusiontables#taskList".
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Token used to access the next page of this result. No token is displayed if
# there are no more pages left.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# Total number of tasks for the table.
# Corresponds to the JSON property `totalItems`
# @return [Fixnum]
attr_accessor :total_items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] unless args[:items].nil?
@kind = args[:kind] unless args[:kind].nil?
@next_page_token = args[:next_page_token] unless args[:next_page_token].nil?
@total_items = args[:total_items] unless args[:total_items].nil?
end
end
# Represents the contents of InfoWindow templates.
class Template
include Google::Apis::Core::Hashable
# List of columns from which the template is to be automatically constructed.
# Only one of body or automaticColumns can be specified.
# Corresponds to the JSON property `automaticColumnNames`
# @return [Array<String>]
attr_accessor :automatic_column_names
# Body of the template. It contains HTML with `column_name` to insert values
# from a particular column. The body is sanitized to remove certain tags, e.g.,
# script. Only one of body or automaticColumns can be specified.
# Corresponds to the JSON property `body`
# @return [String]
attr_accessor :body
# The kind of item this is. For a template, this is always fusiontables#template.
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Optional name assigned to a template.
# Corresponds to the JSON property `name`
# @return [String]
attr_accessor :name
# Identifier for the table for which the template is defined.
# Corresponds to the JSON property `tableId`
# @return [String]
attr_accessor :table_id
# Identifier for the template, unique within the context of a particular table.
# Corresponds to the JSON property `templateId`
# @return [Fixnum]
attr_accessor :template_id
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@automatic_column_names = args[:automatic_column_names] unless args[:automatic_column_names].nil?
@body = args[:body] unless args[:body].nil?
@kind = args[:kind] unless args[:kind].nil?
@name = args[:name] unless args[:name].nil?
@table_id = args[:table_id] unless args[:table_id].nil?
@template_id = args[:template_id] unless args[:template_id].nil?
end
end
# Represents a list of templates for a given table.
class TemplateList
include Google::Apis::Core::Hashable
# List of all requested templates.
# Corresponds to the JSON property `items`
# @return [Array<Google::Apis::FusiontablesV2::Template>]
attr_accessor :items
# The kind of item this is. For a template list, this is always fusiontables#
# templateList .
# Corresponds to the JSON property `kind`
# @return [String]
attr_accessor :kind
# Token used to access the next page of this result. No token is displayed if
# there are no more pages left.
# Corresponds to the JSON property `nextPageToken`
# @return [String]
attr_accessor :next_page_token
# Total number of templates for the table.
# Corresponds to the JSON property `totalItems`
# @return [Fixnum]
attr_accessor :total_items
def initialize(**args)
update!(**args)
end
# Update properties of this object
def update!(**args)
@items = args[:items] unless args[:items].nil?
@kind = args[:kind] unless args[:kind].nil?
@next_page_token = args[:next_page_token] unless args[:next_page_token].nil?
@total_items = args[:total_items] unless args[:total_items].nil?
end
end
end
end
end
|
cstamas/krati | src/test/java/test/store/TestDynamicStoreMapped.java | <reponame>cstamas/krati
package test.store;
import krati.core.segment.SegmentFactory;
/**
* TestDynamicStore using MappedSegment.
*
* @author jwu
*
*/
public class TestDynamicStoreMapped extends TestDynamicStore
{
@Override
protected SegmentFactory getSegmentFactory()
{
return new krati.core.segment.MappedSegmentFactory();
}
}
|
dandycheung/GIFCompressor | lib/src/main/java/com/otaliastudios/gif/source/FileDescriptorDataSource.java | <reponame>dandycheung/GIFCompressor<filename>lib/src/main/java/com/otaliastudios/gif/source/FileDescriptorDataSource.java
package com.otaliastudios.gif.source;
import android.content.Context;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.InputStream;
import androidx.annotation.NonNull;
/**
* A {@link DataSource} backed by a file descriptor.
*/
public class FileDescriptorDataSource extends DefaultDataSource {
@NonNull
private FileDescriptor descriptor;
public FileDescriptorDataSource(@NonNull Context context, @NonNull FileDescriptor descriptor) {
super(context);
this.descriptor = descriptor;
}
@NonNull
@Override
protected InputStream openInputStream() {
return new FileInputStream(descriptor);
}
}
|
florianrusch-zf/DataSpaceConnector | extensions/sql/transfer-process-store/src/main/java/org/eclipse/dataspaceconnector/sql/transferprocess/SqlTransferProcessStoreExtension.java | <reponame>florianrusch-zf/DataSpaceConnector
/*
* Copyright (c) 2020 - 2022 Microsoft Corporation
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Microsoft Corporation - initial API and implementation
*
*/
package org.eclipse.dataspaceconnector.sql.transferprocess;
import org.eclipse.dataspaceconnector.spi.EdcSetting;
import org.eclipse.dataspaceconnector.spi.system.Inject;
import org.eclipse.dataspaceconnector.spi.system.Provides;
import org.eclipse.dataspaceconnector.spi.system.ServiceExtension;
import org.eclipse.dataspaceconnector.spi.system.ServiceExtensionContext;
import org.eclipse.dataspaceconnector.spi.transaction.TransactionContext;
import org.eclipse.dataspaceconnector.spi.transaction.datasource.DataSourceRegistry;
import org.eclipse.dataspaceconnector.spi.transfer.store.TransferProcessStore;
import org.eclipse.dataspaceconnector.sql.transferprocess.store.PostgresStatements;
import org.eclipse.dataspaceconnector.sql.transferprocess.store.SqlTransferProcessStore;
import org.eclipse.dataspaceconnector.sql.transferprocess.store.TransferProcessStoreStatements;
@Provides(TransferProcessStore.class)
public class SqlTransferProcessStoreExtension implements ServiceExtension {
@EdcSetting
private static final String DATASOURCE_NAME_SETTING = "edc.datasource.transferprocess.name";
private static final String DEFAULT_DATASOURCE_NAME = "transferprocess";
@Inject
private DataSourceRegistry dataSourceRegistry;
@Inject
private TransactionContext trxContext;
@Inject(required = false)
private TransferProcessStoreStatements statements;
@Override
public void initialize(ServiceExtensionContext context) {
var store = new SqlTransferProcessStore(dataSourceRegistry, getDataSourceName(context), trxContext, context.getTypeManager().getMapper(), getStatementImpl(), context.getConnectorId());
context.registerService(TransferProcessStore.class, store);
}
/**
* returns an externally-provided sql statement dialect, or postgres as a default
*/
private TransferProcessStoreStatements getStatementImpl() {
return statements != null ? statements : new PostgresStatements();
}
private String getDataSourceName(ServiceExtensionContext context) {
return context.getConfig().getString(DATASOURCE_NAME_SETTING, DEFAULT_DATASOURCE_NAME);
}
}
|
maciejasembler/puppet-pacemaker | spec/unit/puppet/provider/pacemaker_order/xml_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:pacemaker_order).provider(:xml) do
let(:resource) do
Puppet::Type.type(:pacemaker_order).new(
name: 'my_order',
first: 'p_1',
second: 'p_2',
provider: :xml,
)
end
let(:provider) do
resource.provider
end
before(:each) do
puppet_debug_override
provider.stubs(:cluster_debug_report).returns(true)
provider.stubs(:primitive_exists?).with('p_1').returns(true)
provider.stubs(:primitive_exists?).with('p_2').returns(true)
end
describe('#validation') do
it 'should fail if there is no "first" primitive in the CIB' do
provider.stubs(:primitive_exists?).with('p_1').returns(false)
provider.create
expect { provider.flush }.to raise_error "Primitive 'p_1' does not exist!"
end
it 'should fail if there is no "then" primitive in the CIB' do
provider.stubs(:primitive_exists?).with('p_2').returns(false)
provider.create
expect { provider.flush }.to raise_error "Primitive 'p_2' does not exist!"
end
end
context 'with #score' do
it 'should update an order' do
resource[:first] = 'p_1'
resource[:second] = 'p_2'
resource[:score] = '100'
provider.stubs(:constraint_order_exists?).returns(true)
xml = <<-eos
<rsc_order first='p_1' id='my_order' score='100' then='p_2'/>
eos
provider.expects(:wait_for_constraint_update).with xml, resource[:name]
provider.create
provider.property_hash[:ensure] = :present
provider.flush
end
it 'should create an order' do
resource[:first] = 'p_1'
resource[:second] = 'p_2'
resource[:score] = '100'
xml = <<-eos
<rsc_order first='p_1' id='my_order' score='100' then='p_2'/>
eos
provider.expects(:wait_for_constraint_create).with xml, resource['name']
provider.create
provider.property_hash[:ensure] = :absent
provider.flush
end
end
context 'with #kind' do
it 'should update an order' do
resource[:first] = 'p_1'
resource[:second] = 'p_2'
resource[:first_action] = 'promote'
resource[:second_action] = 'demote'
resource[:kind] = 'serialize'
resource[:symmetrical] = false
resource[:require_all] = false
provider.stubs(:constraint_order_exists?).returns(true)
xml = <<-eos
<rsc_order first='p_1' first-action='promote' id='my_order' kind='Serialize' require-all='false' symmetrical='false' then='p_2' then-action='demote'/>
eos
provider.expects(:wait_for_constraint_update).with xml, resource[:name]
provider.create
provider.property_hash[:ensure] = :present
provider.flush
end
it 'should create an order' do
resource[:first] = 'p_1'
resource[:second] = 'p_2'
resource[:first_action] = 'promote'
resource[:second_action] = 'demote'
resource[:kind] = 'serialize'
resource[:symmetrical] = false
resource[:require_all] = false
xml = <<-eos
<rsc_order first='p_1' first-action='promote' id='my_order' kind='Serialize' require-all='false' symmetrical='false' then='p_2' then-action='demote'/>
eos
provider.expects(:wait_for_constraint_create).with xml, resource['name']
provider.create
provider.property_hash[:ensure] = :absent
provider.flush
end
end
describe '#destroy' do
it 'should destroy order with corresponding name' do
xml = "<rsc_order id='my_order'/>\n"
provider.expects(:wait_for_constraint_remove).with xml, resource[:name]
provider.destroy
provider.flush
end
end
end
|
saperiumrocks/node-eventstore | jasmine/integration-narrow/eventstore-playback-list-view-myql-store.jasmine-integration-spec.js | <filename>jasmine/integration-narrow/eventstore-playback-list-view-myql-store.jasmine-integration-spec.js
const Bluebird = require('bluebird');
const EventstorePlaybackListStore = require('../../lib/eventstore-projections/eventstore-playbacklist-mysql-store');
const EventstorePlaybackListView = require('../../lib/eventstore-projections/eventstore-playback-list-view');
const shortid = require('shortid');
const mysqlOptions = {
host: 'localhost',
port: 13306,
user: 'root',
password: '<PASSWORD>',
database: 'playbacklist_db',
connectionLimit: 10
};
const mysqlServer = (function() {
const sleepAsync = function(sleepUntil) {
return new Promise((resolve) => {
setTimeout(resolve, sleepUntil);
});
}
const exec = require('child_process').exec;
const mysql = require('mysql');
return {
up: async function() {
const command = `docker run --name eventstore_playbacklist_view_mysql -e MYSQL_ROOT_PASSWORD=${mysqlOptions.password} -e MYSQL_DATABASE=${mysqlOptions.database} -p ${mysqlOptions.port}:3306 -d mysql:5.7`;
const process = exec(command);
// wait until process has exited
console.log('downloading mysql image or creating a container. waiting for child process to return an exit code');
do {
await sleepAsync(1000);
} while (process.exitCode == null);
console.log('child process exited with exit code: ', process.exitCode);
console.info('waiting for mysql database to start...');
let retries = 0;
let gaveUp = true;
let conn = null;
do {
try {
conn = mysql.createConnection(mysqlOptions);
Bluebird.promisifyAll(conn);
await conn.connectAsync();
console.log('connected!');
gaveUp = false;
break;
} catch (error) {
conn.end();
console.log(`mysql retry attempt ${retries + 1} after 1000ms`);
await sleepAsync(1000);
retries++;
}
} while (retries < 20);
if (gaveUp) {
console.error('given up connecting to mysql database');
console.error('abandoning tests');
} else {
console.log('successfully connected to mysql database');
}
},
down: async function() {
exec('docker rm eventstore_playbacklist_view_mysql --force');
}
}
})();
describe('eventstore-playback-list-view-mysql-store tests', () => {
let eventstorePlaybackListStore = new EventstorePlaybackListStore();
let eventstorePlaybackListView = new EventstorePlaybackListView();
let eventstorePlaybackListViewOptimized = new EventstorePlaybackListView();
let eventstorePlaybackListViewUnionOptimized = new EventstorePlaybackListView();
let eventstorePlaybackListViewDefaultWhereOptimized = new EventstorePlaybackListView();
let listName;
let listName2;
beforeAll(async (done) => {
await mysqlServer.up();
eventstorePlaybackListStore = new EventstorePlaybackListStore(mysqlOptions);
await eventstorePlaybackListStore.init();
let randomString = 'list_' + shortid.generate();
randomString = randomString.replace('-', '');
listName = 'list_' + randomString;
await eventstorePlaybackListStore.createList({
name: listName,
fields: [{
name: 'vehicleId',
type: 'string'
},
{
name: 'accessDate',
type: 'date'
},
{
name: 'type',
type: 'int'
}]
});
let randomString2 = 'list_' + shortid.generate();
randomString2 = randomString2.replace('-', '');
listName2 = 'list_' + randomString2;
await eventstorePlaybackListStore.createList({
name: listName2,
fields: [{
name: 'vehicleId',
type: 'string'
},
{
name: 'accessDate',
type: 'date'
},
{
name: 'type',
type: 'int'
}]
});
// add items to our list
for (let i = 0; i < 10; i++) {
const rowId = shortid.generate();
const revision = i;
const data = {
vehicleId: 'vehicle_' + revision,
accessDate: `2020-11-${(revision+1) >= 10 ? (revision+1) : '0' + (revision+1)}`,
type: i % 2
};
const meta = {
streamRevision: revision
}
await eventstorePlaybackListStore.add(listName, rowId, revision, data, meta);
}
// add items to our second list
for (let i = 0; i < 10; i++) {
const rowId = shortid.generate();
const revision = i;
const data = {
vehicleId: 'vehicle_' + (revision + 10),
accessDate: `2020-11-${(revision+1) >= 10 ? (revision+1) : '0' + (revision+1)}`,
type: i % 2
};
const meta = {
streamRevision: revision
}
await eventstorePlaybackListStore.add(listName2, rowId, revision, data, meta);
}
eventstorePlaybackListView = new EventstorePlaybackListView({
host: mysqlOptions.host,
port: mysqlOptions.port,
database: mysqlOptions.database,
user: mysqlOptions.user,
password: <PASSWORD>,
listName: "list_view_1",
query: `SELECT * FROM ${listName}`,
alias: undefined
});
Bluebird.promisifyAll(eventstorePlaybackListView);
await eventstorePlaybackListView.init();
eventstorePlaybackListViewOptimized = new EventstorePlaybackListView({
host: mysqlOptions.host,
port: mysqlOptions.port,
database: mysqlOptions.database,
user: mysqlOptions.user,
password: <PASSWORD>,
listName: "list_view_2",
query: `SELECT * FROM ${listName} AS vehicle_list @@where @@order @@limit; SELECT COUNT(1) AS total_count FROM ${listName} AS vehicle_list @@where;`,
alias: {
vehicleId: `vehicle_list.vehicleId`,
accessDate: `vehicle_list.accessDate`
}
});
Bluebird.promisifyAll(eventstorePlaybackListViewOptimized);
await eventstorePlaybackListViewOptimized.init();
eventstorePlaybackListViewUnionOptimized = new EventstorePlaybackListView({
host: mysqlOptions.host,
port: mysqlOptions.port,
database: mysqlOptions.database,
user: mysqlOptions.user,
password: <PASSWORD>,
listName: "list_view_3",
query: `SELECT * FROM (( SELECT * FROM ${listName} AS vehicle_list @@where @@order @@unionlimit ) UNION ALL ` +
`( SELECT * FROM ${listName2} AS vehicle_list @@where @@order @@unionlimit )) vehicle_list @@order @@limit; ` +
`SELECT SUM(t_count) as total_count FROM (( SELECT COUNT(1) AS t_count FROM ${listName} AS vehicle_list @@where ) UNION ALL ` +
`( SELECT COUNT(1) AS t_count FROM ${listName2} AS vehicle_list @@where )) t1;`,
alias: {
vehicleId: `vehicle_list.vehicleId`,
accessDate: `vehicle_list.accessDate`
}
});
Bluebird.promisifyAll(eventstorePlaybackListViewUnionOptimized);
await eventstorePlaybackListViewUnionOptimized.init();
eventstorePlaybackListViewDefaultWhereOptimized = new EventstorePlaybackListView({
host: mysqlOptions.host,
port: mysqlOptions.port,
database: mysqlOptions.database,
user: mysqlOptions.user,
password: <PASSWORD>,
listName: "list_view_2",
query: `SELECT * FROM ${listName} AS vehicle_list @@where and vehicle_list.type = 1 @@order @@limit; SELECT COUNT(1) AS total_count FROM ${listName} AS vehicle_list @@where and type = 1;`,
alias: {
vehicleId: `vehicle_list.vehicleId`,
accessDate: `vehicle_list.accessDate`,
type: `vehicle_list.type`
}
});
Bluebird.promisifyAll(eventstorePlaybackListViewDefaultWhereOptimized);
await eventstorePlaybackListViewDefaultWhereOptimized.init();
done();
}, 60000);
describe('query', () => {
it('should return the correct results based on the query parameters passed using LISTVIEW', async (done) => {
try {
const allResultsInserted = await eventstorePlaybackListView.queryAsync(0, 10, null, null);
expect(allResultsInserted.count).toEqual(10);
expect(allResultsInserted.rows.length).toEqual(10);
const pagedResults = await eventstorePlaybackListView.queryAsync(5, 5, null, null);
// should get revision 5 - 9
expect(pagedResults.count).toEqual(10); // total still 10
expect(pagedResults.rows.length).toEqual(5); // paged should be 5
const filteredResults = await eventstorePlaybackListView.queryAsync(0, 5, [{
field: 'vehicleId',
operator: 'is',
value: 'vehicle_5'
},{
field: 'accessDate',
operator: 'dateRange',
from: '2020-11-01',
to: '2020-11-10'
}], null);
expect(filteredResults.count).toEqual(1); // total = 1 after filter
expect(filteredResults.rows.length).toEqual(1);
expect(filteredResults.rows[0].revision).toEqual(5);
expect(filteredResults.rows[0].data.vehicleId).toEqual('vehicle_5');
const sortedResults = await eventstorePlaybackListView.queryAsync(0, 10, null, [{
field: 'vehicleId',
sortDirection: 'ASC'
}]);
expect(sortedResults.count).toEqual(10); // total still 10
expect(sortedResults.rows.length).toEqual(10);
expect(sortedResults.rows[0].revision).toEqual(0);
expect(sortedResults.rows[0].data.vehicleId).toEqual('vehicle_0');
done();
} catch (error) {
console.log(error);
throw error;
}
});
it('should return the correct results based on the query parameters passed using optimized query', async (done) => {
try {
const allResultsInserted = await eventstorePlaybackListViewOptimized.queryAsync(0, 10, null, null);
expect(allResultsInserted.count).toEqual(10);
expect(allResultsInserted.rows.length).toEqual(10);
const pagedResults = await eventstorePlaybackListViewOptimized.queryAsync(5, 5, null, null);
// should get revision 5 - 9
expect(pagedResults.count).toEqual(10); // total still 10
expect(pagedResults.rows.length).toEqual(5); // paged should be 5
const filteredResults = await eventstorePlaybackListViewOptimized.queryAsync(0, 5, [{
field: 'vehicleId',
operator: 'is',
value: 'vehicle_5'
}], null);
expect(filteredResults.count).toEqual(1); // total = 1 after filter
expect(filteredResults.rows.length).toEqual(1);
expect(filteredResults.rows[0].revision).toEqual(5);
expect(filteredResults.rows[0].data.vehicleId).toEqual('vehicle_5');
const sortedResults = await eventstorePlaybackListViewOptimized.queryAsync(0, 10, null, [{
field: 'vehicleId',
sortDirection: 'ASC'
}]);
expect(sortedResults.count).toEqual(10); // total still 10
expect(sortedResults.rows.length).toEqual(10);
expect(sortedResults.rows[0].revision).toEqual(0);
expect(sortedResults.rows[0].data.vehicleId).toEqual('vehicle_0');
done();
} catch (error) {
console.log(error);
throw error;
}
});
it('should return the correct results based on the query parameters passed using union optimized query', async (done) => {
try {
const allResultsInserted = await eventstorePlaybackListViewUnionOptimized.queryAsync(0, 10, null, null);
console.log(JSON.stringify(allResultsInserted));
expect(allResultsInserted.count).toEqual(20);
expect(allResultsInserted.rows.length).toEqual(10);
const pagedResults = await eventstorePlaybackListViewUnionOptimized.queryAsync(5, 5, null, null);
// should get revision 5 - 9
expect(pagedResults.count).toEqual(20); // total still 20
expect(pagedResults.rows.length).toEqual(5); // paged should be 5
const filteredResults = await eventstorePlaybackListViewUnionOptimized.queryAsync(0, 5, [{
field: 'vehicleId',
operator: 'is',
value: 'vehicle_5'
}], null);
expect(filteredResults.count).toEqual(1);
expect(filteredResults.rows.length).toEqual(1);
expect(filteredResults.rows[0].revision).toEqual(5);
expect(filteredResults.rows[0].data.vehicleId).toEqual('vehicle_5');
console.log(JSON.stringify(filteredResults));
const sortedResults = await eventstorePlaybackListViewUnionOptimized.queryAsync(0, 10, null, [{
field: 'accessDate',
sortDirection: 'ASC'
}]);
expect(sortedResults.count).toEqual(20);
expect(sortedResults.rows.length).toEqual(10);
expect(sortedResults.rows[0].revision).toEqual(0);
expect(sortedResults.rows[0].data.vehicleId).toEqual('vehicle_0');
expect(sortedResults.rows[1].revision).toEqual(0);
expect(sortedResults.rows[1].data.vehicleId).toEqual('vehicle_10');
expect(sortedResults.rows[2].revision).toEqual(1);
expect(sortedResults.rows[2].data.vehicleId).toEqual('vehicle_1');
expect(sortedResults.rows[3].revision).toEqual(1);
expect(sortedResults.rows[3].data.vehicleId).toEqual('vehicle_11');
done();
} catch (error) {
console.log(error);
throw error;
}
});
it('should return the correct results based on the query parameters passed using optimized query with default where clause', async (done) => {
try {
const allResultsInserted = await eventstorePlaybackListViewDefaultWhereOptimized.queryAsync(0, 10, null, null);
expect(allResultsInserted.count).toEqual(5);
expect(allResultsInserted.rows.length).toEqual(5);
const pagedResults = await eventstorePlaybackListViewDefaultWhereOptimized.queryAsync(3, 5, null, null);
// should get revision 5 - 9
expect(pagedResults.count).toEqual(5); // total still 5
expect(pagedResults.rows.length).toEqual(2); // paged should be 2
const filteredResults = await eventstorePlaybackListViewDefaultWhereOptimized.queryAsync(0, 5, [{
field: 'vehicleId',
operator: 'is',
value: 'vehicle_5'
}], null);
expect(filteredResults.count).toEqual(1); // total = 1 after filter
expect(filteredResults.rows.length).toEqual(1);
expect(filteredResults.rows[0].revision).toEqual(5);
expect(filteredResults.rows[0].data.vehicleId).toEqual('vehicle_5');
const sortedResults = await eventstorePlaybackListViewDefaultWhereOptimized.queryAsync(0, 10, null, [{
field: 'vehicleId',
sortDirection: 'ASC'
}]);
expect(sortedResults.count).toEqual(5); // total still 5
expect(sortedResults.rows.length).toEqual(5);
expect(sortedResults.rows[0].revision).toEqual(1);
expect(sortedResults.rows[0].data.vehicleId).toEqual('vehicle_1');
done();
} catch (error) {
console.log(error);
throw error;
}
});
});
afterAll(async (done) => {
// NOTE: uncomment if we need to terminate the mysql every test
// for now, it is okay since we are using a non-standard port (13306) and a fixed docker container name
// not terminating will make the tests faster by around 11 secs
await eventstorePlaybackListStore.close();
// await mysqlServer.down();
done();
})
}); |
janheise/zentral | zentral/contrib/mdm/migrations/0036_auto_20210530_0858.py | <filename>zentral/contrib/mdm/migrations/0036_auto_20210530_0858.py
# Generated by Django 2.2.18 on 2021-05-30 08:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mdm', '0035_auto_20210530_0717'),
]
operations = [
migrations.AlterField(
model_name='enterpriseapp',
name='bundle_identifier',
field=models.TextField(),
),
migrations.AlterField(
model_name='profile',
name='payload_description',
field=models.TextField(default=''),
preserve_default=False,
),
migrations.AlterField(
model_name='profile',
name='payload_identifier',
field=models.TextField(db_index=True),
),
migrations.AlterUniqueTogether(
name='artifactversion',
unique_together={('artifact', 'version')},
),
migrations.AlterUniqueTogether(
name='enterpriseapp',
unique_together=set(),
),
migrations.AddIndex(
model_name='enterpriseapp',
index=models.Index(fields=['bundle_identifier', 'bundle_version'], name='mdm_enterpr_bundle__777841_idx'),
),
migrations.RemoveField(
model_name='enterpriseapp',
name='created_at',
),
migrations.RemoveField(
model_name='enterpriseapp',
name='updated_at',
),
]
|
stephen-shelby/starrocks | fe/fe-core/src/test/java/com/starrocks/sql/analyzer/AdminSetTest.java | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
package com.starrocks.sql.analyzer;
import com.starrocks.utframe.UtFrameUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.starrocks.sql.analyzer.AnalyzeTestUtil.analyzeFail;
import static com.starrocks.sql.analyzer.AnalyzeTestUtil.analyzeSuccess;
public class AdminSetTest {
@BeforeClass
public static void beforeClass() throws Exception {
UtFrameUtils.createMinStarRocksCluster();
AnalyzeTestUtil.init();
}
@Test
public void TestAdminSetConfig() {
analyzeSuccess("admin set frontend config(\"alter_table_timeout_second\" = \"60\");");
analyzeFail("admin set frontend config;",
"mismatched input '<EOF>' expecting '('");
}
@Test
public void TestAdminSetReplicaStatus() {
analyzeSuccess("admin set replica status properties(\"tablet_id\" = \"10003\",\"backend_id\" = \"10001\",\"status\" = \"ok\");");
analyzeFail("admin set replica status properties(\"backend_id\" = \"10001\",\"status\" = \"ok\");",
"Should add following properties: TABLET_ID, BACKEND_ID and STATUS");
analyzeFail("admin set replica status properties(\"tablet_id\" = \"10003\",\"status\" = \"ok\");",
"Should add following properties: TABLET_ID, BACKEND_ID and STATUS");
analyzeFail("admin set replica status properties(\"tablet_id\" = \"10003\",\"backend_id\" = \"10001\");",
"Should add following properties: TABLET_ID, BACKEND_ID and STATUS");
analyzeFail("admin set replica status properties(\"tablet_id\" = \"10003\",\"backend_id\" = \"10001\",\"status\" = \"MISSING\");",
"Do not support setting replica status as MISSING");
analyzeFail("admin set replica status properties(\"unknown_config\" = \"10003\");",
"Unknown property: unknown_config");
}
}
|
valera-rozuvan/sharky | src/bitboard.c | <reponame>valera-rozuvan/sharky<filename>src/bitboard.c
/*
*
* setBitMask[] and clrBitMask[] arrays are used by the macros CLEAR_BIT() and SET_BIT().
* There are 64 items in each array so that we can use the macros on any C numeric type
* (integers), including `unsigned long long`.
*
**/
unsigned long long setBitMask[64] = {
1ULL,
2ULL,
4ULL,
8ULL,
16ULL,
32ULL,
64ULL,
128ULL,
256ULL,
512ULL,
1024ULL,
2048ULL,
4096ULL,
8192ULL,
16384ULL,
32768ULL,
65536ULL,
131072ULL,
262144ULL,
524288ULL,
1048576ULL,
2097152ULL,
4194304ULL,
8388608ULL,
16777216ULL,
33554432ULL,
67108864ULL,
134217728ULL,
268435456ULL,
536870912ULL,
1073741824ULL,
2147483648ULL,
4294967296ULL,
8589934592ULL,
17179869184ULL,
34359738368ULL,
68719476736ULL,
137438953472ULL,
274877906944ULL,
549755813888ULL,
1099511627776ULL,
2199023255552ULL,
4398046511104ULL,
8796093022208ULL,
17592186044416ULL,
35184372088832ULL,
70368744177664ULL,
140737488355328ULL,
281474976710656ULL,
562949953421312ULL,
1125899906842624ULL,
2251799813685248ULL,
4503599627370496ULL,
9007199254740992ULL,
18014398509481984ULL,
36028797018963968ULL,
72057594037927936ULL,
144115188075855872ULL,
288230376151711744ULL,
576460752303423488ULL,
1152921504606846976ULL,
2305843009213693952ULL,
4611686018427387904ULL,
9223372036854775808ULL
};
unsigned long long clrBitMask[64] = {
18446744073709551614ULL,
18446744073709551613ULL,
18446744073709551611ULL,
18446744073709551607ULL,
18446744073709551599ULL,
18446744073709551583ULL,
18446744073709551551ULL,
18446744073709551487ULL,
18446744073709551359ULL,
18446744073709551103ULL,
18446744073709550591ULL,
18446744073709549567ULL,
18446744073709547519ULL,
18446744073709543423ULL,
18446744073709535231ULL,
18446744073709518847ULL,
18446744073709486079ULL,
18446744073709420543ULL,
18446744073709289471ULL,
18446744073709027327ULL,
18446744073708503039ULL,
18446744073707454463ULL,
18446744073705357311ULL,
18446744073701163007ULL,
18446744073692774399ULL,
18446744073675997183ULL,
18446744073642442751ULL,
18446744073575333887ULL,
18446744073441116159ULL,
18446744073172680703ULL,
18446744072635809791ULL,
18446744071562067967ULL,
18446744069414584319ULL,
18446744065119617023ULL,
18446744056529682431ULL,
18446744039349813247ULL,
18446744004990074879ULL,
18446743936270598143ULL,
18446743798831644671ULL,
18446743523953737727ULL,
18446742974197923839ULL,
18446741874686296063ULL,
18446739675663040511ULL,
18446735277616529407ULL,
18446726481523507199ULL,
18446708889337462783ULL,
18446673704965373951ULL,
18446603336221196287ULL,
18446462598732840959ULL,
18446181123756130303ULL,
18445618173802708991ULL,
18444492273895866367ULL,
18442240474082181119ULL,
18437736874454810623ULL,
18428729675200069631ULL,
18410715276690587647ULL,
18374686479671623679ULL,
18302628885633695743ULL,
18158513697557839871ULL,
17870283321406128127ULL,
17293822569102704639ULL,
16140901064495857663ULL,
13835058055282163711ULL,
9223372036854775807ULL
};
/*
*
* Below 2 functions, and the constant array, are taken from:
* https://www.chessprogramming.org/Looking_for_Magics
*
* They are used to count bits in a bitmask (type `unsigned long long`),
* and to find (and return the index of) the first set bit (least significant).
*
**/
unsigned char count_1s(unsigned long long bb)
{
unsigned char r;
for(r = 0; bb; r++, bb &= bb - 1);
return r;
}
const unsigned char BitTable[64] = {
63, 30, 3, 32, 25, 41, 22, 33, 15, 50, 42, 13, 11, 53, 19, 34, 61, 29, 2,
51, 21, 43, 45, 10, 18, 47, 1, 54, 9, 57, 0, 35, 62, 31, 40, 4, 49, 5, 52,
26, 60, 6, 23, 44, 46, 27, 56, 16, 7, 39, 48, 24, 59, 14, 12, 55, 38, 28,
58, 20, 37, 17, 36, 8
};
unsigned char pop_1st_bit(unsigned long long *bb)
{
unsigned long long b = *bb ^ (*bb - 1);
unsigned int fold = (unsigned) ((b & 0xffffffff) ^ (b >> 32));
*bb &= (*bb - 1);
return BitTable[(fold * 0x783a9b23) >> 26];
}
|
jm90m/pigzbe-app | src/app/components/keyboard-avoid/index.js | <gh_stars>0
import React from 'react';
import {KeyboardAvoidingView} from 'react-native';
import isDesktop from '../../utils/is-desktop';
import isAndroid from '../../utils/is-android';
export default ({children, offset = 0, containerStyle, pad}) => {
if (isDesktop) {
return children;
}
return (
<KeyboardAvoidingView
keyboardVerticalOffset={offset}
style={{flex: 1}}
contentContainerStyle={containerStyle}
behavior={isAndroid ? null : pad ? 'padding' : 'position'}
enabled>
{children}
</KeyboardAvoidingView>
);
};
|
liujuanLT/insightface | recognition/arcface_torch/losses.py | <gh_stars>1-10
import torch
import math
class ArcFace(torch.nn.Module):
""" ArcFace (https://arxiv.org/pdf/1801.07698v1.pdf):
"""
def __init__(self, s=64.0, margin=0.5):
super(ArcFace, self).__init__()
self.scale = s
self.cos_m = math.cos(margin)
self.sin_m = math.sin(margin)
self.theta = math.cos(math.pi - margin)
self.sinmm = math.sin(math.pi - margin) * margin
self.easy_margin = False
def forward(self, logits: torch.Tensor, labels: torch.Tensor):
index = torch.where(labels != -1)[0]
target_logit = logits[index, labels[index].view(-1)]
sin_theta = torch.sqrt(1.0 - torch.pow(target_logit, 2))
cos_theta_m = target_logit * self.cos_m - sin_theta * self.sin_m # cos(target+margin)
if self.easy_margin:
final_target_logit = torch.where(
target_logit > 0, cos_theta_m, target_logit)
else:
final_target_logit = torch.where(
target_logit > self.theta, cos_theta_m, target_logit - self.sinmm)
logits[index, labels[index].view(-1)] = final_target_logit
logits = logits * self.scale
return logits
class CosFace(torch.nn.Module):
def __init__(self, s=64.0, m=0.40):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, logits: torch.Tensor, labels: torch.Tensor):
index = torch.where(labels != -1)[0]
target_logit = logits[index, labels[index].view(-1)]
final_target_logit = target_logit - self.m
logits[index, labels[index].view(-1)] = final_target_logit
logits = logits * self.s
return logits
|
mythoss/midpoint | gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationFinish.java | <reponame>mythoss/midpoint<gh_stars>0
/*
* Copyright (c) 2010-2019 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.web.page.login;
import com.evolveum.midpoint.authentication.api.util.AuthUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.prism.Objectable;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.CommonException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.authentication.api.authorization.AuthorizationAction;
import com.evolveum.midpoint.authentication.api.authorization.PageDescriptor;
import com.evolveum.midpoint.authentication.api.authorization.Url;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
//CONFIRMATION_LINK = "http://localhost:8080/midpoint/confirm/registration/";
@PageDescriptor(urls = {@Url(mountUrl = "/registration/result")}, action = {
@AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_SELF_REGISTRATION_FINISH_URL,
label = "PageSelfCredentials.auth.registration.finish.label",
description = "PageSelfCredentials.auth.registration.finish.description")})
public class PageRegistrationFinish extends PageRegistrationBase {
private static final Trace LOGGER = TraceManager.getTrace(PageRegistrationFinish.class);
private static final String DOT_CLASS = PageRegistrationFinish.class.getName() + ".";
private static final String ID_LABEL_SUCCESS = "successLabel";
private static final String ID_LABEL_ERROR = "errorLabel";
private static final String ID_LINK_LOGIN = "linkToLogin";
private static final String ID_SUCCESS_PANEL = "successPanel";
private static final String ID_ERROR_PANEL = "errorPanel";
private static final String OPERATION_ASSIGN_DEFAULT_ROLES = DOT_CLASS + "assignDefaultRoles";
private static final String OPERATION_ASSIGN_ADDITIONAL_ROLE = DOT_CLASS + "assignAdditionalRole";
private static final String OPERATION_FINISH_REGISTRATION = DOT_CLASS + "finishRegistration";
private static final String OPERATION_CHECK_CREDENTIALS = DOT_CLASS + "checkCredentials";
private static final String OPERATION_REMOVE_NONCE_AND_SET_LIFECYCLE_STATE = DOT_CLASS + "removeNonceAndSetLifecycleState";
private static final long serialVersionUID = 1L;
public PageRegistrationFinish() {
super();
init();
}
private void init() {
OperationResult result = new OperationResult(OPERATION_FINISH_REGISTRATION);
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!authentication.isAuthenticated()) {
LOGGER.error("Unauthenticated request");
String msg = createStringResource("PageSelfRegistration.unauthenticated").getString();
getSession().error(createStringResource(msg));
result.recordFatalError(msg);
initLayout(result);
throw new RestartResponseException(PageSelfRegistration.class);
}
FocusType user = ((MidPointPrincipal)authentication.getPrincipal()).getFocus();
PrismObject<UserType> administrator = getAdministratorPrivileged(result);
assignDefaultRoles(user.getOid(), administrator, result);
result.computeStatus();
if (result.getStatus() == OperationResultStatus.FATAL_ERROR) {
LOGGER.error("Failed to assign default roles, {}", result.getMessage());
} else {
NonceType nonceClone = user.getCredentials().getNonce().clone();
removeNonceAndSetLifecycleState(user.getOid(), nonceClone, administrator, result);
assignAdditionalRoleIfPresent(user.getOid(), nonceClone, administrator, result);
result.computeStatus();
}
initLayout(result);
} catch (CommonException|AuthenticationException e) {
result.computeStatus();
initLayout(result);
}
}
private void assignDefaultRoles(String userOid, PrismObject<UserType> administrator, OperationResult parentResult) throws CommonException {
List<ObjectReferenceType> rolesToAssign = getSelfRegistrationConfiguration().getDefaultRoles();
if (CollectionUtils.isEmpty(rolesToAssign)) {
return;
}
OperationResult result = parentResult.createSubresult(OPERATION_ASSIGN_DEFAULT_ROLES);
try {
PrismContext prismContext = getPrismContext();
List<AssignmentType> assignmentsToCreate = rolesToAssign.stream()
.map(ref -> ObjectTypeUtil.createAssignmentTo(ref, prismContext))
.collect(Collectors.toList());
ObjectDelta<Objectable> delta = prismContext.deltaFor(UserType.class)
.item(UserType.F_ASSIGNMENT).addRealValues(assignmentsToCreate)
.asObjectDelta(userOid);
runAsChecked(() -> {
Task task = createSimpleTask(OPERATION_ASSIGN_DEFAULT_ROLES);
WebModelServiceUtils.save(delta, result, task, PageRegistrationFinish.this);
return null;
}, administrator);
} catch (CommonException|RuntimeException e) {
result.recordFatalError(getString("PageRegistrationConfirmation.message.assignDefaultRoles.fatalError"), e);
throw e;
} finally {
result.computeStatusIfUnknown();
}
}
private void removeNonceAndSetLifecycleState(String userOid, NonceType nonce, PrismObject<UserType> administrator,
OperationResult parentResult) throws CommonException {
OperationResult result = parentResult.createSubresult(OPERATION_REMOVE_NONCE_AND_SET_LIFECYCLE_STATE);
try {
runAsChecked(() -> {
Task task = createSimpleTask(OPERATION_REMOVE_NONCE_AND_SET_LIFECYCLE_STATE);
ObjectDelta<UserType> delta = getPrismContext().deltaFactory().object()
.createModificationDeleteContainer(UserType.class, userOid,
ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_NONCE),
nonce);
delta.addModificationReplaceProperty(UserType.F_LIFECYCLE_STATE, SchemaConstants.LIFECYCLE_ACTIVE);
WebModelServiceUtils.save(delta, result, task, PageRegistrationFinish.this);
return null;
}, administrator);
} catch (CommonException|RuntimeException e) {
result.recordFatalError(getString("PageRegistrationConfirmation.message.removeNonceAndSetLifecycleState.fatalError"), e);
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't remove nonce and set lifecycle state", e);
throw e;
} finally {
result.computeStatusIfUnknown();
}
}
private void assignAdditionalRoleIfPresent(String userOid, NonceType nonceType,
PrismObject<UserType> administrator, OperationResult parentResult) throws CommonException {
if (nonceType.getName() == null) {
return;
}
OperationResult result = parentResult.createSubresult(OPERATION_ASSIGN_ADDITIONAL_ROLE);
try {
runAsChecked(() -> {
Task task = createAnonymousTask(OPERATION_ASSIGN_ADDITIONAL_ROLE);
ObjectDelta<UserType> assignRoleDelta;
AssignmentType assignment = new AssignmentType();
assignment.setTargetRef(ObjectTypeUtil.createObjectRef(nonceType.getName(), ObjectTypes.ABSTRACT_ROLE));
getPrismContext().adopt(assignment);
List<ItemDelta> userDeltas = new ArrayList<>();
userDeltas.add(getPrismContext().deltaFactory().container().createModificationAdd(UserType.F_ASSIGNMENT,
UserType.class, assignment));
assignRoleDelta = getPrismContext().deltaFactory().object().createModifyDelta(userOid, userDeltas, UserType.class
);
assignRoleDelta.setPrismContext(getPrismContext());
WebModelServiceUtils.save(assignRoleDelta, result, task, PageRegistrationFinish.this);
return null;
}, administrator);
} catch (CommonException|RuntimeException e) {
result.recordFatalError(getString("PageRegistrationConfirmation.message.assignAdditionalRoleIfPresent.fatalError"), e);
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't assign additional role", e);
throw e;
} finally {
result.computeStatusIfUnknown();
}
}
private void initLayout(final OperationResult result) {
WebMarkupContainer successPanel = new WebMarkupContainer(ID_SUCCESS_PANEL);
add(successPanel);
successPanel.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return result.getStatus() != OperationResultStatus.FATAL_ERROR;
}
@Override
public boolean isEnabled() {
return result.getStatus() != OperationResultStatus.FATAL_ERROR;
}
});
Label successMessage = new Label(ID_LABEL_SUCCESS,
createStringResource("PageRegistrationConfirmation.confirmation.successful"));
successPanel.add(successMessage);
AjaxLink<String> continueToLogin = new AjaxLink<String>(ID_LINK_LOGIN) {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
AuthUtil.clearMidpointAuthentication();
setResponsePage(PageLogin.class);
}
};
successPanel.add(continueToLogin);
WebMarkupContainer errorPanel = new WebMarkupContainer(ID_ERROR_PANEL);
add(errorPanel);
errorPanel.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isEnabled() {
return result.getStatus() == OperationResultStatus.FATAL_ERROR;
}
@Override
public boolean isVisible() {
return result.getStatus() == OperationResultStatus.FATAL_ERROR;
}
});
Label errorMessage = new Label(ID_LABEL_ERROR,
createStringResource("PageRegistrationConfirmation.confirmation.error"));
errorPanel.add(errorMessage);
}
@Override
protected void createBreadcrumb() {
// don't create breadcrumb for registration confirmation page
}
@Override
protected boolean isSideMenuVisible() {
return false;
}
}
|
ScienceOctopus/octopus-web-app | server/routes/problems.js | <reponame>ScienceOctopus/octopus-web-app
const express = require("express");
const db = require("../postgresQueries").queries;
const blobService = require("../lib/blobService");
const upload = blobService.upload;
const getUserFromSession = require("../lib/userSessions").getUserFromSession;
const broadcast = require("../lib/webSocket").broadcast;
const fs = require("fs");
function catchAsyncErrors(fn) {
return (req, res, next) => {
const routePromise = fn(req, res, next);
if (routePromise.catch) {
routePromise.catch(err => next(err));
}
};
}
const getProblemsByQuery = async (req, res) => {
const problems = await db.selectProblemsBySearch(req.query.q);
res.status(200).json(problems);
};
const getProblems = async (req, res) => {
if (req.query && req.query.q) {
await getProblemsByQuery(req, res);
return;
}
const problems = await db.selectAllProblems();
res.status(200).json(problems);
};
const getStages = async (req, res) => {
const stages = await db.selectAllStages();
res.status(200).json(stages);
};
const getProblemsAndPublications = async (req, res) => {
let problems = [];
let publications = [];
if (req.query && req.query.q) {
problems = await db.selectProblemsBySearch(req.query.q);
publications = await db.selectPublicationsBySearch(req.query.q);
} else {
problems = await db.selectAllProblems();
publications = await db.selectAllPublications();
}
res.status(200).json({ problems, publications });
};
const getProblemByID = async (req, res) => {
const problems = await db.selectProblemsByID(req.params.id);
if (!problems.length) {
console.log(`Couldn't find problem with ID: ${req.params.id}`);
return res.sendStatus(404);
}
if (problems.length > 1) {
console.error("Found multiple problems with same ID!");
return res.sendStatus(500);
}
return res.status(200).json(problems[0]);
};
const getStagesByProblem = async (req, res) => {
const problems = await db.selectProblemsByID(req.params.id);
if (!problems.length) {
console.log(`Couldn't find problem with ID: ${req.params.id}`);
return res.sendStatus(404);
}
const stages = await db.selectStagesByProblem(req.params.id);
res.status(200).json(stages);
};
const getStageByProblem = async (req, res) => {
const problems = await db.selectProblemsByID(req.params.id);
if (!problems.length) {
return res.sendStatus(404);
}
const stages = await db.selectStagesByID(req.params.stage);
if (!stages.length) {
console.log(`Couldn't find stage: ${req.params.stage}`);
return res.sendStatus(404);
}
res.status(200).json(stages[0]);
};
const getPublicationsByProblemAndStage = async (req, res) => {
const problems = await db.selectProblemsByID(req.params.id);
if (!problems.length) {
console.log(`Couldn't find problem with ID: ${req.params.id}`);
return res.sendStatus(404);
}
const stages = await db.selectStagesByID(req.params.stage);
if (!stages.length) {
return res.sendStatus(404);
}
let publications = await db.selectOriginalPublicationsByProblemAndStage(
req.params.id,
req.params.stage,
);
// TODO: refactor session cookie name into environmental waste
const sessionUser = getUserFromSession(req);
if (sessionUser) {
const additionalPublications =
(await db.selectOriginalDraftPublicationsByProblemAndStageAndUser(
req.params.id,
req.params.stage,
sessionUser,
)) || [];
publications = [...publications, ...additionalPublications];
}
res.status(200).json(publications);
};
const getPublicationsByProblem = async (req, res) => {
const problems = await db.selectProblemsByID(req.params.id);
if (!problems.length) {
console.log(`Couldn't find problem with ID: ${req.params.id}`);
return res.sendStatus(404);
}
const publications = await db.selectCompletedPublicationsByProblem(
req.params.id,
);
res
.status(200)
.append("X-Total-Count", publications.length)
.json(publications);
};
const getPublicationCountByProblem = async (req, res) => {
const count = await db.countCompletedPublicationsForProblem(req.params.id);
res
.status(200)
.append("X-Total-Count", count)
.end();
};
const postPublicationToProblemAndStage = async (req, res) => {
if (req.body.__DEBUG__) {
res.status(200).end();
return;
}
let user = getUserFromSession(req);
if (!isNumber(req.body.user) || !user || user !== Number(req.body.user)) {
console.log(`Couldn't find user with ID: ${req.body.user}`);
return res.sendStatus(400);
}
const problems = await db.selectProblemsByID(req.params.id);
if (!problems.length) {
console.log(`Couldn't find problem with ID: ${req.params.id}`);
return res.sendStatus(400);
}
const stages = await db.selectStagesByID(req.params.stage);
if (!stages.length) {
console.log(`Couldn't find stage: ${req.params.stage}`);
return res.sendStatus(400);
}
if (
req.body.review === "true" &&
(req.body.basedOn === undefined || JSON.parse(req.body.basedOn).length <= 0)
) {
console.log(`Review must have a basedOn property`);
return res.sendStatus(400);
}
let data;
let resources = [];
if (req.body.review === "true") {
data = [];
} else {
const schema = JSON.parse(stages[0].schema);
data = JSON.parse(req.body.data);
if (schema.length !== data.length) {
console.log(`Schema and data lengths do not match`);
return res.sendStatus(400);
}
for (let i = 0; i < schema.length; i++) {
let content = data[i];
let error;
switch (schema[i][1]) {
case "file":
error =
typeof content !== "number" ||
content <= 0 ||
req.files[content] === undefined;
break;
case "uri":
error = typeof content !== "string";
break;
case "text":
error = typeof content !== "string";
break;
case "bool":
error = typeof content !== "boolean";
break;
default:
error = true;
}
if (error) {
return res.sendStatus(400);
}
switch (schema[i][1]) {
case "file":
// @TODO use a generic model for file operations
content = (await db.insertResource(
req.files[0].mimeType,
req.files[0].location,
))[0];
resources.push(content);
break;
case "uri":
content = (await db.insertResource("uri", content))[0];
resources.push(content);
break;
case "text":
break;
case "bool":
break;
}
data[i] = content;
}
}
const publications = await db.insertPublication(
req.params.id,
req.params.stage,
req.body.title,
req.body.summary,
req.body.funding,
req.body.conflict,
req.body.review,
req.body.editorData,
JSON.stringify(data),
true,
req.body.dataRepository,
);
const publicationCollaborators = JSON.parse(
req.body.publicationCollaborators,
);
// check if publication has collaborators
if (publicationCollaborators && publicationCollaborators.length > 1) {
publicationCollaborators.forEach(async (collaborator, index) => {
const collaboratorId = collaborator.id ? collaborator.id : null;
const collaboratorRole = index === 0 ? "author" : "collaborator";
await db.insertPublicationCollaborator(
publications[0], // publication id
collaboratorId,
collaboratorRole,
collaborator.orcid,
);
});
} else {
// insert only the author
const authorId = req.body.user.id;
const authorOrcid = req.body.user.orcid;
await db.insertPublicationCollaborator(
publications[0], // publication id
authorId,
"author", // role
authorOrcid,
);
}
if (JSON.parse(req.body.review) && !JSON.parse(req.body.isUserPublication)) {
await db.insertPublicationRatings(
JSON.parse(req.body.basedOn)[0],
req.body.firstRating,
req.body.secondRating,
req.body.thirdRating,
req.body.user,
);
}
// let usersToNotify = [];
if (req.body.basedOn !== undefined) {
let basedArray = JSON.parse(req.body.basedOn);
await db.insertLink(publications[0], basedArray);
// usersToNotify = await db
// .selectAllCollaboratorsForListOfPublications(basedArray)
// .map(x => x.user);
// for (let i = 0; i < usersToNotify.length; i++) {
// await db.insertUserNotification(usersToNotify[i], publications[0]);
// }
}
if (req.files.length > 0) {
resources.unshift(
(await db.insertResource(
req.files[0].mimetype,
req.files[0].location,
))[0],
);
}
for (let i = 0; i < resources.length; i++) {
await db.insertPublicationResource(
publications[0],
resources[i],
i <= 0 ? "main" : "meta",
);
}
const tags = JSON.parse(req.body.tags);
for (let i = 0; i < tags.length; i++) {
await db.insertTagToPublication(publications[0], tags[i]);
}
// Problem publications changed
broadcast(`/problems/${req.params.id}/publications`);
broadcast(
`/problems/${req.params.id}/stages/${req.params.stage}/publications`,
);
// Reviews of linked publication changed
if (req.body.review === "true") {
let publication = JSON.parse(req.body.basedOn)[0];
broadcast(`/publications/${publication}/reviews`);
}
// linksAfter of linked publications have changed
if (req.body.basedOn !== undefined) {
let basedArray = JSON.parse(req.body.basedOn);
basedArray.forEach(publication =>
broadcast(`/publications/${publication}/linksAfter`),
);
}
broadcast(`/users/${user}/signoffs`);
res.status(200).json(publications[0]);
};
const postProblem = async (req, res) => {
if (req.body.__DEBUG__ === true) {
res.status(200).json(1);
return;
}
let user = getUserFromSession(req);
if (!req.body.title || !user) {
console.log(`Title or user missing in postProblem routine`);
return res.sendStatus(400);
}
// If no stages were provided, just link all of them
let stages =
req.body.stages || (await db.selectAllStagesIds().map(x => x.id));
if (!stages.length || stages.some(x => !isNumber(x))) {
console.log(`Stages not found`);
return res.sendStatus(400);
}
let problem = (await db.insertProblem(
req.body.title,
req.body.description,
req.body.user,
))[0];
for (let i = 0; i < stages.length; i++) {
await db.insertProblemStage(problem, stages[i], stages[i]);
}
broadcast("/problems");
res.status(200).json(problem);
};
const isNumber = x => Number(x) !== NaN;
const fileToText = async (req, res) => {
// ge uploaded files bucket and key
let fileOptions = [];
req.files.forEach(file => {
fileOptions.push({
s3Options: {
Bucket: file.bucket,
Key: file.key,
},
mimetype: file.mimetype,
});
});
fileOptions.forEach(fileOption => {
const aws = require("aws-sdk");
const AWS_KEY = process.env.AWS_KEY;
const AWS_SECRET = process.env.AWS_SECRET;
const AWS_REGION = process.env.AWS_REGION;
aws.config.update({
region: AWS_REGION,
accessKeyId: AWS_KEY,
secretAccessKey: AWS_SECRET,
});
const s3Instance = new aws.S3();
const filePath = `/tmp/V0-${fileOption.s3Options.Key}`;
try {
s3Instance.getObject(fileOption.s3Options, (err, data) => {
if (err) console.error(err);
// base64 encoding doesn't write corrupted .doc and .docx
// base64 encoding doesn't affect .pdf
fs.writeFileSync(filePath, Buffer.from(data.Body).toString("base64"), {
encoding: "base64",
});
if (fileOption.mimetype === "application/msword") {
}
if (fileOption.mimetype === "text/x-tex") {
}
if (
fileOption.mimetype ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
) {
// ------ works for DOCX ------
const mammoth = require("mammoth");
mammoth
.convertToHtml({ path: filePath })
.then(function(result) {
var html = result.value; // The generated HTML
res.status(200).json({ html });
})
.done();
}
// ------ works for PDF ------
if (fileOption.mimetype === "application/pdf") {
var extract = require("pdf-html-extract");
extract(filePath, function(err, html) {
if (err) {
console.dir(err);
return;
}
html.join(" ");
res.status(200).json({ html });
});
}
});
} catch (err) {
console.log("err", err);
res.status(500).send("500 Internal Server Error ");
}
});
};
var router = express.Router();
router.post(
"/file-to-text",
(req, res, next) => {
if (upload) {
return upload().array("file")(req, res, next);
}
next();
},
catchAsyncErrors(fileToText),
);
router.get("/", catchAsyncErrors(getProblems));
router.post("/", catchAsyncErrors(postProblem));
router.get("/stages", catchAsyncErrors(getStages));
router.get("/publications", catchAsyncErrors(getProblemsAndPublications));
router.get(
"/:id(\\d+)/publications",
catchAsyncErrors(getPublicationsByProblem),
);
router.head(
"/:id(\\d+)/publications",
catchAsyncErrors(getPublicationCountByProblem),
);
router.get("/:id", catchAsyncErrors(getProblemByID));
router.get("/:id(\\d+)/stages", catchAsyncErrors(getStagesByProblem));
router.get(
"/:id(\\d+)/stages/:stage(\\d+)",
catchAsyncErrors(getStageByProblem),
);
router.get(
"/:id(\\d+)/stages/:stage(\\d+)/publications",
catchAsyncErrors(getPublicationsByProblemAndStage),
);
router.post(
"/:id(\\d+)/stages/:stage(\\d+)/publications",
(req, res, next) => {
if (upload) {
return upload().array("file")(req, res, next);
}
next();
},
catchAsyncErrors(postPublicationToProblemAndStage),
);
module.exports = {
getProblems,
getProblemByID,
getStagesByProblem,
getPublicationsByProblemAndStage,
postPublicationToProblemAndStage,
router,
};
|
5Sigma/help_kit | app/controllers/help_kit/admin/categories_controller.rb | require_dependency "help_kit/application_controller"
module HelpKit
class Admin::CategoriesController < ApplicationController
layout 'help_kit/admin'
before_action :set_category, only: [:show, :edit, :update, :destroy]
before_action :check_authorization
def index
@categories = Category.roots
end
def new
@category = Category.new
end
def create
@category = Category.new(category_params)
if @category.save
redirect_to admin_categories_path
else
render 'new'
end
end
def edit; end
def update
if @category.update(category_params)
redirect_to admin_categories_path
else
render 'edit'
end
end
def destroy
@category.destroy
redirect_to admin_categories_path
end
private
def set_category
@category = Category.friendly.find(params[:id])
end
def category_params
params.require(:category).permit(:name, :parent_id, :header_content)
end
def check_authorization
unless is_authorized?
redirect_to landing_path
return false
end
end
end
end
|
AdamGlowicki/erpzgeckonetu | resources/js/components/enums/groups/groups.js | <gh_stars>0
export const GroupsType = [
{id: 0, label: 'Szafy'},
{id: 1, label: 'Słupy pod nadajniki'},
{id: 2, label: 'Słupy ENERGA'},
{id: 3, label: 'Słupy ENEA'},
{id: 4, label: 'Studnie'},
]
|
dreamsxin/ultimatepp | uppdev/Malloc/Util.cpp | #include "Malloc.h"
#define LTIMING(x)
static MemoryProfile *sPeak;
void *MemoryAllocPermanentRaw(size_t size)
{
if(size >= 256)
return malloc(size);
static byte *ptr = NULL;
static byte *limit = NULL;
if(ptr + size >= limit) {
ptr = (byte *)AllocRaw4KB();
limit = ptr + 4096;
}
void *p = ptr;
ptr += size;
return p;
}
void *MemoryAllocPermanent(size_t size)
{
#ifdef _MULTITHREADED
Mutex::Lock __(sHeapLock);
#endif
return MemoryAllocPermanentRaw(size);
}
MemoryProfile *MemGetPeak()
{
if(sPeak)
return sPeak;
sPeak = (MemoryProfile *)MemoryAllocPermanent(sizeof(MemoryProfile));
memset(sPeak, 0, sizeof(MemoryProfile));
return NULL;
}
void DoPeakProfile()
{
if(sPeak)
heap.Make(*sPeak);
}
int sKB;
void *SysAllocRaw(size_t size)
{
LTIMING("SysAllocRaw");
sKB += int(((size + 4095) & ~4095) >> 10);
#ifdef PLATFORM_WIN32
void *ptr = VirtualAlloc(NULL, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
#else
#ifdef PLATFORM_LINUX
void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#else
void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
#endif
#endif
if(!ptr)
Panic("Out of memory!");
DoPeakProfile();
return ptr;
}
void SysFreeRaw(void *ptr, size_t size)
{
LTIMING("SysFreeRaw");
// LOGF("SysFreeRaw %X - %d\n", ptr, size);
sKB -= int(((size + 4095) & ~4095) >> 10);
#ifdef PLATFORM_WIN32
VirtualFree(ptr, 0, MEM_RELEASE);
#else
munmap(ptr, size);
#endif
}
int s4kb__;
int s64kb__;
void *AllocRaw4KB()
{
static int left;
static byte *ptr;
static int n = 32;
if(left == 0) {
left = n >> 5;
ptr = (byte *)SysAllocRaw(left * 4096);
}
n = n + 1;
if(n > 4096) n = 4096;
void *p = ptr;
ptr += 4096;
left--;
s4kb__++;
DoPeakProfile();
return p;
}
void *AllocRaw64KB()
{
static int left;
static byte *ptr;
static int n = 32;
if(left == 0) {
left = n >> 5;
ptr = (byte *)SysAllocRaw(left * 65536);
}
n = n + 1;
if(n > 256) n = 256;
void *p = ptr;
ptr += 65536;
left--;
s64kb__++;
DoPeakProfile();
return p;
}
void HeapPanic(const char *text, void *pos, int size)
{
RLOG("\n\n" << text << "\n");
HexDump(VppLog(), pos, size, 64);
Panic(text);
}
#ifdef HEAPDBG
void Heap::DbgFreeFill(void *p, int size)
{
int count = size >> 2;
dword *ptr = (dword *)p;
while(count--)
*ptr++ = 0x65657246;
}
void Heap::DbgFreeCheck(void *p, int size)
{
int count = size >> 2;
dword *ptr = (dword *)p;
while(count--)
if(*ptr++ != 0x65657246)
HeapPanic("Writes to freed blocks detected", p, size);
}
void *Heap::DbgFreeCheckK(void *p, int k)
{
Page *page = (Page *)((uintptr_t)p & ~(uintptr_t)4095);
ASSERT((byte *)page + sizeof(Page) <= (byte *)p && (byte *)p < (byte *)page + 4096);
ASSERT((4096 - ((uintptr_t)p & (uintptr_t)4095)) % Ksz(k) == 0);
ASSERT(page->klass == k);
DbgFreeCheck((FreeLink *)p + 1, Ksz(k) - sizeof(FreeLink));
return p;
}
void Heap::DbgFreeFillK(void *p, int k)
{
DbgFreeFill((FreeLink *)p + 1, Ksz(k) - sizeof(FreeLink));
}
#endif
#ifdef flagHEAPSTAT
int stat[65536];
int bigstat;
void Heap::Stat(size_t sz)
{
if(sz < 65536)
stat[sz]++;
else
bigstat++;
}
EXITBLOCK {
int sum = 0;
for(int i = 0; i < 65536; i++)
sum += stat[i];
sum += bigstat;
int total = 0;
VppLog() << Sprintf("Allocation statistics: (total allocations: %d)\n", sum);
for(int i = 0; i < 65536; i++)
if(stat[i]) {
total += stat[i];
VppLog() << Sprintf("%5d %8dx %2d%%, total %8dx %2d%%\n",
i, stat[i], 100 * stat[i] / sum, total, 100 * total / sum);
}
if(bigstat) {
total += bigstat;
VppLog() << Sprintf(">64KB %8dx %2d%%, total %8dx %2d%%\n",
bigstat, 100 * bigstat / sum, total, 100 * total / sum);
}
}
#endif
|
woozhijun/cat | cat-client/src/test/java/com/dianping/cat/message/CatTestCase.java | /*
* Copyright (c) 2011-2018, <NAME>. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dianping.cat.message;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import org.junit.After;
import org.junit.Before;
import org.unidal.helper.Files;
import org.unidal.lookup.ComponentTestCase;
import com.dianping.cat.Cat;
import com.dianping.cat.configuration.client.entity.ClientConfig;
import com.dianping.cat.configuration.client.entity.Domain;
import com.dianping.cat.configuration.client.entity.Server;
public abstract class CatTestCase extends ComponentTestCase {
protected File getConfigurationFile() {
if (isCatServerAlive()) {
try {
ClientConfig config = new ClientConfig();
config.setMode("client");
config.addDomain(new Domain("cat"));
config.addServer(new Server("localhost").setPort(2280));
File file = new File("target/cat-config.xml");
Files.forIO().writeTo(file, config.toString());
return file;
} catch (IOException e) {
return null;
}
}
return null;
}
protected boolean isCatServerAlive() {
// detect if a CAT server listens on localhost:2280
try {
SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 2280));
channel.close();
return true;
} catch (Exception e) {
// ignore it
}
return false;
}
@Before
public void setup() throws Exception {
Cat.initialize(getConfigurationFile());
}
@After
public void teardown() throws Exception {
}
} |
lottie-c/spl_tests_new | src/java/cz/cuni/mff/spl/reflection/ClassNamesByPaternFilter.java | /*
* Copyright (c) 2012, <NAME>, <NAME>, <NAME>, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cz.cuni.mff.spl.reflection;
import java.util.LinkedList;
import java.util.List;
import cz.cuni.mff.spl.StringFilter;
/**
* Filter for classnames using wild cards.
*
* The filtering uses simple pattern matching.
* When the name ends with <code>.**</code>, the prefix (i.e. everything
* prior the double asterisk) is taken as a package name and all classes
* in that package (even in subpackages) are matched.
* When the name ends with <code>.*</code>, only classes in that package
* are taken (i.e. no subpackage classes).
* Otherwise, the name is treated as a fully qualified class name.
*/
public class ClassNamesByPaternFilter implements StringFilter {
/**
* Factory to create filter from list of patterns.
*
* @param patterns
* Patterns to apply.
* @return New filter.
*/
public static ClassNamesByPaternFilter createFromPatternList(String[] patterns) {
ClassNamesByPaternFilter filter = new ClassNamesByPaternFilter();
for (String p : patterns) {
filter.addPattern(p);
}
return filter;
}
private final List<ClassNamePattern> patterns;
/** Filter accepting all classes. */
public ClassNamesByPaternFilter() {
patterns = new LinkedList<>();
}
/**
* Add search pattern.
*
* @param pat
* The pattern.
*/
public void addPattern(String pat) {
patterns.add(new ClassNamePattern(pat));
}
/** The matching function (interface implementation). */
@Override
public boolean match(String s) {
for (ClassNamePattern p : patterns) {
if (p.match(s)) {
return true;
}
}
return false;
}
private enum ClassNamePatternKind {
THIS_PACKAGE,
ALL_SUBPACKAGES,
EVERYTHING,
THIS_CLASS
};
private class ClassNamePattern {
private String name;
private ClassNamePatternKind kind;
public ClassNamePattern(String s) {
if (s.endsWith(".*")) {
name = s.substring(0, s.length() - 2);
kind = ClassNamePatternKind.THIS_PACKAGE;
} else if (s.endsWith(".**")) {
name = s.substring(0, s.length() - 3);
kind = ClassNamePatternKind.ALL_SUBPACKAGES;
} else if (s.equals("*")) {
name = null;
kind = ClassNamePatternKind.EVERYTHING;
} else {
name = s;
kind = ClassNamePatternKind.THIS_CLASS;
}
}
public boolean match(String s) {
switch (kind) {
case THIS_CLASS:
return name.equals(s);
case EVERYTHING:
return true;
case THIS_PACKAGE:
if (s.startsWith(name + ".")) {
return !s.substring(name.length() + 1).contains(".");
} else {
return false;
}
case ALL_SUBPACKAGES:
return s.startsWith(name + ".");
default:
assert (false);
return false;
}
}
}
}
|
a-shiro/SoftUni-Courses | Python Basics/3. And - Or - Not/10. Invalid Number.py | number = int(input())
calculation = 100 <= number <= 200 or number == 0
if not calculation:
print("invalid")
|
TalentedEurope/te-app | src/components/Profile/common/components/Tags.js | import React from 'react';
import { Text, StyleSheet, View } from 'react-native';
import COMMON_STYLES from '../../../../styles/common';
export const SkillsTags = (props) => {
const tagStyle = [styles.tag, styles.blue];
const tagDarkStyle = [styles.tag, styles.dark];
const addedIds = [];
const skills = props.skills.filter((skill) => {
let count = 0;
for (let i = 0; i < props.skills.length; i++) {
if (skill.id === props.skills[i].id) {
count++;
}
}
skill.important = false;
if (count > 1) {
skill.important = true;
if (addedIds.indexOf(skill.id) !== -1) {
return false;
}
}
addedIds.push(skill.id);
return true;
});
const listTags = skills.map(skill => (
<Text key={skill.id} style={skill.important ? tagDarkStyle : tagStyle}>
{skill.name}
</Text>
));
return <View style={styles.tagsWrapper}>{listTags}</View>;
};
const styles = StyleSheet.create({
tagsWrapper: {
flexDirection: 'row',
flexWrap: 'wrap',
},
tag: {
padding: 5,
paddingHorizontal: 8,
fontSize: 11,
marginRight: 4,
marginBottom: 5,
},
blue: {
backgroundColor: COMMON_STYLES.BLUE,
color: 'white',
},
dark: {
backgroundColor: COMMON_STYLES.YELLOW,
color: 'white',
},
});
|
rjw57/tiw-computer | emulator/src/mame/drivers/picno.cpp | <gh_stars>1-10
// license:BSD-3-Clause
// copyright-holders:Robbbert
/******************************************************************************************************************************
Konami Picno and Picno2
Skeleton driver started on 2017-11-30, can be claimed by anyone interested.
Information provided by Team Europe.
Chips: HD6435328F10 (H8/532 CPU with inbuilt ROM), HN62334BP (27c040 ROM), Konami custom chip 054715 (rectangular 100 pins),
HM538121JP-10, M514256B-70J, OKI M6585.
Crystals: D200L2 (Y1) and D214A3 (Y2), frequencies unknown.
The hardware of the Picno 1 and Picno 2 is completely the same. The Picno 1 has an Audio-Line-Out, which the Picno 2 does not have.
Maskrom of PICNO 1: RX001-Z8-V3J
Maskrom of PICNO 2: RX001-Z8-V4J
The size of the address space and other things is controlled by the 3 mode pins. It's assumed we are in Mode 4.
Can't do anything until the internal ROM is dumped.
******************************************************************************************************************************/
#include "emu.h"
#include "cpu/h8/h83002.h"
#include "bus/generic/slot.h"
#include "bus/generic/carts.h"
//#include "sound/multipcm.h"
//#include "screen.h"
//#include "speaker.h"
class picno_state : public driver_device
{
public:
picno_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
{ }
void picno(machine_config &config);
void io_map(address_map &map);
void mem_map(address_map &map);
private:
required_device<cpu_device> m_maincpu;
};
void picno_state::mem_map(address_map &map)
{
map(0x00000, 0x07fff).rom().region("roms", 0); // 32kb internal rom
map(0x0fb80, 0x0ff7f).ram(); // internal ram
map(0x0ff80, 0x0ffff); // internal controls
map(0x10000, 0x8ffff).rom().region("roms", 0x8000); // guess
}
void picno_state::io_map(address_map &map)
{
// ADDRESS_MAP_GLOBAL_MASK(0xff)
}
static INPUT_PORTS_START( picno )
INPUT_PORTS_END
MACHINE_CONFIG_START(picno_state::picno)
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", H83002, XTAL(20'000'000)) /* TODO: correct CPU type (H8/532), crystal is a guess, divided by 2 in the cpu */
MCFG_CPU_PROGRAM_MAP(mem_map)
MCFG_CPU_IO_MAP(io_map)
//MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker") // no speaker in the unit, but there's a couple of sockets on the back
//MCFG_SOUND_ROUTE(0, "lspeaker", 1.0)
//MCFG_SOUND_ROUTE(1, "rspeaker", 1.0)
MCFG_GENERIC_CARTSLOT_ADD("cartslot", generic_linear_slot, "picno_cart")
MCFG_SOFTWARE_LIST_ADD("cart_list", "picno")
MACHINE_CONFIG_END
ROM_START( picno )
ROM_REGION(0x88000, "roms", 0)
ROM_LOAD( "hd6435328f10.u5", 0x00000, 0x08000, NO_DUMP ) // internal rom
ROM_LOAD( "rx001-z8-v3j.u2", 0x08000, 0x80000, CRC(e3c8929d) SHA1(1716f09b0a594b3782d257330282d77b6ca6fa0d) ) //HN62334BP
ROM_END
ROM_START( picno2 )
ROM_REGION(0x88000, "roms", 0)
ROM_LOAD( "hd6435328f10.u5", 0x00000, 0x08000, NO_DUMP ) // internal rom
ROM_LOAD( "rx001-z8-v4j.u2", 0x08000, 0x80000, CRC(ae89a9a5) SHA1(51ed458ffd151e19019beb23517263efce4be272) ) //HN62334BP
ROM_END
// YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS
CONS( 1993, picno, 0, 0, picno, picno, picno_state, 0, "Konami", "Picno", MACHINE_IS_SKELETON )
CONS( 1993, picno2, 0, 0, picno, picno, picno_state, 0, "Konami", "Picno 2", MACHINE_IS_SKELETON )
|
eder-matheus/programming_marathons | maratona_1/data_structure.cpp | // data structure - uri 1340
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#define ADD_ELEMENT 1
#define REMOVE_ELEMENT 2
int main() {
int cmd_count;
int cmd, param;
while (std::cin >> cmd_count) {
bool is_stack = true;
bool is_queue = true;
bool is_prior_queue = true;
std::stack<int> stack;
std::queue<int> queue;
std::priority_queue<int> priority_queue;
for (int i = 0; i < cmd_count; i++) {
std::cin >> cmd >> param;
if (cmd == ADD_ELEMENT) {
stack.push(param);
queue.push(param);
priority_queue.push(param);
} else if (cmd == REMOVE_ELEMENT) {
if (stack.top() != param) {
is_stack = false;
}
stack.pop();
if (queue.front() != param) {
is_queue = false;
}
queue.pop();
if (priority_queue.top() != param) {
is_prior_queue = false;
}
priority_queue.pop();
} else {
std::cout << "[ERROR] Invalid command\n";
exit(1);
}
}
int possible_structs = 0;
std::string data_struct;
if (is_stack) {
data_struct = "stack";
possible_structs++;
}
if (is_queue) {
data_struct = "queue";
possible_structs++;
}
if (is_prior_queue) {
data_struct = "priority queue";
possible_structs++;
}
if (possible_structs == 1) {
std::cout << data_struct << "\n";
} else if (possible_structs > 1) {
std::cout << "not sure\n";
} else {
std::cout << "impossible\n";
}
}
return 0;
}
|
biemo8/bbs-cloud | biemo-system/biemo-system-app/src/main/java/com/biemo/cloud/system/modular/sys/provider/ResourceServiceProvider.java | package com.biemo.cloud.system.modular.sys.provider;
import com.biemo.cloud.system.api.ResourceServiceApi;
import com.biemo.cloud.system.modular.sys.entity.SysApp;
import com.biemo.cloud.system.modular.sys.entity.SysResource;
import com.biemo.cloud.system.modular.sys.factory.ResourceFactory;
import com.biemo.cloud.system.modular.sys.service.SysAppService;
import com.biemo.cloud.system.modular.sys.service.SysResourceService;
import com.biemo.cloud.kernel.model.enums.StatusEnum;
import com.biemo.cloud.kernel.model.resource.ResourceDefinition;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 资源服务
*
*
* @Date 2019/12/4 21:52
*/
@RestController
public class ResourceServiceProvider implements ResourceServiceApi {
@Autowired
private SysResourceService resourceService;
@Autowired
private SysAppService appService;
/**
* 保存新增的资源
*
*
* @Date 2019/12/4 21:52
*/
@Override
public void saveResource(@RequestBody ResourceDefinition resourceDefinition) {
resourceService.saveResource(resourceDefinition);
}
/**
* 修改资源
*
*
* @Date 2019/12/4 21:52
*/
@Override
public void editResource(@RequestBody ResourceDefinition resourceDefinition) {
SysResource resource = ResourceFactory.createResource(resourceDefinition);
this.resourceService.updateById(resource);
}
/**
* 删除资源
*
*
* @Date 2019/12/4 21:52
*/
@Override
public void removeResource(@RequestParam String resourceId) {
this.resourceService.removeById(resourceId);
}
/**
* 获取应用下拉列表
*
*
* @Date 2019/12/4 21:52
*/
@Override
public List<Map<String, Object>> getAppSelect() {
QueryWrapper<SysApp> wrapper = new QueryWrapper<>();
wrapper = wrapper.select("app_name AS appName,app_code AS appCode")
.eq("status", StatusEnum.ENABLE.getCode());
return this.appService.listMaps(wrapper);
}
@Override
public List<Map<String, Object>> getResModuleSelect() {
return this.resourceService.listMaps(new QueryWrapper<SysResource>()
.select("modular_name as modularName,modular_code as modularCode")
.groupBy("modular_code"));
}
}
|
Robbbert/messui | docs/release/src/osd/winui/mui_opts.cpp | <reponame>Robbbert/messui
// For licensing and usage information, read docs/winui_license.txt
// MASTER
//****************************************************************************
/***************************************************************************
mui_opts.cpp
Stores global options and per-game options;
***************************************************************************/
// standard windows headers
#include <windows.h>
#include <windowsx.h>
// standard C headers
#include <tchar.h>
// MAME/MAMEUI headers
#include "emu.h"
#include "ui/info.h"
#include "drivenum.h"
#include "mui_opts.h"
#include <fstream> // for *_opts.h (below)
#include "game_opts.h"
#include "ui_opts.h"
#include "mui_util.h"
#include "treeview.h"
#include "splitters.h"
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
typedef std::string string;
/***************************************************************************
Internal function prototypes
***************************************************************************/
// static void LoadFolderFilter(int folder_index,int filters);
static string CusColorEncodeString(const COLORREF *value);
static void CusColorDecodeString(string ss, COLORREF *value);
static string SplitterEncodeString(const int *value);
static void SplitterDecodeString(string ss, int *value);
static string FontEncodeString(const LOGFONT *f);
static void FontDecodeString(string ss, LOGFONT *f);
static string TabFlagsEncodeString(int data);
static void TabFlagsDecodeString(string ss, int *data);
static string ColumnEncodeStringWithCount(const int *value, int count);
static void ColumnDecodeStringWithCount(string ss, int *value, int count);
/***************************************************************************
Internal defines
***************************************************************************/
#define GAMEINFO_INI_FILENAME MAMENAME "_g.ini"
/***************************************************************************
Internal structures
***************************************************************************/
/***************************************************************************
Internal variables
***************************************************************************/
static winui_ui_options settings; // mameui.ini
static winui_game_options game_opts; // game stats
// Screen shot Page tab control text
// these must match the order of the options flags in options.h
// (TAB_...)
static const char *const image_tabs_long_name[MAX_TAB_TYPES] =
{
"Artwork",
"Boss",
"Cabinet",
"Control Panel",
"Cover",
"End",
"Flyer",
"Game Over",
"How To",
"Logo",
"Marquee",
"PCB",
"Scores",
"Select",
"Snapshot",
"Title",
"Versus",
"History"
};
static const char *const image_tabs_short_name[MAX_TAB_TYPES] =
{
"artpreview",
"boss",
"cabinet",
"cpanel",
"cover",
"end",
"flyer",
"gameover",
"howto",
"logo",
"marquee",
"pcb",
"scores",
"select",
"snap",
"title",
"versus",
"history"
};
/***************************************************************************
External functions
***************************************************************************/
string GetGameName(uint32_t driver_index)
{
if (driver_index < driver_list::total())
return driver_list::driver(driver_index).name;
else
return "0";
}
void OptionsInit()
{
// set up global options
printf("OptionsInit: About to load %s\n",MUI_INI_FILENAME);fflush(stdout);
settings.load_file(MUI_INI_FILENAME); // parse MAMEUI.ini
printf("OptionsInit: About to load %s\n",GAMEINFO_INI_FILENAME);fflush(stdout);
game_opts.load_file(GAMEINFO_INI_FILENAME); // parse MAME_g.ini
printf("OptionsInit: Finished\n");fflush(stdout);
return;
}
// Restore ui settings to factory
void ResetGUI(void)
{
settings.reset_and_save(MUI_INI_FILENAME);
}
const char * GetImageTabLongName(int tab_index)
{
return image_tabs_long_name[tab_index];
}
const char * GetImageTabShortName(int tab_index)
{
return image_tabs_short_name[tab_index];
}
//============================================================
// OPTIONS WRAPPERS
//============================================================
static COLORREF options_get_color(const char *name)
{
unsigned int r = 0, g = 0, b = 0;
COLORREF value;
const string val = settings.getter(name);
if (sscanf(val.c_str(), "%u,%u,%u", &r, &g, &b) == 3)
value = RGB(r,g,b);
else
value = (COLORREF) - 1;
return value;
}
static void options_set_color(const char *name, COLORREF value)
{
char value_str[32];
if (value == (COLORREF) -1)
snprintf(value_str, std::size(value_str), "%d", (int) value);
else
snprintf(value_str, std::size(value_str), "%d,%d,%d", (((int) value) >> 0) & 0xFF, (((int) value) >> 8) & 0xFF, (((int) value) >> 16) & 0xFF);
settings.setter(name, string(value_str));
}
static COLORREF options_get_color_default(const char *name, int default_color)
{
COLORREF value = options_get_color(name);
if (value == (COLORREF) -1)
value = GetSysColor(default_color);
return value;
}
static void options_set_color_default(const char *name, COLORREF value, int default_color)
{
if (value == GetSysColor(default_color))
options_set_color(name, (COLORREF) -1);
else
options_set_color(name, value);
}
static input_seq *options_get_input_seq(const char *name)
{
/*
static input_seq seq;
string val = settings.getter(name);
input_seq_from_tokens(NULL, seq_string.c_str(), &seq); // HACK
return &seq;*/
return NULL;
}
//============================================================
// OPTIONS CALLS
//============================================================
// ***************************************************************** MAMEUI.INI settings **************************************************************************
void SetViewMode(int val)
{
settings.setter(MUIOPTION_LIST_MODE, val);
}
int GetViewMode(void)
{
return settings.int_value(MUIOPTION_LIST_MODE);
}
void SetGameCheck(BOOL game_check)
{
settings.setter(MUIOPTION_CHECK_GAME, game_check);
}
BOOL GetGameCheck(void)
{
return settings.bool_value(MUIOPTION_CHECK_GAME);
}
void SetJoyGUI(BOOL use_joygui)
{
settings.setter(MUIOPTION_JOYSTICK_IN_INTERFACE, use_joygui);
}
BOOL GetJoyGUI(void)
{
return settings.bool_value( MUIOPTION_JOYSTICK_IN_INTERFACE);
}
void SetKeyGUI(BOOL use_keygui)
{
settings.setter(MUIOPTION_KEYBOARD_IN_INTERFACE, use_keygui);
}
BOOL GetKeyGUI(void)
{
return settings.bool_value(MUIOPTION_KEYBOARD_IN_INTERFACE);
}
void SetCycleScreenshot(int cycle_screenshot)
{
settings.setter(MUIOPTION_CYCLE_SCREENSHOT, cycle_screenshot);
}
int GetCycleScreenshot(void)
{
return settings.int_value(MUIOPTION_CYCLE_SCREENSHOT);
}
void SetStretchScreenShotLarger(BOOL stretch)
{
settings.setter(MUIOPTION_STRETCH_SCREENSHOT_LARGER, stretch);
}
BOOL GetStretchScreenShotLarger(void)
{
return settings.bool_value(MUIOPTION_STRETCH_SCREENSHOT_LARGER);
}
void SetScreenshotBorderSize(int size)
{
settings.setter(MUIOPTION_SCREENSHOT_BORDER_SIZE, size);
}
int GetScreenshotBorderSize(void)
{
return settings.int_value(MUIOPTION_SCREENSHOT_BORDER_SIZE);
}
void SetScreenshotBorderColor(COLORREF uColor)
{
options_set_color_default(MUIOPTION_SCREENSHOT_BORDER_COLOR, uColor, COLOR_3DFACE);
}
COLORREF GetScreenshotBorderColor(void)
{
return options_get_color_default(MUIOPTION_SCREENSHOT_BORDER_COLOR, COLOR_3DFACE);
}
void SetFilterInherit(BOOL inherit)
{
settings.setter(MUIOPTION_INHERIT_FILTER, inherit);
}
BOOL GetFilterInherit(void)
{
return settings.bool_value( MUIOPTION_INHERIT_FILTER);
}
void SetOffsetClones(BOOL offset)
{
settings.setter(MUIOPTION_OFFSET_CLONES, offset);
}
BOOL GetOffsetClones(void)
{
return settings.bool_value( MUIOPTION_OFFSET_CLONES);
}
void SetSavedFolderID(UINT val)
{
settings.setter(MUIOPTION_DEFAULT_FOLDER_ID, (int) val);
}
UINT GetSavedFolderID(void)
{
return (UINT) settings.int_value(MUIOPTION_DEFAULT_FOLDER_ID);
}
void SetOverrideRedX(BOOL val)
{
settings.setter(MUIOPTION_OVERRIDE_REDX, val);
}
BOOL GetOverrideRedX(void)
{
return settings.bool_value(MUIOPTION_OVERRIDE_REDX);
}
static LPBITS GetShowFolderFlags(LPBITS bits)
{
SetAllBits(bits, TRUE);
string val = settings.getter(MUIOPTION_HIDE_FOLDERS);
if (val.empty())
return bits;
extern const FOLDERDATA g_folderData[];
char s[val.size()+1];
snprintf(s, val.size()+1, "%s", val.c_str());
char *token = strtok(s, ",");
int j;
while (token)
{
for (j=0; g_folderData[j].m_lpTitle; j++)
{
if (strcmp(g_folderData[j].short_name,token) == 0)
{
ClearBit(bits, g_folderData[j].m_nFolderId);
break;
}
}
token = strtok(NULL,",");
}
return bits;
}
BOOL GetShowFolder(int folder)
{
LPBITS show_folder_flags = NewBits(MAX_FOLDERS);
show_folder_flags = GetShowFolderFlags(show_folder_flags);
BOOL result = TestBit(show_folder_flags, folder);
DeleteBits(show_folder_flags);
return result;
}
void SetShowFolder(int folder, BOOL show)
{
LPBITS show_folder_flags = NewBits(MAX_FOLDERS);
int i = 0, j = 0;
int num_saved = 0;
string str;
extern const FOLDERDATA g_folderData[];
show_folder_flags = GetShowFolderFlags(show_folder_flags);
if (show)
SetBit(show_folder_flags, folder);
else
ClearBit(show_folder_flags, folder);
// we save the ones that are NOT displayed, so we can add new ones
// and upgraders will see them
for (i=0; i<MAX_FOLDERS; i++)
{
if (TestBit(show_folder_flags, i) == FALSE)
{
if (num_saved != 0)
str.append(",");
for (j=0; g_folderData[j].m_lpTitle; j++)
{
if (g_folderData[j].m_nFolderId == i)
{
str.append(g_folderData[j].short_name);
num_saved++;
break;
}
}
}
}
settings.setter(MUIOPTION_HIDE_FOLDERS, str);
DeleteBits(show_folder_flags);
}
void SetShowStatusBar(BOOL val)
{
settings.setter(MUIOPTION_SHOW_STATUS_BAR, val);
}
BOOL GetShowStatusBar(void)
{
return settings.bool_value( MUIOPTION_SHOW_STATUS_BAR);
}
void SetShowTabCtrl (BOOL val)
{
settings.setter(MUIOPTION_SHOW_TABS, val);
}
BOOL GetShowTabCtrl (void)
{
return settings.bool_value( MUIOPTION_SHOW_TABS);
}
void SetShowToolBar(BOOL val)
{
settings.setter(MUIOPTION_SHOW_TOOLBAR, val);
}
BOOL GetShowToolBar(void)
{
return settings.bool_value( MUIOPTION_SHOW_TOOLBAR);
}
void SetCurrentTab(int val)
{
settings.setter(MUIOPTION_CURRENT_TAB, val);
}
int GetCurrentTab(void)
{
return settings.int_value(MUIOPTION_CURRENT_TAB);
}
// Need int here in case no games were in the list at exit
void SetDefaultGame(int val)
{
if ((val < 0) || (val > driver_list::total()))
settings.setter(MUIOPTION_DEFAULT_GAME, "");
else
settings.setter(MUIOPTION_DEFAULT_GAME, driver_list::driver(val).name);
}
uint32_t GetDefaultGame(void)
{
string t = settings.getter(MUIOPTION_DEFAULT_GAME);
if (t.empty())
return 0;
int val = driver_list::find(t.c_str());
if (val < 0)
val = 0;
return val;
}
void SetWindowArea(const AREA *area)
{
settings.setter(MUIOPTION_WINDOW_X, area->x);
settings.setter(MUIOPTION_WINDOW_Y, area->y);
settings.setter(MUIOPTION_WINDOW_WIDTH, area->width);
settings.setter(MUIOPTION_WINDOW_HEIGHT, area->height);
}
void GetWindowArea(AREA *area)
{
area->x = settings.int_value(MUIOPTION_WINDOW_X);
area->y = settings.int_value(MUIOPTION_WINDOW_Y);
area->width = settings.int_value(MUIOPTION_WINDOW_WIDTH);
area->height = settings.int_value(MUIOPTION_WINDOW_HEIGHT);
}
void SetWindowState(UINT state)
{
settings.setter(MUIOPTION_WINDOW_STATE, (int)state);
}
UINT GetWindowState(void)
{
return settings.int_value(MUIOPTION_WINDOW_STATE);
}
void SetWindowPanes(int val)
{
settings.setter(MUIOPTION_WINDOW_PANES, val & 15);
}
UINT GetWindowPanes(void)
{
return settings.int_value(MUIOPTION_WINDOW_PANES) & 15;
}
void SetCustomColor(int iIndex, COLORREF uColor)
{
if ((iIndex < 0) || (iIndex > 15))
return;
COLORREF custom_color[16];
CusColorDecodeString(settings.getter(MUIOPTION_CUSTOM_COLOR), custom_color);
custom_color[iIndex] = uColor;
settings.setter(MUIOPTION_CUSTOM_COLOR, CusColorEncodeString(custom_color));
}
COLORREF GetCustomColor(int iIndex)
{
if ((iIndex < 0) || (iIndex > 15))
return (COLORREF)RGB(0,0,0);
COLORREF custom_color[16];
CusColorDecodeString(settings.getter(MUIOPTION_CUSTOM_COLOR), custom_color);
if (custom_color[iIndex] == (COLORREF)-1)
return (COLORREF)RGB(0,0,0);
return custom_color[iIndex];
}
void SetListFont(const LOGFONT *font)
{
settings.setter(MUIOPTION_LIST_FONT, FontEncodeString(font));
}
void GetListFont(LOGFONT *font)
{
FontDecodeString(settings.getter(MUIOPTION_LIST_FONT), font);
}
void SetListFontColor(COLORREF uColor)
{
options_set_color_default(MUIOPTION_TEXT_COLOR, uColor, COLOR_WINDOWTEXT);
}
COLORREF GetListFontColor(void)
{
return options_get_color_default(MUIOPTION_TEXT_COLOR, COLOR_WINDOWTEXT);
}
void SetListCloneColor(COLORREF uColor)
{
options_set_color_default(MUIOPTION_CLONE_COLOR, uColor, COLOR_WINDOWTEXT);
}
COLORREF GetListCloneColor(void)
{
return options_get_color_default(MUIOPTION_CLONE_COLOR, COLOR_WINDOWTEXT);
}
int GetShowTab(int tab)
{
int show_tab_flags = 0;
TabFlagsDecodeString(settings.getter(MUIOPTION_HIDE_TABS), &show_tab_flags);
return (show_tab_flags & (1 << tab)) != 0;
}
void SetShowTab(int tab,BOOL show)
{
int show_tab_flags = 0;
TabFlagsDecodeString(settings.getter(MUIOPTION_HIDE_TABS), &show_tab_flags);
if (show)
show_tab_flags |= 1 << tab;
else
show_tab_flags &= ~(1 << tab);
settings.setter(MUIOPTION_HIDE_TABS, TabFlagsEncodeString(show_tab_flags));
}
// don't delete the last one
BOOL AllowedToSetShowTab(int tab,BOOL show)
{
int show_tab_flags = 0;
if (show == TRUE)
return TRUE;
TabFlagsDecodeString(settings.getter(MUIOPTION_HIDE_TABS), &show_tab_flags);
show_tab_flags &= ~(1 << tab);
return show_tab_flags != 0;
}
int GetHistoryTab(void)
{
return settings.int_value(MUIOPTION_HISTORY_TAB);
}
void SetHistoryTab(int tab, BOOL show)
{
if (show)
settings.setter(MUIOPTION_HISTORY_TAB, tab);
else
settings.setter(MUIOPTION_HISTORY_TAB, TAB_NONE);
}
void SetColumnWidths(int width[])
{
settings.setter(MUIOPTION_COLUMN_WIDTHS, ColumnEncodeStringWithCount(width, COLUMN_MAX));
}
void GetColumnWidths(int width[])
{
ColumnDecodeStringWithCount(settings.getter(MUIOPTION_COLUMN_WIDTHS), width, COLUMN_MAX);
}
void SetSplitterPos(int splitterId, int pos)
{
int *splitter;
if (splitterId < GetSplitterCount())
{
splitter = (int *) alloca(GetSplitterCount() * sizeof(*splitter));
SplitterDecodeString(settings.getter(MUIOPTION_SPLITTERS), splitter);
splitter[splitterId] = pos;
settings.setter(MUIOPTION_SPLITTERS, SplitterEncodeString(splitter));
}
}
int GetSplitterPos(int splitterId)
{
int *splitter;
splitter = (int *) alloca(GetSplitterCount() * sizeof(*splitter));
SplitterDecodeString(settings.getter(MUIOPTION_SPLITTERS), splitter);
if (splitterId < GetSplitterCount())
return splitter[splitterId];
return -1; /* Error */
}
void SetColumnOrder(int order[])
{
settings.setter(MUIOPTION_COLUMN_ORDER, ColumnEncodeStringWithCount(order, COLUMN_MAX));
}
void GetColumnOrder(int order[])
{
ColumnDecodeStringWithCount(settings.getter(MUIOPTION_COLUMN_ORDER), order, COLUMN_MAX);
}
void SetColumnShown(int shown[])
{
settings.setter(MUIOPTION_COLUMN_SHOWN, ColumnEncodeStringWithCount(shown, COLUMN_MAX));
}
void GetColumnShown(int shown[])
{
ColumnDecodeStringWithCount(settings.getter(MUIOPTION_COLUMN_SHOWN), shown, COLUMN_MAX);
}
void SetSortColumn(int column)
{
settings.setter(MUIOPTION_SORT_COLUMN, column);
}
int GetSortColumn(void)
{
return settings.int_value(MUIOPTION_SORT_COLUMN);
}
void SetSortReverse(BOOL reverse)
{
settings.setter(MUIOPTION_SORT_REVERSED, reverse);
}
BOOL GetSortReverse(void)
{
return settings.bool_value( MUIOPTION_SORT_REVERSED);
}
const string GetBgDir (void)
{
string t = settings.getter(MUIOPTION_BACKGROUND_DIRECTORY);
if (t.empty())
return "bkground\\bkground.png";
else
return settings.getter(MUIOPTION_BACKGROUND_DIRECTORY);
}
void SetBgDir (const char* path)
{
settings.setter(MUIOPTION_BACKGROUND_DIRECTORY, path);
}
const string GetVideoDir(void)
{
string t = settings.getter(MUIOPTION_VIDEO_DIRECTORY);
if (t.empty())
return "video";
else
return settings.getter(MUIOPTION_VIDEO_DIRECTORY);
}
void SetVideoDir(const char *path)
{
settings.setter(MUIOPTION_VIDEO_DIRECTORY, path);
}
const string GetManualsDir(void)
{
string t = settings.getter(MUIOPTION_MANUALS_DIRECTORY);
if (t.empty())
return "manuals";
else
return settings.getter(MUIOPTION_MANUALS_DIRECTORY);
}
void SetManualsDir(const char *path)
{
settings.setter(MUIOPTION_MANUALS_DIRECTORY, path);
}
// ***************************************************************** MAME_g.INI settings **************************************************************************
int GetRomAuditResults(uint32_t driver_index)
{
return game_opts.rom(driver_index);
}
void SetRomAuditResults(uint32_t driver_index, int audit_results)
{
game_opts.rom(driver_index, audit_results);
}
int GetSampleAuditResults(uint32_t driver_index)
{
return game_opts.sample(driver_index);
}
void SetSampleAuditResults(uint32_t driver_index, int audit_results)
{
game_opts.sample(driver_index, audit_results);
}
static void IncrementPlayVariable(uint32_t driver_index, const char *play_variable, uint32_t increment)
{
if (strcmp(play_variable, "count") == 0)
game_opts.play_count(driver_index, game_opts.play_count(driver_index) + increment);
else
if (strcmp(play_variable, "time") == 0)
game_opts.play_time(driver_index, game_opts.play_time(driver_index) + increment);
}
void IncrementPlayCount(uint32_t driver_index)
{
IncrementPlayVariable(driver_index, "count", 1);
}
uint32_t GetPlayCount(uint32_t driver_index)
{
return game_opts.play_count(driver_index);
}
// int needed here so we can reset all games
static void ResetPlayVariable(int driver_index, const char *play_variable)
{
if (driver_index < 0)
/* all games */
for (uint32_t i = 0; i < driver_list::total(); i++)
ResetPlayVariable(i, play_variable);
else
{
if (strcmp(play_variable, "count") == 0)
game_opts.play_count(driver_index, 0);
else
if (strcmp(play_variable, "time") == 0)
game_opts.play_time(driver_index, 0);
}
}
// int needed here so we can reset all games
void ResetPlayCount(int driver_index)
{
ResetPlayVariable(driver_index, "count");
}
// int needed here so we can reset all games
void ResetPlayTime(int driver_index)
{
ResetPlayVariable(driver_index, "time");
}
uint32_t GetPlayTime(uint32_t driver_index)
{
return game_opts.play_time(driver_index);
}
void IncrementPlayTime(uint32_t driver_index, uint32_t playtime)
{
IncrementPlayVariable(driver_index, "time", playtime);
}
void GetTextPlayTime(uint32_t driver_index, char *buf)
{
if (driver_index < driver_list::total())
{
uint32_t second = GetPlayTime(driver_index);
uint32_t hour = second / 3600;
second -= 3600*hour;
uint8_t minute = second / 60; //Calc Minutes
second -= 60*minute;
if (hour == 0)
sprintf(buf, "%d:%02d", minute, second );
else
sprintf(buf, "%d:%02d:%02d", hour, minute, second );
}
}
input_seq* Get_ui_key_up(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_UP);
}
input_seq* Get_ui_key_down(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_DOWN);
}
input_seq* Get_ui_key_left(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_LEFT);
}
input_seq* Get_ui_key_right(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_RIGHT);
}
input_seq* Get_ui_key_start(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_START);
}
input_seq* Get_ui_key_pgup(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_PGUP);
}
input_seq* Get_ui_key_pgdwn(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_PGDWN);
}
input_seq* Get_ui_key_home(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_HOME);
}
input_seq* Get_ui_key_end(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_END);
}
input_seq* Get_ui_key_ss_change(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_SS_CHANGE);
}
input_seq* Get_ui_key_history_up(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_HISTORY_UP);
}
input_seq* Get_ui_key_history_down(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_HISTORY_DOWN);
}
input_seq* Get_ui_key_context_filters(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_CONTEXT_FILTERS);
}
input_seq* Get_ui_key_select_random(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_SELECT_RANDOM);
}
input_seq* Get_ui_key_game_audit(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_GAME_AUDIT);
}
input_seq* Get_ui_key_game_properties(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_GAME_PROPERTIES);
}
input_seq* Get_ui_key_help_contents(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_HELP_CONTENTS);
}
input_seq* Get_ui_key_update_gamelist(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_UPDATE_GAMELIST);
}
input_seq* Get_ui_key_view_folders(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_FOLDERS);
}
input_seq* Get_ui_key_view_fullscreen(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_FULLSCREEN);
}
input_seq* Get_ui_key_view_pagetab(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_PAGETAB);
}
input_seq* Get_ui_key_view_picture_area(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_PICTURE_AREA);
}
input_seq* Get_ui_key_view_software_area(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_SOFTWARE_AREA);
}
input_seq* Get_ui_key_view_status(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_STATUS);
}
input_seq* Get_ui_key_view_toolbars(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TOOLBARS);
}
input_seq* Get_ui_key_view_tab_cabinet(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_CABINET);
}
input_seq* Get_ui_key_view_tab_cpanel(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_CPANEL);
}
input_seq* Get_ui_key_view_tab_flyer(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_FLYER);
}
input_seq* Get_ui_key_view_tab_history(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_HISTORY);
}
input_seq* Get_ui_key_view_tab_marquee(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_MARQUEE);
}
input_seq* Get_ui_key_view_tab_screenshot(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_SCREENSHOT);
}
input_seq* Get_ui_key_view_tab_title(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_TITLE);
}
input_seq* Get_ui_key_view_tab_pcb(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_VIEW_TAB_PCB);
}
input_seq* Get_ui_key_quit(void)
{
return options_get_input_seq(MUIOPTION_UI_KEY_QUIT);
}
static int GetUIJoy(const char *option_name, int joycodeIndex)
{
int joycodes[4];
if ((joycodeIndex < 0) || (joycodeIndex > 3))
joycodeIndex = 0;
ColumnDecodeStringWithCount(settings.getter(option_name), joycodes, std::size(joycodes));
return joycodes[joycodeIndex];
}
static void SetUIJoy(const char *option_name, int joycodeIndex, int val)
{
int joycodes[4];
if ((joycodeIndex < 0) || (joycodeIndex > 3))
joycodeIndex = 0;
ColumnDecodeStringWithCount(settings.getter(option_name), joycodes, std::size(joycodes));
joycodes[joycodeIndex] = val;
settings.setter(option_name, ColumnEncodeStringWithCount(joycodes, std::size(joycodes)));
}
int GetUIJoyUp(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_UP, joycodeIndex);
}
void SetUIJoyUp(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_UP, joycodeIndex, val);
}
int GetUIJoyDown(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_DOWN, joycodeIndex);
}
void SetUIJoyDown(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_DOWN, joycodeIndex, val);
}
int GetUIJoyLeft(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_LEFT, joycodeIndex);
}
void SetUIJoyLeft(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_LEFT, joycodeIndex, val);
}
int GetUIJoyRight(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_RIGHT, joycodeIndex);
}
void SetUIJoyRight(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_RIGHT, joycodeIndex, val);
}
int GetUIJoyStart(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_START, joycodeIndex);
}
void SetUIJoyStart(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_START, joycodeIndex, val);
}
int GetUIJoyPageUp(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_PGUP, joycodeIndex);
}
void SetUIJoyPageUp(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_PGUP, joycodeIndex, val);
}
int GetUIJoyPageDown(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_PGDWN, joycodeIndex);
}
void SetUIJoyPageDown(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_PGDWN, joycodeIndex, val);
}
int GetUIJoyHome(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_HOME, joycodeIndex);
}
void SetUIJoyHome(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_HOME, joycodeIndex, val);
}
int GetUIJoyEnd(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_END, joycodeIndex);
}
void SetUIJoyEnd(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_END, joycodeIndex, val);
}
int GetUIJoySSChange(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_SS_CHANGE, joycodeIndex);
}
void SetUIJoySSChange(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_SS_CHANGE, joycodeIndex, val);
}
int GetUIJoyHistoryUp(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_HISTORY_UP, joycodeIndex);
}
void SetUIJoyHistoryUp(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_HISTORY_UP, joycodeIndex, val);
}
int GetUIJoyHistoryDown(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_HISTORY_DOWN, joycodeIndex);
}
void SetUIJoyHistoryDown(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_HISTORY_DOWN, joycodeIndex, val);
}
// exec functions start: these are unsupported
void SetUIJoyExec(int joycodeIndex, int val)
{
SetUIJoy(MUIOPTION_UI_JOY_EXEC, joycodeIndex, val);
}
int GetUIJoyExec(int joycodeIndex)
{
return GetUIJoy(MUIOPTION_UI_JOY_EXEC, joycodeIndex);
}
const string GetExecCommand(void)
{
return settings.getter(MUIOPTION_EXEC_COMMAND);
}
// not used
void SetExecCommand(char *cmd)
{
settings.setter(MUIOPTION_EXEC_COMMAND, cmd);
}
int GetExecWait(void)
{
return settings.int_value(MUIOPTION_EXEC_WAIT);
}
void SetExecWait(int wait)
{
settings.setter(MUIOPTION_EXEC_WAIT, wait);
}
// exec functions end
BOOL GetHideMouseOnStartup(void)
{
return settings.bool_value(MUIOPTION_HIDE_MOUSE);
}
void SetHideMouseOnStartup(BOOL hide)
{
settings.setter(MUIOPTION_HIDE_MOUSE, hide);
}
BOOL GetRunFullScreen(void)
{
return settings.bool_value( MUIOPTION_FULL_SCREEN);
}
void SetRunFullScreen(BOOL fullScreen)
{
settings.setter(MUIOPTION_FULL_SCREEN, fullScreen);
}
/***************************************************************************
Internal functions
***************************************************************************/
static string CusColorEncodeString(const COLORREF *value)
{
string str = std::to_string(value[0]);
for (int i = 1; i < 16; i++)
str.append(",").append(std::to_string(value[i]));
return str;
}
static void CusColorDecodeString(string ss, COLORREF *value)
{
const char *str = ss.c_str();
char *s, *p;
char tmpStr[256];
strcpy(tmpStr, str);
p = tmpStr;
for (int i = 0; p && i < 16; i++)
{
s = p;
if ((p = strchr(s,',')) != NULL && *p == ',')
{
*p = '\0';
p++;
}
value[i] = atoi(s);
}
}
static string ColumnEncodeStringWithCount(const int *value, int count)
{
string str = std::to_string(value[0]);
for (int i = 1; i < count; i++)
str.append(",").append(std::to_string(value[i]));
return str;
}
static void ColumnDecodeStringWithCount(string ss, int *value, int count)
{
const char *str = ss.c_str();
char *s, *p;
char tmpStr[256];
if (str == NULL)
return;
strcpy(tmpStr, str);
p = tmpStr;
for (int i = 0; p && i < count; i++)
{
s = p;
if ((p = strchr(s,',')) != NULL && *p == ',')
{
*p = '\0';
p++;
}
value[i] = atoi(s);
}
}
static string SplitterEncodeString(const int *value)
{
string str = std::to_string(value[0]);
for (int i = 1; i < GetSplitterCount(); i++)
str.append(",").append(std::to_string(value[i]));
return str;
}
static void SplitterDecodeString(string ss, int *value)
{
const char *str = ss.c_str();
char *s, *p;
char tmpStr[256];
strcpy(tmpStr, str);
p = tmpStr;
for (int i = 0; p && i < GetSplitterCount(); i++)
{
s = p;
if ((p = strchr(s,',')) != NULL && *p == ',')
{
*p = '\0';
p++;
}
value[i] = atoi(s);
}
}
/* Parse the given comma-delimited string into a LOGFONT structure */
static void FontDecodeString(string ss, LOGFONT *f)
{
const char* str = ss.c_str();
sscanf(str, "%li,%li,%li,%li,%li,%i,%i,%i,%i,%i,%i,%i,%i",
&f->lfHeight,
&f->lfWidth,
&f->lfEscapement,
&f->lfOrientation,
&f->lfWeight,
(int*)&f->lfItalic,
(int*)&f->lfUnderline,
(int*)&f->lfStrikeOut,
(int*)&f->lfCharSet,
(int*)&f->lfOutPrecision,
(int*)&f->lfClipPrecision,
(int*)&f->lfQuality,
(int*)&f->lfPitchAndFamily);
const char *ptr = strrchr(str, ',');
if (ptr)
{
TCHAR *t_s = ui_wstring_from_utf8(ptr + 1);
if( !t_s )
return;
_tcscpy(f->lfFaceName, t_s);
free(t_s);
}
}
/* Encode the given LOGFONT structure into a comma-delimited string */
static string FontEncodeString(const LOGFONT *f)
{
char* utf8_FaceName = ui_utf8_from_wstring(f->lfFaceName);
if( !utf8_FaceName )
return "";
char s[200];
sprintf(s, "%li,%li,%li,%li,%li,%i,%i,%i,%i,%i,%i,%i,%i,%s",
f->lfHeight,
f->lfWidth,
f->lfEscapement,
f->lfOrientation,
f->lfWeight,
f->lfItalic,
f->lfUnderline,
f->lfStrikeOut,
f->lfCharSet,
f->lfOutPrecision,
f->lfClipPrecision,
f->lfQuality,
f->lfPitchAndFamily,
utf8_FaceName);
free(utf8_FaceName);
return string(s);
}
static string TabFlagsEncodeString(int data)
{
int num_saved = 0;
string str;
// we save the ones that are NOT displayed, so we can add new ones
// and upgraders will see them
for ( int i=0; i<MAX_TAB_TYPES; i++)
{
if (((data & (1 << i)) == 0) && GetImageTabShortName(i))
{
if (num_saved > 0)
str.append(",");
str.append(GetImageTabShortName(i));
num_saved++;
}
}
return str;
}
static void TabFlagsDecodeString(string ss, int *data)
{
const char *str = ss.c_str();
int j = 0;
char s[2000];
char *token;
snprintf(s, std::size(s), "%s", str);
// simple way to set all tab bits "on"
*data = (1 << MAX_TAB_TYPES) - 1;
token = strtok(s,", \t");
while (token)
{
for (j=0; j<MAX_TAB_TYPES; j++)
{
if (!GetImageTabShortName(j) || (strcmp(GetImageTabShortName(j), token) == 0))
{
// turn off this bit
*data &= ~(1 << j);
break;
}
}
token = strtok(NULL,", \t");
}
if (*data == 0)
{
// not allowed to hide all tabs, because then why even show the area?
*data = (1 << TAB_SCREENSHOT);
}
}
// not used
#if 0
const char * GetFolderNameByID(UINT nID)
{
UINT i;
extern const FOLDERDATA g_folderData[];
extern LPEXFOLDERDATA ExtraFolderData[];
for (i = 0; i < MAX_EXTRA_FOLDERS * MAX_EXTRA_SUBFOLDERS; i++)
if( ExtraFolderData[i] )
if (ExtraFolderData[i]->m_nFolderId == nID)
return ExtraFolderData[i]->m_szTitle;
for( i = 0; i < MAX_FOLDERS; i++)
if (g_folderData[i].m_nFolderId == nID)
return g_folderData[i].m_lpTitle;
return NULL;
}
#endif
DWORD GetFolderFlags(int folder_index)
{
LPTREEFOLDER lpFolder = GetFolder(folder_index);
if (lpFolder)
return lpFolder->m_dwFlags & F_MASK;
return 0;
}
/* MSH 20080813
* Read the folder filters from MAMEui.ini. This must only
* be called AFTER the folders have all been created.
*/
void LoadFolderFlags(void)
{
LPTREEFOLDER lpFolder;
int i, numFolders = GetNumFolders();
for (i = 0; i < numFolders; i++)
{
lpFolder = GetFolder(i);
if (lpFolder)
{
char folder_name[400];
char *ptr;
// Convert spaces to underscores
strcpy(folder_name, lpFolder->m_lpTitle);
ptr = folder_name;
while (*ptr && *ptr != '\0')
{
if ((*ptr == ' ') || (*ptr == '-'))
*ptr = '_';
ptr++;
}
string option_name = string(folder_name) + "_filters";
}
}
// These are added to our UI ini
// The normal read will skip them.
// retrieve the stored values
for (i = 0; i < numFolders; i++)
{
lpFolder = GetFolder(i);
if (lpFolder)
{
char folder_name[400];
// Convert spaces to underscores
strcpy(folder_name, lpFolder->m_lpTitle);
char *ptr = folder_name;
while (*ptr && *ptr != '\0')
{
if ((*ptr == ' ') || (*ptr == '-'))
*ptr = '_';
ptr++;
}
string option_name = string(folder_name) + "_filters";
// get entry and decode it
lpFolder->m_dwFlags |= (settings.int_value(option_name.c_str()) & F_MASK);
}
}
}
// Adds our folder flags to winui_options, for saving.
static void AddFolderFlags()
{
LPTREEFOLDER lpFolder;
int num_entries = 0, numFolders = GetNumFolders();
for (int i = 0; i < numFolders; i++)
{
lpFolder = GetFolder(i);
if (lpFolder)
{
char folder_name[400];
// Convert spaces to underscores
strcpy(folder_name, lpFolder->m_lpTitle);
char *ptr = folder_name;
while (*ptr && *ptr != '\0')
{
if ((*ptr == ' ') || (*ptr == '-'))
*ptr = '_';
ptr++;
}
string option_name = string(folder_name) + "_filters";
// store entry
settings.setter(option_name.c_str(), lpFolder->m_dwFlags & F_MASK);
// increment counter
num_entries++;
}
}
}
// Save MAMEUI.ini
void mui_save_ini(void)
{
// Add the folder flag to settings.
AddFolderFlags();
settings.save_file(MUI_INI_FILENAME);
}
void SaveGameListOptions(void)
{
// Save GameInfo.ini - game options.
game_opts.save_file(GAMEINFO_INI_FILENAME);
}
const char * GetVersionString(void)
{
return emulator_info::get_build_version();
}
uint32_t GetDriverCacheLower(uint32_t driver_index)
{
return game_opts.cache_lower(driver_index);
}
uint32_t GetDriverCacheUpper(uint32_t driver_index)
{
return game_opts.cache_upper(driver_index);
}
void SetDriverCache(uint32_t driver_index, uint32_t val)
{
game_opts.cache_upper(driver_index, val);
}
BOOL RequiredDriverCache(void)
{
return game_opts.rebuild();
}
void ForceRebuild(void)
{
game_opts.force_rebuild();
}
BOOL DriverIsComputer(uint32_t driver_index)
{
uint32_t cache = game_opts.cache_lower(driver_index) & 3;
return (cache == 2) ? true : false;
}
BOOL DriverIsConsole(uint32_t driver_index)
{
uint32_t cache = game_opts.cache_lower(driver_index) & 3;
return (cache == 1) ? true : false;
}
BOOL DriverIsModified(uint32_t driver_index)
{
return BIT(game_opts.cache_lower(driver_index), 12);
}
BOOL DriverIsImperfect(uint32_t driver_index)
{
return (game_opts.cache_lower(driver_index) & 0xff0000) ? true : false; // (NO|IMPERFECT) (CONTROLS|PALETTE|SOUND|GRAPHICS)
}
// from optionsms.cpp (MESSUI)
#define LOG_SOFTWARE 1
void SetSLColumnOrder(int order[])
{
settings.setter(MESSUI_SL_COLUMN_ORDER, ColumnEncodeStringWithCount(order, SL_COLUMN_MAX));
}
void GetSLColumnOrder(int order[])
{
ColumnDecodeStringWithCount(settings.getter(MESSUI_SL_COLUMN_ORDER), order, SL_COLUMN_MAX);
}
void SetSLColumnShown(int shown[])
{
settings.setter(MESSUI_SL_COLUMN_SHOWN, ColumnEncodeStringWithCount(shown, SL_COLUMN_MAX));
}
void GetSLColumnShown(int shown[])
{
ColumnDecodeStringWithCount(settings.getter(MESSUI_SL_COLUMN_SHOWN), shown, SL_COLUMN_MAX);
}
void SetSLColumnWidths(int width[])
{
settings.setter(MESSUI_SL_COLUMN_WIDTHS, ColumnEncodeStringWithCount(width, SL_COLUMN_MAX));
}
void GetSLColumnWidths(int width[])
{
ColumnDecodeStringWithCount(settings.getter(MESSUI_SL_COLUMN_WIDTHS), width, SL_COLUMN_MAX);
}
void SetSLSortColumn(int column)
{
settings.setter(MESSUI_SL_SORT_COLUMN, column);
}
int GetSLSortColumn(void)
{
return settings.int_value(MESSUI_SL_SORT_COLUMN);
}
void SetSLSortReverse(BOOL reverse)
{
settings.setter(MESSUI_SL_SORT_REVERSED, reverse);
}
BOOL GetSLSortReverse(void)
{
return settings.bool_value(MESSUI_SL_SORT_REVERSED);
}
void SetSWColumnOrder(int order[])
{
settings.setter(MESSUI_SW_COLUMN_ORDER, ColumnEncodeStringWithCount(order, SW_COLUMN_MAX));
}
void GetSWColumnOrder(int order[])
{
ColumnDecodeStringWithCount(settings.getter(MESSUI_SW_COLUMN_ORDER), order, SW_COLUMN_MAX);
}
void SetSWColumnShown(int shown[])
{
settings.setter(MESSUI_SW_COLUMN_SHOWN, ColumnEncodeStringWithCount(shown, SW_COLUMN_MAX));
}
void GetSWColumnShown(int shown[])
{
ColumnDecodeStringWithCount(settings.getter(MESSUI_SW_COLUMN_SHOWN), shown, SW_COLUMN_MAX);
}
void SetSWColumnWidths(int width[])
{
settings.setter(MESSUI_SW_COLUMN_WIDTHS, ColumnEncodeStringWithCount(width, SW_COLUMN_MAX));
}
void GetSWColumnWidths(int width[])
{
ColumnDecodeStringWithCount(settings.getter(MESSUI_SW_COLUMN_WIDTHS), width, SW_COLUMN_MAX);
}
void SetSWSortColumn(int column)
{
settings.setter(MESSUI_SW_SORT_COLUMN, column);
}
int GetSWSortColumn(void)
{
return settings.int_value(MESSUI_SW_SORT_COLUMN);
}
void SetSWSortReverse(BOOL reverse)
{
settings.setter( MESSUI_SW_SORT_REVERSED, reverse);
}
BOOL GetSWSortReverse(void)
{
return settings.bool_value(MESSUI_SW_SORT_REVERSED);
}
void SetCurrentSoftwareTab(int val)
{
settings.setter(MESSUI_SOFTWARE_TAB, val);
}
int GetCurrentSoftwareTab(void)
{
return settings.int_value(MESSUI_SOFTWARE_TAB);
}
|
tony2u/Medusa | Medusa/Medusa/Geometry/GeometryAlgorithm.cpp | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "GeometryAlgorithm.h"
MEDUSA_BEGIN;
bool GeometryAlgorithm::IsInPolygon(const float* verticesX, const float* verticesY, uintp count, float x, float y)
{
// The function will return YES if the point x,y is inside the polygon, or
// NO if it is not. If the point is exactly on the edge of the polygon,
// then the function may return YES or NO.
//
// Note that division by zero is avoided because the division is protected
// by the "if" clause which surrounds it.
//http://alienryderflex.com/polygon/
uintp j = count - 1;
bool oddNodes = false;
for (uintp i = 0; i < count; j = i++)
{
if (((verticesY[i] < y && verticesY[j] >= y) || (verticesY[j] < y && verticesY[i] >= y)) && (verticesX[i] <= x || verticesX[j] <= x))
{
oddNodes ^= (verticesX[i] + (y - verticesY[i]) / (verticesY[j] - verticesY[i])*(verticesX[j] - verticesX[i]) < x);
}
}
return oddNodes;
}
bool GeometryAlgorithm::IsInPolygon2(const float* vertices, uintp count, float x, float y)
{
uintp j = count - 1;
bool oddNodes = false;
for (uintp i = 0; i < count; j = i++)
{
float ix = vertices[i << 1];
float jx = vertices[j << 1];
float iy = vertices[(i << 1) + 1];
float jy = vertices[(j << 1) + 1];
if (((iy < y && jy >= y) || (jy < y && iy >= y)) && (ix <= x || jx <= x))
{
oddNodes ^= (ix + (y - iy) / (jy - iy)*(jx - ix) < x);
}
}
return oddNodes;
}
bool GeometryAlgorithm::IsInPolygon3(const float* vertices, uintp count, float x, float y)
{
uintp j = count - 1;
bool oddNodes = false;
for (uintp i = 0; i < count; j = i++)
{
float ix = vertices[i * 3];
float jx = vertices[j * 3];
float iy = vertices[i * 3 + 1];
float jy = vertices[j * 3 + 1];
if (((iy < y && jy >= y) || (jy < y && iy >= y)) && (ix <= x || jx <= x))
{
oddNodes ^= (ix + (y - iy) / (jy - iy)*(jx - ix) < x);
}
}
return oddNodes;
}
void GeometryAlgorithm::PrecomputePolygonTest(const float* verticesX, const float* verticesY, float* outPrecomputedConstants, float* outPrecomputedMultiples, uintp count)
{
uintp j = count - 1;
for (uintp i = 0; i < count; j = i++)
{
if (Math::IsEqual(verticesY[j], verticesY[i]))
{
outPrecomputedConstants[i] = verticesX[i];
outPrecomputedMultiples[i] = 0;
}
else
{
outPrecomputedConstants[i] = verticesX[i] - (verticesY[i] * verticesX[j]) / (verticesY[j] - verticesY[i]) + (verticesY[i] * verticesX[i]) / (verticesY[j] - verticesY[i]);
outPrecomputedMultiples[i] = (verticesX[j] - verticesX[i]) / (verticesY[j] - verticesY[i]);
}
}
}
void GeometryAlgorithm::PrecomputePolygonTest2(const float* vertices, float* outPrecomputedConstants, float* outPrecomputedMultiples, uintp count)
{
uintp j = count - 1;
for (uintp i = 0; i < count; j = i++)
{
float ix = vertices[i << 1];
float jx = vertices[j << 1];
float iy = vertices[(i << 1) + 1];
float jy = vertices[(j << 1) + 1];
if (Math::IsEqual(jy, iy))
{
outPrecomputedConstants[i] = ix;
outPrecomputedMultiples[i] = 0;
}
else
{
outPrecomputedConstants[i] = ix - (iy * jx) / (jy - iy) + (iy * ix) / (jy - iy);
outPrecomputedMultiples[i] = (jx - ix) / (jy - iy);
}
}
}
void GeometryAlgorithm::PrecomputePolygonTest3(const float* vertices, float* outPrecomputedConstants, float* outPrecomputedMultiples, uintp count)
{
uintp j = count - 1;
for (uintp i = 0; i < count; j = i++)
{
float ix = vertices[i * 3];
float jx = vertices[j * 3];
float iy = vertices[i * 3 + 1];
float jy = vertices[j * 3 + 1];
if (Math::IsEqual(jy, iy))
{
outPrecomputedConstants[i] = ix;
outPrecomputedMultiples[i] = 0;
}
else
{
outPrecomputedConstants[i] = ix - (iy * jx) / (jy - iy) + (iy * ix) / (jy - iy);
outPrecomputedMultiples[i] = (jx - ix) / (jy - iy);
}
}
}
bool GeometryAlgorithm::IsInPolygonWithPrecompute(const float* verticesX, const float* verticesY, const float* precomputedConstants, const float* precomputedMultiples, uintp count, float x, float y)
{
uintp j = count - 1;
bool oddNodes = false;
for (uintp i = 0; i < count; j = i++)
{
if (((verticesY[i] < y && verticesY[j] >= y) || (verticesY[j] < y && verticesY[i] >= y)) && (verticesX[i] <= x || verticesX[j] <= x))
{
oddNodes ^= (y*precomputedMultiples[i] + precomputedConstants[i] < x);
}
}
return oddNodes;
}
bool GeometryAlgorithm::IsInPolygonWithPrecompute2(const float* vertices, const float* precomputedConstants, const float* precomputedMultiples, uintp count, float x, float y)
{
uintp j = count - 1;
bool oddNodes = false;
for (uintp i = 0; i < count; j = i++)
{
float ix = vertices[i << 1];
float jx = vertices[j << 1];
float iy = vertices[(i << 1) + 1];
float jy = vertices[(j << 1) + 1];
if (((iy < y && jy >= y) || (jy < y && iy >= y)) && (ix <= x || jx <= x))
{
oddNodes ^= (y*precomputedMultiples[i] + precomputedConstants[i] < x);
}
}
return oddNodes;
}
bool GeometryAlgorithm::IsInPolygonWithPrecompute3(const float* vertices, const float* precomputedConstants, const float* precomputedMultiples, uintp count, float x, float y)
{
uintp j = count - 1;
bool oddNodes = false;
for (uintp i = 0; i < count; j = i++)
{
float ix = vertices[i * 3];
float jx = vertices[j * 3];
float iy = vertices[i * 3 + 1];
float jy = vertices[j * 3 + 1];
if (((iy < y && jy >= y) || (jy < y && iy >= y)) && (ix <= x || jx <= x))
{
oddNodes ^= (y*precomputedMultiples[i] + precomputedConstants[i] < x);
}
}
return oddNodes;
}
MEDUSA_END;
|
cragkhit/elasticsearch | references/bcb_chosen_clones/selected#725999#523#550.java | <filename>references/bcb_chosen_clones/selected#725999#523#550.java
public static String getUrl(String urlString) {
int retries = 0;
String result = "";
while (true) {
try {
URL url = new URL(urlString);
BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream()));
String line = rdr.readLine();
while (line != null) {
result += line;
line = rdr.readLine();
}
return result;
} catch (IOException ex) {
if (retries == 5) {
logger.debug("Problem getting url content exhausted");
return result;
} else {
logger.debug("Problem getting url content retrying..." + urlString);
try {
Thread.sleep((int) Math.pow(2.0, retries) * 1000);
} catch (InterruptedException e) {
}
retries++;
}
}
}
}
|
yashoza19/OnlineBanking | src/main/java/com/neu/onlinebanking/dao/SavingsTransactionDao.java | package com.neu.onlinebanking.dao;
import java.util.List;
import com.neu.onlinebanking.pojo.SavingsAccount;
import com.neu.onlinebanking.pojo.SavingsTransaction;
public interface SavingsTransactionDao {
List<SavingsTransaction> findAll();
void save(SavingsTransaction savingsTransaction);
SavingsTransaction findTransaction(long ID);
}
|
csokol/finatra | thrift/src/test/scala/com/twitter/finatra/thrift/tests/EmbeddedThriftServerFeatureTest.scala | package com.twitter.finatra.thrift.tests
import com.twitter.converter.thriftscala.Converter
import com.twitter.converter.thriftscala.Converter.Uppercase
import com.twitter.finagle.{Service, SimpleFilter, TimeoutException}
import com.twitter.finatra.thrift.codegen.MethodFilters
import com.twitter.finatra.thrift.filters.{AccessLoggingFilter, ClientIdWhitelistFilter, StatsFilter}
import com.twitter.finatra.thrift.modules.ClientIdWhitelistModule
import com.twitter.finatra.thrift.thriftscala.ClientErrorCause.RequestTimeout
import com.twitter.finatra.thrift.thriftscala.ServerErrorCause.InternalServerError
import com.twitter.finatra.thrift.thriftscala.{ClientError, NoClientIdError, ServerError, UnknownClientIdError}
import com.twitter.finatra.thrift.{EmbeddedThriftServer, ThriftRequest, ThriftRouter, ThriftServer}
import com.twitter.inject.Logging
import com.twitter.inject.server.FeatureTest
import com.twitter.util.{Await, Future, NonFatal}
class EmbeddedThriftServerIntegrationTest extends FeatureTest {
override val server = new EmbeddedThriftServer(new ConverterServer)
val client123 = server.thriftClient[Converter[Future]](clientId = "client123")
"success" in {
Await.result(client123.uppercase("Hi")) should equal("HI")
}
"failure" in {
val e = assertFailedFuture[Exception] {
client123.uppercase("fail")
}
e.getMessage should include("oops")
}
"blacklist" in {
val notWhitelistClient = server.thriftClient[Converter[Future]](clientId = "not_on_whitelist")
assertFailedFuture[UnknownClientIdError] {
notWhitelistClient.uppercase("Hi")
}
}
"no client id" in {
val noClientIdClient = server.thriftClient[Converter[Future]]()
assertFailedFuture[NoClientIdError] {
noClientIdClient.uppercase("Hi")
}
}
}
class ConverterServer extends ThriftServer {
override val modules = Seq(ClientIdWhitelistModule)
override def configureThrift(router: ThriftRouter): Unit = {
router
.filter(classOf[AccessLoggingFilter])
.filter[StatsFilter]
.filter[ExceptionTranslationFilter]
.filter[ClientIdWhitelistFilter]
.add[ConverterImpl](FilteredConverter.create)
}
}
class ConverterImpl extends Converter[Future] {
override def uppercase(msg: String): Future[String] = {
if (msg == "fail")
Future.exception(new Exception("oops"))
else
Future.value(msg.toUpperCase)
}
}
object FilteredConverter {
def create(filters: MethodFilters, underlying: Converter[Future]) = {
new Converter[Future] {
def uppercase(msg: String) = filters.create(Uppercase)(Service.mk(underlying.uppercase))(msg)
}
}
}
class ExceptionTranslationFilter
extends SimpleFilter[ThriftRequest, Any]
with Logging {
override def apply(request: ThriftRequest, service: Service[ThriftRequest, Any]): Future[Any] = {
service(request).rescue {
case e: TimeoutException =>
Future.exception(
ClientError(RequestTimeout, e.getMessage))
case e: ClientError =>
Future.exception(e)
case e: UnknownClientIdError =>
Future.exception(e)
case e: NoClientIdError =>
Future.exception(e)
case NonFatal(e) =>
error("Unhandled exception", e)
Future.exception(
ServerError(InternalServerError, e.getMessage))
}
}
}
|
giux78/daf | storage_manager/app/daf/filesystem/FileFormat.scala | <reponame>giux78/daf
/*
* Copyright 2017 TEAM PER LA TRASFORMAZIONE DIGITALE
*
* 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 daf.filesystem
trait FileFormat {
def extensions: Set[String]
def compressionRatio: Double
}
trait SingleExtension { this: FileFormat =>
protected def extension: String
final lazy val extensions = Set(extension)
}
trait NoExtensions { this: FileFormat =>
final def extensions = Set.empty[String]
}
trait NoCompression { this: FileFormat =>
final lazy val compressionRatio = 1.0
} |
homw188/homw-framework | homw-modbus/src/main/java/com/homw/modbus/struct/pdu/request/ReadDiscreteInputsRequestUnit.java | <gh_stars>1-10
package com.homw.modbus.struct.pdu.request;
import com.homw.modbus.struct.ModbusFuncCode;
import com.homw.modbus.struct.pdu.ModbusProtoUnitSupport;
public class ReadDiscreteInputsRequestUnit extends ModbusProtoUnitSupport {
public ReadDiscreteInputsRequestUnit() {
super(ModbusFuncCode.READ_DISCRETE_INPUTS);
}
public ReadDiscreteInputsRequestUnit(int startAddr, int quantity) {
super(ModbusFuncCode.READ_DISCRETE_INPUTS, startAddr, quantity);
}
}
|
imetaxas/realitycheck | src/test/java/com/yanimetaxas/realitycheck/CustomReadableTestObject.java | package com.yanimetaxas.realitycheck;
import com.yanimetaxas.realitycheck.custom.AbstractCustomObject;
/**
* @author yanimetaxas
* @since 26-Feb-18
*/
public class CustomReadableTestObject extends AbstractCustomObject<CustomReadableTestObjectAssert> {
}
|
EricGrivilers/chords-db | src/db/guitar/chords/C/_D.js | <filename>src/db/guitar/chords/C/_D.js
export default {
key: 'C',
suffix: '/D',
positions: [
{
frets: 'xx0010',
fingers: '000010'
}
]
};
|
thebigcx/micro | usr/apps/ed/ed.c | #include <stdio.h>
#include <stdint.h>
static FILE* file;
static uintptr_t linenr;
void do_insert()
{
printf("insert: ");
char* insert = malloc(256);
fgets(insert, 256, stdin);
char* ptr = strchr(insert, '\n');
if (ptr) *ptr = 0;
size_t old = ftell(file);
fwrite(insert, strlen(insert), 1, file);
fseek(file, old, SEEK_SET);
}
void do_command(char* cmd)
{
if (!strcmp(cmd, "i") || !strcmp(cmd, "insert"))
{
do_insert();
}
else if (!strcmp(cmd, "q") || !strcmp(cmd, "quit"))
{
fclose(file);
exit(0);
}
else if (!strcmp(cmd, "f") || !strcmp(cmd, "file"))
{
size_t old = ftell(file);
fseek(file, 0, SEEK_END);
size_t len = ftell(file);
fseek(file, 0, SEEK_SET);
char* data = malloc(len);
fread(data, len, 1, file);
fseek(file, old, SEEK_SET);
for (size_t i = 0; i < len; i++) printf("%c", data[i]);
printf("\n");
free(data);
}
else if (!strcmp(cmd, "p") || !strcmp(cmd, "print"))
{
char* line = malloc(256);
fgets(line, 256, file);
printf("%s", line);
free(line);
}
else if (!strcmp(cmd, "n") || !strcmp(cmd, "number"))
{
printf("%d\n", linenr + 1);
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
printf("usage: ed [filename]\n");
return 0;
}
file = fopen(argv[1], "r");
linenr = 0;
fseek(file, 0, SEEK_END);
size_t len = ftell(file);
fseek(file, 0, SEEK_SET);
char* data = malloc(len);
fread(data, len, 1, file);
fclose(file);
file = fopen(argv[1], "w+");
fwrite(data, len, 1, file);
fseek(file, 0, SEEK_SET);
char* line = malloc(256);
for (;;)
{
printf("(ed) ");
fgets(line, 256, stdin);
char* ptr = strchr(line, '\n');
if (ptr) *ptr = 0;
do_command(line);
}
free(line);
fclose(file);
return 0;
}
|
Phanatic/vitess | go/vt/mysqlctl/gcsbackup/storage.go | <reponame>Phanatic/vitess
package gcsbackup
import (
"context"
"os"
"path"
"sort"
"strings"
"sync"
"cloud.google.com/go/storage"
"github.com/pkg/errors"
cloudkms "google.golang.org/api/cloudkms/v1"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"vitess.io/vitess/go/vt/mysqlctl/backupstorage"
"vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
)
const (
// AnnotationsPath is the annotations file path to read
// labels from.
annotationsPath = "ANNOTATIONS_FILE_PATH"
)
// Storage implements the backup storage.
type Storage struct {
// Bucket is the bucket name to use.
//
// If empty, all storage methods return an error.
Bucket string
// CredsPath is the GCP service account credentials.json
//
// If empty, all storage methods return an error.
CredsPath string
// KeyURI is the key is the keyring URI to use.
//
// If empty, all storage methods return an error.
KeyURI string
// Loader is a labels loader to use.
//
// By default the internal `load` is used which will load
// all necessary labels from k8s annotations.
//
// It is overriden in tests.
loader func(path string) (*labels, error)
// Client and bucket are initialized once, if initialization
// fails the error is stored and returned from all methods.
client *storage.Client
kms *kms
bucket *storage.BucketHandle
once sync.Once
err error
}
// Init initializes the storage.
func (s *Storage) init(ctx context.Context) error {
s.once.Do(func() {
if s.CredsPath == "" {
s.err = errors.New("empty credentials path")
return
}
if s.Bucket == "" {
s.err = errors.New("empty bucket name")
return
}
if s.KeyURI == "" {
s.err = errors.New("empty key uri")
return
}
c, err := storage.NewClient(ctx,
option.WithCredentialsFile(s.CredsPath),
)
if err != nil {
s.err = err
return
}
service, err := cloudkms.NewService(ctx,
option.WithCredentialsFile(s.CredsPath),
)
if err != nil {
s.err = err
}
if s.loader == nil {
s.loader = load
}
s.kms = newKMS(s.KeyURI, service)
s.client = c
s.bucket = c.Bucket(s.Bucket)
})
return s.err
}
// ListBackups lists backups in a directory.
func (s *Storage) ListBackups(ctx context.Context, dir string) ([]backupstorage.BackupHandle, error) {
if err := s.init(ctx); err != nil {
return nil, err
}
labels, err := s.labels()
if err != nil {
return nil, err
}
if labels.LastBackupID == "" {
return nil, nil
}
parts := strings.Split(dir, "/")
if len(parts) == 0 {
return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "invalid backup directory: %v", dir)
}
keyspace := parts[0]
for _, excluded := range labels.LastBackupExcludedKeyspaces {
if excluded == keyspace {
return nil, nil
}
}
iter := s.bucket.Objects(ctx, &storage.Query{
Delimiter: "/",
Prefix: path.Join(labels.LastBackupID, dir) + "/",
})
var names []string
for {
attrs, err := iter.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
return nil, vterrors.Wrap(err, "iterating over objects")
}
name := path.Base(attrs.Prefix)
names = append(names, name)
}
sort.Strings(names)
ret := make([]backupstorage.BackupHandle, 0, len(names))
for _, name := range names {
h := newHandle(s.bucket, s.kms, labels.LastBackupID, dir, name)
ret = append(ret, h.readonly())
}
return ret, nil
}
// StartBackup creates a new backup with the given name at dir.
func (s *Storage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) {
if err := s.init(ctx); err != nil {
return nil, err
}
labels, err := s.labels()
if err != nil {
return nil, err
}
if labels.BackupID == "" {
return nil, errors.New("gcsbackup: missing backup-id annotation")
}
return newHandle(s.bucket, s.kms, labels.BackupID, dir, name), nil
}
// RemoveBackup implementation.
//
// This is a no-op because singularity is in charge of removing backups.
func (s *Storage) RemoveBackup(ctx context.Context, dir, name string) error {
if err := s.init(ctx); err != nil {
return err
}
return nil
}
// Labels reads and returns labels from the annotations filepath.
func (s *Storage) labels() (*labels, error) {
return s.loader(os.Getenv(annotationsPath))
}
// Close closes the storage.
func (s *Storage) Close() error {
return nil
}
|
verenceLola/Shopping | shoppingList/apps/shoppingItems/tests/test_models.py | import freezegun
import datetime
from django.utils import timezone
def test_create_new_shopping_list(create_shopping_list):
"""
test new list created with no item, and budget of 0
"""
shopping_list = create_shopping_list
assert shopping_list.items.values_list().count() == 0
assert shopping_list.budget == 0
def test_create_new_shopping_list_correct_user(create_user, create_shopping_list): # noqa
"""
test new list has the correct user
"""
shopping_list = create_shopping_list
owner = create_user
assert shopping_list.owner == owner
@freezegun.freeze_time('2019-10-06 13:45:27.415444+03')
def test_new_shopping_list_created_with_correct_time(create_shopping_list):
"""
test new shopping list has correct created_at field
"""
shopping_list = create_shopping_list
created_at = datetime.datetime.fromtimestamp(shopping_list.created_at.timestamp()) # noqa
assert shopping_list.created_at.month == timezone.now().month
def test_printing_shopping_list_print_name(create_shopping_list):
"""
test printing shoppinglist prints its name
"""
shopping_list = create_shopping_list
assert shopping_list.__str__() == 'shopping list one'
def test_creating_shopping_item(create_shopping_item, create_user):
"""
test creating new shopping item assigns correct owner
"""
owner = create_user
shopping_item = create_shopping_item
assert shopping_item.owner == owner
def test_adding_item_to_list(create_shopping_item, create_shopping_list):
"""
test adding shopping item to shopping list
"""
shopping_list = create_shopping_list
items_before = shopping_list.items.values_list().count()
new_item = create_shopping_item
shopping_list.items.add(new_item)
items_after = shopping_list.items.values_list().count()
assert items_after > items_before
assert items_before == 0
assert items_after == 1
def test_printing_shoppping_item_returns_name(create_shopping_item):
"""
test printing shopping item prints its name
"""
item = create_shopping_item
assert item.__str__() == 'shopping item one'
|
plantuml/plantuml-mit | src/net/sourceforge/plantuml/activitydiagram3/ftile/Arrows.java | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, <NAME>
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* Licensed under The MIT License (Massachusetts Institute of Technology License)
*
* See http://opensource.org/licenses/MIT
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
* Original Author: <NAME>
*/
package net.sourceforge.plantuml.activitydiagram3.ftile;
import net.sourceforge.plantuml.Direction;
import net.sourceforge.plantuml.ugraphic.UPolygon;
public class Arrows {
final static private double delta1 = 10;
final static private double delta2 = 4;
public static UPolygon asToUp() {
final UPolygon polygon = new UPolygon("asToUp");
polygon.addPoint(-delta2, delta1);
polygon.addPoint(0, 0);
polygon.addPoint(delta2, delta1);
polygon.addPoint(0, delta1 - 4);
return polygon;
}
public static UPolygon asToDown() {
final UPolygon polygon = new UPolygon("asToDown");
polygon.addPoint(-delta2, -delta1);
polygon.addPoint(0, 0);
polygon.addPoint(delta2, -delta1);
polygon.addPoint(0, -delta1 + 4);
return polygon;
}
public static UPolygon asToRight() {
final UPolygon polygon = new UPolygon("asToRight");
polygon.addPoint(-delta1, -delta2);
polygon.addPoint(0, 0);
polygon.addPoint(-delta1, delta2);
polygon.addPoint(-delta1 + 4, 0);
return polygon;
}
public static UPolygon asToLeft() {
final UPolygon polygon = new UPolygon("asToLeft");
polygon.addPoint(delta1, -delta2);
polygon.addPoint(0, 0);
polygon.addPoint(delta1, delta2);
polygon.addPoint(delta1 - 4, 0);
return polygon;
}
public static UPolygon asTo(Direction direction) {
if (direction == Direction.UP) {
return asToUp();
}
if (direction == Direction.DOWN) {
return asToDown();
}
if (direction == Direction.LEFT) {
return asToLeft();
}
if (direction == Direction.RIGHT) {
return asToRight();
}
throw new IllegalArgumentException();
}
}
|
NTNAEEM/hotentot | examples/win32/echo-hot/stub/echo_service_impl.cc | /******************************************************************
* Generated by Hottentot CC Generator
* Date: 01-02-2016 01:45:06
* Name: echo_service_impl.cc
* Description:
* This file contains empty implementation of sample stub.
******************************************************************/
#include <naeem/hottentot/runtime/configuration.h>
#include <naeem/hottentot/runtime/logger.h>
#include <naeem/hottentot/runtime/utils.h>
#include "echo_service_impl.h"
#include "../echo_request.h"
#include "../echo_response.h"
namespace ir {
namespace ntnaeem {
namespace hottentot {
namespace examples {
namespace win32 {
namespace echo {
void
EchoServiceImpl::OnInit() {
// TODO: Called when service is initializing.
}
void
EchoServiceImpl::OnShutdown() {
// TODO: Called when service is shutting down.
}
void
EchoServiceImpl::DoEcho(::ir::ntnaeem::hottentot::examples::win32::echo::EchoRequest &req, ::ir::ntnaeem::hottentot::examples::win32::echo::EchoResponse &out) {
if (::naeem::hottentot::runtime::Configuration::Verbose()) {
::naeem::hottentot::runtime::Logger::GetOut() << "EchoServiceImpl::DoEcho() is called." << std::endl;
}
out.SetMessage("Hello Kamran!");
}
} // END OF NAMESPACE echo
} // END OF NAMESPACE win32
} // END OF NAMESPACE examples
} // END OF NAMESPACE hottentot
} // END OF NAMESPACE ntnaeem
} // END OF NAMESPACE ir |
mgawan/mhm2_staging | src/aln_depths.cpp | <reponame>mgawan/mhm2_staging
/*
HipMer v 2.0, Copyright (c) 2020, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any required
approvals from the U.S. Dept. of Energy). All rights reserved."
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
(1) Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
(2) Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
(3) Neither the name of the University of California, Lawrence Berkeley National
Laboratory, U.S. Dept. of Energy nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
You are under no obligation whatsoever to provide any bug fixes, patches, or upgrades
to the features, functionality or performance of the source code ("Enhancements") to
anyone; however, if you choose to make your Enhancements available either publicly,
or directly to Lawrence Berkeley National Laboratory, without imposing a separate
written license agreement for such Enhancements, then you hereby grant the following
license: a non-exclusive, royalty-free perpetual license to install, use, modify,
prepare derivative works, incorporate into other computer software, distribute, and
sublicense such enhancements or derivative works thereof, in binary and source code
form.
*/
#include <fcntl.h>
#include <math.h>
#include <stdarg.h>
#include <unistd.h>
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iostream>
#include <string>
#include <upcxx/upcxx.hpp>
#include "alignments.hpp"
#include "contigs.hpp"
#include "upcxx_utils/flat_aggr_store.hpp"
#include "upcxx_utils/log.hpp"
#include "upcxx_utils/ofstream.hpp"
#include "upcxx_utils/progress_bar.hpp"
#include "upcxx_utils/timers.hpp"
#include "utils.hpp"
using namespace std;
using namespace upcxx_utils;
struct CtgBaseDepths {
using base_count_t = vector<uint16_t>;
using read_group_base_count_t = vector<base_count_t>;
int64_t cid;
read_group_base_count_t read_group_base_counts;
CtgBaseDepths(int64_t cid, int num_read_groups, int clen)
: cid(cid)
, read_group_base_counts(num_read_groups) {
for (auto &base_count : read_group_base_counts) base_count.resize(clen, 0);
}
// UPCXX_SERIALIZED_FIELDS(cid, read_group_base_counts);
};
template <typename T>
struct AvgVar {
T avg, var;
AvgVar()
: avg(0)
, var(0) {}
};
class CtgsDepths {
private:
using ctgs_depths_map_t = upcxx::dist_object<HASH_TABLE<int64_t, CtgBaseDepths>>;
ctgs_depths_map_t ctgs_depths;
int edge_base_len, num_read_groups;
HASH_TABLE<int64_t, CtgBaseDepths>::iterator ctgs_depths_iter;
size_t get_target_rank(int64_t cid) { return std::hash<int64_t>{}(cid) % upcxx::rank_n(); }
public:
CtgsDepths(int edge_base_len, int num_read_groups)
: ctgs_depths({})
, edge_base_len(edge_base_len)
, num_read_groups(num_read_groups) {
assert(num_read_groups > 0);
}
int64_t get_num_ctgs() { return upcxx::reduce_one(ctgs_depths->size(), upcxx::op_fast_add, 0).wait(); }
void add_new_ctg(int64_t cid, int num_read_groups, int clen) {
upcxx::rpc(get_target_rank(cid),
[](ctgs_depths_map_t &ctgs_depths, int64_t cid, int num_read_groups, int clen) {
CtgBaseDepths newctg(cid, num_read_groups, clen);
ctgs_depths->insert({cid, std::move(newctg)});
},
ctgs_depths, cid, num_read_groups, clen)
.wait();
}
void update_ctg_aln_depth(int64_t cid, int read_group_id, int aln_start, int aln_stop, int aln_merge_start, int aln_merge_stop) {
if (aln_start >= aln_stop) return;
upcxx::rpc(get_target_rank(cid),
[](ctgs_depths_map_t &ctgs_depths, int64_t cid, int read_group_id, int aln_start, int aln_stop, int aln_merge_start,
int aln_merge_stop) {
const auto it = ctgs_depths->find(cid);
if (it == ctgs_depths->end()) DIE("could not fetch vertex ", cid, "\n");
CtgBaseDepths::read_group_base_count_t &rg_ctg = it->second.read_group_base_counts;
assert(read_group_id < rg_ctg.size());
auto &ctg_base_counts = rg_ctg[read_group_id];
//DBG_VERBOSE("cid=", cid, " counting aln_start=", aln_start, " aln_stop=", aln_stop, " read_group_id=", read_group_id,
// " contig.size()=", ctg_base_counts.size(), "\n");
assert(aln_start >= 0 && "Align start >= 0");
assert(aln_stop <= ctg_base_counts.size() && "Align stop <= contig.size()");
for (int i = aln_start; i < aln_stop; i++) {
ctg_base_counts[i]++;
}
// disabled by default -- counts are "better" if this does not happen
// instead, count *insert coverage* not *read coverage*
// insert coverage should be closer to a Poisson distribution
// this is the merged region in a merged read - will be counted double
if (aln_merge_start != -1 && aln_merge_stop != -1) {
assert(aln_merge_start >= 0 && "merge start >= 0");
assert(aln_merge_stop <= ctg_base_counts.size() && "merge_stop <= size");
for (int i = aln_merge_start; i < aln_merge_stop; i++) {
ctg_base_counts[i]++;
}
}
},
ctgs_depths, cid, read_group_id, aln_start, aln_stop, aln_merge_start, aln_merge_stop)
.wait();
}
CtgBaseDepths *get_first_local_ctg() {
ctgs_depths_iter = ctgs_depths->begin();
if (ctgs_depths_iter == ctgs_depths->end()) return nullptr;
auto ctg = &ctgs_depths_iter->second;
ctgs_depths_iter++;
return ctg;
}
CtgBaseDepths *get_next_local_ctg() {
if (ctgs_depths_iter == ctgs_depths->end()) return nullptr;
auto ctg = &ctgs_depths_iter->second;
ctgs_depths_iter++;
return ctg;
}
// return a vector of pairs of avg,var for total and each read_group
vector<AvgVar<float>> get_depth(int64_t cid) {
auto target_rank = get_target_rank(cid);
// DBG_VERBOSE("Sending rpc to ", target_rank, " for cid=", cid, "\n");
return upcxx::rpc(target_rank,
[](ctgs_depths_map_t &ctgs_depths, int64_t cid, int edge_base_len) -> vector<AvgVar<float>> {
const auto it = ctgs_depths->find(cid);
if (it == ctgs_depths->end()) DIE("could not fetch vertex ", cid, "\n");
CtgBaseDepths::read_group_base_count_t &rg_ctg = it->second.read_group_base_counts;
int num_read_groups = rg_ctg.size();
vector<AvgVar<double>> stats; // calculate in double, send in float
stats.resize(num_read_groups + 1);
auto &avg_depth = stats[num_read_groups].avg;
auto &variance = stats[num_read_groups].var;
size_t clen = rg_ctg[0].size() - 2 * edge_base_len;
if (clen <= 0) clen = 1;
for (int rg = 0; rg < num_read_groups; rg++) {
auto &ctg_base_depths = rg_ctg[rg];
for (int i = edge_base_len; i < (int)ctg_base_depths.size() - edge_base_len; i++) {
avg_depth += ctg_base_depths[i];
stats[rg].avg += ctg_base_depths[i];
}
stats[rg].avg /= clen;
}
avg_depth /= clen;
for (int rg = 0; rg < num_read_groups; rg++) {
auto &ctg_base_depths = rg_ctg[rg];
for (int i = edge_base_len; i < (int)ctg_base_depths.size() - edge_base_len; i++) {
variance += pow((double)ctg_base_depths[i] - avg_depth, 2.0);
stats[rg].var += pow((double)ctg_base_depths[i] - stats[rg].avg, 2.0);
}
stats[rg].var /= clen;
}
variance /= clen;
// if (avg_depth < 2) avg_depth = 2;
vector<AvgVar<float>> ret_vector;
ret_vector.resize(num_read_groups + 1);
for (int i = 0; i < num_read_groups + 1; i++) {
ret_vector[i].avg = stats[i].avg;
ret_vector[i].var = stats[i].var;
}
return ret_vector;
},
ctgs_depths, cid, edge_base_len)
.wait();
}
};
void compute_aln_depths(const string &fname, Contigs &ctgs, Alns &alns, int kmer_len, int min_ctg_len,
vector<string> &read_groups, bool double_count_merged_region) {
BarrierTimer timer(__FILEFUNC__);
int edge_base_len = (min_ctg_len >= 75 ? 75 : 0);
CtgsDepths ctgs_depths(edge_base_len, read_groups.size());
int num_read_groups = read_groups.size();
SLOG_VERBOSE("Processing contigs, using an edge base length of ", edge_base_len, " and a min ctg len of ", min_ctg_len, "\n");
for (auto &ctg : ctgs) {
int clen = ctg.seq.length();
if (clen < min_ctg_len) continue;
ctgs_depths.add_new_ctg(ctg.id, num_read_groups, clen);
upcxx::progress();
}
barrier();
auto unmerged_rlen = alns.calculate_unmerged_rlen();
int64_t num_bad_overlaps = 0;
int64_t num_bad_alns = 0;
auto num_ctgs = ctgs_depths.get_num_ctgs();
SLOG_VERBOSE("Computing aln depths for ", num_ctgs, " ctgs\n");
ProgressBar progbar(alns.size(), "Processing alignments");
for (auto &aln : alns) {
progbar.update();
// require at least this much overlap with the read
// what this does is drop alns that hang too much over the ends of contigs
// this gives abundances more in line with what we see in MetaBAT, although that uses 97% identity as the cutoff and we're using
// 85% here (our alns differ somewhat because of different seed lengths, etc) .
// In practice, when using aln depths for scaffolding, this tends to reduce msa without any benefits so we only use it in the
// final round, i.e. if min_ctg_len > 0
/*
if (min_ctg_len && aln.identity < 85) {
num_bad_alns++;
continue;
}
*/
// convert to coords for use here
assert(aln.is_valid());
auto cstart = aln.cstart;
auto cstop = aln.cstop;
if (aln.orient == '-') {
int tmp = cstart;
cstart = aln.clen - cstop;
cstop = aln.clen - tmp;
}
int unaligned_left = min(aln.rstart, cstart);
int unaligned_right = min(aln.rlen - aln.rstop, aln.clen - cstop);
if (unaligned_left <= KLIGN_UNALIGNED_THRES && unaligned_right <= KLIGN_UNALIGNED_THRES) {
// set to -1 if this read is not merged
int aln_cstart_merge = -1, aln_cstop_merge = -1;
// FIXME: need to somehow communicate to the update func the range of double counting for a merged read.
// This is the area > length of read pair that is in the middle of the read
if (double_count_merged_region && aln.rlen > unmerged_rlen) {
// merged read
int merge_offset = (aln.rlen - unmerged_rlen) / 2;
aln_cstart_merge = (merge_offset > aln.rstart ? merge_offset - aln.rstart : 0) + aln.cstart;
int stop_merge = aln.rlen - merge_offset;
aln_cstop_merge = aln.cstop - (stop_merge < aln.rstop ? aln.rstop - stop_merge : 0);
// the aln may not include the merged region
if (aln_cstart_merge >= aln_cstop_merge) aln_cstart_merge = -1;
}
// as per MetaBAT analysis, ignore the 75 bases at either end because they are likely to be in error
auto adjusted_start = ::max(aln.cstart, edge_base_len);
auto adjusted_stop = ::min(aln.cstop, aln.clen - 1 - edge_base_len);
//DBG_VERBOSE("Sending update for ", aln.to_string(), " st=", adjusted_start, " end=", adjusted_stop, " edge_base_len=", edge_base_len,
// "\n");
ctgs_depths.update_ctg_aln_depth(aln.cid, aln.read_group_id, adjusted_start, adjusted_stop, aln_cstart_merge,
aln_cstop_merge);
} else {
num_bad_overlaps++;
}
upcxx::progress();
}
progbar.done();
barrier();
auto all_num_alns = reduce_one(alns.size(), op_fast_add, 0).wait();
SLOG_VERBOSE("Dropped ", perc_str(reduce_one(num_bad_overlaps, op_fast_add, 0).wait(), all_num_alns), " bad overlaps and ",
perc_str(reduce_one(num_bad_alns, op_fast_add, 0).wait(), all_num_alns), " low quality alns\n");
#ifdef USE_KMER_DEPTHS
if (fname == "") SLOG_VERBOSE("Skipping contig depths calculations and output\n");
#endif
// get string to dump
shared_ptr<upcxx_utils::dist_ofstream> sh_of;
if (fname != "") sh_of = make_shared<upcxx_utils::dist_ofstream>(fname);
if (!upcxx::rank_me() && sh_of) {
*sh_of << "contigName\tcontigLen\ttotalAvgDepth";
for (auto rg_name : read_groups) {
string shortname = upcxx_utils::get_basename(rg_name);
*sh_of << "\t" << shortname << "-avg_depth\t" << shortname << "-var_depth";
}
*sh_of << "\n";
}
// FIXME: the depths need to be in the same order as the contigs in the final_assembly.fasta file. This is an inefficient
// way of ensuring that
for (auto &ctg : ctgs) {
if ((int)ctg.seq.length() < min_ctg_len) continue;
auto rg_avg_vars = ctgs_depths.get_depth(ctg.id);
if (sh_of) {
assert(fname != "");
*sh_of << "Contig" << ctg.id << "\t" << ctg.seq.length() << "\t" << rg_avg_vars[num_read_groups].avg;
for (int rg = 0; rg < num_read_groups; rg++) {
*sh_of << "\t" << rg_avg_vars[rg].avg << "\t" << rg_avg_vars[rg].var;
}
*sh_of << "\n";
}
// it seems that using aln depths improves the ctgy at the cost of an increase in msa
#ifndef USE_KMER_DEPTHS
ctg.depth = rg_avg_vars[num_read_groups].avg;
#endif
upcxx::progress();
}
barrier();
if (fname != "") {
assert(sh_of);
DBG("Prepared contig depths for '", fname, "\n");
sh_of->close(); // sync and print stats
}
}
|
Paul-Long/react-ssr-core | src/client/components/spin/index.js | import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { LOGO } from '@constants/images';
import './style.less';
class Spin extends React.PureComponent {
static propTypes = {
prefixCls: PropTypes.string,
};
static defaultProps = {
prefixCls: 'ssr-spin',
};
render() {
const {prefixCls} = this.props;
return (
<div className={prefixCls}>
<img src={LOGO} className='rubberBand' />
</div>
);
}
}
export default Spin; |
phatblat/macOSPrivateFrameworks | PrivateFrameworks/SearchFoundation/_SFPBText.h | <filename>PrivateFrameworks/SearchFoundation/_SFPBText.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "PBCodable.h"
#import "NSSecureCoding.h"
#import "_SFPBText.h"
@class NSData, NSString;
@interface _SFPBText : PBCodable <_SFPBText, NSSecureCoding>
{
unsigned int _maxLines;
NSString *_text;
}
@property(nonatomic) unsigned int maxLines; // @synthesize maxLines=_maxLines;
@property(copy) NSString *text; // @synthesize text=_text;
- (void).cxx_destruct;
- (id)initWithDictionary:(id)arg1;
- (id)initWithJSON:(id)arg1;
@property(readonly, nonatomic) NSData *jsonData;
- (id)dictionaryRepresentation;
@property(readonly) unsigned long long hash;
- (BOOL)isEqual:(id)arg1;
- (void)writeTo:(id)arg1;
- (BOOL)readFrom:(id)arg1;
- (id)initWithFacade:(id)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) Class superclass;
@end
|
layman-809/gmall | gmall-auth/src/main/java/com/atguigu/gmall/auth/feign/GmallUmsClient.java | package com.atguigu.gmall.auth.feign;
import com.atguigu.gmall.auth.entity.UserEntity;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.ums.api.GmallUmsApi;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("ums-service")
public interface GmallUmsClient extends GmallUmsApi {
}
|
yasserattar/lorawan-stack | pkg/webui/components/wizard/form/next-button.js | <gh_stars>100-1000
// Copyright © 2020 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React from 'react'
import { defineMessages } from 'react-intl'
import Button from '@ttn-lw/components/button'
import { useFormContext } from '@ttn-lw/components/form'
import { useWizardContext } from '@ttn-lw/components/wizard'
import Message from '@ttn-lw/lib/components/message'
import PropTypes from '@ttn-lw/lib/prop-types'
import style from './form.styl'
const m = defineMessages({
next: 'Next',
complete: 'Complete',
})
const WizardNextButton = props => {
const { isLastStep, completeMessage, validationContext, validationSchema } = props
const { currentStepId, steps, onStepComplete } = useWizardContext()
const { disabled, isSubmitting, isValidating, values } = useFormContext()
const stepIndex = steps.findIndex(({ id }) => id === currentStepId)
const { title: nextStepTitle } = steps[Math.min(stepIndex + 1, steps.length - 1)] || {
title: m.next,
}
const nextMessage = isLastStep
? Boolean(completeMessage)
? completeMessage
: m.complete
: nextStepTitle
const handleClick = React.useCallback(() => {
onStepComplete(validationSchema.cast(values, { context: validationContext }))
}, [onStepComplete, validationContext, validationSchema, values])
return (
<Button
className={style.button}
type="submit"
primary
onClick={handleClick}
disabled={disabled}
busy={isSubmitting || isValidating}
>
<Message content={nextMessage} />
<Button.Icon icon={isLastStep ? '' : 'keyboard_arrow_right'} type="right" />
</Button>
)
}
WizardNextButton.propTypes = {
completeMessage: PropTypes.message,
isLastStep: PropTypes.bool.isRequired,
validationContext: PropTypes.shape({}).isRequired,
validationSchema: PropTypes.shape({
cast: PropTypes.func.isRequired,
}).isRequired,
}
WizardNextButton.defaultProps = {
completeMessage: undefined,
}
export default WizardNextButton
|
YorickPeterse/zen-cms | spec/zen/package/dashboard/controller/dashboard.rb | <reponame>YorickPeterse/zen-cms
require File.expand_path('../../../../../helper', __FILE__)
require File.join(Zen::FIXTURES, 'package/dashboard/widget')
##
# The specifications in this block run using Selenium so make sure you have
# Selenium and Firefox installed.
#
# Various specifications in this file contain calls to sleep(N). These calls are
# used because Mootools' Fx.Slide class has a certain lag time that prevents
# people from rapidly clicking the "Options" button.
#
describe 'Dashboard::Controller::Dashboard' do
dashboard_url = Dashboard::Controller::Dashboard.r(:index).to_s
behaves_like :capybara
enable_javascript
before do
Dashboard::Model::Widget.filter(~{:name => 'welcome'}).destroy
unless current_path =~ /#{dashboard_url}/
Users::Model::User[:email => '<EMAIL>'] \
.update(:widget_columns => 1)
visit(dashboard_url)
end
end
it 'Users should see the Welcome widget by default' do
page.has_selector?('#widget_welcome').should == true
page.has_content?(lang('dashboard.widgets.titles.welcome')).should == true
page.has_content?(
lang('dashboard.widgets.welcome.content.paragraph_1').split("\n")[0] \
% Zen::VERSION
).should == true
end
it 'Users should be able to toggle the widget options menu' do
script = "$('widget_options').getStyle('margin-top').toInt();"
page.evaluate_script(script).to_i.should == 0
# Show and hide the options container.
click_button('toggle_options')
sleep(1)
click_button('toggle_options')
sleep(1)
page.evaluate_script(script).to_i.should < 0
end
it 'Users should be able to change the amount of widget columns' do
script = "$('widget_welcome').getSize().x;"
click_button('toggle_options')
choose('widget_columns_1')
old_width = page.evaluate_script(script).to_i
# Switch to a 2 column based layout.
choose('widget_columns_2')
page.evaluate_script(script).to_i.should <= old_width / 2
Users::Model::User[:email => '<EMAIL>'].widget_columns.should == 2
# Switch to a 3 column based layout.
choose('widget_columns_3')
page.evaluate_script(script).to_i.should <= old_width / 3
Users::Model::User[:email => '<EMAIL>'].widget_columns.should == 3
# 4 column layout
choose('widget_columns_4')
page.evaluate_script(script).to_i.should <= old_width / 4
Users::Model::User[:email => '<EMAIL>'].widget_columns.should == 4
end
it 'Users should be able to toggle the active widgets' do
# When $() returns an existing element the type (as returned by typeOf()) is
# "element". If the element doesn't exist the type is "null".
script = "typeOf($('widget_welcome'));"
user = Users::Model::User[:email => '<EMAIL>']
page.evaluate_script(script).should == 'element'
Dashboard::Model::Widget[:name => 'welcome', :user_id => user.id].nil? \
.should == false
uncheck('toggle_widget_welcome')
page.evaluate_script(script).should == 'null'
Dashboard::Model::Widget[:name => 'welcome', :user_id => user.id].nil? \
.should == true
check('toggle_widget_welcome')
page.evaluate_script(script).should == 'element'
Dashboard::Model::Widget[:name => 'welcome', :user_id => user.id].nil? \
.should == false
end
it 'Users should be able to re-arrange widgets' do
script = "$$('.widget:first-child')[0].get('id');"
user = Users::Model::User[:email => '<EMAIL>']
click_button('toggle_options')
check('toggle_widget_spec')
# Check if the standard order and amount of widgets is correct.
page.evaluate_script(script).should == 'widget_welcome'
page.evaluate_script("$$('.widget').length;").to_i.should == 2
# Drag the second widget to the place of the first one.
page.find('#widget_spec header').drag_to(page.find('#widget_welcome header'))
sleep(1)
page.evaluate_script(script).should == 'widget_spec'
Dashboard::Model::Widget[:name => 'spec', :user_id => user.id] \
.order.should == 0
Dashboard::Model::Widget[:name => 'welcome', :user_id => user.id] \
.order.should == 1
# Put the widget order back in place.
page.find('#widget_welcome header').drag_to(page.find('#widget_spec header'))
sleep(1)
Dashboard::Model::Widget[:name => 'spec', :user_id => user.id] \
.order.should == 1
Dashboard::Model::Widget[:name => 'welcome', :user_id => user.id] \
.order.should == 0
end
Dashboard::Model::Widget.filter(:name => 'spec').destroy
disable_javascript
end
|
PrakharPipersania/LeetCode-Solutions | Questions Level-Wise/Medium/pancake-sorting.cpp | <gh_stars>1-10
class Solution {
public:
vector<int> pancakeSort(vector<int>& A)
{
int n,index;
vector<int> x;
for(n=A.size();n>0;n--)
{
index=0;
for(int i=0;A[i]!=n;i++)
index=i+1;
index++;
if(index!=n)
{
if(index>1)
reverse(A.begin(),A.begin()+index),x.push_back(index);
reverse(A.begin(),A.begin()+n),x.push_back(n);
}
}
return x;
}
};
|
sjbose/codegnera | src/styles/sizes.element.js | export const size = {
mobileS: '320px',
mobileM: '375px',
mobileL: '425px',
tablet: '768px',
laptop: '1024px',
laptopL: '1440px',
desktop: '2560px'
} |
trisquareeu/bytemapper | src/main/java/eu/trisquare/bytemapper/fieldmapper/SingleValueFieldMapper.java | <gh_stars>1-10
package eu.trisquare.bytemapper.fieldmapper;
import org.apache.commons.lang3.ClassUtils;
import java.nio.ByteBuffer;
/**
* Default mapper for all single-value data types, i.e. numbers
*/
class SingleValueFieldMapper implements FieldMapper {
/**
* Holds maximum allowed size of processed data type, i.e. 8 bytes for long
*/
protected final int maximumSupportedSize;
/**
* Holds returned data type.
*/
private final Class<?> returnedType;
/**
* Mapper implementation
*/
private final ByteBufferMapper endiannessAwareMapper;
/**
* Creates SingleValueFieldMapper for given arguments
*/
SingleValueFieldMapper(
ByteBufferMapper endiannessAwareMapper,
int maxSupportedSize,
Class<?> returnedType
) {
this.maximumSupportedSize = maxSupportedSize;
this.returnedType = returnedType;
this.endiannessAwareMapper = endiannessAwareMapper;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEligible(Class<?> type) {
return ClassUtils.isAssignable(returnedType, type);
}
/**
* {@inheritDoc}
*/
@Override
public Object getValue(ByteBuffer buffer, boolean isBigEndian, int startByte, int size) {
checkSize(size);
return this.map(buffer, isBigEndian, startByte, size);
}
/**
* Checks if given amount of bytes is valid for mapped data type
*
* @param requestedSize is amount of bytes to map into value
*/
protected void checkSize(int requestedSize) {
if (requestedSize > maximumSupportedSize) {
final String message = String.format(
"For type %s maximum allowed size is %d, but requested parsing of %d bytes. Would you like to use different data type?",
returnedType.getSimpleName(),
maximumSupportedSize,
requestedSize
);
throw new FieldMappingException(message);
}
}
/**
* Converts selected part of ByteBuffer into specific Object instance
*
* @param buffer used as a data source
* @param isBigEndian which is true for big-endian values and false otherwise
* @param startByte is zero-inclusive index of value's first byte
* @param size determines index of value's last byte
* @return mapped value
*/
public Object map(ByteBuffer buffer, boolean isBigEndian, int startByte, int size) {
return endiannessAwareMapper.map(buffer, isBigEndian, startByte, size);
}
/**
* Interface for mappers performing conversion from provided ByteBuffer's data range to specific Object instance
*/
@FunctionalInterface
interface ByteBufferMapper {
/**
* Converts selected ByteBuffer's data range to actual Object instance
*/
Object map(ByteBuffer chunk, boolean isBigEndian, int startByte, int size);
}
}
|
LaudateCorpus1/trufflex86 | projects/org.graalvm.vm.util/src/org/graalvm/vm/util/log/Trace.java | /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.graalvm.vm.util.log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import org.graalvm.vm.util.exception.BaseException;
import org.graalvm.vm.util.exception.ExceptionId;
public class Trace {
public static final boolean debug;
public static final PrintStream stdout;
public static final PrintStream stderr;
public static final PrintStream log;
private static WrappedOutputStream logout;
private static boolean initialized = false;
static {
String type = System.getProperty("log.type");
if (type != null) {
if (type.equals("debug")) {
debug = true;
} else {
debug = false;
}
setup();
} else {
debug = false;
}
String logPath = System.getProperty("log.path");
if (logPath == null) {
logout = new WrappedOutputStream(System.out);
} else {
logout = new WrappedOutputStream(getOutputStream(logPath));
}
log = new PrintStream(logout);
stdout = System.out;
stderr = System.err;
}
private static class WrappedOutputStream extends OutputStream {
private OutputStream out;
public WrappedOutputStream(OutputStream parent) {
this.out = parent;
}
public void setOutputStream(OutputStream out) {
this.out = out;
}
public OutputStream getOutputStream() {
return out;
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
}
private static OutputStream getOutputStream(String path) {
try {
return new FileOutputStream(path);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private Trace() {
}
public static void setup() {
if (initialized) {
return;
}
Logger globalLogger = Logger.getLogger(""); // root logger
if (debug) {
globalLogger.setLevel(Levels.DEBUG);
}
Handler[] handlers = globalLogger.getHandlers();
for (Handler handler : handlers) {
globalLogger.removeHandler(handler);
}
System.setOut(new LoggingStream(Levels.STDOUT));
System.setErr(new LoggingStream(Levels.STDERR, stderr));
StreamHandler handler = new StreamHandler(log, new LogFormatter()) {
@Override
public synchronized void publish(LogRecord record) {
super.publish(record);
super.flush();
}
};
if (debug) {
handler.setLevel(Levels.DEBUG);
}
globalLogger.addHandler(handler);
initialized = true;
}
public static void setupConsoleApplication() {
setupConsoleApplication(Levels.WARNING);
}
public static void setupConsoleApplication(Level level) {
OutputStream out = logout.getOutputStream();
setupConsoleApplication(level, out == System.out ? System.err : out);
}
public static void setupConsoleApplication(Level level, OutputStream out) {
if (initialized) {
return;
}
if (out == logout) {
throw new IllegalArgumentException("cannot log to this stream");
}
logout.setOutputStream(out);
Logger globalLogger = Logger.getLogger(""); // root logger
globalLogger.setLevel(level);
Handler[] handlers = globalLogger.getHandlers();
for (Handler handler : handlers) {
globalLogger.removeHandler(handler);
}
StreamHandler handler = new StreamHandler(out, new LogFormatter()) {
@Override
public synchronized void publish(LogRecord record) {
super.publish(record);
super.flush();
}
};
handler.setLevel(level);
globalLogger.addHandler(handler);
initialized = true;
}
public static void print(String s) {
log.print(s);
}
public static void println(String s) {
log.println(s);
}
public static void printf(String fmt, Object... args) {
log.printf(fmt, args);
}
public static Logger create(Class<?> tracedClass) {
return Logger.getLogger(tracedClass.getCanonicalName());
}
public static Logger create(String name) {
return Logger.getLogger(name);
}
public static String getLoggable(Throwable t) {
if (t == null) {
return BaseException.DEFAULT_ID.format();
} else if (t instanceof BaseException) {
BaseException e = (BaseException) t;
return e.format();
} else {
return BaseException.DEFAULT_ID.format(t);
}
}
public static String getLoggable(Throwable t, ExceptionId id, Object... args) {
if (t == null) {
return id.format(args);
} else if (t instanceof BaseException) {
BaseException e = (BaseException) t;
Object[] params = Arrays.copyOf(args, args.length + 1);
params[args.length] = e.formatEmbeddable();
return id.format(params);
} else {
Object[] params = Arrays.copyOf(args, args.length + 1);
params[args.length] = t.getMessage();
return id.format(params);
}
}
}
|
Excellent1212/React-Next-Hook-Sample | queries/index.js | import petDetailsQuery from './petDetails.query';
import petFindQuery from './petFind.query';
import shelterQuery from './shelterDetails.query';
import shelterGetPetsQuery from './shelterGetPets.query';
export { petDetailsQuery, petFindQuery, shelterQuery, shelterGetPetsQuery };
|
AnomalistDesignLLC/kansha | kansha/card_addons/vote/tests.py | # -*- coding:utf-8 -*-
#--
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
from kansha.cardextension.tests import CardExtensionTestCase
from .comp import Votes
class VoteTest(CardExtensionTestCase):
extension_name = 'votes'
extension_class = Votes
def test_toggle(self):
self.extension.toggle()
self.assertEqual(self.extension.count_votes(), 1)
self.assertTrue(self.extension.has_voted())
self.extension.toggle()
self.assertEqual(self.extension.count_votes(), 0)
self.assertFalse(self.extension.has_voted())
|
bianapis/sd-direct-debit-mandate-v2.0 | src/main/java/org/bian/dto/BQMandateRegistrationRetrieveOutputModelMandateRegistrationInstanceAnalysis.java | <gh_stars>0
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* BQMandateRegistrationRetrieveOutputModelMandateRegistrationInstanceAnalysis
*/
public class BQMandateRegistrationRetrieveOutputModelMandateRegistrationInstanceAnalysis {
private Object mandateRegistrationInstanceAnalysisRecord = null;
private String mandateRegistrationInstanceAnalysisReportType = null;
private String mandateRegistrationInstanceAnalysisParameters = null;
private Object mandateRegistrationInstanceAnalysisReport = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The inputs and results of the instance analysis that can be on-going, periodic and actual and projected
* @return mandateRegistrationInstanceAnalysisRecord
**/
public Object getMandateRegistrationInstanceAnalysisRecord() {
return mandateRegistrationInstanceAnalysisRecord;
}
public void setMandateRegistrationInstanceAnalysisRecord(Object mandateRegistrationInstanceAnalysisRecord) {
this.mandateRegistrationInstanceAnalysisRecord = mandateRegistrationInstanceAnalysisRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external performance analysis report available
* @return mandateRegistrationInstanceAnalysisReportType
**/
public String getMandateRegistrationInstanceAnalysisReportType() {
return mandateRegistrationInstanceAnalysisReportType;
}
public void setMandateRegistrationInstanceAnalysisReportType(String mandateRegistrationInstanceAnalysisReportType) {
this.mandateRegistrationInstanceAnalysisReportType = mandateRegistrationInstanceAnalysisReportType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the analysis (e.g. period, algorithm type)
* @return mandateRegistrationInstanceAnalysisParameters
**/
public String getMandateRegistrationInstanceAnalysisParameters() {
return mandateRegistrationInstanceAnalysisParameters;
}
public void setMandateRegistrationInstanceAnalysisParameters(String mandateRegistrationInstanceAnalysisParameters) {
this.mandateRegistrationInstanceAnalysisParameters = mandateRegistrationInstanceAnalysisParameters;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external analysis report in any suitable form including selection filters where appropriate
* @return mandateRegistrationInstanceAnalysisReport
**/
public Object getMandateRegistrationInstanceAnalysisReport() {
return mandateRegistrationInstanceAnalysisReport;
}
public void setMandateRegistrationInstanceAnalysisReport(Object mandateRegistrationInstanceAnalysisReport) {
this.mandateRegistrationInstanceAnalysisReport = mandateRegistrationInstanceAnalysisReport;
}
}
|
GavrielDunev/Java-Advanced | Java OOP/Polymorphism/src/VehiclesExtension/Bus.java | <gh_stars>0
package VehiclesExtension;
import java.text.DecimalFormat;
public class Bus extends Vehicle{
private static final double ADDITIONAL_CONSUMPTION_WITH_AIR_CONDITIONER = 1.4;
public Bus(double fuelQuantity, double fuelConsumptions, double tankCapacity) {
super(fuelQuantity, fuelConsumptions, tankCapacity);
}
public String drive (double distance, double fuelConsumption) {
double fuelNeeded = (fuelConsumption + ADDITIONAL_CONSUMPTION_WITH_AIR_CONDITIONER) * distance;
if (this.fuelQuantity < fuelNeeded) {
return this.getClass().getSimpleName() + " needs refueling";
}
setFuelQuantity(this.fuelQuantity -= fuelNeeded);
DecimalFormat formatter = new DecimalFormat("#.##");
return String.format("%s travelled %s km", this.getClass().getSimpleName(), formatter.format(distance));
}
}
|
timfel/netbeans | platform/o.n.swing.tabcontrol/src/org/netbeans/swing/tabcontrol/WinsysInfoForTabbed.java | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.swing.tabcontrol;
import java.awt.Component;
/**
* Interface that provides external information (provided by window system)
* that TabbedContainers need to know in order to work fully.<p>
*
* Tab control uses info to provide for example tab buttons reacting on
* the position of the container or on maximization state.
*
* @see TabbedContainer#TabbedContainer
*
* @author <NAME>
*/
public interface WinsysInfoForTabbed {
/** Returns global orientation of given component.
*
* @return Orientation of component, as defined in
* TabDisplayer.ORIENTATION_XXX constants
*/
public Object getOrientation (Component comp);
/** Finds out in what state is window system mode containing given component.
*
* @return true if given component is inside mode which is in maximized state,
* false otherwise
*/
public boolean inMaximizedMode (Component comp);
}
|
bengler/vanilla | spec/helpers/url_helper.rb | module UrlHelper
def params_from_url(url)
params = CGI.parse(URI.parse(url).query)
Hash[*params.entries.map { |k, v| [k, v[0]] }.flatten].with_indifferent_access
end
def params_from_fragment(url)
params = CGI.parse(URI.parse(url).fragment)
Hash[*params.entries.map { |k, v| [k, v[0]] }.flatten].with_indifferent_access
end
end
|
Andreas237/AndroidPolicyAutomation | ExtractedJars/Health_com.huawei.health/javafiles/com/huawei/hms/support/api/entity/auth/AuthorizationInfo.java | <reponame>Andreas237/AndroidPolicyAutomation
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.huawei.hms.support.api.entity.auth;
import android.text.TextUtils;
import com.huawei.hms.core.aidl.IMessageEntity;
import java.util.List;
public class AuthorizationInfo
implements IMessageEntity
{
public AuthorizationInfo()
{
// 0 0:aload_0
// 1 1:invokespecial #23 <Method void Object()>
// 2 4:return
}
public String getAccessToken()
{
return accessToken;
// 0 0:aload_0
// 1 1:getfield #28 <Field String accessToken>
// 2 4:areturn
}
public String getAppID()
{
return appID;
// 0 0:aload_0
// 1 1:getfield #31 <Field String appID>
// 2 4:areturn
}
public String getClientID()
{
return clientID;
// 0 0:aload_0
// 1 1:getfield #34 <Field String clientID>
// 2 4:areturn
}
public String getClientSecret()
{
return clientSecret;
// 0 0:aload_0
// 1 1:getfield #37 <Field String clientSecret>
// 2 4:areturn
}
public long getExpiredTime()
{
return expiredTime;
// 0 0:aload_0
// 1 1:getfield #41 <Field long expiredTime>
// 2 4:lreturn
}
public String getOpenId()
{
return openID;
// 0 0:aload_0
// 1 1:getfield #44 <Field String openID>
// 2 4:areturn
}
public String getRefreshToken()
{
return refreshToken;
// 0 0:aload_0
// 1 1:getfield #47 <Field String refreshToken>
// 2 4:areturn
}
public List getScopeList()
{
return scopeList;
// 0 0:aload_0
// 1 1:getfield #51 <Field List scopeList>
// 2 4:areturn
}
public boolean isTokenExpire()
{
return System.currentTimeMillis() > expiredTime;
// 0 0:invokestatic #60 <Method long System.currentTimeMillis()>
// 1 3:aload_0
// 2 4:getfield #41 <Field long expiredTime>
// 3 7:lcmp
// 4 8:ifle 13
// 5 11:iconst_1
// 6 12:ireturn
// 7 13:iconst_0
// 8 14:ireturn
}
public boolean isValid()
{
return TextUtils.isEmpty(((CharSequence) (appID)));
// 0 0:aload_0
// 1 1:getfield #31 <Field String appID>
// 2 4:invokestatic #67 <Method boolean TextUtils.isEmpty(CharSequence)>
// 3 7:ireturn
}
public void setAccessToken(String s)
{
accessToken = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #28 <Field String accessToken>
// 3 5:return
}
public void setAppID(String s)
{
appID = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #31 <Field String appID>
// 3 5:return
}
public void setClientID(String s)
{
clientID = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #34 <Field String clientID>
// 3 5:return
}
public void setClientSecret(String s)
{
clientSecret = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #37 <Field String clientSecret>
// 3 5:return
}
public void setExpiredTime(long l)
{
expiredTime = l;
// 0 0:aload_0
// 1 1:lload_1
// 2 2:putfield #41 <Field long expiredTime>
// 3 5:return
}
public void setOpenID(String s)
{
openID = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #44 <Field String openID>
// 3 5:return
}
public void setRefreshToken(String s)
{
refreshToken = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #47 <Field String refreshToken>
// 3 5:return
}
public void setScopeList(List list)
{
scopeList = list;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #51 <Field List scopeList>
// 3 5:return
}
public String toString()
{
StringBuilder stringbuilder = new StringBuilder();
// 0 0:new #82 <Class StringBuilder>
// 1 3:dup
// 2 4:invokespecial #83 <Method void StringBuilder()>
// 3 7:astore_1
stringbuilder.append("appID:").append(appID);
// 4 8:aload_1
// 5 9:ldc1 #85 <String "appID:">
// 6 11:invokevirtual #89 <Method StringBuilder StringBuilder.append(String)>
// 7 14:aload_0
// 8 15:getfield #31 <Field String appID>
// 9 18:invokevirtual #89 <Method StringBuilder StringBuilder.append(String)>
// 10 21:pop
stringbuilder.append(", expiredTime:").append(expiredTime);
// 11 22:aload_1
// 12 23:ldc1 #91 <String ", expiredTime:">
// 13 25:invokevirtual #89 <Method StringBuilder StringBuilder.append(String)>
// 14 28:aload_0
// 15 29:getfield #41 <Field long expiredTime>
// 16 32:invokevirtual #94 <Method StringBuilder StringBuilder.append(long)>
// 17 35:pop
return stringbuilder.toString();
// 18 36:aload_1
// 19 37:invokevirtual #96 <Method String StringBuilder.toString()>
// 20 40:areturn
}
private String accessToken;
private String appID;
private String clientID;
private String clientSecret;
private long expiredTime;
private String openID;
private String refreshToken;
private List scopeList;
}
|
michaelrk02/aksen | frontend/portal/OrderFormLocked.js | import {Component, createElement as $} from 'react';
import {Link} from 'react-router-dom';
export default class OrderFormLocked extends Component {
constructor(/* form, duration */ props) {
super(props);
this.state = {
timeLeft: this.props.duration
};
this.page = this.props.form;
this.countdown = null;
}
componentDidMount() {
this.countdown = window.setInterval((() => {
if (this.state.timeLeft > 0) {
this.setState({timeLeft: this.state.timeLeft - 1});
} else {
window.clearInterval(this.countdown);
this.page.determineLock();
}
}).bind(this), 1000);
}
componentWillUnmount() {
if (this.countdown !== null) {
window.clearInterval(this.countdown);
}
}
render() {
const hours = Math.floor(this.state.timeLeft / 3600);
const minutes = Math.floor(this.state.timeLeft / 60) % 60;
const seconds = this.state.timeLeft % 60;
return $('div', {className: 'empty'}, [
$('div', {className: 'empty-icon'}, $('i', {className: 'icon icon-stop icon-4x'})),
$('p', {className: 'empty-title h5'}, 'Form terkunci sementara'),
$('p', {className: 'empty-subtitle'}, 'Anda telah melakukan pemesanan beberapa waktu yang lalu. Silakan tunggu beberapa waktu lagi untuk dapat memesan. Anda diperbolehkan memesan lagi dalam:'),
$('div', {className: 'empty-action'}, $('h5', {className: 'label'}, hours + ' jam ' + minutes + ' menit ' + seconds + ' detik'))
]);
}
}
|
Kyle9021/trireme-lib | controller/pkg/ipsetmanager/helpers.go | package ipsetmanager
import (
"strings"
)
func addToIPset(set Ipset, data string) error {
// ipset can not program this rule
if data == IPv4DefaultIP {
if err := addToIPset(set, "0.0.0.0/1"); err != nil {
return err
}
return addToIPset(set, "172.16.31.10/1")
}
// ipset can not program this rule
if data == IPv6DefaultIP {
if err := addToIPset(set, "::/1"); err != nil {
return err
}
return addToIPset(set, "8000::/1")
}
if strings.HasPrefix(data, "!") {
return set.AddOption(data[1:], "nomatch", 0)
}
return set.Add(data, 0)
}
func delFromIPset(set Ipset, data string) error {
if data == IPv4DefaultIP {
if err := delFromIPset(set, "0.0.0.0/1"); err != nil {
return err
}
return delFromIPset(set, "172.16.31.10/1")
}
if data == IPv6DefaultIP {
if err := delFromIPset(set, "::/1"); err != nil {
return err
}
return delFromIPset(set, "8000::/1")
}
return set.Del(strings.TrimPrefix(data, "!"))
}
|
tracy4262/zhenxingxiangcun | server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/ProxyReversionServiceImpl.java | <reponame>tracy4262/zhenxingxiangcun<filename>server/nswy-api-dev/nswy-member-service/src/main/java/com/ovit/nswy/member/service/impl/ProxyReversionServiceImpl.java
package com.ovit.nswy.member.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ovit.nswy.member.mapper.ProxyReversionMapper;
import com.ovit.nswy.member.model.LoginUser;
import com.ovit.nswy.member.service.LoginUserService;
import com.ovit.nswy.member.service.PerfectInformationService;
import com.ovit.nswy.member.service.ProxyReversionService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ProxyReversionServiceImpl implements ProxyReversionService {
@Autowired
private ProxyReversionMapper proxyReversionMapper;
@Autowired
private LoginUserService loginUserService;
@Autowired
private PerfectInformationService perfectInformationService;
private Logger logger = LogManager.getLogger(ProxyReversionServiceImpl.class);
/**
* 查询用户代理列表
* @param params
*/
@Override
public Map<String, Object> proxyList(Map<String, Object> params) {
params.put("status", 1);
List<Map<String,Object>> proxyList = proxyReversionMapper.queryAccount(params);
List<String> accountList = new ArrayList<>();
String account = MapUtils.getString(params, "proxyAccount");
accountList.add(account);
for (Map<String,Object> map : proxyList) {
accountList.add(MapUtils.getString(map, "account"));
}
Map<String,Object> resultMap = new HashMap<>();
resultMap.put("account", account);
resultMap.put("key", account);
List<Map<String,Object>> proxy = new ArrayList<>();
for (String s : accountList) {
LoginUser loginUser = loginUserService.findByLoginName(s);
Map<String,Object> map = new HashMap<>();
map.put("account", s);
map.put("session", loginUser);
proxy.add(map);
}
resultMap.put("proxy", proxy);
return resultMap;
}
/**
* 用户注册一个账号
* @param params
*/
@Override
public void insertProxy(Map<String, Object> params) {
proxyReversionMapper.insertProxy(params);
}
/**
* 查询账号
* @param params
* @return
*/
@Override
public PageInfo<List<Map<String, Object>>> queryAccount(Map<String, Object> params) {
//分页查询数据
int pageNum = MapUtils.getInteger(params, "pageNum");
int pageSize = MapUtils.getInteger(params, "pageSize");
PageHelper.startPage(pageNum, pageSize);
List<Map<String,Object>> accountList = proxyReversionMapper.queryAccount(params);
//手动清理 ThreadLocal 存储的分页参数
PageHelper.clearPage();
//被操作多次的账号
List<String> multiAccount = proxyReversionMapper.findMultiAccount(params);
for (Map<String,Object> map : accountList) {
//查正在使用的模板信息
String account = MapUtils.getString(map, "account");
//确认被操作多次的账号的最终的状态
if (multiAccount.contains(account)) {
List<Map<String, Object>> proxyInfo = proxyReversionMapper.findProxyInfo(account);
for (Map<String,Object> proxy : proxyInfo) {
int status = MapUtils.getInteger(proxy, "status");
int type = MapUtils.getInteger(proxy, "type");
if (type == 1 && status == 1) {
map.put("status", status);
map.put("type", type);
break;
}
if (type == 0 && status == 2) {
map.put("status", 1);
map.put("type", 1);
break;
}
if (type == 1 && status == 2) {
map.put("status", status);
map.put("type", type);
continue;
}
}
}
Map<String,Object> useTemplate = loginUserService.findUseTemplate(account);
if (MapUtils.isEmpty(useTemplate)) {
//map.put("name", "");
map.put("avatar", "");
} else {
/*String memberName = "";
List<Map<String,Object>> memberList = proxyReversionMapper.findMemberName(useTemplate);
if (CollectionUtils.isNotEmpty(memberList)) {
memberName = MapUtils.getString(memberList.get(0), "memberName");
}
map.put("name", memberName);*/
//查询用户最大的年度文件id
if (MapUtils.isNotEmpty(useTemplate)) {
Map<String,Object> yearInfo = loginUserService.findYearInfo(account);
useTemplate.put("yearId", MapUtils.getString(yearInfo, "id"));
Map<String,Object> privacyInfo = perfectInformationService.findPrivacyInfo(useTemplate);
String avatar = MapUtils.getString(privacyInfo, "image");
if (StringUtils.isBlank(avatar)) {
map.put("avatar", "");
} else {
map.put("avatar", avatar);
}
} else {
map.put("avatar", "");
}
}
}
return new PageInfo(accountList);
}
/**
* 代理或取消代理
* @param params
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void proxyOrCancle(Map<String, Object> params) {
int type = MapUtils.getInteger(params, "type");
params.remove("type");
/*if (type == 0) {
params.remove("type");
}*/
//根据要代理的账号查询是否存在数据
Map<String,Object> proxyMap = proxyReversionMapper.queryByAccount(params);
//保存数据记录
Map<String,Object> proxyRecord = proxyReversionMapper.queryProxyRecord(params);
params.put("status", 2);
params.put("type", type);
if (MapUtils.isEmpty(proxyMap)) {
//新增
proxyReversionMapper.insertProxy(params);
} else {
//更新
params.put("id", MapUtils.getString(proxyMap, "id"));
proxyReversionMapper.updateProxy(params);
}
params.remove("id");
if (MapUtils.isNotEmpty(proxyRecord)) {
//有记录,获取id
params.put("id", MapUtils.getString(proxyRecord, "id"));
}
proxyReversionMapper.saveProxyRecord(params);
}
/**
* 查询代理模板或取消代理模板
* @param params
*/
@Override
public Map<String, Object> proxyTemplate(Map<String, Object> params) {
return proxyReversionMapper.proxyTemplate(params);
}
/**
* 暂不代理
* @param params
*/
@Override
public void noProxy(Map<String, Object> params) {
params.put("status", 4);
proxyReversionMapper.updateProxy(params);
}
/**
* 查询待审数据
* @param params
* @return
*/
@Override
public PageInfo<List<Map<String, Object>>> waitProxy(Map<String, Object> params) {
//分页查询数据
int pageNum = MapUtils.getInteger(params, "pageNum");
int pageSize = MapUtils.getInteger(params, "pageSize");
PageHelper.startPage(pageNum, pageSize);
List<Map<String,Object>> waitProxy = proxyReversionMapper.waitProxy(params);
return new PageInfo(waitProxy);
}
@Override
public List<Map<String, Object>> findMemberName(Map<String, Object> params) {
return proxyReversionMapper.findMemberName(params);
}
@Override
public void toProxy(Map<String, Object> params) {
Map<String, Object> completing = proxyReversionMapper.isCompleting(params);
if (MapUtils.isEmpty(completing)) {
params.put("type", 1);
proxyReversionMapper.insertProxy(params);
} else {
//做更新操作,将type更新为1,status更新为0
completing.put("status", 0);
completing.put("type", 1);
proxyReversionMapper.updateProxy(completing);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.