repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
mauguignard/cbmc
|
jbmc/regression/jbmc-strings/RegexMatches01/RegexMatches01.java
|
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches01
{
public static void main(String[] args)
{
Pattern expression =
Pattern.compile("W.*\\d[0-35-9]-\\d\\d-\\d\\d");
String string1 = "XXXX's Birthday is 05-12-75\n" +
"YYYY's Birthday is 11-04-68\n" +
"ZZZZ's Birthday is 04-28-73\n" +
"WWWW's Birthday is 12-17-77";
Matcher matcher = expression.matcher(string1);
while (matcher.find())
{
System.out.println(matcher.group());
String tmp=matcher.group();
assert tmp.equals("WWWW's Birthday is 12-17-77");
}
}
}
|
asen/smg
|
app/com/smule/smgplugins/mon/anom/ValueChunkStats.scala
|
<gh_stars>1-10
package com.smule.smgplugins.mon.anom
import play.api.libs.json.{JsValue, Json}
import scala.collection.mutable
import scala.math.{max, min, pow}
case class ValueChunkStats(cnt: Int, avg: Double, variance: Double, p90: Double) {
def serialize: JsValue = {
val mm = mutable.Map[String, JsValue](
"cnt" -> Json.toJson(cnt)
)
if (!avg.isNaN) mm("avg") = Json.toJson(avg)
if (!variance.isNaN) mm("variance") = Json.toJson(variance)
if (!p90.isNaN) mm("p90") = Json.toJson(p90)
Json.toJson(mm.toMap)
}
def isSimilar(changeThresh: Double, oth: ValueChunkStats): Boolean = {
(max(avg,oth.avg) < changeThresh * min(avg, oth.avg)) ||
(max(variance, oth.variance) < changeThresh * min(variance, oth.variance)) ||
(max(p90,oth.p90) < changeThresh * min(p90, oth.p90))
}
}
object ValueChunkStats {
def fromSeq(lst: Seq[Double]): ValueChunkStats = {
if (lst.isEmpty) return ValueChunkStats(0, 0.0, 0.0, 0.0)
val cnt = lst.size
val avg = lst.sum / lst.size
val variance = lst.map(v => pow(v - avg, 2)).sum / cnt
val lstsz = lst.size
val p90 = if (lstsz == 1) lst.head else lst.sorted.take( (lstsz * 9) / 10 ).lastOption.getOrElse(0.0)
ValueChunkStats(cnt, avg, variance, p90)
}
def aggregate(lst: Seq[ValueChunkStats]): ValueChunkStats = {
val newCnt = lst.map(_.cnt).sum
val newAvg = lst.map(cs => cs.avg * cs.cnt).sum / newCnt
val newVariance = lst.map(cs => cs.variance * cs.cnt).sum / newCnt
val newP90 = if (lst.isEmpty) Double.NaN else lst.map(_.p90).max
ValueChunkStats(newCnt, newAvg, newVariance, newP90)
}
def deserialize(src: JsValue): ValueChunkStats = {
val cnt = (src \ "cnt").asOpt[Int].getOrElse(0)
val avg = (src \ "avg").asOpt[Double].getOrElse(0.0)
val variance = (src \ "variance").asOpt[Double].getOrElse(0.0)
val p90 = (src \ "p90").asOpt[Double].getOrElse(0.0)
ValueChunkStats(cnt, avg, variance, p90)
}
}
|
scala-steward/LiCOS-JSON4Scala
|
src/test/scala/protocol/engine/lobby/example/server2client/WaitingPage.scala
|
package protocol.engine.lobby.example.server2client
import protocol.engine.ServerToClientLobbyExample
final case class WaitingPage(filePath: String) extends ServerToClientLobbyExample(filePath) {
override val `type`: String = WaitingPage.`type`
}
object WaitingPage {
val `type`: String = "lobby.server2client.WaitingPage"
}
|
lieonCX/XGG
|
xianglegou/Classes/Function/User/Interface/View/Mine/Shop/GC_ShopMoneyTableViewCell.h
|
//
// GC_ShopMoneyTableViewCell.h
// xianglegou
//
// Created by mini3 on 2017/5/11.
// Copyright © 2017年 xianglegou. All rights reserved.
//
// 店铺货款 -- cell
//
#import "Hen_BaseTableViewCell.h"
#import "GC_ShopManagerModel.h"
@interface GC_ShopMoneyTableViewCell : Hen_BaseTableViewCell
///更新 ui
- (void)updateUIForPatMentListData:(GC_MResPaymentListDataModel *)data;
@end
|
pwr-pbrwio/PBR20M2
|
projects/checkstyle/src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java
|
<reponame>pwr-pbrwio/PBR20M2
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2018 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.function.BiPredicate;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import com.puppycrawl.tools.checkstyle.internal.utils.XmlUtil;
public abstract class AbstractXmlTestSupport extends AbstractModuleTestSupport {
protected static Document getOutputStreamXml(ByteArrayOutputStream outputStream)
throws ParserConfigurationException {
final String xml = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
return XmlUtil.getRawXml("audit output", xml, xml);
}
protected static void verifyXml(String expectedOutputFile,
ByteArrayOutputStream actualOutputStream, String... messages) throws Exception {
verifyXml(expectedOutputFile, actualOutputStream, null, messages);
}
protected static void verifyXml(String expectedOutputFile,
ByteArrayOutputStream actualOutputStream,
BiPredicate<Node, Node> ordered, String... messages) throws Exception {
String expectedContents = readFile(expectedOutputFile);
for (int i = 0; i < messages.length; i++) {
expectedContents = expectedContents.replace("$" + i, messages[i]);
}
final Document expectedDocument = XmlUtil.getRawXml("audit output", expectedContents,
expectedContents);
final Document actualDocument = getOutputStreamXml(actualOutputStream);
Assert.assertEquals("xml encoding should be the same", expectedDocument.getXmlEncoding(),
actualDocument.getXmlEncoding());
Assert.assertEquals("xml version should be the same", expectedDocument.getXmlVersion(),
actualDocument.getXmlVersion());
verifyXmlNode(expectedDocument, actualDocument, "/", ordered);
}
private static void verifyXmlNodes(Node expected, Node actual, String path,
BiPredicate<Node, Node> ordered) {
final Node expectedFirstChild = expected.getFirstChild();
final Node actualFirstChild = actual.getFirstChild();
if (expectedFirstChild == null) {
Assert.assertNull("no children nodes should exist: " + path, actualFirstChild);
Assert.assertEquals("text should be the same: " + path, expected.getNodeValue(),
actual.getNodeValue());
}
else {
Assert.assertNotNull("children nodes should exist: " + path, actualFirstChild);
if (ordered == null) {
Node actualChild = actualFirstChild;
for (Node expectedChild = expectedFirstChild; expectedChild != null;
expectedChild = expectedChild.getNextSibling()) {
verifyXmlNode(expectedChild, actualChild, path, ordered);
actualChild = actualChild.getNextSibling();
}
Assert.assertNull("node have same number of children: " + path, actualChild);
}
else {
final Set<Node> expectedChildren = XmlUtil.getChildrenElements(expected);
final Set<Node> actualChildren = XmlUtil.getChildrenElements(actual);
Assert.assertEquals("node have same number of children: " + path,
expectedChildren.size(), actualChildren.size());
for (Node expectedChild : expectedChildren) {
Node foundChild = null;
for (Node actualChild : actualChildren) {
if (ordered.test(expectedChild, actualChild)) {
foundChild = actualChild;
break;
}
}
Assert.assertNotNull("node should exist: " + path + expectedChild.getNodeName()
+ "/", foundChild);
verifyXmlNode(expectedChild, foundChild, path, ordered);
}
}
}
}
private static void verifyXmlNode(Node expected, Node actual, String path,
BiPredicate<Node, Node> ordered) {
if (expected == null) {
if (actual != null) {
Assert.fail("no node should exist: " + path + actual.getNodeName() + "/");
}
}
else {
final String newPath = path + expected.getNodeName() + "/";
Assert.assertNotNull("node should exist: " + newPath, actual);
Assert.assertEquals("node should have same name: " + newPath, expected.getNodeName(),
actual.getNodeName());
Assert.assertEquals("node should have same type: " + newPath, expected.getNodeType(),
actual.getNodeType());
verifyXmlAttributes(expected.getAttributes(), actual.getAttributes(), newPath);
verifyXmlNodes(expected, actual, newPath, ordered);
}
}
private static void verifyXmlAttributes(NamedNodeMap expected, NamedNodeMap actual,
String path) {
if (expected == null) {
Assert.assertNull("no attributes should exist: " + path, actual);
}
else {
Assert.assertNotNull("attributes should exist: " + path, actual);
for (int i = 0; i < expected.getLength(); i++) {
verifyXmlAttribute(expected.item(i), actual.item(i), path);
}
Assert.assertEquals("node have same number of attributes: " + path,
expected.getLength(), actual.getLength());
}
}
private static void verifyXmlAttribute(Node expected, Node actual, String path) {
final String expectedName = expected.getNodeName();
Assert.assertNotNull("attribute value for '" + expectedName + "' should not be null: "
+ path, actual);
Assert.assertEquals("attribute name should match: " + path, expectedName,
actual.getNodeName());
// ignore checkstyle version in xml as it changes each release
if (!"/#document/checkstyle".equals(path) && !"version".equals(expectedName)) {
Assert.assertEquals("attribute value for '" + expectedName + "' should match: " + path,
expected.getNodeValue(), actual.getNodeValue());
}
}
}
|
tritas/bitl
|
examples/two_bernouilli_arms.py
|
<reponame>tritas/bitl<filename>examples/two_bernouilli_arms.py
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
# License: BSD 3-clause
import numpy as np
from bitl.evaluation.comparison import PolicyComparison
from bitl.policies.kl_ucb import klUCB
from bitl.policies.thompson_sampling import ThompsonSampling
from bitl.datasets.synthetic import make_stochastic_batch_dataset
# --- Global parameters
horizon = 20000
n_runs = 100
n_jobs = 4
n_actions = 2
# Fix seed
np.random.seed(1337)
# Pick policies and initialize them.
policies = [
ThompsonSampling(K=n_actions),
klUCB(K=n_actions)
]
# --- First problem
means = np.array([0.55, 0.60])
# Generate some signal
stream = make_stochastic_batch_dataset(means, horizon)
# Initialize simulation object with simul parameters
# (n_runs, results_folder, ...)
evaluator = PolicyComparison(
policies, means, stream,
horizon=horizon, n_runs=n_runs, n_jobs=n_jobs)
# Evaluate it and show print results
evaluator.replay_all()
evaluator.print_metrics()
# --- Second problem
means = np.array([0.2, 0.8])
stream = make_stochastic_batch_dataset(means, horizon)
evaluator = PolicyComparison(
policies, means, stream,
horizon=horizon, n_runs=n_runs, n_jobs=n_jobs)
evaluator.replay_all()
evaluator.print_metrics()
# Get report as plots & HTML table
|
lsa-pucrs/jason-ros-releases
|
cartago-2.0.1/src/main/cartago/tools/inspector/OpCompleted.java
|
<filename>cartago-2.0.1/src/main/cartago/tools/inspector/OpCompleted.java
package cartago.tools.inspector;
import cartago.*;
public class OpCompleted extends LoggerEvent{
private ArtifactId artifactId;
private OpId oid;
public OpCompleted(long when, ArtifactId target, OpId oid){
super(when);
artifactId = target;
this.oid = oid;
}
public ArtifactId getArtifactId(){
return artifactId;
}
public OpId getOpId(){
return oid;
}
}
|
ghga-de/metadata-api
|
metadata_repository_service/dao/biospecimen.py
|
<reponame>ghga-de/metadata-api<gh_stars>0
# Copyright 2021 - 2022 Universität Tübingen, DKFZ and EMBL
# for the German Human Genome-Phenome Archive (GHGA)
#
# 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.
"""
Convenience methods for retrieving Biospecimen records
"""
from typing import List
from metadata_repository_service.config import CONFIG, Config
from metadata_repository_service.dao.db import get_db_client
from metadata_repository_service.dao.utils import get_entity
from metadata_repository_service.models import Biospecimen
COLLECTION_NAME = "Biospecimen"
async def retrieve_biospecimens(config: Config = CONFIG) -> List[str]:
"""
Retrieve a list of Biospecimen object IDs from metadata store.
Args:
config: Rumtime configuration
Returns:
A list of Biospecimen object IDs.
"""
client = await get_db_client(config)
collection = client[config.db_name][COLLECTION_NAME]
biospecimens = await collection.find().to_list(None)
client.close()
return [x["id"] for x in biospecimens]
async def get_biospecimen(
biospecimen_id: str, embedded: bool = False, config: Config = CONFIG
) -> Biospecimen:
"""
Given a Biospecimen ID, get the Biospecimen object from metadata store.
Args:
biospecimen_id: The Biospecimen ID
embedded: Whether or not to embed references. ``False``, by default.
config: Rumtime configuration
Returns:
The Biospecimen object
"""
biospecimen = await get_entity(
identifier=biospecimen_id,
field="id",
collection_name=COLLECTION_NAME,
model_class=Biospecimen,
embedded=embedded,
config=config,
)
return biospecimen
|
Tianqi-Zhu/tp
|
src/test/java/manageme/logic/parser/task/FindTaskCommandParserTest.java
|
<filename>src/test/java/manageme/logic/parser/task/FindTaskCommandParserTest.java<gh_stars>0
package manageme.logic.parser.task;
import static manageme.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import manageme.logic.commands.task.FindTaskCommand;
import manageme.logic.parser.CommandParserTestUtil;
import manageme.model.task.TaskNameContainsKeywordsPredicate;
public class FindTaskCommandParserTest {
private final FindTaskCommandParser parser = new FindTaskCommandParser();
@Test
public void parse_emptyArg_throwsParseException() {
CommandParserTestUtil.assertParseFailure(parser, " ",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindTaskCommand.MESSAGE_USAGE));
}
@Test
public void parse_validArgs_returnsFindCommand() {
// no leading and trailing whitespaces
FindTaskCommand expectedFindTaskCommand =
new FindTaskCommand(new TaskNameContainsKeywordsPredicate(Arrays.asList("Eat", "Sleep")));
CommandParserTestUtil.assertParseSuccess(parser, "Eat Sleep", expectedFindTaskCommand);
// multiple whitespaces between keywords
CommandParserTestUtil.assertParseSuccess(parser, " \n Eat \n \t Sleep \t", expectedFindTaskCommand);
}
}
|
HarvestHaven/TPOT-Next
|
components/layout/PageSpinner.js
|
<gh_stars>1-10
import React from 'react'
import Flex from '@chakra-ui/core/dist/Flex'
import Spinner from '@chakra-ui/core/dist/Spinner'
const PageSpinner = () =>
<Flex h="100%" w="100%" justifyContent="center" alignItems="center">
<Spinner
thickness="4px"
speed="0.65s"
emptyColor="primary.200"
color="primary.500"
size="xl"
/>
</Flex>
export default PageSpinner
|
lemoony/snipkit
|
cmd/info_test.go
|
package cmd
import (
"os"
"testing"
"github.com/spf13/viper"
"github.com/lemoony/snipkit/internal/config/configtest"
"github.com/lemoony/snipkit/internal/model"
"github.com/lemoony/snipkit/internal/utils/termtest"
"github.com/lemoony/snipkit/internal/utils/testutil"
mocks "github.com/lemoony/snipkit/mocks/managers"
)
func Test_Info(t *testing.T) {
_ = os.Unsetenv("SNIPKIT_HOME")
system := testutil.NewTestSystem()
cfgFilePath := configtest.NewTestConfigFilePath(t, system.Fs)
manager := mocks.Manager{}
manager.On("Info").Return([]model.InfoLine{{Key: "Some-Key", Value: "Some-Value", IsError: false}})
v := viper.New()
v.SetFs(system.Fs)
v.SetConfigFile(cfgFilePath)
ts := setup{
system: system,
v: v,
provider: testProviderForManager(&manager),
}
runTerminalTest(t, []string{"info"}, ts, false, func(c *termtest.Console) {
c.ExpectString("Config path: " + cfgFilePath)
c.ExpectString("SNIPKIT_HOME: Not set")
c.ExpectString("Theme: default")
c.ExpectString("Some-Key: Some-Value")
})
}
|
jnthn/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/editor/actions/FocusGutterAction.java
|
<reponame>jnthn/intellij-community<gh_stars>1-10
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.actions;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.util.ui.accessibility.ScreenReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Requests focus to editor gutter to support a11y for Screen Reader.
*
* @author tav
*/
public class FocusGutterAction extends EditorAction {
public FocusGutterAction() {
super(new EditorActionHandler() {
@Override
protected void doExecute(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) {
IdeFocusManager.getGlobalInstance().requestFocus(((EditorImpl)editor).getGutterComponentEx(), true);
}
@Override
protected boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) {
return ScreenReader.isActive();
}
});
}
}
|
dmagadi/demo
|
SNGContacts/app/src/main/java/com/sngastro/sngcontacts/DatabaseService.java
|
<reponame>dmagadi/demo<gh_stars>0
package com.sngastro.sngcontacts;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.util.Log;
import com.sngastro.sngcontacts.contact.ContactInfo;
import com.sngastro.sngcontacts.contact.Email;
import com.sngastro.sngcontacts.contact.PhoneNumber;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by dmagadi on 4/12/16.
*/
public class DatabaseService {
private String TAG = "**********************************************************************************************";
private SQLLiteDBHandler dbhandler = null;
public DatabaseService(Context context) {
dbhandler = new SQLLiteDBHandler(context);
}
public String getSetting(String name) {
Cursor cursor = dbhandler.getReadableDatabase().rawQuery("select * from SETTING where name = ?", new String[]{name});
String value = "";
while (cursor.moveToNext()) {
value = cursor.getString(cursor.getColumnIndex("value"));
Log.d(TAG, value);
}
cursor.close();
return value;
}
public void updateSetting(String name, String value) {
dbhandler.getWritableDatabase().rawQuery("UPDATE SETTING SET value = ? WHERE name = ?", new String[]{value, name});
}
public ArrayList<ContactInfo> getContactInfos() {
ArrayList<ContactInfo> contactInfoArrayList = new ArrayList<>();
Cursor cursor;
cursor = dbhandler.getReadableDatabase().rawQuery("SELECT * FROM CONTACT_INFO ORDER BY LastName, FirstName", null);
Cursor phoneNumberCursor;
Cursor emailCursor;
while (cursor.moveToNext()) {
ContactInfo contactInfo = new ContactInfo();
contactInfo.setFirstName(cursor.getString(cursor.getColumnIndex("FirstName")));
contactInfo.setLastName(cursor.getString(cursor.getColumnIndex("LastName")));
int id = cursor.getInt(cursor.getColumnIndex("contact_id"));
ArrayList<PhoneNumber> phoneNumbers = new ArrayList<>();
phoneNumberCursor = dbhandler.getReadableDatabase().rawQuery("SELECT * FROM PHONE_NUMBERS WHERE contact_id = ?", new String[]{String.valueOf(id)});
while (phoneNumberCursor.moveToNext()) {
PhoneNumber number = new PhoneNumber();
number.setNumber(phoneNumberCursor.getString(phoneNumberCursor.getColumnIndex("phone_number")));
number.setType(phoneNumberCursor.getString(phoneNumberCursor.getColumnIndex("phone_type")));
phoneNumbers.add(number);
}
phoneNumberCursor.close();
contactInfo.setPhoneNumbers(phoneNumbers);
ArrayList<Email> emails = new ArrayList<>();
emailCursor = dbhandler.getReadableDatabase().rawQuery("SELECT * from EMAIL WHERE contact_id = ?", new String[]{String.valueOf(id)});
while (emailCursor.moveToNext()) {
Email email = new Email();
email.setEmail(emailCursor.getString(emailCursor.getColumnIndex("email")));
email.setType(emailCursor.getString(emailCursor.getColumnIndex("email_type")));
emails.add(email);
}
emailCursor.close();
contactInfo.setEmails(emails);
contactInfoArrayList.add(contactInfo);
}
cursor.close();
return contactInfoArrayList;
}
public void setContactInfos(ArrayList<ContactInfo> contactInfos) {
dbhandler.getWritableDatabase().execSQL("PRAGMA foreign_keys = OFF;");
if (dbhandler.getReadableDatabase().rawQuery("SELECT * FROM PHONE_NUMBERS;", null).moveToNext()) {
dbhandler.getWritableDatabase().execSQL("DELETE FROM PHONE_NUMBERS;");
}
if (dbhandler.getReadableDatabase().rawQuery("SELECT * FROM EMAIL;", null).moveToNext()) {
dbhandler.getWritableDatabase().execSQL("DELETE FROM EMAIL;");
}
if (dbhandler.getReadableDatabase().rawQuery("SELECT * FROM CONTACT_INFO;", null).moveToNext()) {
dbhandler.getWritableDatabase().execSQL("DELETE FROM CONTACT_INFO;");
}
dbhandler.getWritableDatabase().execSQL("PRAGMA foreign_keys = ON;");
for (ContactInfo i: contactInfos) {
ContentValues values = new ContentValues();
values.put("FirstName", i.getFirstName());
values.put("LastName", i.getLastName());
long id = dbhandler.getWritableDatabase().insert("CONTACT_INFO", "", values);
for (PhoneNumber n: i.getPhoneNumbers()) {
ContentValues values1 = new ContentValues();
values1.put("phone_number", n.getNumber());
values1.put("phone_type", n.getType());
values1.put("contact_id", id);
dbhandler.getWritableDatabase().insert("PHONE_NUMBERS", "", values1);
}
for (Email e: i.getEmails()) {
ContentValues values2 = new ContentValues();
values2.put("email", e.getEmail());
values2.put("email_type", e.getType());
values2.put("contact_id", id);
dbhandler.getWritableDatabase().insert("EMAIL", "", values2);
}
}
}
}
|
thomasLeclaire/opentelemetry-ruby
|
propagator/b3/test/single/text_map_propagator_test.rb
|
# frozen_string_literal: true
# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
require 'test_helper'
describe OpenTelemetry::Propagator::B3::Single::TextMapPropagator do
let(:propagator) { OpenTelemetry::Propagator::B3::Single::TextMapPropagator.new }
describe('#extract') do
it 'extracts context with trace id, span id, sampling flag, parent span id' do
parent_context = OpenTelemetry::Context.empty
carrier = { 'b3' => '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-1-05e3ac9a4f6e3b90' }
context = propagator.extract(carrier, context: parent_context)
extracted_context = OpenTelemetry::Trace.current_span(context).context
_(extracted_context.hex_trace_id).must_equal('80f198ee56343ba864fe8b2a57d3eff7')
_(extracted_context.hex_span_id).must_equal('e457b5a2e4d86bd1')
_(extracted_context.trace_flags).must_equal(OpenTelemetry::Trace::TraceFlags::SAMPLED)
_(extracted_context).must_be(:remote?)
end
it 'extracts context with trace id, span id, sampling flag' do
parent_context = OpenTelemetry::Context.empty
carrier = { 'b3' => '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-1' }
context = propagator.extract(carrier, context: parent_context)
extracted_context = OpenTelemetry::Trace.current_span(context).context
_(extracted_context.hex_trace_id).must_equal('80f198ee56343ba864fe8b2a57d3eff7')
_(extracted_context.hex_span_id).must_equal('e457b5a2e4d86bd1')
_(extracted_context.trace_flags).must_equal(OpenTelemetry::Trace::TraceFlags::SAMPLED)
_(extracted_context).must_be(:remote?)
end
it 'extracts context with trace id, span id' do
parent_context = OpenTelemetry::Context.empty
carrier = { 'b3' => '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1' }
context = propagator.extract(carrier, context: parent_context)
extracted_context = OpenTelemetry::Trace.current_span(context).context
_(extracted_context.hex_trace_id).must_equal('80f198ee56343ba864fe8b2a57d3eff7')
_(extracted_context.hex_span_id).must_equal('e457b5a2e4d86bd1')
_(extracted_context.trace_flags).must_equal(OpenTelemetry::Trace::TraceFlags::DEFAULT)
_(extracted_context).must_be(:remote?)
end
it 'pads 8 byte id' do
parent_context = OpenTelemetry::Context.empty
carrier = { 'b3' => '64fe8b2a57d3eff7-e457b5a2e4d86bd1' }
context = propagator.extract(carrier, context: parent_context)
extracted_context = OpenTelemetry::Trace.current_span(context).context
_(extracted_context.hex_trace_id).must_equal('000000000000000064fe8b2a57d3eff7')
end
it 'converts debug flag to sampled' do
parent_context = OpenTelemetry::Context.empty
carrier = { 'b3' => '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-d' }
context = propagator.extract(carrier, context: parent_context)
extracted_context = OpenTelemetry::Trace.current_span(context).context
_(extracted_context.trace_flags).must_equal(OpenTelemetry::Trace::TraceFlags::SAMPLED)
end
it 'handles malformed trace id' do
parent_context = OpenTelemetry::Context.empty
carrier = { 'b3' => '80f198ee56343ba864feb2a-e457b5a2e4d86bd1' }
context = propagator.extract(carrier, context: parent_context)
_(context).must_equal(parent_context)
end
it 'handles malformed span id' do
parent_context = OpenTelemetry::Context.empty
carrier = { 'b3' => '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d1' }
context = propagator.extract(carrier, context: parent_context)
_(context).must_equal(parent_context)
end
end
describe '#inject' do
it 'injects context with sampled trace flags' do
context = create_context(
trace_id: '80f198ee56343ba864fe8b2a57d3eff7',
span_id: 'e457b5a2e4d86bd1',
trace_flags: OpenTelemetry::Trace::TraceFlags::SAMPLED
)
carrier = {}
propagator.inject(carrier, context: context)
expected_b3 = '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-1'
_(carrier['b3']).must_equal(expected_b3)
end
it 'injects context with default trace flags' do
context = create_context(
trace_id: '80f198ee56343ba864fe8b2a57d3eff7',
span_id: 'e457b5a2e4d86bd1',
trace_flags: OpenTelemetry::Trace::TraceFlags::DEFAULT
)
carrier = {}
propagator.inject(carrier, context: context)
expected_b3 = '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-0'
_(carrier['b3']).must_equal(expected_b3)
end
it 'injects debug flag when present' do
context = create_context(
trace_id: '80f198ee56343ba864fe8b2a57d3eff7',
span_id: 'e457b5a2e4d86bd1',
b3_debug: true
)
carrier = {}
propagator.inject(carrier, context: context)
expected_b3 = '80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-d'
_(carrier['b3']).must_equal(expected_b3)
end
it 'no-ops if trace id invalid' do
context = create_context(
trace_id: '0' * 32,
span_id: 'e457b5a2e4d86bd1'
)
carrier = {}
propagator.inject(carrier, context: context)
_(carrier.key?('b3')).must_equal(false)
end
it 'no-ops if trace id invalid' do
context = create_context(
trace_id: '80f198ee56343ba864fe8b2a57d3eff7',
span_id: '0' * 16
)
carrier = {}
propagator.inject(carrier, context: context)
_(carrier.key?('b3')).must_equal(false)
end
end
def create_context(trace_id:,
span_id:,
trace_flags: OpenTelemetry::Trace::TraceFlags::DEFAULT,
b3_debug: false)
context = OpenTelemetry::Trace.context_with_span(
OpenTelemetry::Trace.non_recording_span(
OpenTelemetry::Trace::SpanContext.new(
trace_id: Array(trace_id).pack('H*'),
span_id: Array(span_id).pack('H*'),
trace_flags: trace_flags
)
)
)
context = OpenTelemetry::Propagator::B3.context_with_debug(context) if b3_debug
context
end
end
|
dborisenko/scalajs-react-components
|
generator/src/main/scala/com/dbrsn/generator/componentParsers.scala
|
package com.dbrsn.generator
import com.dbrsn.generator.requiresjs.FoundComponent
import scala.util.matching.Regex
object ParseComponent {
val ignoredMembers: Set[String] =
Set(
"render",
"componentDidMount",
"componentWillMount",
"componentWillReceiveProps",
"componentDidUpdate",
"componentWillUnmount",
"shouldComponentUpdate"
)
// scalastyle:off method.length
def apply(
scope: Map[CompName, FoundComponent],
library: Library,
comp: ComponentDef
): ParsedComponent = {
val propTypes: Map[PropName, PropUnparsed] =
scope
.get(comp.name)
.map(_.props)
.getOrElse(
panic(s"No Proptypes found for ${comp.name}")
)
val inheritedProps: Map[PropName, PropUnparsed] =
comp.shared match {
case None => Map.empty[PropName, PropUnparsed]
case Some(shared) =>
scope
.get(shared.name)
.map(_.props)
.getOrElse(
panic(s"$comp: No Proptypes found for $shared")
)
}
val methodClassOpt: Option[ParsedMethodClass] =
scope
.get(comp.name)
.flatMap(_.methods)
.map(_.filterNot(m ⇒ ignoredMembers(m.name) || m.name.startsWith("handle") || m.name.startsWith("_")))
.filter(_.nonEmpty)
.map(
members ⇒
ParsedMethodClass(
library.prefixOpt.getOrElse("") + comp.name.toString + "M",
members.toSeq.sortBy(_.name).map(library.memberMapper(comp.name))
)
)
val basicFields: Seq[ParsedProp] =
Seq(
ParsedProp(PropName("key"), isRequired = false, Normal("String"), None, None, None),
ParsedProp(
PropName("ref"),
isRequired = false,
Normal(methodClassOpt.fold("String")(c => c.className + " => Unit")),
None,
None,
None
)
)
val parsedProps: Seq[ParsedProp] =
(inheritedProps ++ propTypes)
.filterNot(t => basicFields.exists(_.name == t._1))
.toSeq
.sortBy(p => (p._2.fromComp != comp.name, p._1.clean.value))
.map {
case (propName, PropUnparsed(origComp, tpe, commentOpt)) =>
ParseProp(
library,
comp.name,
origComp,
propName,
tpe,
commentOpt
)
}
val domProps: Seq[ParsedProp] =
comp.domeTypeOpt
.map(domType => domType.handlers ++ domType.props)
.toSeq
.flatten
.filterNot(p ⇒ parsedProps.exists(_.name == p.name))
ParsedComponent(comp, basicFields ++ parsedProps ++ domProps, methodClassOpt)
}
// scalastyle:on method.length
}
object ParseProp {
// "Deprecated(string, 'Instead, use a custom `actions` property.')"
val Pattern: Regex = "Deprecated\\(([^,]+), '(.+)'\\)".r
def apply(
library: Library,
compName: CompName,
origCompName: CompName,
propName: PropName,
propString: PropTypeUnparsed,
commentOpt: Option[PropComment]
): ParsedProp = {
val _clean: String =
propString.value
.replace("PropTypes.", "")
.replace(".isRequired", "")
/* old style */
.replace("_react2['default'].", "")
//TODO: this is fairly mui specific, and actually breaks Sui
.replace("_utilsPropTypes2['default'].", "Mui.")
.replace("(0, _utilsDeprecatedPropType2['default'])", "Deprecated")
/* new style */
.replace("_react2.default.", "")
.replace("_propTypes2.default.", "Mui.")
.replace("(0, _deprecatedPropType2.default)", "Deprecated")
/* even another style*/
.replace("_react.", "")
val (typeStr: String, deprecatedOpt: Option[String]) = _clean match {
case Pattern(tpe, depMsg) => (tpe, Some(depMsg))
case tpe => (tpe, None)
}
val mappedType: Type =
library.typeMapper(origCompName, propName, typeStr)
val isRequired: Boolean =
propString.value.contains(".isRequired")
val inheritedFrom: Option[CompName] =
if (compName == origCompName) None else Some(origCompName)
ParsedProp(
propName,
isRequired && inheritedFrom.isEmpty,
mappedType,
commentOpt,
deprecatedOpt,
inheritedFrom
)
}
}
|
zakharchenkoAndrii/expo
|
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/interfaces/barcodescanner/BarCodeScannerProviderInterface.java
|
<reponame>zakharchenkoAndrii/expo
package abi42_0_0.expo.modules.interfaces.barcodescanner;
import android.content.Context;
public interface BarCodeScannerProviderInterface {
BarCodeScannerInterface createBarCodeDetectorWithContext(Context context);
}
|
benf1977/j2objc-serialization-example
|
j2objc/include/java/nio/charset/StandardCharsets.h
|
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/luni/src/main/java/java/nio/charset/StandardCharsets.java
//
#ifndef _JavaNioCharsetStandardCharsets_H_
#define _JavaNioCharsetStandardCharsets_H_
#include "J2ObjC_header.h"
@class JavaNioCharsetCharset;
/*!
@brief Constant definitions for the standard Charsets.
@since 1.7
*/
@interface JavaNioCharsetStandardCharsets : NSObject
@end
J2OBJC_STATIC_INIT(JavaNioCharsetStandardCharsets)
FOUNDATION_EXPORT JavaNioCharsetCharset *JavaNioCharsetStandardCharsets_ISO_8859_1_;
J2OBJC_STATIC_FIELD_GETTER(JavaNioCharsetStandardCharsets, ISO_8859_1_, JavaNioCharsetCharset *)
FOUNDATION_EXPORT JavaNioCharsetCharset *JavaNioCharsetStandardCharsets_US_ASCII_;
J2OBJC_STATIC_FIELD_GETTER(JavaNioCharsetStandardCharsets, US_ASCII_, JavaNioCharsetCharset *)
FOUNDATION_EXPORT JavaNioCharsetCharset *JavaNioCharsetStandardCharsets_UTF_16_;
J2OBJC_STATIC_FIELD_GETTER(JavaNioCharsetStandardCharsets, UTF_16_, JavaNioCharsetCharset *)
FOUNDATION_EXPORT JavaNioCharsetCharset *JavaNioCharsetStandardCharsets_UTF_16BE_;
J2OBJC_STATIC_FIELD_GETTER(JavaNioCharsetStandardCharsets, UTF_16BE_, JavaNioCharsetCharset *)
FOUNDATION_EXPORT JavaNioCharsetCharset *JavaNioCharsetStandardCharsets_UTF_16LE_;
J2OBJC_STATIC_FIELD_GETTER(JavaNioCharsetStandardCharsets, UTF_16LE_, JavaNioCharsetCharset *)
FOUNDATION_EXPORT JavaNioCharsetCharset *JavaNioCharsetStandardCharsets_UTF_8_;
J2OBJC_STATIC_FIELD_GETTER(JavaNioCharsetStandardCharsets, UTF_8_, JavaNioCharsetCharset *)
J2OBJC_TYPE_LITERAL_HEADER(JavaNioCharsetStandardCharsets)
#endif // _JavaNioCharsetStandardCharsets_H_
|
daher-alfawares/xr.desktop
|
sdk/physx/2.8.3/Samples/SampleParticleFluid/src/SampleCollision.cpp
|
<gh_stars>1-10
#include "SampleParticleFluid.h"
#include "MyFluid.h"
#include "cooking.h"
#include "UserAllocator.h"
#include "MediaPath.h"
extern bool gHardwareSimulation;
extern NxScene* gScene;
extern NxArray<MyFluid*> gMyFluids;
extern NxVec3 gCameraPos;
extern NxVec3 gCameraForward;
extern bool gShadows;
extern ErrorStream gErrorStream;
extern UserAllocator* gAllocator;
#define MAX_PARTICLES 32768
#define REST_PARTICLES_PER_METER 10.f
#define KERNEL_RADIUS_MULTIPLIER 1.8f
#define MOTION_LIMIT_MULTIPLIER 3
#define PACKET_SIZE_MULTIPLIER 8
#define COLLISION_DISTANCE_MULTIPLIER 0.18f
void CreateDynamicActors();
void SampleCollision::setup()
{
SetTitleString(getName());
#ifdef __PPCGEKKO__
SetHelpString(" a: create rigid bodies");
#else
SetHelpString(" b: create rigid bodies");
#endif
gShadows = false;
// Create objects in the scene
if (!InitCooking(gAllocator, &gErrorStream))
{
printf("\nError: Unable to initialize the cooking library, exiting the sample.\n\n");
return;
}
// Load ASE file
CookASE("fluidSample.ase", gScene, NxVec3(1,10,0));
CookASE("coolFlow.ase", gScene, NxVec3(1,6,-0), NxVec3(1,0.2,1));
CloseCooking();
// Add a box shaped drain.
NxActorDesc boxDrainActor;
NxBoxShapeDesc boxDrainShape;
boxDrainActor.shapes.pushBack(&boxDrainShape);
boxDrainShape.dimensions.set(40,1,40);
boxDrainShape.shapeFlags |= NX_SF_FLUID_DRAIN;
boxDrainActor.globalPose.t.set(0, 0, 0);
gScene->createActor(boxDrainActor);
//Pre cook hotspots
NxBounds3 precookAABB;
precookAABB.set(NxVec3(-20,-20,-20), NxVec3(20,20,20));
// gScene->cookFluidMeshHotspot(precookAABB, PACKET_SIZE_MULTIPLIER, REST_PARTICLES_PER_METER, KERNEL_RADIUS_MULTIPLIER, MOTION_LIMIT_MULTIPLIER, COLLISION_DISTANCE_MULTIPLIER );
//Create a set of initial particles
ParticleSDK* initParticles = new ParticleSDK[MAX_PARTICLES];
unsigned initParticlesNum = 0;
NxVec3 fluidPos(0, 11.6, 0);
float distance = 0.1f;
unsigned sideNum = 16;
float rad = sideNum*distance*0.5f;
for (unsigned i=0; i<sideNum; i++)
for (unsigned j=0; j<sideNum; j++)
for (unsigned k=0; k<sideNum; k++)
{
NxVec3 p = NxVec3(i*distance,j*distance,k*distance);
if (p.distance(NxVec3(rad,rad,rad)) < rad)
{
p += fluidPos;
ParticleSDK& newParticle = initParticles[initParticlesNum++];
newParticle.position = p;
newParticle.velocity = NxVec3(0,0,0);
}
}
//Setup structure to pass initial particles.
NxParticleData initParticleData;
initParticleData.numParticlesPtr = &initParticlesNum;
initParticleData.bufferPos = &initParticles[0].position.x;
initParticleData.bufferPosByteStride = sizeof(ParticleSDK);
initParticleData.bufferVel = &initParticles[0].velocity.x;
initParticleData.bufferVelByteStride = sizeof(ParticleSDK);
//Setup fluid descriptor
NxFluidDesc fluidDesc;
fluidDesc.maxParticles = initParticlesNum;
fluidDesc.kernelRadiusMultiplier = KERNEL_RADIUS_MULTIPLIER;
fluidDesc.restParticlesPerMeter = REST_PARTICLES_PER_METER;
fluidDesc.collisionDistanceMultiplier = COLLISION_DISTANCE_MULTIPLIER;
fluidDesc.stiffness = 50.0f;
fluidDesc.viscosity = 22.0f;
fluidDesc.damping = 0.0f;
fluidDesc.restitutionForStaticShapes = 0.4f;
fluidDesc.dynamicFrictionForStaticShapes = 0.03f;
fluidDesc.simulationMethod = NX_F_SPH; //NX_F_NO_PARTICLE_INTERACTION;
if (!gHardwareSimulation)
fluidDesc.flags &= ~NX_FF_HARDWARE;
fluidDesc.initialParticleData = initParticleData;
//Create user fluid.
//- create NxFluid in NxScene
//- setup the buffers to read from data from the SDK
//- set NxFluid::userData field to MyFluid instance
bool trackUserData = false;
bool provideCollisionNormals = false;
MyFluid* fluid = new MyFluid(gScene, fluidDesc, trackUserData, provideCollisionNormals, NxVec3(0.2f,0.3f,0.7f), 0.03f);
assert(fluid);
gMyFluids.pushBack(fluid);
delete[] initParticles;
gCameraPos.set(23, 14, 23);
gCameraForward = fluidPos - NxVec3(0, 3, 0) - gCameraPos;
gCameraForward.normalize();
}
void SampleCollision::cleanup()
{
//MyFluid cleaned up by ReleaseNx()
}
void SampleCollision::onKeyPress(unsigned char key, int x, int y)
{
switch (key)
{
case 'b':
CreateDynamicActors();
break;
default:
break;
}
}
void CreateDynamicActors()
{
WaitForPhysics();
// Add a dynamic sphere.
NxActorDesc sphereActor;
NxBodyDesc sphereBody;
NxSphereShapeDesc sphereShape;
sphereShape.radius = 0.4f;
sphereActor.shapes.pushBack(&sphereShape);
sphereActor.body = &sphereBody;
sphereActor.density = 1.0f;
sphereActor.globalPose.t.set(0.0f, 14.0f, 1.0f);
gScene->createActor(sphereActor);
// Add a dynamic capsule.
NxActorDesc capsActor;
NxCapsuleShapeDesc capsShape;
NxBodyDesc capsBody;
capsActor.shapes.pushBack(&capsShape);
capsActor.body = &capsBody;
capsActor.density = 1.0f;
capsActor.globalPose.t.set(3.0f, 10.0f, 8.0f);
gScene->createActor(capsActor);
// Add a dynamic box.
NxActorDesc boxActor;
NxBoxShapeDesc boxShape;
NxBodyDesc boxBody;
boxShape.dimensions.set(0.75f, 0.75f, 0.75f);
boxActor.shapes.pushBack(&boxShape);
boxActor.body = &boxBody;
boxActor.density = 1.0f;
boxActor.globalPose.t.set(2.0f, 15.0f, 7.0f);
gScene->createActor(boxActor);
}
|
tomorrow56/fw-AC63_BT_SDK
|
apps/common/third_party_profile/tuya_protocol/app/demo/tuya_ble_app_demo.c
|
<reponame>tomorrow56/fw-AC63_BT_SDK
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_main.h"
#include "tuya_ble_secure.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_sdk_version.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_event.h"
#include "tuya_ble_app_demo.h"
//#include "tuya_ble_demo_version.h"
#include "tuya_ble_log.h"
#include "tuya_ota.h"
#include "system/generic/printf.h"
#include "log.h"
#include "system/includes.h"
//#include "ota.h"
tuya_ble_device_param_t device_param = {0};
#define LED_PIN IO_PORTA_01
static bool tuya_led_state = 0;
static const char device_id_test[] = "tuya58253f7c8ed1";
static const char auth_key_test[] = "<KEY>";
static const uint8_t mac_test[6] = {0xDC, 0x23, 0x4D, 0x65, 0xB0, 0x66}; //The actual MAC address is : 66:55:44:33:22:11
#define APP_CUSTOM_EVENT_1 1
#define APP_CUSTOM_EVENT_2 2
#define APP_CUSTOM_EVENT_3 3
#define APP_CUSTOM_EVENT_4 4
#define APP_CUSTOM_EVENT_5 5
static uint8_t dp_data_array[255 + 3];
static uint16_t dp_data_len = 0;
typedef struct {
uint8_t data[50];
} custom_data_type_t;
void custom_data_process(int32_t evt_id, void *data)
{
custom_data_type_t *event_1_data;
TUYA_APP_LOG_DEBUG("custom event id = %d", evt_id);
switch (evt_id) {
case APP_CUSTOM_EVENT_1:
event_1_data = (custom_data_type_t *)data;
TUYA_APP_LOG_HEXDUMP_DEBUG("received APP_CUSTOM_EVENT_1 data:", event_1_data->data, 50);
break;
case APP_CUSTOM_EVENT_2:
break;
case APP_CUSTOM_EVENT_3:
break;
case APP_CUSTOM_EVENT_4:
break;
case APP_CUSTOM_EVENT_5:
break;
default:
break;
}
}
custom_data_type_t custom_data;
void custom_evt_1_send_test(uint8_t data)
{
tuya_ble_custom_evt_t event;
for (uint8_t i = 0; i < 50; i++) {
custom_data.data[i] = data;
}
event.evt_id = APP_CUSTOM_EVENT_1;
event.custom_event_handler = (void *)custom_data_process;
event.data = &custom_data;
tuya_ble_custom_event_send(event);
}
static uint16_t sn = 0;
static uint32_t time_stamp = 1587795793;
void tuya_data_init()
{
struct {
uint8_t id;
uint8_t type;
uint16_t len;
uint8_t data;
} p_dp_data;
p_dp_data.id = 1;
p_dp_data.type = 1;
p_dp_data.len = 0x0100;
p_dp_data.data = tuya_led_state;
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x03)
tuya_ble_dp_data_report(&p_dp_data, 5); //1
#endif
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x04)
tuya_ble_dp_data_send(sn, DP_SEND_TYPE_ACTIVE, DP_SEND_FOR_CLOUD_PANEL, DP_SEND_WITH_RESPONSE, &p_dp_data, 5);
#endif
}
void tuya_data_parse(tuya_ble_cb_evt_param_t *event)
{
uint8_t *buf = event->dp_received_data.p_data;
uint32_t sn = event->dp_received_data.sn;
put_buf(buf, event->dp_received_data.data_len);
struct {
uint8_t id;
uint8_t type;
uint16_t len;
uint8_t data;
} p_dp_data;
p_dp_data.id = buf[0];
p_dp_data.type = buf[1];
p_dp_data.len = 0x0100;
p_dp_data.data = buf[4];
printf("\n\n<-------------- tuya_data_parse -------------->");
printf("sn = %d, id = %d, type = %d, len = %d, data = %d", sn, p_dp_data.id, p_dp_data.type, p_dp_data.len, p_dp_data.data);
switch (buf[0]) {
case 1:
printf("tuya switch control, onoff set to: %d\n", p_dp_data.data);
tuya_led_state = p_dp_data.data;
gpio_direction_output(LED_PIN, tuya_led_state);
break;
//case 2:
//printf("tuya mode control, mode set to: %d\n", buf[3]);
//break;
default:
printf("unknow control msg len = %d, data:", buf[2]);
break;
}
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x03)
tuya_ble_dp_data_report(&p_dp_data, 5); //1
#endif
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x04)
tuya_ble_dp_data_send(sn, DP_SEND_TYPE_ACTIVE, DP_SEND_FOR_CLOUD_PANEL, DP_SEND_WITH_RESPONSE, &p_dp_data, 5);
#endif
}
static void tuya_cb_handler(tuya_ble_cb_evt_param_t *event)
{
int16_t result = 0;
printf("tuya cb_handler event->evt=0x%x\n", event->evt);
switch (event->evt) {
case TUYA_BLE_CB_EVT_CONNECTE_STATUS:
TUYA_APP_LOG_INFO("received tuya ble conncet status update event,current connect status = %d", event->connect_status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_RECEIVED:
tuya_data_parse(event);
break;
case TUYA_BLE_CB_EVT_DP_DATA_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data report response result code =%d", event->dp_response_data.status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_WTTH_TIME_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data report response result code =%d", event->dp_response_data.status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_WITH_FLAG_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data with flag report response sn = %d , flag = %d , result code =%d", event->dp_with_flag_response_data.sn, event->dp_with_flag_response_data.mode
, event->dp_with_flag_response_data.status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_WITH_FLAG_AND_TIME_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data with flag and time report response sn = %d , flag = %d , result code =%d", event->dp_with_flag_and_time_response_data.sn,
event->dp_with_flag_and_time_response_data.mode, event->dp_with_flag_and_time_response_data.status);
break;
case TUYA_BLE_CB_EVT_UNBOUND:
TUYA_APP_LOG_INFO("received unbound req");
break;
case TUYA_BLE_CB_EVT_ANOMALY_UNBOUND:
TUYA_APP_LOG_INFO("received anomaly unbound req");
break;
case TUYA_BLE_CB_EVT_DEVICE_RESET:
TUYA_APP_LOG_INFO("received device reset req");
break;
case TUYA_BLE_CB_EVT_DP_QUERY:
TUYA_APP_LOG_INFO("received TUYA_BLE_CB_EVT_DP_QUERY event");
if (dp_data_len > 0) {
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x03)
tuya_ble_dp_data_report(dp_data_array, dp_data_len);
#endif
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x04)
tuya_ble_dp_data_send(sn, DP_SEND_TYPE_ACTIVE, DP_SEND_FOR_CLOUD_PANEL, DP_SEND_WITH_RESPONSE, dp_data_array, dp_data_len);
#endif
}
break;
case TUYA_BLE_CB_EVT_OTA_DATA:
tuya_ota_proc(event->ota_data.type, event->ota_data.p_data, event->ota_data.data_len);
break;
case TUYA_BLE_CB_EVT_NETWORK_INFO:
TUYA_APP_LOG_INFO("received net info : %s", event->network_data.p_data);
tuya_ble_net_config_response(result);
break;
case TUYA_BLE_CB_EVT_WIFI_SSID:
break;
case TUYA_BLE_CB_EVT_TIME_STAMP:
TUYA_APP_LOG_INFO("received unix timestamp : %s ,time_zone : %d", event->timestamp_data.timestamp_string, event->timestamp_data.time_zone);
tuya_data_init();
break;
case TUYA_BLE_CB_EVT_TIME_NORMAL:
break;
case TUYA_BLE_CB_EVT_DATA_PASSTHROUGH:
TUYA_APP_LOG_HEXDUMP_DEBUG("received ble passthrough data :", event->ble_passthrough_data.p_data, event->ble_passthrough_data.data_len);
tuya_ble_data_passthrough(event->ble_passthrough_data.p_data, event->ble_passthrough_data.data_len);
break;
default:
TUYA_APP_LOG_WARNING("app_tuya_cb_queue msg: unknown event type 0x%04x", event->evt);
break;
}
tuya_ble_inter_event_response(event);
}
void tuya_ble_app_init(void)
{
device_param.device_id_len = 16; //If use the license stored by the SDK,initialized to 0, Otherwise 16 or 20.
int ret = 0;
device_param.use_ext_license_key = 1;
if (device_param.device_id_len == 16) {
memcpy(device_param.auth_key, (void *)auth_key_test, AUTH_KEY_LEN);
memcpy(device_param.device_id, (void *)device_id_test, DEVICE_ID_LEN);
memcpy(device_param.mac_addr.addr, mac_test, 6);
device_param.mac_addr.addr_type = TUYA_BLE_ADDRESS_TYPE_RANDOM;
}
device_param.p_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
device_param.product_id_len = 8;
memcpy(device_param.product_id, APP_PRODUCT_ID, 8);
device_param.firmware_version = TY_APP_VER_NUM;
device_param.hardware_version = TY_HARD_VER_NUM;
printf("HJY:12345\n");
tuya_ble_sdk_init(&device_param);
ret = tuya_ble_callback_queue_register(tuya_cb_handler);
y_printf("tuya_ble_callback_queue_register,ret=%d\n", ret);
//tuya_ota_init();
//TUYA_APP_LOG_INFO("demo project version : "TUYA_BLE_DEMO_VERSION_STR);
TUYA_APP_LOG_INFO("app version : "TY_APP_VER_STR);
}
|
vincenthcui/awesome-tencentcloud-go
|
tencentcloud/actions/fmu/2019-12-13/actions.go
|
package fmu
import "github.com/vincenthcui/awesome-tencentcloud-go/tencentcloud"
var (
TryLipstickPic = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "TryLipstickPic",
}
StyleImagePro = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "StyleImagePro",
}
StyleImage = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "StyleImage",
}
QueryBeautifyVideoJob = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "QueryBeautifyVideoJob",
}
GetModelList = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "GetModelList",
}
DeleteModel = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "DeleteModel",
}
CreateModel = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "CreateModel",
}
CancelBeautifyVideoJob = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "CancelBeautifyVideoJob",
}
BeautifyVideo = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "BeautifyVideo",
}
BeautifyPic = tencentcloud.Action{
Service: "fmu",
Version: "2019-12-13",
Action: "BeautifyPic",
}
)
|
leftmike/maho
|
storage/encode/key.go
|
<reponame>leftmike/maho<filename>storage/encode/key.go
package encode
import (
"fmt"
"math"
"github.com/leftmike/maho/sql"
"github.com/leftmike/maho/util"
)
const (
// The SQL values are encoded as a tag followed by a binary representation
// of the value.
NullKeyTag = 128
BoolKeyTag = 129
Int64NegKeyTag = 130
Int64NotNegKeyTag = 131
Float64NaNKeyTag = 140
Float64NegKeyTag = 141
Float64ZeroKeyTag = 142
Float64PosKeyTag = 143
Float64NaNReverseKeyTag = 144
StringKeyTag = 150
BytesKeyTag = 160
)
func encodeKeyBytes(buf []byte, bytes []byte, reverse bool) []byte {
n := len(buf)
for _, b := range bytes {
if b == 0 || b == 1 {
buf = append(buf, 1)
}
buf = append(buf, b)
}
buf = append(buf, 0)
if reverse {
for n < len(buf) {
buf[n] = ^buf[n]
n += 1
}
}
return buf
}
func MakeKey(key []sql.ColumnKey, row []sql.Value) []byte {
var buf []byte
for _, ck := range key {
val := row[ck.Column()]
reverse := ck.Reverse()
switch val := val.(type) {
case sql.BoolValue:
if reverse {
val = !val
}
buf = append(buf, BoolKeyTag)
if val {
buf = append(buf, 1)
} else {
buf = append(buf, 0)
}
case sql.StringValue:
buf = append(buf, StringKeyTag)
buf = encodeKeyBytes(buf, []byte(val), reverse)
case sql.BytesValue:
buf = append(buf, BytesKeyTag)
buf = encodeKeyBytes(buf, []byte(val), reverse)
case sql.Float64Value:
if reverse {
val = -val
}
if math.IsNaN(float64(val)) {
if reverse {
buf = append(buf, Float64NaNReverseKeyTag)
} else {
buf = append(buf, Float64NaNKeyTag)
}
} else if val == 0 {
buf = append(buf, Float64ZeroKeyTag)
} else {
u := math.Float64bits(float64(val))
if u&(1<<63) != 0 {
u = ^u
buf = append(buf, Float64NegKeyTag)
} else {
buf = append(buf, Float64PosKeyTag)
}
buf = util.EncodeUint64(buf, u)
}
case sql.Int64Value:
if reverse {
val = ^val
}
if val < 0 {
buf = append(buf, Int64NegKeyTag)
} else {
buf = append(buf, Int64NotNegKeyTag)
}
buf = util.EncodeUint64(buf, uint64(val))
default:
if val == nil {
buf = append(buf, NullKeyTag)
} else {
panic(fmt.Sprintf("unexpected type for sql.Value: %T: %v", val, val))
}
}
}
return buf
}
|
mrgypnocat/xipki
|
security/src/main/java/org/xipki/security/KeypairGenResult.java
|
/*
*
* Copyright (c) 2013 - 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xipki.security;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.xipki.util.Args;
/**
* Abstract class of the result of Keypair generation.
*
* @author <NAME>
* @since 2.0.0
*/
public class KeypairGenResult {
private final PrivateKeyInfo privateKey;
private final SubjectPublicKeyInfo publicKey;
public KeypairGenResult(PrivateKeyInfo privateKey, SubjectPublicKeyInfo publicKey) {
this.privateKey = Args.notNull(privateKey, "privateKey");
this.publicKey = Args.notNull(publicKey, "publicKey");
}
public PrivateKeyInfo getPrivateKey() {
return privateKey;
}
public SubjectPublicKeyInfo getPublicKey() {
return publicKey;
}
}
|
Vizzuality/heco-invest
|
backend/app/controllers/application_controller.rb
|
<reponame>Vizzuality/heco-invest<filename>backend/app/controllers/application_controller.rb<gh_stars>1-10
class ApplicationController < ActionController::Base
protected
def after_sign_out_path_for(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
if scope == :admin
new_admin_session_path
else
super
end
end
end
|
grischard/osmeditor4android
|
src/main/java/de/blau/android/util/ReadFile.java
|
package de.blau.android.util;
import java.io.Serializable;
import java.util.List;
import android.net.Uri;
public abstract class ReadFile implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Read a file
*
* @param fileUri Uri of the file to read
* @return true if sucessful
*/
public abstract boolean read(Uri fileUri);
/**
* Read multiple files, empty default implementation
*
* @param uris List of Uri to read
*/
public void read(List<Uri> uris) {
// empty
}
}
|
valentincostam/plande
|
components/NotFound.js
|
import { Heading } from '@chakra-ui/react';
export default function NotFound() {
return <Heading>404</Heading>;
}
|
lo-ca/arangodb
|
arangod/Graph/PathManagement/PathStore.h
|
<reponame>lo-ca/arangodb
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author <NAME>
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <queue>
#include <unordered_set>
#include "Basics/ResourceUsage.h"
#include "Basics/debugging.h"
#include <velocypack/Builder.h>
#include <velocypack/Slice.h>
namespace arangodb {
namespace aql {
struct AqlValue;
}
namespace graph {
template <class ProviderType, class Step>
class PathResult;
class ValidationResult;
/*
* Schreier element:
* {
* vertex: "<reference>",
* inboundEdge: "<reference>",
* previous: "<size_t"> // Index entry of prev. vertex
* }
*/
template <class StepType>
class PathStore {
public:
using Step = StepType;
public:
explicit PathStore(arangodb::ResourceMonitor& resourceMonitor);
~PathStore();
// @brief reset
void reset();
// @brief Method adds a new element to the schreier vector
// returns the index of inserted element
size_t append(Step step);
// @briefs Method returns a step at given position
Step getStep(size_t position) const;
// @briefs Method returns a step reference at given position
Step& getStepReference(size_t position);
// @brief returns the current vector size
size_t size() const { return _schreier.size(); }
auto visitReversePath(Step const& step,
std::function<bool(Step const&)> const& visitor) const -> bool;
auto modifyReversePath(Step& step, std::function<bool(Step&)> const& visitor) -> bool;
template <class PathResultType>
auto buildPath(Step const& vertex, PathResultType& path) const -> void;
template <class ProviderType>
auto reverseBuildPath(Step const& vertex, PathResult<ProviderType, Step>& path) const
-> void;
private:
/// @brief schreier vector to store the visited vertices
std::vector<Step> _schreier;
arangodb::ResourceMonitor& _resourceMonitor;
};
} // namespace graph
} // namespace arangodb
|
MislavStipetic/lymph
|
lymph/testing/mock_helpers.py
|
import functools
import unittest
from lymph.exceptions import RemoteError
from lymph.core.container import ServiceContainer
import mock
import hamcrest
class MockMixins(object):
def _assert_equal_calls(self, actual_calls, expected_calls):
actual_count, expected_count = len(actual_calls), len(expected_calls)
# TODO(Mouad): Add in the message which calls are missing.
self.assertEqual(
expected_count, actual_count,
msg="number of calls doesn't match, expected %d actual %d" % (expected_count, actual_count))
for pos, (actual_call, expected_call) in enumerate(zip(actual_calls, expected_calls)):
success, msg = self._check_equal_call(actual_call, expected_call)
if not success:
self.fail("function #%d %s" % (pos, msg))
def _check_equal_call(self, actual_call, expected_call):
act_name, act_args, act_kwargs = self._unpack_mock_call(actual_call)
exp_name, exp_args, exp_kwargs = self._unpack_mock_call(expected_call)
if exp_name != act_name:
return False, "name doesn't match, expected %r actual %r" % (exp_name, act_name)
success, msg = self._check_equal_arguments(act_args, exp_args)
if not success:
return False, msg
return self._check_equal_keyword_arguments(act_kwargs, exp_kwargs)
@staticmethod
def _unpack_mock_call(mock_call):
# Since we are using the syntax mock.call('<func_name>', arg1, arg2, kw1=val1),
# in this case the unpacking of mock.call will put the <func_name> in args[0] and not
# in the first unpacked element.
_, args, kwargs = mock_call
name, args = args[0], args[1:]
return name, args, kwargs
def _check_equal_arguments(self, actual_args, expected_args):
if len(actual_args) != len(expected_args):
return False, "arguments count doesn't match, expected %r actual %r" % (len(expected_args), len(actual_args))
for pos, (actual_arg, expected_arg) in enumerate(zip(actual_args, expected_args)):
success, msg = self._check_that(actual_arg, hamcrest.is_(expected_arg))
if not success:
return False, "argument #%d doesn't match, %s" % (pos, msg)
return True, None
def _check_equal_keyword_arguments(self, actual_kwargs, expected_kwargs):
actual_arg_names = sorted(actual_kwargs.keys())
expected_arg_names = sorted(expected_kwargs.keys())
if actual_arg_names != expected_arg_names:
return False, "keyword arguments doesn't match, expected %r actual %r" % (expected_arg_names, actual_arg_names)
for name, act_value in actual_kwargs.items():
success, msg = self._check_that(act_value, hamcrest.is_(expected_kwargs[name]))
if not success:
return False, "keyword argument %r doesn't match, %s" % (name, msg)
return True, None
@staticmethod
def _check_that(actual, expected):
try:
hamcrest.assert_that(actual, expected)
except AssertionError as ex:
msg = ex.args[0]
return False, msg
return True, None
def _assert_equal_any_calls(self, actual_calls, expected_calls):
next_idx = 0
for exp_call in expected_calls:
name, _, _ = self._unpack_mock_call(exp_call)
possible_matches = self._get_same_named_calls(actual_calls, name, start_idx=next_idx)
if not possible_matches:
self.fail("Call '%r' wasn't found." % (exp_call, ))
elif len(possible_matches) == 1:
# In case we have one possible match, use _assert_equal_calls to have
# a better error message.
match_idx, actual_call = possible_matches[0]
self._assert_equal_calls([actual_call], [exp_call])
else:
match_idx = self._assert_match_one_call(possible_matches, exp_call)
next_idx = match_idx + 1
def _get_same_named_calls(self, actual_calls, name, start_idx=0):
matches = []
for i, act_call in enumerate(actual_calls[start_idx:]):
act_name, _, _ = self._unpack_mock_call(act_call)
if name == act_name:
matches.append((i + start_idx, act_call))
return matches
def _assert_match_one_call(self, actual_calls, exp_call):
for idx, act_call in actual_calls:
success, _ = self._check_equal_call(act_call, exp_call)
if success:
return idx
msg = "Call '%r' wasn't found." % (exp_call, )
if actual_calls:
msg += " Maybe you want: \n%s" % "\n".join(map(str, actual_calls))
self.fail(msg)
class FakeChannel(object):
class Reply(object):
def __init__(self, body):
self.body = body
def __init__(self, result, request):
self.request = request
self.result = result
def get(self, **_):
if isinstance(self.result, Exception):
raise getattr(RemoteError, self.result.__class__.__name__)('', '')
if callable(self.result):
body = self.result(**self.request)
else:
body = self.result
return self.Reply(body)
def _get_rpc_mock(rpc_mocks=None, original=ServiceContainer.send_request):
class RequestSender(mock.MagicMock):
rpc_functions = rpc_mocks or {}
def __call__(self, container, address, subject, body, version=None):
# XXX (Mouad): We need to call MagicMock __call__ here else calls
# will not be tracked, and we do it for all calls mocked or not.
super(RequestSender, self).__call__(subject, **body)
try:
result = self.rpc_functions[subject]
except KeyError:
return original(container, address, subject, body)
return FakeChannel(result, body)
def __get__(self, obj, type=None):
return functools.partial(self.__call__, obj)
return RequestSender()
class RpcMockTestCase(unittest.TestCase, MockMixins):
def setUp(self):
super(RpcMockTestCase, self).setUp()
self.rpc_patch = mock.patch.object(ServiceContainer, 'send_request', new_callable=_get_rpc_mock)
self.rpc_mock = self.rpc_patch.start()
def tearDown(self):
super(RpcMockTestCase, self).tearDown()
self.rpc_patch.stop()
def setup_rpc_mocks(self, rpc_functions):
self.rpc_mock.rpc_functions.update(rpc_functions)
def update_rpc_mock(self, func_name, return_value):
self.rpc_mock.rpc_functions[func_name] = return_value
def delete_rpc_mock(self, func_name):
del self.rpc_mock.rpc_functions[func_name]
@property
def rpc_mock_calls(self):
return self.rpc_mock.mock_calls
def assert_rpc_calls(self, *expected_calls):
self._assert_equal_calls(self.rpc_mock_calls, expected_calls)
def assert_any_rpc_calls(self, *expected_calls):
self._assert_equal_any_calls(self.rpc_mock_calls, expected_calls)
class EventMockTestCase(unittest.TestCase, MockMixins):
def setUp(self):
super(EventMockTestCase, self).setUp()
self.event_patch = mock.patch.object(ServiceContainer, 'emit_event')
self.event_mock = self.event_patch.start()
def tearDown(self):
super(EventMockTestCase, self).tearDown()
self.event_patch.stop()
@property
def events(self):
return self.event_mock.mock_calls
def assert_events_emitted(self, *expected_emitted):
expected_emitted_with_delay = []
for call in expected_emitted:
name, args, kwargs = self._unpack_mock_call(call)
kwargs.setdefault('delay', 0)
expected_emitted_with_delay.append(mock.call(name, *args, **kwargs))
self._assert_equal_calls(self.events, expected_emitted_with_delay)
|
atomorojo/PetSitters-1
|
src/main/java/PetSitters/security/VerificationTokenService.java
|
package PetSitters.security;
import PetSitters.auxiliary.ReadWebPage;
import PetSitters.entity.UserPetSitters;
import PetSitters.repository.UserRepository;
import PetSitters.repository.VerificationTokenRepository;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static PetSitters.security.Constants.*;
@Service
public class VerificationTokenService {
private UserRepository userRepository;
private VerificationTokenRepository verificationTokenRepository;
private SendingMailService sendingMailService;
@Autowired
public VerificationTokenService(UserRepository userRepository, VerificationTokenRepository verificationTokenRepository, SendingMailService sendingMailService) {
this.userRepository = userRepository;
this.verificationTokenRepository = verificationTokenRepository;
this.sendingMailService = sendingMailService;
}
public void createVerification(String email) {
UserPetSitters user = userRepository.findByEmail(email);
VerificationToken verificationToken = verificationTokenRepository.findByEmail(email);
if (verificationToken == null) {
verificationToken = new VerificationToken();
verificationToken.setUsername(user.getUsername());
verificationToken.setEmail(email);
verificationTokenRepository.save(verificationToken);
}
sendingMailService.sendVerificationMail(email, verificationToken.getToken());
}
public ResponseEntity<String> verifyEmail(String token) throws IOException {
List<VerificationToken> verificationTokens = verificationTokenRepository.findByToken(token);
if (verificationTokens.isEmpty()) {
ReadWebPage read = new ReadWebPage();
Map<String, String> data = new HashMap<>();
data.put("error", "Invalid token.");
String formattedString = read.getProcessedText(ERROR_EMAIL_CONFIRMATION_WEB_PAGE_PATH, data);
return ResponseEntity.badRequest().body(formattedString);
}
VerificationToken verificationToken = verificationTokens.get(0);
if (verificationToken.getExpiredDateTime().isBefore(LocalDateTime.now())) {
ReadWebPage read = new ReadWebPage();
Map<String, String> data = new HashMap<>();
data.put("error", "Expired token.");
String formattedString = read.getProcessedText(ERROR_EMAIL_CONFIRMATION_WEB_PAGE_PATH, data);
return ResponseEntity.badRequest().body(formattedString);
}
verificationToken.setConfirmedDateTime(LocalDateTime.now());
verificationToken.setStatus(VerificationToken.STATUS_VERIFIED);
UserPetSitters user = userRepository.findByUsername(verificationToken.getUsername());
user.setActive(true);
userRepository.save(user);
verificationTokenRepository.delete(verificationToken);
ReadWebPage read = new ReadWebPage();
String htmlPage = read.getText(OK_EMAIL_CONFIRMATION_WEB_PAGE_PATH);
return ResponseEntity.ok(htmlPage);
}
}
|
geaviation/shiny
|
vendor/R/lib/R/include/R_ext/Itermacros.h
|
<reponame>geaviation/shiny
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 2001-12 The R Core Team.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, a copy is available at
* http://www.r-project.org/Licenses/
*/
/*
Macros to help defining vectorized functions with proper recycling
and periodic interrupt checks.
*/
#ifndef R_EXT_ITERMACROS_H_
#define R_EXT_ITERMACROS_H_
#define LOOP_WITH_INTERRUPT_CHECK(LOOP, ncheck, n, ...) do { \
for (size_t __intr_threshold__ = ncheck; \
TRUE; \
__intr_threshold__ += ncheck) { \
size_t __intr_end__ = n < __intr_threshold__ ? \
n : __intr_threshold__; \
LOOP(__intr_end__, __VA_ARGS__); \
if (__intr_end__ == n) break; \
else R_CheckUserInterrupt(); \
} \
} while (0)
#define R_ITERATE_CORE(n, i, loop_body) do { \
for (; i < n; ++i) { loop_body } \
} while (0)
#define R_ITERATE(n, i, loop_body) do { \
i = 0; \
R_ITERATE_CORE(n, i, loop_body); \
} while (0)
#define R_ITERATE_CHECK(ncheck, n, i, loop_body) do { \
i = 0; \
LOOP_WITH_INTERRUPT_CHECK(R_ITERATE_CORE, ncheck, n, i, loop_body); \
} while (0)
#define MOD_ITERATE_CORE(n, n1, n2, i, i1, i2, loop_body) do { \
for (; i < n; \
i1 = (++i1 == n1) ? 0 : i1, \
i2 = (++i2 == n2) ? 0 : i2, \
++i) { \
loop_body \
} \
} while (0)
#define MOD_ITERATE(n, n1, n2, i, i1, i2, loop_body) do { \
i = i1 = i2 = 0; \
MOD_ITERATE_CORE(n, n1, n2, i, i1, i2, loop_body); \
} while (0)
#define MOD_ITERATE_CHECK(ncheck, n, n1, n2, i, i1, i2, loop_body) do { \
i = i1 = i2 = 0; \
LOOP_WITH_INTERRUPT_CHECK(MOD_ITERATE_CORE, ncheck, n, \
n1, n2, i, i1, i2, loop_body); \
} while (0)
#define MOD_ITERATE3_CORE(n, n1, n2, n3, i, i1, i2, i3, loop_body) do { \
for (; i < n; \
i1 = (++i1 == n1) ? 0 : i1, \
i2 = (++i2 == n2) ? 0 : i2, \
i3 = (++i3 == n3) ? 0 : i3, \
++i) { \
loop_body \
} \
} while (0)
#define MOD_ITERATE3(n, n1, n2, n3, i, i1, i2, i3, loop_body) do { \
i = i1 = i2 = i3 = 0; \
MOD_ITERATE3_CORE(n, n1, n2, n3, i, i1, i2, i3, loop_body); \
} while (0)
#define MOD_ITERATE3_CHECK(ncheck, n, n1, n2, n3, i, i1, i2, i3, loop_body) \
do { \
i = i1 = i2 = i3 = 0; \
LOOP_WITH_INTERRUPT_CHECK(MOD_ITERATE3_CORE, ncheck, n, \
n1, n2, n3, i, i1, i2, i3, loop_body); \
} while (0)
#define MOD_ITERATE4_CORE(n, n1, n2, n3, n4, i, i1, i2, i3, i4, loop_body) \
do { \
for (; i < n; \
i1 = (++i1 == n1) ? 0 : i1, \
i2 = (++i2 == n2) ? 0 : i2, \
i3 = (++i3 == n3) ? 0 : i3, \
i4 = (++i4 == n4) ? 0 : i4, \
++i) { \
loop_body \
} \
} while (0)
#define MOD_ITERATE4(n, n1, n2, n3, n4, i, i1, i2, i3, i4, loop_body) do { \
i = i1 = i2 = i3 = i4 = 0; \
MOD_ITERATE4_CORE(n, n1, n2, n3, n4, i, i1, i2, i3, i4, loop_body); \
} while (0)
#define MOD_ITERATE4_CHECK(ncheck, n, n1, n2, n3, n4, i, i1, i2, i3, i4, \
loop_body) \
do { \
i = i1 = i2 = i3 = i4 = 0; \
LOOP_WITH_INTERRUPT_CHECK(MOD_ITERATE4_CORE, ncheck, n, \
n1, n2, n3, n4, \
i, i1, i2, i3, i4, loop_body); \
} while (0)
#define MOD_ITERATE5_CORE(n, n1, n2, n3, n4, n5, i, i1, i2, i3, i4, i5, \
loop_body) \
do { \
for (; i < n; \
i1 = (++i1 == n1) ? 0 : i1, \
i2 = (++i2 == n2) ? 0 : i2, \
i3 = (++i3 == n3) ? 0 : i3, \
i4 = (++i4 == n4) ? 0 : i4, \
i5 = (++i5 == n5) ? 0 : i5, \
++i) { \
loop_body \
} \
} while (0)
#define MOD_ITERATE5(n, n1, n2, n3, n4, n5, i, i1, i2, i3, i4, i5, loop_body) \
do { \
i = i1 = i2 = i3 = i4 = i5 = 0; \
MOD_ITERATE5_CORE(n, n1, n2, n3, n4, n5, i, i1, i2, i3, i4, i5, \
loop_body); \
} while (0)
#define MOD_ITERATE5_CHECK(ncheck, n, n1, n2, n3, n4, n5, \
i, i1, i2, i3, i4, i5, \
loop_body) \
do { \
i = i1 = i2 = i3 = i4 = i5 = 0; \
LOOP_WITH_INTERRUPT_CHECK(MOD_ITERATE5_CORE, ncheck, n, \
n1, n2, n3, n4, n5, \
i, i1, i2, i3, i4, i5, loop_body); \
} while (0)
#endif /* R_EXT_ITERMACROS_H_ */
|
soerenkoenig/owl
|
owl/scene/node.hpp
|
<filename>owl/scene/node.hpp
//
// .___.
// {o,o}
// ./)_)
// owl --"-"---
//
// Copyright © 2017 <NAME>. All rights reserved.
//
#pragma once
#include <memory>
#include <functional>
#include "owl/optional.hpp"
#include "owl/math/matrix.hpp"
#include "owl/math/euler_angles.hpp"
#include "owl/math/trafos.hpp"
#include "owl/math/quaternion.hpp"
#include "owl/scene/light.hpp"
#include "owl/scene/camera.hpp"
#include "owl/scene/material.hpp"
#include "owl/scene/geometry.hpp"
#include "owl/scene/animation.hpp"
namespace owl
{
namespace scene
{
template<typename Scalar, typename Color>
class node
{
public:
math::matrix<Scalar,4,4> local_to_parent() const
{
return math::translate<Scalar>(position) * math::square_matrix<Scalar,4>(orientation) * math::scale<Scalar,4>(scale);
}
math::matrix<Scalar,4,4> local_to_world() const
{
if(is_root())
return local_to_parent();
else
return parent_->local_to_world() * local_to_parent();
}
math::matrix<Scalar,4,4> world_to_local() const
{
return math::invert(local_to_world());
}
math::vector4<Scalar> convert(const math::vector4<Scalar>& v,
const node* to = nullptr) const
{
if(!to)
return local_to_world() * v;
return to->world_to_local() * local_to_world() * v;
}
math::vector3<Scalar> convert_position(const math::vector3<Scalar>& pos,
const node* to = nullptr) const
{
math::vector4<Scalar> pos_h;
pos_h << pos, 1;
pos_h = convert(pos_h);
return math::vector3<Scalar>(pos_h.x(), pos_h.y(), pos_h.z());
}
math::vector3<Scalar> convert_direction(const math::vector3<Scalar>& dir,
const node* to = nullptr) const
{
math::vector4<Scalar> dir_h;
dir_h << dir, 0;
dir_h = convert(dir_h);
return math::vector3<Scalar>(dir_h.x(),dir_h.y(), dir_h.z());
}
template <typename... Args>
node& add_child(Args&&... args)
{
children.emplace_back(std::forward<Args>(args)...);
auto& child = children.back();
child.parent_ = this;
return child;
}
bool is_root() const
{
return parent_;
}
const node* parent() const
{
return parent_;
}
std::string name;
std::shared_ptr<light<Scalar,Color>> light;
std::shared_ptr<camera<Scalar>> camera;
std::shared_ptr<geometry<Scalar>> geometry;
std::shared_ptr<material<Scalar>> material;
math::quaternion<Scalar> orientation;
math::vector<Scalar,3> position;
math::vector<Scalar,3> scale;
std::vector<node<Scalar,Color>> children;
std::vector<std::function<void(node&)>> constraints;
private:
node* parent_ = nullptr;
std::vector<animation<Scalar>> animations_;
};
}
}
|
willj/kaboom
|
sample/assetMap.js
|
var assetMap = [];
assetMap.push({
fileType: "Image",
fileName: "pigeon.png",
sprites: [
{
name: "leftPigeon",
startX: 0,
startY: 0,
width: 99,
height: 70,
states: {
initial: [0,"initial"],
fadeAndDie: [1,2,3,"die"]
}
},
{
name: "rightPigeon",
startX: 0,
startY: 70,
width: 99,
height: 70,
states: {
initial: [0,"initial"],
fadeAndDie: [1,2,3,"die"]
}
}
]
});
assetMap.push({
fileType: "Image",
fileName: "charsprite.png",
sprites: [
{
name: "yellow",
startX: 0,
startY: 0,
width: 88,
height: 80,
states: {
initial: [0,"initial"],
fadeAndDie: [1,2,3,"die"]
}
},
{
name: "blue",
startX: 0,
startY: 80,
width: 88,
height: 80,
states: {
initial: [0,"initial"],
fadeAndDie: [1,2,3,"die"]
}
},
{
name: "red",
startX: 0,
startY: 160,
width: 88,
height: 80,
states: {
initial: [0,"initial"],
fadeAndDie: [1,2,3,"die"]
}
}
]
});
assetMap.push({ fileType: "Sound", fileName: "quack.mp3", name: "quack" });
|
mintproject/topoflow
|
topoflow/utils/CMI_base.py
|
<reponame>mintproject/topoflow
#
# NOTE: This is not currently used. See emeli.py in frameworks folder.
#
# Copyright (c) 2010-2012, <NAME>
#
# February 2012 (Complete CMI, starting from CSDMS_base.py.)
#
#-----------------------------------------------------------------------
#
# Notes: This file defines a "base class" with a CMI (Component
# Model Interface) for CSDMS "process" components. These
# methods allow a CSDMS component written in Python to
# communicate with other CSDMS components and to be used
# within a CSDMS/CCA framework.
#
# CMI methods often call BMI (Basic Model Interface) methods.
# The BMI interface is designed to be completely framework
# independent, and therefore contains no methods related to
# CCA framework concepts such as ports.
#
# Some "private" utility methods are defined at the end.
#
#-----------------------------------------------------------------------
#
# unit_test()
#
# class CMI_component
#
# __init__()
#
# --------------------------------------------
# CMI methods related to ports and framework
# --------------------------------------------
# set_services() # (not a CMI method)
# release_services() # (not a CMI method)
# get_cca_port_info()
# get_cca_ports()
# release_cca_ports()
#
# -----------------------------------
# CMI/BMI methods to get model info
# -----------------------------------
# get_status()
# set_status()
# get_mode()
# set_mode()
# get_attribute() # (component and model attributes)
#
# --------------------------------------
# CMI/BMI methods to get variable info
# --------------------------------------
# get_values()
# set_values()
# get_values_at_indices()
# set_values_at_indices()
# -------------------------
# get_input_var_names()
# get_output_var_names()
# -------------------------
# get_var_rank()
# get_var_type()
# get_var_units()
#
# ----------------------------------
# CMI/BMI methods to get grid info
# ----------------------------------
# get_grid_shape()
# get_grid_spacing()
# get_grid_lower_left_corner()
# get_grid_attribute() ### NEW CMI METHOD ??
#
# ----------------------------------
# CMI/BMI methods to get time info
# ----------------------------------
# get_time_step()
# get_time_units()
# get_time() (current, start, or stop)
# get_start_time()
# get_current_time()
# get_end_time()
#
# --------------------------------------
# CMI methods for fine-grained control
# --------------------------------------
# initialize()
# run_until()
# run_for()
# finalize()
# ------------------
# run_model() # (not required for CMI)
# go()
#
# ------------------------------
# Private methods or utilities
# ------------------------------
# check_finished() # (called by run_model(), update().)
# print_traceback()
#
#-----------------------------------------------------------------------
# import BMI_base
from topoflow.components import topoflow_driver
import sys
import traceback
# import numpy as np
# import os
# import time
## import edu.csdms.models.IRFPort # (in IMPL file only)
## import edu.csdms.tools.ConfigDialog
## import edu.csdms.tools.IRFPortQueue
## import edu.csdms.tools.PrintQueue
## import edu.csdms.tools.TemplateFiles
#-----------------------------------------------------------------------
def unit_test():
c = CMI_component()
print 'Instantiated CMI component.'
# unit_test()
#-----------------------------------------------------------------------
### class CMI_component( BMI_base.BMI_component ):
class CMI_component:
#-------------------------------------------------------------------
def __init__(self):
self.bmi = topoflow_driver.topoflow_driver()
## ## self.DEBUG = True
## self.DEBUG = False
## self.SKIP_ERRORS = False
## self.SILENT = True # (new default: 11/16/11)
## self.REPORT = False
## self.DONE = False
## self.status = 'created' # (OpenMI 2.0 conventions)
##
## self.in_directory = None
## self.out_directory = None
## self.site_prefix = None
## self.case_prefix = None
## self.comp_status = 'Enabled'
##
## # __init__()
#-------------------------------------------------------------------
def set_services( self, services ):
#-------------------------------------------------------
# Notes: This is to be called by IMPL's setServices(),
# similar to how boccaSetServices() is called.
#-------------------------------------------------------
#-----------------------
# Get model attributes
#-----------------------
comp_name = self.bmi.get_attribute( 'comp_name' )
gui_xml_file = self.bmi.get_attribute( 'gui_xml_file' )
dialog_title = self.bmi.get_attribute( 'dialog_title' )
self.mode = 'nondriver' # (default)
try:
print 'SUCCESS:', comp_name, 'component status =', self.bmi.get_status()
except:
print 'FAILURE:', comp_name, 'component has not been instantiated yet.'
return # (do not return a value)
#-------------------------------------------------------
# Call the function that creates the tabbed-dialog GUI
#-------------------------------------------------------
# user_input is an object of type gov.cca.TypeMap
#-------------------------------------------------------
button_label = 'Configure'
dialog_tool = edu.csdms.tools.ConfigDialog.ConfigDialog()
dialog_tool.make_dialog( services, gui_xml_file, button_label, dialog_title )
self.user_input = dialog_tool.get_user_input()
# self.bmi.get_user_input( services, self.d_services )
# set_services()
#-------------------------------------------------------------------
def release_services( self, services ):
#--------------------------------------------------------
# Notes: This is to be called by IMPL's setServices(),
# similar to how boccaReleaseServices is called.
# But we aren't doing anything in IMPL file yet.
#--------------------------------------------------------
pass
# release_services()
#-------------------------------------------------------------------
def get_cca_port_info(self):
#-------------------------------------------------------
# Read required CCA port names from a file?
# This is done already by the PortQueue service class.
#-------------------------------------------------------
self.cca_port_names = ['']
self.cca_port_short = ['']
self.cca_port_type = "IRFPort"
self.cca_project = "edu.csdms.models"
## self.cca_project = "edu.csdms.ports"
# get_cca_port_info()
#-------------------------------------------------------------------
def get_cca_ports(self, d_services):
#-------------------------------------------------------------
# Example call in initialize method of "TopoFlow_Impl.py":
#
# OK = self.tf.get_cca_ports( self.d_services )
# if not(OK): return -1
#-------------------------------------------------------------
# print 'CALLING get_cca_ports()...'
############################################
self.get_cca_port_info()
############################################
port_names = self.cca_port_names
short_names = self.cca_port_short
port_type = self.cca_port_type
project_name = self.cca_project
exec("import " + project_name)
#--------------------------------------------
# Does this component have any uses ports ?
#--------------------------------------------
if (port_names[0] == ''):
if (self.DEBUG):
print '------------------------------------------'
print 'NOTE: This component has no uses ports.'
print '------------------------------------------'
SUCCESS = True
return SUCCESS
#--------------------------------------------
# Note: Use "d_services" added by Bocca to
# an Impl file to get a CCA port
#--------------------------------------------
SUCCESS = True
str2 = project_name + "." + port_type + "." + port_type
str3 = "( port )"
for k in xrange(len(port_names)):
#-----------------------------------
# Try to get a "generic" CCA port.
#-----------------------------------
name = port_names[k]
name_str = '"' + name + '".'
try:
port = d_services.getPort( name )
print "SUCCESS: Got CCA port: " + name_str
## print "*** type(port) =", type(port)
except:
print '#####################################################'
print ' ERROR: Unable to get CCA port named: ' + name_str
print ' '
print ' Please select a component from the palette that'
print ' provides a port named ' + name_str
print '#####################################################'
print ' '
## message = "FAILURE: Unable to get CCA port: " + name
## print message
port = None
SUCCESS = False
if not(SUCCESS):
break
#------------------------------------------
# Try to typecast the port to "port_type"
# and then store it within "self"
#------------------------------------------
### str1 = "self." + short_names[k]
str1 = "self.bmi." + short_names[k] ############## (3/12/12)
exec( str1 + " = " + str2 + str3 )
exec( "UNABLE = (" + str1 + " == None)" )
if (UNABLE):
print 'FAILURE: Unable to cast CCA port: ' + name
exec( "d_services.releasePort( " + name + " )")
SUCCESS = False
return SUCCESS
# get_cca_ports()
#-------------------------------------------------------------------
def release_cca_ports(self, d_services):
#----------------------
# Release all ports
#----------------------
for name in self.cca_port_names:
d_services.releasePort( name )
# release_cca_ports()
#-------------------------------------------------------------------
def get_status( self ):
#-----------------------------------------------------
# Notes: Return component status as a string. The
# possible return values are from OpenMI 2.0:
#
# created, initializing, initialized,
# updating, updated, finalizing, finalized,
# failed (could add "stopped").
#-----------------------------------------------------
return self.bmi.get_status()
# get_status()
#-------------------------------------------------------------------
def set_status( self, status ):
#-----------------------------------------------------
# Note: Valid values for the status string are:
#
# created, initializing, initialized,
# updating, updated, finalizing, finalized,
# failed (could add "stopped").
# Could check if valid before setting.
#-----------------------------------------------------
self.status = status
# set_status()
#-------------------------------------------------------------------
def get_mode( self ):
#-------------------------------------------------------
# Maybe get mode string from get_attribute() instead ?
#-------------------------------------------------------
return self.mode # ('driver' or 'nondriver')
# get_mode()
#-------------------------------------------------------------------
def set_mode( self, mode ):
mode_list = ['driver', 'nondriver']
if (mode.lower() in mode_list):
self.mode = mode.lower() # (store directly into self ??)
else:
print '################################################'
print ' ERROR: In CMI_base.set_mode():'
print ' Mode must be "driver" or "nondriver".'
print '################################################'
print ' '
#############################################
# Should we also set mode at BMI level ??
#############################################
# self.bmi.set_mode( 'driver' )
# set_mode()
#-------------------------------------------------------------------
def get_attribute( self, att_name ):
#------------------------------------------------------------
# Note: There is a BMI.get_attribute() method, but perhaps
# this one should read component-specific attributes
# from a config file (vs. model-specific).
#------------------------------------------------------------
try:
#----------------------------------------------
# This will work for model attributes, like:
# model_name, version, time_step_type,
# time_units, mesh_type, author_name, etc.
#----------------------------------------------
return self.bmi.get_attribute( att_name )
except:
pass
#--------------------------------------------------
# Read key-value pairs from a file and then build
# a dictionary like this ??
#--------------------------------------------------
amap = {'comp_name': 'ErodeGlobal',
'model_family': 'Erode',
## 'cfg_extension': '_erode_global.cfg', # (In BMI-level ??)
'cmt_var_prefix': '/ErodeGlobal/Input/Var/',
'cfg_template_file': 'Erode_Global.cfg.in',
'gui_xml_file': '/home/csdms/cca/erode/0.5/src/share/cmt/gui/Erode_Global.xml',
'dialog_title': 'LEM: Erode Global-Timestep Parameters' }
try:
return amap[ att_name.lower() ]
except:
print '#####################################################'
print ' ERROR: Could not find CMI attribute: ' + att_name
print '#####################################################'
print ' '
# get_attribute()
#-------------------------------------------------------------------
#-------------------------------------------------------------------
def get_values( self, long_var_name ):
#---------------------------------------------------------
# Note: This method returns a NumPy "ndarray" object
# that Babel is able to pass to other components
# as a SIDL generic array.
#---------------------------------------------------------
# The functions called by this one below are "port
# functions" (or methods) and therefore have
# static return types.
#---------------------------------------------------------
# This component (self) often won't have a port
# connection to the caller and so can't call the
# methods of its caller. Regridding and unit
# conversion is done by PortQueue just prior to
# calling CMT.set_values().
#---------------------------------------------------------
return self.bmi.get_values( long_var_name )
# try:
# #----------------------------------------------
# # Get data type and rank for long_var_name.
# # Assume that NumPy dtype string is returned.
# #----------------------------------------------
# type_name = self.bmi.get_var_type( long_var_name )
# rank = self.bmi.get_var_rank( long_var_name )
#
# #-----------------------------------------------------------
# # Call the appropriate BMI method. We could do this other
# # ways in Python, but this is the general approach.
# #-----------------------------------------------------------
# if (type_name == 'float64'):
# if (rank == 0):
# values = self.bmi.get_0d_double( long_var_name )
# elif (rank == 1):
# values = self.bmi.get_1d_double( long_var_name )
# elif (rank == 2):
# values = self.bmi.get_2d_double( long_var_name )
# elif (rank == 3):
# values = self.bmi.get_3d_double( long_var_name )
# ## elif (rank == 4):
# ## values = self.bmi.get_4d_double( long_var_name )
# #-------------------------------------------------------------
# elif (type_name == 'int32'):
# if (rank == 0):
# values = self.bmi.get_0d_int( long_var_name )
# elif (rank == 1):
# values = self.bmi.get_1d_int( long_var_name )
# elif (rank == 2):
# values = self.bmi.get_2d_int( long_var_name )
# elif (rank == 3):
# values = self.bmi.get_3d_int( long_var_name )
# ## elif (rank == 4):
# ## values = self.bmi.get_4d_int( long_var_name )
# #-------------------------------------------------------------
# else:
# print '############################################'
# print ' ERROR: In CMI_base.get_values():'
# print ' Type_name of "' + type_name + '"'
# print ' is not yet supported.'
# print '############################################'
# print ' '
#
# #-----------------------------------------------
# # Return values on this component's own grid
# # and with its own units for variables.
# # Set values will do conversions when needed ?
# #-----------------------------------------------
# return values
#
# except:
# print '######################################'
# print ' ERROR: In CMI_base.get_values():'
# print ' A BMI method call failed.'
# print ' Returning a value of zero.'
# print '######################################'
# print ' '
# return np.float64( 0 )
# get_values()
#-------------------------------------------------------------------
def set_values( self, long_var_name, values ):
self.bmi.set_values( long_var_name, values )
# #----------------------------------------------
# # Get data type and rank for long_var_name.
# # Assume that NumPy dtype string is returned.
# #----------------------------------------------
# dtype = self.bmi.get_var_type( long_var_name )
# rank = self.bmi.get_var_rank( long_var_name )
#
# #---------------------------------------------
# # Check data type and rank for input values.
# #---------------------------------------------
# val_dtype = str( values.dtype )
# val_rank = np.ndim( values )
#
# if (val_rank != rank):
# print '#############################################'
# print ' ERROR: In CMI_base.set_values():'
# print ' Rank of values does not match the'
# print ' rank of target variable named:'
# print ' ' + long_var_name
# print '#############################################'
# print ' '
# return
#
# if (val_dtype != dtype):
# #------------------------------------
# # Attempt to cast values to dtype ?
# #------------------------------------
# new_vals = values.astype( dtype )
# else:
# new_vals = values
#
# #------------------------------------------------------------------
# # First check the type of the data that is stored in the
# # generic array. Cast the generic array to a SIDL array of
# # that type. Call the appropriate BMI set_value function and
# # pass it a pointer to the start of the data. This is pseudo
# # code that looks more or less like what it would be in C.
# # The underlying data is contiguous in memory and of unit stride.
# #------------------------------------------------------------------
# if (dtype == 'float64'):
# if (rank == 0):
# self.bmi.set_0d_double( long_var_name, new_vals )
# elif (rank == 1):
# self.bmi.set_1d_double( long_var_name, new_vals )
# elif (rank == 2):
# self.bmi.set_2d_double( long_var_name, new_vals )
# elif (rank == 3):
# self.bmi.set_3d_double( long_var_name, new_vals )
# #------------------------------------------------------------------
# elif (dtype == 'int32'):
# if (rank == 0):
# self.bmi.set_0d_int( long_var_name, new_vals )
# elif (rank == 1):
# self.bmi.set_1d_int( long_var_name, new_vals )
# elif (rank == 2):
# self.bmi.set_2d_int( long_var_name, new_vals )
# elif (rank == 3):
# self.bmi.set_3d_int( long_var_name, new_vals )
# #-------------------------------------------------------------
# else:
# print '############################################'
# print ' ERROR: In CMI_base.set_values():'
# print ' Type_name of "' + dtype + '"'
# print ' is not yet supported.'
# print '############################################'
# print ' '
# set_values()
#-------------------------------------------------------------------
def get_values_at_indices( self, long_var_name, indices ):
#-------------------------------------------------------------
# Notes: For the specified variable, get the values at the
# specified indices and return them. If the wrapped
# model is raster, then each raster cell has a long
# integer, calendar-style index and these are used
# for indices. If the wrapped model is ugrid, then
# each cell in the grid has a unique, long-integer
# ID and these are used for indices.
#-------------------------------------------------------------
self.bmi.get_values_at_indices( long_var_name, indices )
# #----------------------------------------------
# # Get data type and rank for long_var_name.
# # Assume that NumPy dtype string is returned.
# #----------------------------------------------
# dtype = self.bmi.get_var_type( long_var_name )
# rank = self.bmi.get_var_rank( long_var_name )
#
# if (dtype == 'float64'):
# if (rank == 2):
# return self.bmi.get_2d_double_at_indices( long_var_name, indices )
# elif (dtype == 'int32'):
# if (rank == 2):
# return self.bmi.get_2d_int_at_indices( long_var_name, indices )
# get_values_at_indices()
#-------------------------------------------------------------------
def set_values_at_indices( self, long_var_name, indices, values ):
self.bmi.set_values_at_indices( long_var_name, indices, values )
# #----------------------------------------------
# # Get data type and rank for long_var_name.
# # Assume that NumPy dtype string is returned.
# #----------------------------------------------
# dtype = self.bmi.get_var_type( long_var_name )
# rank = self.bmi.get_var_rank( long_var_name )
#
# if (dtype == 'float64'):
# if (rank == 2):
# self.bmi.set_2d_double_at_indices( long_var_name, indices, values )
# return
# elif (dtype == 'int32'):
# if (rank == 2):
# self.bmi.set_2d_int_at_indices( long_var_name, indices, values )
# return
#
# print '#####################################################'
# print ' ERROR: CMI_base.set_values_at_indices() currently'
# print ' requires target variable to be a 2D array.'
# print '#####################################################'
# print ' '
# set_values_at_indices()
#-------------------------------------------------------------------
#-------------------------------------------------------------------
def get_input_var_names(self):
#------------------------------------------------------
# Note: NumPy dtype of returned array will be "|Sn",
# where n is the length of the longest string.
#------------------------------------------------------
return self.bmi.get_input_var_names()
# get_input_var_names()
#-------------------------------------------------------------------
def get_output_var_names(self):
#------------------------------------------------------
# Note: NumPy dtype of returned array will be "|Sn",
# where n is the length of the longest string.
#------------------------------------------------------
return self.bmi.get_output_var_names()
# get_output_var_names()
#-------------------------------------------------------------------
def get_var_type( self, long_var_name ):
#-----------------------------------------------------
# Notes: This may need to be in CMI as well as BMI.
#-----------------------------------------------------
return self.bmi.get_var_type( long_var_name )
# get_var_type()
#-------------------------------------------------------------------
def get_var_units( self, long_var_name ):
#-------------------------------------------------------------
# This needs to be in CMI as well as BMI to be called by a
# service component that converts units. See CMI.initialize.
#-------------------------------------------------------------
return self.bmi.get_var_units( long_var_name )
# get_var_units()
#-------------------------------------------------------------------
def get_var_rank( self, long_var_name ):
#-----------------------------------------------------
# Notes: This may need to be in CMI as well as BMI.
#-----------------------------------------------------
return self.bmi.get_var_rank( long_var_name )
# get_var_rank()
#-------------------------------------------------------------------
#-------------------------------------------------------------------
def get_grid_shape(self, long_var_name):
#-------------------------------------------------------
# Note: Return ndarray with [nx, ny, nz] as int32.
# We may want to reverse the order of the
# returned values in this method and the next 2.
#-------------------------------------------------------
return self.bmi.get_grid_shape()
# get_grid_shape()
#-------------------------------------------------------------------
def get_grid_spacing(self, long_var_name):
#--------------------------------------------------------
# Note: Return ndarray with [dx, dy, dz] as float64.
# xres and yres could have angular units like
# arcseconds, if (info.pixel_geom == 0). In
# that case, xres (or dx) will vary with latitude
# and this method isn't really appropriate.
#--------------------------------------------------------
return self.bmi.get_grid_spacing()
# get_grid_spacing()
#-------------------------------------------------------------------
def get_grid_lower_left_corner(self, long_var_name):
#--------------------------------------------------------
# Note: Return ndarray with [x0, y0, z0] as float64.
# What about units for [x0,y0,z0] and [dx,dy,dz]?
#--------------------------------------------------------
return self.bmi.get_grid_lower_left_corner( long_var_name )
# get_grid_lower_left_corner()
#-------------------------------------------------------------------
def get_grid_attribute(self, long_var_name, att_name):
return self.bmi.get_grid_attribute( long_var_name, att_name )
# get_grid_attribute()
#-------------------------------------------------------------------
#-------------------------------------------------------------------
# BMI methods to get time-related info
#-------------------------------------------------------------------
def get_time_step(self):
return self.bmi.get_time_step()
# get_time_step()
#-------------------------------------------------------------------
def get_time_units(self):
#-----------------------------------------------------------
# Notes: The get_attribute() method should always provide
# a model's time units. However, some components
# have an initialize_time_vars() method that saves
# a units string in self.time_units. These strings
# are lower-case, e.g. 'seconds', 'minutes',
# or 'years'. They should conform to UDUNITS.
#-----------------------------------------------------------
unit_str = self.get_attribute( 'time_units' )
return unit_str
# get_time_units()
#-------------------------------------------------------------------
def get_time(self, when='current'):
#---------------------------------------------------------
# Note: The "when" argument can be: current, start, end.
#---------------------------------------------------------
# return self.bmi.get_time( when )
if (when == 'current'):
return self.bmi.get_current_time()
elif (when == 'start'):
return self.bmi.get_start_time()
elif (when == 'stop'):
return self.bmi.get_end_time()
elif (when == 'end'):
return self.bmi.get_end_time()
else:
return self.bmi.get_current_time() # (e.g. 'now')
# get_time()
#-------------------------------------------------------------------
#-------------------------------------------------------------------
def initialize( self, cfg_prefix ):
#-----------------------------------------------------------
# NB! We currently ignore cfg_prefix argument and assume
# that a string variable called "case_prefix is
# available from the GUI.
#-----------------------------------------------------------
# We could use "cfg_dir = os.getcwd()" instead of "."
#-----------------------------------------------------------
self.set_status( 'initializing' )
DEBUG = False
#----------------------------------------------
# Get CCA ports for all required components.
# Later use the PortQueue service here.
#----------------------------------------------
OK = self.get_cca_ports( self.d_services )
if not(OK):
comp_name = self.get_attribute( 'comp_name' )
## comp_name = self.bmi.get_attribute( 'comp_name' )
print 'ERROR during', comp_name + '.get_cca_ports().'
return
## return -1 # (not in initialize())
#----------------------
# Set up a Port Queue (something like this)
#----------------------
# port_names = ???
# self.pq = edu.csdms.tools.IRFPortQueue.PortQueue( port_names )
#--------------------------------------------
# Build name of new model config file (CFG)
#--------------------------------------------
var_prefix = self.get_attribute( 'cmt_var_prefix' )
cfg_ext = self.get_attribute( 'cfg_extension' )
cfg_template = self.get_attribute( 'cfg_template_file')
## var_prefix = self.bmi.get_attribute( 'cmt_var_prefix' )
## cfg_ext = self.bmi.get_attribute( 'cfg_extension' )
## cfg_template = self.bmi.get_attribute( 'cfg_template_file')
#---------------------------------------------------------------
cfg_dir = "."
var_name = var_prefix + "case_prefix" # (need full name)
cfg_prefix = self.user_input.getString( var_name, "DEFAULT" )
if (DEBUG):
print '#### Read from GUI: cfg_prefix =', cfg_prefix
cfg_file = cfg_prefix + cfg_ext
#--------------------------------------------------------
# Read values from tabbed-dialog GUI and then use them
# to create a valid input file from a "template file".
# Template files have extension ".in", e.g. ".cfg.in".
# All info read from GUI is in self.user_input.
#--------------------------------------------------------
template = edu.csdms.tools.TemplateFiles.TemplateFiles()
template.add_file( cfg_template, cfg_file )
template.substitute( self.user_input, var_prefix, cfg_dir )
#------------------------------------
# Initialize the wrapped model.
# Currently need to set the "mode".
#------------------------------------
self.bmi.initialize( cfg_prefix, mode=self.mode)
self.set_status( 'initialized' )
# initialize()
#-------------------------------------------------------------------
def run_until( self ):
self.set_status( 'updating' )
self.set_status( 'updated' )
# run_until()
#-------------------------------------------------------------------
def run_for( self ):
self.set_status( 'updating' )
self.set_status( 'updated' )
# run_for()
#-------------------------------------------------------------------
def finalize( self ):
self.set_status( 'finalizing' )
self.bmi.finalize()
self.bmi.release_cca_ports( self.d_services )
self.set_status( 'finalized' )
# finalize()
#-------------------------------------------------------------------
def run_model(self):
#-------------------------------------------------------------
# Use CMI methods vs. BMI.run_model. (10/26/11)
#-------------------------------------------------------------
# Note: CMI.initialize ignores arg and sets cfg_prefix.
#-------------------------------------------------------------
### self.mode = 'driver'
self.set_mode( 'driver' )
comp_name = self.get_attribute( 'comp_name' )
self.initialize( '' )
##########################################
# Use something like this instead soon
##########################################
## try:
## self.run_until() ########
## except:
## print 'ERROR in CMI.run_model() at:'
## print ' time_index =', self.bmi.time_index
## self.print_traceback( comp_name + '.run_model()' )
## return -1 # (component can still be used)
while not(self.bmi.DONE): #################
try:
self.update( self.bmi.time_sec ) # (check argument; maybe use None?)
except:
print 'ERROR in CMI.run_model() at:'
print ' time_index =', self.bmi.time_index
self.print_traceback( comp_name + '.run_model()' )
return -1 # (component can still be used)
#--------------------------------------------
# Later do report with a service component.
# NB! BMI.finalize() closes the log_file.
#--------------------------------------------
self.bmi.print_final_report(comp_name=comp_name + ' component', mode='driver')
self.set_mode( 'nondriver' ) # (restore default)
## self.mode = 'nondriver' # (restore default)
self.finalize() # (very last thing)
return 0
# run_model()
#-------------------------------------------------------------------
def go(self):
self.run_model()
# go()
#-------------------------------------------------------------------
# Private methods or utilities; not part of BMI interface.
#-------------------------------------------------------------------
def check_finished(self):
#------------------------------------------------------
# Note: If self.DONE has already been set to True by
# another function or component, this function
# preserves that setting (see below).
#------------------------------------------------------
if (self.stop_code == 0):
#---------------------
# Stop after n_steps
#---------------------
TIMES_UP = (self.time_index >= self.n_steps)
elif (self.stop_code == 1):
#-----------------------
# Stop after stop_time
#-----------------------
TIMES_UP = (self.time >= self.stop_time)
elif (self.stop_code == 2):
#-----------------------------------------
# Stop if "steady-state", but only works
# as written here for global timesteps.
#-----------------------------------------
TIMES_UP = (self.dz_max < self.dz_tolerance) #######
self.DONE = (self.DONE or TIMES_UP)
# check_finished()
#-------------------------------------------------------------------
def print_traceback(self, comp_name='None'):
if (comp_name == 'None'):
comp_name = self.get_attribute( 'comp_name' )
print '################################################'
print ' ERROR encountered in ' + comp_name
print ' Please check your input parameters.'
print '################################################'
#-----------------------------------------------
# Print the Python exception traceback message
#-----------------------------------------------
traceback.print_exc()
# print_traceback()
#-------------------------------------------------------------------
|
bayne/ebean
|
ebean-core/src/test/java/org/tests/model/basic/first/TestFirstSecond.java
|
<reponame>bayne/ebean
package org.tests.model.basic.first;
import io.ebean.BaseTestCase;
import io.ebean.Ebean;
import org.junit.Test;
public class TestFirstSecond extends BaseTestCase {
@Test
public void test() {
First first = new First();
first.setName("first");
Ebean.save(first);
Second second = new Second();
second.setName("Jim");
second.setTitle("Sir");
second.setFirst(first);
Ebean.save(second);
second.getFirst().setName("changed");
Ebean.save(second);
Ebean.save(first);
}
}
|
megri/EmbroideryIO
|
core/src/main/java/org/embroideryio/embroideryio/PcsWriter.java
|
package org.embroideryio.embroideryio;
import java.io.IOException;
import static org.embroideryio.embroideryio.EmbConstant.*;
public class PcsWriter extends EmbWriter {
private static final double R = 5d / 3d;
void pcsEncode(int dx, int dy, int flags) throws IOException {
if ((flags & COMMAND_MASK) == COLOR_CHANGE) {
writeInt8(0);
writeInt24LE(0);
writeInt8(0);
writeInt24LE(0);
writeInt8(0x01);
if ((dx == 0) && (dy == 0)) return;
flags = STITCH;
}
int flagsToWrite = 0;
writeInt8(0);
writeInt24LE(dx);
writeInt8(0);
writeInt24LE(-dy);
switch ((flags & COMMAND_MASK)) {
case COLOR_CHANGE:
flagsToWrite |= 0x01;
break;
case TRIM:
flagsToWrite |= 0x04;
break;
}
writeInt8(flagsToWrite);
}
@Override
public void write() throws IOException {
pattern.fixColorCount();
writeInt8(0x32);
writeInt8(3);/* hoop size defaulting to Large PCS hoop */
int colorCount = pattern.getThreadCount();
writeInt16LE((colorCount < 16) ? 16 : colorCount); //I do not know if the format is limited at 16 explictly.
for (EmbThread thread : pattern.getThreadlist()) {
writeInt8(thread.getRed());
writeInt8(thread.getGreen());
writeInt8(thread.getBlue());
writeInt8(0);
}
for (; colorCount < 16; colorCount++) {
writeInt32(0);/* write remaining colors to reach 16 */
}
/* write stitches */
Points stitches = pattern.getStitches();
double xx = 0.0, yy = 0.0;
writeInt16LE(stitches.size());
for (int i = 0, ie = stitches.size(); i < ie; i++) {
pcsEncode((int) (R * stitches.getX(i)), (int) (R * stitches.getY(i)), stitches.getData(i));
}
}
}
|
Vezorla/vezorla-backend
|
src/main/java/ca/sait/vezorla/repository/AccountDiscountRepo.java
|
<reponame>Vezorla/vezorla-backend<gh_stars>0
package ca.sait.vezorla.repository;
import ca.sait.vezorla.model.AccountDiscount;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
/**
* AccountDiscountRepo class.
* <p>
* Repository classes are used to interact the the database
* via Spring and its annotations.
* <p>
* Repo class to interface with the AccountDiscount
* bridging table.
*
* @author matthewjflee, jjrr1717
*/
@Repository
public class AccountDiscountRepo {
/**
* EntityManager interacts with the persistence context.
*/
@PersistenceContext
private EntityManager entityManager;
/**
* Transactional annotation
* <p>
* Spring creates a proxy that implements the same interface(s)
* as the class you're annotating.
*
* @param accountDiscount AccountDiscount to add to the
* database.
*/
@Transactional
public void insertWithQuery(AccountDiscount accountDiscount) {
entityManager.createNativeQuery("INSERT INTO account_discount (account_email, discount_code) VALUES (?,?)")
.setParameter(1, accountDiscount.getEmail().getEmail())
.setParameter(2, accountDiscount.getCode().getCode())
.executeUpdate();
}
}
|
smccarthy-ie/app-services-cli
|
pkg/localize/goi18n/go_i18n.go
|
<gh_stars>0
// Internationalization implementation using nicksnyder/go-i18n
package goi18n
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"github.com/redhat-developer/app-services-cli/pkg/dump"
"github.com/redhat-developer/app-services-cli/pkg/localize"
"gopkg.in/yaml.v2"
"github.com/BurntSushi/toml"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
// go-i18n implementation
type Goi18n struct {
files fs.FS
language *language.Tag
bundle *i18n.Bundle
localizer *i18n.Localizer
format string
path string
}
type Config struct {
files fs.FS
language *language.Tag
format string
path string
}
// New creates a new nicksnyder/go-i18n client.
// You can pass nil to use the pre-configured defaults
// Or pass a partial config to override some defaults.
// Default file path: locales
// Default file format: toml (yaml and json are supported)
// Default language: English
func New(cfg *Config) (localize.Localizer, error) {
if cfg == nil {
cfg = &Config{}
}
if cfg.files == nil {
cfg.files = localize.GetDefaultLocales()
cfg.path = "locales"
cfg.format = "toml"
}
if cfg.language == nil {
cfg.language = localize.GetDefaultLanguage()
}
if cfg.format == "" {
cfg.format = "toml"
}
bundle := i18n.NewBundle(*cfg.language)
loc := &Goi18n{
files: cfg.files,
language: cfg.language,
bundle: bundle,
localizer: i18n.NewLocalizer(bundle),
format: cfg.format,
path: cfg.path,
}
err := loc.load()
return loc, err
}
// MustLocalize loads a i18n message from the file system
// You can pass dynamic values using template entries
// Examples:
//
// `localizer.MustLocalize("my-message-id", &localize.TemplateEntry{"Name", "Danny"})`
//
func (l *Goi18n) MustLocalize(id string, tmplEntries ...*localize.TemplateEntry) string {
templateData := map[string]interface{}{}
// map the template entries to the go-i18n format
for _, t := range tmplEntries {
templateData[t.Key] = t.Value
}
cfg := &i18n.LocalizeConfig{MessageID: id, PluralCount: 1, TemplateData: templateData}
return l.localizer.MustLocalize(cfg)
}
// MustLocalizePlural loads a pluralized i18n message from the file system
// You can pass dynamic values using template entries
// Examples:
//
// `localizer.MustLocalizePlural("my-message-id", 2)`
//
func (l *Goi18n) MustLocalizePlural(id string, pluralCount int, tmplEntries ...*localize.TemplateEntry) string {
templateData := map[string]interface{}{}
// map the template entries to the go-i18n format
for _, t := range tmplEntries {
templateData[t.Key] = t.Value
}
cfg := &i18n.LocalizeConfig{MessageID: id, PluralCount: pluralCount, TemplateData: templateData}
return l.localizer.MustLocalize(cfg)
}
// MustLocalizeError loads a i18n message from the file system
// and returns an error
// Examples:
//
// `err := localizer.MustLocalizeError("my-message-id", &localize.TemplateEntry{"Name", "Danny"}`
//
func (l *Goi18n) MustLocalizeError(id string, tmplEntries ...*localize.TemplateEntry) error {
return errors.New(l.MustLocalize(id, tmplEntries...))
}
// walk the file system and load each file into memory
func (l *Goi18n) load() error {
return fs.WalkDir(l.files, l.path, func(path string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
return l.MustLocalizeFile(l.files, path)
})
}
// read the message file from the file system
func (l *Goi18n) MustLocalizeFile(files fs.FS, path string) (err error) {
// open the static i18n file
buf, err := fs.ReadFile(files, path)
if err != nil {
return err
}
fileext := fmt.Sprintf("%v.%v", l.language.String(), l.format)
var unmarshalFunc i18n.UnmarshalFunc
switch l.format {
case "toml":
unmarshalFunc = toml.Unmarshal
case dump.YAMLFormat, dump.YMLFormat:
unmarshalFunc = yaml.Unmarshal
case dump.JSONFormat:
unmarshalFunc = json.Unmarshal
default:
return fmt.Errorf("unsupported format \"%v\"", l.format)
}
l.bundle.RegisterUnmarshalFunc(l.format, unmarshalFunc)
_, err = l.bundle.ParseMessageFileBytes(buf, fileext)
return
}
|
cattong/YiBo
|
YiBo/src/com/shejiaomao/weibo/service/listener/ImageViewerSaveClickListener.java
|
package com.shejiaomao.weibo.service.listener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.shejiaomao.maobo.R;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import com.cattong.commons.Logger;
import com.cattong.commons.util.FileUtil;
import com.cattong.commons.util.StringUtil;
import com.shejiaomao.weibo.SheJiaoMaoApplication;
import com.shejiaomao.weibo.common.Constants;
public class ImageViewerSaveClickListener implements OnClickListener {
private static final String TAG = ImageViewerSaveClickListener.class.getSimpleName();
private String imagePath;
public ImageViewerSaveClickListener(String imagePath) {
this.imagePath = imagePath;
}
@Override
public void onClick(View v) {
if (StringUtil.isEmpty(imagePath)) {
return;
}
final Context context = v.getContext();
SheJiaoMaoApplication sheJiaoMao = (SheJiaoMaoApplication)context.getApplicationContext();
String imageFolder = sheJiaoMao.getImageFolder();
if (imageFolder.toLowerCase().startsWith("/sdcard")) {
String state = Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)) {
String msg = null;
if (state.equals(Environment.MEDIA_REMOVED)) {
msg = context.getString(R.string.msg_image_save_fail_sdcard_removed);
} else if (state.equals(Environment.MEDIA_UNMOUNTED)) {
msg = context.getString(R.string.msg_image_save_fail_sdcard_unmounted);
} else if (state.equals(Environment.MEDIA_SHARED)) {
msg = context.getString(R.string.msg_image_save_fail_sdcard_shared);
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
return;
}
}
// 如果SD卡已挂载,则保存图片
File image = new File(imagePath);
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(imagePath);
if (StringUtil.isEmpty(fileExtension)) {
if (FileUtil.isGif(image.getAbsolutePath())){
fileExtension = "gif";
} else {
fileExtension = "png";
}
}
final String extension = fileExtension;
String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String destName = Constants.PICTURE_NAME_PREFIX + fileName + "." + extension;
final File dest = new File(imageFolder, destName);
boolean isSuccess = false;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(image).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
isSuccess = true;
} catch (IOException e) {
if (Logger.isDebug()) {
Log.e(TAG, e.getMessage(), e);
}
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
} finally {
try {
if (inputChannel != null) {
inputChannel.close();
}
if (outputChannel != null) {
outputChannel.close();
}
} catch (IOException e) {
if (Logger.isDebug()) {
Log.e(TAG, e.getMessage(), e);
}
}
}
if (isSuccess) {
final String absolutePath = dest.getAbsolutePath();
new MediaScannerConnectionClient() {
MediaScannerConnection mConnection = new MediaScannerConnection(context, this);
{
mConnection.connect();
}
@Override
public void onScanCompleted(String path, Uri uri) {
mConnection.disconnect();
mConnection = null;
}
@Override
public void onMediaScannerConnected() {
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
mConnection.scanFile(absolutePath, mime);
}
};
String msg = context.getString(R.string.msg_image_save_success, imageFolder + File.separator + destName);
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
}
|
UnicornGlobal/quick-dash-framework
|
test/unit/specs/auth/index.spec.js
|
// http://chaijs.com/api/bdd/
import Vue from 'vue'
import { createLocalVue } from '@vue/test-utils'
import router from '@/router'
import auth, { userHasRole, reloadSelf } from '@/auth'
const localVue = createLocalVue()
localVue.router = router
if (Vue.auth) {
Vue.auth.check = () => {
return true
}
} else {
Vue.auth = {
check() {
return true
}
}
}
describe('Authentication Redirects', () => {
it('Does not load login page if already logged in', () => {
localVue.router.push({name: 'Home'})
expect(localVue.router.currentRoute).to.be.an('Object')
expect(localVue.router.currentRoute.name).to.equal('Home')
localVue.router.push({name: 'Login'})
expect(localVue.router.currentRoute.name).to.equal('Home')
})
it('Loads password reset page if already logged in', () => {
localVue.router.push({name: 'Home'})
expect(localVue.router.currentRoute).to.be.an('Object')
expect(localVue.router.currentRoute.name).to.equal('Home')
localVue.router.push({name: 'ResetPassword'})
expect(localVue.router.currentRoute.name).to.equal('ResetPassword')
})
})
describe('User roles', () => {
it('User has role', () => {
const result = userHasRole({
roles: [{
name: 'xx'
}]
}, 'xx')
expect(result).to.equal(true)
})
it('User doesn not have role', () => {
const result = userHasRole({
roles: [{
name: 'a'
}]
}, 'xx')
expect(result).to.equal(false)
})
})
describe('General methods', () => {
it('reloadSelf', () => {
const originalGet = Vue.axios.get
var getSelf = sinon.stub().resolves({
_id: '111111111',
username: 'user',
first_name: 'User',
last_name: 'Last',
email: '<EMAIL>',
mobile: '+27822221111',
about: 'Example',
is_verified: 0,
title: null,
location: 'London, ON, Canada',
company_name: 'ExtraVallis',
referer: null,
account_type: 'startup',
facebook: null,
twitter: null,
linkedin: null,
instagram: null,
youtube: null,
confirmed: false,
roles: [
{
_id: '1111',
name: 'startup'
},
{
_id: '2222',
name: 'user'
}
],
primary_startup: null,
startup_company: null,
primary_investment: null,
investment_company: null,
profile_photo: null
})
Vue.axios.get = getSelf
reloadSelf()
expect(getSelf.called).to.equal(true)
Vue.axios.get = originalGet
})
})
describe('Default export', () => {
it('init', () => {
Vue.axios.interceptors = {
response: {
use: sinon.stub().resolves({})
}
}
const originalRouter = Vue.router
const originalUse = Vue.use
Vue.use = sinon.stub()
Vue.router = {
beforeEach: sinon.stub()
}
auth.init()
expect(Vue.use.called).to.equal(true)
expect(Vue.router.beforeEach.called).to.equal(true)
Vue.use = originalUse
Vue.router = originalRouter
})
})
|
Mrsunsunshine/ForElder
|
HeartWings/src/com/nwpu/heartwings/util/MSGUtil.java
|
package com.nwpu.heartwings.util;
import java.net.InetSocketAddress;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
public class MSGUtil {
public static final String THISCLIENT = "thisclient";
public static final String TYPE_HELLO = "hello";
public static final String TYPE_BIND = "bind";
public static final String TYPE_SYSTEM = "system";
public static final String TYPE_POSITION = "position";
public static final String TYPE_REQUESTPOSITION = "requestposition";
public static final String TYPE_REQUESTPOSITIONERR = "requestpositionerr";
public static final String TYPE_BINDRETURN = "returnbind";
public static final String TYPE_SHARE = "image";
public static NioSocketConnector connector = getConnector();
public static IoSession session;
public static final String MINAIP = "172.16.31.10";
//public static final String MINAIP = "10.128.52.177";
public static final int MINAPORT = 33333;
public static NioSocketConnector getConnector() {
NioSocketConnector connector = new NioSocketConnector();
connector.setConnectTimeoutMillis(10 * 1000);
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
connector.setHandler(new MinaClientHandler());
return connector;
}
public static IoSession getIOSession(String clientPhone){
IoSession session = null;
ConnectFuture future = connector.connect(new InetSocketAddress(MINAIP, MINAPORT));
future.awaitUninterruptibly();
session = future.getSession();
session.setAttribute(MSGUtil.THISCLIENT, clientPhone);
return session;
}
}
|
tendril-cirrus/4308Cirrus
|
tendril-domain/src/test/java/edu/colorado/cs/cirrus/domain/model/DeviceCostAndConsumptionTest.java
|
<gh_stars>1-10
package edu.colorado.cs.cirrus.domain.model;
import static org.junit.Assert.*;
import java.io.File;
import org.junit.Test;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
public class DeviceCostAndConsumptionTest {
@Test
public void canDeserializeDeviceCostAndConsumption() {
Serializer serializer = new Persister();
File source = new File("src/test/resources/DeviceCostAndConsumption.xml");
try {
DeviceCostAndConsumption exampleDeviceCostAndConsumption = serializer.read(
DeviceCostAndConsumption.class, source);
System.err.println(exampleDeviceCostAndConsumption);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
|
EventHorizon27/dataset-lib
|
dataset.ims/src/tech/pod/dataset/ims/WordHistogramClassifier.java
|
<gh_stars>1-10
package tech.pod.dataset.ims;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
//WordHistogramClassifier classifies an IndexKey list based on whether an individual IndexKey's WordHistogramList contains the queried words in the given quantities
public class WordHistogramClassifier implements ClassifierRule < IndexKey > {
List < IndexKey > classifierOutput;
List < String > wordKeys;
HashMap < String,
Integer > wordClassifiers;
WordHistogramClassifier(List < String > wordKeys, HashMap < String, Integer > wordClassifiers, List < IndexKey > classifierInput) {
this.wordKeys = wordKeys;
this.wordClassifiers = wordClassifiers;
classifierOutput = classifierInput;
}
public List < IndexKey > classify() {
for (int i = 0; i < wordKeys.length; i++) {
Integer individualWordCount = wordClassifiers.get(wordKeys.get(i));
for (int j = 0; j < classifierOutput.length; j++) {
HashMap wordOccurences = classifierOutput.get(i).wordOccurences();
if(wordOccurences.get(wordKeys.get(i))==null||(Integer)wordOccurences.get(wordKeys.get(i))<individualWordCount){
classifierOutput.remove(j);
continue;
}
}
}
return classifierOutput;
}
}
|
Zoltan45/Mame-mkp119
|
src/mame/audio/tiamc1.c
|
<filename>src/mame/audio/tiamc1.c
/***************************************************************************
TIA-MC1 sound hardware
driver by <NAME>
special thanks to Shiru for his standalone emulator and documentation
timer1 timer0
|--------| |--------|
| 8253 | | 8253 | |---|
in0 | | | | | 1 | |---|
----+ g0 o0 +---+ g0 o0 +---+ | | & |
in1 | | | | | o---+ | out
----+ g1 o1 +---+ g1 o1 +---+ | | +-----
in2 | | | | |---| | |
----+ g2 o2 +---+ g2 o2 +-----------+ |
clk1| | | | |---|
----+ clk | +-+ clk |
| | | | |
|--------| | |--------|
clk0 |
---------------+
in0-in2 comes from port #da
clk0 comes from 8224 and equals to 1777777Hz, i.e. processor clock
clk1 comes from divider 16000000/4/16/16/2 = 7812Hz
********************
TODO: use machine/pit8253.c
***************************************************************************/
#include "driver.h"
#include "streams.h"
#include "sound/custom.h"
#define CLOCK_DIVIDER 16
#define BUF_LEN 100000
static sound_stream *channel;
static int timer1_divider;
struct timer8253chan {
UINT16 count;
UINT16 cnval;
UINT8 bcdMode;
UINT8 cntMode;
UINT8 valMode;
UINT8 gate;
UINT8 output;
UINT8 loadCnt;
UINT8 enable;
};
struct timer8253struct {
struct timer8253chan channel[3];
};
static struct timer8253struct timer0;
static struct timer8253struct timer1;
#define T8253_CHAN0 0
#define T8253_CHAN1 1
#define T8253_CHAN2 2
#define T8253_CWORD 3
void timer8253_reset(struct timer8253struct *t) {
memset(t,0,sizeof(struct timer8253struct));
}
void timer8253_tick(struct timer8253struct *t,int chn) {
if (t->channel[chn].enable && t->channel[chn].gate) {
switch (t->channel[chn].cntMode) {
case 0:
t->channel[chn].count--;
if (t->channel[chn].count == 0xffff)
t->channel[chn].output = 1;
break;
case 3:
t->channel[chn].count--;
if (t->channel[chn].count < (t->channel[chn].cnval >> 1))
t->channel[chn].output = 0;
else
t->channel[chn].output = 1;
if (t->channel[chn].count == 0xffff)
t->channel[chn].count = t->channel[chn].cnval;
break;
case 4:
t->channel[chn].count--;
if(t->channel[chn].count==0)
t->channel[chn].output = 1;
if(t->channel[chn].count == 0xffff) {
t->channel[chn].enable = 0;
t->channel[chn].output = 1;
}
break;
}
}
}
void timer8253_wr(struct timer8253struct *t, int reg, UINT8 val)
{
int chn;
switch (reg) {
case T8253_CWORD:
chn = val >> 6;
if (chn < 3) {
t->channel[chn].bcdMode = (val & 1) ? 1 : 0;
t->channel[chn].cntMode = (val >> 1) & 0x07;
t->channel[chn].valMode = (val >> 4) & 0x03;
switch (t->channel[chn].valMode) {
case 1:
case 2:
t->channel[chn].loadCnt = 1;
break;
case 3:
t->channel[chn].loadCnt = 2;
break;
default:
mame_printf_debug("unhandled val mode %i\n", t->channel[chn].valMode);
}
switch (t->channel[chn].cntMode) {
case 0:
t->channel[chn].output = 0;
t->channel[chn].enable = 0;
break;
case 3:
t->channel[chn].output = 1;
break;
case 4:
t->channel[chn].output = 1;
t->channel[chn].enable = 0;
break;
default:
mame_printf_debug("unhandled cnt mode %i\n", t->channel[chn].cntMode);
}
}
break;
default:
chn = reg;
switch (t->channel[chn].valMode) {
case 1:
t->channel[chn].cnval = (t->channel[chn].cnval & 0xff00) | val;
break;
case 2:
t->channel[chn].cnval = (t->channel[chn].cnval & 0x00ff) | (val << 8);
break;
case 3:
t->channel[chn].cnval = (t->channel[chn].cnval >> 8) | (val << 8);
break;
default:
mame_printf_debug("unhandled val mode %i\n", t->channel[chn].valMode);
}
if (t->channel[chn].cntMode==0) {
t->channel[chn].enable = 0;
}
t->channel[chn].loadCnt--;
if (t->channel[chn].loadCnt == 0) {
switch (t->channel[chn].valMode) {
case 1:
case 2:
t->channel[chn].loadCnt = 1;
break;
case 3:
t->channel[chn].loadCnt = 2;
break;
default:
mame_printf_debug("unhandled val mode %i\n", t->channel[chn].valMode);
}
switch (t->channel[chn].cntMode) {
case 3:
t->channel[chn].count = t->channel[chn].cnval;
t->channel[chn].enable = 1;
break;
case 0:
case 4:
t->channel[chn].count = t->channel[chn].cnval;
t->channel[chn].enable = 1;
break;
default:
mame_printf_debug("unhandled cnt mode %i\n", t->channel[chn].cntMode);
}
}
}
}
void timer8253_set_gate(struct timer8253struct *t, int chn, UINT8 gate)
{
t->channel[chn].gate = gate;
}
char timer8253_get_output(struct timer8253struct *t, int chn)
{
return t->channel[chn].output;
}
WRITE8_HANDLER( tiamc1_timer0_w )
{
timer8253_wr(&timer0, offset, data);
}
WRITE8_HANDLER( tiamc1_timer1_w )
{
timer8253_wr(&timer1, offset, data);
}
WRITE8_HANDLER( tiamc1_timer1_gate_w )
{
timer8253_set_gate(&timer1, 0, (data & 1) ? 1 : 0);
timer8253_set_gate(&timer1, 1, (data & 2) ? 1 : 0);
timer8253_set_gate(&timer1, 2, (data & 4) ? 1 : 0);
}
static void tiamc1_sound_update(void *param, stream_sample_t **inputs, stream_sample_t **outputs, int length)
{
int count, o0, o1, o2, len, or = 0;
len = length * CLOCK_DIVIDER;
for (count = 0; count < len; count++) {
timer1_divider++;
if (timer1_divider == 228) {
timer1_divider = 0;
timer8253_tick(&timer1, 0);
timer8253_tick(&timer1, 1);
timer8253_tick(&timer1, 2);
timer8253_set_gate(&timer0, 0, timer8253_get_output(&timer1, 0));
timer8253_set_gate(&timer0, 1, timer8253_get_output(&timer1, 1));
timer8253_set_gate(&timer0, 2, timer8253_get_output(&timer1, 2));
}
timer8253_tick(&timer0, 0);
timer8253_tick(&timer0, 1);
timer8253_tick(&timer0, 2);
o0 = timer8253_get_output(&timer0, 0) ? 1 : 0;
o1 = timer8253_get_output(&timer0, 1) ? 1 : 0;
o2 = timer8253_get_output(&timer0, 2) ? 1 : 0;
or = (or << 1) | (((o0 | o1) ^ 0xff) & o2);
if ((count + 1) % CLOCK_DIVIDER == 0) {
outputs[0][count / CLOCK_DIVIDER] = or ? 0x2828 : 0;
or = 0;
}
}
}
void *tiamc1_sh_start(int clock, const struct CustomSound_interface *config)
{
int i, j;
timer8253_reset(&timer0);
timer8253_reset(&timer1);
channel = stream_create(0, 1, clock / CLOCK_DIVIDER, 0, tiamc1_sound_update);
timer1_divider = 0;
for (i = 0; i < 2; i++) {
struct timer8253struct *t = (i ? &timer1 : &timer0);
for (j = 0; j < 3; j++) {
state_save_register_item("channel", i * 3 + j, t->channel[j].count);
state_save_register_item("channel", i * 3 + j, t->channel[j].cnval);
state_save_register_item("channel", i * 3 + j, t->channel[j].bcdMode);
state_save_register_item("channel", i * 3 + j, t->channel[j].cntMode);
state_save_register_item("channel", i * 3 + j, t->channel[j].valMode);
state_save_register_item("channel", i * 3 + j, t->channel[j].gate);
state_save_register_item("channel", i * 3 + j, t->channel[j].output);
state_save_register_item("channel", i * 3 + j, t->channel[j].loadCnt);
state_save_register_item("channel", i * 3 + j, t->channel[j].enable);
}
}
state_save_register_global(timer1_divider);
return channel;
}
|
RedBrumbler/virtuoso-codegen
|
include/UnityEngine/TextCore/LowLevel/GlyphRenderMode.hpp
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: UnityEngine.TextCore.LowLevel
namespace UnityEngine::TextCore::LowLevel {
// Forward declaring type: GlyphRenderMode
struct GlyphRenderMode;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::TextCore::LowLevel::GlyphRenderMode, "UnityEngine.TextCore.LowLevel", "GlyphRenderMode");
// Type namespace: UnityEngine.TextCore.LowLevel
namespace UnityEngine::TextCore::LowLevel {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.TextCore.LowLevel.GlyphRenderMode
// [TokenAttribute] Offset: FFFFFFFF
// [UsedByNativeCodeAttribute] Offset: 5BC5B0
struct GlyphRenderMode/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: GlyphRenderMode
constexpr GlyphRenderMode(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SMOOTH_HINTED
static constexpr const int SMOOTH_HINTED = 4121;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SMOOTH_HINTED
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SMOOTH_HINTED();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SMOOTH_HINTED
static void _set_SMOOTH_HINTED(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SMOOTH
static constexpr const int SMOOTH = 4117;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SMOOTH
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SMOOTH();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SMOOTH
static void _set_SMOOTH(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode RASTER_HINTED
static constexpr const int RASTER_HINTED = 4122;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode RASTER_HINTED
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_RASTER_HINTED();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode RASTER_HINTED
static void _set_RASTER_HINTED(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode RASTER
static constexpr const int RASTER = 4118;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode RASTER
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_RASTER();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode RASTER
static void _set_RASTER(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF
static constexpr const int SDF = 4134;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SDF();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF
static void _set_SDF(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF8
static constexpr const int SDF8 = 8230;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF8
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SDF8();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF8
static void _set_SDF8(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF16
static constexpr const int SDF16 = 16422;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF16
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SDF16();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF16
static void _set_SDF16(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF32
static constexpr const int SDF32 = 32806;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF32
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SDF32();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDF32
static void _set_SDF32(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDFAA_HINTED
static constexpr const int SDFAA_HINTED = 4169;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDFAA_HINTED
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SDFAA_HINTED();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDFAA_HINTED
static void _set_SDFAA_HINTED(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// static field const value: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDFAA
static constexpr const int SDFAA = 4165;
// Get static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDFAA
static ::UnityEngine::TextCore::LowLevel::GlyphRenderMode _get_SDFAA();
// Set static field: static public UnityEngine.TextCore.LowLevel.GlyphRenderMode SDFAA
static void _set_SDFAA(::UnityEngine::TextCore::LowLevel::GlyphRenderMode value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // UnityEngine.TextCore.LowLevel.GlyphRenderMode
#pragma pack(pop)
static check_size<sizeof(GlyphRenderMode), 0 + sizeof(int)> __UnityEngine_TextCore_LowLevel_GlyphRenderModeSizeCheck;
static_assert(sizeof(GlyphRenderMode) == 0x4);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
|
lulululbj/Everything
|
app/src/main/java/luyao/everything/view/dialog/ShowNumberDialog.java
|
<gh_stars>1-10
package luyao.everything.view.dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import luyao.everything.R;
import luyao.everything.enity.NumberEnity;
import luyao.everything.utils.Util;
/**
* Created by Lu
* on 2016/11/24 15:41.
*/
public class ShowNumberDialog extends BaseDialog {
@BindView(R.id.img_call1)
ImageView img_call1;
@BindView(R.id.img_call2)
ImageView img_call2;
@BindView(R.id.tv_name1)
TextView tv_name1;
@BindView(R.id.tv_name2)
TextView tv_name2;
@BindView(R.id.tv_num1)
TextView tv_num1;
@BindView(R.id.tv_num2)
TextView tv_num2;
@BindView(R.id.tv_brand)
TextView tv_brand;
@BindView(R.id.rl_num1)
RelativeLayout rl_num1;
@BindView(R.id.rl_num2)
RelativeLayout rl_num2;
private NumberEnity.NumberDetail numberDetail;
public ShowNumberDialog(Context context, int themeId) {
super(context, themeId);
}
public ShowNumberDialog(Context context, int themeId, NumberEnity.NumberDetail numberDetail) {
this(context, themeId);
this.numberDetail = numberDetail;
setData();
}
@Override
protected int getResId() {
return R.layout.show_number_dialog;
}
@Override
protected void initData() {
}
private void setData() {
tv_brand.setText(numberDetail.getBrand());
String name1 = numberDetail.getName1();
String name2 = numberDetail.getName2();
if (!TextUtils.isEmpty(name1)) {
rl_num1.setVisibility(View.VISIBLE);
tv_name1.setText(name1);
tv_num1.setText(numberDetail.getNumber1());
} else {
rl_num1.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(name2)) {
rl_num2.setVisibility(View.VISIBLE);
tv_name2.setText(name2);
tv_num2.setText(numberDetail.getNumber2());
} else {
rl_num2.setVisibility(View.GONE);
}
}
@OnClick(R.id.img_call1)
public void call1() {
Util.callPhone(getContext(), tv_num1.getText().toString().replace(" ", ""));
}
@OnClick(R.id.img_call2)
public void call2() {
Util.callPhone(getContext(), tv_num2.getText().toString().replace(" ", ""));
}
}
|
8d1h/TiddlyWiki5
|
core/modules/startup/render.js
|
/*\
title: $:/core/modules/startup/render.js
type: application/javascript
module-type: startup
Title, stylesheet and page rendering
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
// Export name and synchronous status
exports.name = "render";
exports.platforms = ["browser"];
exports.after = ["story"];
exports.synchronous = true;
// Default story and history lists
var PAGE_TITLE_TITLE = "$:/core/wiki/title";
var PAGE_STYLESHEET_TITLE = "$:/core/ui/PageStylesheet";
var PAGE_TEMPLATE_TITLE = "$:/core/ui/RootTemplate";
// Time (in ms) that we defer refreshing changes to draft tiddlers
var DRAFT_TIDDLER_TIMEOUT_TITLE = "$:/config/Drafts/TypingTimeout";
var THROTTLE_REFRESH_TIMEOUT = 400;
exports.startup = function() {
// Set up the title
$tw.titleWidgetNode = $tw.wiki.makeTranscludeWidget(PAGE_TITLE_TITLE,{document: $tw.fakeDocument, parseAsInline: true});
$tw.titleContainer = $tw.fakeDocument.createElement("div");
$tw.titleWidgetNode.render($tw.titleContainer,null);
document.title = $tw.titleContainer.textContent;
$tw.wiki.addEventListener("change",function(changes) {
if($tw.titleWidgetNode.refresh(changes,$tw.titleContainer,null)) {
document.title = $tw.titleContainer.textContent;
}
});
// Set up the styles
$tw.styleWidgetNode = $tw.wiki.makeTranscludeWidget(PAGE_STYLESHEET_TITLE,{document: $tw.fakeDocument});
$tw.styleContainer = $tw.fakeDocument.createElement("style");
$tw.styleWidgetNode.render($tw.styleContainer,null);
$tw.styleElement = document.createElement("style");
$tw.styleElement.innerHTML = $tw.styleContainer.textContent;
document.head.insertBefore($tw.styleElement,document.head.firstChild);
$tw.wiki.addEventListener("change",$tw.perf.report("styleRefresh",function(changes) {
if($tw.styleWidgetNode.refresh(changes,$tw.styleContainer,null)) {
$tw.styleElement.innerHTML = $tw.styleContainer.textContent;
}
}));
// Display the $:/core/ui/PageTemplate tiddler to kick off the display
$tw.perf.report("mainRender",function() {
$tw.pageWidgetNode = $tw.wiki.makeTranscludeWidget(PAGE_TEMPLATE_TITLE,{document: document, parentWidget: $tw.rootWidget, recursionMarker: "no"});
$tw.pageContainer = document.createElement("div");
$tw.utils.addClass($tw.pageContainer,"tc-page-container-wrapper");
document.body.insertBefore($tw.pageContainer,document.body.firstChild);
$tw.pageWidgetNode.render($tw.pageContainer,null);
$tw.hooks.invokeHook("th-page-refreshed");
})();
// Remove any splash screen elements
var removeList = document.querySelectorAll(".tc-remove-when-wiki-loaded");
$tw.utils.each(removeList,function(removeItem) {
if(removeItem.parentNode) {
removeItem.parentNode.removeChild(removeItem);
}
});
// Prepare refresh mechanism
var deferredChanges = Object.create(null),
timerId;
function refresh() {
// Process the refresh
$tw.hooks.invokeHook("th-page-refreshing");
$tw.pageWidgetNode.refresh(deferredChanges);
deferredChanges = Object.create(null);
$tw.hooks.invokeHook("th-page-refreshed");
}
// Add the change event handler
$tw.wiki.addEventListener("change",$tw.perf.report("mainRefresh",function(changes) {
// Check if only tiddlers that are throttled have changed
var onlyThrottledTiddlersHaveChanged = true;
for(var title in changes) {
var tiddler = $tw.wiki.getTiddler(title);
if(!$tw.wiki.isVolatileTiddler(title) && (!tiddler || !(tiddler.hasField("draft.of") || tiddler.hasField("throttle.refresh")))) {
onlyThrottledTiddlersHaveChanged = false;
}
}
// Defer the change if only drafts have changed
if(timerId) {
clearTimeout(timerId);
}
timerId = null;
if(onlyThrottledTiddlersHaveChanged) {
var timeout = parseInt($tw.wiki.getTiddlerText(DRAFT_TIDDLER_TIMEOUT_TITLE,""),10);
if(isNaN(timeout)) {
timeout = THROTTLE_REFRESH_TIMEOUT;
}
timerId = setTimeout(refresh,timeout);
$tw.utils.extend(deferredChanges,changes);
} else {
$tw.utils.extend(deferredChanges,changes);
refresh();
}
}));
// Fix up the link between the root widget and the page container
$tw.rootWidget.domNodes = [$tw.pageContainer];
$tw.rootWidget.children = [$tw.pageWidgetNode];
// Run any post-render startup actions
$tw.rootWidget.invokeActionsByTag("$:/tags/StartupAction/PostRender");
};
})();
|
keaton-freude/Nimble
|
NimbleGraphics/NimbleGraphics/src/SplatMap.cpp
|
#include "SplatMap.h"
SplatMap::SplatMap()
{
}
void SplatMap::LoadFromFile(D3DDevice device, D3DDeviceContext deviceContext, const vector<wstring>& textures)
{
_textures = TextureArray(device, deviceContext, textures, true);
}
SplatMap::~SplatMap()
{
}
ID3D11ShaderResourceView** SplatMap::GetTextureViews()
{
return _textures.GetTextureViews();
}
size_t SplatMap::GetNumberOfViews()
{
return _textures.GetNumberOfTextures();
}
ID3D11Resource* SplatMap::GetSplat(int texture_index)
{
// texture_index refers to the detail texture index
// 0-3 -> splat0
if (texture_index <= 3)
{
return _textures.GetTexture(0);
}
else if (texture_index <= 7)
{
return _textures.GetTexture(5);
}
else if (texture_index <= 11)
{
return _textures.GetTexture(10);
}
return _textures.GetTexture(0);
}
int SplatMap::GetColorComponent(int texture_index)
{
// texture_index_0 -> SKIP (splat)
// texture_index_1 -> r
// texture_index_2 -> g
// texture_index_3 -> b
// texture_index_4 -> a
// texture_idnex_5 -> SKIP (splat)
// texture_index_6 -> r
// ...
// r = 0, g = 1, b = 2, a = 3
switch (texture_index)
{
case 1:
return 0;
case 2:
return 1;
case 3:
return 2;
case 4:
return 3;
case 6:
return 0;
case 7:
return 1;
case 8:
return 2;
case 9:
return 3;
case 11:
return 0;
case 12:
return 1;
case 13:
return 2;
case 14:
return 3;
}
return 0;
}
|
StrahinjaJacimovic/mikrosdk_click_v2
|
clicks/dht22/lib/src/dht22.c
|
<filename>clicks/dht22/lib/src/dht22.c<gh_stars>10-100
/*
* MikroSDK - MikroE Software Development Kit
* Copyright© 2020 MikroElektronika d.o.o.
*
* 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.
*/
/*!
* \file
*
*/
#include "dht22.h"
void dht22_cfg_setup ( dht22_cfg_t *cfg )
{
cfg->sd1 = HAL_PIN_NC;
cfg->sd2 = HAL_PIN_NC;
cfg->sda_sel = DHT22_SDA_SEL_SDA1;
}
err_t dht22_init ( dht22_t *ctx, dht22_cfg_t *cfg )
{
ctx->sd1 = cfg->sd1;
ctx->sd2 = cfg->sd2;
ctx->sda_sel = cfg->sda_sel;
ctx->sda_out_stat = DIGITAL_OUT_UNSUPPORTED_PIN;
ctx->sda_in_stat = DIGITAL_IN_UNSUPPORTED_PIN;
if ( ( cfg->sd1 == HAL_PIN_NC ) && ( cfg->sd2 == HAL_PIN_NC ) )
{
return DHT22_ERROR;
}
return DHT22_OK;
}
err_t dht22_start_signal ( dht22_t *ctx )
{
if ( ctx->sda_out_stat == DIGITAL_OUT_UNSUPPORTED_PIN )
{
return DHT22_ERROR;
}
digital_out_low( &ctx->sda_out );
Delay_1ms( );
Delay_1ms( );
digital_out_high( &ctx->sda_out );
return DHT22_OK;
}
err_t dht22_check_sensor_response ( dht22_t *ctx, uint8_t *check_out )
{
if ( ctx->sda_in_stat == DIGITAL_IN_UNSUPPORTED_PIN )
{
return DHT22_ERROR;
}
while ( digital_in_read( &ctx->sda_in ) )
{
Delay_1us( );
}
while ( !digital_in_read( &ctx->sda_in ) )
{
Delay_1us( );
}
while ( digital_in_read( &ctx->sda_in ) )
{
Delay_1us( );
}
*check_out = DHT22_RESP_READY;
return DHT22_OK;
}
err_t dht22_get_sensor_data ( dht22_t *ctx, uint32_t *data_out )
{
uint8_t read_buffer[ 5 ];
uint32_t results;
uint8_t cnt_j;
uint8_t cnt_i;
uint8_t tim_cnt = 0;
uint8_t sensor_byte_buffer;
for ( cnt_i = 0; cnt_i < 5; cnt_i++ )
{
sensor_byte_buffer = 0;
for ( cnt_j = 0; cnt_j < 8; cnt_j++ )
{
tim_cnt = 0;
while ( !digital_in_read( &ctx->sda_in ) )
{
Delay_1us( );
}
while ( digital_in_read( &ctx->sda_in ) )
{
Delay_1us( );
tim_cnt++;
}
sensor_byte_buffer <<= 1;
if( tim_cnt > 30 )
{
sensor_byte_buffer |= 1;
}
}
read_buffer[ cnt_i ] = sensor_byte_buffer;
}
results = read_buffer[ 0 ];
results <<= 8;
results |= read_buffer[ 1 ];
results <<= 8;
results |= read_buffer[ 2 ];
results <<= 8;
results |= read_buffer[ 3 ];
*data_out = results;
return DHT22_OK;
}
uint16_t dht22_get_temperature ( dht22_t *ctx, uint32_t sensor_data )
{
return ( uint16_t )sensor_data;
}
float dht22_calculate_temperature ( dht22_t *ctx, uint32_t sensor_data )
{
uint16_t temp_data = dht22_get_temperature( ctx, sensor_data );
return ( float )temp_data / 10;
}
uint16_t dht22_get_humidity ( dht22_t *ctx, uint32_t sensor_data )
{
return ( uint16_t )( sensor_data >> 16 );
}
float dht22_calculate_humidity ( dht22_t *ctx, uint32_t sensor_data )
{
uint16_t hum_data = dht22_get_humidity( ctx, sensor_data );
return ( float )hum_data / 10;
}
err_t dht22_init_sda_input ( dht22_t *ctx )
{
if ( ctx->sda_sel == DHT22_SDA_SEL_SDA1 )
{
ctx->sda_in_stat = digital_in_init( &ctx->sda_in, ctx->sd1 );
}
else
{
ctx->sda_in_stat = digital_in_init( &ctx->sda_in, ctx->sd2 );
}
ctx->sda_out_stat = DIGITAL_OUT_UNSUPPORTED_PIN;
return ctx->sda_in_stat;
}
err_t dht22_init_sda_output ( dht22_t *ctx )
{
if ( ctx->sda_sel == DHT22_SDA_SEL_SDA1 )
{
ctx->sda_out_stat = digital_out_init( &ctx->sda_out, ctx->sd1 );
}
else
{
ctx->sda_out_stat = digital_out_init( &ctx->sda_out, ctx->sd2 );
}
ctx->sda_in_stat = DIGITAL_IN_UNSUPPORTED_PIN;
return ctx->sda_out_stat;
}
// ------------------------------------------------------------------------ END
|
erezrokah/appsmith
|
app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ValidationUtils.java
|
<reponame>erezrokah/appsmith<filename>app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ValidationUtils.java
package com.appsmith.server.helpers;
import org.apache.commons.validator.routines.EmailValidator;
public final class ValidationUtils {
public static final int LOGIN_PASSWORD_MIN_LENGTH = 6;
public static final int LOGIN_PASSWORD_MAX_LENGTH = 48;
public static boolean validateEmail(String emailStr) {
return EmailValidator.getInstance().isValid(emailStr);
}
public static boolean validateLoginPassword(String password) {
int passwordLength = password.length();
return passwordLength >= LOGIN_PASSWORD_MIN_LENGTH && passwordLength <= LOGIN_PASSWORD_MAX_LENGTH;
}
}
|
SeungpilPark/fastcampus-monolithic
|
backend/src/main/java/com/fastcampus/mobility/entity/UserRole.java
|
<reponame>SeungpilPark/fastcampus-monolithic
package com.fastcampus.mobility.entity;
public enum UserRole {
시스템관리, 일반관리
}
|
medismailben/llvm-project
|
llvm/lib/CodeGen/PostRAHazardRecognizer.cpp
|
<gh_stars>1000+
//===----- PostRAHazardRecognizer.cpp - hazard recognizer -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This runs the hazard recognizer and emits noops when necessary. This
/// gives targets a way to run the hazard recognizer without running one of
/// the schedulers. Example use cases for this pass would be:
///
/// - Targets that need the hazard recognizer to be run at -O0.
/// - Targets that want to guarantee that hazards at the beginning of
/// scheduling regions are handled correctly. The post-RA scheduler is
/// a top-down scheduler, but when there are multiple scheduling regions
/// in a basic block, it visits the regions in bottom-up order. This
/// makes it impossible for the scheduler to gauranttee it can correctly
/// handle hazards at the beginning of scheduling regions.
///
/// This pass traverses all the instructions in a program in top-down order.
/// In contrast to the instruction scheduling passes, this pass never resets
/// the hazard recognizer to ensure it can correctly handles noop hazards at
/// the beginning of blocks.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "post-RA-hazard-rec"
STATISTIC(NumNoops, "Number of noops inserted");
namespace {
class PostRAHazardRecognizer : public MachineFunctionPass {
public:
static char ID;
PostRAHazardRecognizer() : MachineFunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &Fn) override;
};
char PostRAHazardRecognizer::ID = 0;
}
char &llvm::PostRAHazardRecognizerID = PostRAHazardRecognizer::ID;
INITIALIZE_PASS(PostRAHazardRecognizer, DEBUG_TYPE,
"Post RA hazard recognizer", false, false)
bool PostRAHazardRecognizer::runOnMachineFunction(MachineFunction &Fn) {
const TargetInstrInfo *TII = Fn.getSubtarget().getInstrInfo();
std::unique_ptr<ScheduleHazardRecognizer> HazardRec(
TII->CreateTargetPostRAHazardRecognizer(Fn));
// Return if the target has not implemented a hazard recognizer.
if (!HazardRec.get())
return false;
// Loop over all of the basic blocks
for (auto &MBB : Fn) {
// We do not call HazardRec->reset() here to make sure we are handling noop
// hazards at the start of basic blocks.
for (MachineInstr &MI : MBB) {
// If we need to emit noops prior to this instruction, then do so.
unsigned NumPreNoops = HazardRec->PreEmitNoops(&MI);
for (unsigned i = 0; i != NumPreNoops; ++i) {
HazardRec->EmitNoop();
TII->insertNoop(MBB, MachineBasicBlock::iterator(MI));
++NumNoops;
}
HazardRec->EmitInstruction(&MI);
if (HazardRec->atIssueLimit()) {
HazardRec->AdvanceCycle();
}
}
}
return true;
}
|
tuhintoxin/indic-keyboard
|
native/jni/src/suggest/core/policy/scoring.h
|
<gh_stars>0
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LATINIME_SCORING_H
#define LATINIME_SCORING_H
#include "defines.h"
namespace latinime {
class DicNode;
class DicTraverseSession;
class SuggestionResults;
// This class basically tweaks suggestions and distances apart from CompoundDistance
class Scoring {
public:
virtual int calculateFinalScore(const float compoundDistance, const int inputSize,
const ErrorTypeUtils::ErrorType containedErrorTypes, const bool forceCommit,
const bool boostExactMatches) const = 0;
virtual void getMostProbableString(const DicTraverseSession *const traverseSession,
const float languageWeight, SuggestionResults *const outSuggestionResults) const = 0;
virtual float getAdjustedLanguageWeight(DicTraverseSession *const traverseSession,
DicNode *const terminals, const int size) const = 0;
virtual float getDoubleLetterDemotionDistanceCost(
const DicNode *const terminalDicNode) const = 0;
virtual bool autoCorrectsToMultiWordSuggestionIfTop() const = 0;
virtual bool sameAsTyped(const DicTraverseSession *const traverseSession,
const DicNode *const dicNode) const = 0;
protected:
Scoring() {}
virtual ~Scoring() {}
private:
DISALLOW_COPY_AND_ASSIGN(Scoring);
};
} // namespace latinime
#endif // LATINIME_SCORING_H
|
Sensory-Cloud/android-sdk
|
SensoryCloud/src/main/java/ai/sensorycloud/api/common/ModelType.java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: common/common.proto
package ai.sensorycloud.api.common;
/**
* <pre>
* A type of model supported by this API
* Note: if you change this enum, ensure to update schema.prisma ModelType
* </pre>
*
* Protobuf enum {@code sensory.api.common.ModelType}
*/
public enum ModelType
implements com.google.protobuf.Internal.EnumLite {
/**
* <pre>
* Voice Auth Text Dependent (Enrollable)
* </pre>
*
* <code>VOICE_BIOMETRIC_TEXT_DEPENDENT = 0;</code>
*/
VOICE_BIOMETRIC_TEXT_DEPENDENT(0),
/**
* <pre>
* Voice Auth Text Independent (Enrollable)
* </pre>
*
* <code>VOICE_BIOMETRIC_TEXT_INDEPENDENT = 1;</code>
*/
VOICE_BIOMETRIC_TEXT_INDEPENDENT(1),
/**
* <pre>
* Voice Wakeword (Enrollable)
* </pre>
*
* <code>VOICE_BIOMETRIC_WAKEWORD = 2;</code>
*/
VOICE_BIOMETRIC_WAKEWORD(2),
/**
* <pre>
* Voice Wakeword
* </pre>
*
* <code>VOICE_EVENT_WAKEWORD = 3;</code>
*/
VOICE_EVENT_WAKEWORD(3),
/**
* <pre>
* Voice Grammar Recognition such as LVCSR
* </pre>
*
* <code>VOICE_TRANSCRIBE_GRAMMAR = 4;</code>
*/
VOICE_TRANSCRIBE_GRAMMAR(4),
/**
* <pre>
* Voice Commands and Search recognition
* </pre>
*
* <code>VOICE_TRANSCRIBE_COMMAND_AND_SEARCH = 5;</code>
*/
VOICE_TRANSCRIBE_COMMAND_AND_SEARCH(5),
/**
* <pre>
* Voice activity detection
* </pre>
*
* <code>VOICE_RECOGNITION_ACTIVITY_DETECTION = 6;</code>
*/
VOICE_RECOGNITION_ACTIVITY_DETECTION(6),
/**
* <pre>
* Voice feature extractor
* </pre>
*
* <code>VOICE_FEATURE_EXTRACTOR = 7;</code>
*/
VOICE_FEATURE_EXTRACTOR(7),
/**
* <pre>
* Voice digit recognizer for liveness
* </pre>
*
* <code>VOICE_BIOMETRIC_LIVENESS_DIGIT = 8;</code>
*/
VOICE_BIOMETRIC_LIVENESS_DIGIT(8),
/**
* <pre>
* Sound Event Auth (Enrollable)
* </pre>
*
* <code>SOUND_EVENT_ENROLLABLE = 100;</code>
*/
SOUND_EVENT_ENROLLABLE(100),
/**
* <pre>
* Sound Event Revalidation
* </pre>
*
* <code>SOUND_EVENT_REVALIDATION = 101;</code>
*/
SOUND_EVENT_REVALIDATION(101),
/**
* <pre>
* Sound Event Recognition
* </pre>
*
* <code>SOUND_EVENT_FIXED = 102;</code>
*/
SOUND_EVENT_FIXED(102),
/**
* <pre>
* Sound Scene Recognition
* </pre>
*
* <code>SOUND_SCENE_FIXED = 103;</code>
*/
SOUND_SCENE_FIXED(103),
/**
* <pre>
* Face Auth (Enrollable)
* </pre>
*
* <code>FACE_BIOMETRIC = 201;</code>
*/
FACE_BIOMETRIC(201),
/**
* <pre>
* Face Recognition
* </pre>
*
* <code>FACE_RECOGNITION = 202;</code>
*/
FACE_RECOGNITION(202),
/**
* <pre>
* Object Recognition
* </pre>
*
* <code>OBJECT_RECOGNITION = 203;</code>
*/
OBJECT_RECOGNITION(203),
/**
* <pre>
* Image Transformation
* </pre>
*
* <code>IMAGE_TRANSFORM = 204;</code>
*/
IMAGE_TRANSFORM(204),
/**
* <pre>
* Unknown Model Type
* </pre>
*
* <code>UNKNOWN = 1000;</code>
*/
UNKNOWN(1000),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Voice Auth Text Dependent (Enrollable)
* </pre>
*
* <code>VOICE_BIOMETRIC_TEXT_DEPENDENT = 0;</code>
*/
public static final int VOICE_BIOMETRIC_TEXT_DEPENDENT_VALUE = 0;
/**
* <pre>
* Voice Auth Text Independent (Enrollable)
* </pre>
*
* <code>VOICE_BIOMETRIC_TEXT_INDEPENDENT = 1;</code>
*/
public static final int VOICE_BIOMETRIC_TEXT_INDEPENDENT_VALUE = 1;
/**
* <pre>
* Voice Wakeword (Enrollable)
* </pre>
*
* <code>VOICE_BIOMETRIC_WAKEWORD = 2;</code>
*/
public static final int VOICE_BIOMETRIC_WAKEWORD_VALUE = 2;
/**
* <pre>
* Voice Wakeword
* </pre>
*
* <code>VOICE_EVENT_WAKEWORD = 3;</code>
*/
public static final int VOICE_EVENT_WAKEWORD_VALUE = 3;
/**
* <pre>
* Voice Grammar Recognition such as LVCSR
* </pre>
*
* <code>VOICE_TRANSCRIBE_GRAMMAR = 4;</code>
*/
public static final int VOICE_TRANSCRIBE_GRAMMAR_VALUE = 4;
/**
* <pre>
* Voice Commands and Search recognition
* </pre>
*
* <code>VOICE_TRANSCRIBE_COMMAND_AND_SEARCH = 5;</code>
*/
public static final int VOICE_TRANSCRIBE_COMMAND_AND_SEARCH_VALUE = 5;
/**
* <pre>
* Voice activity detection
* </pre>
*
* <code>VOICE_RECOGNITION_ACTIVITY_DETECTION = 6;</code>
*/
public static final int VOICE_RECOGNITION_ACTIVITY_DETECTION_VALUE = 6;
/**
* <pre>
* Voice feature extractor
* </pre>
*
* <code>VOICE_FEATURE_EXTRACTOR = 7;</code>
*/
public static final int VOICE_FEATURE_EXTRACTOR_VALUE = 7;
/**
* <pre>
* Voice digit recognizer for liveness
* </pre>
*
* <code>VOICE_BIOMETRIC_LIVENESS_DIGIT = 8;</code>
*/
public static final int VOICE_BIOMETRIC_LIVENESS_DIGIT_VALUE = 8;
/**
* <pre>
* Sound Event Auth (Enrollable)
* </pre>
*
* <code>SOUND_EVENT_ENROLLABLE = 100;</code>
*/
public static final int SOUND_EVENT_ENROLLABLE_VALUE = 100;
/**
* <pre>
* Sound Event Revalidation
* </pre>
*
* <code>SOUND_EVENT_REVALIDATION = 101;</code>
*/
public static final int SOUND_EVENT_REVALIDATION_VALUE = 101;
/**
* <pre>
* Sound Event Recognition
* </pre>
*
* <code>SOUND_EVENT_FIXED = 102;</code>
*/
public static final int SOUND_EVENT_FIXED_VALUE = 102;
/**
* <pre>
* Sound Scene Recognition
* </pre>
*
* <code>SOUND_SCENE_FIXED = 103;</code>
*/
public static final int SOUND_SCENE_FIXED_VALUE = 103;
/**
* <pre>
* Face Auth (Enrollable)
* </pre>
*
* <code>FACE_BIOMETRIC = 201;</code>
*/
public static final int FACE_BIOMETRIC_VALUE = 201;
/**
* <pre>
* Face Recognition
* </pre>
*
* <code>FACE_RECOGNITION = 202;</code>
*/
public static final int FACE_RECOGNITION_VALUE = 202;
/**
* <pre>
* Object Recognition
* </pre>
*
* <code>OBJECT_RECOGNITION = 203;</code>
*/
public static final int OBJECT_RECOGNITION_VALUE = 203;
/**
* <pre>
* Image Transformation
* </pre>
*
* <code>IMAGE_TRANSFORM = 204;</code>
*/
public static final int IMAGE_TRANSFORM_VALUE = 204;
/**
* <pre>
* Unknown Model Type
* </pre>
*
* <code>UNKNOWN = 1000;</code>
*/
public static final int UNKNOWN_VALUE = 1000;
@java.lang.Override
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ModelType valueOf(int value) {
return forNumber(value);
}
public static ModelType forNumber(int value) {
switch (value) {
case 0: return VOICE_BIOMETRIC_TEXT_DEPENDENT;
case 1: return VOICE_BIOMETRIC_TEXT_INDEPENDENT;
case 2: return VOICE_BIOMETRIC_WAKEWORD;
case 3: return VOICE_EVENT_WAKEWORD;
case 4: return VOICE_TRANSCRIBE_GRAMMAR;
case 5: return VOICE_TRANSCRIBE_COMMAND_AND_SEARCH;
case 6: return VOICE_RECOGNITION_ACTIVITY_DETECTION;
case 7: return VOICE_FEATURE_EXTRACTOR;
case 8: return VOICE_BIOMETRIC_LIVENESS_DIGIT;
case 100: return SOUND_EVENT_ENROLLABLE;
case 101: return SOUND_EVENT_REVALIDATION;
case 102: return SOUND_EVENT_FIXED;
case 103: return SOUND_SCENE_FIXED;
case 201: return FACE_BIOMETRIC;
case 202: return FACE_RECOGNITION;
case 203: return OBJECT_RECOGNITION;
case 204: return IMAGE_TRANSFORM;
case 1000: return UNKNOWN;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ModelType>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
ModelType> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ModelType>() {
@java.lang.Override
public ModelType findValueByNumber(int number) {
return ModelType.forNumber(number);
}
};
public static com.google.protobuf.Internal.EnumVerifier
internalGetVerifier() {
return ModelTypeVerifier.INSTANCE;
}
private static final class ModelTypeVerifier implements
com.google.protobuf.Internal.EnumVerifier {
static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new ModelTypeVerifier();
@java.lang.Override
public boolean isInRange(int number) {
return ModelType.forNumber(number) != null;
}
};
private final int value;
private ModelType(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:sensory.api.common.ModelType)
}
|
Whoaa512/list-share
|
src/redux/modules/listMeta.js
|
import get from 'lodash/get'
import isEmpty from 'lodash/isEmpty'
import cloneDeep from 'lodash/cloneDeep'
import { getUser } from './auth'
const STATE_PATH = 'listMeta'
const LOAD = `list-share/${STATE_PATH}/LOAD`
const LOAD_SUCCESS = `list-share/${STATE_PATH}/LOAD_SUCCESS`
const LOAD_FAIL = `list-share/${STATE_PATH}/LOAD_FAIL`
const UPDATE = `list-share/${STATE_PATH}/UPDATE`
const UPDATE_SUCCESS = `list-share/${STATE_PATH}/UPDATE_SUCCESS`
const UPDATE_FAIL = `list-share/${STATE_PATH}/UPDATE_FAIL`
const initialState = {
loaded: false
}
export default function reducer (state = initialState, action = {}) {
switch (action.type) {
case LOAD:
return {
...state,
loading: true,
loaded: false
}
case LOAD_SUCCESS:
return {
...state,
loading: false,
loaded: true,
data: action.result
}
case LOAD_FAIL:
return {
...state,
loading: false,
loaded: false,
error: action.error
}
case UPDATE:
return {
...state,
updating: true,
updated: false
}
case UPDATE_SUCCESS:
return {
...state,
updating: false,
updated: true,
data: action.result
}
case UPDATE_FAIL:
return {
...state,
updating: false,
updated: false,
error: action.error
}
default:
return state
}
}
export function isLoaded (globalState) {
return get(globalState, `${STATE_PATH}.loaded`, false)
}
export function getData (globalState) {
return get(globalState, `${STATE_PATH}.data`, {})
}
export function getError (globalState) {
return get(globalState, `${STATE_PATH}.error`, {})
}
export function load () {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.get('/listMeta/load')
}
}
export function loadListMetaFromLocal () {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client, getState) => {
return new Promise((resolve, reject) => {
let { listMeta } = getUser(getState())
listMeta = cloneDeep(listMeta)
if (isEmpty(listMeta)) {
return reject(new Error('Local list meta not found.'))
}
resolve(listMeta)
})
}
}
}
export function update (data) {
return {
types: [UPDATE, UPDATE_SUCCESS, UPDATE_FAIL],
promise: (client) => client.post('/listMeta/update', { data })
}
}
|
lfaraone/sal
|
profiles/migrations/0001_squashed_0003_auto_20180411_1623.py
|
<reponame>lfaraone/sal
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-04-12 18:29
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [(b'profiles', '0001_initial'), (b'profiles', '0002_auto_20180411_1423'), (b'profiles', '0003_auto_20180411_1623')]
initial = True
dependencies = [
('server', '0068_auto_20180313_1440'),
]
operations = [
migrations.CreateModel(
name='Payload',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(max_length=255)),
('identifier', models.CharField(db_index=True, max_length=255)),
('uuid', models.CharField(max_length=255)),
],
options={
'ordering': ['identifier'],
},
),
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False)),
('identifier', models.CharField(db_index=True, max_length=255)),
('display_name', models.CharField(max_length=255)),
('description', models.TextField()),
('install_date', models.DateTimeField()),
('organization', models.CharField(max_length=255)),
('uuid', models.CharField(max_length=255)),
('verification_state', models.CharField(max_length=255)),
('machine', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='server.Machine')),
],
options={
'ordering': ['display_name'],
},
),
migrations.AddField(
model_name='payload',
name='profile',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='profiles.Profile'),
),
migrations.RenameField(
model_name='payload',
old_name='type',
new_name='payload_type',
),
migrations.AlterField(
model_name='payload',
name='id',
field=models.BigAutoField(primary_key=True, serialize=False),
),
]
|
brettbevers/programr
|
lib/string.rb
|
class String
def to_s_with_arguments(*args)
to_s_without_arguments
end
alias_method :to_s_without_arguments, :to_s
alias_method :to_s, :to_s_with_arguments
end
|
xjc90s/serenity-core
|
serenity-core/src/main/java/net/thucydides/core/steps/StepLibraryCreator.java
|
package net.thucydides.core.steps;
import net.thucydides.core.util.EnvironmentVariables;
import static net.thucydides.core.ThucydidesSystemProperty.STEP_CREATION_STRATEGY;
class StepLibraryCreator {
static StepLibraryCreationStrategy usingConfiguredCreationStrategy(StepFactory stepFactory,
StepsAnnotatedField stepsField,
EnvironmentVariables environmentVariables) {
boolean useDefaultStrategy = STEP_CREATION_STRATEGY.from(environmentVariables,"default")
.equalsIgnoreCase("default");
return (useDefaultStrategy) ?
new IndividualInstancesByDefaultStepCreationStrategy(stepFactory, stepsField) :
new SharedInstancesByDefaultStepCreationStrategy(stepFactory, stepsField);
}
}
|
Starkovsky/mossebo-shop
|
resources/assets/js/store/catalog/modules/sort/index.js
|
import * as actionTypes from './types'
const sortMethods = {
/**
* Сортировка по популярности.
*
* @param products
* @returns {Array}
*/
sortPopular(products) {
return _.orderBy(products, ['popular', 'showed', 'id'], ['desc', 'desc', 'asc'])
},
sortCheaper(products) {
return products.sort((a, b) => a.getPrice() - b.getPrice())
},
sortExpensive(products) {
return products.sort((a, b) => b.getPrice() - a.getPrice())
},
/**
* Сортировка по новинкам.
*
* @param products
* @returns {Array}
*/
sortNew(products) {
return _.orderBy(products, ['new', 'id'], ['desc', 'desc'])
},
/**
* Сортировка по названию.
*
* @param products
* @returns {Array}
*/
sortName(products) {
return _.orderBy(products, ['name', 'id'])
},
/**
* Сортировка по скидке.
*
* @param products
* @returns {Array}
*/
sortDiscount(products) {
return products.sort((a, b) => {
let result = b.getDiscountPercent() - a.getDiscountPercent()
if (result === 0) {
return a.id - b.id
}
return result
})
},
/**
* Сортировка по соответствию поисковому запросу.
*
* @param products
* @returns {Array}
*/
sortRelevance(products) {
return products.sort((a, b) => {
let result = a.getSearchRelevance() - b.getSearchRelevance()
if (result === 0) {
return a.id - b.id
}
return result
})
}
}
const types = {
relevance: 'По релевантности',
popular: 'Популярное',
cheaper: 'Сначала дешевле',
expensive: 'Сначала дороже',
discount: 'Со скидками',
new: 'Новинки',
}
export default {
namespaced: true,
state: {
types: {},
active: 'popular'
},
actions: {
init({state}, params = {}) {
if (params.active && params.active in types) {
state.active = params.active
}
if (params.types && params.types instanceof Array) {
state.types = params.types.reduce((acc, item) => {
if (item in types) {
acc[item] = types[item]
}
return acc
}, {})
}
else {
state.types = types
}
},
sort({state}, products) {
if (! state.active) {
return products
}
let methodName = 'sort' + _.upperFirst(_.camelCase(state.active))
if (methodName in sortMethods) {
return sortMethods[methodName](products)
}
return products
},
setType({state, commit}, type) {
if (type && typeof state.types[type] !== 'undefined') {
commit(actionTypes.CATALOG_SET_SORT, type)
}
},
},
mutations: {
[actionTypes.CATALOG_SET_SORT](state, sort) {
state.active = sort
}
}
}
|
efornara/cc65
|
include/_io2.h
|
/*** File generated by inc2h.pl - DO NOT EDIT ***/
/* */
/* io2.inc */
/* */
/* */
/* Copyright (C) 2012-2017 <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. */
/* */
/* 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. */
/* */
#define REQPUT 0x0201
#define REQEND 0x0202
#define REQRES 0x0203
#define REQPTRLO 0x0204
#define REQPTRHI 0x0205
#define ENABLE 0x0210
#define FRMFPS 0x0211
#define FRMDRAW 0x0212
#define GKEY0 0x0213
#define GKEY1 0x0214
#define RANDOM 0x0217
#define KEYBUF 0x0218
#define CONCOLS 0x0220
#define CONROWS 0x0221
#define CONCX 0x0222
#define CONCY 0x0223
#define CONCCHR 0x0224
#define CONCFG 0x0225
#define CONCBG 0x0226
#define CONVIDEO 0x0228
#define CONROW0 0x0228
#define CONROW1 0x0232
#define CONROW2 0x023C
#define CONROW3 0x0246
#define LID 0x0250
#define LCTL 0x0251
#define LX 0x0252
#define LY 0x0253
#define SFRAME 0x0254
#define STRANSFM 0x0255
#define SCWITH 0x0256
#define TCOLLO 0x0257
#define TCOLHI 0x0258
#define TROWLO 0x0259
#define TROWHI 0x025A
#define TCELL 0x025B
#define REQDAT 0x0260
#define REQ_NOREQ 0x00
#define REQ_TIME 0x02
#define REQ_LOADROM 0x06
#define REQ_RSFORMAT 0x08
#define REQ_RLOAD 0x09
#define REQ_RSAVE 0x0A
#define REQ_RDELETE 0x0B
#define REQ_DPYINFO 0x10
#define REQ_SETBGCOL 0x11
#define REQ_SETPAL 0x12
#define REQ_SETBGIMG 0x13
#define REQ_IDESTROY 0x14
#define REQ_IDIM 0x15
#define REQ_IINFO 0x16
#define REQ_ILOAD 0x17
#define REQ_IDUMMY 0x18
#define REQ_IPNGGEN 0x19
#define REQ_IEMPTY 0x1A
#define REQ_IMKIMMUT 0x1B
#define REQ_IRAWRGBA 0x1C
#define REQ_LMVIEW 0x20
#define REQ_LMPOS 0x21
#define REQ_LDESTROY 0x22
#define REQ_LDIM 0x23
#define REQ_LTILED 0x24
#define REQ_LSPRITE 0x25
#define REQ_LSETPOS 0x26
#define REQ_LGETPOS 0x27
#define REQ_LMOVE 0x28
#define REQ_LSETPRI 0x29
#define REQ_LGETPRI 0x2A
#define REQ_LTLANIM 0x2B
#define REQ_LTLFILL 0x2C
#define REQ_LTLPUT 0x2D
#define REQ_LTLSCRLL 0x2E
#define REQ_LSPCOPY 0x2F
#define REQ_LSPAPOS 0x30
#define REQ_LSPREFPX 0x31
#define REQ_LSPCLRCT 0x32
#define REQ_GAMESET 0x3C
#define REQ_FXTONE 0x40
#define REQ_FXVIBRA 0x41
#define REQ_FXFLASH 0x42
#define ENABLE_BGCOL 0x01
#define ENABLE_BGIMG 0x02
#define ENABLE_CONSOLE 0x04
#define ENABLE_LAYERS 0x08
#define TIME_ABS 0x01
#define TIME_RESET 0x02
#define TIME_1 0x01
#define TIME_10 0x02
#define TIME_100 0x03
#define TIME_1000 0x04
#define DPYINFO_WIDTH 0x00
#define DPYINFO_HEIGHT 0x02
#define DPYINFO_COLORDEPTH 0x04
#define DPYINFO_ALPHADEPTH 0x05
#define DPYINFO_FLAGS 0x06
#define DPYINFO_FLAGS_ISCOLOR 0x80
#define DPYINFO_FLAGS_ISMIDP2 0x40
#define DPYINFO_FLAGS_ISTOUCH 0x20
#define SETPAL_STD 0x00
#define SETPAL_RGB 0x01
#define IINFO_WIDTH 0x00
#define IINFO_HEIGHT 0x02
#define IINFO_FLAGS 0x04
#define IINFO_FLAGS_ISMUTABLE 0x80
#define IDUMMY_SIMPLE 0x01
#define IDUMMY_SPRITE 0x02
#define IDUMMY_TILES 0x03
#define IPNGGEN_CT_GRAYSCALE 0x00
#define IPNGGEN_CT_TRUECOLOR 0x02
#define IPNGGEN_CT_INDEXED_COLOR 0x03
#define IPNGGEN_CT_GRAYSCALE_ALPHA 0x04
#define IPNGGEN_CT_TRUECOLOR_ALPHA 0x06
#define IPNGGEN_FLAGS_IDX0TRANSP 0x01
#define IPNGGEN_FLAGS_PALREF 0x02
#define IPNGGEN_FLAGS_ZOOM0 0x04
#define IPNGGEN_FLAGS_ZOOM1 0x08
#define IPNGGEN_FLAGS_ZOOM2 0x10
#define IRAWRGBA_FLAGS_ALPHA 0x01
#define DATATYPE_U8 0x01
#define DATATYPE_I8 0x02
#define DATATYPE_U16 0x03
#define DATATYPE_I16 0x04
#define LCTL_SHIFTX0 0x01
#define LCTL_SHIFTX1 0x02
#define LCTL_SHIFTY0 0x04
#define LCTL_SHIFTY1 0x08
#define LCTL_PXLCOLL 0x40
#define LCTL_ENABLE 0x80
#define LCTL_SHIFTX_MASK 0x03
#define LCTL_SHIFTY_MASK 0x0C
#define LTRANSFM_NONE 0x00
#define LTRANSFM_ROT90 0x05
#define LTRANSFM_ROT180 0x03
#define LTRANSFM_ROT270 0x06
#define LTRANSFM_MIRROR 0x02
#define LTRANSFM_MIRROR_ROT90 0x07
#define LTRANSFM_MIRROR_ROT180 0x01
#define LTRANSFM_MIRROR_ROT270 0x04
#define GKEY0_UP 0x02
#define GKEY0_LEFT 0x04
#define GKEY0_RIGHT 0x20
#define GKEY0_DOWN 0x40
#define GKEY1_FIRE 0x01
#define GKEY1_A 0x02
#define GKEY1_B 0x04
#define GKEY1_C 0x08
#define GKEY1_D 0x10
#define GAMESET_COLS 0x00
#define GAMESET_ROWS 0x02
#define TILESET_SILK 0xFF
#define TILESET_FONT 0xFE
#define TILESET_MICRO 0xFD
#define ALINE_TOP 0x01
#define ALINE_LEFT 0x02
#define ALINE_RIGHT 0x04
#define ALINE_BOTTOM 0x08
#define COLOR_BLACK 0x00
#define COLOR_WHITE 0x01
#define COLOR_RED 0x02
#define COLOR_CYAN 0x03
#define COLOR_VIOLET 0x04
#define COLOR_PURPLE 0x04
#define COLOR_GREEN 0x05
#define COLOR_BLUE 0x06
#define COLOR_YELLOW 0x07
#define COLOR_ORANGE 0x08
#define COLOR_BROWN 0x09
#define COLOR_LIGHTRED 0x0A
#define COLOR_GRAY1 0x0B
#define COLOR_GRAY2 0x0C
#define COLOR_LIGHTGREEN 0x0D
#define COLOR_LIGHTBLUE 0x0E
#define COLOR_GRAY3 0x0F
#define CH_ULCORNER 0x8C
#define CH_URCORNER 0x8A
#define CH_LLCORNER 0x85
#define CH_LRCORNER 0x83
#define CH_HLINE 0x86
#define CH_VLINE 0x89
#define CH_TTEE 0x8E
#define CH_RTEE 0x89
#define CH_BTEE 0x8B
#define CH_LTEE 0x8D
#define CH_CROSS 0x8F
|
pawanrajoriya/axis-axis1-java
|
axis-rt-core/src/main/java/org/apache/axis/components/encoding/AbstractXMLEncoder.java
|
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.components.encoding;
import org.apache.axis.utils.Messages;
/**
*
* Abstract class for XML String encoders.
*
* The new encoding mechanism fixes the following bugs/issues:
* http://nagoya.apache.org/bugzilla/show_bug.cgi?id=15133
* http://nagoya.apache.org/bugzilla/show_bug.cgi?id=15494
* http://nagoya.apache.org/bugzilla/show_bug.cgi?id=19327
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>"><NAME></a>
*
*/
public abstract class AbstractXMLEncoder implements XMLEncoder {
protected static final String AMP = "&";
protected static final String QUOTE = """;
protected static final String LESS = "<";
protected static final String GREATER = ">";
protected static final String LF = "\n";
protected static final String CR = "\r";
protected static final String TAB = "\t";
/**
* gets the encoding supported by this encoder
* @return string
*/
public abstract String getEncoding();
/**
* Encode a string
* @param xmlString string to be encoded
* @return encoded string
*/
public String encode(String xmlString) {
if(xmlString == null) {
return "";
}
char[] characters = xmlString.toCharArray();
StringBuffer out = null;
char character;
for (int i = 0; i < characters.length; i++) {
character = characters[i];
switch (character) {
// we don't care about single quotes since axis will
// use double quotes anyway
case '&':
if (out == null) {
out = getInitialByteArray(xmlString, i);
}
out.append(AMP);
break;
case '"':
if (out == null) {
out = getInitialByteArray(xmlString, i);
}
out.append(QUOTE);
break;
case '<':
if (out == null) {
out = getInitialByteArray(xmlString, i);
}
out.append(LESS);
break;
case '>':
if (out == null) {
out = getInitialByteArray(xmlString, i);
}
out.append(GREATER);
break;
case '\n':
if (out == null) {
out = getInitialByteArray(xmlString, i);
}
out.append(LF);
break;
case '\r':
if (out == null) {
out = getInitialByteArray(xmlString, i);
}
out.append(CR);
break;
case '\t':
if (out == null) {
out = getInitialByteArray(xmlString, i);
}
out.append(TAB);
break;
default:
if (character < 0x20) {
throw new IllegalArgumentException(Messages.getMessage("invalidXmlCharacter00", Integer.toHexString(character), xmlString.substring(0, i)));
} else {
if (out != null) {
out.append(character);
}
}
break;
}
}
if (out == null) {
return xmlString;
}
return out.toString();
}
protected StringBuffer getInitialByteArray(String aXmlString, int pos) {
return new StringBuffer(aXmlString.substring(0, pos));
}
}
|
chigley/advent2021
|
day04/board.go
|
<reponame>chigley/advent2021
package day04
const BoardDimension = 5
type Board [][]int
func (b Board) IsWon(draw map[int]struct{}) bool {
row:
for _, row := range b {
for _, n := range row {
if _, ok := draw[n]; !ok {
continue row
}
}
return true
}
column:
for i := 0; i < BoardDimension; i++ {
for _, row := range b {
if _, ok := draw[row[i]]; !ok {
continue column
}
}
return true
}
return false
}
func (b Board) SumUnmarked(draw map[int]struct{}) int {
var sumUnmarked int
for _, row := range b {
for _, n := range row {
if _, ok := draw[n]; !ok {
sumUnmarked += n
}
}
}
return sumUnmarked
}
|
douglasmiller/recurly-client-ruby
|
lib/recurly/resources/subscription_add_on.rb
|
<gh_stars>10-100
# This file is automatically created by Recurly's OpenAPI generation process
# and thus any edits you make by hand will be lost. If you wish to make a
# change to this file, please create a Github issue explaining the changes you
# need and we will usher them to the appropriate places.
module Recurly
module Resources
class SubscriptionAddOn < Resource
# @!attribute add_on
# @return [AddOnMini] Just the important parts.
define_attribute :add_on, :AddOnMini
# @!attribute add_on_source
# @return [String] Used to determine where the associated add-on data is pulled from. If this value is set to `plan_add_on` or left blank, then add-on data will be pulled from the plan's add-ons. If the associated `plan` has `allow_any_item_on_subscriptions` set to `true` and this field is set to `item`, then the associated add-on data will be pulled from the site's item catalog.
define_attribute :add_on_source, String
# @!attribute created_at
# @return [DateTime] Created at
define_attribute :created_at, DateTime
# @!attribute expired_at
# @return [DateTime] Expired at
define_attribute :expired_at, DateTime
# @!attribute id
# @return [String] Subscription Add-on ID
define_attribute :id, String
# @!attribute object
# @return [String] Object type
define_attribute :object, String
# @!attribute quantity
# @return [Integer] Add-on quantity
define_attribute :quantity, Integer
# @!attribute revenue_schedule_type
# @return [String] Revenue schedule type
define_attribute :revenue_schedule_type, String
# @!attribute subscription_id
# @return [String] Subscription ID
define_attribute :subscription_id, String
# @!attribute tier_type
# @return [String] The pricing model for the add-on. For more information, [click here](https://docs.recurly.com/docs/billing-models#section-quantity-based). See our [Guide](https://developers.recurly.com/guides/item-addon-guide.html) for an overview of how to configure quantity-based pricing models.
define_attribute :tier_type, String
# @!attribute tiers
# @return [Array[SubscriptionAddOnTier]] If tiers are provided in the request, all existing tiers on the Subscription Add-on will be removed and replaced by the tiers in the request.
define_attribute :tiers, Array, { :item_type => :SubscriptionAddOnTier }
# @!attribute unit_amount
# @return [Float] Supports up to 2 decimal places.
define_attribute :unit_amount, Float
# @!attribute unit_amount_decimal
# @return [String] Supports up to 9 decimal places.
define_attribute :unit_amount_decimal, String
# @!attribute updated_at
# @return [DateTime] Updated at
define_attribute :updated_at, DateTime
# @!attribute usage_percentage
# @return [Float] The percentage taken of the monetary amount of usage tracked. This can be up to 4 decimal places. A value between 0.0 and 100.0. Required if add_on_type is usage and usage_type is percentage.
define_attribute :usage_percentage, Float
end
end
end
|
sarang-apps/darshan_browser
|
components/password_manager/core/browser/site_affiliation/asset_link_data.cc
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/site_affiliation/asset_link_data.h"
#include <algorithm>
#include <utility>
#include "base/json/json_reader.h"
#include "base/json/json_value_converter.h"
#include "base/values.h"
namespace password_manager {
namespace {
constexpr char kGetLoginsRelation[] =
"delegate_permission/common.get_login_creds";
constexpr char kWebNamespace[] = "web";
struct Target {
std::string target_namespace;
std::string site;
static void RegisterJSONConverter(
base::JSONValueConverter<Target>* converter) {
converter->RegisterStringField("namespace", &Target::target_namespace);
converter->RegisterStringField("site", &Target::site);
}
};
struct Statement {
std::string include;
std::vector<std::unique_ptr<std::string>> relations;
Target target;
static void RegisterJSONConverter(
base::JSONValueConverter<Statement>* converter) {
converter->RegisterStringField("include", &Statement::include);
converter->RegisterRepeatedString("relation", &Statement::relations);
converter->RegisterNestedField("target", &Statement::target);
}
};
} // namespace
AssetLinkData::AssetLinkData() = default;
AssetLinkData::AssetLinkData(AssetLinkData&& other) noexcept = default;
AssetLinkData::~AssetLinkData() = default;
AssetLinkData& AssetLinkData::operator=(AssetLinkData&& other) = default;
bool AssetLinkData::Parse(const std::string& data) {
std::unique_ptr<base::Value> value = base::JSONReader::ReadDeprecated(data);
if (!value || !value->is_list())
return false;
base::JSONValueConverter<Statement> converter;
for (const auto& item : value->GetList()) {
Statement statement;
if (converter.Convert(item, &statement)) {
if (!statement.include.empty()) {
// The statement is an 'include' statement.
GURL include(statement.include);
if (include.is_valid() && include.SchemeIs(url::kHttpsScheme))
includes_.push_back(std::move(include));
} else if (std::any_of(statement.relations.begin(),
statement.relations.end(),
[](const std::unique_ptr<std::string>& relation) {
return *relation == kGetLoginsRelation;
})) {
// 'get_login_creds' statement. Only web HTTPS targets are interesting.
if (statement.target.target_namespace == kWebNamespace) {
GURL site(statement.target.site);
if (site.is_valid() && site.SchemeIs(url::kHttpsScheme))
targets_.push_back(std::move(site));
}
}
} else {
return false;
}
}
return true;
}
} // namespace password_manager
|
Trickcorrea/workflow
|
src/tests/healthCheck.test.js
|
<reponame>Trickcorrea/workflow<gh_stars>1-10
require("dotenv").config();
const axios = require("axios");
const { startServer } = require("../app");
const { delay } = require("./utils/auxiliar");
const { config } = require("./utils/requestConfig");
let server;
beforeAll(() => {
server = startServer(3001);
axios.defaults.baseURL = `${config.baseURL}/`;
axios.defaults.headers = config.headers;
axios.defaults.validateStatus = config.validateStatus;
});
beforeEach(async () => {
await delay(100);
});
afterAll(async () => {
await server.close();
});
describe("GET /", () => {
test("should return 200", async () => {
const response = await axios.get("/");
expect(response.status).toBe(200);
});
});
describe("GET /healthcheck", () => {
test("should return 200", async () => {
const response = await axios.get("/");
expect(response.status).toBe(200);
expect(response.data).toBeDefined();
expect(response.data.version).toBeDefined();
expect(response.data.message).toBeDefined();
});
});
|
noah-ubf/bbooxx
|
src/reducers/helpers/tab.js
|
import * as _ from 'lodash';
import { getDescriptorFromList } from '../../libs/modules/descriptor';
import ModulesHelper from './modules';
class TabHelper {
add(state, id, verses = [], verse = null) {
const tabOrder = _.chain(state.tabOrder).without(id).unshift(id).value();
console.log('==>', tabOrder)
return {
...state,
config: {
...state.config,
lists: [
...state.config.lists,
{
id,
type: 'tab',
params: {},
descriptor: getDescriptorFromList(verses),
}
],
selectedTab: id,
},
lists: [
...state.lists,
{
id,
verses: verses.map(v => ({v})),
},
],
selectedVerse: verse,
tabOrder,
};
}
toTemp(state, verses = []) {
return {
...state,
config: {
...state.config,
lists: state.config.lists.map(l => {
if (l.id !== 'temp') return l;
return {
id: 'temp',
type: 'temp',
params: {},
descriptor: getDescriptorFromList(verses),
customized: true,
};
}),
rightBarHidden: false,
selectedTabRight: 'temp',
},
rightBarHidden: false,
lists: state.lists.map(l => {
if (l.id !== 'temp') return l;
return {
id: 'temp',
verses: verses.map(v => ({v})),
};
}),
};
}
remove(state, listId) {
const tabOrder = _.chain(state.tabOrder).without(listId).value();
console.log('==>', tabOrder)
if (_.filter(state.config.lists, l => l.type === 'tab').length <= 1) return state;
const selectedTab = tabOrder[0] || ((listId === state.config.selectedTab)
? _.chain(state.config.lists).find(l => (l.type === 'tab' && l.id !== listId)).get('id').value()
: state.config.selectedTab);
return {
...state,
config: {
...state.config,
lists: [
..._.filter(state.config.lists, l => l.id !== listId),
],
selectedTab,
},
lists: [
..._.filter(state.lists, l => l.id !== listId),
],
selectedVerse: null,
tabOrder,
};
}
select(state, listId) {
const tabOrder = _.chain(state.tabOrder).without(listId).unshift(listId).value();
const selectedTab = listId || _.chain(state.config.lists).find(l => (l.type === 'tab')).get('id').value();
const li = _.find(state.lists, l => (l.id === selectedTab));
const newState = {
...state,
config: {
...state.config,
selectedTab,
},
selectedVerse: null,
tabOrder,
};
if (!_.get(li, 'chapter')) return newState;
return ModulesHelper.selectChapter(newState, li.chapter);
}
}
export default new TabHelper();
|
Zalexanninev15/VitNX
|
docs/search--/s_4766.js
|
<reponame>Zalexanninev15/VitNX
search_result['4766']=["topic_0000000000001254_overloads--.html","VitNX_TreeNode Constructor",""];
|
tektronix/syphon
|
tests/hash/test_openhashfile.py
|
<filename>tests/hash/test_openhashfile.py
"""tests.hash.test_openhashfile.py
Copyright <NAME>, LLC.
Licensed under MIT (https://github.com/tektronix/syphon/blob/master/LICENSE)
"""
import enum
import os
import random
from typing import List, Optional
import pytest
from _pytest.monkeypatch import MonkeyPatch
from py._path.local import LocalPath
import syphon.hash
from .. import get_data_path, rand_string, randomize
class CacheEntryPosition(enum.Enum):
FIRST = 0
RANDOM = 1
LAST = 2
def populate_hash_file(
hash_file: LocalPath,
cache_file: Optional[LocalPath] = None,
cache_position: CacheEntryPosition = CacheEntryPosition.RANDOM,
final_newline: bool = True,
) -> List[syphon.hash.HashEntry]:
# Generate hashfile content.
expected_entries: List[syphon.hash.HashEntry] = [
syphon.hash.HashEntry(os.path.join(get_data_path(), "empty.csv")),
syphon.hash.HashEntry(os.path.join(get_data_path(), "iris.csv")),
syphon.hash.HashEntry(os.path.join(get_data_path(), "iris_plus.csv")),
]
expected_entries = randomize(*expected_entries)
if cache_file is not None:
if cache_position == CacheEntryPosition.FIRST:
expected_entries.insert(0, syphon.hash.HashEntry(cache_file))
elif cache_position == CacheEntryPosition.RANDOM:
expected_entries.insert(
random.randint(1, len(expected_entries) - 1),
syphon.hash.HashEntry(cache_file),
)
elif cache_position == CacheEntryPosition.LAST:
expected_entries.append(syphon.hash.HashEntry(cache_file))
hashfile_content = "\n".join([str(e) for e in expected_entries])
# There's a test that checks for proper handling of files without a trailing
# newline, so we should make our file with the opposite case.
hash_file.write(hashfile_content + "\n" if final_newline else "")
return expected_entries
def test_openhashfile_init(hash_file: LocalPath, hash_type: Optional[str]):
if hash_type is None:
hash_type = syphon.hash.DEFAULT_HASH_TYPE
expected_content = rand_string()
hash_file.write(expected_content)
openhashfile = syphon.hash._OpenHashFile(hash_file, hash_type)
try:
assert expected_content == openhashfile._file_obj.readline()
assert not openhashfile._file_obj.closed
assert openhashfile.hash_type == hash_type
assert openhashfile.line_split is None
finally:
openhashfile._file_obj.close()
def test_openhashfile_close(hash_file: LocalPath):
hash_file.write(rand_string())
openhashfile = syphon.hash._OpenHashFile(hash_file, "")
openhashfile.close()
try:
assert openhashfile._file_obj.closed
finally:
openhashfile._file_obj.close()
def test_openhashfile_items_are_hashentries(tmpdir: LocalPath):
target_hashfile: LocalPath = tmpdir.join("sha256sums")
expected_entries: List[syphon.hash.HashEntry] = populate_hash_file(target_hashfile)
# Iterate through the hash file entries.
with syphon.hash.HashFile(target_hashfile) as openfile:
for actual in openfile:
expected = expected_entries.pop(0)
assert isinstance(actual, syphon.hash.HashEntry)
assert str(expected) == str(actual)
def test_openhashfile_tell(hash_file: LocalPath):
hash_file.write(rand_string())
openhashfile = syphon.hash._OpenHashFile(hash_file, "")
assert openhashfile.tell() == 0
assert openhashfile.tell() == openhashfile._file_obj.tell()
line = openhashfile._file_obj.readline()
assert openhashfile._file_obj.tell() == len(line)
class TestAppend(object):
@staticmethod
def test_adds_to_end(cache_file: LocalPath, hash_file: LocalPath):
cache_file.write(rand_string())
populate_hash_file(hash_file)
expected_final_entry = syphon.hash.HashEntry(cache_file)
with syphon.hash.HashFile(hash_file) as hashfile:
hashfile.append(expected_final_entry)
actual_final_entry: Optional[syphon.hash.HashEntry] = None
with syphon.hash.HashFile(hash_file) as hashfile:
for actual_final_entry in hashfile:
pass
assert actual_final_entry is not None
assert expected_final_entry.binary == actual_final_entry.binary
assert os.path.samefile(
expected_final_entry.filepath, actual_final_entry.filepath
)
assert expected_final_entry.hash == actual_final_entry.hash
assert str(expected_final_entry) == str(actual_final_entry)
@staticmethod
def test_handles_last_line_lacking_newline(
cache_file: LocalPath, hash_file: LocalPath
):
cache_file.write(rand_string())
populate_hash_file(hash_file, final_newline=False)
expected_final_entry = syphon.hash.HashEntry(cache_file)
with syphon.hash.HashFile(hash_file) as hashfile:
hashfile.append(expected_final_entry)
actual_final_entry: Optional[syphon.hash.HashEntry] = None
with syphon.hash.HashFile(hash_file) as hashfile:
for actual_final_entry in hashfile:
pass
assert actual_final_entry is not None
assert expected_final_entry.binary == actual_final_entry.binary
assert os.path.samefile(
expected_final_entry.filepath, actual_final_entry.filepath
)
assert expected_final_entry.hash == actual_final_entry.hash
assert str(expected_final_entry) == str(actual_final_entry)
@staticmethod
def test_populates_first_line_when_hashfile_empty(
cache_file: LocalPath, hash_file: LocalPath
):
cache_file.write(rand_string())
hash_file.write("")
expected_final_entry = syphon.hash.HashEntry(cache_file)
with syphon.hash.HashFile(hash_file) as hashfile:
hashfile.append(expected_final_entry)
actual_first_entry: Optional[syphon.hash.HashEntry] = None
with syphon.hash.HashFile(hash_file) as hashfile:
for actual_first_entry in hashfile:
break
assert actual_first_entry is not None
assert expected_final_entry.binary == actual_first_entry.binary
assert os.path.samefile(
expected_final_entry.filepath, actual_first_entry.filepath
)
assert expected_final_entry.hash == actual_first_entry.hash
assert str(expected_final_entry) == str(actual_first_entry)
@staticmethod
def test_raises_valueerror_on_mismatching_hash_type(
cache_file: LocalPath, hash_file: LocalPath
):
cache_file.write(rand_string())
hash_file.write("")
entry = syphon.hash.HashEntry(cache_file)
entry.hash_type = "md5"
with pytest.raises(ValueError, match=entry.hash_type):
with syphon.hash.HashFile(hash_file) as hashfile:
hashfile.append(entry)
class TestUpdate(object):
@staticmethod
@pytest.mark.parametrize(
"entry_position",
[CacheEntryPosition.FIRST, CacheEntryPosition.RANDOM, CacheEntryPosition.LAST],
)
@pytest.mark.parametrize("final_newline", [True, False])
def test_updates_existing_entry(
cache_file: LocalPath,
hash_file: LocalPath,
entry_position: CacheEntryPosition,
final_newline: bool,
):
cache_file.write(rand_string())
populate_hash_file(
hash_file,
cache_file=cache_file,
cache_position=entry_position,
final_newline=final_newline,
)
cache_file.write(rand_string())
expected_entry = syphon.hash.HashEntry(cache_file)
with syphon.hash.HashFile(hash_file) as hashfile:
hashfile.update(expected_entry)
actual_entry: Optional[syphon.hash.HashEntry] = None
with syphon.hash.HashFile(hash_file) as hashfile:
for actual_entry in hashfile:
if os.path.samefile(expected_entry.filepath, actual_entry.filepath):
break
assert actual_entry is not None
assert expected_entry.binary == actual_entry.binary
assert os.path.samefile(expected_entry.filepath, actual_entry.filepath)
assert expected_entry.hash == actual_entry.hash
assert str(expected_entry) == str(actual_entry)
@staticmethod
def test_appends_when_entry_does_not_exist(
monkeypatch: MonkeyPatch, cache_file: LocalPath, hash_file: LocalPath
):
def raise_assertionerror(*args, **kwargs):
raise AssertionError()
with monkeypatch.context() as m:
# Throw an AssertionError when append is called.
m.setattr(syphon.hash._OpenHashFile, "append", value=raise_assertionerror)
cache_file.write(rand_string())
populate_hash_file(hash_file)
entry = syphon.hash.HashEntry(cache_file)
with pytest.raises(AssertionError):
with syphon.hash.HashFile(hash_file) as hashfile:
hashfile.update(entry)
@staticmethod
def test_raises_valueerror_on_mismatching_hash_type(
cache_file: LocalPath, hash_file: LocalPath
):
cache_file.write(rand_string())
hash_file.write("")
entry = syphon.hash.HashEntry(cache_file)
entry.hash_type = "md5"
with pytest.raises(ValueError, match=entry.hash_type):
with syphon.hash.HashFile(hash_file) as hashfile:
hashfile.update(entry)
|
H-Tatsuhiro/Com_Pro-Cpp
|
AtCoder/abc156/c/main.cpp
|
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int N; cin >> N;
vector<int> X(N, 0);
for (int i = 0; i < N; ++i) cin >> X[i];
vector<int> C(100, 0);
int ans = 10000000;
for (int i = 1; i <= 100 ; ++i) {
int cost_sum = 0;
for (int j = 0; j < N; ++j) {
cost_sum += pow(X[j] - i, 2);
}
ans = min(ans, cost_sum);
}
cout << ans << endl;
}
|
giantoak/OpenAds-Flask
|
app/static/scripts/xdataht/modules/graph/graph.js
|
<reponame>giantoak/OpenAds-Flask
/**
* Copyright (c) 2013 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released under the MIT License.
*
* 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.
*/
define(['jquery', '../util/ui_util', './radial_layout', './column_layout', '../util/rest', './controlsPanel', '../util/colors'],
function($, ui_util, radial_layout, column_layout, rest, controlsPanel, colors) {
var ENABLE_ZOOM_PAN = aperture.config.get()['xdataht.config']['enable-zoom-pan'],
MAX_GRAPH_NODES = aperture.config.get()['xdataht.config']['max-graph-nodes'],
GRAPH_CONTROLS_CONTAINER_WIDTH = 150;
var displayAjaxLoader = function(container) {
var loaderDiv = $('<div/>');
container.empty();
loaderDiv.css({
'background' : 'url("./img/ajaxLoader.gif") no-repeat center center',
'height' : '100%',
'width' : '100%'
});
container.append(loaderDiv);
};
var getMousePos = function(e) {
var clientX = e.clientX;
var clientY = e.clientY;
if (clientX==undefined) {
if (e.originalEvent) {
clientX = e.originalEvent.clientX;
clientY = e.originalEvent.clientY;
} else if (e.source) {
clientX = e.source.clientX;
clientY = e.source.clientY;
}
}
return {x:clientX,y:clientY};
};
var createWidget = function(appwidget, baseUrl, nodeClickCallback) {
var container = appwidget.graphCanvasContainer,
graphWidgetObj = {
graphCanvas: null,
graphCanvasPadding: {top:0,bottom:0,left:0,right:0},
graphCanvasOffset: {x:0,y:0},
graphZoom: 0,
graphPan: {x:0,y:0},
bDisplayingGraph: false,
preclusterType:null,
datasetName:null,
clustersetName:null,
plot: null,
controlsPanelContainer: null,
controlsPanel: null,
previousGraphData: null,
ATTRIBUTE_MODE: window.location.href.indexOf('?attributeid=')!=-1,
isRadialLayout: amplify.store('graphLayout'),
rLayer:null,
linkLayer:null,
nodeLayer:null,
init: function() {
if (this.isRadialLayout === undefined) this.isRadialLayout = false;
this.createGraphCanvas();
this.createControlsCanvas();
},
createControlsCanvas: function(){
var jqContainer = $(container),
controlsPanelContainerHeight = 79;
if (this.controlsPanelContainer) {
this.controlsPanelContainer.empty();
this.controlsPanel = null;
}
this.controlsPanelContainer = $('<div/>');
this.controlsPanelContainer.css({
position:'absolute',
top:'2px',
right:'-1px',
width:GRAPH_CONTROLS_CONTAINER_WIDTH + 'px',
height:controlsPanelContainerHeight + 'px',
overflow:'hidden',
opacity:1
});
jqContainer.append(this.controlsPanelContainer);
this.controlsPanel = controlsPanel.createWidget(this, controlsPanelContainerHeight);
},
createGraphCanvas: function() {
this.graphCanvas = $('<div/>', {id: 'NodeLink' + ui_util.uuid()});
this.graphCanvas.css({
'position':'relative',
'top':'0px',
'left':'0px'
});
this.graphCanvas.width(container.width());
this.graphCanvas.height(container.height());
container.append(this.graphCanvas);
},
update: function() {
if (this.plot) {
this.sizeChanged();
return;
}
this.createPlot();
},
selectNode: function(nodeId) {
var updated = this.selectedNodes.clear();
updated.push(this.selectedNodes.add(nodeId));
this.nodeLayer.all().where('id', updated).and(this.linkLayer.all()).redraw().toFront('labeled');
},
selectLinkedAds: function (event) {
if(this.selectLinksFn) this.selectLinksFn(event);
},
buildRings: function() {
if (!this.rLayer) return;
if(this.isRadialLayout) {
this.rLayer.all([
{color: colors.GRAPH_RING_4, radius: 2.5},
{color: colors.GRAPH_RING_3, radius: 0.4375},
{color: colors.GRAPH_RING_2, radius: 0.3125},
{color: colors.GRAPH_RING_1, radius: 0.1875}
]);
} else {
this.rLayer.all([
{color: colors.GRAPH_RING_4, radius: 2.5}
]);
}
},
createPlot: function() {
var startMousePos = null,
startPan = null;
this.plot = new aperture.NodeLink(this.graphCanvas.get(0).id);
//setup radial Layer
this.rLayer = this.plot.addLayer(aperture.RadialLayer);
this.rLayer.map('fill').from('color');
this.rLayer.map('x').from(function () {
var scale = Math.pow(1.5, that.graphZoom);
var viewportWidth = container.width();
var w = viewportWidth * scale;
var viewX = w * 0.5;
var windowX = viewX + that.graphCanvasPadding.left + that.graphCanvasOffset.x;
return windowX / (w + that.graphCanvasPadding.left + that.graphCanvasPadding.right);
});
this.rLayer.map('y').from(function () {
var scale = Math.pow(1.5, that.graphZoom);
var viewportHeight = container.height();
var h = viewportHeight * scale;
var viewY = h * 0.5;
var windowY = viewY + that.graphCanvasPadding.top + that.graphCanvasOffset.y;
return windowY / (h + that.graphCanvasPadding.top + that.graphCanvasPadding.bottom);
});
this.rLayer.map('radius').from(function (data) {
return Math.min(that.graphCanvas.width() - that.graphCanvasPadding.left - that.graphCanvasPadding.right,
that.graphCanvas.height() - that.graphCanvasPadding.top - that.graphCanvasPadding.bottom) * this.radius;
});
this.buildRings();
// add a node layer
this.nodeLayer = this.plot.addLayer(aperture.NodeLayer);
this.nodeLayer.all(this.linkData.nodes, 'id');
// size of node is based on overall connectedness.
var nodeSize = this.nodeLayer.map('radius').from('radius');
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SET UP A FEW HIGHLIGHT THINGS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var focusNodes = new aperture.Set('id'),
selectedLinks = new aperture.Set('id');
this.selectedNodes = new aperture.Set('id');
this.visitedNodes = new aperture.Set('id');
var highlightedNodes = new aperture.Set('id');
var highlightedLinks = new aperture.Set('id');
// the graph will be sorted into three planes based on highlight state.
this.nodeLayer.map('plane').from(function() {
return (this.tag&&this.tag.visible)? 'labeled' : 'normal';
})
.filter(highlightedNodes.constant('highlight'))
.filter(this.visitedNodes.constant('visited'))
.filter(this.selectedNodes.constant('selected'))
.filter(focusNodes.constant('focus'));
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// CREATE THE LINK REPRESENTATION.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.linkLayer = this.plot.addLayer( aperture.LinkLayer );
this.linkLayer.all(this.linkData.links, 'id');
this.linkLayer.map('source').from('source');
this.linkLayer.map('target').from('target');
this.linkLayer.map('opacity').asValue(0.5).filter(highlightedLinks.constant(1)).filter(selectedLinks.constant(1));
var maxLinks = Math.max.apply(Math,this.linkData.links.map(function(link){return link.weight;}));
if(maxLinks <= 0)
maxLinks = 1;
this.linkLayer.map('stroke-width').from(function() {
if(that.ATTRIBUTE_MODE){
return (this.weight/maxLinks)*10+1;
} else {
return 2;
}
});
this.linkLayer.map('link-style').asValue('arc');
// The color key for node connectedness, which is applied to links too.
var highlightColor = new aperture.Color(colors.CIRCLE_HOVER),
selectColor = new aperture.Color(colors.CIRCLE_SELECTED),
visitedColor = new aperture.Color(colors.CIRCLE_VISITED),
linkSelectColor = new aperture.Color(colors.LINK_SELECTED);
// these mappings will be assigned a source later
this.nodeLayer.map('fill').asValue('#000')
.filter(highlightedNodes.filter(function(color) {
return highlightColor;
}))
.filter(this.visitedNodes.filter(function(color) {
return visitedColor;
}))
.filter(this.selectedNodes.filter(function(color) {
return selectColor;
}));
this.linkLayer.map('stroke').from(function() {
if (that.ATTRIBUTE_MODE) {
return colors.LINK_DEFAULT;
} else if (this.type=='phone') {
return colors.LINK_PHONE;
} else if (this.type=='email') {
return colors.LINK_EMAIL;
} else if (this.type=='website') {
return colors.LINK_WEBSITE;
}
return colors.LINK_DEFAULT;
}).filter(highlightedLinks.constant(highlightColor))
.filter(selectedLinks.constant(linkSelectColor));
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// CREATE THE NODE REPRESENTATION.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var dotLayer = this.nodeLayer.addLayer( aperture.RadialLayer );
dotLayer.map('fill').asValue(colors.CIRCLE_TOTAL);
dotLayer.map('stroke').from(function() {
return (this.tag&&this.tag.visible)? colors.GRAPH_DOT_STROKE: 'none';
});
dotLayer.map('stroke-width').asValue(1.5);
// the same offset is used for links and labels, derived from the radius mapping
function nodeOffset() {
return 2+ nodeSize.valueFor(this);
}
// link offsets from the radius of each node.
this.linkLayer.map('source-offset').from(nodeOffset);
this.linkLayer.map('target-offset').from(nodeOffset);
var toTa = {left: 'start', middle: 'middle', right: 'end'};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ADD NODE LABELS.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var labelLayer = this.nodeLayer.addLayer(aperture.LabelLayer);
labelLayer.map('text').from(function(){
return ui_util.trunc(this.name,40);
});
labelLayer.map('visible').from('tag.visible');
labelLayer.map('text-anchor').from(function() {
return toTa[this.tag.anchorX];
});
labelLayer.map('text-anchor-y').from('tag.anchorY');
labelLayer.map('font-family').asValue('Arial');
labelLayer.map('connect').from('tag.connect');
labelLayer.map('connect-x').from('tag.connectX');
labelLayer.map('connect-y').from('tag.connectY');
labelLayer.map('font-size').asValue(14);
labelLayer.map('font-weight').asValue('bold');
labelLayer.map('offset-x').from('tag.offsetX');
labelLayer.map('offset-y').from('tag.offsetY');
labelLayer.map('fill').asValue('#000').filter(this.visitedNodes.filter(function(color) { return visitedColor;
})).filter(this.selectedNodes.filter(function(color) { return selectColor;
})).filter(highlightedNodes.filter(function(color) { return highlightColor; }));
var that = this;
var nodeClick = function(event) {
that.selectNode(event.data.id);
nodeClickCallback(event, that.datasetName, that.clustersetName?that.clustersetName:event.data.name, that.preclusterType);
};
var nodeOver = function(event) {
//make the node draggable and attach the data
var node = document.elementFromPoint(event.source.clientX, event.source.clientY),
buildCasePanel = appwidget.buildCasePanel.canvas,
$dropHere = $('<div/>').css({
position: 'absolute',
top: '0px',
border: '3px dashed gray',
width: 'calc(100% - 6px)',
height: 'calc(100% - 6px)',
'text-align': 'center',
'overflow':'hidden'
}).append($('<span>Drop Here</span>').css({
position: 'relative',
top: (buildCasePanel.height()/2)+'px',
'font-size': '24px',
color: colors.CASE_DROP_HERE,
'font-weight': 'bold'
}));
$(node).css('cursor','pointer');
event.data.ATTRIBUTE_MODE = that.ATTRIBUTE_MODE;
$(node).draggable({
cursor: 'no-drop',
start: function (event) {
buildCasePanel.append($dropHere);
},
stop: function (event) {
$dropHere.remove();
}
}).data('data', event.data);
if (that.noHover_ || !focusNodes.add(event.data.id)) {
return;
}
var changed = [highlightedNodes.add(event.data.id)];
// Add the appropriate target nodes to the selection set.
aperture.util.forEach(event.data.links, function(link) {
var add = highlightedNodes.add(link.other);
changed.push(add);
highlightedLinks.add(link.id);
},this);
// update graphics then pop the nodes of interest to front.
that.nodeLayer.all().where('id', changed).and(that.linkLayer.all()).redraw().toFront(['labeled', 'highlight', 'focus', 'selected']);
var html = '<B>ID: </B>' + ui_util.trunc(event.data.id.trim()) + '<BR/>' +
'<B>Name: </B>' + ui_util.trunc(event.data.name.trim()) + '<BR/>' +
'<B>Label: </B>' + ui_util.trunc(event.data.label.trim());
if (event.data['Cluster Size']) {
html += '<BR/><B>Cluster Size: </B>'+event.data['Cluster Size'] +'<BR/>';
}
if (event.data.latestad) {
html += '<B>Latest Ad: </B>'+event.data.latestad +'<BR/>';
}
if (event.data.attributes) {
//we want the attributes to appear in this order
var attributeNames = [ 'Email Addresses', 'Phone Numbers', 'Websites', 'Link Reasons', 'Common Ads'];
for (var j = 0; j<attributeNames.length; j++) {
var attributeName = attributeNames[j];
if(event.data.attributes[attributeName]) {
var attribute = attributeName,
val = event.data.attributes[attribute],
vals = val.split('\n');
if (vals.length > 0) {
html += '<B>' + attribute.trim() + ':</B>';
for (var i = 0; i < vals.length && i < 5; i++) {
var strs = ui_util.trunc(vals[i]).split('\t');
if (strs.length === 2) {
html += '<div style="overflow:hidden;position:relative;width:100%;height:15px;">' +
'<div style="text-align: right;float:left;padding-right:3px;width:30px;">' +
((strs[0] === "") ? ' </div>' : ('<b>' + strs[0]+ '</b>:</div>')) +
'<div style="text-align: left; width:calc(100% - 35px);float:left;white-space:nowrap;">' +
strs[1] + '</div></div>';
} else if (vals[i].length>0) {
html += '<div style="overflow:hidden;position:relative;width:100%;height:15px;">' + vals[i] + '</div>';
}
}
}
}
}
}
aperture.tooltip.showTooltip({event:event, html:html});
};
var nodeOut = function(event) {
if (focusNodes.clear()) {
// clear everything.
highlightedLinks.clear();
var updated = highlightedNodes.clear();
that.nodeLayer.all().where('id', updated).and(that.linkLayer.all()).redraw().toFront('labeled');
}
aperture.tooltip.hideTooltip();
};
var panMouseDown = function(e) {
that.mouseDown = true;
startMousePos = getMousePos(e);
startPan = {x:that.graphPan.x, y:that.graphPan.y};
that.noHover_ = true;
};
var panMouseUp = function(e) {
that.mouseDown = false;
startMousePos = null;
startPan = null;
that.noHover_ = false;
that.sizeChanged();
};
var panMouseMove = function(e) {
if (that.mouseDown && that.bDisplayingGraph) {
var mousePos = getMousePos(e);
var deltaX = mousePos.x - startMousePos.x;
var deltaY = mousePos.y - startMousePos.y;
that.graphPan.x = startPan.x + deltaX;
that.graphPan.y = startPan.y + deltaY;
that.updatePan();
} else {
that.mouseDown = false;
}
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// WHEN HOVERING OVER A NODE HIGHLIGHT JUST IT AND ITS CONNECTED NODES.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
dotLayer.on('mouseover', nodeOver);
dotLayer.on('mouseout', nodeOut);
dotLayer.on('dblclick', nodeClick);
dotLayer.on('click', nodeClick);
labelLayer.on('mouseover', nodeOver);
labelLayer.on('mouseout', nodeOut);
//setup Panning
this.rLayer.on('mousedown', panMouseDown);
this.rLayer.on('mouseup', panMouseUp);
this.rLayer.on('drag', panMouseMove);
if(that.ATTRIBUTE_MODE) {
this.linkLayer.on('mousedown', function(e) {that.selectLinkedAds(e)});
this.linkLayer.on('mousemove', function(e){
var html;
html = 'Common Ads: ' + e.data.weight;
$(document.elementFromPoint(e.source.clientX, e.source.clientY)).css('cursor','pointer');
aperture.tooltip.showTooltip({event:e, html:html});
});
this.linkLayer.on('mouseout', function(e){
aperture.tooltip.hideTooltip();
$(document.elementFromPoint(e.source.clientX, e.source.clientY)).css('cursor','default');
});
} else {
this.linkLayer.on('mousedown', panMouseDown);
this.linkLayer.on('mouseup', panMouseUp);
this.linkLayer.on('drag', panMouseMove);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SET UP ZOOM AND PAN
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// zoom with scroll wheel.
if ( ENABLE_ZOOM_PAN ) {
this.setupZoom();
}
// track button state so hovers are deactivated when dragging.
$(this.contentsId_).mousedown(function(e) {
that.noHover_ = true;
dotLayer.trigger('mouseout');
});
$('body').mouseup(function(e) {
that.noHover_ = false;
});
this.nodeLayer.all().toFront('labeled');
this.sizeChanged();
},
setupZoom: function() {
var that = this;
container.unbind('DOMMouseScroll mousewheel').bind('DOMMouseScroll mousewheel', function(e) {
if (!that.bDisplayingGraph) {
return;
}
var delta = e.originalEvent.wheelDelta || -e.originalEvent.detail;
var zoomIn = delta > 0;
var oldscale = Math.pow(1.5, that.graphZoom);
if (zoomIn) {
that.graphZoom++;
} else if (that.graphZoom>0){
that.graphZoom--;
}
var newscale = Math.pow(1.5, that.graphZoom);
var scaleFactor = newscale/oldscale;
var canvasOffset = that.graphCanvas.offset();
var mousePos = getMousePos(e);
var mouseGraphX = mousePos.x - canvasOffset.left - that.graphCanvasPadding.left - that.graphCanvasOffset.x;
var mouseGraphY = mousePos.y - canvasOffset.top - that.graphCanvasPadding.top - that.graphCanvasOffset.y;
var mouseGraphXNew = mouseGraphX*scaleFactor;
var mouseGraphYNew = mouseGraphY*scaleFactor;
that.graphPan.x = that.graphPan.x + mouseGraphX - mouseGraphXNew;
that.graphPan.y = that.graphPan.y + mouseGraphY - mouseGraphYNew;
that.layout('organic');
that.updatePan();
that.sizeChanged();
e.preventDefault();
});
},
updateZoom: function() {
var viewportWidth = container.width();
var viewportHeight = container.height();
var scale = Math.pow(1.5, this.graphZoom);
var w = viewportWidth * scale;
var h = viewportHeight * scale;
this.graphCanvas.width(w + this.graphCanvasPadding.left + this.graphCanvasPadding.right);
this.graphCanvas.height(h + this.graphCanvasPadding.top + this.graphCanvasPadding.bottom);
},
updatePan: function() {
var newTop = this.graphPan.y - this.graphCanvasOffset.y - this.graphCanvasPadding.top;
var newLeft = this.graphPan.x - this.graphCanvasOffset.x - this.graphCanvasPadding.left;
this.graphCanvas.css({
'top':newTop + 'px',
'left':newLeft + 'px'
});
},
sizeChanged: function() {
if (this.width) {
var viewportWidth = container.width();
var viewportHeight = container.height();
var scale = Math.pow(1.5, this.graphZoom);
var w = viewportWidth * scale;
var h = viewportHeight * scale;
this.graphCanvasPadding.left = viewportWidth;
this.graphCanvasPadding.right = viewportWidth;
this.graphCanvasPadding.top = viewportHeight;
this.graphCanvasPadding.bottom = viewportHeight;
this.graphCanvasOffset.x = this.graphPan.x;
this.graphCanvasOffset.y = this.graphPan.y;
this.updatePan();
this.updateZoom();
this.plot.map('node-x').from('x').using(new aperture.Scalar('w', [-this.graphCanvasPadding.left-this.graphCanvasOffset.x,w+this.graphCanvasPadding.right-this.graphCanvasOffset.x]).mapKey([0,w+this.graphCanvasPadding.left+this.graphCanvasPadding.right]));
this.plot.map('node-y').from('y').using(new aperture.Scalar('h', [-this.graphCanvasPadding.top-this.graphCanvasOffset.y,h+this.graphCanvasPadding.bottom-this.graphCanvasOffset.y]).mapKey([0,h+this.graphCanvasPadding.top+this.graphCanvasPadding.bottom]));
this.plot.map('width').asValue(w);
this.plot.map('height').asValue(h);
this.plot.all().redraw();
this.linkLayer.toFront();
this.nodeLayer.toFront();
}
},
layout: function(type) {
var graphData = this.linkData;
if (!graphData) return;
var viewportWidth = container.width();
var viewportHeight = container.height();
var scale = Math.pow(1.5, this.graphZoom);
var w = viewportWidth * scale;
var h = viewportHeight * scale;
this.buildRings();
if(this.isRadialLayout) {
radial_layout.layout(this, w, h);
} else {
column_layout.layout(this, w, h, GRAPH_CONTROLS_CONTAINER_WIDTH);
}
},
getGraph: function(baseURL, datasetName, linkCriteria, filters, clustersetName, existingClusterIds, onlyLinked, callback, errcallback) {
this.attributeBased = false;
var graphRequest = {
datasetName : datasetName,
clustersetName : clustersetName,
onlyLinkedNodes : onlyLinked
};
if (linkCriteria && linkCriteria.length > 0) {
graphRequest.linkCriteria = linkCriteria
}
if (filters && filters.length > 0) {
graphRequest.filters = filters;
}
if (existingClusterIds && existingClusterIds.length > 0) {
graphRequest.existingClusters = existingClusterIds;
}
rest.post(baseURL + "rest/graph/link", graphRequest, "Compute graph and connectivity", callback, false, errcallback);
},
simpleGraph: function(baseURL, searchString, clusterType, callback, errcallback) {
this.attributeBased = false;
var graphRequest = {
searchString : searchString,
clusterType : clusterType,
ringCount: 3
};
rest.post(baseURL + "rest/graph/simple", graphRequest, "Compute graph and connectivity", callback, false, errcallback);
},
fetchClusterId: function(baseURL, clusterid, clusterType, callback, errcallback) {
this.attributeBased = false;
var graphRequest = {
searchString : clusterid,
clusterType : clusterType,
ringCount: 3
};
rest.post(baseURL + "rest/graph/cluster", graphRequest, "Compute graph and connectivity", callback, false, errcallback);
},
fetchAttribute: function(baseURL, attribute, value, callback, errcallback) {
this.attributeBased = true;
value = encodeURIComponent(value);
rest.post(baseURL + "rest/graph/attribute/" + attribute + "/" + value, null, "Compute graph and connectivity", callback, false, errcallback);
},
fetchAttributeId: function(baseURL, attributeid, callback, errcallback) {
this.attributeBased = true;
rest.post(baseURL + "rest/graph/attributeid/" + attributeid, null, "Compute graph and connectivity", callback, false, errcallback);
},
fetchImageId: function(baseURL, imageid, callback, errcallback) {
this.attributeBased = false;
var graphRequest = {
searchString : imageid,
clusterType : 'org',
ringCount: 3
};
rest.post(baseURL + "rest/graph/image", graphRequest, "Compute image graph and connectivity", callback, false, errcallback);
},
markSelectedCluster: function(clusterid) {
var updated = this.selectedNodes.clear();
updated.push(this.selectedNodes.add(clusterid));
this.nodeLayer.all().where('id', updated).and(this.linkLayer.all()).redraw().toFront('labeled');
},
markVisitedNodes: function(visitedNodes) {
for (var i=0; i<visitedNodes.length; i++) {
var visitedNode = visitedNodes[i];
this.visitedNodes.add(visitedNode);
}
this.nodeLayer.all().where('id', visitedNodes).and(this.linkLayer.all()).redraw().toFront('labeled');
},
displayGraph: function(graphIn, datasetName, clustersetName, preclusterType) {
var i, j, k;
var bCleanupData = true;
if (preclusterType) {
this.preclusterType = preclusterType;
this.datasetName = null;
this.clustersetName = null;
} else {
this.preclusterType = null;
this.datasetName = datasetName;
this.clustersetName = clustersetName;
}
this.graphCanvas.empty();
this.bDisplayingGraph = true;
if (!graphIn) graphIn = {nodes:[],links:[]};
if (!graphIn.nodes) graphIn.nodes = [];
if (!graphIn.links) graphIn.links = [];
var graph = graphIn;
var tooManyNodesMsg = 'Your search returned too many nodes.';
if (graph.nodes.length==0) {
alert('Your search returned no results.');
} else if (graph.nodes.length > MAX_GRAPH_NODES) {
if (this.previousGraphData) {
alert(tooManyNodesMsg + ' Please refine your search by adding link attributes or click the "Only Linked Nodes" checkbox. Reverting to previous graph.');
graph = this.previousGraphData;
bCleanupData = false;
} else {
alert(tooManyNodesMsg + ' Please refine your search by adding search criteria.');
graph.nodes = [];
graph.links = [];
}
}
if (bCleanupData) {
// Do some data formatting and cleanup on the nodes
for (i = 0; i < graph.nodes.length; i++) {
var attributes = {};
if (graph.nodes[i].attributes && graph.nodes[i].attributes.map && graph.nodes[i].attributes.map.entry) {
for (j = 0; j < graph.nodes[i].attributes.map.entry.length; j++) {
var attr = graph.nodes[i].attributes.map.entry[j];
attributes[attr.key] = attr.value;
}
}
graph.nodes[i].attributes = attributes;
graph.nodes[i].ring = parseInt(graph.nodes[i].ring);
graph.nodes[i].size = parseFloat(graph.nodes[i].size);
graph.nodes[i]['Cluster Size'] = parseInt(graph.nodes[i].clusterSize);
delete graph.nodes[i]['clusterSize'];
// Clean up node links
if (!graph.nodes[i].links) {
graph.nodes[i].links = [];
} else {
var links = [];
if (graph.nodes[i].links instanceof Array) {
for (j = 0; j < graph.nodes[i].links.length; j++) {
link = {};
if (graph.nodes[i].links[j].map) {
for (k = 0; k < graph.nodes[i].links[j].map.entry.length; k++) {
linkattr = graph.nodes[i].links[j].map.entry[k];
link[linkattr.key] = linkattr.value;
}
links.push(link);
} else {
links.push(graph.nodes[i].links[j]);
}
}
} else {
link = {};
for (k = 0; k < graph.nodes[i].links.map.entry.length; k++) {
var linkattr = graph.nodes[i].links.map.entry[k];
link[linkattr.key] = linkattr.value;
}
links.push(link);
}
graph.nodes[i].links = links;
}
}
// Clean up the links
for (i = 0; i < graph.links.length; i++) {
graph.links[i].weight = parseFloat(graph.links[i].weight);
}
}
this.linkData = {
nodes: [],
links: [],
nodeMap: {},
connectednessRange: new aperture.Scalar('Connectedness')
};
this.linkData.connectednessRange.expand(0);
this.linkData.connectednessRange.expand(graph['connectedness']);
this.linkData.nodes = graph.nodes;
if (this.linkData.nodes) {
for (i=0; i<this.linkData.nodes.length; i++) {
var node = this.linkData.nodes[i];
this.linkData.nodeMap[node.id] = node;
}
}
this.linkData.links = graph.links;
if (graph.links) {
for (i=0; i<graph.links.length; i++) {
var link = graph.links[i];
link.source = this.linkData.nodeMap[link.sourceId];
link.target = this.linkData.nodeMap[link.targetId];
}
}
this.graphZoom = 0;
this.updateZoom();
this.graphCanvas.css({
top : '0px',
left: '0px'
});
this.layout('organic');
this.previousGraphData = graph;
},
empty: function() {
this.graphCanvas.empty();
this.plot = null;
},
resize: function(w,h) {
// Keep track of total scale since last graph relayout
if (!this.scaleFactorX) {
this.scaleFactorX = 1;
this.scaleFactorY = 1;
}
this.scaleFactorX = this.scaleFactorX*w/this.width;
this.scaleFactorY = this.scaleFactorY*h/this.height;
this.width = w;
this.height = h;
if (this.resizing) {
clearTimeout(this.resizing);
}
var that = this;
this.resizing = setTimeout(function() {
that.adjustCanvasOnResize(that.scaleFactorX, that.scaleFactorY);
that.updateZoom();
that.layout('organic');
that.resizing = null;
that.scaleFactorX = 1;
that.scaleFactorY = 1;
}, 200);
},
displayLoader: function() {
this.plot = null;
this.graphCanvas.css({
top:'0px',
left:'0px'
});
this.graphCanvas.width(container.width());
this.graphCanvas.height(container.height());
displayAjaxLoader(this.graphCanvas);
},
adjustCanvasOnResize: function(scaleX, scaleY) {
var oldpos = this.graphCanvas.position();
this.graphCanvas.css({
left: (oldpos.left*scaleX) + 'px',
top : (oldpos.top*scaleY) + 'px'
});
}
};
graphWidgetObj.init();
return graphWidgetObj;
};
return {
createWidget:createWidget
}
});
|
ATrain951/01.python-com_Qproject
|
hackerrank/Data Structures/Find Merge Point of Two Lists/test.py
|
<filename>hackerrank/Data Structures/Find Merge Point of Two Lists/test.py<gh_stars>1-10
import unittest
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
index = 1
list1_count = 3
list1 = solution.SinglyLinkedList()
for item in [1, 2, 3]:
list1.insert_node(item)
list2_count = 1
list2 = solution.SinglyLinkedList()
for item in [1]:
list2.insert_node(item)
ptr1 = list1.head
ptr2 = list2.head
for i in range(list1_count):
if i < index:
ptr1 = ptr1.next
for i in range(list2_count):
if i != list2_count - 1:
ptr2 = ptr2.next
ptr2.next = ptr1
self.assertEqual(solution.findMergeNode(list1.head, list2.head), 2)
def test_case_1(self):
index = 2
list1_count = 3
list1 = solution.SinglyLinkedList()
for item in [1, 2, 3]:
list1.insert_node(item)
list2_count = 1
list2 = solution.SinglyLinkedList()
for item in [1]:
list2.insert_node(item)
ptr1 = list1.head
ptr2 = list2.head
for i in range(list1_count):
if i < index:
ptr1 = ptr1.next
for i in range(list2_count):
if i != list2_count - 1:
ptr2 = ptr2.next
ptr2.next = ptr1
self.assertEqual(solution.findMergeNode(list1.head, list2.head), 3)
if __name__ == '__main__':
unittest.main()
|
zhaodm/skia_sdl
|
gm/blurs.cpp
|
<reponame>zhaodm/skia_sdl<filename>gm/blurs.cpp<gh_stars>0
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBlurMask.h"
#include "SkBlurMaskFilter.h"
class BlursGM : public skiagm::GM {
public:
BlursGM() {
this->setBGColor(0xFFDDDDDD);
}
protected:
virtual uint32_t onGetFlags() const SK_OVERRIDE {
return kSkipTiled_Flag;
}
virtual SkString onShortName() {
return SkString("blurs");
}
virtual SkISize onISize() {
return SkISize::Make(700, 500);
}
virtual void onDraw(SkCanvas* canvas) {
SkBlurStyle NONE = SkBlurStyle(-999);
static const struct {
SkBlurStyle fStyle;
int fCx, fCy;
} gRecs[] = {
{ NONE, 0, 0 },
{ kInner_SkBlurStyle, -1, 0 },
{ kNormal_SkBlurStyle, 0, 1 },
{ kSolid_SkBlurStyle, 0, -1 },
{ kOuter_SkBlurStyle, 1, 0 },
};
SkPaint paint;
paint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&paint);
paint.setTextSize(SkIntToScalar(25));
canvas->translate(SkIntToScalar(-40), SkIntToScalar(0));
SkBlurMaskFilter::BlurFlags flags = SkBlurMaskFilter::kNone_BlurFlag;
for (int j = 0; j < 2; j++) {
canvas->save();
paint.setColor(SK_ColorBLUE);
for (size_t i = 0; i < SK_ARRAY_COUNT(gRecs); i++) {
if (gRecs[i].fStyle != NONE) {
SkMaskFilter* mf = SkBlurMaskFilter::Create(gRecs[i].fStyle,
SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(20)),
flags);
paint.setMaskFilter(mf)->unref();
} else {
paint.setMaskFilter(NULL);
}
canvas->drawCircle(SkIntToScalar(200 + gRecs[i].fCx*100),
SkIntToScalar(200 + gRecs[i].fCy*100),
SkIntToScalar(50),
paint);
}
// draw text
{
SkMaskFilter* mf = SkBlurMaskFilter::Create(kNormal_SkBlurStyle,
SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(4)),
flags);
paint.setMaskFilter(mf)->unref();
SkScalar x = SkIntToScalar(70);
SkScalar y = SkIntToScalar(400);
paint.setColor(SK_ColorBLACK);
canvas->drawText("Hamburgefons Style", 18, x, y, paint);
canvas->drawText("Hamburgefons Style", 18,
x, y + SkIntToScalar(50), paint);
paint.setMaskFilter(NULL);
paint.setColor(SK_ColorWHITE);
x -= SkIntToScalar(2);
y -= SkIntToScalar(2);
canvas->drawText("Hamburgefons Style", 18, x, y, paint);
}
canvas->restore();
flags = SkBlurMaskFilter::kHighQuality_BlurFlag;
canvas->translate(SkIntToScalar(350), SkIntToScalar(0));
}
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new BlursGM; )
//////////////////////////////////////////////////////////////////////////////////////////////
// exercise a special-case of blurs, which is two nested rects. These are drawn specially,
// and possibly cached.
//
// in particular, we want to notice that the 2nd rect draws slightly differently, since it
// is translated a fractional amount.
//
class Blur2RectsGM : public skiagm::GM {
public:
SkString onShortName() SK_OVERRIDE {
return SkString("blur2rects");
}
SkISize onISize() SK_OVERRIDE {
return SkISize::Make(700, 500);
}
void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
paint.setMaskFilter(SkBlurMaskFilter::Create(kNormal_SkBlurStyle,
2.3f))->unref();
SkRect outer = SkRect::MakeXYWH(10.125f, 10.125f, 100.125f, 100);
SkRect inner = SkRect::MakeXYWH(20.25f, 20.125f, 80, 80);
SkPath path;
path.addRect(outer, SkPath::kCW_Direction);
path.addRect(inner, SkPath::kCCW_Direction);
canvas->drawPath(path, paint);
// important to translate by a factional amount to exercise a different "phase"
// of the same path w.r.t. the pixel grid
SkScalar dx = SkScalarRoundToScalar(path.getBounds().width()) + 14 + 0.25f;
canvas->translate(dx, 0);
canvas->drawPath(path, paint);
}
};
DEF_GM( return new Blur2RectsGM; )
class Blur2RectsNonNinePatchGM : public skiagm::GM {
public:
SkString onShortName() SK_OVERRIDE {
return SkString("blur2rectsnonninepatch");
}
SkISize onISize() SK_OVERRIDE {
return SkISize::Make(700, 500);
}
void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
paint.setMaskFilter(SkBlurMaskFilter::Create(kNormal_SkBlurStyle,
4.3f))->unref();
SkRect outer = SkRect::MakeXYWH(10, 110, 100, 100);
SkRect inner = SkRect::MakeXYWH(50, 150, 10, 10);
SkPath path;
path.addRect(outer, SkPath::kCW_Direction);
path.addRect(inner, SkPath::kCW_Direction);
canvas->drawPath(path, paint);
SkScalar dx = SkScalarRoundToScalar(path.getBounds().width()) + 40 + 0.25f;
canvas->translate(dx, 0);
canvas->drawPath(path, paint);
// Translate to outside of clip bounds.
canvas->translate(-dx, 0);
canvas->translate(-30, -150);
canvas->drawPath(path, paint);
}
};
DEF_GM( return new Blur2RectsNonNinePatchGM; )
|
CodingFu/bitly
|
lib/bitly/api.rb
|
# frozen_string_literal: true
require "uri"
module Bitly
module API
BASE_URL = URI("https://api-ssl.bitly.com/v4")
autoload :Base, File.join(File.dirname(__FILE__), "api/base.rb")
autoload :Client, File.join(File.dirname(__FILE__), "api/client.rb")
autoload :ClickMetric, File.join(File.dirname(__FILE__), "api/click_metric.rb")
autoload :Bitlink, File.join(File.dirname(__FILE__), "api/bitlink.rb")
autoload :Organization, File.join(File.dirname(__FILE__), "api/organization.rb")
autoload :Group, File.join(File.dirname(__FILE__), "api/group.rb")
autoload :User, File.join(File.dirname(__FILE__), "api/user.rb")
autoload :BSD, File.join(File.dirname(__FILE__), "api/bsd.rb")
autoload :OAuthApp, File.join(File.dirname(__FILE__), "api/oauth_app.rb")
autoload :ShortenCounts, File.join(File.dirname(__FILE__), "api/shorten_counts.rb")
end
end
|
isabella232/mobile-messaging-sdk-android
|
infobip-mobile-messaging-android-sdk/src/main/java/org/infobip/mobile/messaging/util/DeviceInformation.java
|
package org.infobip.mobile.messaging.util;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import org.infobip.mobile.messaging.logging.MobileMessagingLogger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author sslavin
* @since 27/04/16.
*/
public class DeviceInformation {
private DeviceInformation() {
}
@SuppressLint("HardwareIds")
public static String getDeviceID(Context context) {
return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
public static String getDeviceModel() {
return Build.MODEL;
}
public static String getDeviceManufacturer() {
return Build.MANUFACTURER;
}
public static boolean isDeviceSecure(Context context) {
// Starting with android 6.0 calling isLockScreenDisabled fails altogether because the signature has changed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
KeyguardManager keyguardMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
return keyguardMgr != null && keyguardMgr.isDeviceSecure();
}
try {
String LOCKSCREEN_UTILS_CLASSNAME = "com.android.internal.widget.LockPatternUtils";
@SuppressLint("PrivateApi") Class<?> lockUtilsClass = Class.forName(LOCKSCREEN_UTILS_CLASSNAME);
Object lockUtils = lockUtilsClass.getConstructor(Context.class).newInstance(context);
Method method = lockUtilsClass.getMethod("getActivePasswordQuality");
// Starting with android 5.x this fails with InvocationTargetException (caused by SecurityException - MANAGE_USERS permission is
// required because internally some additional logic was added to return false if one can switch between several users)
// -> therefore if no exception is thrown, we know the screen lock setting is set to Pattern, PIN/PW or something else other than 'None' or 'Swipe'
Integer lockProtectionLevel = (Integer) method.invoke(lockUtils);
return lockProtectionLevel >= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
} catch (InvocationTargetException ignored) {
} catch (Exception e) {
MobileMessagingLogger.e("Error detecting whether screen lock is disabled: " + e);
}
return false;
}
public static String getDeviceTimeZoneOffset() {
return DateTimeUtil.getGMTTimeZoneOffset();
}
}
|
room77/77up
|
public/util/counter/metrics/count/count.cc
|
<filename>public/util/counter/metrics/count/count.cc
// Copyright 2013 Room77 Inc. All Rights Reserved.
// Author: <EMAIL> (<NAME>)
#include "util/counter/metrics/count/count.h"
namespace counter {
namespace metrics {
// register
auto reg_count = MetricInterface::bind("count", [] { return new Count(); });
} // namespace metrics
} // namespace counter
|
MightyCupcakes/ArmourReborn
|
src/main/java/teamOD/armourReborn/common/modifiers/TraitGuardianAngel.java
|
<filename>src/main/java/teamOD/armourReborn/common/modifiers/TraitGuardianAngel.java
package teamOD.armourReborn.common.modifiers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import teamOD.armourReborn.common.potion.ModPotions;
public class TraitGuardianAngel extends AbstractTrait {
public static final String GUARDIAN_COOLDOWN = "guardian" + IModifier.COOLDOWN ;
public static final Potion INSTANT = MobEffects.INSTANT_HEALTH;
public static final Potion DEFENSE = MobEffects.RESISTANCE ;
public static final Potion REGEN = MobEffects.REGENERATION;
public static final Potion GUARDIAN = ModPotions.guardianPotion ;
public TraitGuardianAngel () {
super ("guardian Angel", TextFormatting.YELLOW) ;
}
@Override
public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) {
if (!itemStack.getTagCompound().hasKey(GUARDIAN_COOLDOWN)) {
itemStack.getTagCompound().setLong(GUARDIAN_COOLDOWN, world.getTotalWorldTime()) ;
}
float health = player.getHealth() / player.getMaxHealth() ;
long time = itemStack.getTagCompound().getLong(GUARDIAN_COOLDOWN) ;
if (player.getActivePotionEffect(GUARDIAN) != null) return ;
if (health <= 0.25 && world.getTotalWorldTime() >= time) {
PotionEffect healPlayer = new PotionEffect (INSTANT, 1, 0, false, false) ;
PotionEffect fortitude = new PotionEffect (DEFENSE, 200, 0, true, true) ;
PotionEffect regeneration = new PotionEffect (REGEN, 200, 0, true, true) ;
PotionEffect guardian = new PotionEffect (GUARDIAN, 200, 0, false, false) ;
PotionEffect[] effects = new PotionEffect[] { healPlayer, fortitude, regeneration, guardian } ;
for (PotionEffect effect : effects) {
player.addPotionEffect(effect) ;
}
itemStack.getTagCompound().setLong(GUARDIAN_COOLDOWN, world.getTotalWorldTime() + (45 * 20));
}
}
}
|
ankurshukla1993/IOT-test
|
coeey/android/arch/persistence/room/Database.java
|
package android.arch.persistence.room;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
public @interface Database {
Class[] entities();
boolean exportSchema() default true;
int version();
}
|
Scorbutics/skalang
|
bytecode/generator/src/Generator/GeneratorOperatorFilter.h
|
<gh_stars>1-10
#pragma once
#include "GeneratorOperator.h"
#include "Operation/OperationTypeFilter.h"
namespace ska {
namespace bytecode {
SKALANG_GENERATOR_OPERATOR_DEFINE(ska::Operator::FILTER);
}
}
|
xlasers/spring-modules
|
spring-boot/spring-boot-basic/props/src/main/java/com/xlaser4j/demo/Logo.java
|
package com.xlaser4j.demo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @package: com.xlaser4j.demo
* @author: Elijah.D
* @time: 2019/12/5 12:29
* @description:
* @modified: Elijah.D
*/
@Data
@Component
public class Logo {
@Value("${company.logo}")
private String logo;
}
|
jiageh08/tea-springboot
|
bdnav-provider/school-provider/src/main/java/com/bdxh/school/service/SinglePermissionService.java
|
package com.bdxh.school.service;
import com.bdxh.common.support.IService;
import com.bdxh.school.dto.SinglePermissionQueryDto;
import com.bdxh.school.entity.SinglePermission;
import com.bdxh.school.vo.SinglePermissionShowVo;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Description: 业务层接口
* @Author Kang
* @Date 2019-03-27 12:21:12
*/
@Service
public interface SinglePermissionService extends IService<SinglePermission> {
/**
* 查询所有数量
*/
Integer getSinglePermissionAllCount();
/**
* 批量删除方法
*/
Boolean batchDelSinglePermissionInIds(List<Long> id);
/**
* 门禁单人信息根据条件分页查询
*
* @param singlePermissionQueryDto
* @return
*/
PageInfo<SinglePermissionShowVo> findSinglePermissionInConditionPage(SinglePermissionQueryDto singlePermissionQueryDto);
}
|
aanacleto/erp-
|
core/objs/candidatura.py
|
# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = '<NAME>'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "<NAME>"
__status__ = "Development"
__model_name__ = 'candidatura.Candidatura'
import auth, base_models
from orm import *
from form import *
class Candidatura(Model, View):
def __init__(self, **kargs):
Model.__init__(self, **kargs)
self.__name__ = 'candidatura'
self.__title__ ='Candidatura' #Gestão de atendimento Presencial serviço
self.__model_name__ = __model_name__
self.__get_options__ = ['nome']
self.__list_edit_mode__ = 'edit'
#self.__order_by__ = 'candidatura.nome'
self.__auth__ = {
'read':['All'],
'write':['Atendedor'],
'create':['Gestor de Loja'],
'delete':['Gestor de Atendimento'],
'full_access':['Gestor de Atendimento']
}
self.tipo = date_field(view_order=1 , name='Datacandidatura', size=80)
self.proposta = list_field(view_order = 2, name = 'Proposta Candidatura', model_name = 'proposta.Proposta', condition = "rfpp='{id}'", list_edit_mode = 'popup', onlist = False)
self.rfcd = parent_field(view_order=3, name ='Ref Candidatura', model_name='concurso.Concurso', nolabel=True, column='candidatura')
|
mwerlberger/imp
|
deprecated/tests/core/image_cv_test.cpp
|
<gh_stars>1-10
#include <assert.h>
#include <cstdint>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <imp/core/roi.hpp>
#include <imp/bridge/opencv/image_cv.hpp>
#include "default_msg.h"
int main(int /*argc*/, char** /*argv*/)
{
try
{
cv::Mat lena = cv::imread("/home/mwerlberger/data/std/Lena.pgm", CV_LOAD_IMAGE_GRAYSCALE);
imp::Size2u sz(510, 512);
imp::ImageCv8uC1 im8uC1(sz);
std::cout << "im8uC1: " << im8uC1 << std::endl;
imp::ImageCv8uC1 lena_8uC1(lena);
imp::ImageCv8uC1 lena_copy_8uC1(lena_8uC1);
//lena_8uC1.copyTo(lena_copy_8uC1);
std::cout << "lena_8uC1: " << lena_8uC1 << std::endl;
std::cout << "lena_copy_8uC1: " << lena_copy_8uC1 << std::endl;
cv::imshow("input", lena_8uC1.cvMat());
cv::imshow("copy", lena_copy_8uC1.cvMat());
cv::waitKey();
}
catch (std::exception& e)
{
std::cout << "[exception] " << e.what() << std::endl;
assert(false);
}
std::cout << imp::ok_msg << std::endl;
return EXIT_SUCCESS;
}
|
Kirishikesan/haiku
|
src/apps/haikudepot/ui/UserUsageConditionsWindow.h
|
/*
* Copyright 2019-2020, <NAME> <<EMAIL>>.
* All rights reserved. Distributed under the terms of the MIT License.
*/
#ifndef USER_USAGE_CONDITIONS_WINDOW_H
#define USER_USAGE_CONDITIONS_WINDOW_H
#include <Locker.h>
#include <Messenger.h>
#include <Window.h>
#include "HaikuDepotConstants.h"
#include "PackageInfo.h"
#include "UserDetail.h"
#include "UserUsageConditions.h"
class BarberPole;
class BTextView;
class BStringView;
class MarkupTextView;
class Model;
class UserUsageConditionsWindow : public BWindow {
public:
UserUsageConditionsWindow(Model& model,
UserUsageConditions& userUsageConditions);
UserUsageConditionsWindow(Model& model,
UserUsageConditionsSelectionMode mode);
virtual ~UserUsageConditionsWindow();
virtual void MessageReceived(BMessage* message);
virtual bool QuitRequested();
private:
void _InitUiControls();
static const BString _VersionText(const BString& code);
static const BString _MinimumAgeText(uint8 minimumAge);
static const BString _IntroductionTextForMode(
UserUsageConditionsSelectionMode mode,
const UserDetail& userDetail);
static float _ExpectedIntroductionTextHeight(
BTextView* introductionTextView);
void _DisplayData(const UserDetail& userDetail,
const UserUsageConditions&
userUsageConditions);
void _FetchData();
void _SetWorkerThread(thread_id thread);
static int32 _FetchDataThreadEntry(void* data);
void _FetchDataPerform();
status_t _FetchUserUsageConditionsCodePerform(
UserDetail& userDetail, BString& code);
status_t _FetchUserUsageConditionsCodeForUserPerform(
UserDetail& userDetail, BString& code);
void _NotifyFetchProblem();
private:
UserUsageConditionsSelectionMode
fMode;
MarkupTextView* fCopyView;
Model& fModel;
BStringView* fAgeNoteStringView;
BStringView* fVersionStringView;
BTextView* fIntroductionTextView;
BarberPole* fWorkerIndicator;
thread_id fWorkerThread;
};
#endif // USER_USAGE_CONDITIONS_WINDOW_H
|
srikanthprathi/Segs
|
Common/Messages/Game/GameEvents.h
|
/*
* SEGS - Super Entity Game Server
* http://www.segs.dev/
* Copyright (c) 2006 - 2019 SEGS Team (see AUTHORS.md)
* This software is licensed under the terms of the 3-clause BSD License. See LICENSE.md for details.
*/
#pragma once
#include "Components/LinkLevelEvent.h"
#include "Components/BitStream.h"
//#include "GameLink.h"
//#include "CRUDP_Protocol/CRUD_Link.h"
#include "Common/CRUDP_Protocol/CRUD_Events.h"
#include "Common/Servers/InternalEvents.h"
// GameEvents make use of some of the event Data defined in GameDBSyncEvents
#include "Common/Messages/GameDatabase/GameDBSyncEvents.h"
#include <QtCore/QString>
#include <array>
namespace SEGSEvents
{
using GameLinkEvent = CRUDLink_Event;
struct GameAccountResponseData;
enum GameEventTypes
{
BEGINE_EVENTS(GameEventTypes,CRUD_EventTypes)
evUpdateServer,
evMapServerAddrRequest,
evDeleteCharacter,
evUpdateCharacter,
evGameEntryError,
evCharacterSlots,
evCharacterResponse,
evMapServerAddrResponse,
evDeleteAcknowledged,
evServerReconfigured = evDeleteAcknowledged+100,
END_EVENTS(GameEventTypes,102)
};
// [[ev_def:type]]
class MapServerAddrRequest : public GameLinkEvent
{
public:
MapServerAddrRequest() : GameLinkEvent(GameEventTypes::evMapServerAddrRequest)
{
}
void serializeto(BitStream &bs) const override
{
bs.StorePackedBits(1,3); //opcode
}
void serializefrom(BitStream &src) override
{
m_character_index = src.GetPackedBits(1);
m_map_server_ip = src.GetPackedBits(1);
m_mapnumber = src.GetPackedBits(1);
src.GetString(m_char_name);
}
// [[ev_def:field]]
uint32_t m_map_server_ip;
// [[ev_def:field]]
uint16_t m_character_index;
// [[ev_def:field]]
uint32_t m_mapnumber;
// [[ev_def:field]]
QString m_char_name;
EVENT_IMPL(MapServerAddrRequest)
};
// [[ev_def:type]]
class MapServerAddrResponse : public GameLinkEvent
{
public:
MapServerAddrResponse() : GameLinkEvent(GameEventTypes::evMapServerAddrResponse)
{
unused1=unused2=unused3=unused4=0;
}
void serializefrom(BitStream &src) override
{
unused1 = src.GetPackedBits(1);
unused2 = src.GetPackedBits(1);
uint32_t ipaddr = src.GetPackedBits(1);
unused3 = src.GetPackedBits(1);
uint16_t port = src.GetPackedBits(1);
unused4 = src.GetPackedBits(1);
m_map_cookie = src.GetPackedBits(1);
m_address.set(port,ntohl(ipaddr));
}
void serializeto(BitStream &tgt) const override
{
uint32_t ipaddr = htonl(m_address.get_ip_address());
uint16_t port = m_address.get_port_number();
tgt.StorePackedBits(1,4); //opcode
tgt.StorePackedBits(1,unused1);
tgt.StorePackedBits(1,unused2);
tgt.StorePackedBits(1,ipaddr);
tgt.StorePackedBits(1,unused3);
tgt.StorePackedBits(1,port);
tgt.StorePackedBits(1,unused4);
tgt.StorePackedBits(1,m_map_cookie); // this should be 0 if there was an error ( like "InvalidName" )
}
// [[ev_def:field]]
uint8_t unused1;
// [[ev_def:field]]
uint8_t unused2;
// [[ev_def:field]]
uint8_t unused3;
// [[ev_def:field]]
uint8_t unused4;
// [[ev_def:field]]
ACE_INET_Addr m_address;
/// @note m_map_cookie has two special values:
/// 0 - Name already taken.
/// 1 - Problem detected in the game database system
// [[ev_def:field]]
uint32_t m_map_cookie;
EVENT_IMPL(MapServerAddrResponse)
};
// [[ev_def:type]]
class DeleteCharacter : public GameLinkEvent
{
public:
DeleteCharacter():GameLinkEvent(GameEventTypes::evDeleteCharacter)
{}
DeleteCharacter(EventProcessor *evsrc,uint8_t idx,const QString &name) : GameLinkEvent(GameEventTypes::evDeleteCharacter,evsrc),m_index(idx),m_char_name(name)
{}
void serializeto(BitStream &bs) const override
{
bs.StorePackedBits(1,4); // opcode
bs.StorePackedBits(1,m_index);
bs.StoreString(m_char_name);
}
void serializefrom(BitStream &bs) override
{
m_index=bs.GetPackedBits(1);
bs.GetString(m_char_name);
}
// [[ev_def:field]]
uint8_t m_index;
// [[ev_def:field]]
QString m_char_name;
EVENT_IMPL(DeleteCharacter)
};
// [[ev_def:type]]
class UpdateCharacter : public GameLinkEvent
{
public:
UpdateCharacter():GameLinkEvent(GameEventTypes::evUpdateCharacter)
{
}
void serializeto(BitStream &bs) const override;
void serializefrom(BitStream &bs) override;
// [[ev_def:field]]
uint8_t m_index;
EVENT_IMPL(UpdateCharacter)
};
// [[ev_def:type]]
class CharacterResponse : public GameLinkEvent
{
public:
CharacterResponse():GameLinkEvent(GameEventTypes::evCharacterResponse)
{}
CharacterResponse(EventProcessor *src,uint8_t idx,const GameAccountResponseData &gad) : GameLinkEvent(GameEventTypes::evCharacterResponse,src)
{
m_index=idx;
m_data=gad;
}
void serializeto(BitStream &bs) const override;
void serializefrom(BitStream &bs) override;
// [[ev_def:field]]
uint8_t m_index;
// [[ev_def:field]]
GameAccountResponseData m_data;
EVENT_IMPL(CharacterResponse)
};
// [[ev_def:type]]
class UpdateServer : public GameLinkEvent
{
public:
UpdateServer():GameLinkEvent(GameEventTypes::evUpdateServer)
{}
void serializeto( BitStream &tgt ) const override;
void serializefrom( BitStream &src ) override;
void dependent_dump() const;
EVENT_IMPL(UpdateServer)
// [[ev_def:field]]
uint32_t m_build_date;
// [[ev_def:field]]
QString currentVersion;
// [[ev_def:field]]
std::array<uint8_t,16> clientInfo;
// [[ev_def:field]]
uint32_t authID;
// [[ev_def:field]]
uint32_t authCookie;
// [[ev_def:field]]
QString accountName;
// [[ev_def:field]]
bool localMapServer;
};
// [[ev_def:type]]
class CharacterSlots : public GameLinkEvent
{
public:
CharacterSlots():GameLinkEvent(GameEventTypes::evCharacterSlots)
{}
void serializeto( BitStream &tgt ) const override;
void serializefrom( BitStream &src ) override;
// [[ev_def:field]]
uint32_t m_unknown_new;
// [[ev_def:field]]
std::array<uint8_t,16> m_clientinfo;
// [[ev_def:field]]
GameAccountResponseData m_data;
EVENT_IMPL(CharacterSlots)
};
// [[ev_def:type]]
class GameEntryError : public GameLinkEvent
{
public:
GameEntryError():GameLinkEvent(GameEventTypes::evGameEntryError)
{}
GameEntryError(EventProcessor *evsrc,const QString &erstr):GameLinkEvent(GameEventTypes::evGameEntryError,evsrc),m_error(erstr)
{}
void serializeto( BitStream &tgt ) const override;
void serializefrom( BitStream &src ) override;
// [[ev_def:field]]
QString m_error;
EVENT_IMPL(GameEntryError)
};
// [[ev_def:type]]
class DeleteAcknowledged : public GameLinkEvent
{
public:
DeleteAcknowledged():GameLinkEvent(GameEventTypes::evDeleteAcknowledged)
{}
void serializeto( BitStream &tgt ) const override;
void serializefrom( BitStream &) override {}
EVENT_IMPL(DeleteAcknowledged)
};
// [[ev_def:type]]
class ServerReconfigured : public InternalEvent
{
public:
ServerReconfigured():InternalEvent(GameEventTypes::evServerReconfigured) {}
EVENT_IMPL(ServerReconfigured)
};
} // end of SEGSEvents namespace
|
ruhan-islam/ctf-archives
|
ICHSA/2021/crypto/Baby_Homework/best_crypto_service.py
|
#!/usr/local/bin/python2
from Crypto.Cipher.AES import AESCipher
import os, random, binascii
from sys import argv
import string
import sys
def padding(data):
pad_size = 16 - (len(data) % 16)
data = data + "".join([random.choice(string.printable) for _ in range(pad_size)])
return data
def encrypt(data):
return AESCipher(os.environ.get('KEY')).encrypt(padding(data))
def main():
print "Hello! What do you want to encrypt today?"
sys.stdout.flush()
user_input = raw_input()
print binascii.hexlify(encrypt(user_input + os.environ.get('FLAG')))
sys.exit()
if __name__ == '__main__':
main()
|
DavidWhitlock/PortlandStateJava
|
grader/src/test/java/edu/pdx/cs410J/grader/GradesFromD2LImporterTest.java
|
<filename>grader/src/test/java/edu/pdx/cs410J/grader/GradesFromD2LImporterTest.java
package edu.pdx.cs410J.grader;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class GradesFromD2LImporterTest {
@Test
public void errorWhenD2LQuizDoesNotExistInGradebook() {
String studentId = "studentId";
GradeBook gradebook = new GradeBook("test");
Student student = new Student(studentId);
gradebook.addStudent(student);
GradesFromD2L d2l = new GradesFromD2L();
GradesFromD2L.D2LStudent d2LStudent = GradesFromD2L.newStudent().setFirstName("first").setLastName("last").setD2LId(studentId).create();
d2LStudent.setScore("quiz", 3.4);
d2l.addStudent(d2LStudent);
assertThrows(IllegalStateException.class, () ->
GradesFromD2LImporter.importGradesFromD2L(d2l, gradebook)
);
}
@Test
public void importScoreFromD2LWhenStudentIdMatchesD2LId() {
String studentId = "studentId";
String quizName = "quiz";
double score = 3.4;
GradeBook gradebook = new GradeBook("test");
gradebook.addAssignment(new Assignment(quizName, 4.0));
Student student = new Student(studentId);
gradebook.addStudent(student);
GradesFromD2L d2l = new GradesFromD2L();
GradesFromD2L.D2LStudent d2LStudent = GradesFromD2L.newStudent().setFirstName("first").setLastName("last").setD2LId(studentId).create();
d2LStudent.setScore(quizName, score);
d2l.addStudent(d2LStudent);
GradesFromD2LImporter.importGradesFromD2L(d2l, gradebook);
assertThat(student.getGradeNames(), hasItem(quizName));
assertThat(student.getGrade(quizName).getScore(), equalTo(score));
}
@Test
public void importScoreFromD2LWhenStudentNameMatchesD2LName() {
String firstName = "first";
String lastName = "last";
String quizName = "quiz";
double score = 3.4;
GradeBook gradebook = new GradeBook("test");
gradebook.addAssignment(new Assignment(quizName, 4.0));
Student student = new Student("studentId");
student.setFirstName(firstName);
student.setLastName(lastName);
gradebook.addStudent(student);
GradesFromD2L d2l = new GradesFromD2L();
GradesFromD2L.D2LStudent d2LStudent = GradesFromD2L.newStudent().setFirstName(firstName).setLastName(lastName).setD2LId("d2LstudentId").create();
d2LStudent.setScore(quizName, score);
d2l.addStudent(d2LStudent);
GradesFromD2LImporter.importGradesFromD2L(d2l, gradebook);
assertThat(student.getGradeNames(), hasItem(quizName));
assertThat(student.getGrade(quizName).getScore(), equalTo(score));
}
}
|
tstibro/chip8
|
Chip8lib/core/cpu/instructions/setVxToVyMinusVxInstruction.cpp
|
<reponame>tstibro/chip8
/*
* setVxToVyMinusVxInstruction.cpp
*
* Created on: Jul 16, 2016
* Author: <NAME>
*/
#include "setVxToVyMinusVxInstruction.hpp"
#include "../cpu.hpp"
using namespace chip8::core::cpu::instructions;
using namespace chip8::core::cpu;
SetVxToVyMinusVxInstruction::SetVxToVyMinusVxInstruction(u8 registerXindex, u8 registerYindex, CPU *cpu) : IInstruction()
{
SetRegisterXindex(registerXindex);
SetRegisterYindex(registerYindex);
this->cpu = cpu;
}
SetVxToVyMinusVxInstruction::~SetVxToVyMinusVxInstruction()
{
}
void SetVxToVyMinusVxInstruction::Execute()
{
u8 registerXvalue = this->cpu->ReadFromGeneralPurposeRegister(registerXindex);
u8 registerYvalue = this->cpu->ReadFromGeneralPurposeRegister(registerYindex);
u8 newValue = (u8)((i16)registerYvalue - (i16)registerXvalue);
this->cpu->WriteToGeneralPurposeRegister(registerXindex, newValue);
//VF is set to 0 when there's a borrow, and 1 when there isn't.
u8 borrow = (registerYvalue >= registerXvalue) ? 1 : 0;
this->cpu->WriteToFlagRegister(borrow);
}
void SetVxToVyMinusVxInstruction::SetRegisterXindex(u8 registerIndex)
{
this->registerXindex = registerIndex;
}
void SetVxToVyMinusVxInstruction::SetRegisterYindex(u8 registerIndex)
{
this->registerYindex = registerIndex;
}
|
Doorglazing/java
|
javase/Object/src/Date/DateTest1.java
|
package Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateTest1 {
public static void main(String[] args) throws ParseException {
String str = "2001年6月6日";
DateFormat date = new SimpleDateFormat("yyyy年M月d日");
System.out.println(date.parse(str));
//Wed Jun 06 00:00:00 CST 2001
}
}
|
fullstackdev39/Admin-Panel-React
|
src/theme/theme/react/demo2/src/_metronic/layout/header/Topbar/Topbar.js
|
/* eslint-disable no-unused-vars */
import React from "react";
import QuickPanelToggler from "./quick-panel-toggler/QuickPanelToggle";
import QuickActionsPanel from "../../../../app/partials/layout/QuickActionsPanel";
import MyCart from "../../../../app/partials/layout/MyCart";
import UserNotifications from "../../../../app/partials/layout/UserNotifications";
import UserProfile from "../../../../app/partials/layout/UserProfile";
import LanguageSelector from "../../../../app/partials/layout/LanguageSelector";
import { toAbsoluteUrl } from "../../../utils/utils";
export default class Topbar extends React.Component {
render() {
return (
<div className="kt-header__topbar">
<MyCart
icon={toAbsoluteUrl("/media/icons/svg/Shopping/Cart%233.svg")}
iconType=""
useSVG="true"
bgImage={toAbsoluteUrl("/media/misc/bg-1.jpg")}
/>
<UserNotifications
bgImage={toAbsoluteUrl("/media/misc/bg-1.jpg")}
pulse="true"
pulseLight="false"
skin="dark"
icon={toAbsoluteUrl("/media/icons/svg/Code/Compiling.svg")}
iconType=""
type="success"
useSVG="true"
dot="false"
/>
<QuickActionsPanel
bgImage={toAbsoluteUrl("/media/misc/bg-2.jpg")}
skin="dark"
iconType=""
icon={toAbsoluteUrl("/media/icons/svg/Media/Equalizer.svg")}
useSVG="true"
gridNavSkin="light"
/>
<QuickPanelToggler />
<LanguageSelector iconType="" />
<UserProfile showAvatar={false} showHi={true} showBadge={true} />
</div>
);
}
}
|
jasha64/jasha64
|
Spring 2018/ACM/2018.7.24/C.cpp
|
<reponame>jasha64/jasha64
#include <iostream>
using namespace std;
inline int Lowbit(int x) {return x & -x;}
int main()
{
ios::sync_with_stdio(false);
int T;
cin >> T;
while (T--)
{
int n;
cin >> n;
int Res = 0;
for (int i = n ^ (n-1); i > 0; i -= Lowbit(i)) ++Res;
cout << Res << endl;
}
return 0;
}
|
echinopsii/net.echinopsii.3rdparty.infinispan
|
compatibility52x/adaptor52x/src/main/java/org/infinispan/config/TypedPropertiesAdapter.java
|
package org.infinispan.config;
import java.util.Set;
import java.util.Map.Entry;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.infinispan.util.TypedProperties;
/**
* TypedPropertiesAdapter is JAXB XmlAdapter for TypedProperties.
*
* @author <NAME>
* @since 4.0
*/
public class TypedPropertiesAdapter extends XmlAdapter<PropertiesType, TypedProperties> {
@Override
public PropertiesType marshal(TypedProperties tp) throws Exception {
PropertiesType pxml = new PropertiesType();
Property[] pa = new Property[tp.size()];
Set<Entry<Object, Object>> set = tp.entrySet();
int index = 0;
for (Entry<Object, Object> entry : set) {
pa[index] = new Property();
pa[index].name = (String) entry.getKey();
pa[index].value = (String) entry.getValue();
index++;
}
pxml.properties = pa;
return pxml;
}
@Override
public TypedProperties unmarshal(PropertiesType props) throws Exception {
TypedProperties tp = new TypedProperties();
if (props != null && props.properties != null) {
for (Property p : props.properties) {
tp.put(p.name, p.value);
}
}
return tp;
}
}
|
SoftHoardersOG/FreightFrenzyNatio
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Tests/TestCarusel.java
|
<reponame>SoftHoardersOG/FreightFrenzyNatio<gh_stars>0
package org.firstinspires.ftc.teamcode.Tests;
import static org.firstinspires.ftc.teamcode.Hardware.HardwareUtils.changeDirection;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import org.firstinspires.ftc.teamcode.Autonomous.AutoUtils.AutoUtil;
import org.firstinspires.ftc.teamcode.Hardware.Hardware;
import org.firstinspires.ftc.teamcode.TeleOp.Utils.Initializations;
@TeleOp(name = "TestCarusel")
public class TestCarusel extends LinearOpMode {
@Override
public void runOpMode() throws InterruptedException {
Initializations.AutoInitialization(telemetry, hardwareMap);
waitForStart();
while (!isStopRequested() && opModeIsActive()) {
}
}
}
|
benihime91/litcv
|
gale/classification/augment.py
|
<gh_stars>0
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05a_classification.augment.ipynb (unless otherwise specified).
__all__ = ['imagenet_stats', 'cifar_stats', 'mnist_stats', 'imagenet_stats', 'cifar_stats', 'mnist_stats',
'imagenet_no_augment_transform', 'imagenet_augment_transform', 'aug_transforms']
# Cell
from typing import *
import albumentations as A
import numpy as np
import torchvision.transforms as T
from timm.data.auto_augment import auto_augment_transform, rand_augment_transform
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data.transforms import RandomResizedCropAndInterpolation, _pil_interp
from torch import Tensor
# Cell
imagenet_stats = (IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD)
cifar_stats = ([0.491, 0.482, 0.447], [0.247, 0.243, 0.261])
mnist_stats = ([0.15, 0.15, 0.15], [0.15, 0.15, 0.15])
#nbdev_comment _all_ = ["imagenet_stats", "cifar_stats", "mnist_stats"]
# Cell
def imagenet_no_augment_transform(
size: Union[Sequence, int] = 224, interpolation: str = "bilinear"
) -> T.Compose:
"""
The default image transform without data augmentation.
It is often useful for testing models on Imagenet.
It sequentially resizes the image and takes a central cropping.
"""
interpolation = _pil_interp(interpolation)
tfl = [T.Resize(size, _pil_interp(interpolation)), T.CenterCrop(size)]
return T.Compose(tfl)
# Cell
def imagenet_augment_transform(
size: int = 224,
scale: Optional[float] = None,
ratio: Optional[float] = None,
interpolation: str = "random",
hflip: Union[float, bool] = 0.5,
vflip: Union[float, bool] = False,
color_jitter: Union[Sequence, float] = 0.4,
auto_augment: Optional[str] = None,
mean: Optional[Sequence[float]] = IMAGENET_DEFAULT_MEAN,
) -> T.Compose:
"""
The default image transform with data augmentation.It is often useful for training models on Imagenet.
Adapted from: https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/transforms_factory.py
"""
scale = tuple(scale or (0.08, 1.0)) # default imagenet scale range
ratio = tuple(ratio or (3.0 / 4.0, 4.0 / 3.0)) # default imagenet ratio range
transforms = [
RandomResizedCropAndInterpolation(size, scale, ratio, interpolation),
]
if hflip and hflip > 0:
transforms.append(T.RandomHorizontalFlip(p=hflip))
if vflip and vflip > 0.0:
transforms.append(T.RandomVerticalFlip(p=vflip))
if auto_augment:
assert isinstance(auto_augment, str)
if isinstance(size, (tuple, list)):
size_min = min(size)
else:
size_min = size
aa_params = dict(
translate_const=int(size_min * 0.45),
img_mean=tuple([min(255, round(255 * x)) for x in mean]),
)
if interpolation and interpolation != "random":
aa_params["interpolation"] = _pil_interp(interpolation)
if auto_augment.startswith("rand"):
transforms += [rand_augment_transform(auto_augment, aa_params)]
else:
transforms += [auto_augment_transform(auto_augment, aa_params)]
elif color_jitter is not None:
# color jitter is enabled when not using AA
if isinstance(color_jitter, (list, tuple)):
# color jitter should be a 3-tuple/list if spec brightness/contrast/saturation
# or 4 if also augmenting hue
assert len(color_jitter) in (3, 4)
else:
# if it's a scalar, duplicate for brightness, contrast, and saturation, no hue
color_jitter = (float(color_jitter),) * 3
transforms += [T.ColorJitter(*color_jitter)]
return T.Compose(transforms)
# Cell
def aug_transforms(
presize: int = 260,
size: int = 224,
interpolation: int = 1,
hflip: Union[float, bool] = 0.5,
vflip: Union[float, bool] = False,
max_lighting: Union[float, bool] = 0.2,
p_lighting: float = 0.75,
max_rotate: Union[float, int, bool] = 10.0,
p_rotate: float = 0.5,
max_warp: Union[float, bool] = 0.2,
p_affine: float = 0.75,
pad_mode: str = "reflect",
mult: float = 1.0,
xtra_tfms: Optional[List] = None,
) -> A.Compose:
"""
Utility func to easily create a list of flip, rotate, zoom, lighting transforms.
Inspired from : https://docs.fast.ai/vision.augment.html#aug_transforms
"""
max_rotate, max_lighting, max_warp = (
np.array([max_rotate, max_lighting, max_warp]) * mult
)
transforms = [
A.Resize(presize, presize, interpolation=interpolation, always_apply=True)
]
if hflip:
transforms += [A.HorizontalFlip(p=hflip)]
if vflip:
transforms += [A.VerticalFlip(p=vflip)]
if max_rotate:
transforms += [
A.Rotate(limit=max_rotate, interpolation=interpolation, p=p_rotate)
]
if max_warp:
transforms += [A.IAAAffine(scale=max_warp, p=p_affine, mode=pad_mode)]
if max_lighting:
transforms += [A.RandomBrightness(max_lighting, p=p_lighting)]
transforms += [A.RandomContrast(max_lighting, p=p_lighting)]
if xtra_tfms is not None:
transforms += [xtra_tfms]
transforms += [
A.RandomResizedCrop(size, size, interpolation=interpolation, always_apply=True)
]
return A.Compose(transforms)
|
CourtHive/tods-competition-factory
|
src/drawEngine/governors/positionGovernor/conditionallyDisableLinkPositioning.js
|
<filename>src/drawEngine/governors/positionGovernor/conditionallyDisableLinkPositioning.js
import {
addExtension,
removeExtension,
} from '../../../tournamentEngine/governors/tournamentGovernor/addRemoveExtensions';
import { getPositionAssignments } from '../../getters/positionsGetter';
import { DISABLE_LINKS } from '../../../constants/extensionConstants';
import { MAIN, QUALIFYING } from '../../../constants/drawDefinitionConstants';
export function conditionallyDisableLinkPositioning({
drawPositions,
structure,
}) {
if (
[QUALIFYING, MAIN].includes(structure.stage) &&
structure.stageSequence === 1
) {
// positionActions are not disabled for first stage QUALIFYING and MAIN structures
return;
}
const { positionAssignments } = getPositionAssignments({ structure });
const relevantAssignments = positionAssignments.filter(({ drawPosition }) =>
drawPositions.includes(drawPosition)
);
relevantAssignments.forEach((assignment) => {
const extension = {
name: DISABLE_LINKS,
value: true,
};
addExtension({ element: assignment, extension });
});
}
// NOTE: NOT READY TO USE.
// Would only be possible to remove disabling extension if the position is unassigned..
// ...AND the source position has not yet attempted participant traversal
export function reEnableDrawPositionLinks({ drawPosition, structure }) {
const { positionAssignments } = getPositionAssignments({ structure });
const assignment = positionAssignments.find(
(assignment) => assignment.drawPosition === drawPosition
);
const { participantId, bye, qualifier } = assignment || {};
if (!participantId && !bye && !qualifier) {
removeExtension({ element: assignment, name: DISABLE_LINKS });
}
}
|
akashkj/commcare-hq
|
corehq/preindex/preindex_plugins.py
|
from abc import ABCMeta, abstractmethod
import os
from dimagi.utils.couch.database import get_db
from dimagi.utils.couch.sync_docs import DesignInfo
PREINDEX_PLUGINS = {}
def register_preindex_plugin(plugin):
PREINDEX_PLUGINS[plugin.app_label] = plugin
class PreindexPlugin(metaclass=ABCMeta):
synced = False
@abstractmethod
def _get_designs(self):
raise NotImplementedError()
def get_designs(self):
used = set()
designs = []
for design in self._get_designs():
key = (design.db.uri, design.app_label)
if key not in used:
designs.append(design)
used.add(key)
return designs
@classmethod
def register(cls, *args, **kwargs):
register_preindex_plugin(cls(*args, **kwargs))
def sync_design_docs(self, temp=None):
from corehq.preindex.accessors import sync_design_doc
if self.synced:
# workaround emit_post_sync_signal called twice
# https://code.djangoproject.com/ticket/17977
# this is to speed up test initialization
return
self.synced = True
for design in self.get_designs():
sync_design_doc(design, temp=temp)
def copy_designs(self, temp=None, delete=True):
from corehq.preindex.accessors import copy_design_doc
for design in self.get_designs():
copy_design_doc(design, temp=temp, delete=delete)
def __repr__(self):
return '{cls.__name__}({self.app_label!r}, {self.dir!r})'.format(
cls=self.__class__,
self=self,
)
def __init__(self, app_label, file):
self.app_label = app_label
self.dir = os.path.abspath(os.path.dirname(file))
def get_dbs_from_app_label_and_map(app_label, app_db_map):
if app_db_map and app_label in app_db_map:
db_names = app_db_map[app_label]
if not isinstance(db_names, (list, tuple, set)):
db_names = [db_names]
return [get_db(db_name) for db_name in set(db_names)]
return [get_db()]
class CouchAppsPreindexPlugin(PreindexPlugin):
"""
:param app_label: The app label for the top level application.
:param dir: The directory of the top level application.
:param app_db_map: A dictionary mapping child apps to couch databases.
e.g. {'my_app': 'meta'} will result in 'my_app' being synced
to the '{main_db}__meta' database.
use e.g.
CouchAppsPreindexPlugin.register('couchapps', __file__, {
'myview': <list of db slugs to sync to>
...
})
to register a module as a couchapps root
"""
def __init__(self, app_label, file, app_db_map=None):
super().__init__(app_label, file)
self.app_db_map = app_db_map
def get_couchapps(self):
return [d for d in os.listdir(self.dir)
if os.path.isdir(os.path.join(self.dir, d)) and d != '__pycache__']
def _get_designs(self):
return [
DesignInfo(app_label=app_label, db=db,
design_path=os.path.join(self.dir, app_label))
for app_label in self.get_couchapps()
for db in self.get_dbs(app_label)
]
def get_dbs(self, app_label):
return get_dbs_from_app_label_and_map(app_label, self.app_db_map)
class ExtraPreindexPlugin(PreindexPlugin):
"""
ExtraPreindexPlugin.register('myapp', __file__, <list of db slugs to sync to>)
"""
def __init__(self, app_label, file, db_names=None):
super().__init__(app_label, file)
self.db_names = db_names
def _get_designs(self):
return [
DesignInfo(
app_label=self.app_label,
db=db,
design_path=os.path.join(self.dir, "_design")
)
for db in self.get_dbs(self.app_label)
]
def get_dbs(self, app_label):
return get_dbs_from_app_label_and_map(app_label, {app_label: self.db_names})
|
rentianhua/tsf_android
|
houseAd/HouseGo/src/com/dumu/housego/view/ISureYuYueView.java
|
package com.dumu.housego.view;
public interface ISureYuYueView {
void sureyuyue(String info);
}
|
jbrandolinisf/EDA
|
force-app/main/releaseGating/aura/releaseGateModalOpener/releaseGateModalOpenerController.js
|
({
openReleaseGateModal: function (component, event, helper) {
helper.openReleaseGateModal(component, event.getParam("arguments"));
},
handleModalDataChangeEvent: function (component, event, helper) {
helper.handleModalDataChangeEvent(component, event);
},
handleModalFooterEvent: function (component, event, helper) {
helper.handleModalFooterEvent(component, event);
}
});
|
npocmaka/Windows-Server-2003
|
admin/pchealth/helpctr/rc/rctool/safrcfiledlg/panic.h
|
<filename>admin/pchealth/helpctr/rc/rctool/safrcfiledlg/panic.h
// Panic.h : Declaration of the CPanic
#ifndef __PANIC_H_
#define __PANIC_H_
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CPanic
#define EventName "{26ED148B-1050-461d-9999-3A5002D0103D}"
LRESULT CALLBACK KeyboardProc(int code,WPARAM wParam,LPARAM lParam);
class CHookHnd
{
public:
HHOOK m_hHook;
CHookHnd()
{
m_hHook = NULL;
}
~CHookHnd()
{
if (m_hHook)
UnhookWindowsHookEx(m_hHook);
}
HHOOK SetHook()
{
if (!m_hHook)
{
m_hHook = SetWindowsHookEx(WH_KEYBOARD,KeyboardProc,_Module.GetModuleInstance(),NULL);
}
return m_hHook;
}
BOOL UnHook()
{
BOOL bRetVal = TRUE;
if (m_hHook)
{
bRetVal = UnhookWindowsHookEx(m_hHook);
if (bRetVal == TRUE)
m_hHook = NULL;
}
return bRetVal;
}
};
class ATL_NO_VTABLE CPanic :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CPanic, &CLSID_Panic>,
public IDispatchImpl<IPanic, &IID_IPanic, &LIBID_SAFRCFILEDLGLib>
{
public:
CPanic()
{
m_hEvent = NULL;
}
~CPanic();
DECLARE_REGISTRY_RESOURCEID(IDR_PANIC)
DECLARE_NOT_AGGREGATABLE(CPanic)
DECLARE_PROTECT_FINAL_CONSTRUCT()
BEGIN_COM_MAP(CPanic)
COM_INTERFACE_ENTRY(IPanic)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
CComPtr<IDispatch> m_ptrScriptFncPtr;
HANDLE m_hEvent;
static CHookHnd m_Hook;
static HANDLE m_hPanicThread;
static DWORD WINAPI PanicThread(LPVOID lpParameter);
// IPanic
public:
STDMETHOD(ClearPanicHook)();
STDMETHOD(SetPanicHook)(/*[in]*/ IDispatch *iDisp);
};
#endif //__PANIC_H_
|
shayanhabibi/gitnim
|
bin/cache/@m..@salgo@shalgorithm.nim.c
|
<filename>bin/cache/@m..@salgo@shalgorithm.nim.c<gh_stars>0
/* Generated by Nim Compiler v1.4.8 */
/* (c) 2021 <NAME> */
/* The generated code is subject to the original license. */
/* Compiled for: Windows, amd64, gcc */
/* Command for C compiler:
gcc.exe -c -w -fmax-errors=3 -mno-ms-bitfields -DWIN32_LEAN_AND_MEAN -pg -O3 -fno-strict-aliasing -fno-ident -IC:\Users\PC\.choosenim\toolchains\nim-1.4.8\lib -IC:\Users\PC\AppData\Local\Temp\nimble_23592\githubcom_haxscramperhmisc_0.12.0\src\hmisc\scripts -o C:\Users\PC\.choosenim\toolchains\nim-1.4.8\bin\cache\@m..@salgo@shalgorithm.nim.c.o C:\Users\PC\.choosenim\toolchains\nim-1.4.8\bin\cache\@m..@salgo@shalgorithm.nim.c */
#define NIM_INTBITS 64
/* section: NIM_merge_HEADERS */
#include "nimbase.h"
#include <string.h>
#undef LANGUAGE_C
#undef MIPSEB
#undef MIPSEL
#undef PPC
#undef R3000
#undef R4000
#undef i386
#undef linux
#undef mips
#undef near
#undef far
#undef powerpc
#undef unix
/* section: NIM_merge_FRAME_DEFINES */
#define nimfr_(x, y)
#define nimln_(x, y)
/* section: NIM_merge_FORWARD_TYPES */
typedef struct tySequence__4eRCaZmrYLLw2k30GPTiMw tySequence__4eRCaZmrYLLw2k30GPTiMw;
typedef struct TGenericSeq TGenericSeq;
typedef struct tyTuple__QeWl6B6ffS4pU6WWrtcrDw tyTuple__QeWl6B6ffS4pU6WWrtcrDw;
typedef struct NimStringDesc NimStringDesc;
typedef struct TNimType TNimType;
typedef struct TNimNode TNimNode;
typedef struct tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g;
typedef struct tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w;
typedef struct tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ;
typedef struct tyObject_GcStack__7fytPA5bBsob6See21YMRA tyObject_GcStack__7fytPA5bBsob6See21YMRA;
typedef struct tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg;
typedef struct tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ;
typedef struct tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg;
typedef struct tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw;
typedef struct tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA;
typedef struct tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw;
typedef struct tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw;
typedef struct tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg;
typedef struct tyTuple__ujsjpB2O9cjj3uDHsXbnSzg tyTuple__ujsjpB2O9cjj3uDHsXbnSzg;
typedef struct tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg;
typedef struct tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ;
typedef struct tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg;
typedef struct tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA;
/* section: NIM_merge_TYPES */
struct TGenericSeq {
NI len;
NI reserved;
};
struct NimStringDesc {
TGenericSeq Sup;
NIM_CHAR data[SEQ_DECL_SIZE];
};
struct tyTuple__QeWl6B6ffS4pU6WWrtcrDw {
NI Field0;
NimStringDesc* Field1;
};
typedef NU8 tyEnum_TNimKind__jIBKr1ejBgsfM33Kxw4j7A;
typedef NU8 tySet_tyEnum_TNimTypeFlag__v8QUszD1sWlSIWZz7mC4bQ;
typedef N_NIMCALL_PTR(void, tyProc__ojoeKfW4VYIm36I9cpDTQIg) (void* p, NI op);
typedef N_NIMCALL_PTR(void*, tyProc__WSm2xU5ARYv9aAR4l0z9c9auQ) (void* p);
struct TNimType {
NI size;
NI align;
tyEnum_TNimKind__jIBKr1ejBgsfM33Kxw4j7A kind;
tySet_tyEnum_TNimTypeFlag__v8QUszD1sWlSIWZz7mC4bQ flags;
TNimType* base;
TNimNode* node;
void* finalizer;
tyProc__ojoeKfW4VYIm36I9cpDTQIg marker;
tyProc__WSm2xU5ARYv9aAR4l0z9c9auQ deepcopy;
};
typedef NU8 tyEnum_TNimNodeKind__unfNsxrcATrufDZmpBq4HQ;
struct TNimNode {
tyEnum_TNimNodeKind__unfNsxrcATrufDZmpBq4HQ kind;
NI offset;
TNimType* typ;
NCSTRING name;
NI len;
TNimNode** sons;
};
struct tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g {
NI refcount;
TNimType* typ;
};
struct tyObject_GcStack__7fytPA5bBsob6See21YMRA {
void* bottom;
};
struct tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w {
NI len;
NI cap;
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g** d;
};
typedef tyObject_SmallChunk__tXn60W2f8h3jgAYdEmy5NQ* tyArray__SPr7N6UKfuF549bNPiUvSRw[256];
typedef NU32 tyArray__BHbOSqU1t9b3Gt7K2c6fQig[24];
typedef tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg* tyArray__N1u1nqOgmuJN9cSZrnMHgOQ[32];
typedef tyArray__N1u1nqOgmuJN9cSZrnMHgOQ tyArray__B6durA4ZCi1xjJvRtyYxMg[24];
typedef tyObject_Trunk__W0r8S0Y3UGke6T9bIUWnnuw* tyArray__lh2A89ahMmYg9bCmpVaplLbA[256];
struct tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA {
tyArray__lh2A89ahMmYg9bCmpVaplLbA data;
};
typedef tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* tyArray__0aOLqZchNi8nWtMTi8ND8w[2];
struct tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw {
tyArray__0aOLqZchNi8nWtMTi8ND8w link;
NI key;
NI upperBound;
NI level;
};
struct tyTuple__ujsjpB2O9cjj3uDHsXbnSzg {
tyObject_BigChunk__Rv9c70Uhp2TytkX7eH78qEg* Field0;
NI Field1;
};
typedef tyTuple__ujsjpB2O9cjj3uDHsXbnSzg tyArray__LzOv2eCDGiceMKQstCLmhw[30];
struct tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg {
NI len;
tyArray__LzOv2eCDGiceMKQstCLmhw chunks;
tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg* next;
};
struct tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg {
NI minLargeObj;
NI maxLargeObj;
tyArray__SPr7N6UKfuF549bNPiUvSRw freeSmallChunks;
NU32 flBitmap;
tyArray__BHbOSqU1t9b3Gt7K2c6fQig slBitmap;
tyArray__B6durA4ZCi1xjJvRtyYxMg matrix;
tyObject_LLChunk__XsENErzHIZV9bhvyJx56wGw* llmem;
NI currMem;
NI maxMem;
NI freeMem;
NI occ;
NI lastSize;
tyObject_IntSet__EZObFrE3NC9bIb3YMkY9crZA chunkStarts;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* root;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* deleted;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* last;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw* freeAvlNodes;
NIM_BOOL locked;
NIM_BOOL blockChunkSizeIncrease;
NI nextChunkSize;
tyObject_AvlNode__IaqjtwKhxLEpvDS9bct9blEw bottomData;
tyObject_HeapLinks__PDV1HBZ8CQSQJC9aOBFNRSg heapLinks;
};
struct tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg {
NI stackScans;
NI cycleCollections;
NI maxThreshold;
NI maxStackSize;
NI maxStackCells;
NI cycleTableSize;
NI64 maxPause;
};
struct tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ {
NI counter;
NI max;
tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg* head;
tyObject_PageDesc__fublkgIY4LG3mT51LU2WHg** data;
};
struct tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ {
tyObject_GcStack__7fytPA5bBsob6See21YMRA stack;
NI cycleThreshold;
NI zctThreshold;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w zct;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w decStack;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w tempStack;
NI recGcLock;
tyObject_MemRegion__x81NhDv59b8ercDZ9bi85jyg region;
tyObject_GcStat__0RwLoVBHZPfUAcLczmfQAg stat;
tyObject_CellSet__jG87P0AI9aZtss9ccTYBIISQ marked;
tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w additionalRoots;
NI gcThreadId;
};
typedef NU8 tyEnum_StrNormalizationKind__fwCBRnNT8uJ7604Pow8DgA;
struct tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA {
NI a;
NI b;
};
/* section: NIM_merge_SEQ_TYPES */
struct tySequence__4eRCaZmrYLLw2k30GPTiMw {
TGenericSeq Sup;
tyTuple__QeWl6B6ffS4pU6WWrtcrDw data[SEQ_DECL_SIZE];
};
/* section: NIM_merge_PROC_HEADERS */
N_LIB_PRIVATE N_NOINLINE(void, raiseIndexError2)(NI i, NI n);
static N_INLINE(void, nimZeroMem)(void* p, NI size);
static N_INLINE(void, nimSetMem__zxfKBYntu9cBapkhrCOk1fgmemory)(void* a, int v, NI size);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, copyString)(NimStringDesc* src);
N_LIB_PRIVATE N_NIMCALL(TGenericSeq*, incrSeqV3)(TGenericSeq* s, TNimType* typ);
N_LIB_PRIVATE N_NIMCALL(void, nimGCvisit)(void* d, NI op);
static N_NIMCALL(void, Marker_tySequence__4eRCaZmrYLLw2k30GPTiMw)(void* p, NI op);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, copyStringRC1)(NimStringDesc* src);
static N_INLINE(void, nimGCunrefNoCycle)(void* p);
static N_INLINE(void, decRef__AT1eRuflKWyTTBdLjEDZbgsystem)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
static N_INLINE(NI, minuspercent___dgYAo7RfdUVVpvkfKDym8w_2system)(NI x, NI y);
static N_INLINE(NIM_BOOL, ltpercent___hPljn3JCDQ00ua1R07X9bxQsystem)(NI x, NI y);
static N_INLINE(void, rtlAddZCT__AT1eRuflKWyTTBdLjEDZbg_2system)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
N_LIB_PRIVATE N_NOINLINE(void, addZCT__Y66tOYFjgwJ0k4aLz4bc0Q)(tyObject_CellSeq__Axo1XVm9aaQueTOldv8le5w* s, tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c);
static N_INLINE(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*, usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem)(void* usr);
N_LIB_PRIVATE N_NOINLINE(void, raiseOverflow)(void);
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, addChar)(NimStringDesc* s, NIM_CHAR c);
static N_INLINE(NimStringDesc*, X5BX5D___ogYTOKbgqbjPfyC123US1gsystem)(NimStringDesc* s, tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA x);
N_NIMCALL(NimStringDesc*, mnewString)(NI len);
N_LIB_PRIVATE N_NOINLINE(void, raiseRangeErrorI)(NI64 i, NI64 a, NI64 b);
static N_INLINE(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA, dotdot___xNR8BVBMWzS9bXXNMikmyLgsystem)(NI a, NI b);
N_LIB_PRIVATE N_NIMCALL(void, failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A)(NimStringDesc* msg);
/* section: NIM_merge_DATA */
N_LIB_PRIVATE TNimType NTI__QeWl6B6ffS4pU6WWrtcrDw_;
extern TNimType NTI__rR5Bzr1D5krxoo1NcNyeMA_;
extern TNimType NTI__77mFvmsOLKik79ci2hXkHEg_;
N_LIB_PRIVATE TNimType NTI__4eRCaZmrYLLw2k30GPTiMw_;
STRING_LITERAL(TM__cYXlk6iIaZ0nvpH4aISAaQ_11, "iterators.nim(222, 11) `len(a) == L` the length of the string c"
"hanged while iterating over it", 93);
/* section: NIM_merge_VARS */
extern tyObject_GcHeap__1TRH1TZMaVZTnLNcIHuNFQ gch__IcYaEuuWivYAS86vFMTS3Q;
/* section: NIM_merge_PROCS */
static N_INLINE(void, nimSetMem__zxfKBYntu9cBapkhrCOk1fgmemory)(void* a, int v, NI size) {
void* T1_;
T1_ = (void*)0;
T1_ = memset(a, v, ((size_t) (size)));
}
static N_INLINE(void, nimZeroMem)(void* p, NI size) {
nimSetMem__zxfKBYntu9cBapkhrCOk1fgmemory(p, ((int) 0), size);
}
static N_NIMCALL(void, Marker_tySequence__4eRCaZmrYLLw2k30GPTiMw)(void* p, NI op) {
tySequence__4eRCaZmrYLLw2k30GPTiMw* a;
NI T1_;
a = (tySequence__4eRCaZmrYLLw2k30GPTiMw*)p;
T1_ = (NI)0;
for (T1_ = 0; T1_ < (a ? a->Sup.len : 0); T1_++) {
nimGCvisit((void*)a->data[T1_].Field1, op);
}
}
static N_INLINE(NI, minuspercent___dgYAo7RfdUVVpvkfKDym8w_2system)(NI x, NI y) {
NI result;
result = (NI)0;
result = ((NI) ((NU)((NU64)(((NU) (x))) - (NU64)(((NU) (y))))));
return result;
}
static N_INLINE(NIM_BOOL, ltpercent___hPljn3JCDQ00ua1R07X9bxQsystem)(NI x, NI y) {
NIM_BOOL result;
result = (NIM_BOOL)0;
result = ((NU64)(((NU) (x))) < (NU64)(((NU) (y))));
return result;
}
static N_INLINE(void, rtlAddZCT__AT1eRuflKWyTTBdLjEDZbg_2system)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) {
addZCT__Y66tOYFjgwJ0k4aLz4bc0Q((&gch__IcYaEuuWivYAS86vFMTS3Q.zct), c);
}
static N_INLINE(void, decRef__AT1eRuflKWyTTBdLjEDZbgsystem)(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* c) {
(*c).refcount = minuspercent___dgYAo7RfdUVVpvkfKDym8w_2system((*c).refcount, ((NI) 8));
{
NIM_BOOL T3_;
T3_ = (NIM_BOOL)0;
T3_ = ltpercent___hPljn3JCDQ00ua1R07X9bxQsystem((*c).refcount, ((NI) 8));
if (!T3_) goto LA4_;
rtlAddZCT__AT1eRuflKWyTTBdLjEDZbg_2system(c);
}
LA4_: ;
}
static N_INLINE(tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*, usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem)(void* usr) {
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* result;
NI T1_;
result = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T1_ = (NI)0;
T1_ = minuspercent___dgYAo7RfdUVVpvkfKDym8w_2system(((NI) (ptrdiff_t) (usr)), ((NI) 16));
result = ((tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*) (T1_));
return result;
}
static N_INLINE(void, nimGCunrefNoCycle)(void* p) {
tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g* T1_;
T1_ = (tyObject_Cell__1zcF9cV8XIAtbN8h5HRUB8g*)0;
T1_ = usrToCell__QFQqcLB3lgOdwipkv9a60xwsystem(p);
decRef__AT1eRuflKWyTTBdLjEDZbgsystem(T1_);
}
N_LIB_PRIVATE N_NIMCALL(tySequence__4eRCaZmrYLLw2k30GPTiMw*, enumerate__p35EXIgSaBOqnMGKvMdV4g)(NimStringDesc** s, NI sLen_0) {
tySequence__4eRCaZmrYLLw2k30GPTiMw* result;
result = (tySequence__4eRCaZmrYLLw2k30GPTiMw*)0;
{
NI idx;
NimStringDesc* item;
NI i;
idx = (NI)0;
item = (NimStringDesc*)0;
i = ((NI) 0);
{
while (1) {
tyTuple__QeWl6B6ffS4pU6WWrtcrDw T4_;
NI T5_;
NimStringDesc* T6_;
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_3;
if (!(i < sLen_0)) goto LA3;
idx = i;
if ((NU)(i) >= (NU)(sLen_0)){ raiseIndexError2(i,sLen_0-1); }
item = s[i];
nimZeroMem((void*)(&T4_), sizeof(tyTuple__QeWl6B6ffS4pU6WWrtcrDw));
T4_.Field0 = idx;
T4_.Field1 = copyString(item);
result = (tySequence__4eRCaZmrYLLw2k30GPTiMw*) incrSeqV3((TGenericSeq*)(result), (&NTI__4eRCaZmrYLLw2k30GPTiMw_));
T5_ = result->Sup.len++;
result->data[T5_].Field0 = T4_.Field0;
T6_ = (NimStringDesc*)0;
T6_ = result->data[T5_].Field1; result->data[T5_].Field1 = copyStringRC1(T4_.Field1);
if (T6_) nimGCunrefNoCycle(T6_);
if (nimAddInt(i, ((NI) 1), &TM__cYXlk6iIaZ0nvpH4aISAaQ_3)) { raiseOverflow(); };
i = (NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_3);
} LA3: ;
}
}
return result;
}
static N_INLINE(NimStringDesc*, X5BX5D___ogYTOKbgqbjPfyC123US1gsystem)(NimStringDesc* s, tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA x) {
NimStringDesc* result;
NI a;
NI L;
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_5;
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_6;
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_7;
result = (NimStringDesc*)0;
a = x.a;
if (nimSubInt((s ? s->Sup.len : 0), x.b, &TM__cYXlk6iIaZ0nvpH4aISAaQ_5)) { raiseOverflow(); };
if (nimSubInt((NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_5), a, &TM__cYXlk6iIaZ0nvpH4aISAaQ_6)) { raiseOverflow(); };
if (nimAddInt((NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_6), ((NI) 1), &TM__cYXlk6iIaZ0nvpH4aISAaQ_7)) { raiseOverflow(); };
L = (NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_7);
if ((L) < ((NI) 0) || (L) > ((NI) IL64(9223372036854775807))){ raiseRangeErrorI(L, ((NI) 0), ((NI) IL64(9223372036854775807))); }
result = mnewString(((NI) (L)));
{
NI i;
NI i_2;
i = (NI)0;
i_2 = ((NI) 0);
{
while (1) {
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_8;
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_9;
if (!(i_2 < L)) goto LA3;
i = i_2;
if ((NU)(i) >= (NU)(result ? result->Sup.len : 0)){ raiseIndexError2(i,(result ? result->Sup.len : 0)-1); }
if (nimAddInt(i, a, &TM__cYXlk6iIaZ0nvpH4aISAaQ_8)) { raiseOverflow(); };
if ((NU)((NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_8)) >= (NU)(s ? s->Sup.len : 0)){ raiseIndexError2((NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_8),(s ? s->Sup.len : 0)-1); }
result->data[i] = s->data[(NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_8)];
if (nimAddInt(i_2, ((NI) 1), &TM__cYXlk6iIaZ0nvpH4aISAaQ_9)) { raiseOverflow(); };
i_2 = (NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_9);
} LA3: ;
}
}
return result;
}
static N_INLINE(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA, dotdot___xNR8BVBMWzS9bXXNMikmyLgsystem)(NI a, NI b) {
tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA result;
nimZeroMem((void*)(&result), sizeof(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA));
nimZeroMem((void*)(&result), sizeof(tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA));
result.a = a;
result.b = b;
return result;
}
N_LIB_PRIVATE N_NIMCALL(NimStringDesc*, normalize__4HitcvaswvtyHH5XGydCBw)(NimStringDesc* str, tyEnum_StrNormalizationKind__fwCBRnNT8uJ7604Pow8DgA kind) {
NimStringDesc* result;
result = (NimStringDesc*)0;
switch (kind) {
case ((tyEnum_StrNormalizationKind__fwCBRnNT8uJ7604Pow8DgA) 0):
{
result = copyString(str);
}
break;
case ((tyEnum_StrNormalizationKind__fwCBRnNT8uJ7604Pow8DgA) 1):
case ((tyEnum_StrNormalizationKind__fwCBRnNT8uJ7604Pow8DgA) 2):
{
NI start;
start = ((NI) 0);
{
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_4;
if (!(kind == ((tyEnum_StrNormalizationKind__fwCBRnNT8uJ7604Pow8DgA) 1))) goto LA5_;
if ((NU)(((NI) 0)) >= (NU)(str ? str->Sup.len : 0)){ raiseIndexError2(((NI) 0),(str ? str->Sup.len : 0)-1); }
result = addChar(result, str->data[((NI) 0)]);
if (nimAddInt(start, ((NI) 1), &TM__cYXlk6iIaZ0nvpH4aISAaQ_4)) { raiseOverflow(); };
start = (NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_4);
}
LA5_: ;
{
NIM_CHAR ch;
NimStringDesc* colontmp_;
tyObject_HSlice__EE5dzjqoOrHT6HJhIPXAvA T8_;
NI i;
NI L;
ch = (NIM_CHAR)0;
colontmp_ = (NimStringDesc*)0;
T8_ = dotdot___xNR8BVBMWzS9bXXNMikmyLgsystem(start, ((NI) 1));
colontmp_ = X5BX5D___ogYTOKbgqbjPfyC123US1gsystem(str, T8_);
i = ((NI) 0);
L = (colontmp_ ? colontmp_->Sup.len : 0);
{
while (1) {
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_10;
if (!(i < L)) goto LA10;
if ((NU)(i) >= (NU)(colontmp_ ? colontmp_->Sup.len : 0)){ raiseIndexError2(i,(colontmp_ ? colontmp_->Sup.len : 0)-1); }
ch = colontmp_->data[i];
switch (((NU8)(ch))) {
case 95:
case 45:
{
}
break;
case 97 ... 122:
{
result = addChar(result, ch);
}
break;
case 65 ... 90:
{
result = addChar(result, ((NIM_CHAR) ((NU8)((NU8)(((NU8) (((NU8)(ch))))) - (NU8)(((NU8) 32))))));
}
break;
default:
{
result = addChar(result, ch);
}
break;
}
if (nimAddInt(i, ((NI) 1), &TM__cYXlk6iIaZ0nvpH4aISAaQ_10)) { raiseOverflow(); };
i = (NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_10);
{
if (!!(((colontmp_ ? colontmp_->Sup.len : 0) == L))) goto LA17_;
failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A(((NimStringDesc*) &TM__cYXlk6iIaZ0nvpH4aISAaQ_11));
}
LA17_: ;
} LA10: ;
}
}
}
break;
case ((tyEnum_StrNormalizationKind__fwCBRnNT8uJ7604Pow8DgA) 3):
{
{
NIM_CHAR ch_2;
NI i_2;
NI L_2;
ch_2 = (NIM_CHAR)0;
i_2 = ((NI) 0);
L_2 = (str ? str->Sup.len : 0);
{
while (1) {
NI TM__cYXlk6iIaZ0nvpH4aISAaQ_12;
if (!(i_2 < L_2)) goto LA22;
if ((NU)(i_2) >= (NU)(str ? str->Sup.len : 0)){ raiseIndexError2(i_2,(str ? str->Sup.len : 0)-1); }
ch_2 = str->data[i_2];
switch (((NU8)(ch_2))) {
case 65 ... 90:
{
result = addChar(result, ((NIM_CHAR) ((NU8)((NU8)(((NU8) (((NU8)(ch_2))))) - (NU8)(((NU8) 32))))));
}
break;
default:
{
result = addChar(result, ch_2);
}
break;
}
if (nimAddInt(i_2, ((NI) 1), &TM__cYXlk6iIaZ0nvpH4aISAaQ_12)) { raiseOverflow(); };
i_2 = (NI)(TM__cYXlk6iIaZ0nvpH4aISAaQ_12);
{
if (!!(((str ? str->Sup.len : 0) == L_2))) goto LA27_;
failedAssertImpl__W9cjVocn1tjhW7p7xohJj6A(((NimStringDesc*) &TM__cYXlk6iIaZ0nvpH4aISAaQ_11));
}
LA27_: ;
} LA22: ;
}
}
}
break;
}
return result;
}
N_LIB_PRIVATE N_NIMCALL(void, hmisc_halgorithmDatInit000)(void) {
/* section: NIM_merge_TYPE_INIT1 */
static TNimNode* TM__cYXlk6iIaZ0nvpH4aISAaQ_2_2[2];
static TNimNode TM__cYXlk6iIaZ0nvpH4aISAaQ_0[3];
/* section: NIM_merge_TYPE_INIT3 */
NTI__QeWl6B6ffS4pU6WWrtcrDw_.size = sizeof(tyTuple__QeWl6B6ffS4pU6WWrtcrDw);
NTI__QeWl6B6ffS4pU6WWrtcrDw_.align = NIM_ALIGNOF(tyTuple__QeWl6B6ffS4pU6WWrtcrDw);
NTI__QeWl6B6ffS4pU6WWrtcrDw_.kind = 18;
NTI__QeWl6B6ffS4pU6WWrtcrDw_.base = 0;
TM__cYXlk6iIaZ0nvpH4aISAaQ_2_2[0] = &TM__cYXlk6iIaZ0nvpH4aISAaQ_0[1];
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[1].kind = 1;
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[1].offset = offsetof(tyTuple__QeWl6B6ffS4pU6WWrtcrDw, Field0);
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[1].typ = (&NTI__rR5Bzr1D5krxoo1NcNyeMA_);
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[1].name = "Field0";
TM__cYXlk6iIaZ0nvpH4aISAaQ_2_2[1] = &TM__cYXlk6iIaZ0nvpH4aISAaQ_0[2];
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[2].kind = 1;
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[2].offset = offsetof(tyTuple__QeWl6B6ffS4pU6WWrtcrDw, Field1);
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[2].typ = (&NTI__77mFvmsOLKik79ci2hXkHEg_);
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[2].name = "Field1";
TM__cYXlk6iIaZ0nvpH4aISAaQ_0[0].len = 2; TM__cYXlk6iIaZ0nvpH4aISAaQ_0[0].kind = 2; TM__cYXlk6iIaZ0nvpH4aISAaQ_0[0].sons = &TM__cYXlk6iIaZ0nvpH4aISAaQ_2_2[0];
NTI__QeWl6B6ffS4pU6WWrtcrDw_.node = &TM__cYXlk6iIaZ0nvpH4aISAaQ_0[0];
NTI__4eRCaZmrYLLw2k30GPTiMw_.size = sizeof(tySequence__4eRCaZmrYLLw2k30GPTiMw*);
NTI__4eRCaZmrYLLw2k30GPTiMw_.align = NIM_ALIGNOF(tySequence__4eRCaZmrYLLw2k30GPTiMw*);
NTI__4eRCaZmrYLLw2k30GPTiMw_.kind = 24;
NTI__4eRCaZmrYLLw2k30GPTiMw_.base = (&NTI__QeWl6B6ffS4pU6WWrtcrDw_);
NTI__4eRCaZmrYLLw2k30GPTiMw_.marker = Marker_tySequence__4eRCaZmrYLLw2k30GPTiMw;
}
|
zealoussnow/chromium
|
chrome/test/data/extensions/api_test/tts_engine/call_update_voices/test.js
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function setup() {
var speakListener = function(utterance, options, sendTtsEvent) {};
var stopListener = function() {};
chrome.ttsEngine.onSpeak.addListener(speakListener);
chrome.ttsEngine.onStop.addListener(stopListener);
}
chrome.test.runTests([
function testSetUpDynamicVoices() {
var testVoiceData = [
{
eventTypes: ['start'],
lang: 'zh-TW',
remote: false,
voiceName: 'Dynamic Voice 1'
},
{
eventTypes: ['end', 'interrupted', 'cancelled'],
lang: 'en-GB',
remote: false,
voiceName: 'Dynamic Voice 2'
}
];
setup();
chrome.ttsEngine.updateVoices(testVoiceData);
chrome.test.succeed();
}
]);
|
nekoniaow/OSDK
|
xa/sources/xat.cpp
|
#include <ctype.h>
#include <stdio.h>
#include "xah.h"
#include "xah2.h"
#include "xar.h"
#include "xa.h"
#include "xaa.h"
#include "xal.h"
#include "xat.h"
#include "xao.h"
#include "xap.h"
int gDsbLen = 0;
static ErrorCode t_conv(signed char*,signed char*,int*,int,int*,int*,int*,int);
static ErrorCode t_keyword(signed char *ptr_src, int *keyword_lenght, int *keyword_index);
static ErrorCode ParseQuotedString(signed char*,signed char*,int*,int*,int*,int*);
static void ParseDecimalValue(signed char*,int*,int*);
static void ParseHexadecimalValue(signed char*,int*,int*);
static void ParseOctalValue(signed char*,int*,int*);
static void ParseBinaryValue(signed char*,int*,int*);
#ifdef C64_ASCII
static signed char Asc2Scr(signed char c);
static signed char Asc2Pet(signed char c);
#endif
static int curr,dft=0;
static char *kt[] =
{
"adc","and","asl","bbr","bbs","bcc","bcs","beq",
"bit","bmi",
"bne","bpl","bra","brk","bvc","bvs",
/* new */
"brl",
"clc","cld","cli","clv","cmp","cpx","cpy",
/* new */
"cop",
"dec","dex","dey","eor",
"inc","inx","iny","jmp","jsr","lda","ldx","ldy",
"lsr",
/* new */
"mvp","mvn",
"nop","ora","pha","php","phx","phy","pla",
"plp","plx","ply",
/* new */
"phb","phd","phk","plb","pld",
"pea","pei","per",
"rmb","rol",
"ror","rti","rts",
/* new */
"rep","rtl",
"sbc","sec","sed","sei","smb","sta",
"stx","sty","stz",
/* new */
"sep","stp",
"tax","tay","trb","tsb","tsx","txa","txs","tya",
/* new */
"txy","tyx","tcd","tdc","tcs","tsc",
"wai","wdb",
"xba","xce",
".byt",".word",".asc",".dsb",
".(",".)","*=", ".text", ".data", ".bss", ".zero",
".fopt", ".byte", ".end", ".list", ".xlist",
".dupb", ".blkb", ".db", ".dw", ".align",
".block", ".bend",
".long", ".al",".as",".xl",".xs",".scr",".psc",".dft"
};
#define Lastbef 93
#define Anzkey 125
#define Kbyt Lastbef+1
#define Kword Lastbef+2
#define Kasc Lastbef+3
#define Kdsb Lastbef+4
#define Kopen Lastbef+5 /* .( */
#define Kclose Lastbef+6 /* .) */
#define Kpcdef Lastbef+7 /* *=value */
#define Ktext Lastbef+8
#define Kdata Lastbef+9
#define Kbss Lastbef+10
#define Kzero Lastbef+11
#define Kfopt Lastbef+12
#define Kbyte Lastbef+13 /* gets remapped to Kbyt */
#define Kend Lastbef+14 /* ignored (MASM compat.) */
#define Klist Lastbef+15 /* ignored (MASM compat.) */
#define Kxlist Lastbef+16 /* ignored (MASM compat.) */
#define Kdupb Lastbef+17 /* gets remapped to Kdsb */
#define Kblkb Lastbef+18 /* gets remapped to Kdsb */
#define Kdb Lastbef+19 /* gets remapped to Kbyt */
#define Kdw Lastbef+20 /* gets remapped to Kword */
#define Kalign Lastbef+21
#define Kblock Lastbef+22 /* gets remapped to .( */
#define Kbend Lastbef+23 /* gets remapped to .) */
#define Klong Lastbef+24
#define Kalong Lastbef+25
#define Kashort Lastbef+26
#define Kxlong Lastbef+27
#define Kxshort Lastbef+28
#define Kscr Lastbef+29
#define Kpsc Lastbef+30
#define Kdft Lastbef+31
#define Kreloc Anzkey /* *= (relocation mode) */
#define Ksegment Anzkey+1
static int ktp[]=
{
0,3,17,25,28,29,29,29,29,32,34,34,38,40,41,42,58,
58,65,76,90,90,90,92,94,94,94,Anzkey
};
#define Admodes 24
// Values starting by '*' are stored on 16 bits
enum AdressingModes_e
{
e_AdressingMode_Accumulator, // 0 - ASL A
e_AdressingMode_DirectPage, // 1 - ADC dp
e_AdressingMode_DirectPage_Indexed_X, // 2 - ADC dp,X
e_AdressingMode_DirectPage_Indexed_Y, // 3 - LDX dp,Y
e_AdressingMode_DirectPage_Indirect, //*4 - ADC (dp)
e_AdressingMode_DirectPage_Indexed_Indirect_X, // 5 - ADC (dp,X)
e_AdressingMode_DirectPage_Indirect_Indexed_Y, // 7 - ADC (dp),Y
e_AdressingMode_Immediate, //*7 - ADC #const
e_AdressingMode_Absolute, // 8 - ADC addr
e_AdressingMode_Absolute_Indexed_X, // 9 - ADC addr,X
e_AdressingMode_Absolute_Indexed_Y, // 10 - ADC addr,Y
e_AdressingMode_Program_Counter_Relative, // 11 - BCC nearlabel
e_AdressingMode_Absolute_Indirect, // 12 - JMP (addr)
e_AdressingMode_Absolute_Indexed_Indirect, //*13 - JMP (addr,X)
e_AdressingMode_14, // 14
e_AdressingMode_15, // 15
e_AdressingMode_Program_Counter_Relative_Long, //*16 - BRL label
e_AdressingMode_Absolute_Long, //*17 - ADC long
e_AdressingMode_Absolute_Long_Indexed_X, //*18 - ADC long,X
e_AdressingMode_StackRelative, //*19 - ADC sr,S
e_AdressingMode_StackRelative_Indirect_Indexed_Y, //*20 - ADC (sr,S),Y
e_AdressingMode_DirectPage_Indirect_Long, //*21 - ADC [dp]
e_AdressingMode_DirectPage_Indirect_Long_Indexed_Y, //*22 - ADC [dp],Y
e_AdressingMode_Absolute_Indirect_Long, //*23 - JMP [addr]
_e_AdressingMode_Last_
};
static int ct[Lastbef+1][Admodes] =
{
/* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 imm */
{ -1, 0x65,0x75,-1,0x172,0x61,0x71,0x469,0x6d,0x7d,0x79,-1, -1, -1, -1, -1, -1,0x26f,0x27f,0x263,0x273,0x267,0x277,-1 }, /*adc*/
{ -1, 0x25,0x35,-1,0x132,0x21,0x31,0x429,0x2d,0x3d,0x39,-1, -1, -1, -1, -1, -1,0x22f,0x23f,0x223,0x233,0x227,0x237,-1 }, /*and*/
{ 0x0a,0x06,0x16,-1, -1, -1, -1, -1, 0x0e,0x1e,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*asl*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x10f,-1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bbr*/ // 65c02 instruction ?
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x18f,-1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bbs*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x90,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bcc*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0xb0,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bcs*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0xf0,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*beq*/
{ -1, 0x24,0x134,-1, -1, -1, -1, 0x589,0x2c,0x13c,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bit*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x30,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bmi*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0xd0,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bne*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x10,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bpl*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x180,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bra*/
{ 0x00,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*brk*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x50,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bvc*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x70,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*bvs*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,0x282, -1, -1, -1, -1, -1, -1, -1 }, /*brl*/
{ 0x18,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*clc*/
{ 0xd8,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*cld*/
{ 0x58,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*cli*/
{ 0xb8,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*clv*/
{ -1, 0xc5,0xd5,-1, 0x1d2,0xc1,0xd1,0x4c9,0xcd,0xdd,0xd9,-1, -1, -1, -1, -1,-1,0x2cf,0x2df,0x2c3,0x2d3,0x2c7,0x2d7,-1 }, /*cmp*/
{ -1, 0xe4,-1, -1, -1, -1, -1, 0x8e0,0xec,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*cpx*/
{ -1, 0xc4,-1, -1, -1, -1, -1, 0x8c0,0xcc,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*cpy*/
{ -1, -1, -1, -1, -1, -1, -1, 0x202,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*cop*/
{ 0x13a,0xc6,0xd6,-1, -1, -1, -1, -1, 0xce,0xde,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*dec*/
{ 0xca,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*dex*/
{ 0x88,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*dey*/
{ -1, 0x45,0x55,-1, 0x152,0x41,0x51,0x449,0x4d,0x5d,0x59,-1, -1, -1, -1, -1,-1,0x24f,0x25f,0x243,0x253,0x247,0x257,-1 }, /*eor*/
{ 0x11a,0xe6,0xf6,-1, -1, -1, -1, -1, 0xee,0xfe,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*inc*/
{ 0xe8,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*inx*/
{ 0xc8,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*iny*/
{ -1, -1, -1, -1, -1, -1, -1, -1, 0x4c,-1, -1, -1, 0x6c,0x17c,-1, -1, -1,0x25c, -1, -1, -1, -1, -1,0x2dc}, /*jmp*/
{ -1, -1, -1, -1, -1, -1, -1, -1, 0x20,-1, -1, -1, -1, 0x2fc,-1, -1, -1,0x222, -1, -1, -1, -1, -1, -1 }, /*jsr*/
{ -1, 0xa5,0xb5,-1, 0x1b2,0xa1,0xb1,0x4a9,0xad,0xbd,0xb9,-1, -1, -1, -1, -1,-1,0x2af,0x2bf,0x2a3,0x2b3,0x2a7,0x2b7,-1 }, /*lda*/
{ -1, 0xa6,-1, 0xb6,-1, -1, -1, 0x8a2,0xae,-1, 0xbe,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*ldx*/
{ -1, 0xa4,0xb4,-1, -1, -1, -1, 0x8a0,0xac,0xbc,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*ldy*/
{ 0x4a,0x46,0x56,-1, -1, -1, -1, -1, 0x4e,0x5e,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*lsr*/
{ -1, -1, -1, -1, -1, -1, -1, -1, 0x244,-1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*mvp*/
{ -1, -1, -1, -1, -1, -1, -1, -1, 0x254,-1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*mvn*/
{ 0xea,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*nop*/
{ -1, 0x05,0x15,-1, 0x112,0x01,0x11,0x409,0x0d,0x1d,0x19,-1, -1, -1, -1, -1,-1,0x20f,0x21f,0x203,0x213,0x207,0x217,-1 }, /*ora*/
{ 0x48,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*pha*/
{ 0x08,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*php*/
{ 0x1da,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*phx*/
{ 0x15a,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*phy*/
{ 0x68,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*pla*/
{ 0x28,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*plp*/
{ 0x1fa,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*plx*/
{ 0x17a,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*ply*/
{ 0x28b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*phb*/
{ 0x20b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*phd*/
{ 0x24b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*phk*/
{ 0x2ab,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*plb*/
{ 0x22b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*pld*/
{ -1, -1, -1, -1, -1, -1, -1, -1, 0x2f4,-1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*pea*/
{ -1, -1, -1, -1,0x2d4, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*pei*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, 0x262,-1, -1, -1, -1, -1, -1, -1 }, /*per*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,0x107, -1, -1, -1, -1, -1, -1, -1, -1 }, /*rmb*/
{ 0x2a,0x26,0x36,-1, -1, -1, -1, -1, 0x2e,0x3e,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*rol*/
{ 0x6a,0x66,0x76,-1, -1, -1, -1, -1, 0x6e,0x7e,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*ror*/
{ 0x40,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*rti*/
{ 0x60,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*rts*/
{ -1, -1, -1, -1, -1, -1, -1, 0x2c2,-1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*rep*/
{ 0x26b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*rtl*/
{ -1, 0xe5,0xf5,-1, 0x1f2,0xe1,0xf1,0x4e9,0xed,0xfd,0xf9,-1, -1, -1, -1, -1,-1,0x2ef,0x2ff,0x2e3,0x2f3,0x2e7,0x2f7,-1 }, /*sbc*/
{ 0x38,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*sec*/
{ 0xf8,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*sed*/
{ 0x78,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*sei*/
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,0x187, -1, -1, -1, -1, -1, -1, -1, -1 }, /*smb*/
{ -1, 0x85,0x95,-1, 0x192,0x81,0x91,-1, 0x8d,0x9d,0x99,-1, -1, -1, -1, -1,-1,0x28f,0x29f,0x283,0x293,0x287,0x297,-1 }, /*sta*/
{ -1, 0x86,-1, 0x96,-1, -1, -1, -1, 0x8e,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*stx*/
{ -1, 0x84,0x94,-1, -1, -1, -1, -1, 0x8c,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*sty*/
{ -1, 0x164,0x174,-1, -1, -1, -1, -1, 0x19c,0x19e,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*stz*/
{ -1, -1, -1, -1, -1, -1, -1, 0x2e2,-1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*sep*/
{ 0x2db,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*stp*/
{ 0xaa,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tax*/
{ 0xa8,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tay*/
{ -1, 0x114,-1, -1, -1, -1, -1, -1, 0x11c,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*trb*/
{ -1, 0x104,-1, -1, -1, -1, -1, -1, 0x10c,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tsb*/
{ 0xba,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tsx*/
{ 0x8a,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*txa*/
{ 0x9a,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*txs*/
{ 0x98,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tya*/
{ 0x29b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*txy*/
{ 0x2bb,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tyx*/
{ 0x25b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tcd*/
{ 0x27b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tdc*/
{ 0x21b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tcs*/
{ 0x23b,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*tsc*/
{ 0x2cb,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*wai*/
{ 0x242,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*wdb*/
{ 0x2eb,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, /*xba*/
{ 0x2fb,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } /*xce*/
} ;
#define Syntax 14
#define Maxbyt 4
static int at[Syntax][Maxbyt] =
{
{ 0, -1, -1 ,-1 },
{ -1, 7, -1 ,-1 },
{ -1, 15, -1 ,-1 },
{ -1, -1, 14 ,-1 },
{ -1, 1, 8 ,17 },
{ -1, 2, 9 ,18 },
{ -1, 3, 10 ,-1 },
{ -1, 4, 12 ,-1 },
{ -1, 5, 13 ,-1 },
{ -1, 6, -1 ,-1 },
{ -1, 21, 23 ,-1 },
{ -1, 22, -1 ,-1 },
{ -1, 19, -1 ,-1 },
{ -1, 20, -1 ,-1 }
};
#define NB_ALTERNATIVE_ADRESSING_MODES 5
static int TableAlternativeAdressingModes[NB_ALTERNATIVE_ADRESSING_MODES][2] =
{
{ 8, 11 }, // abs -> rel
{ 2, 3 }, // z,x -> z,y
{ 5, 6 }, // ,x) -> ),y
{ 9, 10 }, // a,x -> a,y
{ 8, 16 } // abs -> relong
};
static int le[]=
{
1,2,2,2,2,2,2,2,3,3,3,2,3,3,3,2,
/* new modes */
3,4,4,2,2,2,2,3
};
static int opt[] =
{
-1,-1,-1,-1,-1,-1,-1,-1,1,2,3,-1,4,5,-1,-1,
/*new*/ -1,8,9,-1,-1,-1,-1,-1
}; /* abs -> zp */
#define cval(s) (256*((s)[1]&255)+((s)[0]&255))
int is_end_of_line(const char *ptr)
{
if (ptr[0]==0) return 1; // NULL terminator
if (ptr[0]==';') return 1; // ASSEMBLER comment
if ((ptr[0]=='/') && (ptr[1]=='/')) return 1; // C++ comment
return 0;
}
/* pass 1 */
ErrorCode t_p1(signed char *ptr_text,signed char *ptr_output,int *ll,int *ptr_size_written)
{
static int written_bytes,n,v,nk,number_quoted_strings,size_quoted_strings,bl,am,sy,i,label; /*,j,v2 ;*/
int afl = 0;
bl=0;
*ptr_size_written = 0;
ErrorCode er=t_conv(ptr_text,ptr_output,&written_bytes,TablePcSegment[gCurrentSegment],&nk,&number_quoted_strings,&size_quoted_strings,0);
*ll=written_bytes;
// if text/data produced, then no more fopt allowed in romable mode
if ((romable>1) && (ptr_output[0]<Kopen || ptr_output[0]==Kbyte || ptr_output[0]==Kpcdef))
{
afile->SetSegmentBase(eSEGMENT_TEXT,romadr + afile->h_length());
romable=1;
}
if (!er)
{
n=ptr_output[0];
// TODO: make that a big switch statement...
if (n==Kdft)
{
i=1;
evaluate_expression(ptr_output+1,&dft,&written_bytes,TablePcSegment[gCurrentSegment],&afl,&label,0);
ptr_output[i++]=T_VALUE;
ptr_output[i++]=((dft)>>0)&255;
ptr_output[i++]=((dft)>>8)&255;
ptr_output[i++]=((dft)>>16)&255;
ptr_output[i++]=((dft)>>24)&255;
ptr_output[0]=Kdft;
ptr_output[i++]=T_END;
*ll = 7;
er=E_OKDEF;
}
else
if (n==Kend || n==Klist || n==Kxlist)
{
*ll = 0; /* ignore */
}
else
if (n==Kfopt)
{
if (romable==1) er=E_ROMOPT;
ptr_output[0] = Kbyt;
afile->set_fopt(written_bytes,ptr_output,nk+1-number_quoted_strings+size_quoted_strings);
*ll = 0;
}
else
if (n==Kpcdef)
{
int tmp;
if (!(er=evaluate_expression(ptr_output+1,&tmp,&written_bytes,TablePcSegment[gCurrentSegment],&afl,&label,0)))
{
i=1;
ptr_output[i++]=T_VALUE;
ptr_output[i++]=((tmp)>>0)&255;
ptr_output[i++]=((tmp)>>8)&255;
ptr_output[i++]=((tmp)>>16)&255;
ptr_output[i++]=((tmp)>>24)&255;
ptr_output[i++]=T_END;
*ll=7;
er=E_OKDEF;
if (gCurrentSegment==eSEGMENT_TEXT)
{
TablePcSegment[eSEGMENT_ABS] = tmp;
r_mode(RMODE_ABS);
}
else
{
if (!relmode)
{
TablePcSegment[gCurrentSegment] = tmp;
}
else
{
er = E_ILLSEGMENT;
}
}
}
else
{
/* TODO: different error code */
if ((gCurrentSegment==eSEGMENT_ABS) && (er==E_SYNTAX && written_bytes==0))
{
ptr_output[0]=Kreloc;
i=1;
ptr_output[i++]=T_VALUE;
ptr_output[i++]=((TablePcSegment[eSEGMENT_TEXT])>>0)&255;
ptr_output[i++]=((TablePcSegment[eSEGMENT_TEXT])>>8)&255;
ptr_output[i++]=((TablePcSegment[eSEGMENT_TEXT])>>16)&255;
ptr_output[i++]=((TablePcSegment[eSEGMENT_TEXT])>>24)&255;
ptr_output[i++]=T_END;
*ll=7;
er=E_OKDEF;
r_mode(RMODE_RELOC);
}
}
}
else
if (n==Kopen)
{
if (gFlag_ShowBlocks)
{
fprintf(stderr,"%s line %d: .(\n", PreprocessorFile_c::GetCurrentFile()->GetCurrentFileName().c_str(),PreprocessorFile_c::GetCurrentFile()->GetCurrentLine());
}
b_open();
er=E_NOLINE;
}
else
if (n==Kclose)
{
if (gFlag_ShowBlocks)
{
fprintf(stderr,"%s line %d: .)\n", PreprocessorFile_c::GetCurrentFile()->GetCurrentFileName().c_str(),PreprocessorFile_c::GetCurrentFile()->GetCurrentLine());
}
er=b_close();
if (!er) er=E_NOLINE;
}
else
if (n==Kalong)
{
memode=1;
ptr_output[0]=Kalong;
*ll=1;
er=E_OKDEF;
}
else
if (n==Kashort)
{
memode=0;
ptr_output[0]=Kashort;
*ll=1;
er=E_OKDEF;
}
else
if (n==Kxlong)
{
xmode=1;
ptr_output[0]=Kxlong;
*ll=1;
er=E_OKDEF;
}
else
if (n==Kxshort)
{
xmode=0;
ptr_output[0]=Kxshort;
*ll=1;
er=E_OKDEF;
}
else
if (n==Kdsb)
{
gDsbLen = 1;
if (!(er=evaluate_expression(ptr_output+1,&bl,&written_bytes,TablePcSegment[gCurrentSegment],&afl,&label,0)))
{
er=E_OKDEF;
}
gDsbLen = 0;
}
else
if (n==Ktext)
{
gCurrentSegment = relmode ? eSEGMENT_TEXT : eSEGMENT_ABS;
ptr_output[0]=Ksegment;
ptr_output[1]=gCurrentSegment;
*ll=2;
er=E_OKDEF;
}
else
if (n==Kdata)
{
gCurrentSegment = eSEGMENT_DATA;
ptr_output[0]=Ksegment;
ptr_output[1]=eSEGMENT_DATA;
*ll=2;
er=E_OKDEF;
}
else
if (n==Kbss)
{
gCurrentSegment = eSEGMENT_BSS;
ptr_output[0]=Ksegment;
ptr_output[1]=eSEGMENT_BSS;
*ll=2;
er=E_OKDEF;
}
else
if (n==Kzero)
{
gCurrentSegment = eSEGMENT_ZERO;
ptr_output[0]=Ksegment;
ptr_output[1]=eSEGMENT_ZERO;
*ll=2;
er=E_OKDEF;
}
else
if (n==Kalign)
{
int tmp;
if (gCurrentSegment!=eSEGMENT_ABS)
{
if (!(er=evaluate_expression(ptr_output+1,&tmp,&written_bytes,TablePcSegment[gCurrentSegment],&afl,&label,0)))
{
if (tmp == 1 || tmp == 2 || tmp == 4 || tmp == 256)
{
set_align(tmp);
if (TablePcSegment[gCurrentSegment] & (tmp-1))
{
/* not aligned */
int tmp2;
ptr_output[0]=Kdsb;
i=1;
bl=tmp=(tmp - (TablePcSegment[gCurrentSegment] & (tmp-1))) & (tmp-1);
ptr_output[i++]=T_VALUE;
ptr_output[i++]=((tmp)>>0)&255;
ptr_output[i++]=((tmp)>>8)&255;
ptr_output[i++]=((tmp)>>16)&255;
ptr_output[i++]=((tmp)>>24)&255;
ptr_output[i++]=',';
tmp2= 0xea; // nop opcode
ptr_output[i++]=T_VALUE;
ptr_output[i++]=((tmp2)>>0)&255;
ptr_output[i++]=((tmp2)>>8)&255;
ptr_output[i++]=((tmp2)>>16)&255;
ptr_output[i++]=((tmp2)>>24)&255;
ptr_output[i++]=T_END;
*ll=11;
er=E_OKDEF;
}
else
{
*ll=0; /* ignore if aligned right */
}
}
else
{
er=E_ILLALIGN;
}
}
}
else
{
er=E_ILLSEGMENT;
}
}
else
{
er=t_p2(ptr_output,ll,1, ptr_size_written);
}
}
else
if (er==ERR_UNDEFINED_LABEL)
{
er=E_OK;
n=ptr_output[0];
if (n>=0 && n<=Lastbef)
{
if (ptr_output[1]==T_END)
{
sy=0;
}
else
if (ptr_output[1]=='#')
{
sy=1+nk;
}
else
if (ptr_output[1]=='(')
{
sy=7+nk;
}
else
{
sy=4+nk;
}
bl=Maxbyt+1;
while (--bl)
{
if ((am=at[sy][bl-1])>=0)
{
if (am>Admodes-1)
{
// Did not found out a valid addressing mode
er=E_SYNTAX;
break;
}
if (ct[n][am]>=0)
break;
for(v=0;v<NB_ALTERNATIVE_ADRESSING_MODES;v++)
{
if (TableAlternativeAdressingModes[v][0]==am && ct[n][TableAlternativeAdressingModes[v][1]]>=0)
{
break;
}
}
if (v<NB_ALTERNATIVE_ADRESSING_MODES)
{
am=TableAlternativeAdressingModes[v][1];
break;
}
}
}
if (ptr_output[written_bytes-1]!='@')
{
if (bl && !er && opt[am]>=0 && am>16)
{
if (ct[n][opt[am]]>=0)
{
am=opt[am];
}
}
}
if (!bl)
{
er=E_SYNTAX;
}
else
{
bl=le[am];
if ( ((ct[n][am]&0x400) && memode) || ((ct[n][am]&0x800) && xmode))
{
bl++;
}
}
}
else
if (n==Kbyt || n==Kasc || n==Kpsc || n==Kscr)
{
bl=nk+1-number_quoted_strings+size_quoted_strings;
}
else
if (n==Kword)
{
bl=2*nk+2;
}
else
if (n==Klong)
{
bl=2*nk+4;
}
else
if (n==Kdsb)
{
er=evaluate_expression(ptr_output+1,&bl,&written_bytes,TablePcSegment[gCurrentSegment],&afl,&label,0);
}
else
if (n==Kfopt)
{
afile->set_fopt(written_bytes-1,ptr_output+1, nk+1-number_quoted_strings+size_quoted_strings);
*ll = 0;
}
else
if (n==T_OP)
{
er=E_OKDEF;
}
else
{
er=ERR_UNDEFINED_LABEL;
}
if (!er)
{
er=E_OKDEF;
}
}
if (er==E_NOLINE)
{
// This line happens to contain nothing, either no text, or possibly just a commented out line.
// Anyway, it's no an error cause.
er=E_OK;
*ll=0;
}
*ptr_size_written += bl;
TablePcSegment[gCurrentSegment]+=bl;
if (gCurrentSegment==eSEGMENT_TEXT) TablePcSegment[eSEGMENT_ABS]+=bl;
if (gCurrentSegment==eSEGMENT_ABS) TablePcSegment[eSEGMENT_TEXT]+=bl;
return er;
}
ErrorCode t_p2(signed char *t,int *ll,int fl,int *al)
{
static int afl,nafl,i,j,k,v,n,l,bl,sy,am,c,vv[3],v2,label;
static int rlt[3]; /* relocation table */
static int lab[3]; /* undef. label table */
ErrorCode er=E_OK;
bl=0;
if (*ll<0) /* <0 bei E_OK, >0 bei E_OKDEF */
{
*ll=-*ll;
bl=*ll;
er=E_OK;
}
else
{
n=t[0];
if (n==T_OP)
{
n=cval(t+1);
er=evaluate_expression(t+4,&v,&l,TablePcSegment[gCurrentSegment],&nafl,&label,0);
if (!er)
{
if (t[3]=='=')
{
v2=v;
}
else
{
SymbolEntry& symbol_entry=afile->m_cSymbolData.GetSymbolEntry(n);
if ( (!(er=symbol_entry.Get(&v2,&afl))) && ((afl & A_FMASK)!=(eSEGMENT_UNDEF<<8)) )
{
if (t[3]=='+')
{
if (afl && nafl)
{
errout(E_WPOINTER);
nafl=0;
}
nafl = afl;
v2+=v;
}
else
if (t[3]=='-')
{
if ( (((nafl & A_FMASK)>>8) != afl) || ((nafl & A_MASK)==A_HIGH) )
{
errout(E_WPOINTER);
nafl=0;
}
else
{
nafl = afl;
}
v2-=v;
}
else
if (t[3]=='*')
{
if (afl || nafl)
{
errout(E_WPOINTER);
nafl=0;
}
v2*=v;
}
else
if (t[3]=='/')
{
if (afl || nafl)
{
errout(E_WPOINTER);
nafl=0;
}
if (v)
v2/=v;
else
er=E_DIV;
}
else
if (t[3]=='|')
{
if (afl || nafl)
{
errout(E_WPOINTER);
nafl=0;
}
v2=v|v2;
}
else
if (t[3]=='&')
{
if (afl || nafl)
{
errout(E_WPOINTER);
nafl=0;
}
v2=v2&v;
}
}
}
SymbolEntry& symbol_entry=afile->m_cSymbolData.GetSymbolEntry(n);
symbol_entry.Set(v2,(SEGMENT_e)(nafl>>8));
*ll=0;
if (!er)
{
er=E_NOLINE;
}
}
}
else
if (n==Kword)
{
i=1;
j=0;
while (!er && t[i]!=T_END)
{
if (!(er=evaluate_expression(t+i,&v,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
if (afl) afile->u_set(TablePcSegment[gCurrentSegment]+j, afl, label, 2);
t[j++]=v&255;
t[j++]=(v>>8)&255;
i+=l;
if (t[i]!=T_END && t[i]!=',')
er=E_SYNTAX;
else
if (t[i]==',')
i++;
}
}
*ll=j;
bl=j;
}
else
if (n==Klong)
{
i=1;
j=0;
while (!er && t[i]!=T_END)
{
if (!(er=evaluate_expression(t+i,&v,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
if (afl) afile->u_set(TablePcSegment[gCurrentSegment]+j, afl, label, 2);
t[j++]=v&255;
t[j++]=(v>>8)&255;
t[j++]=(v>>16)&255;
t[j++]=(v>>24)&255;
i+=l;
if (t[i]!=T_END && t[i]!=',')
er=E_SYNTAX;
else
if (t[i]==',')
i++;
}
}
*ll=j;
bl=j;
}
else
if (n==Kasc || n==Kbyt || n==Kpsc || n==Kscr)
{
i=1;
j=0;
while (!er && t[i]!=T_END)
{
if (t[i]=='\"')
{
i++;
k=t[i]+i+1;
i++;
while (i<k)
{
t[j++]=t[i++];
}
}
else
{
if (!(er=evaluate_expression(t+i,&v,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
if (afl) afile->u_set(TablePcSegment[gCurrentSegment]+j, afl, label, 1);
if (v&0xff00)
er=E_OVERFLOW;
else
{
t[j++]=v;
i+=l;
}
}
}
if (t[i]!=T_END && t[i]!=',')
er=E_SYNTAX;
else
if (t[i]==',')
i++;
}
*ll=j;
bl=j;
}
else
if (n==Kdft)
{
er=evaluate_expression(t+1,&dft,&l,TablePcSegment[gCurrentSegment],&afl,&label,0);
*ll=0;
}
else
if (n==Kalong)
{
memode=1;
*ll=0;
}
else
if (n==Kashort)
{
memode=0;
*ll=0;
}
else
if (n==Kxlong)
{
xmode=1;
*ll=0;
}
else
if (n==Kxshort)
{
xmode=0;
*ll=0;
}
else
if (n==Kpcdef)
{
int npc;
er=evaluate_expression(t+1,&npc,&l,TablePcSegment[gCurrentSegment],&afl,&label,0);
bl=0;
*ll=0;
if (gCurrentSegment==eSEGMENT_TEXT)
{
r_mode(RMODE_ABS);
}
TablePcSegment[gCurrentSegment] = npc;
}
else
if (n==Kreloc)
{
int npc;
er=evaluate_expression(t+1,&npc,&l,TablePcSegment[gCurrentSegment],&afl,&label,0);
bl=0;
*ll=0;
r_mode(RMODE_RELOC);
TablePcSegment[gCurrentSegment] = npc;
}
else
if (n==Ksegment)
{
gCurrentSegment = (SEGMENT_e)t[1];
*ll=0;
bl =0;
}
else
if (n==Kdsb)
{
gDsbLen = 1;
if (!(er=evaluate_expression(t+1,&j,&i,TablePcSegment[gCurrentSegment],&afl,&label,0)))
{
{
gDsbLen = 0;
if (t[i+1]==',')
{
er=evaluate_expression(t+2+i,&v,&l,TablePcSegment[gCurrentSegment],&afl,&label,0);
}
else
{
v=0;
}
if (!er && v>>8)
er=E_OVERFLOW;
t[0]=v&255;
if (!er)
{
*ll=j;
bl=j;
er=E_DSB;
}
}
if (!er)
bl=j;
}
gDsbLen = 0;
}
else
if (n<=Lastbef)
{
if ((c=t[1])=='#')
{
i=2;
sy=1;
if (!(er=evaluate_expression(t+i,vv,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
rlt[0] = afl;
lab[0] = label;
i+=l;
if (t[i]!=T_END)
{
if (t[i]!=',')
er=E_SYNTAX;
else
{
i++;
sy++;
if (!(er=evaluate_expression(t+i,vv+1,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
rlt[1] = afl;
lab[1] = label;
i+=l;
if (t[i]!=T_END)
{
if (t[i]!=',')
er=E_SYNTAX;
else
{
i++;
sy++;
if (!(er=evaluate_expression(t+i,vv+2,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
rlt[2] = afl;
lab[2] = label;
i+=l;
if (t[i]!=T_END)
er=E_SYNTAX;
}
}
}
}
}
}
}
}
else
if (c==T_END)
{
sy=0;
}
else
if (c=='(')
{
sy=7;
if (!(er=evaluate_expression(t+2,vv,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
rlt[0] = afl;
lab[0] = label;
if (t[2+l]!=T_END)
{
if (t[2+l]==',')
{
if (tolower(t[3+l])=='x')
sy=8;
else
sy=13;
}
else
if (t[2+l]==')')
{
if (t[3+l]==',')
{
if (tolower(t[4+l])=='y')
sy=9;
else
er=E_SYNTAX;
}
else
if (t[3+l]!=T_END)
er=E_SYNTAX;
}
}
else
er=E_SYNTAX;
}
}
else
if (c=='[')
{
sy=10;
if (!(er=evaluate_expression(t+2,vv,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
rlt[0] = afl;
lab[0] = label;
if (t[2+l]!=T_END)
{
if (t[2+l]==']')
{
if (t[3+l]==',')
{
if (tolower(t[4+l])=='y')
sy=11;
else
er=E_SYNTAX;
}
else
if (t[3+l]!=T_END)
er=E_SYNTAX;
}
}
else
er=E_SYNTAX;
}
}
else
{
sy=4;
if (!(er=evaluate_expression(t+1,vv,&l,TablePcSegment[gCurrentSegment],&afl,&label,1)))
{
rlt[0] = afl;
lab[0] = label;
if (t[1+l]!=T_END)
{
if (t[1+l]==',')
{
if (tolower(t[2+l])=='y')
sy=6;
else
if (tolower(t[2+l])=='s')
sy=12;
else
sy=5;
}
else
er=E_SYNTAX;
}
}
}
bl=Maxbyt+1;
while (--bl)
{
if ((am=at[sy][bl-1])>=0)
{
if (am>Admodes)
{
// Did not found out a valid addressing mode
er=E_SYNTAX;
break;
}
if (ct[n][am]>=0)
break;
for(v=0;v<NB_ALTERNATIVE_ADRESSING_MODES;v++)
if (TableAlternativeAdressingModes[v][0]==am && ct[n][TableAlternativeAdressingModes[v][1]]>=0)
break;
if (v<NB_ALTERNATIVE_ADRESSING_MODES)
{
am=TableAlternativeAdressingModes[v][1];
break;
}
}
}
if (t[*ll-1]!='@')
{
if (t[*ll-1]=='!')
vv[0]&=0xffff;
if (bl && !er && !(vv[0]&0xff0000) && opt[am]>=0 && am>16)
if (ct[n][opt[am]]>=0)
am=opt[am];
if (t[*ll-1]!='!' && fl)
{
if (bl && !er && !(vv[0]&0xffff00) && opt[am]>=0)
if (ct[n][opt[am]]>=0)
am=opt[am];
}
}
if (!bl)
er=E_SYNTAX;
else
{
bl=le[am];
if ( ((ct[n][am]&0x400) && memode) || ((ct[n][am]&0x800) && xmode))
bl++;
*ll=bl;
}
if (!er)
{
t[0]=ct[n][am]&0x00ff;
if (ct[n][am]&0x0300)
{
if (ct[n][am]&0x100)
{
gFlag_ncmos++;
if (!gFlag_cmosfl)
{
er=E_CMOS;
}
}
else
{
gFlag_n65816++;
if (!gFlag_w65816)
{
er=E_65816;
}
}
}
if (am!=0)
{
if ((am<8) && !( ((ct[n][am]&0x400) && memode) || ((ct[n][am]&0x800) && xmode) ) || (am>=19 && am!=23))
{
if (vv[0]&0xff00)
er=E_OVERFLOW;
else
t[1]=vv[0];
if (rlt[0]) afile->u_set(TablePcSegment[gCurrentSegment]+1, rlt[0], lab[0], 1);
}
else
if (((am<14 || am==23) && (am!=11)) || (am==7))
{
if (vv[0]>0xffff)
er=E_OVERFLOW;
else
{
t[1]=vv[0]&255;
t[2]=(vv[0]>>8)&255;
if (rlt[0]) afile->u_set(TablePcSegment[gCurrentSegment]+1, rlt[0], lab[0], 2);
}
}
else
if (am==11 || am==16)
{
if ((gCurrentSegment!=eSEGMENT_ABS) && (!rlt[0]))
{
er=E_ILLPOINTER;
}
else
{
v=vv[0]-TablePcSegment[gCurrentSegment]-le[am];
if (((v&0xff80)!=0xff80) && (v&0xff80) && (am==11))
er=E_RANGE;
else
{
t[1]=v&255;
t[2]=(v>>8)&255;
}
}
}
else
if (am==14)
{
if (vv[0]&0xfff8 || vv[1]&0xff00)
er=E_RANGE;
else
if ((gCurrentSegment!=eSEGMENT_ABS) && (rlt[0] || !rlt[2]))
{
er=E_ILLPOINTER;
}
else
{
if (rlt[1]) afile->u_set(TablePcSegment[gCurrentSegment]+1, rlt[1], lab[1], 1);
t[0]=t[0]|(vv[0]<<4);
t[1]=vv[1];
v=vv[2]-TablePcSegment[gCurrentSegment]-3;
if ((v&0xff80) && ((v&0xff80)!=0xff80))
er=E_OVERFLOW;
else
t[2]=v;
}
}
else
if (am==15)
{
if (rlt[1]) afile->u_set(TablePcSegment[gCurrentSegment]+1, rlt[1], lab[1], 1);
if (vv[0]&0xfff8 || vv[1]&0xff00)
er=E_OVERFLOW;
else
{
t[0]=t[0]|(vv[0]<<4);
t[1]=vv[1];
}
}
else
if (am==17 || am==18)
{
t[1]=vv[0]&255;
t[2]=(vv[0]>>8)&255;
t[3]=(vv[0]>>16)&255;
if (rlt[0])
{
rlt[0]|=A_LONG;
afile->u_set(TablePcSegment[gCurrentSegment]+1, rlt[0], lab[0], 3);
}
}
else
er=E_SYNTAX;
}
}
}
else
{
er=E_SYNTAX;
}
}
TablePcSegment[gCurrentSegment]+=bl;
if (gCurrentSegment==eSEGMENT_TEXT) TablePcSegment[eSEGMENT_ABS]+=bl;
if (gCurrentSegment==eSEGMENT_ABS) TablePcSegment[eSEGMENT_TEXT]+=bl;
*al = bl;
return er;
}
int b_term(char *s, int *v, int *l, int pc)
{
static signed char t[MAXLINE];
int er,i,afl, label;
if (!(er=t_conv((signed char*)s,t,l,pc,&i,&i,&i,1)))
{
er=evaluate_expression(t,v,&i,pc,&afl,&label,0);
}
return er;
}
static ErrorCode t_conv(signed char *s,signed char *ptr_output,int *l,int pc,int *number_commas,int *number_quoted_strings,int *size_quoted_strings,int af) /* Pass1 von s nach t */
{
static int v;
static int operand;
*number_commas=0; // Anzahl Komma
*number_quoted_strings=0; // Anzahl "asc-texte"
*size_quoted_strings=0; // und Anzahl Byte in diesen
int ll=0; // Token lenght
ErrorCode er=E_OK;
int p=0;
int q=0;
bool flag_undefined_label=false;
int mk=0; // 0 = more commas allowed (mehrere Kommas erlaubt)
int fl=0; // 1 = text einfach weitergeben
int afl=0; // pointer flag for label
while (s[p]==' ') p++;
int n=T_END;
unsigned char cast=0;
if (!af)
{
//while (s[p]!=0 && s[p]!=';')
while (!is_end_of_line( ((char*)(s+p)) ))
{
// Test if the line starts by a keyword
if (!(er=t_keyword(s+p,&ll,&n))) break;
if (er && er!=E_NOKEY) break;
// Test if the line starts by a label definition
bool flag_redefine_label;
if ((er=afile->m_cSymbolData.DefineLabel((char*)s+p,&ll,&n,&flag_redefine_label))) break;
p+=ll;
while (s[p]==' ') p++;
if (s[p]=='=')
{
ptr_output[q++]=T_OP;
ptr_output[q++]=n&255;
ptr_output[q++]=(n>>8)&255;
ptr_output[q++]='=';
p++;
ll=n=0;
break;
}
else
if (flag_redefine_label && s[p]!=0 && s[p+1]=='=')
{
ptr_output[q++]=T_OP;
ptr_output[q++]=n&255;
ptr_output[q++]=(n>>8)&255;
ptr_output[q++]=s[p];
p+=2;
ll=n=0;
break;
}
else
{
SymbolEntry& symbol_entry=afile->m_cSymbolData.GetSymbolEntry(n);
symbol_entry.Set(pc,gCurrentSegment); // set as address value
n=0;
}
}
if (n<=Lastbef)
{
mk=1; // 1=only one comma allowed (nur 1 Komma erlaubt)
}
}
//if (s[p]==0 || s[p]==';')
if (is_end_of_line( (char*)s+p))
{
er=E_NOLINE;
ll=0;
}
else
if (!er)
{
p+=ll;
if (ll)
{
ptr_output[q++]=n;
}
operand=1;
while (s[p]==' ') p++;
if (s[p]=='#')
{
mk=0;
ptr_output[q++]=s[p++];
while (s[p]==' ') p++;
}
//while (s[p]!=0 && s[p]!=';' && !er)
while (!is_end_of_line( (char*)s+p) && !er)
{
if (fl)
{
ptr_output[q++]=s[p++];
}
else
{
if (operand)
{
if (s[p]=='!' || s[p]=='@')
{
cast=s[p];
operand= -operand+1;
p++;
}
else
if (s[p]=='(' || s[p]=='-' || s[p]=='>' || s[p]=='<' || s[p]=='[' || s[p]=='^')
{
ptr_output[q++]=s[p++];
operand= -operand+1;
}
else
if (s[p]=='*')
{
ptr_output[q++]=s[p++];
}
else
if (isalpha(s[p]) || s[p]=='_')
{
// This token is alphanumeric, we have to check if it exists in the list of known labels
er=afile->m_cSymbolData.l_such((char*)s+p,&ll,&n,&v,&afl);
if (!er)
{
// No error, store the label information
if (afl)
{
ptr_output[q++]=T_POINTER;
ptr_output[q++]=afl & 255;
ptr_output[q++]=v & 255;
ptr_output[q++]=(v>>8) & 255;
}
else
{
ptr_output[q++]=T_VALUE;
ptr_output[q++]=((v)>>0)&255;
ptr_output[q++]=((v)>>8)&255;
ptr_output[q++]=((v)>>16)&255;
ptr_output[q++]=((v)>>24)&255;
}
}
else
if (er==ERR_UNDEFINED_LABEL)
{
// Record a missing label (probably will have to be found out in the second pass)
ptr_output[q++]=T_LABEL;
ptr_output[q++]=n & 255;
ptr_output[q++]=(n>>8) & 255;
flag_undefined_label=true;
er=E_OK;
}
p+=ll;
}
else
if (s[p]<='9' && s[p]>='0')
{
if ((s[p]=='0') && (s[p+1]=='x'))
{
// Hexadecimal (C/C++ mode)
ParseHexadecimalValue(s+p+1,&ll,&v);
p+=2+ll;
ptr_output[q++]=T_VALUE;
ptr_output[q++]=((v)>>0)&255;
ptr_output[q++]=((v)>>8)&255;
ptr_output[q++]=((v)>>16)&255;
ptr_output[q++]=((v)>>24)&255;
}
else
{
// Decimal
ParseDecimalValue(s+p,&ll,&v);
p+=ll;
ptr_output[q++]=T_VALUE;
ptr_output[q++]=((v)>>0)&255;
ptr_output[q++]=((v)>>8)&255;
ptr_output[q++]=((v)>>16)&255;
ptr_output[q++]=((v)>>24)&255;
}
}
else
{
switch (s[p])
{
case '$':
// Hexadecimal (asm mode)
ParseHexadecimalValue(s+p+1,&ll,&v);
p+=1+ll;
ptr_output[q++]=T_VALUE;
ptr_output[q++]=((v)>>0)&255;
ptr_output[q++]=((v)>>8)&255;
ptr_output[q++]=((v)>>16)&255;
ptr_output[q++]=((v)>>24)&255;
break;
case '%':
ParseBinaryValue(s+p+1,&ll,&v);
p+=1+ll;
ptr_output[q++]=T_VALUE;
ptr_output[q++]=((v)>>0)&255;
ptr_output[q++]=((v)>>8)&255;
ptr_output[q++]=((v)>>16)&255;
ptr_output[q++]=((v)>>24)&255;
break;
case '&':
ParseOctalValue(s+p+1,&ll,&v);
p+=1+ll;
ptr_output[q++]=T_VALUE;
ptr_output[q++]=((v)>>0)&255;
ptr_output[q++]=((v)>>8)&255;
ptr_output[q++]=((v)>>16)&255;
ptr_output[q++]=((v)>>24)&255;
break;
case '\"':
curr=n;
er=ParseQuotedString(s+p,ptr_output+q,&q,&p,number_quoted_strings,size_quoted_strings);
break;
case ',':
if (mk)
{
//while (s[p]!=0 && s[p]!=';')
while (!is_end_of_line( (char*)s+p))
{
while (s[p]==' ') p++;
*number_commas+=(s[p]==',');
ptr_output[q++]=s[p++];
}
}
else
{
*number_commas+=1;
ptr_output[q++]=s[p++];
}
break;
default :
er=E_SYNTAX;
break;
}
}
operand= -operand+1;
}
else
{
// operator
OPERATOR_e o=eOPERATOR_NONE;
if (s[p]==')' || s[p]==']')
{
ptr_output[q++]=s[p++];
operand =-operand+1;
}
else
if (s[p]==',')
{
ptr_output[q++]=s[p++];
if (mk)
fl++;
*number_commas+=1;
}
else
switch (s[p])
{
case '+':
o=eOPERATOR_ADD;
break;
case '-':
o=eOPERATOR_SUBTRACT;
break;
case '*':
o=eOPERATOR_MULTIPLY;
break;
case '/':
o=eOPERATOR_DIVIDE;
break;
case '<':
switch (s[p+1])
{
case '<':
o=eOPERATOR_SHIFTLEFT;
break;
case '>':
o=eOPERATOR_DIFFERENT;
break;
case '=':
o=eOPERATOR_INFERIOR_OR_EQUAL;
break;
default :
o=eOPERATOR_INFERIOR;
break;
}
break;
case '>':
switch (s[p+1])
{
case '>':
o=eOPERATOR_SHIFTRIGHT;
break;
case '<':
o=eOPERATOR_DIFFERENT;
break;
case '=':
o=eOPERATOR_SUPERIOR_OR_EQUAL;
break;
default:
o=eOPERATOR_SUPERIOR;
break;
}
break;
case '=':
switch (s[p+1])
{
case '<':
o=eOPERATOR_INFERIOR_OR_EQUAL;
break;
case '>':
o=eOPERATOR_SUPERIOR_OR_EQUAL;
break;
default:
o=eOPERATOR_EQUAL;
break;
}
break;
case '&':
if (s[p+1]=='&')
o=eOPERATOR_LOGICAL_AND;
else
o=eOPERATOR_BINARY_AND;
break;
case '|':
if (s[p+1]=='|')
o=eOPERATOR_LOGICAL_OR;
else
o=eOPERATOR_BINARY_OR;
break;
case '^':
o=eOPERATOR_XOR;
break;
default:
er=E_SYNTAX;
break;
}
if (o)
{
int gOperatorStringLength[]= { 0,1,1,1,1,2,2,1,1,1,2,2,2,1,1,1,2,2 };
ptr_output[q++]=o;
p+=gOperatorStringLength[o];
}
operand= -operand+1;
}
while (s[p]==' ') p++;
}
}
}
if (!er)
{
ptr_output[q++]=T_END;
if (flag_undefined_label)
{
er=ERR_UNDEFINED_LABEL;
}
}
ptr_output[q++]=0;
ptr_output[q++]=cast;
*l=q;
return er;
}
static ErrorCode t_keyword(signed char *ptr_src, int *keyword_lenght, int *keyword_index)
{
if (!isalpha(ptr_src[0]) && ptr_src[0]!='.' && ptr_src[0]!='*' )
return E_NOKEY;
int hash=0;
if (isalpha(ptr_src[0]))
hash=tolower(ptr_src[0])-'a';
else
hash=26;
int i=0;
int j=0;
if (ptr_src[0]=='*')
{
j=1;
while (ptr_src[j] && isspace(ptr_src[j])) j++;
if (ptr_src[j]=='=')
{
i=Kpcdef;
j++;
}
}
if (!i)
{
i=ktp[hash];
hash=ktp[hash+1];
while (i<hash)
{
j=0;
while (kt[i][j]!=0 && kt[i][j]==tolower(ptr_src[j]))
j++;
if ((kt[i][j]==0) && ((i==Kpcdef) || ((ptr_src[j]!='_') && !isalnum(ptr_src[j]))))
break;
i++;
}
}
if (i==Kbyte) i=Kbyt;
if (i==Kdupb) i=Kdsb;
if (i==Kblkb) i=Kdsb;
if (i==Kdb) i=Kbyt;
if (i==Kdw) i=Kword;
if (i==Kblock) i=Kopen;
if (i==Kbend) i=Kclose;
*keyword_lenght=j;
*keyword_index=i;
return i==hash ? E_NOKEY : E_OK;
}
static void ParseDecimalValue(signed char *ptr_source_string,int *l,int *ptr_output_value)
{
int i=0;
int val=0;
while (isdigit(ptr_source_string[i]))
{
val=val*10+(ptr_source_string[i++]-'0');
}
*l=i;
*ptr_output_value=val;
}
static void ParseBinaryValue(signed char *ptr_source_string, int *l, int *ptr_output_value)
{
int i=0,val=0;
while (ptr_source_string[i]=='0' || ptr_source_string[i]=='1')
{
val=val*2+(ptr_source_string[i++]-'0');
}
*l=i;
*ptr_output_value=val;
}
static void ParseOctalValue(signed char *ptr_source_string, int *l, int *ptr_output_value)
{
int i=0,val=0;
while (ptr_source_string[i]<'8' && ptr_source_string[i]>='0')
{
val=val*8+(ptr_source_string[i++]-'0');
}
*l=i;
*ptr_output_value=val;
}
static void ParseHexadecimalValue(signed char *ptr_source_string, int *l, int *ptr_output_value)
{
int i=0,val=0;
while ((ptr_source_string[i]>='0' && ptr_source_string[i]<='9') || (tolower(ptr_source_string[i])<='f' && tolower(ptr_source_string[i])>='a'))
{
val=val*16+(ptr_source_string[i]<='9' ? ptr_source_string[i]-'0' : tolower(ptr_source_string[i])-'a'+10);
i++;
}
*l=i;
*ptr_output_value=val;
}
static ErrorCode ParseQuotedString(signed char *ptr_src, signed char *ptr_dst, int *size_dst, int *size_src, int *number_quoted_strings, int *size_quoted_strings)
{
ErrorCode er=E_OK;
int i=0,j=0;
ptr_dst[j++]=ptr_src[i++]; // "
j++; // Place holder for the String size (up to 256 characters)
while (ptr_src[i]!=0 && ptr_src[i]!='\"')
{
#ifdef C64_ASCII
//
// PET/C64 special ascii codes
//
if (ptr_src[i]!='^')
{
int ch;
ch=ptr_src[i];
if (curr!=Kpsc && curr!=Kscr && curr!=Kasc)
{
if (dft==1)
curr=Kpsc;
else
if (dft==2)
curr=Kscr;
else
curr=Kasc;
}
if (curr==Kpsc)
ch = Asc2Pet(ch);
else if (curr==Kscr)
ch = Asc2Scr(ch);
ptr_dst[j++]=ch;
}
else
{
switch (ptr_src[i+1])
{
case 0:
case '\"':
er=E_SYNTAX;
break;
case '^':
ptr_dst[j++]='^';
i++;
break;
default:
ptr_dst[j++]=ptr_src[i+1]&0x1f;
i++;
break;
}
}
#else
//
// Case of ORIC, or other machines
// that do not need special codes
// handling
//
ptr_dst[j++]=ptr_src[i];
#endif
i++;
}
if (j==3)
{
// Literal character, like in lda #"A"
ptr_dst[0]=T_VALUE;
ptr_dst[1]=ptr_dst[2];
ptr_dst[2]=0;
ptr_dst[3]=0;
ptr_dst[4]=0;
j+=2;
}
else
{
ptr_dst[1]=j-2;
*number_quoted_strings +=1;
*size_quoted_strings +=j-2;
}
if (ptr_src[i]=='\"')
{
i++;
}
*size_dst +=j;
*size_src +=i;
return er;
}
/* return value if ascii has no c64 equivalent */
#define NO_CHAR 0x2d
#ifdef C64_ASCII
static signed char Asc2Pet(signed char c)
{
if (c==-0x23) return 0x5c; //pound -> 5c
else if (c <0x20) return NO_CHAR; //00 - 1f : nothing
else if (c <0x41) return c; //20 - 40 : same
else if (c <0x5b) return c+0x80; //41 - 5a -> c0 - da
else if (c==0x5b || c==0x5d) return c; //5b, 5d -> 5b, 5d
else if (c==0x5c) return 0x6d; //backslash -> shift M
else if (c==0x5e) return c; //^ -> arrow up
else if (c==0x5f) return 0xa4; //_ -> C= @
else if (c==0x60) return NO_CHAR; //` -> nothing
else if (c <0x7b) return c-0x20; //61 - 7a -> 41 - 5a
else if (c==0x7c) return 0xdd; //| -> C= -
else return NO_CHAR; //7b, 7d, 7e, 7f -> nothing
}
static signed char Asc2Scr(signed char c)
{
if (c==-0x23) return 0x1c; //pound -> 1c
else if (c <0x20) return NO_CHAR; //00 - 1f : nothing
else if (c==0x40) return 0; //@ -> 00
else if (c <0x5b) return c; //20 - 5a : same
else if (c==0x5b || c==0x5d) return c-0x40; //5b, 5d -> 1b, 1d
else if (c==0x5c) return 0x4d; //backslash -> shift M
else if (c==0x5e) return 0x1e; //^ -> arrow up
else if (c==0x5f) return 0x64; //_ -> C= @
else if (c==0x60) return NO_CHAR; //` -> nothing
else if (c <0x7b) return c-0x60; //61 - 7a -> 01 - 1a
else if (c==0x7c) return 0x5d; //| -> C= -
else return NO_CHAR; //7b, 7d, 7e, 7f -> nothing
}
#endif
|
ExoPlant/refinedstorage2
|
refinedstorage2-grid-api/src/main/java/com/refinedmods/refinedstorage2/api/grid/view/GridView.java
|
package com.refinedmods.refinedstorage2.api.grid.view;
import com.refinedmods.refinedstorage2.api.storage.channel.StorageTracker;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
public interface GridView<T> {
void setListener(Runnable listener);
GridSortingType getSortingType();
void setSortingType(GridSortingType sortingType);
void setFilter(Predicate<GridResource<T>> filter);
boolean isPreventSorting();
void setPreventSorting(boolean preventSorting);
GridSortingDirection getSortingDirection();
void setSortingDirection(GridSortingDirection sortingDirection);
void loadResource(T resource, long amount, StorageTracker.Entry trackerEntry);
Optional<StorageTracker.Entry> getTrackerEntry(Object resource);
void sort();
void onChange(T resource, long amount, StorageTracker.Entry trackerEntry);
List<GridResource<T>> getAll();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.