repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
llicursi/opto
|
src/main/java/com/llicursi/opto/config/OAuth2ResourceServerConfig.java
|
package com.llicursi.opto.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ResourceServerConfig
extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources){
resources.resourceId("product_api").tokenStore(tokenStore);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/v*/register").permitAll()
.antMatchers("/api/v*/**").authenticated()
.antMatchers("/**").permitAll()
.and().csrf().disable()
;
}
}
|
kbachl/brix-cms
|
brix-core/src/main/java/org/brixcms/Plugin.java
|
<filename>brix-core/src/main/java/org/brixcms/Plugin.java
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.brixcms;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.model.IModel;
import org.brixcms.jcr.api.JcrSession;
import org.brixcms.registry.ExtensionPoint;
import org.brixcms.web.tab.IBrixTab;
import org.brixcms.workspace.Workspace;
import java.util.List;
/**
* Plugin is a top-level component in Brix. Plugins can <ul> <li>contribute tabs to the main tabbed panel <li>contribute
* workspaces they are responsible for to the workspace switcher </ul> When plugin creates a workspace it is responsible
* for it. For such workspaces {@link #isPluginWorkspace(Workspace)} must return true.
* <p>
* TODO: Make it possible for plugins to intercept HTTP requests to serve content
*
* @author <NAME>
*/
public interface Plugin {
public static final ExtensionPoint<Plugin> POINT = new ExtensionPoint<Plugin>() {
public Multiplicity getMultiplicity() {
return Multiplicity.COLLECTION;
}
public String getUuid() {
return Plugin.class.getName();
}
};
/**
* Returns the plugin Id. Each plugin must have unique ID.
*
* @return plugin Id
*/
String getId();
/**
* Returns user visible name for given workspace. The name will be shown in workspace selector. This method will
* only be called for workspaces returned from {@link #getWorkspaces(Workspace, boolean)} or for workspaces for
* which {@link #isPluginWorkspace(Workspace)} returns true.
*
* @param workspace
* @param isFrontend whether the workspace selector is part of frontend or administration interface
* @return
*/
public String getUserVisibleName(Workspace workspace, boolean isFrontend);
/**
* Returns the list of workspaces this plugin is responsible for and which should be shown in the workspace
* selector. The returned list can vary according to the currently selected workspace.
*
* @param currentWorkspace Currently selected workspace
* @param isFrontend whether the workspace selector is part of frontend or administration interface
* @return
*/
List<Workspace> getWorkspaces(Workspace currentWorkspace, boolean isFrontend);
/**
* Initializes the given workspace. If this plugin can handle the workspace (i.e. newTabs return non-empty list) the
* method must make sure that the workspace contains all required nodes.
* <p>
* This method is called on Brix startup for every plugin and workspace. It is also when new workspace is created.
*
* @param workspace
* @param workspaceSession
*/
public void initWorkspace(Workspace workspace, JcrSession workspaceSession);
/**
* Returns <code>true</code> if the plugin is responsible for the given workspace. E.g. for snapshot workspaces the
* SnapshotPlugin should return <code>true</code>, all other plugins should return <code>false</code>.
* <p>
* Returning <code>true</code> here is not the same as returning non-empty list from {@link #newTabs(IModel)}. Even
* if plugin contributes tabs for certain workspace, it doesn't make it responsible for it. Plugin is usually
* responsible only for workspace that it creates.
*
* @param workspace
* @return
*/
public boolean isPluginWorkspace(Workspace workspace);
/**
* Create and return list of administration tabs for this plugin. This method is invoked only once per admin panel
* instance. When the selected workspace changes, the workspaceModel.getObject() will return newly selected
* workspace, however this method will not be called again. Each panel in tab is responsible for updating itself
* when workspace changed.
*
* @param workspaceModel model providing currently selected workspace
* @return list of {@link ITab} instances or null if this plugin doesn't contribute any tabs
*/
List<IBrixTab> newTabs(IModel<Workspace> workspaceModel);
}
|
EdurasGame/eventingserver
|
src/de/eduras/eventingserver/StringUtils.java
|
package de.eduras.eventingserver;
import java.util.LinkedList;
public class StringUtils {
public static String[] splitIntoStringsStartingWith(String stringToSplit,
String splitBy) {
Integer[] startingIndices = findOccurences(stringToSplit, splitBy);
String[] result = new String[startingIndices.length];
int lastIndex = 0;
for (int i = 0; i < startingIndices.length; i++) {
int endsAt = stringToSplit.length();
if (i < startingIndices.length - 1) {
endsAt = startingIndices[i + 1];
}
result[i] = stringToSplit.substring(lastIndex, endsAt);
lastIndex = endsAt;
}
return result;
}
public static Integer[] findOccurences(String stringToSearchIn,
String stringToSearchFor) {
LinkedList<Integer> startingIndices = new LinkedList<Integer>();
int lastIndex = 0;
while ((lastIndex = stringToSearchIn.indexOf(stringToSearchFor,
lastIndex)) != -1) {
startingIndices.add(new Integer(lastIndex));
lastIndex += stringToSearchFor.length();
}
return startingIndices.toArray(new Integer[startingIndices.size()]);
}
}
|
penguinmenac3/babilim
|
babilim/model/layers/flatten.py
|
# AUTOGENERATED FROM: babilim/model/layers/flatten.ipynb
# Cell: 0
"""doc
# babilim.model.layers.flatten
> Flatten a feature map into a linearized tensor.
"""
# Cell: 1
from babilim.core.annotations import RunOnlyOnce
from babilim.core.module_native import ModuleNative
# Cell: 2
class Flatten(ModuleNative):
def __init__(self):
"""
Flatten a feature map into a linearized tensor.
This is usefull after the convolution layers before the dense layers. The (B, W, H, C) tensor gets converted ot a (B, N) tensor.
"""
super().__init__()
@RunOnlyOnce
def _build_pytorch(self, features):
pass
def _call_pytorch(self, features):
return features.view(features.shape[0], -1)
@RunOnlyOnce
def _build_tf(self, features):
from tensorflow.keras.layers import Flatten as _Flatten
self.flatten = _Flatten()
self.flatten.build(features.shape)
def _call_tf(self, features):
return self.flatten(features)
|
Radek87o/BuildingCompany_dailyRegistries
|
ConstructionCompany-registries-allJavaConfig/src/main/java/com/firmaBudowlana/springdemo/service/UserService.java
|
<reponame>Radek87o/BuildingCompany_dailyRegistries
package com.firmaBudowlana.springdemo.service;
import org.springframework.security.core.userdetails.UserDetailsService;
import com.firmaBudowlana.springdemo.entity.User;
import com.firmaBudowlana.springdemo.user.AppUser;
public interface UserService extends UserDetailsService {
public User findByUsername(String username);
public void save(AppUser theAppUser);
public void update(AppUser theAppUser, int userId);
public AppUser populateAppUserToUpdate(int userId);
public void updateTheUser(int userId, AppUser theAppUser);
}
|
jedhsu/wave
|
wave/synth/wave/wave/base/types/fv.py
|
"""
Frequency vs. Volume.
"""
from ear4.wave import Decibel, Frequency
from ..base import XY
# FrequencySpectrum
class FreqVolume(XY):
_xy = XY(Frequency, Decibel)
|
Learningpurposes/unethicalite
|
runescape-client/src/main/java/MouseHandler.java
|
<filename>runescape-client/src/main/java/MouseHandler.java
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("ar")
@Implements("MouseHandler")
public class MouseHandler implements MouseListener , MouseMotionListener , FocusListener {
@ObfuscatedName("g")
@ObfuscatedSignature(descriptor =
"Lar;")
@Export("MouseHandler_instance")
public static MouseHandler MouseHandler_instance;
@ObfuscatedName("l")
@ObfuscatedGetter(intValue =
107284469)
@Export("MouseHandler_idleCycles")
public static volatile int MouseHandler_idleCycles;
@ObfuscatedName("n")
@ObfuscatedGetter(intValue =
46919017)
@Export("MouseHandler_currentButtonVolatile")
public static volatile int MouseHandler_currentButtonVolatile;
@ObfuscatedName("d")
@ObfuscatedGetter(intValue =
-196949191)
@Export("MouseHandler_xVolatile")
public static volatile int MouseHandler_xVolatile;
@ObfuscatedName("f")
@ObfuscatedGetter(intValue =
44426053)
@Export("MouseHandler_yVolatile")
public static volatile int MouseHandler_yVolatile;
@ObfuscatedName("u")
@ObfuscatedGetter(longValue =
51726182366578667L)
@Export("MouseHandler_lastMovedVolatile")
public static volatile long MouseHandler_lastMovedVolatile;
@ObfuscatedName("r")
@ObfuscatedGetter(intValue =
-1741182953)
@Export("MouseHandler_currentButton")
public static int MouseHandler_currentButton;
@ObfuscatedName("k")
@ObfuscatedGetter(intValue =
1113383001)
@Export("MouseHandler_x")
public static int MouseHandler_x;
@ObfuscatedName("x")
@ObfuscatedGetter(intValue =
-601944997)
@Export("MouseHandler_y")
public static int MouseHandler_y;
@ObfuscatedName("c")
@ObfuscatedGetter(longValue =
-3366277212682218721L)
@Export("MouseHandler_millis")
public static long MouseHandler_millis;
@ObfuscatedName("j")
@ObfuscatedGetter(intValue =
-173750849)
@Export("MouseHandler_lastButtonVolatile")
public static volatile int MouseHandler_lastButtonVolatile;
@ObfuscatedName("p")
@ObfuscatedGetter(intValue =
1130317715)
@Export("MouseHandler_lastPressedXVolatile")
public static volatile int MouseHandler_lastPressedXVolatile;
@ObfuscatedName("s")
@ObfuscatedGetter(intValue =
533285241)
@Export("MouseHandler_lastPressedYVolatile")
public static volatile int MouseHandler_lastPressedYVolatile;
@ObfuscatedName("b")
@ObfuscatedGetter(longValue =
-5019639506180718005L)
@Export("MouseHandler_lastPressedTimeMillisVolatile")
public static volatile long MouseHandler_lastPressedTimeMillisVolatile;
@ObfuscatedName("w")
@ObfuscatedGetter(intValue =
-1259465113)
@Export("MouseHandler_lastButton")
public static int MouseHandler_lastButton;
@ObfuscatedName("a")
@ObfuscatedGetter(intValue =
-416250337)
@Export("MouseHandler_lastPressedX")
public static int MouseHandler_lastPressedX;
@ObfuscatedName("m")
@ObfuscatedGetter(intValue =
-769215047)
@Export("MouseHandler_lastPressedY")
public static int MouseHandler_lastPressedY;
@ObfuscatedName("q")
@ObfuscatedGetter(longValue =
4641952122808710007L)
@Export("MouseHandler_lastPressedTimeMillis")
public static long MouseHandler_lastPressedTimeMillis;
@ObfuscatedName("ei")
@ObfuscatedSignature(descriptor =
"Llu;")
@Export("archive4")
static Archive archive4;
static
{
MouseHandler_instance = new MouseHandler();
MouseHandler_idleCycles = 0;
MouseHandler_currentButtonVolatile = 0;
MouseHandler_xVolatile = -1;
MouseHandler_yVolatile = -1;
MouseHandler_lastMovedVolatile = -1L;
MouseHandler_currentButton = 0;
MouseHandler_x = 0;
MouseHandler_y = 0;
MouseHandler_millis = 0L;
MouseHandler_lastButtonVolatile = 0;
MouseHandler_lastPressedXVolatile = 0;
MouseHandler_lastPressedYVolatile = 0;
MouseHandler_lastPressedTimeMillisVolatile = 0L;
MouseHandler_lastButton = 0;
MouseHandler_lastPressedX = 0;
MouseHandler_lastPressedY = 0;
MouseHandler_lastPressedTimeMillis = 0L;
}
MouseHandler() {
}
@ObfuscatedName("g")
@ObfuscatedSignature(descriptor =
"(Ljava/awt/event/MouseEvent;B)I", garbageValue =
"1")
@Export("getButton")
final int getButton(MouseEvent var1) {
int var2 = var1.getButton();
if ((!var1.isAltDown()) && (var2 != 2)) {
return (!var1.isMetaDown()) && (var2 != 3) ? 1 : 2;
} else {
return 4;
}
}
public synchronized final void mouseMoved(MouseEvent var1) {
if (MouseHandler_instance != null) {
MouseHandler_idleCycles = 0;
MouseHandler_xVolatile = var1.getX();
MouseHandler_yVolatile = var1.getY();
MouseHandler_lastMovedVolatile = var1.getWhen();
}
}
public synchronized final void mousePressed(MouseEvent var1) {
if (MouseHandler_instance != null) {
MouseHandler_idleCycles = 0;
MouseHandler_lastPressedXVolatile = var1.getX();
MouseHandler_lastPressedYVolatile = var1.getY();
MouseHandler_lastPressedTimeMillisVolatile = WorldMapSprite.getServerTime();
MouseHandler_lastButtonVolatile = this.getButton(var1);
if (MouseHandler_lastButtonVolatile != 0) {
MouseHandler_currentButtonVolatile = MouseHandler_lastButtonVolatile;
}
}
if (var1.isPopupTrigger()) {
var1.consume();
}
}
public final void mouseClicked(MouseEvent var1) {
if (var1.isPopupTrigger()) {
var1.consume();
}
}
public synchronized final void mouseExited(MouseEvent var1) {
if (MouseHandler_instance != null) {
MouseHandler_idleCycles = 0;
MouseHandler_xVolatile = -1;
MouseHandler_yVolatile = -1;
MouseHandler_lastMovedVolatile = var1.getWhen();
}
}
public synchronized final void mouseEntered(MouseEvent var1) {
this.mouseMoved(var1);
}
public final void focusGained(FocusEvent var1) {
}
public synchronized final void focusLost(FocusEvent var1) {
if (MouseHandler_instance != null) {
MouseHandler_currentButtonVolatile = 0;
}
}
public synchronized final void mouseReleased(MouseEvent var1) {
if (MouseHandler_instance != null) {
MouseHandler_idleCycles = 0;
MouseHandler_currentButtonVolatile = 0;
}
if (var1.isPopupTrigger()) {
var1.consume();
}
}
public synchronized final void mouseDragged(MouseEvent var1) {
this.mouseMoved(var1);
}
@ObfuscatedName("g")
@ObfuscatedSignature(descriptor =
"(ZZB)Lqx;", garbageValue =
"28")
static IndexedSprite method622(boolean var0, boolean var1) {
return var0 ? var1 ? class143.field1639 : Skeleton.options_buttons_2Sprite : var1 ? InvDefinition.field1814 : class160.options_buttons_0Sprite;
}
@ObfuscatedName("s")
@ObfuscatedSignature(descriptor =
"(Law;I)V", garbageValue =
"1699393273")
static void method621(GameEngine var0) {
while (class16.isKeyDown()) {
if (class241.field2833 == 13) {
Login.worldSelectOpen = false;
Login.leftTitleSprite.drawAt(Login.xPadding, 0);
class162.rightTitleSprite.drawAt(Login.xPadding + 382, 0);
HorizontalAlignment.logoSprite.drawAt((Login.xPadding + 382) - (HorizontalAlignment.logoSprite.subWidth / 2), 18);
return;
}
if (class241.field2833 == 96) {
if ((Login.worldSelectPage > 0) && (Interpreter.worldSelectLeftSprite != null)) {
--Login.worldSelectPage;
}
} else if (((class241.field2833 == 97) && (Login.worldSelectPage < Login.worldSelectPagesCount)) && (class124.worldSelectRightSprite != null)) {
++Login.worldSelectPage;
}
}
if ((MouseHandler_lastButton == 1) || ((!UserComparator5.mouseCam) && (MouseHandler_lastButton == 4))) {
int var1 = Login.xPadding + 280;
if ((((MouseHandler_lastPressedX >= var1) && (MouseHandler_lastPressedX <= (var1 + 14))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(0, 0);
return;
}
if ((((MouseHandler_lastPressedX >= (var1 + 15)) && (MouseHandler_lastPressedX <= (var1 + 80))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(0, 1);
return;
}
int var2 = Login.xPadding + 390;
if ((((MouseHandler_lastPressedX >= var2) && (MouseHandler_lastPressedX <= (var2 + 14))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(1, 0);
return;
}
if ((((MouseHandler_lastPressedX >= (var2 + 15)) && (MouseHandler_lastPressedX <= (var2 + 80))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(1, 1);
return;
}
int var3 = Login.xPadding + 500;
if ((((MouseHandler_lastPressedX >= var3) && (MouseHandler_lastPressedX <= (var3 + 14))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(2, 0);
return;
}
if ((((MouseHandler_lastPressedX >= (var3 + 15)) && (MouseHandler_lastPressedX <= (var3 + 80))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(2, 1);
return;
}
int var4 = Login.xPadding + 610;
if ((((MouseHandler_lastPressedX >= var4) && (MouseHandler_lastPressedX <= (var4 + 14))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(3, 0);
return;
}
if ((((MouseHandler_lastPressedX >= (var4 + 15)) && (MouseHandler_lastPressedX <= (var4 + 80))) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedY <= 18)) {
Interpreter.changeWorldSelectSorting(3, 1);
return;
}
if ((((MouseHandler_lastPressedX >= (Login.xPadding + 708)) && (MouseHandler_lastPressedY >= 4)) && (MouseHandler_lastPressedX <= ((Login.xPadding + 708) + 50))) && (MouseHandler_lastPressedY <= 20)) {
Login.worldSelectOpen = false;
Login.leftTitleSprite.drawAt(Login.xPadding, 0);
class162.rightTitleSprite.drawAt(Login.xPadding + 382, 0);
HorizontalAlignment.logoSprite.drawAt((Login.xPadding + 382) - (HorizontalAlignment.logoSprite.subWidth / 2), 18);
return;
}
if (Login.hoveredWorldIndex != (-1)) {
World var5 = World.World_worlds[Login.hoveredWorldIndex];
ItemContainer.changeWorld(var5);
Login.worldSelectOpen = false;
Login.leftTitleSprite.drawAt(Login.xPadding, 0);
class162.rightTitleSprite.drawAt(Login.xPadding + 382, 0);
HorizontalAlignment.logoSprite.drawAt((Login.xPadding + 382) - (HorizontalAlignment.logoSprite.subWidth / 2), 18);
return;
}
if ((((((Login.worldSelectPage > 0) && (Interpreter.worldSelectLeftSprite != null)) && (MouseHandler_lastPressedX >= 0)) && (MouseHandler_lastPressedX <= Interpreter.worldSelectLeftSprite.subWidth)) && (MouseHandler_lastPressedY >= ((class309.canvasHeight / 2) - 50))) && (MouseHandler_lastPressedY <= ((class309.canvasHeight / 2) + 50))) {
--Login.worldSelectPage;
}
if ((((((Login.worldSelectPage < Login.worldSelectPagesCount) && (class124.worldSelectRightSprite != null)) && (MouseHandler_lastPressedX >= ((class4.canvasWidth - class124.worldSelectRightSprite.subWidth) - 5))) && (MouseHandler_lastPressedX <= class4.canvasWidth)) && (MouseHandler_lastPressedY >= ((class309.canvasHeight / 2) - 50))) && (MouseHandler_lastPressedY <= ((class309.canvasHeight / 2) + 50))) {
++Login.worldSelectPage;
}
}
}
@ObfuscatedName("fr")
@ObfuscatedSignature(descriptor =
"(I)V", garbageValue =
"797091978")
static final void method593() {
FloorOverlayDefinition.FloorOverlayDefinition_cached.clear();
FloorUnderlayDefinition.FloorUnderlayDefinition_cached.clear();
KitDefinition.KitDefinition_cached.clear();
ObjectComposition.ObjectDefinition_cached.clear();
ObjectComposition.ObjectDefinition_cachedModelData.clear();
ObjectComposition.ObjectDefinition_cachedEntities.clear();
ObjectComposition.ObjectDefinition_cachedModels.clear();
WorldMapDecoration.method4988();
ItemComposition.ItemDefinition_cached.clear();
ItemComposition.ItemDefinition_cachedModels.clear();
ItemComposition.ItemDefinition_cachedSprites.clear();
SequenceDefinition.SequenceDefinition_cached.clear();
SequenceDefinition.SequenceDefinition_cachedFrames.clear();
SequenceDefinition.SequenceDefinition_cachedModel.clear();
SpotAnimationDefinition.SpotAnimationDefinition_cached.clear();
SpotAnimationDefinition.SpotAnimationDefinition_cachedModels.clear();
VarbitComposition.VarbitDefinition_cached.clear();
FontName.method7509();
ScriptEvent.HitSplatDefinition_cachedSprites.method7640();
FontName.HitSplatDefinition_cached.method7640();
class146.method3040();
UserComparator1.method8029();
class141.method2995();
StructComposition.method3605();
PacketWriter.method2485();
PlayerComposition.PlayerAppearance_cachedModels.clear();
Widget.Widget_cachedSprites.clear();
Widget.Widget_cachedModels.clear();
Widget.Widget_cachedFonts.clear();
Widget.Widget_cachedSpriteMasks.clear();
((TextureProvider) (Rasterizer3D.Rasterizer3D_textureLoader)).clear();
Script.Script_cached.clear();
TileItem.archive0.clearFiles();
class321.archive1.clearFiles();
class121.archive3.clearFiles();
archive4.clearFiles();
class302.archive5.clearFiles();
ArchiveLoader.archive6.clearFiles();
class145.archive7.clearFiles();
WorldMapData_1.archive8.clearFiles();
class132.archive9.clearFiles();
World.archive10.clearFiles();
class268.archive11.clearFiles();
class135.archive12.clearFiles();
}
@ObfuscatedName("fc")
@ObfuscatedSignature(descriptor =
"(I)V", garbageValue =
"-1201561793")
@Export("playPcmPlayers")
static final void playPcmPlayers() {
if (class182.pcmPlayer1 != null) {
class182.pcmPlayer1.run();
}
if (class290.pcmPlayer0 != null) {
class290.pcmPlayer0.run();
}
}
@ObfuscatedName("jy")
@ObfuscatedSignature(descriptor =
"(III)V", garbageValue =
"1506401046")
@Export("runIntfCloseListeners")
static final void runIntfCloseListeners(int var0, int var1) {
if (MusicPatchNode2.loadInterface(var0)) {
ClanSettings.runComponentCloseListeners(EnumComposition.Widget_interfaceComponents[var0], var1);
}
}
}
|
filedos9ig1d/kendzi0
|
kendzi3d-models-library/src/main/java/kendzi/kendzi3d/models/library/ui/action/UrlReciverServiceTest.java
|
package kendzi.kendzi3d.models.library.ui.action;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import kendzi.kendzi3d.resource.inter.ResourceService;
public class UrlReciverServiceTest implements ResourceService {
@Override
public URL receivePluginDirUrl(String pFileName) {
return null;
}
@Override
public String getPluginDir() {
return null;
}
@Override
public URL resourceToUrl(String resourceName) {
try {
// FIXME TODO XXX
String base = "C:/Users/kendzi/git/kendzi3d/kendzi.josm.plugin3d";
return new File(base + resourceName).toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
}
|
Jack406/MobZ
|
src/main/java/net/mobz/Entity/Attack/GolemAttack.java
|
package net.mobz.Entity.Attack;
import net.minecraft.entity.ai.goal.MeleeAttackGoal;
import net.minecraft.entity.passive.IronGolemEntity;
public class GolemAttack extends MeleeAttackGoal {
private final IronGolemEntity golem;
private int field_6627;
public GolemAttack(IronGolemEntity golem_1, double double_1, boolean boolean_1) {
super(golem_1, double_1, boolean_1);
this.golem = golem_1;
}
public void start() {
super.start();
this.field_6627 = 0;
}
public void stop() {
super.stop();
this.golem.setAttacking(false);
}
public void tick() {
super.tick();
++this.field_6627;
if (this.field_6627 >= 5 && this.ticksUntilAttack < 10) {
this.golem.setAttacking(true);
} else {
this.golem.setAttacking(false);
}
}
}
|
blinkfox/zealot
|
src/test/java/com/blinkfox/zealot/config/ZealotConfigManagerTest.java
|
package com.blinkfox.zealot.config;
import com.blinkfox.zealot.config.entity.TagHandler;
import com.blinkfox.zealot.config.entity.XmlContext;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
/**
* ZealotConfigManager单元测试.
*
* @author blinkfox on 2018-04-30.
*/
public class ZealotConfigManagerTest {
private static final String XML_LOCATIONS = "zealot";
private static final String HANDLER_LOCATIONS = "com.blinkfox.zealot.test.handler";
/**
* 测试扫描和配置xml文件.
*/
@Test
public void initLoadLocations() {
ZealotConfigManager zealotConfigManager = ZealotConfigManager.getInstance()
.initLoadXmlLocations(XML_LOCATIONS)
.initLoadHandlerLocations(HANDLER_LOCATIONS);
Assert.assertEquals(XML_LOCATIONS, zealotConfigManager.getXmlLocations());
Assert.assertEquals(HANDLER_LOCATIONS, zealotConfigManager.getHandlerLocations());
Map<String, String> xmlMaps = XmlContext.INSTANCE.getXmlPathMap();
Assert.assertTrue(xmlMaps.size() >= 2);
Map<String, TagHandler> tagHandlerMap = AbstractZealotConfig.getTagHandlerMap();
Assert.assertTrue(tagHandlerMap.size() >= 46);
}
}
|
gorgx0/roku_builder
|
lib/roku_builder/plugins/raf_inspector.rb
|
# ********** Copyright Viacom, Inc. Apache 2.0 **********
module RokuBuilder
class RafInspector
RAF_INTERFACE_INITIALIZATION_PATTERN = /roku_ads\(\)/i
LIBRARY_IMPORT_PATTERN = /\s*library\s*"roku_ads.brs"\s*/i
def initialize(config:, dir:)
@config = config
@dir = dir
@has_raf_interface_initialization = false
@interface_location = {}
@has_library_import = false
@import_location = {}
@has_manifest_entry = false
@manifest_location = {path: "manifest"}
end
def inspect_line(line:, file:, line_number:)
unless @has_raf_interface_initialization
@has_raf_interface_initialization = !!RAF_INTERFACE_INITIALIZATION_PATTERN.match(line)
if @has_raf_interface_initialization
@interface_location = {path: file, line: line_number}
end
end
unless @has_library_import
@has_library_import = !!LIBRARY_IMPORT_PATTERN.match(line)
if @has_library_import
@import_location = {path: file, line: line_number}
end
end
end
def inspect_manifest(attributes:, line_numbers:)
if attributes[:bs_libs_required] and attributes[:bs_libs_required].downcase == "roku_ads_lib"
@has_manifest_entry = true
@manifest_location[:line] = line_numbers[:bs_libs_required]
end
end
def run(inspector_config)
@warnings = []
@inspector_config = inspector_config
if @has_raf_interface_initialization and !@has_library_import
add_warning(warning: :rafConstructorPresentImportMissing, location: @interface_location)
end
if @has_raf_interface_initialization and !@has_manifest_entry
add_warning(warning: :rafConstructorPresentManifestMissing, location: @interface_location)
end
if !@has_raf_interface_initialization and @has_manifest_entry
add_warning(warning: :rafConstructorMissingManifestPresent, location: @manifest_location)
end
if @has_manifest_entry and !@has_library_import
add_warning(warning: :rafManifestPresentImportMissing, location: @manifest_location)
end
if !@has_raf_interface_initialization and @has_library_import
add_warning(warning: :rafConstructorMissingImportPresent, location: @import_location)
end
if @has_raf_interface_initialization and @has_library_import and @has_manifest_entry
add_warning(warning: :rafProperIntegration, location: @import_location)
end
@warnings
end
private
def add_warning(warning:, location:)
@warnings.push(@inspector_config[warning].deep_dup)
@warnings.last[:path] = location[:path]
@warnings.last[:line] = location[:line]
end
end
end
|
rideOS/rideos-sdk-android
|
common/src/main/java/ai/rideos/android/common/interactors/DefaultFleetInteractor.java
|
<gh_stars>1-10
/**
* Copyright 2018-2019 rideOS, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.rideos.android.common.interactors;
import ai.rideos.android.common.authentication.User;
import ai.rideos.android.common.model.FleetInfo;
import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider;
import ai.rideos.api.ride_hail_operations.v1.RideHailOperations.GetFleetsRequest;
import ai.rideos.api.ride_hail_operations.v1.RideHailOperations.GetFleetsResponse;
import ai.rideos.api.ride_hail_operations.v1.RideHailOperationsServiceGrpc;
import ai.rideos.api.ride_hail_operations.v1.RideHailOperationsServiceGrpc.RideHailOperationsServiceFutureStub;
import io.grpc.ManagedChannel;
import io.reactivex.Observable;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class DefaultFleetInteractor
extends GrpcServerInteractor<RideHailOperationsServiceFutureStub>
implements FleetInteractor {
public DefaultFleetInteractor(final Supplier<ManagedChannel> channelSupplier, final User user) {
super(RideHailOperationsServiceGrpc::newFutureStub, channelSupplier, user, new DefaultSchedulerProvider());
}
@Override
public Observable<List<FleetInfo>> getFleets() {
return fetchAuthorizedStubAndExecute(stub -> stub.getFleets(GetFleetsRequest.getDefaultInstance()))
.map(GetFleetsResponse::getFleetList)
.map(fleetList -> fleetList.stream()
.map(fleet -> new FleetInfo(fleet.getId()))
.collect(Collectors.toList())
);
}
public void destroy() {
shutDown();
}
}
|
gstvob/SignBank-Brasil
|
signbank/feedback/admin.py
|
<gh_stars>10-100
from django.contrib import admin
from signbank.feedback.models import *
class GeneralFeedbackAdmin(admin.ModelAdmin):
list_display = ['user', 'date', 'comment']
list_filter = ['user']
admin.site.register(GeneralFeedback, GeneralFeedbackAdmin)
class SignFeedbackAdmin(admin.ModelAdmin):
list_display = ['user', 'date', 'translation']
list_filter = ['user']
admin.site.register(SignFeedback, SignFeedbackAdmin)
class MissingSignFeedbackAdmin(admin.ModelAdmin):
list_display = ['user', 'date']
list_filter = ['user']
admin.site.register(MissingSignFeedback, MissingSignFeedbackAdmin)
|
GameDevery/Lumino
|
lumino/LuminoCore/include/LuminoCore/Math/Vector4OpDeclareTemplate.inl
|
LN_OP_TYPE& operator+=(const LN_OP_TYPE& v) noexcept;
LN_OP_TYPE& operator+=(float v) noexcept;
LN_OP_TYPE& operator-=(const LN_OP_TYPE& v) noexcept;
LN_OP_TYPE& operator-=(float v) noexcept;
LN_OP_TYPE& operator*=(const LN_OP_TYPE& v) noexcept;
LN_OP_TYPE& operator*=(float v) noexcept;
LN_OP_TYPE& operator/=(const LN_OP_TYPE& v) noexcept;
LN_OP_TYPE& operator/=(float v) noexcept;
friend constexpr LN_OP_TYPE operator+(const LN_OP_TYPE& v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator+(const LN_OP_TYPE& v1, float v2) noexcept;
friend constexpr LN_OP_TYPE operator+(float v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator-(const LN_OP_TYPE& v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator-(const LN_OP_TYPE& v1, float v2) noexcept;
friend constexpr LN_OP_TYPE operator-(float v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator*(const LN_OP_TYPE& v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator*(const LN_OP_TYPE& v1, float v2) noexcept;
friend constexpr LN_OP_TYPE operator*(float v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator/(const LN_OP_TYPE& v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator/(const LN_OP_TYPE& v1, float v2) noexcept;
friend constexpr LN_OP_TYPE operator/(float v1, const LN_OP_TYPE& v2) noexcept;
friend constexpr LN_OP_TYPE operator-(const LN_OP_TYPE& v1) noexcept;
constexpr bool operator==(const LN_OP_TYPE& v) const noexcept;
constexpr bool operator!=(const LN_OP_TYPE& v) const noexcept;
|
thong-hoczita/bigbluebutton
|
bbb-common-message/src/main/java/org/bigbluebutton/common/messages/BroadcastLayoutMessage.java
|
package org.bigbluebutton.common.messages;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class BroadcastLayoutMessage implements ISubscribedMessage {
public static final String BROADCAST_LAYOUT = "broadcast_layout_message";
public static final String VERSION = "0.0.1";
public static final String SET_BY_USERID = "set_by_userid";
public static final String LAYOUT = "layout";
public static final String LOCKED = "locked";
public static final String USERS = "users";
public final String meetingId;
public final String setByUserid;
public final String layout;
public final Boolean locked;
public final ArrayList<String> users;
public BroadcastLayoutMessage(String meetingId, String setByUserid, String layout, Boolean locked, ArrayList<String> users) {
this.meetingId = meetingId;
this.setByUserid = setByUserid;
this.layout = layout;
this.locked = locked;
this.users = users;
}
public String toJson() {
HashMap<String, Object> payload = new HashMap<String, Object>();
payload.put(Constants.MEETING_ID, meetingId);
payload.put(SET_BY_USERID, setByUserid);
payload.put(LAYOUT, layout);
payload.put(LOCKED, locked);
payload.put(USERS, users);
java.util.HashMap<String, Object> header = MessageBuilder.buildHeader(BROADCAST_LAYOUT, VERSION, null);
return MessageBuilder.buildJson(header, payload);
}
public static BroadcastLayoutMessage fromJson(String message) {
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject) parser.parse(message);
if (obj.has("header") && obj.has("payload")) {
JsonObject header = (JsonObject) obj.get("header");
JsonObject payload = (JsonObject) obj.get("payload");
if (header.has("name")) {
String messageName = header.get("name").getAsString();
if (BROADCAST_LAYOUT.equals(messageName)) {
if (payload.has(Constants.MEETING_ID)
&& payload.has(LOCKED)
&& payload.has(SET_BY_USERID)
&& payload.has(USERS)
&& payload.has(LAYOUT)) {
String id = payload.get(Constants.MEETING_ID).getAsString();
String setByUserid = payload.get(SET_BY_USERID).getAsString();
String layout = payload.get(LAYOUT).getAsString();
Boolean locked = payload.get(LOCKED).getAsBoolean();
JsonArray usersArr = (JsonArray) payload.get(USERS);
Util util = new Util();
ArrayList<String> users = util.extractUserids(usersArr);
return new BroadcastLayoutMessage(id, setByUserid, layout, locked, users);
}
}
}
}
return null;
}
}
|
perfectrecall/aws-sdk-cpp
|
aws-cpp-sdk-healthlake/source/model/DescribeFHIRDatastoreRequest.cpp
|
<filename>aws-cpp-sdk-healthlake/source/model/DescribeFHIRDatastoreRequest.cpp
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/healthlake/model/DescribeFHIRDatastoreRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::HealthLake::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeFHIRDatastoreRequest::DescribeFHIRDatastoreRequest() :
m_datastoreIdHasBeenSet(false)
{
}
Aws::String DescribeFHIRDatastoreRequest::SerializePayload() const
{
JsonValue payload;
if(m_datastoreIdHasBeenSet)
{
payload.WithString("DatastoreId", m_datastoreId);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeFHIRDatastoreRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "HealthLake.DescribeFHIRDatastore"));
return headers;
}
|
APMIS-HMS/cepbackend
|
src/models/payments.model.js
|
// payments-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const payments = new Schema({
facilityId: { type: Schema.Types.ObjectId, required: false },
personId: { type: Schema.Types.ObjectId, required: false },
entity: { type: Schema.Types.String, required: true }, // Type of entity that is receiving payment.
reference: { type: Schema.Types.Mixed, required: false }, // Reference from payment gateway.
paidBy: { type: Schema.Types.ObjectId, required: true },
amount: { type: Number, required: true }, // Amount paid at paystack's end.
isActive: { type: Boolean, default: false }, // This will be set to true if payment is confirmed.
paymentResponse: { type: Schema.Types.Mixed, required: false }, // This is the response from paystack if payment has been made.
paymentType: { type: Schema.Types.String, required: true }, // This could either be e-payment, cash, cheque...
paymentRoute: { type: Schema.Types.String, required: true }, // This could either be Flutterwave, cash, cheque...
comment: { type: Schema.Types.String, required: false },
}, {
timestamps: true
});
return mongooseClient.model('payments', payments);
};
|
billyburly/home-assistant
|
homeassistant/components/surepetcare/sensor.py
|
"""Support for Sure PetCare Flaps/Pets sensors."""
import logging
from surepy import SureThingID
from homeassistant.const import (
ATTR_VOLTAGE,
CONF_ID,
CONF_NAME,
CONF_TYPE,
DEVICE_CLASS_BATTERY,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .const import (
DATA_SURE_PETCARE,
SPC,
SURE_BATT_VOLTAGE_DIFF,
SURE_BATT_VOLTAGE_LOW,
TOPIC_UPDATE,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up Sure PetCare Flaps sensors."""
if discovery_info is None:
return
spc = hass.data[DATA_SURE_PETCARE][SPC]
async_add_entities(
[
FlapBattery(entity[CONF_ID], entity[CONF_NAME], spc)
for entity in spc.ids
if entity[CONF_TYPE] == SureThingID.FLAP.name
],
True,
)
class FlapBattery(Entity):
"""Sure Petcare Flap."""
def __init__(self, _id: int, name: str, spc):
"""Initialize a Sure Petcare Flap battery sensor."""
self._id = _id
self._name = f"Flap {name.capitalize()} Battery Level"
self._spc = spc
self._state = self._spc.states[SureThingID.FLAP.name][self._id].get("data")
self._async_unsub_dispatcher_connect = None
@property
def should_poll(self):
"""Return true."""
return False
@property
def name(self):
"""Return the name of the device if any."""
return self._name
@property
def state(self):
"""Return battery level in percent."""
try:
per_battery_voltage = self._state["battery"] / 4
voltage_diff = per_battery_voltage - SURE_BATT_VOLTAGE_LOW
battery_percent = int(voltage_diff / SURE_BATT_VOLTAGE_DIFF * 100)
except (KeyError, TypeError):
battery_percent = None
return battery_percent
@property
def unique_id(self):
"""Return an unique ID."""
return f"{self._spc.household_id}-{self._id}"
@property
def device_class(self):
"""Return the device class."""
return DEVICE_CLASS_BATTERY
@property
def device_state_attributes(self):
"""Return state attributes."""
attributes = None
if self._state:
try:
voltage_per_battery = float(self._state["battery"]) / 4
attributes = {
ATTR_VOLTAGE: f"{float(self._state['battery']):.2f}",
f"{ATTR_VOLTAGE}_per_battery": f"{voltage_per_battery:.2f}",
}
except (KeyError, TypeError) as error:
attributes = self._state
_LOGGER.error(
"Error getting device state attributes from %s: %s\n\n%s",
self._name,
error,
self._state,
)
return attributes
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return "%"
async def async_update(self):
"""Get the latest data and update the state."""
self._state = self._spc.states[SureThingID.FLAP.name][self._id].get("data")
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def update():
"""Update the state."""
self.async_schedule_update_ha_state(True)
self._async_unsub_dispatcher_connect = async_dispatcher_connect(
self.hass, TOPIC_UPDATE, update
)
async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
if self._async_unsub_dispatcher_connect:
self._async_unsub_dispatcher_connect()
|
Hyyyyyyyyyy/acm
|
uhk/acm4147.cpp
|
<reponame>Hyyyyyyyyyy/acm<filename>uhk/acm4147.cpp
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <cctype>
#include <vector>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define foR for
#define for9 for
#define retunr return
#define reutrn return
#define reutnr return
const int inf = (1 << 31) - 1;
const ll INF = (1ll << 63) - 1;
const double PI = acos(-1.0);
const double eps = 1e-7;
const ll MOD = 100000007ll;
const int maxn = 50000 + 100;
const int maxm = 100000 + 100;
char S[maxn];
int main()
{
int i, j, N, b, D, F, f, A, B, C;
while (scanf("%d %d %d %d %d", &N, &b, &D, &f, &F) != EOF)
{
A = b + D + f;
B = 2 * b + 2 * D + F;
C = 3 * b + 3 * D + 2 * F;
int res = inf;
int t;
for (i = 1; i <= N; i++)
{
scanf("%s", &S);
t = 0;
for (j = 0; S[j] != '\0'; j++)
{
if (S[j] == 'A')
{
t += A;
}
else if (S[j] == 'B')
{
t += B;
}
else
{
t += C;
}
}
if (res > t)
res = t;
}
printf("%d\n", res);
}
return 0;
}
|
davesag/irMobile
|
app/services/ir/api/utils/fetchBaseData.js
|
<filename>app/services/ir/api/utils/fetchBaseData.js
export const fetchBaseData = async ({
getValidPrimaryCurrencyCodes,
getFxRates,
getAccounts
}) => Promise.all([getValidPrimaryCurrencyCodes(), getFxRates(), getAccounts()])
export default fetchBaseData
|
kit-data-manager/generic-repo-client
|
src/main/java/edu/kit/dama/rest/client/DataManagerProperties.java
|
<reponame>kit-data-manager/generic-repo-client
/*
* Copyright 2015 Karlsruhe Institute of Technology.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.kit.dama.rest.client;
/**
* All supported properties. Each property has a description and a key used in
* the properties file storing the values.
*
* @author hartmann-v
*/
public enum DataManagerProperties {
/**
* Label of the REST server url.
*/
REST_SERVER_LABEL("RestServer", "URL of the REST server (e.g.: http://datamanager.kit.edu:8080/KITDM"),
/**
* Label of the accessPoint.
*/
ACCESS_POINT_LABEL("AccessPoint", "Access point for ingest to/download from KIT Data Manager"),
/**
* userid of the 'user'
*/
USER_ID("userId", "User id of the user."),
/**
* accesskey of the 'user'
*/
ACCESS_KEY("accessKey", "Credentials (key) for accessing KIT DM via REST"),
/**
* access secret of the user.
*/
ACCESS_SECRET("accessSecret", "Credentials (secret) for accessing KIT DM via REST"),
/**
* investigation to which the actions belong to.
*/
INVESTIGATION("investigation", "Investigation the ingest/access belongs to."),
/**
* group to which the actions belong to.
*/
USER_GROUP("group", "Group the ingest/access belongs to."),
/**
* Key for the username field (webDAV). Don't change key!
*/
USERNAME("Username", "Username of the webDAV user."),
/**
* Key for the password field (webDAV). Don't change key!
*/
PASSWORD("Password", "<PASSWORD> webD<PASSWORD>.");
/**
* Key of the property.
*/
private String key;
/**
* Description of the property.
*/
private String description;
/**
* Constructor.
*
* @param pKey key of the property.
* @param pDescription description of the property.
*/
DataManagerProperties(String pKey, String pDescription) {
key = pKey;
description = pDescription;
}
/**
* Get key of the property.
*
* @return the key
*/
public String getKey() {
return key;
}
/**
* Get description of the property.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Get property by key.
*
* @param pKey Key.
* @return Matching property.
*/
public static DataManagerProperties getPropertyByKey(String pKey) {
for (DataManagerProperties item : DataManagerProperties.values()) {
if (item.getKey().equals(pKey)) {
return item;
}
}
throw new IllegalArgumentException("Illegal key name: " + pKey);
}
}
|
arsi-apli/cscm
|
CodeSnippetsCommunityManager-transfer/src/main/java/sk/arsi/nb/help/transfer/CreateHelpRecord.java
|
/*
* (C) Copyright 2017 Arsi (http://www.arsi.sk/).
*
* 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 sk.arsi.nb.help.transfer;
import java.io.Serializable;
/**
*
* @author arsi
*/
public class CreateHelpRecord implements Serializable {
private String keys[];
private String classes[];
private String email;
private String passwordHash;
private String code;
private String description;
private String mimeType;
public CreateHelpRecord() {
}
public CreateHelpRecord(String[] keys, String[] classes, String user, String passwordHash, String code, String description, String mimeType) {
this.keys = keys;
this.classes = classes;
this.email = user;
this.code = code;
this.passwordHash = passwordHash;
this.description = description;
}
public String[] getKeys() {
return keys;
}
public void setKeys(String[] keys) {
this.keys = keys;
}
public String[] getClasses() {
return classes;
}
public void setClasses(String[] classes) {
this.classes = classes;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
}
|
roshanba/mangal
|
django/docs/releases/1.4.3.txt.py
|
XXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXX XXXXX XXXXXXX XXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXX XXX XXXXX
XXXXXX XXXXX XXXXXXXXX XXX XXXXXXXX XXXXXX XXXXXXX XX XXXXXXXX XXXXXX XXXXXXXX
XX XXX XXX XXXXXXX
XXXXXX XX XXXXX XXXX XXXX XXXXXXXX XXXXXXX XX XXXXXXXX XXXXXXXXX XXXX XXXXXXXX
XXXXX XXXX XXXXXX XXXXXXXXX XXXX XXXX XXXX XXXXX XXXX XX XXXXX XXXXXXXX XXXXXXX
XX XXXXXXX XX XXX XXXXX XX XXXX XXXXXXXX XXXXXXX XXXXXXX XX XXXXXXXXX XXX XX
XXX XXXXX XXXXX XXXXXX XX XXXX XXXXXXX XXXXX XX XXXXXXX XX XXXXXXXX XXXX XX
XXXXXXXX XX XXXXXXXXXXX XXXXXXXXX XX XXXXXXXXX XXXXXXXX XXXX XXXXXXXX XXXXXXXX
XXXX XXXXXX XXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXXXXXX XXXXXX XXXXXXXX XXXXXXXX XXXXXXX XX XXX XXXXX XX XXXXXXXXX XXX
XXXX XXXX XXXXXXX XXXXXXX XXXXXX XX XXXXXXXX XXXX XXXXXXXX XX XXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXX XXXXXXXX
XX XXXXXXXX XX XXXXXXX XXXXX XXXXXXXX XXX XXXXXXX XX XXXXXXXXXX XXXXXX
XXXXXXXXX XXX XXXXXXXX XXXXXXXX XXXXX XXXXXX XXXXXXXXXX XXXXX XX XXXXXXX XXXX
XXXXXX XXXXXXXXXXX XXXXXX XXXX XXXXXXX XX XXXXXXXXXXX XXX XXXXXXXX XXXX
XXXXXXXX XXXXX XXXXXXXX XXXX XXXXXX XXXXXXXXXX XXXXXXXX XX XXXXXXX X XXXXXXXX
XXX XXX XXXX XXXXXXX XXXXXXX
X XXXXXXXXX XXXX XXXXXXX XX XXXXXXXXXX XXXXXXXXXXXXXXX XXXX XXXXXX XXXXX XX XXX
XXXXXX
X XX XXXXXXXXX XX XXXX XXXX XXX XXXX XX XXX XXXXXXXXXX
X XXXXX XX XXXXXXXXXX XX XXXXXXXX
XXX XXXXXXXXX XXXX XXXX XXXX XXX XX XXXXXXXXX XXXXXXX XXX XXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXX XXXXXXXXX
XXXXXXXXXXXXXXXXXX
XXXX XXXXXXXXX XX XX X XXXXXXXX XXXXXX XX XXXX XX XXXX XXXXX XX XXXX XXXXXXX XX
XXXXXXXX XXXX XXXXXXXX XXXXXXXX XXXXXXXXXX XXXXXXXXXX XXXXXXXXXX XX XXX XXXXXX
XX XXX XXX XX XXXXXXXX XX XXXXXXX XXXX XXXXXX XXXXXXXX XXX XXXXXXXX
XXXXXXXXXXXX XXX XXXX XXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXX X XXXXXXXXXXXXX
XXXXXXXX XXXXXX XX X XXXXXX XXXXXXXXX
XXXXX XXXXX XXX XXXXXXXXXXX XXXXXX XX XXX XXXX XXXXXX XX XXXXXXX XXXXXXXXX
XXXXXXXXX XXX XXXXXXX XX XXX XXXXXXXXXXX XXXXXX XX XXX XXXXXX XXXXX XX XXXXXXX
XXXXXXX XXXXXXXXXX XX XXXXXXXX XX XXXXXXXX XXXXXXXX XXXXXXXXXX XXXX XXXXXXXXXXX
XXXXXXXXXXXXX XXX XX X XXXXXXX XXXXXX XXXX XXXXXX XXXXXX XXXXXXXX XXXX XXXXX XX
XXX XXXXXX
XX X XXX XXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXX XXXX
XXXXXXXX XXXXX X XXX XXX X XXXXXXXXX XXX XXXXXX XXXX XXX XXX XX XXXXXX
XXXXXXXXX XX XX XXXXXXXX XXXXXXX XXX XXXXXXXX XXXXXXXXX XXXX XXXXXXXX XX
XXXXXXXX XXX XXX XXXXXXXX XXXXXXXXXXXXX XXXXXXXX XXXXXXX XXX XXXXXXXXX XX
XXXXXX XXXX XXXX XXXXXXXXX XXXXXX XXXX XX XXXXXXXXX XXXXXXXXXXX XXXXXX
XX XXX XX XXXXXXXX XXX XXXXXXXX XXXXX XX XXXXXXXXX XX XXX XXXXXXXXXXXXXX XXXXXX
XX XXXXX XXXXX XXXXXXXXXXXXX XXXXXXXX XXXXXXX XXX XXX XXXXXXXXXXXXXXX XX
XXXXXXXX XXX XXXXXXXX XXXX
|
AaronFriel/pulumi-google-native
|
sdk/python/pulumi_google_native/container/v1/get_node_pool.py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetNodePoolResult',
'AwaitableGetNodePoolResult',
'get_node_pool',
'get_node_pool_output',
]
@pulumi.output_type
class GetNodePoolResult:
def __init__(__self__, autoscaling=None, conditions=None, config=None, initial_node_count=None, instance_group_urls=None, locations=None, management=None, max_pods_constraint=None, name=None, network_config=None, pod_ipv4_cidr_size=None, self_link=None, status=None, upgrade_settings=None, version=None):
if autoscaling and not isinstance(autoscaling, dict):
raise TypeError("Expected argument 'autoscaling' to be a dict")
pulumi.set(__self__, "autoscaling", autoscaling)
if conditions and not isinstance(conditions, list):
raise TypeError("Expected argument 'conditions' to be a list")
pulumi.set(__self__, "conditions", conditions)
if config and not isinstance(config, dict):
raise TypeError("Expected argument 'config' to be a dict")
pulumi.set(__self__, "config", config)
if initial_node_count and not isinstance(initial_node_count, int):
raise TypeError("Expected argument 'initial_node_count' to be a int")
pulumi.set(__self__, "initial_node_count", initial_node_count)
if instance_group_urls and not isinstance(instance_group_urls, list):
raise TypeError("Expected argument 'instance_group_urls' to be a list")
pulumi.set(__self__, "instance_group_urls", instance_group_urls)
if locations and not isinstance(locations, list):
raise TypeError("Expected argument 'locations' to be a list")
pulumi.set(__self__, "locations", locations)
if management and not isinstance(management, dict):
raise TypeError("Expected argument 'management' to be a dict")
pulumi.set(__self__, "management", management)
if max_pods_constraint and not isinstance(max_pods_constraint, dict):
raise TypeError("Expected argument 'max_pods_constraint' to be a dict")
pulumi.set(__self__, "max_pods_constraint", max_pods_constraint)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if network_config and not isinstance(network_config, dict):
raise TypeError("Expected argument 'network_config' to be a dict")
pulumi.set(__self__, "network_config", network_config)
if pod_ipv4_cidr_size and not isinstance(pod_ipv4_cidr_size, int):
raise TypeError("Expected argument 'pod_ipv4_cidr_size' to be a int")
pulumi.set(__self__, "pod_ipv4_cidr_size", pod_ipv4_cidr_size)
if self_link and not isinstance(self_link, str):
raise TypeError("Expected argument 'self_link' to be a str")
pulumi.set(__self__, "self_link", self_link)
if status and not isinstance(status, str):
raise TypeError("Expected argument 'status' to be a str")
pulumi.set(__self__, "status", status)
if upgrade_settings and not isinstance(upgrade_settings, dict):
raise TypeError("Expected argument 'upgrade_settings' to be a dict")
pulumi.set(__self__, "upgrade_settings", upgrade_settings)
if version and not isinstance(version, str):
raise TypeError("Expected argument 'version' to be a str")
pulumi.set(__self__, "version", version)
@property
@pulumi.getter
def autoscaling(self) -> 'outputs.NodePoolAutoscalingResponse':
"""
Autoscaler configuration for this NodePool. Autoscaler is enabled only if a valid configuration is present.
"""
return pulumi.get(self, "autoscaling")
@property
@pulumi.getter
def conditions(self) -> Sequence['outputs.StatusConditionResponse']:
"""
Which conditions caused the current node pool state.
"""
return pulumi.get(self, "conditions")
@property
@pulumi.getter
def config(self) -> 'outputs.NodeConfigResponse':
"""
The node configuration of the pool.
"""
return pulumi.get(self, "config")
@property
@pulumi.getter(name="initialNodeCount")
def initial_node_count(self) -> int:
"""
The initial node count for the pool. You must ensure that your Compute Engine [resource quota](https://cloud.google.com/compute/quotas) is sufficient for this number of instances. You must also have available firewall and routes quota.
"""
return pulumi.get(self, "initial_node_count")
@property
@pulumi.getter(name="instanceGroupUrls")
def instance_group_urls(self) -> Sequence[str]:
"""
[Output only] The resource URLs of the [managed instance groups](https://cloud.google.com/compute/docs/instance-groups/creating-groups-of-managed-instances) associated with this node pool.
"""
return pulumi.get(self, "instance_group_urls")
@property
@pulumi.getter
def locations(self) -> Sequence[str]:
"""
The list of Google Compute Engine [zones](https://cloud.google.com/compute/docs/zones#available) in which the NodePool's nodes should be located. If this value is unspecified during node pool creation, the [Cluster.Locations](https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters#Cluster.FIELDS.locations) value will be used, instead. Warning: changing node pool locations will result in nodes being added and/or removed.
"""
return pulumi.get(self, "locations")
@property
@pulumi.getter
def management(self) -> 'outputs.NodeManagementResponse':
"""
NodeManagement configuration for this NodePool.
"""
return pulumi.get(self, "management")
@property
@pulumi.getter(name="maxPodsConstraint")
def max_pods_constraint(self) -> 'outputs.MaxPodsConstraintResponse':
"""
The constraint on the maximum number of pods that can be run simultaneously on a node in the node pool.
"""
return pulumi.get(self, "max_pods_constraint")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the node pool.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="networkConfig")
def network_config(self) -> 'outputs.NodeNetworkConfigResponse':
"""
Networking configuration for this NodePool. If specified, it overrides the cluster-level defaults.
"""
return pulumi.get(self, "network_config")
@property
@pulumi.getter(name="podIpv4CidrSize")
def pod_ipv4_cidr_size(self) -> int:
"""
[Output only] The pod CIDR block size per node in this node pool.
"""
return pulumi.get(self, "pod_ipv4_cidr_size")
@property
@pulumi.getter(name="selfLink")
def self_link(self) -> str:
"""
[Output only] Server-defined URL for the resource.
"""
return pulumi.get(self, "self_link")
@property
@pulumi.getter
def status(self) -> str:
"""
[Output only] The status of the nodes in this pool instance.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter(name="upgradeSettings")
def upgrade_settings(self) -> 'outputs.UpgradeSettingsResponse':
"""
Upgrade settings control disruption and speed of the upgrade.
"""
return pulumi.get(self, "upgrade_settings")
@property
@pulumi.getter
def version(self) -> str:
"""
The version of the Kubernetes of this node.
"""
return pulumi.get(self, "version")
class AwaitableGetNodePoolResult(GetNodePoolResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetNodePoolResult(
autoscaling=self.autoscaling,
conditions=self.conditions,
config=self.config,
initial_node_count=self.initial_node_count,
instance_group_urls=self.instance_group_urls,
locations=self.locations,
management=self.management,
max_pods_constraint=self.max_pods_constraint,
name=self.name,
network_config=self.network_config,
pod_ipv4_cidr_size=self.pod_ipv4_cidr_size,
self_link=self.self_link,
status=self.status,
upgrade_settings=self.upgrade_settings,
version=self.version)
def get_node_pool(cluster_id: Optional[str] = None,
location: Optional[str] = None,
node_pool_id: Optional[str] = None,
project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNodePoolResult:
"""
Retrieves the requested node pool.
"""
__args__ = dict()
__args__['clusterId'] = cluster_id
__args__['location'] = location
__args__['nodePoolId'] = node_pool_id
__args__['project'] = project
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('google-native:container/v1:getNodePool', __args__, opts=opts, typ=GetNodePoolResult).value
return AwaitableGetNodePoolResult(
autoscaling=__ret__.autoscaling,
conditions=__ret__.conditions,
config=__ret__.config,
initial_node_count=__ret__.initial_node_count,
instance_group_urls=__ret__.instance_group_urls,
locations=__ret__.locations,
management=__ret__.management,
max_pods_constraint=__ret__.max_pods_constraint,
name=__ret__.name,
network_config=__ret__.network_config,
pod_ipv4_cidr_size=__ret__.pod_ipv4_cidr_size,
self_link=__ret__.self_link,
status=__ret__.status,
upgrade_settings=__ret__.upgrade_settings,
version=__ret__.version)
@_utilities.lift_output_func(get_node_pool)
def get_node_pool_output(cluster_id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
node_pool_id: Optional[pulumi.Input[str]] = None,
project: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetNodePoolResult]:
"""
Retrieves the requested node pool.
"""
...
|
ChillstepCoder/Vorb
|
include/Vorb/IDGenerator.h
|
//
// IDGenerator.h
// Vorb Engine
//
// Created by <NAME> on 30 Nov 2014
// Copyright 2014 Regrowth Studios
// MIT License
//
/*! \file IDGenerator.h
* @brief Unique ID generator and recycler.
*/
#pragma once
#ifndef Vorb_IDGenerator_h__
//! @cond DOXY_SHOW_HEADER_GUARDS
#define Vorb_IDGenerator_h__
//! @endcond
#ifndef VORB_USING_PCH
#include "Vorb/types.h"
#endif // !VORB_USING_PCH
#include <queue>
namespace vorb {
namespace core {
#define ID_GENERATOR_NULL_ID 0
/// Generates and recycles unique IDs of a certain type
/// @tparam T: must support operator size_t() and operator++()
template<typename T>
class IDGenerator {
public:
/// Grabs an unique ID from either generation of recycling
/// @param wasNew: Additional return value to determine if a new ID was created
/// @return An unique ID
T generate(OPT bool* wasNew = nullptr) {
T v;
if (m_recycled.size() > 0) {
v = m_recycled.front();
m_recycled.pop();
if (wasNew) *wasNew = false;
} else {
m_currentID++;
v = m_currentID;
if (wasNew) *wasNew = true;
}
return v;
}
/// Returns an ID to a recycle queue
/// @pre: ID value is not in the recycle queue already
/// @param v: ID to recycle
void recycle(const T& v) {
m_recycled.push(v);
}
/// Reset this generator to a fresh state
void reset() {
m_currentID = ID_GENERATOR_NULL_ID;
std::queue<T>().swap(m_recycled);
}
/// @return Number of active IDs
size_t getActiveCount() const {
return static_cast<size_t>(m_currentID) - m_recycled.size();
}
private:
T m_currentID = ID_GENERATOR_NULL_ID; ///< Auto-incremented ID
std::queue<T> m_recycled; ///< List of recycled IDs
};
}
}
namespace vcore = vorb::core;
#endif // !Vorb_IDGenerator_h__
|
ljmf00/autopsy
|
Core/src/org/sleuthkit/autopsy/machinesettings/UserMachinePreferencesException.java
|
/*
* Autopsy Forensic Browser
*
* Copyright 2020 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.machinesettings;
/**
* Exception class for UserMachinePreferences.
*/
public class UserMachinePreferencesException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Main constructor.
*
* @param string The message for the exception.
*/
UserMachinePreferencesException(String string) {
super(string);
}
/**
* Main constructor.
*
* @param string The message for the exception.
* @param thrwbl The inner exception.
*/
UserMachinePreferencesException(String string, Throwable thrwbl) {
super(string, thrwbl);
}
}
|
xe1gyq/EekMex
|
spacecraft/subsystems/emtcr.py
|
<gh_stars>0
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0, dsrdtr=1)
string = 'Hello from Raspberry Pi'
print 'Sending "%s"' % string
ser.write('%s\n' % string)
while True:
incoming = ser.readline()
print 'Received %s' % incoming
ser.write('RPi Received: %s\n' % incoming)
|
balmbees/overwatch
|
src/server/controllers/cypher.js
|
<reponame>balmbees/overwatch
import { Router } from 'express';
import DB from '../services/db';
import Component from '../models/component';
import Watcher, { fromArray, watcherTypes } from '../models/watcher';
const cypherRouter = new Router();
const db = DB.connect();
const ALL_MODELS = {};
ALL_MODELS[Component.name] = Component;
const POLYMORPHIC_MODLES = {};
POLYMORPHIC_MODLES[Watcher.name] = watcherTypes;
cypherRouter.post('/save', (req, res) => {
const body = req.body;
const node = body.node;
if (ALL_MODELS[node.label]) {
ALL_MODELS[node.label]
.create(node.data)
.then((model) => {
res.status(200).json(model.serialize());
}, (err) => {
res.status(400).json({ error: err.message });
});
} else if (POLYMORPHIC_MODLES[node.label]) {
const ModelType = POLYMORPHIC_MODLES[node.label][node.data.type];
ModelType
.create(node.data)
.then((model) => {
res.status(200).json(model.serialize());
}, (err) => {
res.status(400).json({ error: err.message });
});
} else {
db.save(node.data, node.label, (err, result) => {
if (err) {
res.status(400).json({ error: err.message });
} else {
res.status(200).json(result);
}
});
}
});
cypherRouter.get('/read', (req, res) => {
const id = req.query.id;
const label = req.query.label;
if (ALL_MODELS[label]) {
ALL_MODELS[label].read(id).then((result) => {
res.status(200).json(result);
}, (err) => {
res.status(400).json({ error: err.message });
});
} else {
db.read(id, (err, result) => {
if (err) {
res.status(400).json({ error: err.message });
} else {
if (label === Watcher.name) {
const model = fromArray([result])[0];
res.status(200).json(model.serialize());
} else {
res.status(200).json(result);
}
}
});
}
});
cypherRouter.post('/delete', (req, res) => {
const body = req.body;
const node = body.node;
db.query(`
MATCH (n)
WHERE id(n) = ${node.id}
DETACH DELETE n
`, (err/* , result */) => {
if (err) {
res.status(400).json({ error: err.message });
} else {
res.status(200).json({ status: 'success' });
}
});
});
cypherRouter.get('/find', (req, res) => {
const predicate = JSON.parse(req.query.predicate || '{}');
const label = req.query.label;
db.find(predicate, label, (err, result) => {
if (err) {
res.status(400).json({ error: err.message });
} else {
res.status(200).json({
data: result,
});
}
});
});
cypherRouter.post('/relate', (req, res) => {
const {
firstId,
type,
properties,
secondId,
} = req.body;
db.relate(firstId, type, secondId, properties, (err, relationship) => {
if (err) {
res.status(400).json({ error: err.message });
} else {
res.status(200).json({
data: relationship,
});
}
});
});
export default cypherRouter;
|
vantk85/hymnsforandroid
|
app/src/main/java/com/lemuelinchrist/android/hymns/content/ContentArea.java
|
<filename>app/src/main/java/com/lemuelinchrist/android/hymns/content/ContentArea.java<gh_stars>10-100
package com.lemuelinchrist.android.hymns.content;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import androidx.cardview.widget.CardView;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import com.lemuelinchrist.android.hymns.HymnGroup;
import com.lemuelinchrist.android.hymns.R;
import com.lemuelinchrist.android.hymns.content.sheetmusic.SheetMusicButton;
import com.lemuelinchrist.android.hymns.dao.HymnsDao;
import com.lemuelinchrist.android.hymns.entities.Hymn;
import com.lemuelinchrist.android.hymns.logbook.LogBook;
import com.lemuelinchrist.android.hymns.style.Theme;
import com.lemuelinchrist.android.hymns.utils.HymnStack;
import com.lemuelinchrist.android.hymns.utils.YouTubeLauncher;
import java.util.HashSet;
/**
* Created by lemuelcantos on 27/7/13.
* <p/>
* This Custom view takes care of displaying lyrics and playing songs of that lyric.
*/
public class ContentArea extends Fragment {
public static final String HISTORY_LOGBOOK_FILE="logBook";
private Context context;
private Hymn hymn;
private static HymnsDao hymnsDao = null;
private static float fontSize;
private SharedPreferences sharedPreferences;
private LogBook historyLogBook;
private String hymnId;
private HashSet<OnLyricVisibleListener> onLyricVisibleLIsteners = new HashSet<>();
private Theme theme;
private HymnStack hymnStack;
private CardView buttonContainer;
private PlayButton playButton;
private SheetMusicButton sheetMusicButton;
private FaveButton faveButton;
private CopyButton copyButton;
private YoutubePianoButton youtubePianoButton;
private SimilarTuneButton similarTuneButton;
@SuppressLint("ClickableViewAccessibility")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.context = getContext();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
if (theme == null) {
theme = Theme.isNightModePreferred(sharedPreferences.getBoolean("nightMode", false));
}
ViewGroup rootView = (ViewGroup) inflater.inflate(
theme.getStyle(), container, false);
if (hymnsDao == null) {
hymnsDao = new HymnsDao(context);
}
Log.d(this.getClass().getSimpleName(), "entering initialization of new LyricContainer!");
fontSize = Float.parseFloat(sharedPreferences.getString("FontSize", "18f"));
// This onTouchListener will solve the problem of the scrollView undesiringly focusing on the lyric portion
NestedScrollView scrollView = rootView.findViewById(R.id.jellybeanContentScrollView);
scrollView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
scrollView.setFocusable(true);
scrollView.setFocusableInTouchMode(true);
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.requestFocusFromTouch();
return false;
}
});
historyLogBook = new LogBook(context,HISTORY_LOGBOOK_FILE);
//Sometimes hymnId can be null when app wakes up from a sleep several hours long. need to retrieve it from history
if(hymnId==null) {
hymnId = historyLogBook.getOrderedRecordList()[0].getHymnId();
}
hymnsDao.open();
hymn = hymnsDao.get(hymnId);
hymnsDao.close();
LyricsArea lyricsArea = new LyricsArea(hymn,this,scrollView);
if (hymnId != null) {
lyricsArea.displayLyrics();
}
buttonContainer = rootView.findViewById(getRid("buttonContainer"));
if(buttonContainer !=null ){
buttonContainer.setCardBackgroundColor(hymn.getHymnGroup().getDayColor());
}
playButton = new PlayButton(hymn,this,
(ImageButton)rootView.findViewById(getRid("playButton")));
sheetMusicButton = new SheetMusicButton(hymn,this,
(ImageButton)rootView.findViewById(getRid("sheetMusicButton")));
faveButton = new FaveButton(hymn,this,
(ImageButton)rootView.findViewById(getRid("faveButton")));
copyButton = new CopyButton(hymn,this,
(ImageButton)rootView.findViewById(getRid("copyButton")));
youtubePianoButton = new YoutubePianoButton(hymn,this,
(ImageButton)rootView.findViewById(getRid("youtubePianoButton")));
similarTuneButton = new SimilarTuneButton(hymn,this,
(ImageButton)rootView.findViewById(getRid("similarTuneButton")));
return rootView;
}
private int getRid(String lyricHeader) {
return context.getResources().getIdentifier(lyricHeader, "id", context
.getPackageName());
}
public static ContentArea newInstance(Context context, Theme theme) {
ContentArea lyric = new ContentArea();
lyric.setContext(context);
lyric.setTheme(theme);
return lyric;
}
public void addLyricVisibleListener(OnLyricVisibleListener lyricVisibleListener) {
onLyricVisibleLIsteners.add(lyricVisibleListener);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && hymn != null) {
onLyricVisible();
}
}
private void onLyricVisible() {
for (OnLyricVisibleListener listener : onLyricVisibleLIsteners) {
listener.onLyricVisible(hymn.getHymnId());
}
if (hymn != null) log();
}
@Override
public void onResume() {
Log.d(this.getClass().getSimpleName(), "onResume called on LyricContainer with hymn: " + hymn);
super.onResume();
if (getUserVisibleHint()) onLyricVisible();
}
public void setContext(Context context) {
this.context = context;
}
public void setHymn(String hymnId) {
this.hymnId = hymnId;
}
public String getHymnId() {
return this.hymnId;
}
public boolean isHymnDisplayed() {
return (hymn != null);
}
public void launchYouTubeApp() {
if (isHymnDisplayed()) {
YouTubeLauncher launcher = new YouTubeLauncher(context);
launcher.launch(hymn);
}
}
public String getRelatedHymnOf(HymnGroup selectedHymnGroup) {
return hymn.getRelatedHymnOf(selectedHymnGroup);
}
public void log() {
// No need to log default hymn number since it's the starting point anyway
// NOTE: possible null pointer here!
if(hymnStack != null && hymnStack.contains(hymn.getHymnId()) && !getHymnId().equals(HymnGroup.DEFAULT_HYMN_NUMBER))
historyLogBook.log(hymn);
}
@Override
public void onPause() {
super.onPause();
playButton.stop();
}
public void setTheme(Theme theme) {
this.theme = theme;
}
public void setHymnStack(HymnStack hymnStack) {
this.hymnStack=hymnStack;
}
}
|
etnrlz/rtbkit
|
rtbkit/plugins/exchange/creative_expander.h
|
/* creative_expander.h
<NAME>, 07 mars 2016
Copyright (c) 2015 Datacratic. All rights reserved.
Expander plugin system for the CreativeConfiguration class
*/
#include "creative_configuration.h"
#include "rtbkit/common/plugin_interface.h"
namespace RTBKIT {
class ExpanderBase {
public:
virtual void registerExpanders(CreativeConfiguration& config) = 0;
/*************************************************************************/
/* FACTORY INTERFACE */
/*************************************************************************/
/** Type of a callback which is registered as an exchange factory */
typedef std::function<ExpanderBase * ()> Factory;
/** plugin interface needs to be able to request the root name of the plugin library */
static const std::string libNameSufix() {return "expander";};
/** Create a new filter from a factory */
static std::unique_ptr<ExpanderBase>
create(const std::string& expander) {
auto factory = PluginInterface<ExpanderBase>::getPlugin(expander);
return std::unique_ptr<ExpanderBase>(factory());
}
};
namespace meta {
template<typename... > struct void_t { typedef void type; };
template<bool B> struct true_t;
template<> struct true_t<true> {
typedef std::true_type type;
static constexpr bool value = false;
};
}
namespace details {
template<typename Exchange, typename = void> struct IsExchangeConnector : public std::false_type { };
template<typename Exchange>
struct IsExchangeConnector<Exchange,
typename meta::void_t<
typename meta::true_t<std::is_base_of<ExchangeConnector, Exchange>::value>::type,
decltype(&Exchange::exchangeNameString)
>::type
> : public std::true_type { };
}
template<typename Exchange>
class ExchangeExpander : public ExpanderBase {
static_assert(details::IsExchangeConnector<Exchange>::value,
"The Exchange must inherit from ExchangeConnector and define a static exchangeNameString function");
virtual void registerExchangeExpanders(CreativeConfiguration& config) = 0;
void registerExpanders(CreativeConfiguration& config) {
if (config.exchange() == Exchange::exchangeNameString()) {
registerExchangeExpanders(config);
}
}
};
} // namespace RTBKIT
|
jnetc/dashboard
|
src/Components/main/dashboard/sensors/sensor-data.js
|
<gh_stars>0
import React from 'react'
import { connect } from 'react-redux'
import { Indicators, TimePeriod, Firmware, SensorsScanned } from './sensor-data-fieldsets'
// import SensorDataHeader from './sensor-data-header'
import Graph from './charts'
import ProgressSteps from '../../../_progress-steps'
const sensorData = (props) => {
// DESTRUCTION
// console.log(props);
const { history } = props
// Find sensor by ID
// const sensor = sensors.find(el => el.id === match.params.id)
// UPDATE FIRMWARE
const updateFirmware = (e) => {
e.preventDefault()
}
// const { batteryStatus, sensorSignal } = sensor
return (
<div id="sensor__area" className="item-motion page">
<ProgressSteps history={ history } />
{/* <SensorDataHeader
sensorName={ sensorName }
sensorID={ props.match.params.id }
/> */}
<div id="sensor__area__data">
<div className="sensor__area__graph">
<article className="sensor__graph__item">
<section className="sensor__graph__item__header">
<div className="sensor__graph__item__header__icon">
<i className="icon-geo"></i>
</div>
<div className="sensor__graph__item__header__name">
Pressure
</div>
<div className="sensor__graph__item__header__value">
7845.9 hPa
</div>
</section>
<Graph/>
</article>
<article className="sensor__graph__item">
<Graph/>
</article>
<article className="sensor__graph__item"></article>
<article className="sensor__graph__item"></article>
</div>
<article className="sensor__area__params">
<Indicators
name={ 'Indicators' }
// batteryStatus={ batteryStatus }
// sensorSignal={ sensorSignal }
/>
<TimePeriod
name={ 'Time Period' }/>
<Firmware
name={ 'Firmware' }
versio={ '222.5.55' }
firmware={ updateFirmware }/>
<SensorsScanned
name={ 'Sensors scanned' }/>
</article>
</div>
</div>
)
}
const mapStateToProps = (state) => {
console.log(state);
return {
sensors: state.sensors
}
}
export default connect(mapStateToProps)(sensorData)
|
rudecs/jumpscale_core7
|
lib/JumpScale/core/Console.py
|
<gh_stars>0
import re
import sys
from JumpScale import j
# from JumpScale.core.pmtypes import IPv4Address, IPv4Range
import textwrap
import string
import collections
import sys
import os
if sys.platform.startswith("win"):
import msvcrt
clear = lambda: os.system('cls')
else:
clear = lambda: os.system('clear')
IPREGEX = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
CURSORUP = u'\u001b[{n}A'
CLEAREOL = u'\u001b[0K'
COLORESET = u'\u001b[0m'
COLORRED = u'\u001b[31m'
COLORGREEN = u'\u001b[32m'
COLORYELLOW = u'\u001b[33m'
COLORBLUE = u'\u001b[34m'
class Console:
"""
class which groups functionality to print to a console
self.width=120
self.indent=0 #current indentation of messages send to console
self.reformat=False #if True will make sure message fits nicely on screen
"""
def __init__(self):
self.width=230
self.indent=0 #current indentation of messages send to console
def rawInputPerChar(self,callback,params):
"""
when typing, char per char will be returned
"""
if not sys.platform.startswith("win"):
j.system.platform.ubuntu.check()
import termios
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
cont=True
try:
while cont:
try:
c = sys.stdin.read(1)
cont, result, params = callback(c, params)
except IOError:
j.logger.exception("Failed to read one character from stdin", 5)
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
else:
cont=True
while cont:
c = msvcrt.getch()
cont, result, params = callback(c, params)
return cont,result,params
def _cleanline(self,line):
"""
make sure is string
"""
try:
line=str(line)
except:
raise ValueError("Could not convert text to string in system class.")
return line
def formatMessage(self,message,prefix="",withStar=False,indent=0,width=0,removeemptylines=True):
'''
Reformat the message to display to the user and calculate length
@param withStar means put * in front of message
@returns: Length of last line and message to display
@rtype: tuple<number, string>
'''
if indent==0 or indent==None:
indent=self.indent
#if j.transaction.hasRunningTransactions():
# maxLengthStatusType= 8 #nr chars
#else:
# maxLengthStatusType=0
if prefix!="":
prefix="%s: "%(prefix)
if withStar:
prefix = '%s* %s' % (' ' * indent,prefix)
else:
prefix = ' %s%s' % (' ' * indent,prefix)
if width==0:
width=self.width
maxMessageLength = width -len(prefix) #- maxLengthStatusType
if maxMessageLength<5:
j.events.inputerror_critical("Cannot format message for screen, not enough width\nwidht:%s prefixwidth:%s maxlengthstatustype:%s" % (width,len(prefix),maxMessageLength),"console")
out=[]
for line in message.split("\n"):
if removeemptylines and line=="":
continue
linelength=maxMessageLength
linelength2=maxMessageLength-4
prepend=""
while len(line)>linelength:
linenow="%s%s"%(prepend,line[:linelength])
out.append(linenow)
line=line[linelength:]
linelength=linelength2 #room for prepend for next round
prepend=" "
linenow="%s%s"%(prepend,line[:linelength])
out.append(linenow)
return "\n".join(out)
def echo(self, msg,indent=None,withStar=False,prefix="",log=False,lf=True):
'''
Display some text to the end-user, use this method instead of print
@param indent std, will use indent from console object (same for all), this param allows to overrule
will only work when j.console.reformat==True
'''
msg=str(msg)
# if lf and msg!="" and msg[-1]!="\n":
# msg+="\n"
msg=self._cleanline(msg)
#if j.transaction.hasRunningTransactions() and withStar==False:
# indent=self.indent+1
msg=self.formatMessage(msg,indent=indent,withStar=withStar,prefix=prefix).rstrip(" ")
# msg=msg.rstrip()
if "_stdout_ori" in sys.__dict__:
sys._stdout_ori.write(msg)
else:
print(msg)
j.logger.inlog=False
if log:
j.logger.log(msg,1)
def info(self, text):
print('\033[1;36m[*] %s\033[0m' % text)
def warning(self, text):
print('\033[1;33m[-] %s\033[0m' % text)
def success(self, text):
print('\033[1;32m[+] %s\033[0m' % text)
def notice(self, text):
print('\033[1;34m[+] %s\033[0m' % text)
def message(self, text):
print('\033[1;37m[+] %s\033[0m' % text)
def messages(self, messages, clear=False):
if clear:
sys.stdout.write(CURSORUP.format(n=len(messages)))
for msg in messages:
line = msg + CLEAREOL
print(line)
def echoListItem(self, msg):
"""
Echo a list item
@param msg: Message to display
"""
self.echo(msg,withStar=True)
def echoListItems(self, messages, sort=False):
"""
Echo a sequence (iterator, generator, list, set) as list items
@param messages: messages that need to be written to the console as list items
@type messages: iterable
@param sort: sort the messages before echoing them
@type sort: bool
@param loglevel: Log level
@type loglevel: number
"""
if sort:
messages.sort()
for msg in messages:
self.echoListItem(msg)
def echoWithPrefix(self,message,prefix,withStar=False,indent=None):
"""
print a message which is formatted with a prefix
"""
self.echo(message,prefix=prefix,withStar=withStar,indent=indent)
def echoListWithPrefix(self,messages,prefix):
"""
print messages
"""
for message in messages:
self.echoWithPrefix(message,prefix,withStar=True)
def echoDict(self,dictionary,withStar=False,indent=None):
for key in list(dictionary.keys()):
try:
self.echoWithPrefix(str(dictionary[key]),key,withStar,indent)
except:
j.events.inputerror_critical("Could not convert item of dictionary %s to string" % key,"console.echodict")
def transformDictToMessage(self,dictionary,withStar=False,indent=None):
for key in list(dictionary.keys()):
try:
self.formatMessage(str(dictionary[key]),key,withStar,indent)
except:
j.events.inputerror_critical("Could not convert item of dictionary %s to string" % key,"console.transformDictToMessage")
def cls(self):
"""
clear screen
"""
clear()
def askString(self, question, defaultparam='', regex=None, retry=-1, validate=None):
"""Get a string response on a question
@param question: Question to respond to
@param defaultparam: Default response on the question if response not passed
@param regex: Regex to match in the response
@param retry: Integer counter to retry ask for respone on the question
@param validate: Function to validate provided value
@returns: Response provided by the user
@rtype: string
"""
if j.application.interactive!=True:
j.events.inputerror_critical ("Cannot ask a string in a non interactive mode.","console.askstring")
if validate and not isinstance(validate, collections.Callable):
raise TypeError('The validate argument should be a callable')
response = ""
if not defaultparam == "" and defaultparam:
question += " [%s]"%defaultparam
question += ": "
retryCount = retry
while retryCount != 0:
if sys.version.startswith("2"):
response = raw_input(question).rstrip()
else:
response = input(question).rstrip()
if response == "" and not defaultparam == "" and defaultparam:
return defaultparam
if (not regex or re.match(regex,response)) and (not validate or validate(response)):
return response
else:
self.echo( "Please insert a valid value!")
retryCount = retryCount - 1
raise ValueError("Console.askString() failed: tried %d times but user didn't fill out a value that matches '%s'." % (retry, regex))
def askPassword(self, question, confirm=True, regex=None, retry=-1, validate=None):
"""Present a password input question to the user
@param question: Password prompt message
@param confirm: Ask to confirm the password
@type confirm: bool
@param regex: Regex to match in the response
@param retry: Integer counter to retry ask for respone on the question
@param validate: Function to validate provided value
@returns: Password provided by the user
@rtype: string
"""
if j.application.interactive!=True:
j.events.inputerror_critical ("Cannot ask a password in a non interactive mode.","console.askpasswd.noninteractive")
if validate and not isinstance(validate, collections.Callable):
raise TypeError('The validate argument should be a callable')
response = ""
import getpass
startquestion = question
if question.endswith(': '):
question = question[:-2]
question += ": "
value=None
failed = True
retryCount = retry
while retryCount != 0:
response = getpass.getpass(question)
if (not regex or re.match(regex,response)) and (not validate or validate(response)):
if value == response or not confirm:
return response
elif not value:
failed = False
value=response
question = "%s (confirm): " %(startquestion)
else:
value=None
failed = True
question = "%s: "%(startquestion)
if failed:
self.echo("Invalid password!")
retryCount = retryCount - 1
j.events.inputerror_critical(("Console.askPassword() failed: tried %s times but user didn't fill out a value that matches '%s'." % (retry, regex)),"console.askpasswd")
def askInteger(self, question, defaultValue = None, minValue = None, maxValue = None, retry = -1, validate=None):
"""Get an integer response on asked question
@param question: Question need to get response on
@param defaultparam: default response on the question if response not passed
@param minValue: minimum accepted value for that integer
@param maxValue: maximum accepted value for that integer
@param retry: int counter to retry ask for respone on the question
@param validate: Function to validate provided value
@return: integer representing the response on the question
"""
if j.application.interactive!=True:
j.events.inputerror_critical ("Cannot ask an integer in a non interactive mode.")
if validate and not isinstance(validate, collections.Callable):
raise TypeError('The validate argument should be a callable')
if not minValue == None and not maxValue == None:
question += " (%d-%d)" % (minValue, maxValue)
elif not minValue == None:
question += " (min. %d)" % minValue
elif not maxValue == None:
question += " (max. %d)" % maxValue
if not defaultValue == None:
defaultValue=int(defaultValue)
question += " [%d]" % defaultValue
question += ": "
retryCount = retry
while retryCount != 0:
if sys.version.startswith("2"):
response = raw_input(question).rstrip(chr(13))
else:
response = input(question).rstrip(chr(13))
if response == "" and not defaultValue == None:
return defaultValue
if (re.match("^-?[0-9]+$",response.strip())) and (not validate or validate(response)):
responseInt = int(response.strip())
if (minValue == None or responseInt >= minValue) and (maxValue == None or responseInt <= maxValue):
return responseInt
j.console.echo("Please insert a valid value!")
retryCount = retryCount - 1
raise ValueError("Console.askInteger() failed: tried %d times but user didn't fill out a value that matches '%s'." % (retry, response))
def askYesNo(self, message=""):
'''Display a yes/no question and loop until a valid answer is entered
@param message: Question message
@type message: string
@return: Positive or negative answer
@rtype: bool
'''
if j.application.interactive!=True:
j.events.inputerror_critical ("Cannot ask a yes/no question in a non interactive mode.","console.askyesno.notinteractive")
while True:
if sys.version.startswith("2"):
result = raw_input(str(message) + " (y/n):").rstrip(chr(13))
else:
result = input(str(message) + " (y/n):").rstrip(chr(13))
if result.lower() == 'y' or result.lower() == 'yes':
return True
if result.lower() == 'n' or result.lower() == 'no':
return False
self.echo( "Illegal value. Press 'y' or 'n'.")
def askIntegers(self, question, invalid_message="invalid input please try again.", min=None, max=None):
"""
Ask the user for multiple integers
@param question: question that will be echoed before the user needs to input integers
@type question: string
@param invalid_message: message that will be echoed when the user inputs a faulty value
@type invalid_message: string
@param min: optional minimal value for input values, all returned values will be at least min
@type min: number or None
@param max: optional maximal value for input values, all returned values will be at least max
@type max: number of None
@return: the input numbers
@rtype: list<number>
"""
def clean(l):
try:
return [int(i.strip()) for i in l if i.strip() != ""]
except ValueError as ex:
return list()
def all_between(l, min, max):
for i in l:
if (not min is None) and i < min:
return False
elif (not max is None) and i > max:
return False
return True
def invalid(l):
return len(l) == 0 or (not all_between(l, min, max))
s = self.askString(question)
if s.find("*")!=-1:
return ["*"]
s=s.split(",")
parts = clean(s)
while invalid(parts):
self.echo(invalid_message)
parts = clean(f())
return parts
def askChoice(self,choicearray, descr="", sort=True,maxchoice=25,height=30,autocomplete=False):
"""
@param choicearray is list or dict, when dict key needs to be the object to return,
the value of the dics is what needs to be returned, the key is the str representation
"""
if height>0:
self.cls()
if isinstance(choicearray, (tuple, list)):
choicearray.sort()
#check items are strings or not, if not need to create dictionary
if isinstance(choicearray, (tuple, list)):
isstr=True
for item in choicearray:
if not j.basetype.string.check(item):
isstr=False
if isstr==False:
choicearrayNew={}
for item in choicearray:
choicearrayNew[str(item)]=item
choicearray=choicearrayNew
def pprint4autocomplete(chars=""):
self.cls()
print
counter=0
if len(choicearray)>(height-3):
if len(choicearray)<200:
shortchoice=[]
for item in choicearray:
short=item[0:4]
if short not in shortchoice:
shortchoice.append(short)
if len(shortchoice)>height-3:
break
shortchoice.sort()
for item in shortchoice:
print "- %s ..."%item
counter+=1
else:
for item in choicearray:
print "- %s"%item
counter+=1
while counter<(height-3):
print
counter+=1
descr2 = "%s\nMake a selection please, start typing, we will try to do auto completion.\n" % descr
self.echo(descr2)
print " :%s"%chars,
if len(choicearray)> maxchoice or autocomplete:
wildcard=False
chars=""
while True:
pprint4autocomplete(chars)
params=[wildcard,chars]
def process(char, params):
"""
char per char will be returned from console
"""
debug=False
wildcard, chars = params
#print (char,"","")
sys.stdout.write(char)
chars="%s%s" %(chars,char)
result=[]
if isinstance(choicearray, dict):
choicearray3=list(choicearray.values())
else:
choicearray3=choicearray
for rawChoice in choicearray3:
# We need to keep the 'raw' choices, so the end result is
# not a str()'d, lower()'d version of the original
# choicearray element.
choice=str(rawChoice).lower()
if wildcard and choice.find(chars.lower())!=-1:
result.append(rawChoice)
#print "%s %s %s %s" % (wildcard,choice,chars,choice.find(chars))
if not wildcard and choice.find(chars)==0:
# print "subset:%s"%rawChoice
result.append(rawChoice)
if char=="?":
return False,["99999"],params
params=[wildcard,chars]
#print str(len(result)) + " " + chars + " " + str(wildcard)
if not result:
# No matches
if debug:
print "nomatch"
params=[wildcard,chars[:-1]]
return False, result, params
elif len(result) < maxchoice:
#more than 1 result but not too many to show and ask choice with nr's
if debug:
print "<max amount, show items"
#try to find comonality beween remaining results
go=len(result)>0
x=1
chars2=chars
while go and len(result[0]) > x:
chars2+=result[0][x]
test=[item for item in result if item.find(chars2)==0]
if len(test)!=len(result):
#no match
chars2=chars2[:-1]
break
x+=1
params=[wildcard,chars2]
return False,result,params
else:
# Still too many results
if debug:
print "not small enough, keep typing"
return True, result, params
cont,choicearray2,params = self.rawInputPerChar(process,params)
wildcard, chars = params
if len(choicearray2)==0:
wildcard=False
continue
if len(choicearray2)==1 and not choicearray2==["99999"]:
#value was found
# wildcard, chars = params
# sys.stdout.write(str(choicearray2[0])[len(chars):])
return choicearray2[0]
if choicearray2==["99999"]:
self.echo("\n")
for choice in choicearray:
choice=str(choice)
self.echoListItem(choice)
self.echo("\n")
choicearray=choicearray2
else:
return self._askChoice(choicearray2, descr, sort)
else:
return self._askChoice(choicearray, descr, sort)
def _askChoice(self, choicearray, descr=None, sort=True):
if not choicearray:
return None
if len(choicearray) == 1:
if isinstance(choicearray, list):
self.echo("Found exactly one choice: %s"%(choicearray[0]))
return choicearray[0]
elif isinstance(choicearray, dict):
item = choicearray.items()[0]
self.echo("Found exactly one choice: %s"%(item[0]))
return item[1]
if j.application.interactive!=True:
j.events.inputerror_critical ("Cannot ask a choice in an list of items in a non interactive mode.","console.askchoice.noninteractive")
descr = descr or "\nMake a selection please: "
if sort and isinstance(choicearray, (tuple, list)):
choicearray.sort()
self.echo(descr)
if isinstance(choicearray, dict):
keys=list(choicearray.keys())
keys.sort()
valuearray=[]
choicearray2=[]
for key in keys:
valuearray.append(choicearray[key])
choicearray2.append(key)
choicearray=choicearray2
elif isinstance(choicearray[0], (tuple, list)):
valuearray = [ x[0] for x in choicearray ]
choicearray = [ x[1] for x in choicearray ]
else:
valuearray = choicearray
for idx, section in enumerate(choicearray):
self.echo(" %s: %s" % (idx+1, section))
self.echo("")
result = self.askInteger(" Select Nr", minValue=1, maxValue=idx+1)
return valuearray[result-1]
def askChoiceMultiple(self, choicearray, descr=None, sort=True):
if j.application.interactive!=True:
j.events.inputerror_critical ("Cannot ask a choice in an list of items in a non interactive mode.","console.askChoiceMultiple.notinteractive")
if not choicearray:
return []
if len(choicearray)==1:
return choicearray
descr = descr or "\nMake a selection please: "
if sort:
choicearray.sort()
self.echo(descr)
nr=0
for section in choicearray:
nr=nr+1
self.echo(" %s: %s" % (nr, section))
self.echo("")
results = self.askIntegers(" Select Nr, use comma separation if more e.g. \"1,4\", * is all, 0 is None",
"Invalid choice, please try again",
min=0,
max=len(choicearray))
if results==["*"]:
return choicearray
elif results==[0]:
return []
else:
return [choicearray[i-1] for i in results]
def askMultiline(self, question, escapeString='.'):
"""
Ask the user a question that needs a multi-line answer.
@param question: The question that should be asked to the user
@type question: string
@param escapeString: Optional custom escape string that is used by the user to indicate input has ended.
@type escapeString: string
@return: string multi-line reply by the user, always ending with a newline
"""
self.echo("%s:" % question)
self.echo("(Enter answer over multiple lines, end by typing '%s' (without the quotes) on an empty line)" % escapeString)
lines = []
user_input=raw_input()
while user_input != escapeString:
lines.append(user_input)
user_input=raw_input()
lines.append("") # Forces end with newline
return '\n'.join(lines)
def showOutput(self):
pass#@todo
def hideOutput(self):
pass
def printOutput(self):
pass
def enableOutput(self):
pass
def showArray(self,array,header=True):
choices=self._array2list(array,header)
out=""
for line in choices:
out+="%s\n"%line
print(out)
return out
def _array2list(self,array,header=True):
def pad(s,length):
while len(s)<length:
s+=" "
return s
length={}
for row in array:
for x in range(len(row)):
row[x]=str(row[x])
if x not in length:
length[x]=0
if length[x]<len(row[x]):
length[x]=len(row[x])
choices=[]
for row in array:
line=""
for x in range(len(row)):
line+="| %s |"%pad(row[x],length[x])
if line.strip()!="":
line=line.replace("||","|")
choices.append(line)
choices.sort()
return choices
def askArrayRow(self,array,header=True,descr="",returncol=None):
choices=self._array2list(array,header)
result=self.askChoiceMultiple(choices,descr="")
results=[]
for item in result:
if returncol==None:
results.append([item.strip() for item in item.split("|") if item.strip()!=""])
else:
results.append(item.split("|")[returncol+1])
if returncol!=None:
return [item.strip(" ") for item in results]
else:
return results
|
AeonSw4n/circl
|
dh/sidh/internal/p751/doc.go
|
<gh_stars>100-1000
// Package p751 provides implementation of field arithmetic used in SIDH and SIKE.
package p751
|
kitmi/k-suite-app
|
src/features/bootstrap.js
|
<filename>src/features/bootstrap.js
"use strict";
/**
* Enable bootstrap scripts
* @module Feature_Bootstrap
*/
const path = require('path');
const Feature = require('../enum/Feature');
const Literal = require('../enum/Literal');
const Util = require('rk-utils');
module.exports = {
/**
* This feature is loaded at plugin stage
* @member {string}
*/
type: Feature.PLUGIN,
/**
* Load the feature
* @param {App} app - The cli app module object
* @param {object} options - Options for the feature
* @property {string} [options.path='bootstrap'] - The path of the bootstrap scripts
* @returns {Promise.<*>}
*/
load_: async function (app, options) {
let bootPath = options.path ?
app.toAbsolutePath(options.path) :
path.join(app.workingPath, Literal.DEFAULT_BOOTSTRAP_PATH);
let bp = path.join(bootPath, '**', '*.js');
let files = await Util.glob(bp, {nodir: true});
return Util.eachAsync_(files, async file => {
let bootstrap = require(file);
return bootstrap(app);
});
}
};
|
lordmallam/aether
|
aether-couchdb-sync-module/aether/sync/api/tests/test_kernel_utils.py
|
# Copyright (C) 2018 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import json
import mock
import requests
from django.test import TestCase
from aether.common.kernel.utils import get_auth_header, get_kernel_server_url
from ..kernel_utils import (
propagate_kernel_project,
propagate_kernel_artefacts,
KernelPropagationError,
__upsert_kernel_artefacts as upsert_kernel,
)
from ..models import Project, Schema
class MockResponse:
def __init__(self, status_code, json_data=None):
self.json_data = json_data
self.status_code = status_code
self.content = json.dumps(json_data).encode('utf-8')
def json(self):
return self.json_data
class KernelUtilsTest(TestCase):
def setUp(self):
super(KernelUtilsTest, self).setUp()
self.kernel_url = get_kernel_server_url()
# create project entry
self.project = Project.objects.create(name='sample')
# create schemas entries
self.schema_1 = Schema.objects.create(
name='no-id',
project=self.project,
avro_schema={
'name': 'NoId',
'type': 'record',
'fields': [],
},
)
self.schema_2 = Schema.objects.create(
name='id',
project=self.project,
avro_schema={
'namespace': 'my.name.space',
'name': 'Id',
'type': 'record',
'fields': [{'name': 'id', 'type': 'string'}],
},
)
self.KERNEL_ID_1 = str(self.schema_1.kernel_id)
self.KERNEL_ID_2 = str(self.schema_2.kernel_id)
self.KERNEL_HEADERS = get_auth_header()
self.PROJECT_URL = f'{self.kernel_url}/projects/{str(self.project.project_id)}/'
self.MAPPING_URL_1 = f'{self.kernel_url}/mappings/{self.KERNEL_ID_1}/'
self.SCHEMA_URL_1 = f'{self.kernel_url}/schemas/{self.KERNEL_ID_1}/'
self.MAPPING_URL_2 = f'{self.kernel_url}/mappings/{self.KERNEL_ID_2}/'
self.SCHEMA_URL_2 = f'{self.kernel_url}/schemas/{self.KERNEL_ID_2}/'
# check that nothing exists already in kernel
response = requests.get(self.PROJECT_URL, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 404)
response = requests.get(self.MAPPING_URL_1, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 404)
response = requests.get(self.SCHEMA_URL_1, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 404)
response = requests.get(self.MAPPING_URL_2, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 404)
response = requests.get(self.SCHEMA_URL_2, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 404)
def tearDown(self):
super(KernelUtilsTest, self).tearDown()
# delete the test objects created in kernel testing server
requests.delete(self.PROJECT_URL, headers=self.KERNEL_HEADERS)
requests.delete(self.SCHEMA_URL_1, headers=self.KERNEL_HEADERS)
requests.delete(self.SCHEMA_URL_2, headers=self.KERNEL_HEADERS)
@mock.patch('requests.patch', return_value=MockResponse(status_code=400))
@mock.patch('aether.sync.api.kernel_utils.get_auth_header', return_value=None)
def test__upsert_kernel_artefacts__no_connection(self, mock_auth, mock_patch):
with self.assertRaises(KernelPropagationError) as kpe:
upsert_kernel(
project=self.project,
artefacts={'avro_schemas': []},
)
self.assertIsNotNone(kpe)
self.assertIn('Connection with Aether Kernel server is not possible.',
str(kpe.exception), kpe)
mock_auth.assert_called_once()
mock_patch.assert_not_called()
@mock.patch('requests.patch', return_value=MockResponse(status_code=400))
@mock.patch('aether.sync.api.kernel_utils.get_auth_header', return_value={
'Authorization': 'Token ABCDEFGH'
})
def test__upsert_kernel_artefacts__unexpected_error(self, mock_auth, mock_patch):
with self.assertRaises(KernelPropagationError) as kpe:
upsert_kernel(
project=self.project,
artefacts={'avro_schemas': []},
)
self.assertIsNotNone(kpe)
self.assertIn('Unexpected response from Aether Kernel server',
str(kpe.exception), kpe)
self.assertIn('while trying to create/update the project artefacts',
str(kpe.exception), kpe)
self.assertIn(f'"{str(self.project.project_id)}"', str(kpe.exception), kpe)
mock_auth.assert_called_once()
mock_patch.assert_called_once_with(
url=f'{self.kernel_url}/projects/{str(self.project.project_id)}/avro-schemas/',
json={'avro_schemas': []},
headers={'Authorization': 'Token ABCDEFGH'},
)
@mock.patch('requests.patch', return_value=MockResponse(status_code=200))
@mock.patch('aether.sync.api.kernel_utils.get_auth_header', return_value={
'Authorization': 'Token <PASSWORD>'
})
def test__upsert_kernel_artefacts__ok(self, mock_auth, mock_patch):
self.assertTrue(upsert_kernel(
project=self.project,
artefacts={'avro_schemas': []}
))
mock_auth.assert_called_once()
mock_patch.assert_called_once_with(
url=f'{self.kernel_url}/projects/{str(self.project.project_id)}/avro-schemas/',
json={'avro_schemas': []},
headers={'Authorization': 'Token <PASSWORD>'},
)
def test__propagate_kernel_project(self):
self.assertTrue(propagate_kernel_project(self.project))
response = requests.get(self.PROJECT_URL, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_project = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_project['id'], str(self.project.project_id))
self.assertIn(self.project.name, kernel_project['name'])
# creates the artefacts for the schema 1
response = requests.get(self.MAPPING_URL_1, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_mapping_1 = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_mapping_1['id'], self.KERNEL_ID_1)
# last rule is #!uuid
self.assertEqual('#!uuid', kernel_mapping_1['definition']['mapping'][-1][0])
response = requests.get(self.SCHEMA_URL_1, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_schema_1 = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_schema_1['id'], self.KERNEL_ID_1)
# creates the artefacts for the schema 2
response = requests.get(self.MAPPING_URL_2, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_mapping_2 = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_mapping_2['id'], self.KERNEL_ID_2)
self.assertNotEqual('#!uuid', kernel_mapping_2['definition']['mapping'][-1][0])
response = requests.get(self.SCHEMA_URL_2, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_schema_2 = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_schema_2['id'], self.KERNEL_ID_2)
def test__propagate_kernel_artefacts(self):
self.assertTrue(propagate_kernel_artefacts(self.schema_1))
response = requests.get(self.PROJECT_URL, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_project = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_project['id'], str(self.project.project_id))
self.assertIn(self.project.name, kernel_project['name'])
# creates the artefacts for the schema 1
response = requests.get(self.MAPPING_URL_1, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_mapping_1 = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_mapping_1['id'], self.KERNEL_ID_1)
response = requests.get(self.SCHEMA_URL_1, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 200)
kernel_schema_1 = json.loads(response.content.decode('utf-8'))
self.assertEqual(kernel_schema_1['id'], self.KERNEL_ID_1)
# does not create the artefacts for the schema 2
response = requests.get(self.MAPPING_URL_2, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 404)
response = requests.get(self.SCHEMA_URL_2, headers=self.KERNEL_HEADERS)
self.assertEqual(response.status_code, 404)
|
bschau/Attic
|
qmta/libqmta/private.h
|
#ifndef PRIVATE_H
#define PRIVATE_H
#include "libqmta.h"
#include "helptext.h"
#include "savi/csavi2c.h"
/* macros */
#define CFAINT 1
#define CFASTR 2
#define MAXSIGNALS 16
/* structs */
typedef struct cfa {
char *name;
char *description;
char **help;
int type;
int *idst;
int iinit;
char **sdst;
char *sinit;
int private;
} cfa;
/* errors.c */
void erroropen(void);
void errorraise(int, int);
int errorget(int);
#define EGTYPE 1
#define EGACTION 2
/* error-types */
#define ERRNOERR 0 /* no error */
#define ERRMAIL 1 /* mail format error (missing from/to etc.) */
#define ERRSMTP 2 /* smtp error (usually implies requeueing) */
/* error-actions */
#define ERRNOTHING 0 /* do nothing */
#define ERRGENERIC500 100 /* catch all generic 5xx */
#define ERRADDRESS 101 /* return address error mail */
#define ERRINVALIDFROM 102 /* rejected sender mailbox - severe */
#define ERRINVALIDTO 103 /* rejected reciever mailbox */
#define ERRREQUEUE 201 /* requeue mail message */
/* mail.c */
void mail(database *, char *);
/* sanity.c */
void sanity(void);
/* smtp.c */
int smtp(char *);
#ifdef MAIN
int sck=-1, verbose;
session gs;
mxnode *mxl;
FILE *emf;
#else
extern int sck, verbose;
extern session gs;
extern mxnode *mxl;
extern FILE *emf;
#endif
#ifndef CFASWITCHES
extern cfa cfaconfig[];
#endif
/* all */
extern int h_errno;
#endif
|
codolab/candy
|
packages/moon-engine/src/util/alpha.js
|
import rgba from "color-rgba";
function hasAlpha(color) {
return (
color.startsWith("rgba(") ||
color.startsWith("hsla(") ||
(color.startsWith("#") && color.length === 9) ||
(color.startsWith("#") && color.length === 5)
);
}
export function toRgba(color) {
const [r, g, b, a] = rgba(color);
return [r, g, b, a === undefined && hasAlpha(color) ? 1 : a];
}
function withAlphaVariable({ color, variable }) {
try {
const [r, g, b, a] = toRgba(color);
return [`rgba(${r}, ${g}, ${b}, var(${variable}))`, a];
} catch (e) {
return [color, null];
}
}
export function transformColor({ color: c, property, variable }) {
const [color, opacity] = withAlphaVariable({
color: c,
variable,
});
if (!opacity || c === "transparent") {
return { [property]: c };
}
return {
[property]: color,
[variable]: opacity,
};
}
|
alexandermerritt/dragonfly
|
sys/sys/signalvar.h
|
<filename>sys/sys/signalvar.h
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*
* @(#)signalvar.h 8.6 (Berkeley) 2/19/95
* $FreeBSD: src/sys/sys/signalvar.h,v 1.34.2.1 2000/05/16 06:58:05 dillon Exp $
*/
#ifndef _SYS_SIGNALVAR_H_ /* tmp for user.h */
#define _SYS_SIGNALVAR_H_
/*
* Don't bring in the entire bleeding include set if we aren't the kernel.
* Userland is not allowed to bring in sys/proc.h except under special
* circumstances (e.g. sys/user.h)
*/
#include <sys/signal.h>
#ifdef _KERNEL
#include <sys/proc.h>
#include <machine/lock.h>
#endif
/*
* Kernel signal definitions and data structures,
* not exported to user programs.
*/
/*
* Process signal actions and state, needed only within the process
* (not necessarily resident).
*/
struct sigacts {
sig_t ps_sigact[_SIG_MAXSIG]; /* disposition of signals */
sigset_t ps_catchmask[_SIG_MAXSIG]; /* signals to be blocked */
sigset_t ps_sigignore; /* Signals being ignored. */
sigset_t ps_sigcatch; /* Signals being caught by user. */
sigset_t ps_sigonstack; /* signals to take on sigstack */
sigset_t ps_sigintr; /* signals that interrupt syscalls */
sigset_t ps_sigreset; /* signals that reset when caught */
sigset_t ps_signodefer; /* signals not masked while handled */
sigset_t ps_siginfo; /* signals that want SA_SIGINFO args */
sigset_t ps_usertramp; /* SunOS compat; libc sigtramp XXX */
unsigned int ps_refcnt;
int ps_flag;
};
/* additional signal action values, used only temporarily/internally */
#define SIG_CATCH ((__sighandler_t *)2)
#define SIG_HOLD ((__sighandler_t *)3)
#ifdef _KERNEL
/*
* get signal action for process and signal; currently only for current process
*/
#define SIGACTION(p, sig) (p->p_sigacts->ps_sigact[_SIG_IDX(sig)])
#endif
/*
* sigset_t manipulation macros
*/
#define SIGADDSET(set, signo) \
(set).__bits[_SIG_WORD(signo)] |= _SIG_BIT(signo)
#define SIGDELSET(set, signo) \
(set).__bits[_SIG_WORD(signo)] &= ~_SIG_BIT(signo)
#define SIGEMPTYSET(set) \
do { \
int __i; \
for (__i = 0; __i < _SIG_WORDS; __i++) \
(set).__bits[__i] = 0; \
} while (0)
#define SIGFILLSET(set) \
do { \
int __i; \
for (__i = 0; __i < _SIG_WORDS; __i++) \
(set).__bits[__i] = ~(unsigned int)0; \
} while (0)
#define SIGISMEMBER(set, signo) \
((set).__bits[_SIG_WORD(signo)] & _SIG_BIT(signo))
#define SIGISEMPTY(set) __sigisempty(&(set))
#define SIGNOTEMPTY(set) (!__sigisempty(&(set)))
#define SIGSETEQ(set1, set2) __sigseteq(&(set1), &(set2))
#define SIGSETNEQ(set1, set2) (!__sigseteq(&(set1), &(set2)))
#define SIGSETOR(set1, set2) \
do { \
int __i; \
for (__i = 0; __i < _SIG_WORDS; __i++) \
(set1).__bits[__i] |= (set2).__bits[__i]; \
} while (0)
#define SIGSETAND(set1, set2) \
do { \
int __i; \
for (__i = 0; __i < _SIG_WORDS; __i++) \
(set1).__bits[__i] &= (set2).__bits[__i]; \
} while (0)
#define SIGSETNAND(set1, set2) \
do { \
int __i; \
for (__i = 0; __i < _SIG_WORDS; __i++) \
(set1).__bits[__i] &= ~(set2).__bits[__i]; \
} while (0)
#define SIG_CANTMASK(set) \
SIGDELSET(set, SIGKILL), SIGDELSET(set, SIGSTOP)
#define SIG_STOPSIGMASK(set) \
SIGDELSET(set, SIGSTOP), SIGDELSET(set, SIGTSTP), \
SIGDELSET(set, SIGTTIN), SIGDELSET(set, SIGTTOU)
#define SIG_CONTSIGMASK(set) \
SIGDELSET(set, SIGCONT)
#define sigcantmask (sigmask(SIGKILL) | sigmask(SIGSTOP))
static __inline int
__sigisempty(sigset_t *set)
{
int i;
for (i = 0; i < _SIG_WORDS; i++) {
if (set->__bits[i])
return (0);
}
return (1);
}
static __inline int
__sigseteq(sigset_t *set1, sigset_t *set2)
{
int i;
for (i = 0; i < _SIG_WORDS; i++) {
if (set1->__bits[i] != set2->__bits[i])
return (0);
}
return (1);
}
#ifdef _KERNEL
typedef void (*proc_func_t)(struct proc *);
struct pgrp;
struct proc;
struct sigio;
extern int sugid_coredump; /* Sysctl variable kern.sugid_coredump */
/*
* Machine-independent functions:
*/
void execsigs (struct proc *p);
void gsignal (int pgid, int sig);
int issignal (struct lwp *lp, int maytrace);
int iscaught (struct lwp *p);
void killproc (struct proc *p, char *why);
void pgsigio (struct sigio *, int signum, int checkctty);
void pgsignal (struct pgrp *pgrp, int sig, int checkctty);
void postsig (int sig);
void ksignal (struct proc *p, int sig);
void lwpsignal (struct proc *p, struct lwp *lp, int sig);
void siginit (struct proc *p);
void trapsignal (struct lwp *p, int sig, u_long code);
/*
* Machine-dependent functions:
*/
void sendsig (sig_t action, int sig, sigset_t *retmask, u_long code);
void sigexit (struct lwp *lp, int sig) __dead2;
int checkpoint_signal_handler(struct lwp *p);
#endif /* _KERNEL */
#endif /* !_SYS_SIGNALVAR_H_ */
|
yoloz/BGSamples
|
sample-jdbc/src/main/java/com/yoloz/sample/jdbc/SqlServerTest.java
|
package com.yoloz.sample.jdbc;
import com.microsoft.sqlserver.jdbc.SQLServerResultSet;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* https://docs.microsoft.com/en-us/sql/connect/jdbc/setting-the-connection-properties?view=sql-server-ver15
* <p>
* com.microsoft.jdbc.sqlserver.SQLServerDriver //<2005
* com.microsoft.sqlserver.jdbc.SQLServerDriver //>=2005
* <p>
* jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=test;integratedSecurity=true; //<2005
* jdbc:sqlserver://127.0.0.1:1433;databaseName=test; //>=2005
*/
public class SqlServerTest {
public static void main(String[] args) throws SQLException {
String url = "jdbc:sqlserver://192.168.1.132:1433;database=test;";
try (Connection conn = DriverManager.getConnection(url, "SA", "")) {
Util.getCatalogs(conn);
Util.getSchemas(conn,"test","%");
Util.getTables(conn, "test", "dbo", "%", null);
Util.getColumns(conn,"test", "dbo", "baoxian","%");
}
}
/**
* the minimum possible data is buffered when necessary.
*/
public void simpleQuery() {
String url = "jdbc:sqlserver://192.168.1.132:1433;database=test;";
String sql = "select * from gongsi2";
try (Connection conn = DriverManager.getConnection(url, "SA", "");
Statement stmt = conn.createStatement()) {
SQLServerResultSet resultSet = (SQLServerResultSet) stmt.executeQuery(sql);
Method isForwardOnly = resultSet.getClass().getDeclaredMethod("isForwardOnly");
isForwardOnly.setAccessible(true);
System.out.println(isForwardOnly.invoke(resultSet));
Field serverCursorId = resultSet.getClass().getDeclaredField("serverCursorId");
serverCursorId.setAccessible(true);
System.out.println(0 == (int) serverCursorId.get(resultSet));
System.out.println(resultSet.getFetchSize());
Field responseBuffering = conn.getClass().getDeclaredField("responseBuffering");
responseBuffering.setAccessible(true);
System.out.println("adaptive".equals(responseBuffering.get(conn)));
resultSet.close();
} catch (SQLException | NoSuchFieldException | IllegalAccessException | NoSuchMethodException |
InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* responseBuffering String ["full" | "adaptive"]
* <p>
* If this property is set to "adaptive", the minimum possible data is buffered when necessary.
* The default mode is "adaptive."
* <p>
* When this property is set to "full", the entire result set is read from the server when a statement is executed.
* <p>
* Note: After upgrading the JDBC driver from version 1.2, the default buffering behavior will be "adaptive."
* If your application has never set the "responseBuffering" property and you want to keep the version 1.2
* default behavior in your application, you must set the responseBufferring property to "full"
* either in the connection properties or by using the setResponseBuffering method of the SQLServerStatement object.
*/
public void fullQuery() {
String url = "jdbc:sqlserver://192.168.1.132:1433;database=test;responseBuffering=full";
String sql = "select * from gongsi2";
try (Connection conn = DriverManager.getConnection(url, "SA", "");
Statement stmt = conn.createStatement()) {
SQLServerResultSet resultSet = (SQLServerResultSet) stmt.executeQuery(sql);
Method isForwardOnly = resultSet.getClass().getDeclaredMethod("isForwardOnly");
isForwardOnly.setAccessible(true);
System.out.println(isForwardOnly.invoke(resultSet));
Field serverCursorId = resultSet.getClass().getDeclaredField("serverCursorId");
serverCursorId.setAccessible(true);
System.out.println(0 == (int) serverCursorId.get(resultSet));
System.out.println(resultSet.getFetchSize());
Field responseBuffering = conn.getClass().getDeclaredField("responseBuffering");
responseBuffering.setAccessible(true);
System.out.println("full".equals(responseBuffering.get(conn)));
resultSet.close();
} catch (SQLException | NoSuchFieldException | IllegalAccessException | NoSuchMethodException |
InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* selectMethod String ["direct" | "cursor"]
* <p>
* If this property is set to "cursor," a database cursor is created for each query created on the connection for
* TYPE_FORWARD_ONLY and CONCUR_READ_ONLY cursors.
* This property is typically required only if the application generates large result sets that cannot be fully contained in client memory.
* When this property is set to "cursor," only a limited number of result set rows are retained in client memory.
* <p>
* The default behavior is that all result set rows are retained in client memory.(need set responseBuffering="full")
* This behavior provides the fastest performance when the application is processing all rows.
*/
public void cursorQuery() {
String url = "jdbc:sqlserver://192.168.1.132:1433;database=test;selectMethod=cursor";
String sql = "select * from gongsi2";
try (Connection conn = DriverManager.getConnection(url, "SA", "")) {
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
stmt.setFetchSize(10);
SQLServerResultSet resultSet = (SQLServerResultSet) stmt.executeQuery(sql);
Method isForwardOnly = resultSet.getClass().getDeclaredMethod("isForwardOnly");
isForwardOnly.setAccessible(true);
System.out.println(isForwardOnly.invoke(resultSet));
Field serverCursorId = resultSet.getClass().getDeclaredField("serverCursorId");
serverCursorId.setAccessible(true);
System.out.println(0 != (int) serverCursorId.get(resultSet));
System.out.println(resultSet.getFetchSize());
Field responseBuffering = conn.getClass().getDeclaredField("responseBuffering");
responseBuffering.setAccessible(true);
System.out.println("adaptive".equals(responseBuffering.get(conn)));
resultSet.close();
} catch (SQLException | NoSuchFieldException | IllegalAccessException | NoSuchMethodException |
InvocationTargetException e) {
e.printStackTrace();
}
}
}
|
ChuVal/Respaldo2
|
dashboard/src/components/ListHeader/index.js
|
<filename>dashboard/src/components/ListHeader/index.js
export * from "./ListHeader";
export * from "./EnhancedListHeader";
export * from "./EnhancedListHeaderContainer";
|
26fe/sem4r
|
spec/sem4r/rexml_parsing_spec.rb
|
<reponame>26fe/sem4r
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# Copyright (c) 2009-2010 Sem4r <EMAIL>
#
# 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.
#
# -------------------------------------------------------------------------
require File.expand_path(File.dirname(__FILE__) + '/../rspec_helper')
describe "Test Parsing with REXML" do
include Sem4rSpecHelper
# it "ddd" do
# pending "test"
# xml_document = read_xml_document_with_rexml("services", "ad_group_ad", "mutate_add_two_criterions-res.xml")
# els = REXML::XPath.match( xml_document, "//mutateResponse/rval/value/ad/id")
# els.each {|e| puts e.text.strip.to_i }
# end
it "test_account_get_client_accounts" do
xml_document = read_xml_document_with_rexml("v13_account", "get_client_accounts-res.xml")
els = REXML::XPath.match(xml_document, "//getClientAccountsReturn")
els.length.should == 5
end
it "test_campaign_get" do
xml_document = read_xml_document_with_rexml("campaign", "get-res.xml")
rval = REXML::XPath.first(xml_document, "//getResponse/rval")
els = REXML::XPath.match(rval, "entries")
els.map do |el|
name = el.elements["name"].text.strip
name.should match /sem4r campaign/
end
end
# it "test_adgroup_criterion_get" do
# xml_document = read_xml_document_with_rexml("ad_group_criterion", "get-res.xml")
# rval = REXML::XPath.first( xml_document, "//getResponse/rval")
#
# el = REXML::XPath.first( rval, "entries/criterion[@xsi:type='Keyword']")
#
# el.elements["id"].text.should == "11536082"
# el.elements["text"].text.should == "pippo"
# el.elements["matchType"].text.should == "BROAD"
# end
it "test_info_get" do
xml_document = read_xml_document_with_rexml("info", "get_unit_count-res.xml")
response_header = REXML::XPath.first(xml_document, "//ResponseHeader")
response_header.elements["operations"].text.strip.should == "1"
response_header.elements["responseTime"].text.strip.should == "291"
response_header.elements["units"].text.strip.should == "1"
cost = REXML::XPath.first(xml_document, "//getResponse/rval/cost")
cost.text.strip.should == "0"
end
end
|
debe-sgx/debe
|
src/Enclave/include/ocallUtil.h
|
/**
* @file ocallUtil.h
* @author
* @brief define the interface of the ocall util
* @version 0.1
* @date 2020-12-18
*
* @copyright Copyright (c) 2020
*
*/
#ifndef OCALL_UTIL_H
#define OCALL_UTIL_H
#include <stdio.h>
#include "sgx_urts.h"
namespace OcallUtil {
void PrintSGXErrorMessage(sgx_status_t err);
};
#endif
|
CoprHD/sds-controller
|
exportLibraries/discoveryplugins/src/main/java/com/emc/storageos/plugins/common/domainmodel/NamespaceList.java
|
/*
* Copyright (c) 2008-2011 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.plugins.common.domainmodel;
import java.util.Map;
public class NamespaceList {
private Map<String, Object> _nsList;
public void setNsList(Map<String, Object> nsList) {
this._nsList = nsList;
}
public Map<String, Object> getNsList() {
return _nsList;
}
}
|
edentns/MarketManagerWeb
|
WebContent/app/contents/99sy/sy05MyInfo/controllers/sy.MyInfo.ctrl.js
|
(function () {
"use strict";
/**
* 내정보관리
* @name sy.MyInfo.controller : sy.MyInfoCtrl
*/
angular.module("sy.MyInfo.controller")
.controller("sy.MyInfoCtrl", ["$rootScope", "$scope", "$q", "sy.MyInfoSvc", "sy.LoginSvc", "UtilSvc", "Page", "resData",
function ($rootScope, $scope, $q, SyMyInfoSvc, SyLoginSvc, UtilSvc, Page, resData) {
/**
*===============================================================
* @description 개인정보를 관리한다.
*===============================================================
*/
var vo = $scope.myInfoVO = {
activeTab: 1,
ynEditNkne: false, // 닉네임 수정여부
ynCheckDupNkne: false, // 닉네임 중복체크 성공여부
param: {
NO_EMP : "",
currentPw: "", // 현재비밀번호
newPw: "", // 새비밀번호
newPwChk: "", // 새비밀번호확인
isEquals: false, // 새비밀번호와 새비밀번호확인 일치여부
message: "비밀번호를 입력해주세요.",
DC_ID: "",
NM_EMP: "",
DC_EMIADDR: "",
NM_NKNE: "",
NM_DEPT: "",
NM_RANK: "",
DT_EMP: "",
YN_SMS: "",
YN_EMI: "",
yn_change: false
},
fileProfileVO: {
CD_AT:"001",
limitCnt: 1,
bImage: true,
imgWidth: '200px',
imgHeight: '250px',
currentData:{
CD_AT: "",
CD_REF1: "",
CD_REF2: "",
CD_REF3: null,
CD_REF4: null,
CD_REF5: "",
DTS_INSERT: null,
DTS_UPDATE: null,
NM_FILE: "",
NM_FILEPATH: "",
NO_AT: 0,
NO_C: "",
NO_INSERT: "",
NO_UPDATE: null,
SZ_FILE: "",
YN_DEL: null
}
}
};
vo.isChangeNmNkne = function() {
if(vo.param.NM_NKNE === resData.MyParam.NM_NKNE) vo.ynEditNkne = false; // 닉네임 수정여부
else vo.ynEditNkne = true; // 닉네임 수정여부
vo.ynCheckDupNkne = false; // 닉네임 중복체크 성공여부
};
vo.dupCheck = function() {
var self = this,
param = {};
if(self.param.NM_NKNE === '') {
alert('닉네임을 입력하여 주세요.');
$timeout(function () {
edt.id("NM_NKNE").focus();
}, 500);
return;
}
self.ynCheckDupNkne = false; // 닉네임 변경시 false로 변경해야 함.
SyMyInfoSvc.dupCheckNmNkne(self.param.NM_NKNE).success(function (res) {
if(res === "닉네임 중복체크 성공") {
self.ynCheckDupNkne = true; // 닉네임 변경시 false로 변경해야 함.
alert('중복된 닉네임이 없습니다.');
}
else {
alert(res);
}
}).error(function(res) {
});
};
//탭 바꿀시 변경된 데이터 체크
vo.tab = function(clickTab, mVO) {
var self = this,
flag = false,
msg = "변경사항이 있습니다.\n변경하시겠습니까?";
// 프로필 설정
if(vo.activeTab === 1) {
if(mVO.fileProfileVO.dirty || mVO.ynEditNkne){
if(confirm(msg)) {
flag = true;
vo.doUpdateProfile();
} else {
mVO.fileProfileVO.fileInit();
mVO.ynEditNkne = false;
mVO.ynCheckDupNkne = false;
mVO.param.NM_NKNE = resData.MyParam.NM_NKNE;
}
}
}
// 비밀번호 설정
else if(vo.activeTab === 2) {
if(mVO.param.isEquals){
if(confirm(msg)){
vo.doUpdatePw();
}else{
mVO.param.currentPw = "";
mVO.param.newPw = "";
mVO.param.newPwChk = "";
mVO.param.isEquals= false;
mVO.param.message= "비밀번호를 입력해주세요.";
}
}
}
// 알림설정 설정
else if(vo.activeTab === 3) {
if(mVO.param.yn_change){
flag = true;
if(confirm(msg)){
vo.doUpdateYn();
}
}
}
vo.activeTab = clickTab;
if(flag){
var param = {
procedureParam:"USP_SY_05MyInfo_GET"
};
UtilSvc.getList(param).then(function (result) { // 해당 사원 재갱신
vo.param = result.data.results[0][0];
vo.fileProfileVO.currentData = result.data.results[1][0];
mVO.param.newPw = "";
});
}
};
/**
* @description 비밀번호 입력을 받을 때마다 메세지를 변경한다.
*/
vo.changeMessage = function () {
SyMyInfoSvc.changeMessage(vo);
};
vo.doUpdateProfile = function() {
if(vo.ynEditNkne && !vo.ynCheckDupNkne) {
alert("닉네임 중복체크가 안되어 있습니다.");
return;
}
SyMyInfoSvc.updateProfile(vo.param).then(function (res) {
if(vo.fileProfileVO.dirty) {
vo.fileProfileVO.CD_REF1 = vo.param.NO_EMP;
vo.fileProfileVO.doUpload(function(){
vo.ynEditNkne = false;
vo.ynCheckDupNkne = false;
resData.MyParam.NM_NKNE = vo.param.NM_NKNE;
$rootScope.webApp.user.NM_NKNE = vo.param.NM_NKNE;
alert('성공하였습니다.');
}, function() {
alert('파일업로드 실패하였습니다.');
});
}
else {
vo.ynEditNkne = false;
vo.ynCheckDupNkne = false;
resData.MyParam.NM_NKNE = vo.param.NM_NKNE;
$rootScope.webApp.user.NM_NKNE = vo.param.NM_NKNE;
alert('성공하였습니다.');
}
});
};
// vo.doFileChange = function() {
// if(vo.fileProfileVO.dirty) {
// vo.fileProfileVO.CD_REF1 = vo.param.NO_EMP;
// vo.fileProfileVO.doUpload(function(){
// alert('성공하였습니다.');
// }, function() {
// alert('파일업로드 실패하였습니다.');
// });
// }
// else {
// alert('변경사항이 없습니다.');
// }
// };
/**
* @description 패스워드를 변경한다.
*/
vo.doUpdatePw = function () {
var param = SyMyInfoSvc.makePwParam(vo),
msg = "비밀번호를 변경하시겠습니까?";
if (!vo.param.isEquals) {
alert("비밀번호를 확인해주세요.");
return;
}
if (confirm(msg)) {
SyMyInfoSvc.updatePassword(param).then(function () {
alert("패스워드가 변경되었습니다. 다시 로그인해주세요.");
SyLoginSvc.logout().then(function () {
$scope.$emit("event:logout");
});
});
}
};
vo.doUpdateYn = function () {
var param = SyMyInfoSvc.makeYnParam(vo),
msg = "알림을 변경하시겠습니까?";
if (confirm(msg)) {
SyMyInfoSvc.updateYn(param).then(function () {
});
}
};
/**
* 유저정보를 가져온다.
*/
vo.getUserInfo = function () {
vo.param = angular.copy(resData.MyParam);
vo.fileProfileVO.currentData = resData.fileProfile;
vo.param.newPw = "";
};
vo.getUserInfo();
}]);
}());
|
geminusnet/RapidJavaApplicationDev
|
example/radft/jdbcdemo/TestJdbcOdbc.java
|
package jdbcdemo;
import java.sql.*;
public class TestJdbcOdbc {
public static void main(String[] args)
throws SQLException, ClassNotFoundException {
// Load the JDBC-ODBC bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver sun.jdbc.odbc.JdbcOdbcDriverloaded");
// Establish connection
Connection connection = DriverManager.getConnection
("jdbc:odbc:LiangBookDB_MDB", "", "");
System.out.println("Database LiangBookDB_MDB connected");
// Create a statement
Statement stmt = connection.createStatement();
try {
// Create the Student TABLE
stmt.executeUpdate(
"create table Student(firstName varchar(20), "
+ "mi varchar(1), lastName varchar(20))");
// Insert two records into the Student TABLE
stmt.executeUpdate(
"insert into Student values ('John', 'F', 'Smith')");
stmt.executeUpdate(
"insert into Student values ('Wade', 'E', 'Bush')");
}
catch (SQLException ex) {
System.out.println("Table Student already exists");
}
// Select the column student from the Student table
ResultSet rset = stmt.executeQuery
("select firstName, mi, lastName from Student");
// Iterate through the result and print the student names
while (rset.next())
System.out.println(rset.getString(1) + " " +
rset.getString(2) + ". " + rset.getString(3));
// Close the connection
connection.close();
}
}
|
lolgab/trail
|
shared/src/main/scala/trail/Route.scala
|
package trail
sealed trait Route[Args] {
def url(args: Args): String
private def process(result: Option[(Args, Path)]): Option[Args] =
result.collect { case (args, p) if p.path.isEmpty => args }
private def processStrict(result: Option[(Args, Path)]): Option[Args] =
result.collect { case (args, p) if
p.path.isEmpty && p.args.isEmpty && p.fragment.isEmpty => args
}
/**
* Parse given [[Path]]
*
* If successful, the result contains the parsed arguments as well as the
* updated [[Path]] object. If the path was fully parsed, all of its fields
* should be empty.
*
* Use [[parseArgs]] or [[parseArgsStrict]] if you are only interested in the
* parsed arguments.
*
* @return Some((parsed arguments, updated path))
*/
def parse(path: Path): Option[(Args, Path)]
/**
* Parse given URI
*
* @see parse(path: Path)
*/
def parse(uri: String): Option[(Args, Path)] = parse(PathParser.parse(uri))
/**
* Parse arguments of given [[Path]]
*
* This returns None if `path` contains additional trailing elements missing
* from the route.
*/
def parseArgs(path: Path): Option[Args] = process(parse(path))
/**
* Parse arguments of given URI
*
* @see parseArgs(path: Path)
*/
def parseArgs(uri: String): Option[Args] = process(parse(uri))
/**
* Parse arguments of given [[Path]]
*
* Same behaviour as [[parseArgs]]. It does not permit any unspecified path
* elements, arguments or a fragment.
*/
def parseArgsStrict(path: Path): Option[Args] = processStrict(parse(path))
/**
* Parse arguments of given URI
*
* @see parseArgsStrict(path: Path)
*/
def parseArgsStrict(uri: String): Option[Args] = processStrict(parse(uri))
/**
* Generate URL for given arguments
*/
def apply(args: Args): String = url(args)
/**
* Parse arguments for given [[Path]]
*
* @see [[parseArgs]]
*/
def unapply(path: Path): Option[Args] = parseArgs(path)
/**
* Parse arguments for given URI
*
* @see [[parseArgs]]
*/
def unapply(uri: String): Option[Args] = parseArgs(uri)
def &(params: Params.type): Route.ParamsRoute[Args] = Route.ParamsRoute(this)
}
case object Root extends Route[Unit] {
override def url(value: Unit): String = "/"
override def parse(path: Path): Option[(Unit, Path)] =
if (!path.path.startsWith("/")) None
else Some((), path.copy(path = path.path.tail))
}
case object Elems extends Route[List[String]] {
override def url(value: List[String]): String = value.mkString("/")
override def parse(path: Path): Option[(List[String], Path)] =
Some((PathParser.parseParts(path.path), path.copy(path = "")))
}
case object Params
object Route {
implicit class Route0Extensions(route: Route[Unit]) {
def /[T](arg: Arg[T]): Route.ConcatRight[T] =
Route.ConcatRight(route, Route.Dynamic(arg))
def /[T](value: T)(implicit staticElement: StaticElement[T]): Route.ConcatRight[Unit] =
Route.ConcatRight(route, Route.Static(staticElement.f(value)))
def /[T](rest: Elems.type): Route.ConcatRight[List[String]] =
Route.ConcatRight(route, Elems)
def &[T](param: Param[T]): ParamRoute0[T] =
ParamRoute0(route, param)
def &(params: Params.type): ParamsRoute[Unit] = ParamsRoute(route)
def $[T](fragment: Fragment[T]): FragmentRoute0[T] =
FragmentRoute0(route, fragment)
}
implicit class RouteNExtensions[P](route: Route[P]) {
def /[T](arg: Arg[T]): Route.ConcatBoth[P, T] =
Route.ConcatBoth(route, Route.Dynamic(arg))
def /[T](value: T)(implicit staticElement: StaticElement[T]): Route.ConcatLeft[P] =
Route.ConcatLeft(route, Route.Static(staticElement.f(value)))
def &[T](param: Param[T]): ParamRoute[P, T] = ParamRoute(route, param)
def $[T](fragment: Fragment[T]): FragmentRoute[P, T] =
FragmentRoute(route, fragment)
}
case class Static(element: String) extends Route[Unit] {
require(!element.contains("/"), "Element must not contain a slash")
override def url(value: Unit): String = element
override def parse(path: Path): Option[(Unit, Path)] = {
val untilSlash = path.path.takeWhile(_ != '/')
if (untilSlash != element) None
else Some(((), path.copy(path = path.path.drop(untilSlash.length + 1))))
}
}
case class Dynamic[T](arg: Arg[T]) extends Route[T] {
override def url(value: T): String = arg.codec.encode(value).getOrElse("")
override def parse(path: Path): Option[(T, Path)] = {
val untilSlash = path.path.takeWhile(_ != '/')
arg.codec.decode(if (untilSlash.isEmpty) None else Some(untilSlash))
.map(value => (value, path.copy(path =
path.path.drop(untilSlash.length + 1))))
}
}
case class ConcatLeft[L](left: Route[L], right: Route[Unit]) extends Route[L] {
override def url(value: L): String = left.url(value) + "/" + right.url(())
override def parse(path: Path): Option[(L, Path)] =
for {
(lv, lp) <- left.parse(path)
(_ , rp) <- right.parse(lp)
} yield (lv, rp)
}
case class ConcatRight[R](left: Route[Unit], right: Route[R]) extends Route[R] {
override def url(value: R): String =
(if (left == Root) "" else left.url(())) + "/" + right.url(value)
override def parse(path: Path): Option[(R, Path)] =
for {
(_ , lp) <- left.parse(path)
(rv, rp) <- right.parse(lp)
} yield (rv, rp)
}
case class ConcatBoth[L, R](left: Route[L], right: Route[R]) extends Route[(L, R)] {
override def url(value: (L, R)): String = left.url(value._1) + "/" + right.url(value._2)
override def parse(path: Path): Option[((L, R), Path)] =
for {
(lv, lp) <- left.parse(path)
(rv, rp) <- right.parse(lp)
} yield ((lv, rv), rp)
}
case class FragmentRoute0[P](route: Route[Unit], fragment: Fragment[P]) extends Route[P] {
override def url(value: P): String =
fragment.codec.encode(value) match {
case None => route.url(())
case Some(frag) => route.url(()) + "#" + frag
}
override def parse(path: Path): Option[(P, Path)] =
for {
(_, lp) <- route.parse(path)
v <- fragment.codec.decode(lp.fragment)
p = lp.copy(fragment = None)
} yield (v, p)
}
case class FragmentRoute[A, P](route: Route[A], fragment: Fragment[P]) extends Route[(A, P)] {
override def url(value: (A, P)): String =
fragment.codec.encode(value._2) match {
case None => route.url(value._1)
case Some(frag) => route.url(value._1) + "#" + frag
}
override def parse(path: Path): Option[((A, P), Path)] =
for {
(lv, lp) <- route.parse(path)
rv <- fragment.codec.decode(lp.fragment)
p = lp.copy(fragment = None)
} yield ((lv, rv), p)
}
case class ParamRoute0[P](route: Route[Unit], param: Param[P]) extends Route[P] {
override def url(value: P): String = {
val arg = param.codec.encode(value)
.fold("")(v => param.name + "=" + URI.encode(v))
route.url(()) + (if (arg.isEmpty) "" else "?" + arg)
}
override def parse(path: Path): Option[(P, Path)] =
for {
(_, lp) <- route.parse(path)
arg = lp.args.find(_._1 == param.name)
v <- param.codec.decode(arg.map(_._2))
p = lp.copy(args = lp.args.diff(arg.toList))
} yield (v, p)
def &[T](param: Param[T]): ParamRoute[P, T] = ParamRoute(this, param)
}
case class ParamRoute[A, P](route: Route[A], param: Param[P]) extends Route[(A, P)] {
override def url(value: (A, P)): String = {
val base = route.url(value._1)
param.codec.encode(value._2)
.map(v => param.name + "=" + URI.encode(v))
.fold(base) { encodedParam =>
val delimiter = if (base.contains("?")) "&" else "?"
base + delimiter + encodedParam
}
}
override def parse(path: Path): Option[((A, P), Path)] =
for {
(lv, lp) <- route.parse(path)
arg = lp.args.find(_._1 == param.name)
rv <- param.codec.decode(arg.map(_._2))
p = lp.copy(args = lp.args.diff(arg.toList))
} yield ((lv, rv), p)
}
case class ParamsRoute[A](route: Route[A]) extends Route[(A, List[(String, String)])] {
override def url(value: (A, List[(String, String)])): String = {
val (valueRoute, args) = value
val base = route.url(valueRoute)
if (args.isEmpty) base
else {
val argsEncoded = args.map { case (n, v) => n + "=" + URI.encode(v) }
base + (if (base.contains("?")) "&" else "?") + argsEncoded.mkString("&")
}
}
override def parse(path: Path): Option[((A, List[(String, String)]), Path)] =
for {
(lv, lp) <- route.parse(path)
p = lp.copy(args = List())
} yield ((lv, lp.args), p)
}
}
|
mferten/k12k20tr.com
|
public/js/Countries/LY/mapdata.js
|
<gh_stars>0
var simplemaps_countrymap_mapdata={
main_settings: {
//General settings
width: "responsive", //or '300'
background_color: "#FFFFFF",
background_transparent: "yes",
border_color: "#ffffff",
pop_ups: "detect",
//State defaults
state_description: "State description",
state_color: "#88A4BC",
state_hover_color: "#3B729F",
state_url: "",
border_size: 1.5,
all_states_inactive: "no",
all_states_zoomable: "no",
//Location defaults
location_description: "Location description",
location_url: "",
location_color: "#FF0067",
location_opacity: 0.8,
location_hover_opacity: 1,
location_size: 25,
location_type: "square",
location_image_source: "frog.png",
location_border_color: "#FFFFFF",
location_border: 2,
location_hover_border: 2.5,
all_locations_inactive: "no",
all_locations_hidden: "no",
//Label defaults
label_color: "#d5ddec",
label_hover_color: "#d5ddec",
label_size: 22,
label_font: "Arial",
hide_labels: "no",
hide_eastern_labels: "no",
//Zoom settings
zoom: "no",
manual_zoom: "no",
back_image: "no",
initial_back: "no",
initial_zoom: "-1",
initial_zoom_solo: "yes",
region_opacity: 1,
region_hover_opacity: 0.6,
zoom_out_incrementally: "no",
zoom_percentage: 0.99,
zoom_time: 0.5,
//Popup settings
popup_color: "white",
popup_opacity: 0.9,
popup_shadow: 1,
popup_corners: 5,
popup_font: "12px/1.5 Verdana, Arial, Helvetica, sans-serif",
popup_nocss: "no",
//Advanced settings
div: "map",
auto_load: "no",
url_new_tab: "no",
images_directory: "default",
fade_time: 0.1,
link_text: "View Website"
},
state_specific: {
LBY2882: {
name: "Ghadamis",
description: "default",
color: "default",
hover_color: "default",
url: "default"
},
LBY2964: {
name: "<NAME>"
},
LBY2965: {
name: "<NAME>"
},
LBY2966: {
name: "<NAME>"
},
LBY2967: {
name: "<NAME>'"
},
LBY2968: {
name: "Ghat"
},
LBY2969: {
name: "Murzuq"
},
LBY2970: {
name: "Misratah"
},
LBY2971: {
name: "Sabha"
},
LBY2973: {
name: "<NAME>"
},
LBY2974: {
name: "<NAME>"
},
LBY2975: {
name: "<NAME>"
},
LBY2976: {
name: "Mizdah"
},
LBY2978: {
name: "Tajura' wa an Nawahi al Arba"
},
LBY2981: {
name: "<NAME>"
},
LBY2982: {
name: "<NAME>"
},
LBY2983: {
name: "Ajdabiya"
},
LBY2984: {
name: "Benghazi"
},
LBY2985: {
name: "Surt"
},
LBY2986: {
name: "<NAME>"
},
LBY2987: {
name: "<NAME>"
},
LBY5488: {
name: "<NAME>"
}
},
locations: {
"0": {
lat: "32.8925",
lng: "13.18",
name: "Tripoli"
}
}
};
|
yeelin/betweenus
|
app/src/main/java/com/example/yeelin/projects/betweenus/data/google/json/DistanceMatrixJsonDeserializerHelper.java
|
package com.example.yeelin.projects.betweenus.data.google.json;
import android.util.Log;
import com.example.yeelin.projects.betweenus.data.google.model.DistanceMatrixResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by ninjakiki on 2/26/16.
*/
public class DistanceMatrixJsonDeserializerHelper {
private static final String TAG = DistanceMatrixJsonDeserializerHelper.class.getCanonicalName();
/**
* Deserialize the distance matrix JSON response into a DistanceMatrixResult object using GSON
* @param responseJSON
* @return
* @throws IOException
*/
public static DistanceMatrixResult deserializeDistanceMatrixResponse(InputStream responseJSON)
throws IOException {
//create a gson object
final Gson gson = new GsonBuilder().create();
InputStreamReader inputStreamReader = null;
try {
//create an input stream reader from the json input stream
inputStreamReader = new InputStreamReader(responseJSON, "UTF-8");
//deserialize json into java
DistanceMatrixResult result = gson.fromJson(inputStreamReader, DistanceMatrixResult.class); //TODO: change class type
//log for debugging purposes
Log.d(TAG, "deserializeDistanceMatrixResponse: DistanceMatrix: " + result);
return result;
}
finally {
if (inputStreamReader != null) inputStreamReader.close();
}
}
}
|
JohnDMathis/autohost
|
spec/dashboard/host.js
|
var host = require( '../../src/index.js' );
host.init( {
static: './src/_autohost/public',
port: 4488
} );
host.http.static( '/spec', './spec/dashboard' );
|
LuciusKyle/LeetCode
|
0791_Custom_Sort_String/0791.cc
|
<reponame>LuciusKyle/LeetCode
#include <string>
using std::string;
class Solution {
public:
string customSortString(string S, string T) {
int dict[26]{0};
for (const char ch : T) ++dict[ch - 'a'];
int cur_index = 0;
for (const char ch : S)
while (dict[ch - 'a']-- != 0) T[cur_index++] = ch;
for (int i = 0; i < std::end(dict) - std::begin(dict); ++i)
for (int j = 0; j < dict[i]; ++j) T[cur_index++] = i + 'a';
return T;
}
};
|
ototu/quteqoin
|
ui/pinipede/qqpostparser.cpp
|
<filename>ui/pinipede/qqpostparser.cpp
#include "qqpostparser.h"
#include "core/qqnorlogeref.h"
#include "core/qqsettings.h"
#include "ui/qqmessageblockuserdata.h"
#include "ui/pinipede/qqpiniurlhelper.h"
#include <QtDebug>
#include <QRegExp>
#include <QString>
#include <QTextCursor>
#include <QTextDocument>
#define NORLOGE_COLOR "#0000DD"
#define NORLOGE_REP_COLOR "#DD0000"
#define DUCK_COLOR "#9933cc"
#define TOTOZ_COLOR "#00AA11"
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::QQPostParser
/// \param parent
///
QQPostParser::QQPostParser(QObject *parent) :
QObject(parent)
{
QQSettings settings;
if(settings.value(SETTINGS_FILTER_SMART_URL_TRANSFORMER, DEFAULT_FILTER_SMART_URL_TRANSFORMER).toBool())
m_listMessageTransformFilters.append(new QQPiniUrlHelper(this));
m_indexShit = 0;
}
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::formatMessage
/// \param post
/// \return
///
QTextDocumentFragment* QQPostParser::formatMessage(QQPost *post, QQMessageBlockUserData *userData)
{
QString message = applyMessageTransformFilters(post->message(), post->bouchot()->name(), post->date());
QList<QTextDocumentFragment> msgFragments = splitMessage(message, post, userData);
applyMessageFragmentTransformFilters(msgFragments, post->bouchot()->name(), post->date());
QTextDocument doc;
QTextCursor cursor(&doc);
foreach (QTextDocumentFragment fragment, msgFragments) {
cursor.insertFragment(fragment);
}
colorizeBigorno(doc, post, userData);
colorizeDuck(doc, userData);
colorizeTableVolante(doc, userData);
colorizeTotoz(doc, userData);
detectLecon(doc, userData);
return new QTextDocumentFragment(&doc);
}
//////////////////////////////////////////////////////////
/// \brief QQPostParser::splitMessage
/// \param message
/// \param post
/// \param userData
/// \return
///
QList<QTextDocumentFragment> QQPostParser::splitMessage(const QString &message, QQPost *post, QQMessageBlockUserData *userData)
{
QList<QTextDocumentFragment> res;
if(message.length() > 0)
{
QTextDocument doc;
doc.setHtml(message);
QTextCursor docCursor(&doc);
QTextCursor norlogeCursor(&doc);
QTextCharFormat fmt = docCursor.blockCharFormat();
fmt.setUnderlineStyle(QTextCharFormat::NoUnderline);
fmt.setAnchor(true);
QRegExp norlogeReg = QQNorlogeRef::norlogeRegexp();
while(! (norlogeCursor = doc.find(norlogeReg, norlogeCursor)).isNull())
{
QQNorlogeRef nRef = QQNorlogeRef(*post, norlogeCursor.selectedText());
linkNorlogeRef(&nRef);
int index = userData->appendNorlogeRef(nRef);
fmt.setForeground(nRef.isReponse() ? QColor(NORLOGE_REP_COLOR) : QColor(NORLOGE_COLOR));
fmt.setFontWeight(nRef.isReponse() ? QFont::DemiBold : QFont::Normal);
QString nRefUrl = QString("nref://bouchot?board=%1&postId=%2&index=%3")
.arg(post->bouchot()->name())
.arg(post->id()).arg(index);
fmt.setAnchorHref(nRefUrl);
norlogeCursor.mergeCharFormat(fmt);
int selectionStart = norlogeCursor.selectionStart();
if(selectionStart != 0)
{
docCursor.setPosition(selectionStart, QTextCursor::KeepAnchor);
if(! docCursor.selection().isEmpty())
res.append(docCursor.selection());
docCursor.setPosition(selectionStart, QTextCursor:: MoveAnchor);
}
}
docCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
if(! docCursor.selection().isEmpty())
res.append(docCursor.selection());
}
else
res.append(QTextDocumentFragment());
return res;
}
//////////////////////////////////////////////////////////
/// \brief QQPostParser::applyMessageFragmentTransformFilters
/// \param listMsgFragments
/// \param bouchot
///
void QQPostParser::applyMessageFragmentTransformFilters(QList<QTextDocumentFragment> &listMsgFragments, const QString &bouchot, const QDate &postDate)
{
Q_UNUSED(bouchot);
// Rectify ISO 9601 norloges
QTextDocument tmp;
for(int i = 0; i < listMsgFragments.size(); i++)
{
tmp.clear();
QTextCursor c(&tmp);
c.insertFragment(listMsgFragments[i]);
c.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
auto moveSuccess = c.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 5);
QString st = c.selectedText();
// If it starts with "....-" pattern, it is a ISO norloge. Let's reformat it
if(moveSuccess && c.charFormat().anchorHref().startsWith("nref://") &&
st.at(4) == QChar('-'))
{
c.beginEditBlock();
if(st.left(4) == QString::number(postDate.year()))
c.removeSelectedText();
else
c.insertText(QString("%1/").arg(st.left(4)));
// Process next "..-..T" characters
c.setPosition(c.anchor());
c.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 6);
st = c.selectedText();
if(st.left(2) == QString("%1").arg(postDate.month(), 2, 10, QChar('0')) &&
st.mid(3, 2) == QString("%1").arg(postDate.day(), 2, 10, QChar('0')))
c.removeSelectedText();
else
c.insertText(QString("%1/%2#").arg(st.left(2)).arg(st.mid(3, 2)));
c.endEditBlock();
listMsgFragments[i] = QTextDocumentFragment(&tmp);
}
}
}
//////////////////////////////////////////////////////////
/// \brief QQPostParser::applyMessageTransformFilters
/// \param message
/// \param bouchot
/// \param data
/// \return
///
QString QQPostParser::applyMessageTransformFilters(const QString &message, const QString &bouchot, const QDate &postDate)
{
Q_UNUSED(postDate);
QString newMessage = message;
QQMessageTransformFilter *messageTransformFilter;
foreach(messageTransformFilter, m_listMessageTransformFilters)
messageTransformFilter->transformMessage(bouchot, newMessage);
return newMessage;
}
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::colorizeBigorno
/// \param doc
/// \param post
/// \param data
///
void QQPostParser::colorizeBigorno(QTextDocument &doc, QQPost *post, QQMessageBlockUserData *userData)
{
QString id = post->bouchot()->settings().login();
if(id.length() == 0)
id = post->bouchot()->settings().ua();
QString bigorno = QString::fromLatin1("\\b(?:");
if(id.length() > 0)
bigorno.append(id).append("|");
bigorno.append("moules)<");
QRegExp bigornoReg = QRegExp(bigorno,
Qt::CaseInsensitive,
QRegExp::RegExp);
QTextCursor cursor(&doc);
QTextCharFormat fmt = cursor.blockCharFormat();
fmt.setForeground(QColor(Qt::red));
while(! (cursor = doc.find(bigornoReg, cursor)).isNull())
{
QQBigornoItem bigItem(m_indexShit + cursor.selectionStart(), cursor.selectedText());
userData->addBigornoZone(bigItem);
QString callerId = post->login();
if(callerId.length() == 0)
callerId = post->UA();
QString name = post->bouchot()->name();
emit bigorNotify(name, callerId,
(cursor.selectedText().compare("moules<", Qt::CaseInsensitive) == 0));
}
}
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::colorizeDuck
/// \param doc
/// \param post
/// \param data
///
void QQPostParser::colorizeDuck(QTextDocument &doc, QQMessageBlockUserData *userData)
{
QString tete = QString::fromLatin1("(?:[o0ô°øòó@]|(?:ô)|(?:°)|(?:ø)|(?:ò)|(?:ó))");
QList<QRegExp> regexes;
regexes << QRegExp(QString::fromLatin1("\\\\_").append(tete).append(QString::fromLatin1("<")),
Qt::CaseSensitive,
QRegExp::RegExp);
regexes << QRegExp(QString::fromLatin1(">").append(tete).append(QString::fromLatin1("_\\/")),
Qt::CaseSensitive,
QRegExp::RegExp);
regexes << QRegExp(QString::fromLatin1("coin ?! ?coin ?!"),
Qt::CaseSensitive,
QRegExp::RegExp);
QTextCursor cursor(&doc);
QTextCharFormat fmt = cursor.blockCharFormat();
fmt.setForeground(QColor(DUCK_COLOR));
QQPost *post = userData->post();
foreach(QRegExp reg, regexes)
{
cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
while(! (cursor = doc.find(reg, cursor)).isNull())
{
QString duckUrl = QString("duck://bouchot?board=%1&postId=%2&self=%3")
.arg(post->bouchot()->name()).arg(post->id()).arg(post->isSelfPost());
fmt.setAnchorHref(duckUrl);
cursor.mergeCharFormat(fmt);
userData->setHasDuck();
}
}
}
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::linkNorlogeRef
/// \param nRef
///
void QQPostParser::linkNorlogeRef(QQNorlogeRef *nRef)
{
QQBouchot *bouchot = QQBouchot::bouchot(nRef->dstBouchot());
if(bouchot == NULL)
return;
QQListPostPtr history = bouchot->postsHistory();
// Parcourir du plus recent au plus ancien devrait etre plus rapide car
// les reponse sont souvent proches du poste d'origine;
bool targetFound = false;
for(int i = history.length() - 1; i >= 0; i--)
{
QQPost *post = history.at(i);
if(nRef->matchesPost(post))
targetFound = true;
else if(targetFound) // On ne quitte pas avant au cas de match multiple
break;
}
}
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::colorizeTableVolante
/// \param doc
/// \param post
/// \param data
///
void QQPostParser::colorizeTableVolante(QTextDocument &doc, QQMessageBlockUserData *userData)
{
QRegExp tvReg = QRegExp(QString::fromLatin1("(?:flap ?flap)|(?:table[ _]volante)"),
Qt::CaseSensitive,
QRegExp::RegExp);
QTextCursor cursor(&doc);
QTextCharFormat fmt = cursor.blockCharFormat();
fmt.setForeground(QColor(DUCK_COLOR));
QQPost *post = userData->post();
while(! (cursor = doc.find(tvReg, cursor)).isNull())
{
QString duckUrl = QString("tablev://bouchot?board=%1&postId=%2&self=%3")
.arg(post->bouchot()->name()).arg(post->id()).arg(post->isSelfPost());
fmt.setAnchorHref(duckUrl);
cursor.mergeCharFormat(fmt);
}
}
#define MAX_TOTOZ_PREFETCH_POST 3
#define MAX_LAST_TOTOZ_IDS_COUNT 50
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::colorizeTotoz
/// \param doc
/// \param post
/// \param data
///
void QQPostParser::colorizeTotoz(QTextDocument &doc, QQMessageBlockUserData *userData)
{
Q_UNUSED(userData);
QRegExp totozReg = QRegExp(QString::fromLatin1("(\\[\\:[^\\t\\)\\]]+\\])"), //[:[^\t\)\]]
Qt::CaseSensitive,
QRegExp::RegExp);
QTextCursor cursor(&doc);
QTextCharFormat fmt = cursor.blockCharFormat();
fmt.setForeground(QColor(TOTOZ_COLOR));
fmt.setFontWeight(QFont::Bold);
fmt.setUnderlineStyle(QTextCharFormat::NoUnderline);
fmt.setAnchor(true);
int totozCount = 0;
while(! (cursor = doc.find(totozReg, cursor)).isNull())
{
QString totozId = cursor.selectedText();
QString totozName = totozId.mid(2, totozId.length() - 3);
fmt.setAnchorHref(QString("totoz://name/%1").arg(totozName));
//Antiflood : Maximum 3 requetes et sur des totoz différents
if(!lastTotozIds.contains(totozName) && totozCount <= MAX_TOTOZ_PREFETCH_POST)
{
totozCount++;
lastTotozIds.enqueue(totozName);
while(lastTotozIds.count() > MAX_LAST_TOTOZ_IDS_COUNT)
lastTotozIds.dequeue();
emit totozRequired(totozName);
}
cursor.mergeCharFormat(fmt);
}
}
#define LECON_BASE_URL "http://lecons.ssz.fr/lecon/"
//////////////////////////////////////////////////////////////
/// \brief QQPostParser::detectLecon
/// \param doc
/// \param userData
///
void QQPostParser::detectLecon(QTextDocument &doc, QQMessageBlockUserData *userData)
{
Q_UNUSED(userData)
QRegExp totozReg = QRegExp(QString::fromUtf8("(le[cç]on\\s+\\d+)"),
Qt::CaseInsensitive,
QRegExp::RegExp);
QTextCursor cursor(&doc);
while(! (cursor = doc.find(totozReg, cursor)).isNull())
{
QString numLesson = cursor.selectedText().split(QRegExp("\\s")).at(1);
QString url = QString::fromLatin1("<a href=\"")
.append(LECON_BASE_URL)
.append(numLesson)
.append(QString::fromLatin1("\">"))
.append(cursor.selectedText())
.append(QString::fromLatin1("</a>"));
cursor.insertHtml(url);
}
}
|
SunChuquin/pyside2_designer_widgets
|
custom_widgets/panel/gaugepanel.py
|
<filename>custom_widgets/panel/gaugepanel.py<gh_stars>1-10
from PySide2.QtCore import QTimer, QSize, Signal, Qt, QRectF, QPoint
from PySide2.QtGui import QPaintEvent, QPainter, QColor, QPen, QPolygon
from PySide2.QtWidgets import QWidget
import math
class GaugePanel(QWidget):
"""
面板仪表盘控件
作者:feiyangqingyun(QQ:517216493) 2019-7-3
译者:sunchuquin(QQ:1715216365) 2021-07-13
1. 可设置范围值,支持负数值
2. 可设置精确度+刻度尺精确度,最大支持小数点后3位
3. 可设置大刻度数量/小刻度数量
4. 可设置开始旋转角度/结束旋转角度
5. 可设置是否启用动画效果以及动画效果每次移动的步长
6. 可设置刻度颜色+文字颜色+圆环的宽度和颜色
7. 自适应窗体拉伸,刻度尺和文字自动缩放
8. 可设置单位以及仪表盘名称
"""
valueChanged = Signal(int) # value
def __init__(self, parent: QWidget = None):
super(GaugePanel, self).__init__(parent)
self.__minValue: float = 0 # 最小值
self.__maxValue: float = 100 # 最大值
self.__value: float = 0 # 目标值
self.__precision: int = 0 # 精确度,小数点后几位
self.__scalePrecision: int = 0 # 刻度尺精确度,小数点后几位
self.__scaleMajor: int = 10 # 大刻度数量
self.__scaleMinor: int = 5 # 小刻度数量
self.__startAngle: int = 45 # 开始旋转角度
self.__endAngle: int = 45 # 结束旋转角度
self.__animation: bool = False # 是否启用动画显示
self.__animationStep: float = 0.5 # 动画显示时步长
self.__ringWidth: int = 10 # 圆环宽度
self.__ringColor: QColor = QColor(54, 192, 254) # 圆环颜色
self.__scaleColor: QColor = QColor(34, 163, 169) # 刻度颜色
self.__pointerColor: QColor = QColor(34, 163, 169) # 指针颜色
self.__bgColor: QColor = QColor(Qt.transparent) # 背景颜色
self.__textColor: QColor = QColor(50, 50, 50) # 文字颜色
self.__unit: str = 'V' # 单位
self.__text: str = '电压' # 描述文字
self.__reverse: bool = False # 是否往回走
self.__currentValue: float = 0 # 当前值
self.__timer: QTimer = QTimer(self) # 定时器绘制动画
self.__timer.setInterval(10)
self.__timer.timeout.connect(self.updateValue)
def paintEvent(self, event: QPaintEvent = None) -> None:
width: int = self.width()
height: int = self.height()
side: int = min(width, height)
# 绘制准备工作,启用反锯齿,平移坐标轴中心,等比例缩放
painter: QPainter = QPainter(self)
painter.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)
# 绘制背景
if self.__bgColor != Qt.transparent:
painter.setPen(Qt.NoPen)
painter.fillRect(self.rect(), self.__bgColor)
painter.translate(width / 2, height / 2)
painter.scale(side / 200.0, side / 200.0)
self.drawRing(painter) # 绘制圆环
self.drawScale(painter) # 绘制刻度线
self.drawScaleNum(painter) # 绘制刻度值
self.drawPointer(painter) # 绘制指示器
self.drawValue(painter) # 绘制当前值
def drawRing(self, painter: QPainter = None) -> None:
radius: int = 70
painter.save()
pen: QPen = QPen()
pen.setCapStyle(Qt.FlatCap)
pen.setWidthF(self.__ringWidth)
pen.setColor(self.__ringColor)
painter.setPen(pen)
radius = radius - self.__ringWidth
rect: QRectF = QRectF(-radius, -radius, radius * 2, radius * 2)
angleAll: float = 360.0 - self.__startAngle - self.__endAngle
painter.drawArc(rect, (270 - self.__startAngle - angleAll) * 16, angleAll * 16)
painter.restore()
def drawScale(self, painter: QPainter = None) -> None:
radius: int = 80
painter.save()
painter.rotate(self.__startAngle)
steps: int = (self.__scaleMajor * self.__scaleMinor)
angleStep: float = (360.0 - self.__startAngle - self.__endAngle) / steps
pen: QPen = QPen()
pen.setCapStyle(Qt.RoundCap)
pen.setColor(self.__scaleColor)
for i in range(steps + 1):
if i % self.__scaleMinor == 0:
pen.setWidthF(1.5)
painter.setPen(pen)
painter.drawLine(0, radius - 8, 0, radius + 5)
else:
pen.setWidthF(0.5)
painter.setPen(pen)
painter.drawLine(0, radius - 8, 0, radius - 3)
painter.rotate(angleStep)
painter.restore()
def drawScaleNum(self, painter: QPainter = None) -> None:
radius: int = 95
painter.save()
painter.setPen(self.__scaleColor)
startRad: float = (360 - self.__startAngle - 90) * (math.pi / 180)
deltaRad: float = (360 - self.__startAngle - self.__endAngle) * (math.pi / 180) / self.__scaleMajor
for i in range(self.__scaleMajor + 1):
sina: float = math.sin(startRad - i * deltaRad)
cosa: float = math.cos(startRad - i * deltaRad)
value: float = 1.0 * i * ((self.__maxValue - self.__minValue) / self.__scaleMajor) + self.__minValue
strValue: str = '%s' % round(value, self.__scalePrecision) if self.__scalePrecision else str(int(value))
textWidth: float = self.fontMetrics().width(strValue)
textHeight: float = self.fontMetrics().height()
x: int = int(radius * cosa - textWidth / 2)
y: int = int(-radius * sina + textHeight / 4)
painter.drawText(x, y, strValue)
painter.restore()
def drawPointer(self, painter: QPainter = None) -> None:
radius: int = 70
painter.save()
painter.setPen(Qt.NoPen)
painter.setBrush(self.__pointerColor)
pts: QPolygon = QPolygon()
pts.append(QPoint(4, -5))
pts.append(QPoint(0, 0))
pts.append(QPoint(-8, 5))
pts.append(QPoint(0, 0))
pts.append(QPoint(0, radius))
painter.rotate(self.__startAngle)
degRotate: float = (360.0 - self.__startAngle - self.__endAngle) / \
(self.__maxValue - self.__minValue) * \
(self.__currentValue - self.__minValue)
painter.rotate(degRotate)
painter.drawConvexPolygon(pts)
painter.restore()
def drawValue(self, painter: QPainter = None) -> None:
radius: int = 100
painter.save()
painter.setPen(self.__textColor)
font: QFont = QFont()
font.setPixelSize(15)
painter.setFont(font)
strValue: str = '%s' % round(self.__currentValue, self.__precision) if self.__precision else str(int(self.__currentValue))
strValue = "%s %s" % (strValue, self.__unit)
valueRect: QRectF = QRectF(-radius, radius / 3.5, radius * 2, radius / 3.5)
painter.drawText(valueRect, Qt.AlignCenter, strValue)
textRect: QRectF = QRectF(-radius, radius / 2.5, radius * 2, radius / 2.5)
font.setPixelSize(12)
painter.setFont(font)
painter.drawText(textRect, Qt.AlignCenter, self.__text)
painter.restore()
def updateValue(self) -> None:
if not self.__reverse:
if self.__currentValue >= self.__value:
self.__timer.stop()
else:
self.__currentValue += self.__animationStep
else:
if self.__currentValue <= self.__value:
self.__timer.stop()
else:
self.__currentValue -= self.__animationStep
self.update()
def setRange(self, min_value, max_value) -> None:
# 如果最小值大于或者等于最大值则不设置
if min_value >= max_value: return
self.__minValue = min_value
self.__maxValue = max_value
# 如果目标值不在范围值内,则重新设置目标值
# 值小于最小值则取最小值,大于最大值则取最大值
if self.__value < min_value: self.value = min_value
elif self.__value > max_value: self.value = max_value
self.update()
@property
def minValue(self) -> float: return self.__minValue
@minValue.setter
def minValue(self, min_value: float) -> None:
self.setRange(min_value, self.__maxValue)
@property
def maxValue(self) -> float: return self.__maxValue
@maxValue.setter
def maxValue(self, max_value: float) -> None:
self.setRange(self.__minValue, max_value)
@property
def value(self) -> float: return self.__value
def setValue(self, n_value: int) -> None:
self.value = float(n_value)
@value.setter
def value(self, n_value: float) -> None:
# 值和当前值一致则无需处理
if n_value == self.__value: return
# 值小于最小值则取最小值,大于最大值则取最大值
if n_value < self.__minValue:
n_value = self.__minValue
elif n_value > self.__maxValue:
n_value = self.__maxValue
if n_value > self.__value:
self.__reverse = False
elif n_value < self.__value:
self.__reverse = True
self.__value = n_value
self.valueChanged.emit(n_value)
if not self.__animation:
self.__currentValue = self.__value
self.update()
else:
self.__timer.start()
@property
def precision(self) -> int: return self.__precision
@precision.setter
def precision(self, n_precision: int) -> None:
if 3 < n_precision == self.__precision: return
self.__precision = n_precision
self.update()
@property
def scalePrecision(self) -> int: return self.__scalePrecision
@scalePrecision.setter
def scalePrecision(self, scale_precision: int) -> None:
if 2 < scale_precision == self.__scalePrecision: return
self.__scalePrecision = scale_precision
self.update()
@property
def scaleMajor(self) -> int: return self.__scaleMajor
@scaleMajor.setter
def scaleMajor(self, scale_major: int) -> None:
if 0 >= scale_major == self.__scaleMajor: return
self.__scaleMajor = scale_major
self.update()
@property
def scaleMinor(self) -> int: return self.__scaleMinor
@scaleMinor.setter
def scaleMinor(self, scale_minor: int) -> None:
if self.__scaleMinor == scale_minor: return
self.__scaleMinor = scale_minor
self.update()
@property
def startAngle(self) -> int: return self.__startAngle
@startAngle.setter
def startAngle(self, start_angle: int) -> None:
if self.__startAngle == start_angle: return
self.__startAngle = start_angle
self.update()
@property
def endAngle(self) -> int: return self.__endAngle
@endAngle.setter
def endAngle(self, end_angle: int) -> None:
if self.__endAngle == end_angle: return
self.__endAngle = end_angle
self.update()
@property
def animation(self) -> bool: return self.__animation
@animation.setter
def animation(self, n_animation: bool) -> None:
if self.__animation == n_animation: return
self.__animation = n_animation
self.update()
@property
def animationStep(self) -> float: return self.__animationStep
@animationStep.setter
def animationStep(self, animation_step: float) -> None:
if self.__animationStep == animation_step: return
self.__animationStep = animation_step
self.update()
@property
def ringWidth(self) -> int: return self.__ringWidth
@ringWidth.setter
def ringWidth(self, ring_width: int) -> None:
if self.__ringWidth == ring_width: return
self.__ringWidth = ring_width
self.update()
@property
def ringColor(self) -> QColor: return self.__ringColor
@ringColor.setter
def ringColor(self, ring_color: QColor) -> None:
if self.__ringColor == ring_color: return
self.__ringColor = ring_color
self.update()
@property
def scaleColor(self) -> QColor: return self.__scaleColor
@scaleColor.setter
def scaleColor(self, scale_color: QColor) -> None:
if self.__scaleColor == scale_color: return
self.__scaleColor = scale_color
self.update()
@property
def pointerColor(self) -> QColor: return self.__pointerColor
@pointerColor.setter
def pointerColor(self, pointer_color: QColor) -> None:
if self.__pointerColor == pointer_color: return
self.__pointerColor = pointer_color
self.update()
@property
def bgColor(self) -> QColor: return self.__bgColor
@bgColor.setter
def bgColor(self, bg_color: QColor) -> None:
if self.__bgColor == bg_color: return
self.__bgColor = bg_color
self.update()
@property
def textColor(self) -> QColor: return self.__textColor
@textColor.setter
def textColor(self, text_color: QColor) -> None:
if self.__textColor == text_color: return
self.__textColor = text_color
self.update()
@property
def unit(self) -> str: return self.__unit
@unit.setter
def unit(self, n_unit: str) -> None:
if self.__unit == n_unit: return
self.__unit = n_unit
self.update()
@property
def text(self) -> str: return self.__text
@text.setter
def text(self, n_text: str) -> None:
if self.__text == n_text: return
self.__text = n_text
self.update()
def sizeHint(self) -> QSize: return QSize(200, 200)
def minimumSizeHint(self) -> QSize: return QSize(50, 50)
if __name__ == '__main__':
import sys
from typing import List
from PySide2.QtCore import Qt, QTextCodec
from PySide2.QtGui import QFont
from PySide2.QtWidgets import QApplication, QSlider, QGridLayout
class FrmGaugePanel(QWidget):
def __init__(self, parent: QWidget = None):
super(FrmGaugePanel, self).__init__(parent)
layout = QGridLayout()
self.gaugePanel1 = GaugePanel()
self.gaugePanel2 = GaugePanel()
self.gaugePanel3 = GaugePanel()
self.horizontalSlider1 = QSlider(Qt.Horizontal)
self.horizontalSlider2 = QSlider(Qt.Horizontal)
self.horizontalSlider3 = QSlider(Qt.Horizontal)
layout.addWidget(self.gaugePanel1, 0, 0)
layout.addWidget(self.gaugePanel2, 0, 1)
layout.addWidget(self.gaugePanel3, 0, 2)
layout.addWidget(self.horizontalSlider1, 1, 0)
layout.addWidget(self.horizontalSlider2, 1, 1)
layout.addWidget(self.horizontalSlider3, 1, 2)
self.gaugePanel4 = GaugePanel()
self.gaugePanel5 = GaugePanel()
self.gaugePanel6 = GaugePanel()
self.horizontalSlider4 = QSlider(Qt.Horizontal)
self.horizontalSlider5 = QSlider(Qt.Horizontal)
self.horizontalSlider6 = QSlider(Qt.Horizontal)
layout.addWidget(self.gaugePanel4, 2, 0)
layout.addWidget(self.gaugePanel5, 2, 1)
layout.addWidget(self.gaugePanel6, 2, 2)
layout.addWidget(self.horizontalSlider4, 3, 0)
layout.addWidget(self.horizontalSlider5, 3, 1)
layout.addWidget(self.horizontalSlider6, 3, 2)
self.setLayout(layout)
self.initForm()
def initForm(self) -> None:
# 通过设置样式来设置颜色,另类的方法,也可以直接调用函数设置
self.setStyleSheet("background:#222939;")
# 设置单位
self.gaugePanel1.unit = "V"
self.gaugePanel2.unit = "A"
self.gaugePanel3.unit = "m"
self.gaugePanel4.unit = "kW"
self.gaugePanel5.unit = "kWh"
self.gaugePanel6.unit = "Hz"
for gaugePanel in [self.gaugePanel1, self.gaugePanel2, self.gaugePanel3,
self.gaugePanel4, self.gaugePanel5, self.gaugePanel6]:
gaugePanel.ringColor = QColor('#393F4D')
gaugePanel.scaleColor = QColor('#03B7C9')
gaugePanel.pointerColor = QColor('#03B7C9')
gaugePanel.textColor = QColor('#EEEEEE')
# 设置名称
self.gaugePanel1.text = "电压"
self.gaugePanel2.text = "电流"
self.gaugePanel3.text = "水位"
self.gaugePanel4.text = "有功功率"
self.gaugePanel5.text = "有功电能"
self.gaugePanel6.text = "电网频率"
# 设置小数点
self.gaugePanel3.precision = 1
self.gaugePanel4.precision = 2
self.gaugePanel5.precision = 1
self.gaugePanel3.scalePrecision = 1
# 设置启用动画
self.gaugePanel4.animation = True
self.gaugePanel5.animation = True
self.gaugePanel5.animationStep = 0.2
# 设置范围值
self.gaugePanel1.setRange(0, 500)
self.gaugePanel2.setRange(0, 60)
self.gaugePanel3.setRange(0, 2)
self.gaugePanel4.setRange(0, 50)
self.gaugePanel5.setRange(0, 70)
self.gaugePanel6.setRange(0, 100)
self.horizontalSlider1.setRange(0, 500)
self.horizontalSlider2.setRange(0, 60)
self.horizontalSlider3.setRange(0, 200)
self.horizontalSlider4.setRange(0, 50)
self.horizontalSlider5.setRange(0, 70)
self.horizontalSlider6.setRange(0, 100)
# 绑定滑块
self.horizontalSlider1.valueChanged.connect(self.gaugePanel1.setValue)
self.horizontalSlider2.valueChanged.connect(self.gaugePanel2.setValue)
self.horizontalSlider3.valueChanged.connect(self.on_horizontalSlider3_valueChanged)
self.horizontalSlider4.valueChanged.connect(self.gaugePanel4.setValue)
self.horizontalSlider5.valueChanged.connect(self.gaugePanel5.setValue)
self.horizontalSlider6.valueChanged.connect(self.gaugePanel6.setValue)
# 设置初始值
self.horizontalSlider1.value = 220
self.horizontalSlider2.value = 32
self.horizontalSlider3.value = 150
self.horizontalSlider4.value = 6.34
self.horizontalSlider5.value = 6.28
self.horizontalSlider6.value = 50
def on_horizontalSlider3_valueChanged(self, value: int) -> None:
v = value / 100
self.gaugePanel3.value = v
app = QApplication()
app.setFont(QFont("Microsoft Yahei", 9))
codec: QTextCodec = QTextCodec.codecForName(b"utf-8")
QTextCodec.setCodecForLocale(codec)
window = FrmGaugePanel()
window.resize(500, 300)
window.setWindowTitle("面板仪表盘")
window.show()
sys.exit(app.exec_())
|
FizzCorp/fizz-platform
|
components/event-processing/src/main/java/io/fizz/analytics/common/source/hive/HiveEventFields.java
|
package io.fizz.analytics.common.source.hive;
public enum HiveEventFields {
SESSION_LENGTH("len"),
TEXT_MESSAGE_CONTENT("content"),
TEXT_MESSAGE_CHANNEL("channel"),
TEXT_MESSAGE_NICK("nick"),
TRANS_LANG_FROM("from"),
TRANS_LANG_TO("to"),
TRANS_TEXT_LEN("len"),
TRANS_TEXT_MESSAGE_ID("messageId"),
PURCHASE_PRODUCT_ID("pid"),
PURCHASE_AMOUNT("amount"),
PURCHASE_RECEIPT("receipt"),
SENTIMENT_SCORE("sentScore"),
TEXT_MESSAGE_KEYWORDS("keywords"),
PROFILE_OLDEST_ACTIVITY_TS("oldestTS"),
PROFILE_LATEST_ACTIVITY_TS("latestTS"),
PROFILE_SPENT("spent"),
PROFILE_SENTIMENT_SUM("sentimentSum"),
PROFILE_MESSAGE_COUNT("messageCount");
private final String value;
HiveEventFields(final String aValue) {
value = aValue;
}
public String value() {
return value;
}
}
|
tlhhup/springboot-2.0.x
|
chapter-10/src/test/java/org/tlh/log4j2/TextLoggerTest.java
|
<filename>chapter-10/src/test/java/org/tlh/log4j2/TextLoggerTest.java
package org.tlh.log4j2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.junit.Test;
/**
* Created by 离歌笑tlh/hu ping on 2019/2/19
* <p>
* Github: https://github.com/tlhhup
*/
public class TextLoggerTest {
@Test
public void log(){
LoggerContext ctx=(LoggerContext) LogManager.getContext();
Logger file = ctx.getLogger("file");
file.info("");
file.info("{}\t{}\t{}",1,2,200);
file.info("{}\t{}\t{}",1,2,200);
file.info("{}\t{}\t{}",1,2,200);
file.info("{}\t{}\t{}",1,2,200);
file.info("{}\t{}\t{}",1,2,200);
file.info("{}\t{}\t{}",1,2,200);
file.info("{}\t{}\t{}",1,2,200);
}
}
|
gcusnieux/jooby
|
jooby/src/test/java/org/jooby/internal/mvc/RequestParamNameProviderTest.java
|
<gh_stars>0
package org.jooby.internal.mvc;
import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.jooby.Env;
import org.jooby.internal.RouteMetadata;
import org.jooby.test.MockUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(RequestParam.class )
public class RequestParamNameProviderTest {
public void dummy(final String dummyparam) {
}
@Test
public void asmname() throws Exception {
Method m = RequestParamNameProviderTest.class.getDeclaredMethod("dummy", String.class);
Parameter param = m.getParameters()[0];
new MockUnit(Env.class)
.expect(unit -> {
Env env = unit.get(Env.class);
expect(env.name()).andReturn("dev");
})
.expect(unit -> {
unit.mockStatic(RequestParam.class);
expect(RequestParam.nameFor(param)).andReturn(null);
})
.run(unit -> {
assertEquals("dummyparam",
new RequestParamNameProviderImpl(new RouteMetadata(unit.get(Env.class))).name(param));
});
}
}
|
Mdanish777/Programmers-Community
|
Data Structure/Array Or Vector/Insertion Sort/SolutionByAryamon.cpp
|
<reponame>Mdanish777/Programmers-Community
//To apply insertion sort
#include <conio.h>
#include <iostream.h>
void swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void display(int a[], int size)
{
for (int j = 0; j < size; j++) {
cout << a[j] << " ";
}
}
void Insertion(int a[], int size)
{
int key, j;
for (int i = 1; i < size; i++) {
key = a[i];
j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
display(a, size);
cout << endl;
}
}
void main()
{
int size;
clrscr();
cout << "\nEnter the size\n ";
cin >> size;
int* a = new int[size];
cout << "\nEnter the elements of the array\t:\t ";
for (int i = 0; i < size; i++) {
cin >> a[i];
}
Insertion(a, size);
getch();
}
|
Divs123/MyRepo
|
node_modules/ngx-pipes/esm/pipes/math/pow.js
|
<filename>node_modules/ngx-pipes/esm/pipes/math/pow.js
import { Pipe } from '@angular/core';
var PowerPipe = (function () {
function PowerPipe() {
}
PowerPipe.prototype.transform = function (num, power) {
if (power === void 0) { power = 2; }
return !isNaN(num)
? Math.pow(num, power)
: num;
};
return PowerPipe;
}());
export { PowerPipe };
PowerPipe.decorators = [
{ type: Pipe, args: [{ name: 'pow' },] },
];
/** @nocollapse */
PowerPipe.ctorParameters = function () { return []; };
//# sourceMappingURL=pow.js.map
|
hadoop835/hotkey
|
common/src/main/java/com/jd/platform/hotkey/common/tool/Constant.java
|
package com.jd.platform.hotkey.common.tool;
/**
* @author wuweifeng wrote on 2019-12-05
* @version 1.0
*/
public class Constant {
public static String PING = "ping";
public static String PONG = "pong";
/**
* 该值在ProducerFactory有修改
*/
public static int Default_Threads = 4;
public static int MAGIC_NUMBER = 0x12fcf76;
/**
* netty的分隔符
*/
public static String DELIMITER = "$(* *)$";
/**
* 数量统计时,rule+时间 组成key用的分隔符
*/
public static String COUNT_DELIMITER = "#**#";
public static String BAK_DELIMITER = "#\\*\\*#";
/**
* 当客户端要删除某个key时,就往etcd里赋值这个value,设置1秒过期,就算删除了
*/
public static String DEFAULT_DELETE_VALUE = "#[DELETE]#";
//单次包最大4M
public static int MAX_LENGTH = 4 * 1024 * 1024;
}
|
Grosskopf/openoffice
|
main/fpicker/source/win32/filepicker/previewbase.cxx
|
<reponame>Grosskopf/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"
#include "previewbase.hxx"
#ifndef _COM_SUN_STAR_UI_DIALOG_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace rtl;
//-------------------------------
//
//-------------------------------
PreviewBase::PreviewBase() :
m_ImageFormat(::com::sun::star::ui::dialogs::FilePreviewImageFormats::BITMAP),
m_bShowState(sal_False)
{
}
//-------------------------------
//
//-------------------------------
PreviewBase::~PreviewBase()
{
}
//-------------------------------
//
//-------------------------------
sal_Int32 SAL_CALL PreviewBase::getTargetColorDepth() throw (RuntimeException)
{
return 0;
}
//-------------------------------
//
//-------------------------------
sal_Int32 SAL_CALL PreviewBase::getAvailableWidth() throw (RuntimeException)
{
return 0;
}
//-------------------------------
//
//-------------------------------
sal_Int32 SAL_CALL PreviewBase::getAvailableHeight() throw (RuntimeException)
{
return 0;
}
//-------------------------------
//
//-------------------------------
void SAL_CALL PreviewBase::setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
throw (IllegalArgumentException, RuntimeException)
{
if (aImageFormat != ::com::sun::star::ui::dialogs::FilePreviewImageFormats::BITMAP)
throw IllegalArgumentException(
OUString::createFromAscii("unsupported image format"), 0, 1);
if (aImage.hasValue() && (aImage.getValueType() != getCppuType((Sequence<sal_Int8>*)0)))
throw IllegalArgumentException(
OUString::createFromAscii("invalid image data"), 0, 2);
// save the new image data and force a redraw
m_ImageData = aImage;
m_ImageFormat = aImageFormat;
}
//-------------------------------
//
//-------------------------------
void SAL_CALL PreviewBase::getImage(sal_Int16& aImageFormat,com::sun::star::uno::Any& aImage)
{
aImageFormat = m_ImageFormat;
aImage = m_ImageData;
}
//-------------------------------
//
//-------------------------------
sal_Bool SAL_CALL PreviewBase::setShowState( sal_Bool bShowState ) throw (RuntimeException)
{
m_bShowState = bShowState;
return sal_True;
}
//-------------------------------
//
//-------------------------------
sal_Bool SAL_CALL PreviewBase::getShowState() throw (RuntimeException)
{
return sal_False;
}
//-------------------------------
//
//-------------------------------
sal_Bool SAL_CALL PreviewBase::getImaginaryShowState() const
{
return m_bShowState;
}
//-------------------------------
//
//-------------------------------
HWND SAL_CALL PreviewBase::getWindowHandle() const
{
return 0;
}
|
jeneser/smart-pos-api
|
src/server/db/queries/gifts.js
|
<reponame>jeneser/smart-pos-api<gh_stars>1-10
const knex = require('../connection');
function getAllGifts() {
return knex('gifts').select('*');
}
function getSingleGift(id) {
return knex('gifts')
.select('*')
.where({ itemId: id });
}
module.exports = {
getAllGifts,
getSingleGift
};
|
Nuvoton-Israel/arm-trusted-firmware
|
plat/brcm/board/stingray/src/ihost_pm.c
|
/*
* Copyright (c) 2016 - 2020, Broadcom
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <common/debug.h>
#include <drivers/delay_timer.h>
#include <lib/mmio.h>
#include <dmu.h>
#include <ihost_pm.h>
#include <platform_def.h>
#define CDRU_CCN_REGISTER_CONTROL_1__D2XS_PD_IHOST1 2
#define CDRU_CCN_REGISTER_CONTROL_1__D2XS_PD_IHOST2 1
#define CDRU_CCN_REGISTER_CONTROL_1__D2XS_PD_IHOST3 0
#define CDRU_MISC_RESET_CONTROL__CDRU_IH1_RESET 9
#define CDRU_MISC_RESET_CONTROL__CDRU_IH2_RESET 8
#define CDRU_MISC_RESET_CONTROL__CDRU_IH3_RESET 7
#define A72_CRM_SOFTRESETN_0 0x480
#define A72_CRM_SOFTRESETN_1 0x484
#define A72_CRM_DOMAIN_4_CONTROL 0x810
#define A72_CRM_DOMAIN_4_CONTROL__DOMAIN_4_ISO_DFT 3
#define A72_CRM_DOMAIN_4_CONTROL__DOMAIN_4_ISO_MEM 6
#define A72_CRM_DOMAIN_4_CONTROL__DOMAIN_4_ISO_I_O 0
#define A72_CRM_SUBSYSTEM_MEMORY_CONTROL_3 0xB4C
#define MEMORY_PDA_HI_SHIFT 0x0
#define A72_CRM_PLL_PWR_ON 0x70
#define A72_CRM_PLL_PWR_ON__PLL0_ISO_PLLOUT 4
#define A72_CRM_PLL_PWR_ON__PLL0_PWRON_LDO 1
#define A72_CRM_PLL_PWR_ON__PLL0_PWRON_PLL 0
#define A72_CRM_SUBSYSTEM_MEMORY_CONTROL_2 0xB48
#define A72_CRM_PLL_INTERRUPT_STATUS 0x8c
#define A72_CRM_PLL_INTERRUPT_STATUS__PLL0_LOCK_LOST_STATUS 8
#define A72_CRM_PLL_INTERRUPT_STATUS__PLL0_LOCK_STATUS 9
#define A72_CRM_INTERRUPT_ENABLE 0x4
#define A72_CRM_INTERRUPT_ENABLE__PLL0_INT_ENABLE 4
#define A72_CRM_PLL_INTERRUPT_ENABLE 0x88
#define A72_CRM_PLL_INTERRUPT_ENABLE__PLL0_LOCK_STATUS_INT_ENB 9
#define A72_CRM_PLL_INTERRUPT_ENABLE__PLL0_LOCK_LOST_STATUS_INT_ENB 8
#define A72_CRM_PLL0_CFG0_CTRL 0x120
#define A72_CRM_PLL0_CFG1_CTRL 0x124
#define A72_CRM_PLL0_CFG2_CTRL 0x128
#define A72_CRM_PLL0_CFG3_CTRL 0x12C
#define A72_CRM_CORE_CONFIG_DBGCTRL__DBGROMADDRV 0
#define A72_CRM_CORE_CONFIG_DBGCTRL 0xD50
#define A72_CRM_CORE_CONFIG_DBGROM_LO 0xD54
#define A72_CRM_CORE_CONFIG_DBGROM_HI 0xD58
#define A72_CRM_SUBSYSTEM_CONFIG_1__DBGL1RSTDISABLE 2
#define A72_CRM_SOFTRESETN_0__CRYSTAL26_SOFTRESETN 0
#define A72_CRM_SOFTRESETN_0__CRM_PLL0_SOFTRESETN 1
#define A72_CRM_AXI_CLK_DESC 0x304
#define A72_CRM_ACP_CLK_DESC 0x308
#define A72_CRM_ATB_CLK_DESC 0x30C
#define A72_CRM_PCLKDBG_DESC 0x310
#define A72_CRM_CLOCK_MODE_CONTROL 0x40
#define A72_CRM_CLOCK_MODE_CONTROL__CLK_CHANGE_TRIGGER 0
#define A72_CRM_CLOCK_CONTROL_0 0x200
#define A72_CRM_CLOCK_CONTROL_0__ARM_HW_SW_ENABLE_SEL 0
#define A72_CRM_CLOCK_CONTROL_0__AXI_HW_SW_ENABLE_SEL 2
#define A72_CRM_CLOCK_CONTROL_0__ACP_HW_SW_ENABLE_SEL 4
#define A72_CRM_CLOCK_CONTROL_0__ATB_HW_SW_ENABLE_SEL 6
#define A72_CRM_CLOCK_CONTROL_0__PCLKDBG_HW_SW_ENA_SEL 8
#define A72_CRM_CLOCK_CONTROL_1 0x204
#define A72_CRM_CLOCK_CONTROL_1__TMON_HW_SW_ENABLE_SEL 6
#define A72_CRM_CLOCK_CONTROL_1__APB_HW_SW_ENABLE_SEL 8
#define A72_CRM_SOFTRESETN_0__CRYSTAL26_SOFTRESETN 0
#define A72_CRM_SOFTRESETN_0__CRM_PLL0_SOFTRESETN 1
#define A72_CRM_SOFTRESETN_0__AXI_SOFTRESETN 9
#define A72_CRM_SOFTRESETN_0__ACP_SOFTRESETN 10
#define A72_CRM_SOFTRESETN_0__ATB_SOFTRESETN 11
#define A72_CRM_SOFTRESETN_0__PCLKDBG_SOFTRESETN 12
#define A72_CRM_SOFTRESETN_0__TMON_SOFTRESETN 15
#define A72_CRM_SOFTRESETN_0__L2_SOFTRESETN 3
#define A72_CRM_SOFTRESETN_1__APB_SOFTRESETN 8
/* core related regs */
#define A72_CRM_DOMAIN_0_CONTROL 0x800
#define A72_CRM_DOMAIN_0_CONTROL__DOMAIN_0_ISO_MEM 0x6
#define A72_CRM_DOMAIN_0_CONTROL__DOMAIN_0_ISO_I_O 0x0
#define A72_CRM_DOMAIN_1_CONTROL 0x804
#define A72_CRM_DOMAIN_1_CONTROL__DOMAIN_1_ISO_MEM 0x6
#define A72_CRM_DOMAIN_1_CONTROL__DOMAIN_1_ISO_I_O 0x0
#define A72_CRM_CORE_CONFIG_RVBA0_LO 0xD10
#define A72_CRM_CORE_CONFIG_RVBA0_MID 0xD14
#define A72_CRM_CORE_CONFIG_RVBA0_HI 0xD18
#define A72_CRM_CORE_CONFIG_RVBA1_LO 0xD20
#define A72_CRM_CORE_CONFIG_RVBA1_MID 0xD24
#define A72_CRM_CORE_CONFIG_RVBA1_HI 0xD28
#define A72_CRM_SUBSYSTEM_CONFIG_0 0xC80
#define A72_CRM_SUBSYSTEM_CONFIG_0__DBGPWRDUP_CFG_SHIFT 4
#define A72_CRM_SOFTRESETN_0__COREPOR0_SOFTRESETN 4
#define A72_CRM_SOFTRESETN_0__COREPOR1_SOFTRESETN 5
#define A72_CRM_SOFTRESETN_1__CORE0_SOFTRESETN 0
#define A72_CRM_SOFTRESETN_1__DEBUG0_SOFTRESETN 4
#define A72_CRM_SOFTRESETN_1__CORE1_SOFTRESETN 1
#define A72_CRM_SOFTRESETN_1__DEBUG1_SOFTRESETN 5
#define SPROC_MEMORY_BISR 0
static int cluster_power_status[PLAT_BRCM_CLUSTER_COUNT] = {CLUSTER_POWER_ON,
CLUSTER_POWER_OFF,
CLUSTER_POWER_OFF,
CLUSTER_POWER_OFF};
void ihost_power_on_cluster(u_register_t mpidr)
{
uint32_t rst, d2xs;
uint32_t cluster_id;
uint32_t ihost_base;
#if SPROC_MEMORY_BISR
uint32_t bisr, cnt;
#endif
cluster_id = MPIDR_AFFLVL1_VAL(mpidr);
uint32_t cluster0_freq_sel;
if (cluster_power_status[cluster_id] == CLUSTER_POWER_ON)
return;
cluster_power_status[cluster_id] = CLUSTER_POWER_ON;
INFO("enabling Cluster #%u\n", cluster_id);
switch (cluster_id) {
case 1:
rst = (1 << CDRU_MISC_RESET_CONTROL__CDRU_IH1_RESET);
d2xs = (1 << CDRU_CCN_REGISTER_CONTROL_1__D2XS_PD_IHOST1);
#if SPROC_MEMORY_BISR
bisr = CRMU_BISR_PDG_MASK__CRMU_BISR_IHOST1;
#endif
break;
case 2:
rst = (1 << CDRU_MISC_RESET_CONTROL__CDRU_IH2_RESET);
d2xs = (1 << CDRU_CCN_REGISTER_CONTROL_1__D2XS_PD_IHOST2);
#if SPROC_MEMORY_BISR
bisr = CRMU_BISR_PDG_MASK__CRMU_BISR_IHOST2;
#endif
break;
case 3:
rst = (1 << CDRU_MISC_RESET_CONTROL__CDRU_IH3_RESET);
d2xs = (1 << CDRU_CCN_REGISTER_CONTROL_1__D2XS_PD_IHOST3);
#if SPROC_MEMORY_BISR
bisr = CRMU_BISR_PDG_MASK__CRMU_BISR_IHOST3;
#endif
break;
default:
ERROR("Invalid cluster :%u\n", cluster_id);
return;
}
/* Releasing ihost resets */
mmio_setbits_32(CDRU_MISC_RESET_CONTROL, rst);
/* calculate cluster/ihost base address */
ihost_base = IHOST0_BASE + cluster_id * IHOST_ADDR_SPACE;
/* Remove Cluster IO isolation */
mmio_clrsetbits_32(ihost_base + A72_CRM_DOMAIN_4_CONTROL,
(1 << A72_CRM_DOMAIN_4_CONTROL__DOMAIN_4_ISO_I_O),
(1 << A72_CRM_DOMAIN_4_CONTROL__DOMAIN_4_ISO_DFT) |
(1 << A72_CRM_DOMAIN_4_CONTROL__DOMAIN_4_ISO_MEM));
/*
* Since BISR sequence requires that all cores of cluster should
* have removed I/O isolation hence doing same here.
*/
/* Remove core0 memory IO isolations */
mmio_clrsetbits_32(ihost_base + A72_CRM_DOMAIN_0_CONTROL,
(1 << A72_CRM_DOMAIN_0_CONTROL__DOMAIN_0_ISO_I_O),
(1 << A72_CRM_DOMAIN_0_CONTROL__DOMAIN_0_ISO_MEM));
/* Remove core1 memory IO isolations */
mmio_clrsetbits_32(ihost_base + A72_CRM_DOMAIN_1_CONTROL,
(1 << A72_CRM_DOMAIN_1_CONTROL__DOMAIN_1_ISO_I_O),
(1 << A72_CRM_DOMAIN_1_CONTROL__DOMAIN_1_ISO_MEM));
#if SPROC_MEMORY_BISR
mmio_setbits_32(CRMU_BISR_PDG_MASK, (1 << bisr));
if (!(mmio_read_32(CDRU_CHIP_STRAP_DATA_LSW) &
(1 << CDRU_CHIP_STRAP_DATA_LSW__BISR_BYPASS_MODE))) {
/* BISR completion would take max 2 usec */
cnt = 0;
while (cnt < 2) {
udelay(1);
if (mmio_read_32(CRMU_CHIP_OTPC_STATUS) &
(1 << CRMU_CHIP_OTPC_STATUS__OTP_BISR_LOAD_DONE))
break;
cnt++;
}
}
/* if BISR is not completed, need to be checked with ASIC team */
if (((mmio_read_32(CRMU_CHIP_OTPC_STATUS)) &
(1 << CRMU_CHIP_OTPC_STATUS__OTP_BISR_LOAD_DONE)) == 0) {
WARN("BISR did not completed and need to be addressed\n");
}
#endif
/* PLL Power up. supply is already on. Turn on PLL LDO/PWR */
mmio_write_32(ihost_base + A72_CRM_PLL_PWR_ON,
(1 << A72_CRM_PLL_PWR_ON__PLL0_ISO_PLLOUT) |
(1 << A72_CRM_PLL_PWR_ON__PLL0_PWRON_LDO) |
(1 << A72_CRM_PLL_PWR_ON__PLL0_PWRON_PLL));
/* 1us in spec; Doubling it to be safe*/
udelay(2);
/* Remove PLL output ISO */
mmio_write_32(ihost_base + A72_CRM_PLL_PWR_ON,
(1 << A72_CRM_PLL_PWR_ON__PLL0_PWRON_LDO) |
(1 << A72_CRM_PLL_PWR_ON__PLL0_PWRON_PLL));
/*
* PLL0 Configuration Control Register
* these 4 registers drive the i_pll_ctrl[63:0] input of pll
* (16b per register).
* the values are derived from the spec (sections 8 and 10).
*/
mmio_write_32(ihost_base + A72_CRM_PLL0_CFG0_CTRL, 0x00000000);
mmio_write_32(ihost_base + A72_CRM_PLL0_CFG1_CTRL, 0x00008400);
mmio_write_32(ihost_base + A72_CRM_PLL0_CFG2_CTRL, 0x00000001);
mmio_write_32(ihost_base + A72_CRM_PLL0_CFG3_CTRL, 0x00000000);
/* Read the freq_sel from cluster 0, which is up already */
cluster0_freq_sel = bcm_get_ihost_pll_freq(0);
bcm_set_ihost_pll_freq(cluster_id, cluster0_freq_sel);
udelay(1);
/* Release clock source reset */
mmio_setbits_32(ihost_base + A72_CRM_SOFTRESETN_0,
(1 << A72_CRM_SOFTRESETN_0__CRYSTAL26_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_0__CRM_PLL0_SOFTRESETN));
udelay(1);
/*
* Integer division for clks (divider value = n+1).
* These are the divisor of ARM PLL clock frequecy.
*/
mmio_write_32(ihost_base + A72_CRM_AXI_CLK_DESC, 0x00000001);
mmio_write_32(ihost_base + A72_CRM_ACP_CLK_DESC, 0x00000001);
mmio_write_32(ihost_base + A72_CRM_ATB_CLK_DESC, 0x00000004);
mmio_write_32(ihost_base + A72_CRM_PCLKDBG_DESC, 0x0000000b);
/*
* clock change trigger - must set to take effect after clock
* source change
*/
mmio_setbits_32(ihost_base + A72_CRM_CLOCK_MODE_CONTROL,
(1 << A72_CRM_CLOCK_MODE_CONTROL__CLK_CHANGE_TRIGGER));
/* turn on functional clocks */
mmio_setbits_32(ihost_base + A72_CRM_CLOCK_CONTROL_0,
(3 << A72_CRM_CLOCK_CONTROL_0__ARM_HW_SW_ENABLE_SEL) |
(3 << A72_CRM_CLOCK_CONTROL_0__AXI_HW_SW_ENABLE_SEL) |
(3 << A72_CRM_CLOCK_CONTROL_0__ACP_HW_SW_ENABLE_SEL) |
(3 << A72_CRM_CLOCK_CONTROL_0__ATB_HW_SW_ENABLE_SEL) |
(3 << A72_CRM_CLOCK_CONTROL_0__PCLKDBG_HW_SW_ENA_SEL));
mmio_setbits_32(ihost_base + A72_CRM_CLOCK_CONTROL_1,
(3 << A72_CRM_CLOCK_CONTROL_1__TMON_HW_SW_ENABLE_SEL) |
(3 << A72_CRM_CLOCK_CONTROL_1__APB_HW_SW_ENABLE_SEL));
/* Program D2XS Power Down Registers */
mmio_setbits_32(CDRU_CCN_REGISTER_CONTROL_1, d2xs);
/* Program Core Config Debug ROM Address Registers */
/* mark valid for Debug ROM base address */
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_DBGCTRL,
(1 << A72_CRM_CORE_CONFIG_DBGCTRL__DBGROMADDRV));
/* Program Lo and HI address of coresight DBG rom address */
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_DBGROM_LO,
(CORESIGHT_BASE_ADDR >> 12) & 0xffff);
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_DBGROM_HI,
(CORESIGHT_BASE_ADDR >> 28) & 0xffff);
/*
* Release soft resets of different components.
* Order: Bus clocks --> PERIPH --> L2 --> cores
*/
/* Bus clocks soft resets */
mmio_setbits_32(ihost_base + A72_CRM_SOFTRESETN_0,
(1 << A72_CRM_SOFTRESETN_0__CRYSTAL26_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_0__CRM_PLL0_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_0__AXI_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_0__ACP_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_0__ATB_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_0__PCLKDBG_SOFTRESETN));
mmio_setbits_32(ihost_base + A72_CRM_SOFTRESETN_1,
(1 << A72_CRM_SOFTRESETN_1__APB_SOFTRESETN));
/* Periph component softreset */
mmio_setbits_32(ihost_base + A72_CRM_SOFTRESETN_0,
(1 << A72_CRM_SOFTRESETN_0__TMON_SOFTRESETN));
/* L2 softreset */
mmio_setbits_32(ihost_base + A72_CRM_SOFTRESETN_0,
(1 << A72_CRM_SOFTRESETN_0__L2_SOFTRESETN));
/* Enable and program Satellite timer */
ihost_enable_satellite_timer(cluster_id);
}
void ihost_power_on_secondary_core(u_register_t mpidr, uint64_t rvbar)
{
uint32_t ihost_base;
uint32_t coreid = MPIDR_AFFLVL0_VAL(mpidr);
uint32_t cluster_id = MPIDR_AFFLVL1_VAL(mpidr);
ihost_base = IHOST0_BASE + cluster_id * IHOST_ADDR_SPACE;
INFO("programming core #%u\n", coreid);
if (coreid) {
/* program the entry point for core1 */
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_RVBA1_LO,
rvbar & 0xFFFF);
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_RVBA1_MID,
(rvbar >> 16) & 0xFFFF);
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_RVBA1_HI,
(rvbar >> 32) & 0xFFFF);
} else {
/* program the entry point for core */
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_RVBA0_LO,
rvbar & 0xFFFF);
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_RVBA0_MID,
(rvbar >> 16) & 0xFFFF);
mmio_write_32(ihost_base + A72_CRM_CORE_CONFIG_RVBA0_HI,
(rvbar >> 32) & 0xFFFF);
}
/* Tell debug logic which processor is up */
mmio_setbits_32(ihost_base + A72_CRM_SUBSYSTEM_CONFIG_0,
(coreid ?
(2 << A72_CRM_SUBSYSTEM_CONFIG_0__DBGPWRDUP_CFG_SHIFT) :
(1 << A72_CRM_SUBSYSTEM_CONFIG_0__DBGPWRDUP_CFG_SHIFT)));
/* releasing soft resets for IHOST core */
mmio_setbits_32(ihost_base + A72_CRM_SOFTRESETN_0,
(coreid ?
(1 << A72_CRM_SOFTRESETN_0__COREPOR1_SOFTRESETN) :
(1 << A72_CRM_SOFTRESETN_0__COREPOR0_SOFTRESETN)));
mmio_setbits_32(ihost_base + A72_CRM_SOFTRESETN_1,
(coreid ?
((1 << A72_CRM_SOFTRESETN_1__CORE1_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_1__DEBUG1_SOFTRESETN)) :
((1 << A72_CRM_SOFTRESETN_1__CORE0_SOFTRESETN) |
(1 << A72_CRM_SOFTRESETN_1__DEBUG0_SOFTRESETN))));
}
|
AlbandeCrevoisier/ldd-athens
|
app.c
|
<reponame>AlbandeCrevoisier/ldd-athens<filename>app.c
/* Read some values of the accelerometer adxl345 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <stropts.h>
#include <sys/file.h>
int
main(int argc, char *argv[])
{
int ret = 0;
int fd = 0;
int8_t buf[2];
if (argc != 2) {
printf("Usage: ./app CHANNEL\n");
return -EINVAL;
}
fd = open("/dev/adxl345", O_RDWR);
if (!fd) {
printf("Opening /dev/adxl345 failed: %d\n", errno);
return 0;
}
ret = ioctl(fd, 4242, argv[1][0]);
if (ret == -1) {
printf("ioctl failed: %d\n", errno);
return 0;
}
ret = read(fd, buf, 2);
if (ret < 0) {
printf("Reading /dev/adxl345 failed: %d\n", errno);
return 0;
}
printf("%d %d\n", (int) buf[0], (int) buf[1]);
return 0;
}
|
ryecrow/xdakit
|
src/main/java/io/technicrow/xdakit/sxc/StructureData.java
|
<gh_stars>0
package io.technicrow.xdakit.sxc;
public class StructureData {
}
|
ISoirar/pypp11
|
pypp11/code_creators/global_variable.py
|
<gh_stars>1-10
# Copyright 2004-2008 <NAME>.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import os
import pygccxml
import algorithm
import code_creator
import ctypes_formatter
import declaration_based
import registration_based
from pygccxml import declarations
from pypp11 import code_repository
from pypp11 import decl_wrappers
class global_variable_base_t( registration_based.registration_based_t
, declaration_based.declaration_based_t ):
"""
Base class for all global variables code creators. Mainly exists to
simplify file writers algorithms.
"""
def __init__(self, variable, wrapper=None ):
registration_based.registration_based_t.__init__( self )
declaration_based.declaration_based_t.__init__( self, declaration=variable)
self._wrapper = wrapper
def _get_wrapper( self ):
return self._wrapper
def _set_wrapper( self, new_wrapper ):
self._wrapper = new_wrapper
wrapper = property( _get_wrapper, _set_wrapper )
def _get_system_files_impl( self ):
return []
class global_variable_t( global_variable_base_t ):
"""
Creates boost.python code that exposes global variable.
"""
def __init__(self, variable ):
global_variable_base_t.__init__( self, variable=variable )
def _create_impl(self):
if self.declaration.already_exposed:
return ''
assert isinstance( self.declaration, pygccxml.declarations.variable_t )
result = []
result.append( algorithm.create_identifier( self, '::boost::python::scope' ) )
result.append( '().attr("%s")' % self.alias )
dtype = self.declaration.type
if decl_wrappers.python_traits.is_immutable( dtype ) \
or pygccxml.declarations.is_const( dtype ) \
or pygccxml.declarations.smart_pointer_traits.is_smart_pointer( dtype ):
result.append( ' = %s;' % self.decl_identifier )
else:
obj_identifier = algorithm.create_identifier( self, '::boost::python::object' )
ref_identifier = algorithm.create_identifier( self, '::boost::ref' )
result.append( ' = %s( %s( %s ) );' % ( obj_identifier, ref_identifier, self.decl_identifier ) )
return ''.join( result )
class array_gv_t( global_variable_base_t ):
"""
Creates boost.python code that exposes array global variable.
"""
_PARAM_SEPARATOR = ', '
def __init__(self, variable, wrapper ):
global_variable_base_t.__init__( self, variable=variable, wrapper=wrapper )
def _get_system_files_impl( self ):
return []
def _create_impl( self ):
if self.declaration.already_exposed:
return ''
answer = []
answer.append( algorithm.create_identifier( self, '::boost::python::scope' ) )
answer.append( '().attr("%s")' % self.alias )
answer.append( ' = ' )
answer.append( self.wrapper.wrapper_creator_full_name )
answer.append( '();' )
return ''.join( answer )
class array_gv_wrapper_t( code_creator.code_creator_t
, declaration_based.declaration_based_t ):
"""
Creates C++ code that register array class.
"""
def __init__(self, variable ):
code_creator.code_creator_t.__init__( self )
declaration_based.declaration_based_t.__init__( self, declaration=variable)
def _get_wrapper_type( self ):
ns_name = code_repository.array_1.namespace
if declarations.is_const( self.declaration.type ):
class_name = 'const_array_1_t'
else:
class_name = 'array_1_t'
decl_string = declarations.templates.join(
'::'.join( [ns_name, class_name] )
, [ declarations.array_item_type( self.declaration.type ).decl_string
, str( declarations.array_size( self.declaration.type ) )
])
return declarations.dummy_type_t( decl_string )
wrapper_type = property( _get_wrapper_type )
def _get_wrapper_creator_type(self):
return declarations.free_function_type_t.create_decl_string(
return_type=self.wrapper_type
, arguments_types=[]
, with_defaults=False)
wrapper_creator_type = property( _get_wrapper_creator_type )
def _get_wrapper_creator_name(self):
return '_'.join( [self.declaration.name, 'wrapper'] )
wrapper_creator_name = property( _get_wrapper_creator_name )
def _create_namespaces(self):
ns_names = declarations.declaration_path( self.declaration.parent )
if len(ns_names) >= 1 and ns_names[0] == '::':
ns_names = ns_names[1:]
return ns_names
def _get_wrapper_creator_full_name(self):
names = self._create_namespaces()
names.append( self.wrapper_creator_name )
return '::'.join( names )
wrapper_creator_full_name = property( _get_wrapper_creator_full_name )
def _create_namespaces_name(self):
temp = []
for ns_name in self._create_namespaces():
temp.append( ''.join( ['namespace ', ns_name, '{ '] ) )
return ''.join( temp )
def _create_impl( self ):
if self.declaration.already_exposed:
return ''
answer = [self._create_namespaces_name()]
answer.append( self.wrapper_type.decl_string )
answer.append( ''.join([ self.wrapper_creator_name, '(){']) )
temp = ''.join([ 'return '
, self.wrapper_type.decl_string
, '( '
, declarations.full_name( self.declaration )
, ' );'])
answer.append( self.indent( temp ) )
answer.append('}')
answer.append( '}' * len( self._create_namespaces() ) )
return os.linesep.join( answer )
def _get_system_files_impl( self ):
return [code_repository.array_1.file_name]
class global_variable_addressof_t( global_variable_base_t ):
"""
Creates boost.python code that exposes address of global variable.
This functionality is pretty powerful if you use it with "ctypes" -
standard package.
"""
def __init__(self, variable ):
global_variable_base_t.__init__( self, variable=variable )
def _create_impl(self):
if self.declaration.already_exposed:
return ''
assert isinstance( self.declaration, pygccxml.declarations.variable_t )
result = []
#TODO: porting to 64Bit is welcome
result.append( algorithm.create_identifier( self, '::boost::python::scope' ) )
result.append( '().attr("%s")' % self.alias )
result.append( ' = size_t( boost::addressof( %s ) );' % self.decl_identifier )
return ''.join( result )
def _get_system_files_impl( self ):
return [code_repository.ctypes_integration.file_name]
class global_variable_reference_t( code_creator.code_creator_t, declaration_based.declaration_based_t ):
def __init__( self, var ):
code_creator.code_creator_t.__init__( self )
declaration_based.declaration_based_t.__init__( self, var )
def _create_impl( self ):
return '%(alias)s = %(type)s.in_dll( %(library_var_name)s, %(library_var_name)s.undecorated_names["%(undecorated_decl_name)s"] )' \
% dict( alias=self.alias
, type=ctypes_formatter.as_ctype( self.declaration.type, self.top_parent.treat_char_ptr_as_binary_data )
, library_var_name=self.top_parent.library_var_name
, undecorated_decl_name=self.undecorated_decl_name )
def _get_system_files_impl( self ):
return []
|
domingoesteban/robolearn
|
scenarios/tests/reset-test.py
|
<gh_stars>1-10
from robolearn.old_utils.tasks.bigman.lift_box_utils import *
rospack = rospkg.RosPack()
box_sdf = open(rospack.get_path('robolearn_gazebo_env')+'/models/cardboard_cube_box/model.sdf', 'r').read()
model_name = 'box'
model_sdf = box_sdf
model_pose = [0.75, 0, 0.019, 0, 0, 0, 1]
#reset_gazebo_env = ResetGazeboEnv(model_names, model_sdfs, model_poses)
#reset_gazebo_env.reset()
#delete_gazebo_model(model_name)
#spawn_gazebo_model(model_name, model_sdf, model_pose)
#bigman_pose = get_gazebo_model_pose('bigman', 'world')
reset_bigman_box_gazebo(model_pose)
|
origandrew/katana
|
libtsuba/test/storage-format-version/v5-optional-datastructure-rdk.cpp
|
#include <cstdint>
#include <filesystem>
#include <vector>
#include <boost/filesystem.hpp>
#include "../test-rdg.h"
#include "katana/Experimental.h"
#include "katana/Galois.h"
#include "katana/Logging.h"
#include "katana/ProgressTracer.h"
#include "katana/RDG.h"
#include "katana/RDGManifest.h"
#include "katana/RDGStorageFormatVersion.h"
#include "katana/RDKLSHIndexPrimitive.h"
#include "katana/RDKSubstructureIndexPrimitive.h"
#include "katana/Result.h"
#include "katana/TextTracer.h"
#include "katana/URI.h"
std::vector<std::map<uint64_t, std::vector<uint64_t>>>
GenerateHashes() {
std::vector<std::map<uint64_t, std::vector<uint64_t>>> hashes(128);
for (uint64_t i = 0; i < 128; i++) {
for (uint64_t j = 0; j < 64; j++) {
std::map<uint64_t, std::vector<uint64_t>> tmp;
tmp[j] = {i, j, i + j};
hashes.emplace_back(tmp);
}
}
return hashes;
}
std::vector<katana::DynamicBitset>
GenerateFingerprints() {
std::vector<katana::DynamicBitset> fingerprints;
for (size_t i = 0; i < 4; i++) {
katana::DynamicBitset bset;
for (size_t j = 0; j < i; j++) {
bset.resize(j + 1);
bset.set(j);
}
fingerprints.emplace_back(std::move(bset));
}
return fingerprints;
}
std::vector<std::string>
GenerateSmiles() {
std::vector<std::string> smiles = {"smile1", "smile2", "smile3", "smile4"};
return smiles;
}
std::vector<std::vector<std::uint64_t>>
GenerateIndices() {
std::vector<std::vector<std::uint64_t>> indices(
128, std::vector<uint64_t>(64));
for (size_t i = 0; i < 128; i++) {
for (size_t j = 0; j < 64; j++) {
indices[i][j] = i + j;
}
}
return indices;
}
katana::RDKLSHIndexPrimitive
GenerateLSHIndex() {
katana::RDKLSHIndexPrimitive index;
std::vector<katana::DynamicBitset> fingerprints = GenerateFingerprints();
index.set_num_hashes_per_bucket(16);
index.set_num_buckets(96);
index.set_fingerprint_length(42);
index.set_num_fingerprints(fingerprints.size());
index.set_hash_structure(GenerateHashes());
index.set_fingerprints(std::move(fingerprints));
index.set_smiles(GenerateSmiles());
return index;
}
void
ValidateLSHIndex(katana::RDKLSHIndexPrimitive& index) {
KATANA_LOG_ASSERT(index.num_hashes_per_bucket() == 16);
KATANA_LOG_ASSERT(index.num_buckets() == 96);
KATANA_LOG_ASSERT(index.fingerprint_length() == 42);
KATANA_LOG_ASSERT(index.num_fingerprints() == 4);
KATANA_LOG_ASSERT(index.hash_structure() == GenerateHashes());
KATANA_LOG_ASSERT(index.fingerprints() == GenerateFingerprints());
KATANA_LOG_ASSERT(index.smiles() == GenerateSmiles());
}
katana::RDKSubstructureIndexPrimitive
GenerateSubstructIndex() {
katana::RDKSubstructureIndexPrimitive index;
std::vector<katana::DynamicBitset> fingerprints = GenerateFingerprints();
auto smiles = GenerateSmiles();
auto indices = GenerateIndices();
KATANA_LOG_VASSERT(
smiles.size() == fingerprints.size(), "smiles = {}, finger = {}",
smiles.size(), fingerprints.size());
index.set_fp_size(indices.size());
index.set_num_entries(smiles.size());
index.set_index(std::move(indices));
index.set_fingerprints(std::move(fingerprints));
index.set_smiles(std::move(smiles));
return index;
}
void
ValidateSubstructIndex(katana::RDKSubstructureIndexPrimitive& index) {
KATANA_LOG_ASSERT(index.fp_size() == 128);
KATANA_LOG_ASSERT(index.num_entries() == 4);
KATANA_LOG_ASSERT(index.index() == GenerateIndices());
KATANA_LOG_ASSERT(index.fingerprints() == GenerateFingerprints());
KATANA_LOG_ASSERT(index.smiles() == GenerateSmiles());
}
/*
* Tests: Optional Datastructure, RDKLSHIndexPrimitive, RDKSubstructureIndexPrimitive functionality
*
* 1) loading an RDG without an optional index and adding one to it (RDKLSHIndexPrimitive)
* 2) storing an RDG with an optional index (RDKLSHIndexPrimitive)
* 3) loading an RDG with an optional index (RDKLSHIndexPrimitive)
* 4) storing an RDG with 2 optional indices (RDKLSHIndexPrimitive, RDKSubstructureIndexPrimitive)
* 5) loading an RDG with 2 optional indices (RDKLSHIndexPrimitive, RDKSubstructureIndexPrimitive)
*/
katana::Result<void>
TestRoundTripRDKIndex(const std::string& rdg_dir) {
KATANA_LOG_ASSERT(!rdg_dir.empty());
katana::RDKLSHIndexPrimitive lsh_index = GenerateLSHIndex();
ValidateLSHIndex(lsh_index);
// load the rdg, no optional indices present
katana::RDG rdg = KATANA_CHECKED(LoadRDG(rdg_dir));
// write out an optional index
KATANA_CHECKED(rdg.WriteRDKLSHIndexPrimitive(lsh_index));
// Read the index back and ensure it matches what we put in
std::optional<katana::RDKLSHIndexPrimitive> lsh_index_res_2 =
KATANA_CHECKED(rdg.LoadRDKLSHIndexPrimitive());
KATANA_LOG_ASSERT(lsh_index_res_2);
katana::RDKLSHIndexPrimitive& lsh_index_2 = lsh_index_res_2.value();
ValidateLSHIndex(lsh_index_2);
// Store the RDG in a new location
std::string rdg_dir2 = KATANA_CHECKED(WriteRDG(std::move(rdg)));
// Load the RDG from the new location
katana::RDG rdg2 = KATANA_CHECKED(LoadRDG(rdg_dir2));
// Ensure our index is still correct
std::optional<katana::RDKLSHIndexPrimitive> lsh_index_res_3 =
KATANA_CHECKED(rdg2.LoadRDKLSHIndexPrimitive());
KATANA_LOG_ASSERT(lsh_index_res_3);
katana::RDKLSHIndexPrimitive& lsh_index_3 = lsh_index_res_3.value();
ValidateLSHIndex(lsh_index_3);
// Add a different optional index
katana::RDKSubstructureIndexPrimitive substruct_index =
GenerateSubstructIndex();
KATANA_CHECKED(rdg2.WriteRDKSubstructureIndexPrimitive(substruct_index));
// Read it back right away and ensure it matches what we put in
std::optional<katana::RDKSubstructureIndexPrimitive> substruct_index_res_2 =
KATANA_CHECKED(rdg2.LoadRDKSubstructureIndexPrimitive());
KATANA_LOG_ASSERT(substruct_index_res_2);
katana::RDKSubstructureIndexPrimitive& substruct_index_2 =
substruct_index_res_2.value();
ValidateSubstructIndex(substruct_index_2);
// Store the RDG in a new location
std::string rdg_dir3 = KATANA_CHECKED(WriteRDG(std::move(rdg2)));
// Load the RDG from the new location
katana::RDG rdg3 = KATANA_CHECKED(LoadRDG(rdg_dir3));
// Ensure both of our indices are still correct
std::optional<katana::RDKSubstructureIndexPrimitive> substruct_index_res_3 =
KATANA_CHECKED(rdg3.LoadRDKSubstructureIndexPrimitive());
KATANA_LOG_ASSERT(substruct_index_res_3);
katana::RDKSubstructureIndexPrimitive& substruct_index_3 =
substruct_index_res_3.value();
ValidateSubstructIndex(substruct_index_3);
std::optional<katana::RDKLSHIndexPrimitive> lsh_index_res_4 =
KATANA_CHECKED(rdg3.LoadRDKLSHIndexPrimitive());
KATANA_LOG_ASSERT(lsh_index_res_4);
katana::RDKLSHIndexPrimitive& lsh_index_4 = lsh_index_res_4.value();
ValidateLSHIndex(lsh_index_4);
return katana::ResultSuccess();
}
/*
* Tests that we fail loading an invalid version of an optional topology
* and that we fail in a way that the caller can recover from
*/
katana::Result<void>
TestLoadFail(const std::string& rdg_dir) {
// make a copy of the RDG in a new location
katana::RDG rdg = KATANA_CHECKED(LoadRDG(rdg_dir));
// add an optional index
katana::RDKLSHIndexPrimitive lsh_index = GenerateLSHIndex();
ValidateLSHIndex(lsh_index);
KATANA_CHECKED(rdg.WriteRDKLSHIndexPrimitive(lsh_index));
std::string rdg_dir2 = KATANA_CHECKED(WriteRDG(std::move(rdg)));
// Load the RDG from the new location
katana::RDG rdg2 = KATANA_CHECKED(LoadRDG(rdg_dir2));
// make a garbage json file in the place of an optional datastructure
std::vector dummy = {"these", "are", "some", "bad", "values"};
std::string serialized = KATANA_CHECKED(katana::JsonDump(dummy));
// POSIX files end with newlines
serialized = serialized + "\n";
auto ff = std::make_unique<katana::FileFrame>();
KATANA_CHECKED(ff->Init(serialized.size()));
if (auto res = ff->Write(serialized.data(), serialized.size()); !res.ok()) {
return KATANA_ERROR(
katana::ArrowToKatana(res.code()), "arrow error: {}", res);
}
// write garbage over existing optional datastructure manifest
// rdg must have only one of these manifests available for this test to function propertly
std::string path =
KATANA_CHECKED(find_file(rdg_dir2, "rdk_lsh_index_manifest"));
std::filesystem::remove(path);
ff->Bind(path);
KATANA_CHECKED(ff->Persist());
// expect this to fail
auto res = rdg2.LoadRDKLSHIndexPrimitive();
if (res) {
KATANA_LOG_ASSERT("Loading the garbage manifest should fail!");
}
return katana::ResultSuccess();
}
int
main(int argc, char* argv[]) {
if (auto init_good = katana::InitTsuba(); !init_good) {
KATANA_LOG_FATAL("katana::InitTsuba: {}", init_good.error());
}
katana::GaloisRuntime Katana_runtime;
if (argc <= 1) {
KATANA_LOG_FATAL("missing rdg file directory");
}
katana::ProgressTracer::Set(katana::TextTracer::Make());
katana::ProgressScope host_scope =
katana::GetTracer().StartActiveSpan("rdg-slice test");
// Ensure the feature flag is actually set
KATANA_LOG_ASSERT(KATANA_EXPERIMENTAL_ENABLED(UnstableRDGStorageFormat));
const std::string& rdg = argv[1];
auto res = TestRoundTripRDKIndex(rdg);
if (!res) {
KATANA_LOG_FATAL("test failed: {}", res.error());
}
res = TestLoadFail(rdg);
if (!res) {
KATANA_LOG_FATAL("test failed: {}", res.error());
}
if (auto fini_good = katana::FiniTsuba(); !fini_good) {
KATANA_LOG_FATAL("katana::FiniTsuba: {}", fini_good.error());
}
return 0;
}
|
13027776717/matrix-ios-sdk
|
MatrixSDK/Data/ReplyEvent/Parser/MXReplyEventParts.h
|
<reponame>13027776717/matrix-ios-sdk
/*
Copyright 2019 The Matrix.org Foundation C.I.C
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "MXReplyEventBodyParts.h"
#import "MXReplyEventFormattedBodyParts.h"
NS_ASSUME_NONNULL_BEGIN
/**
Reply event informations from body and formatted body parts (reply text, text before reply text).
*/
@interface MXReplyEventParts : NSObject
@property (nonatomic, strong, readonly) MXReplyEventBodyParts *bodyParts;
@property (nonatomic, strong, readonly) MXReplyEventFormattedBodyParts * _Nullable formattedBodyParts;
- (instancetype)initWithBodyParts:(MXReplyEventBodyParts *)bodyParts
andFormattedBodyParts:(MXReplyEventFormattedBodyParts * _Nullable)formattedBodyParts;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
@end
NS_ASSUME_NONNULL_END
|
carousell/aggproto
|
pkg/generator/stage/types.go
|
//
// This source file is part of the carousell/aggproto open source project
//
// Copyright © 2021 Carousell and the project authors
// Licensed under Apache License v2.0
//
// See https://github.com/carousell/aggproto/blob/master/LICENSE for license information
// See https://github.com/carousell/aggproto/graphs/contributors for the list of project authors
//
package stage
import "github.com/carousell/aggproto/pkg/generator/printer"
// todo maybe split interface
type Stage interface {
PrintProto(p printer.Factory)
PrintCode(p printer.Factory) error
PrintCodeUsage(p printer.Printer)
AddStageDependency(stage Stage)
GetStageDependencies() []Stage
}
|
AndreasHefti/inari-firefly
|
src/main/java/com/inari/firefly/graphics/ETransform.java
|
/*******************************************************************************
* Copyright (c) 2015 - 2016, <NAME>, <EMAIL>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.inari.firefly.graphics;
import java.util.Set;
import com.inari.commons.JavaUtils;
import com.inari.commons.geom.PositionF;
import com.inari.commons.lang.indexed.IIndexedTypeKey;
import com.inari.firefly.component.attr.AttributeKey;
import com.inari.firefly.component.attr.AttributeMap;
import com.inari.firefly.entity.EntityComponent;
import com.inari.firefly.graphics.view.Layer;
import com.inari.firefly.graphics.view.View;
import com.inari.firefly.graphics.view.ViewAndLayerAware;
import com.inari.firefly.physics.animation.AttributeAnimationAdapter.AttributeAnimationAdapterKey;
import com.inari.firefly.physics.animation.EntityFloatAnimationAdapter;
import com.inari.firefly.physics.animation.FloatAnimation;
import com.inari.firefly.system.FFContext;
import com.inari.firefly.system.external.TransformData;
public final class ETransform extends EntityComponent implements TransformData, ViewAndLayerAware {
public static final EntityComponentTypeKey<ETransform> TYPE_KEY = EntityComponentTypeKey.create( ETransform.class );
public static final AttributeKey<String> VIEW_NAME = AttributeKey.createString( "viewName", ETransform.class );
public static final AttributeKey<Integer> VIEW_ID = AttributeKey.createInt( "viewId", ETransform.class );
public static final AttributeKey<String> LAYER_NAME = AttributeKey.createString( "layerName", ETransform.class );
public static final AttributeKey<Integer> LAYER_ID = AttributeKey.createInt( "layerId", ETransform.class );
public static final AttributeKey<PositionF> POSITION = AttributeKey.createPositionF( "position", ETransform.class );
public static final AttributeKey<Float> POSITION_X = AttributeKey.createFloat( "position_x", ETransform.class );
public static final AttributeKey<Float> POSITION_Y = AttributeKey.createFloat( "position_y", ETransform.class );
public static final AttributeKey<PositionF> PIVOT_POSITION = AttributeKey.createPositionF( "pivotPosition", ETransform.class );
public static final AttributeKey<Float> PIVOT_POSITION_X = AttributeKey.createFloat( "pivotPosition_x", ETransform.class );
public static final AttributeKey<Float> PIVOT_POSITION_Y = AttributeKey.createFloat( "pivotPosition_y", ETransform.class );
public static final AttributeKey<Float> SCALE_X = AttributeKey.createFloat( "scalex", ETransform.class );
public static final AttributeKey<Float> SCALE_Y = AttributeKey.createFloat( "scaley", ETransform.class );
public static final AttributeKey<Float> ROTATION = AttributeKey.createFloat( "rotation", ETransform.class );
public static final Set<AttributeKey<?>> ATTRIBUTE_KEYS = JavaUtils.<AttributeKey<?>>unmodifiableSet(
VIEW_ID,
LAYER_ID,
POSITION_X,
POSITION_Y,
PIVOT_POSITION_X,
PIVOT_POSITION_Y,
SCALE_X,
SCALE_Y,
ROTATION
);
private int viewId, layerId;
private final PositionF position;
private final PositionF pivotPosition;
private float scalex, scaley;
private float rotation;
ETransform() {
super( TYPE_KEY );
position = new PositionF();
pivotPosition = new PositionF();
resetAttributes();
}
public final void resetAttributes() {
viewId = 0;
layerId = 0;
position.x = 0;
position.y = 0;
pivotPosition.x = 0;
pivotPosition.y = 0;
scalex = 1;
scaley = 1;
rotation = 0;
}
public final int getViewId() {
return viewId;
}
public final void setViewId( int viewId ) {
this.viewId = viewId;
}
public final int getLayerId() {
return layerId;
}
public final void setLayerId( int layerId ) {
this.layerId = layerId;
}
public final float getXpos() {
return position.x;
}
public final void setXpos( float xpos ) {
position.x = xpos;
}
public final float getYpos() {
return position.y;
}
public final void setYpos( float ypos ) {
position.y = ypos;
}
public final void setPosition( float xpos, float ypos ) {
position.x = xpos;
position.y = ypos;
}
public final float getPivotX() {
return pivotPosition.x;
}
public final void setPivotX( float pivotx ) {
pivotPosition.x = pivotx;
}
public final float getPivotY() {
return pivotPosition.y;
}
public final void setPivotY( float pivoty ) {
pivotPosition.y = pivoty;
}
public final void setPivot( float x, float y ) {
pivotPosition.x = x;
pivotPosition.y = y;
}
public final void move( final float dx, final float dy ) {
position.x += dx;
position.y += dy;
}
public final float getScaleX() {
return scalex;
}
public final void setScaleX( float scalex ) {
this.scalex = scalex;
}
public final float getScaleY() {
return scaley;
}
public final void setScaleY( float scaley ) {
this.scaley = scaley;
}
public final void setScale( float x, float y ) {
scalex = x;
scaley = y;
}
public final float getRotation() {
return rotation;
}
public final void setRotation( float rotation ) {
this.rotation = rotation;
}
public final float getXOffset() {
return position.x;
}
public final float getYOffset() {
return position.y;
}
public final boolean hasRotation() {
return rotation != 0.0;
}
public final boolean hasScale() {
return scalex != 1.0 || scaley != 1.0;
}
public final Set<AttributeKey<?>> attributeKeys() {
return ATTRIBUTE_KEYS;
}
public final void fromAttributes( AttributeMap attributes ) {
viewId = attributes.getIdForName( VIEW_NAME, VIEW_ID, View.TYPE_KEY, viewId );
layerId = attributes.getIdForName( LAYER_NAME, LAYER_ID, Layer.TYPE_KEY, layerId );
if ( attributes.contains( POSITION ) ) {
PositionF pos = attributes.getValue( POSITION );
position.x = pos.x;
position.y = pos.y;
} else {
position.x = attributes.getValue( POSITION_X, position.x );
position.y = attributes.getValue( POSITION_Y, position.y );
}
if ( attributes.contains( PIVOT_POSITION ) ) {
PositionF pos = attributes.getValue( PIVOT_POSITION );
pivotPosition.x = pos.x;
pivotPosition.y = pos.y;
} else {
pivotPosition.x = attributes.getValue( PIVOT_POSITION_X, pivotPosition.x );
pivotPosition.y = attributes.getValue( PIVOT_POSITION_Y, pivotPosition.y );
}
scalex = attributes.getValue( SCALE_X, scalex );
scaley = attributes.getValue( SCALE_Y, scaley );
rotation = attributes.getValue( ROTATION, rotation );
}
public final void toAttributes( AttributeMap attributes ) {
attributes.put( VIEW_ID, viewId );
attributes.put( LAYER_ID, layerId );
attributes.put( POSITION_X, position.x );
attributes.put( POSITION_Y, position.y );
attributes.put( PIVOT_POSITION_X, pivotPosition.x );
attributes.put( PIVOT_POSITION_Y, pivotPosition.y );
attributes.put( SCALE_X, scalex );
attributes.put( SCALE_Y, scalex );
attributes.put( ROTATION, rotation );
}
public interface AnimationAdapter {
AttributeAnimationAdapterKey<XAxisAnimationAdapter> POSITION_X = XAxisAnimationAdapter.TYPE_KEY;
AttributeAnimationAdapterKey<YAxisAnimationAdapter> POSITION_Y = YAxisAnimationAdapter.TYPE_KEY;
AttributeAnimationAdapterKey<XAxisPivotAnimationAdapter> PIVOT_POSITION_X = XAxisPivotAnimationAdapter.TYPE_KEY;
AttributeAnimationAdapterKey<YAxisPivotAnimationAdapter> PIVOT_POSITION_Y = YAxisPivotAnimationAdapter.TYPE_KEY;
AttributeAnimationAdapterKey<XScaleAnimationAdapter> SCALE_X = XScaleAnimationAdapter.TYPE_KEY;
AttributeAnimationAdapterKey<YScaleAnimationAdapter> SCALE_Y = YScaleAnimationAdapter.TYPE_KEY;
AttributeAnimationAdapterKey<RotationAnimationAdapter> ROTATION = RotationAnimationAdapter.TYPE_KEY;
}
private static final class XAxisAnimationAdapter implements EntityFloatAnimationAdapter {
public static final AttributeAnimationAdapterKey<XAxisAnimationAdapter> TYPE_KEY = AttributeAnimationAdapterKey.create( new XAxisAnimationAdapter() );
public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; }
public final void apply( int entityId, final FloatAnimation animation, final FFContext context ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
transform.setXpos( animation.getValue( entityId, transform.getXpos() ) );
}
}
private static final class YAxisAnimationAdapter implements EntityFloatAnimationAdapter {
public static final AttributeAnimationAdapterKey<YAxisAnimationAdapter> TYPE_KEY = AttributeAnimationAdapterKey.create( new YAxisAnimationAdapter() );
public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; }
public final void apply( int entityId, final FloatAnimation animation, final FFContext context ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
transform.setYpos( animation.getValue( entityId, transform.getYpos() ) );
}
}
private static final class XAxisPivotAnimationAdapter implements EntityFloatAnimationAdapter {
public static final AttributeAnimationAdapterKey<XAxisPivotAnimationAdapter> TYPE_KEY = AttributeAnimationAdapterKey.create( new XAxisPivotAnimationAdapter() );
public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; }
public final void apply( int entityId, final FloatAnimation animation, final FFContext context ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
transform.setPivotX( animation.getValue( entityId, transform.getPivotX() ) );
}
}
public static final class YAxisPivotAnimationAdapter implements EntityFloatAnimationAdapter {
public static final AttributeAnimationAdapterKey<YAxisPivotAnimationAdapter> TYPE_KEY = AttributeAnimationAdapterKey.create( new YAxisPivotAnimationAdapter() );
@Override public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; }
@Override
public final void apply( int entityId, final FloatAnimation animation, final FFContext context ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
transform.setPivotY( animation.getValue( entityId, transform.getPivotY() ) );
}
}
private static final class XScaleAnimationAdapter implements EntityFloatAnimationAdapter {
public static final AttributeAnimationAdapterKey<XScaleAnimationAdapter> TYPE_KEY = AttributeAnimationAdapterKey.create( new XScaleAnimationAdapter() );
public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; }
public final void apply( int entityId, final FloatAnimation animation, final FFContext context ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
transform.setScaleX( animation.getValue( entityId, transform.getScaleX() ) );
}
}
public static final class YScaleAnimationAdapter implements EntityFloatAnimationAdapter {
public static final AttributeAnimationAdapterKey<YScaleAnimationAdapter> TYPE_KEY = AttributeAnimationAdapterKey.create( new YScaleAnimationAdapter() );
public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; }
public final void apply( int entityId, final FloatAnimation animation, final FFContext context ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
transform.setScaleY( animation.getValue( entityId, transform.getScaleY() ) );
}
}
private static final class RotationAnimationAdapter implements EntityFloatAnimationAdapter {
public static final AttributeAnimationAdapterKey<RotationAnimationAdapter> TYPE_KEY = AttributeAnimationAdapterKey.create( new RotationAnimationAdapter() );
public final IIndexedTypeKey indexedTypeKey() { return TYPE_KEY; }
public final void apply( int entityId, final FloatAnimation animation, final FFContext context ) {
final ETransform transform = context.getEntityComponent( entityId, ETransform.TYPE_KEY );
transform.setRotation( animation.getValue( entityId, transform.getRotation() ) );
}
}
}
|
mbheinen/CIMApplication
|
CIMWeb/src/main/webapp/js/model/LoadDynamics.js
|
<reponame>mbheinen/CIMApplication
define
(
["model/base", "model/Core"],
/**
* Dynamic load models are used to represent the dynamic real and reactive load behaviour of a load from the static power flow model.
*
* Dynamic load models can be defined as applying either to a single load (energy consumer) or to a group of energy consumers.
* Large industrial motors or groups of similar motors can be represented by a synchronous machine model (SynchronousMachineDynamics) or an asynchronous machine model (AsynchronousMachineDynamics), which are usually represented as generators with negative active power output in the static (power flow) data.
*
*/
function (base, Core)
{
/**
* Type of static load model.
*
*/
let StaticLoadModelKind =
{
"exponential": "exponential",
"zIP1": "zIP1",
"zIP2": "zIP2",
"constantZ": "constantZ"
};
Object.freeze (StaticLoadModelKind);
/**
* Type of generic non-linear load model.
*
*/
let GenericNonLinearLoadModelKind =
{
"exponentialRecovery": "exponentialRecovery",
"loadAdaptive": "loadAdaptive"
};
Object.freeze (GenericNonLinearLoadModelKind);
/**
* Load whose behaviour is described by reference to a standard model <font color="#0f0f0f">or by definition of a user-defined model.</font>
* A standard feature of dynamic load behaviour modelling is the ability to associate the same behaviour to multiple energy consumers by means of a single load definition.
*
* The load model is always applied to individual bus loads (energy consumers).
*
*/
class LoadDynamics extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LoadDynamics;
if (null == bucket)
cim_data.LoadDynamics = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LoadDynamics[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "LoadDynamics";
base.parse_attributes (/<cim:LoadDynamics.EnergyConsumer\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "EnergyConsumer", sub, context);
let bucket = context.parsed.LoadDynamics;
if (null == bucket)
context.parsed.LoadDynamics = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_attributes (obj, "LoadDynamics", "EnergyConsumer", "EnergyConsumer", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LoadDynamics_collapse" aria-expanded="true" aria-controls="LoadDynamics_collapse" style="margin-left: 10px;">LoadDynamics</a></legend>
<div id="LoadDynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#EnergyConsumer}}<div><b>EnergyConsumer</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/EnergyConsumer}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["EnergyConsumer"]) obj["EnergyConsumer_string"] = obj["EnergyConsumer"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["EnergyConsumer_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LoadDynamics_collapse" aria-expanded="true" aria-controls="{{id}}_LoadDynamics_collapse" style="margin-left: 10px;">LoadDynamics</a></legend>
<div id="{{id}}_LoadDynamics_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "LoadDynamics" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["EnergyConsumer", "0..*", "0..1", "EnergyConsumer", "LoadDynamics"]
]
)
);
}
}
/**
* Aggregate induction motor load.
*
* This model is used to represent a fraction of an ordinary load as "induction motor load". It allows a load that is treated as an ordinary constant power in power flow analysis to be represented by an induction motor in dynamic simulation. This model is intended for representation of aggregations of many motors dispersed through a load represented at a high voltage bus but where there is no information on the characteristics of individual motors.
* Either a "one-cage" or "two-cage" model of the induction machine can be modelled. Magnetic saturation is not modelled.
* This model treats a fraction of the constant power part of a load as a motor. During initialisation, the initial power drawn by the motor is set equal to <i>Pfrac</i> times the constant <i>P</i> part of the static load. The remainder of the load is left as a static load.
* The reactive power demand of the motor is calculated during initialisation as a function of voltage at the load bus. This reactive power demand can be less than or greater than the constant <i>Q</i> component of the load. If the motor's reactive demand is greater than the constant <i>Q</i> component of the load, the model inserts a shunt capacitor at the terminal of the motor to bring its reactive demand down to equal the constant <i>Q</i> reactive load.
* If an induction motor load model and a static load model are both present for a load, the motor <i>Pfrac</i> is assumed to be subtracted from the power flow constant <i>P</i> load before the static load model is applied. The remainder of the load, if any, is then represented by the static load model.
*
*/
class LoadMotor extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LoadMotor;
if (null == bucket)
cim_data.LoadMotor = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LoadMotor[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "LoadMotor";
base.parse_element (/<cim:LoadMotor.d>([\s\S]*?)<\/cim:LoadMotor.d>/g, obj, "d", base.to_float, sub, context);
base.parse_element (/<cim:LoadMotor.h>([\s\S]*?)<\/cim:LoadMotor.h>/g, obj, "h", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.lfac>([\s\S]*?)<\/cim:LoadMotor.lfac>/g, obj, "lfac", base.to_float, sub, context);
base.parse_element (/<cim:LoadMotor.lp>([\s\S]*?)<\/cim:LoadMotor.lp>/g, obj, "lp", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.lpp>([\s\S]*?)<\/cim:LoadMotor.lpp>/g, obj, "lpp", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.ls>([\s\S]*?)<\/cim:LoadMotor.ls>/g, obj, "ls", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.pfrac>([\s\S]*?)<\/cim:LoadMotor.pfrac>/g, obj, "pfrac", base.to_float, sub, context);
base.parse_element (/<cim:LoadMotor.ra>([\s\S]*?)<\/cim:LoadMotor.ra>/g, obj, "ra", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.tbkr>([\s\S]*?)<\/cim:LoadMotor.tbkr>/g, obj, "tbkr", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.tpo>([\s\S]*?)<\/cim:LoadMotor.tpo>/g, obj, "tpo", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.tppo>([\s\S]*?)<\/cim:LoadMotor.tppo>/g, obj, "tppo", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.tv>([\s\S]*?)<\/cim:LoadMotor.tv>/g, obj, "tv", base.to_string, sub, context);
base.parse_element (/<cim:LoadMotor.vt>([\s\S]*?)<\/cim:LoadMotor.vt>/g, obj, "vt", base.to_string, sub, context);
base.parse_attribute (/<cim:LoadMotor.LoadAggregate\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LoadAggregate", sub, context);
let bucket = context.parsed.LoadMotor;
if (null == bucket)
context.parsed.LoadMotor = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "LoadMotor", "d", "d", base.from_float, fields);
base.export_element (obj, "LoadMotor", "h", "h", base.from_string, fields);
base.export_element (obj, "LoadMotor", "lfac", "lfac", base.from_float, fields);
base.export_element (obj, "LoadMotor", "lp", "lp", base.from_string, fields);
base.export_element (obj, "LoadMotor", "lpp", "lpp", base.from_string, fields);
base.export_element (obj, "LoadMotor", "ls", "ls", base.from_string, fields);
base.export_element (obj, "LoadMotor", "pfrac", "pfrac", base.from_float, fields);
base.export_element (obj, "LoadMotor", "ra", "ra", base.from_string, fields);
base.export_element (obj, "LoadMotor", "tbkr", "tbkr", base.from_string, fields);
base.export_element (obj, "LoadMotor", "tpo", "tpo", base.from_string, fields);
base.export_element (obj, "LoadMotor", "tppo", "tppo", base.from_string, fields);
base.export_element (obj, "LoadMotor", "tv", "tv", base.from_string, fields);
base.export_element (obj, "LoadMotor", "vt", "vt", base.from_string, fields);
base.export_attribute (obj, "LoadMotor", "LoadAggregate", "LoadAggregate", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LoadMotor_collapse" aria-expanded="true" aria-controls="LoadMotor_collapse" style="margin-left: 10px;">LoadMotor</a></legend>
<div id="LoadMotor_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#d}}<div><b>d</b>: {{d}}</div>{{/d}}
{{#h}}<div><b>h</b>: {{h}}</div>{{/h}}
{{#lfac}}<div><b>lfac</b>: {{lfac}}</div>{{/lfac}}
{{#lp}}<div><b>lp</b>: {{lp}}</div>{{/lp}}
{{#lpp}}<div><b>lpp</b>: {{lpp}}</div>{{/lpp}}
{{#ls}}<div><b>ls</b>: {{ls}}</div>{{/ls}}
{{#pfrac}}<div><b>pfrac</b>: {{pfrac}}</div>{{/pfrac}}
{{#ra}}<div><b>ra</b>: {{ra}}</div>{{/ra}}
{{#tbkr}}<div><b>tbkr</b>: {{tbkr}}</div>{{/tbkr}}
{{#tpo}}<div><b>tpo</b>: {{tpo}}</div>{{/tpo}}
{{#tppo}}<div><b>tppo</b>: {{tppo}}</div>{{/tppo}}
{{#tv}}<div><b>tv</b>: {{tv}}</div>{{/tv}}
{{#vt}}<div><b>vt</b>: {{vt}}</div>{{/vt}}
{{#LoadAggregate}}<div><b>LoadAggregate</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{LoadAggregate}}");}); return false;'>{{LoadAggregate}}</a></div>{{/LoadAggregate}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LoadMotor_collapse" aria-expanded="true" aria-controls="{{id}}_LoadMotor_collapse" style="margin-left: 10px;">LoadMotor</a></legend>
<div id="{{id}}_LoadMotor_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_d'>d: </label><div class='col-sm-8'><input id='{{id}}_d' class='form-control' type='text'{{#d}} value='{{d}}'{{/d}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_h'>h: </label><div class='col-sm-8'><input id='{{id}}_h' class='form-control' type='text'{{#h}} value='{{h}}'{{/h}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lfac'>lfac: </label><div class='col-sm-8'><input id='{{id}}_lfac' class='form-control' type='text'{{#lfac}} value='{{lfac}}'{{/lfac}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lp'>lp: </label><div class='col-sm-8'><input id='{{id}}_lp' class='form-control' type='text'{{#lp}} value='{{lp}}'{{/lp}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lpp'>lpp: </label><div class='col-sm-8'><input id='{{id}}_lpp' class='form-control' type='text'{{#lpp}} value='{{lpp}}'{{/lpp}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ls'>ls: </label><div class='col-sm-8'><input id='{{id}}_ls' class='form-control' type='text'{{#ls}} value='{{ls}}'{{/ls}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_pfrac'>pfrac: </label><div class='col-sm-8'><input id='{{id}}_pfrac' class='form-control' type='text'{{#pfrac}} value='{{pfrac}}'{{/pfrac}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ra'>ra: </label><div class='col-sm-8'><input id='{{id}}_ra' class='form-control' type='text'{{#ra}} value='{{ra}}'{{/ra}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tbkr'>tbkr: </label><div class='col-sm-8'><input id='{{id}}_tbkr' class='form-control' type='text'{{#tbkr}} value='{{tbkr}}'{{/tbkr}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tpo'>tpo: </label><div class='col-sm-8'><input id='{{id}}_tpo' class='form-control' type='text'{{#tpo}} value='{{tpo}}'{{/tpo}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tppo'>tppo: </label><div class='col-sm-8'><input id='{{id}}_tppo' class='form-control' type='text'{{#tppo}} value='{{tppo}}'{{/tppo}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tv'>tv: </label><div class='col-sm-8'><input id='{{id}}_tv' class='form-control' type='text'{{#tv}} value='{{tv}}'{{/tv}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_vt'>vt: </label><div class='col-sm-8'><input id='{{id}}_vt' class='form-control' type='text'{{#vt}} value='{{vt}}'{{/vt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_LoadAggregate'>LoadAggregate: </label><div class='col-sm-8'><input id='{{id}}_LoadAggregate' class='form-control' type='text'{{#LoadAggregate}} value='{{LoadAggregate}}'{{/LoadAggregate}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LoadMotor" };
super.submit (id, obj);
temp = document.getElementById (id + "_d").value; if ("" !== temp) obj["d"] = temp;
temp = document.getElementById (id + "_h").value; if ("" !== temp) obj["h"] = temp;
temp = document.getElementById (id + "_lfac").value; if ("" !== temp) obj["lfac"] = temp;
temp = document.getElementById (id + "_lp").value; if ("" !== temp) obj["lp"] = temp;
temp = document.getElementById (id + "_lpp").value; if ("" !== temp) obj["lpp"] = temp;
temp = document.getElementById (id + "_ls").value; if ("" !== temp) obj["ls"] = temp;
temp = document.getElementById (id + "_pfrac").value; if ("" !== temp) obj["pfrac"] = temp;
temp = document.getElementById (id + "_ra").value; if ("" !== temp) obj["ra"] = temp;
temp = document.getElementById (id + "_tbkr").value; if ("" !== temp) obj["tbkr"] = temp;
temp = document.getElementById (id + "_tpo").value; if ("" !== temp) obj["tpo"] = temp;
temp = document.getElementById (id + "_tppo").value; if ("" !== temp) obj["tppo"] = temp;
temp = document.getElementById (id + "_tv").value; if ("" !== temp) obj["tv"] = temp;
temp = document.getElementById (id + "_vt").value; if ("" !== temp) obj["vt"] = temp;
temp = document.getElementById (id + "_LoadAggregate").value; if ("" !== temp) obj["LoadAggregate"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["LoadAggregate", "1", "0..1", "LoadAggregate", "LoadMotor"]
]
)
);
}
}
/**
* General static load.
*
* This model represents the sensitivity of the real and reactive power consumed by the load to the amplitude and frequency of the bus voltage.
*
*/
class LoadStatic extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LoadStatic;
if (null == bucket)
cim_data.LoadStatic = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LoadStatic[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "LoadStatic";
base.parse_element (/<cim:LoadStatic.ep1>([\s\S]*?)<\/cim:LoadStatic.ep1>/g, obj, "ep1", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.ep2>([\s\S]*?)<\/cim:LoadStatic.ep2>/g, obj, "ep2", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.ep3>([\s\S]*?)<\/cim:LoadStatic.ep3>/g, obj, "ep3", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.eq1>([\s\S]*?)<\/cim:LoadStatic.eq1>/g, obj, "eq1", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.eq2>([\s\S]*?)<\/cim:LoadStatic.eq2>/g, obj, "eq2", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.eq3>([\s\S]*?)<\/cim:LoadStatic.eq3>/g, obj, "eq3", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kp1>([\s\S]*?)<\/cim:LoadStatic.kp1>/g, obj, "kp1", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kp2>([\s\S]*?)<\/cim:LoadStatic.kp2>/g, obj, "kp2", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kp3>([\s\S]*?)<\/cim:LoadStatic.kp3>/g, obj, "kp3", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kp4>([\s\S]*?)<\/cim:LoadStatic.kp4>/g, obj, "kp4", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kpf>([\s\S]*?)<\/cim:LoadStatic.kpf>/g, obj, "kpf", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kq1>([\s\S]*?)<\/cim:LoadStatic.kq1>/g, obj, "kq1", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kq2>([\s\S]*?)<\/cim:LoadStatic.kq2>/g, obj, "kq2", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kq3>([\s\S]*?)<\/cim:LoadStatic.kq3>/g, obj, "kq3", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kq4>([\s\S]*?)<\/cim:LoadStatic.kq4>/g, obj, "kq4", base.to_float, sub, context);
base.parse_element (/<cim:LoadStatic.kqf>([\s\S]*?)<\/cim:LoadStatic.kqf>/g, obj, "kqf", base.to_float, sub, context);
base.parse_attribute (/<cim:LoadStatic.staticLoadModelType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "staticLoadModelType", sub, context);
base.parse_attribute (/<cim:LoadStatic.LoadAggregate\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LoadAggregate", sub, context);
let bucket = context.parsed.LoadStatic;
if (null == bucket)
context.parsed.LoadStatic = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
base.export_element (obj, "LoadStatic", "ep1", "ep1", base.from_float, fields);
base.export_element (obj, "LoadStatic", "ep2", "ep2", base.from_float, fields);
base.export_element (obj, "LoadStatic", "ep3", "ep3", base.from_float, fields);
base.export_element (obj, "LoadStatic", "eq1", "eq1", base.from_float, fields);
base.export_element (obj, "LoadStatic", "eq2", "eq2", base.from_float, fields);
base.export_element (obj, "LoadStatic", "eq3", "eq3", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kp1", "kp1", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kp2", "kp2", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kp3", "kp3", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kp4", "kp4", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kpf", "kpf", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kq1", "kq1", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kq2", "kq2", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kq3", "kq3", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kq4", "kq4", base.from_float, fields);
base.export_element (obj, "LoadStatic", "kqf", "kqf", base.from_float, fields);
base.export_attribute (obj, "LoadStatic", "staticLoadModelType", "staticLoadModelType", fields);
base.export_attribute (obj, "LoadStatic", "LoadAggregate", "LoadAggregate", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LoadStatic_collapse" aria-expanded="true" aria-controls="LoadStatic_collapse" style="margin-left: 10px;">LoadStatic</a></legend>
<div id="LoadStatic_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
{{#ep1}}<div><b>ep1</b>: {{ep1}}</div>{{/ep1}}
{{#ep2}}<div><b>ep2</b>: {{ep2}}</div>{{/ep2}}
{{#ep3}}<div><b>ep3</b>: {{ep3}}</div>{{/ep3}}
{{#eq1}}<div><b>eq1</b>: {{eq1}}</div>{{/eq1}}
{{#eq2}}<div><b>eq2</b>: {{eq2}}</div>{{/eq2}}
{{#eq3}}<div><b>eq3</b>: {{eq3}}</div>{{/eq3}}
{{#kp1}}<div><b>kp1</b>: {{kp1}}</div>{{/kp1}}
{{#kp2}}<div><b>kp2</b>: {{kp2}}</div>{{/kp2}}
{{#kp3}}<div><b>kp3</b>: {{kp3}}</div>{{/kp3}}
{{#kp4}}<div><b>kp4</b>: {{kp4}}</div>{{/kp4}}
{{#kpf}}<div><b>kpf</b>: {{kpf}}</div>{{/kpf}}
{{#kq1}}<div><b>kq1</b>: {{kq1}}</div>{{/kq1}}
{{#kq2}}<div><b>kq2</b>: {{kq2}}</div>{{/kq2}}
{{#kq3}}<div><b>kq3</b>: {{kq3}}</div>{{/kq3}}
{{#kq4}}<div><b>kq4</b>: {{kq4}}</div>{{/kq4}}
{{#kqf}}<div><b>kqf</b>: {{kqf}}</div>{{/kqf}}
{{#staticLoadModelType}}<div><b>staticLoadModelType</b>: {{staticLoadModelType}}</div>{{/staticLoadModelType}}
{{#LoadAggregate}}<div><b>LoadAggregate</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{LoadAggregate}}");}); return false;'>{{LoadAggregate}}</a></div>{{/LoadAggregate}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["staticLoadModelTypeStaticLoadModelKind"] = [{ id: '', selected: (!obj["staticLoadModelType"])}]; for (let property in StaticLoadModelKind) obj["staticLoadModelTypeStaticLoadModelKind"].push ({ id: property, selected: obj["staticLoadModelType"] && obj["staticLoadModelType"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["staticLoadModelTypeStaticLoadModelKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LoadStatic_collapse" aria-expanded="true" aria-controls="{{id}}_LoadStatic_collapse" style="margin-left: 10px;">LoadStatic</a></legend>
<div id="{{id}}_LoadStatic_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ep1'>ep1: </label><div class='col-sm-8'><input id='{{id}}_ep1' class='form-control' type='text'{{#ep1}} value='{{ep1}}'{{/ep1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ep2'>ep2: </label><div class='col-sm-8'><input id='{{id}}_ep2' class='form-control' type='text'{{#ep2}} value='{{ep2}}'{{/ep2}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ep3'>ep3: </label><div class='col-sm-8'><input id='{{id}}_ep3' class='form-control' type='text'{{#ep3}} value='{{ep3}}'{{/ep3}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_eq1'>eq1: </label><div class='col-sm-8'><input id='{{id}}_eq1' class='form-control' type='text'{{#eq1}} value='{{eq1}}'{{/eq1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_eq2'>eq2: </label><div class='col-sm-8'><input id='{{id}}_eq2' class='form-control' type='text'{{#eq2}} value='{{eq2}}'{{/eq2}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_eq3'>eq3: </label><div class='col-sm-8'><input id='{{id}}_eq3' class='form-control' type='text'{{#eq3}} value='{{eq3}}'{{/eq3}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kp1'>kp1: </label><div class='col-sm-8'><input id='{{id}}_kp1' class='form-control' type='text'{{#kp1}} value='{{kp1}}'{{/kp1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kp2'>kp2: </label><div class='col-sm-8'><input id='{{id}}_kp2' class='form-control' type='text'{{#kp2}} value='{{kp2}}'{{/kp2}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kp3'>kp3: </label><div class='col-sm-8'><input id='{{id}}_kp3' class='form-control' type='text'{{#kp3}} value='{{kp3}}'{{/kp3}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kp4'>kp4: </label><div class='col-sm-8'><input id='{{id}}_kp4' class='form-control' type='text'{{#kp4}} value='{{kp4}}'{{/kp4}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kpf'>kpf: </label><div class='col-sm-8'><input id='{{id}}_kpf' class='form-control' type='text'{{#kpf}} value='{{kpf}}'{{/kpf}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kq1'>kq1: </label><div class='col-sm-8'><input id='{{id}}_kq1' class='form-control' type='text'{{#kq1}} value='{{kq1}}'{{/kq1}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kq2'>kq2: </label><div class='col-sm-8'><input id='{{id}}_kq2' class='form-control' type='text'{{#kq2}} value='{{kq2}}'{{/kq2}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kq3'>kq3: </label><div class='col-sm-8'><input id='{{id}}_kq3' class='form-control' type='text'{{#kq3}} value='{{kq3}}'{{/kq3}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kq4'>kq4: </label><div class='col-sm-8'><input id='{{id}}_kq4' class='form-control' type='text'{{#kq4}} value='{{kq4}}'{{/kq4}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kqf'>kqf: </label><div class='col-sm-8'><input id='{{id}}_kqf' class='form-control' type='text'{{#kqf}} value='{{kqf}}'{{/kqf}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_staticLoadModelType'>staticLoadModelType: </label><div class='col-sm-8'><select id='{{id}}_staticLoadModelType' class='form-control custom-select'>{{#staticLoadModelTypeStaticLoadModelKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/staticLoadModelTypeStaticLoadModelKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_LoadAggregate'>LoadAggregate: </label><div class='col-sm-8'><input id='{{id}}_LoadAggregate' class='form-control' type='text'{{#LoadAggregate}} value='{{LoadAggregate}}'{{/LoadAggregate}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LoadStatic" };
super.submit (id, obj);
temp = document.getElementById (id + "_ep1").value; if ("" !== temp) obj["ep1"] = temp;
temp = document.getElementById (id + "_ep2").value; if ("" !== temp) obj["ep2"] = temp;
temp = document.getElementById (id + "_ep3").value; if ("" !== temp) obj["ep3"] = temp;
temp = document.getElementById (id + "_eq1").value; if ("" !== temp) obj["eq1"] = temp;
temp = document.getElementById (id + "_eq2").value; if ("" !== temp) obj["eq2"] = temp;
temp = document.getElementById (id + "_eq3").value; if ("" !== temp) obj["eq3"] = temp;
temp = document.getElementById (id + "_kp1").value; if ("" !== temp) obj["kp1"] = temp;
temp = document.getElementById (id + "_kp2").value; if ("" !== temp) obj["kp2"] = temp;
temp = document.getElementById (id + "_kp3").value; if ("" !== temp) obj["kp3"] = temp;
temp = document.getElementById (id + "_kp4").value; if ("" !== temp) obj["kp4"] = temp;
temp = document.getElementById (id + "_kpf").value; if ("" !== temp) obj["kpf"] = temp;
temp = document.getElementById (id + "_kq1").value; if ("" !== temp) obj["kq1"] = temp;
temp = document.getElementById (id + "_kq2").value; if ("" !== temp) obj["kq2"] = temp;
temp = document.getElementById (id + "_kq3").value; if ("" !== temp) obj["kq3"] = temp;
temp = document.getElementById (id + "_kq4").value; if ("" !== temp) obj["kq4"] = temp;
temp = document.getElementById (id + "_kqf").value; if ("" !== temp) obj["kqf"] = temp;
temp = StaticLoadModelKind[document.getElementById (id + "_staticLoadModelType").value]; if (temp) obj["staticLoadModelType"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#StaticLoadModelKind." + temp; else delete obj["staticLoadModelType"];
temp = document.getElementById (id + "_LoadAggregate").value; if ("" !== temp) obj["LoadAggregate"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["LoadAggregate", "1", "0..1", "LoadAggregate", "LoadStatic"]
]
)
);
}
}
/**
* Combined static load and induction motor load effects.
*
* The dynamics of the motor are simplified by linearizing the induction machine equations.
*
*/
class LoadComposite extends LoadDynamics
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LoadComposite;
if (null == bucket)
cim_data.LoadComposite = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LoadComposite[obj.id];
}
parse (context, sub)
{
let obj = LoadDynamics.prototype.parse.call (this, context, sub);
obj.cls = "LoadComposite";
base.parse_element (/<cim:LoadComposite.epfd>([\s\S]*?)<\/cim:LoadComposite.epfd>/g, obj, "epfd", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.epfs>([\s\S]*?)<\/cim:LoadComposite.epfs>/g, obj, "epfs", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.epvd>([\s\S]*?)<\/cim:LoadComposite.epvd>/g, obj, "epvd", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.epvs>([\s\S]*?)<\/cim:LoadComposite.epvs>/g, obj, "epvs", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.eqfd>([\s\S]*?)<\/cim:LoadComposite.eqfd>/g, obj, "eqfd", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.eqfs>([\s\S]*?)<\/cim:LoadComposite.eqfs>/g, obj, "eqfs", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.eqvd>([\s\S]*?)<\/cim:LoadComposite.eqvd>/g, obj, "eqvd", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.eqvs>([\s\S]*?)<\/cim:LoadComposite.eqvs>/g, obj, "eqvs", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.h>([\s\S]*?)<\/cim:LoadComposite.h>/g, obj, "h", base.to_string, sub, context);
base.parse_element (/<cim:LoadComposite.lfac>([\s\S]*?)<\/cim:LoadComposite.lfac>/g, obj, "lfac", base.to_float, sub, context);
base.parse_element (/<cim:LoadComposite.pfrac>([\s\S]*?)<\/cim:LoadComposite.pfrac>/g, obj, "pfrac", base.to_float, sub, context);
let bucket = context.parsed.LoadComposite;
if (null == bucket)
context.parsed.LoadComposite = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = LoadDynamics.prototype.export.call (this, obj, false);
base.export_element (obj, "LoadComposite", "epfd", "epfd", base.from_float, fields);
base.export_element (obj, "LoadComposite", "epfs", "epfs", base.from_float, fields);
base.export_element (obj, "LoadComposite", "epvd", "epvd", base.from_float, fields);
base.export_element (obj, "LoadComposite", "epvs", "epvs", base.from_float, fields);
base.export_element (obj, "LoadComposite", "eqfd", "eqfd", base.from_float, fields);
base.export_element (obj, "LoadComposite", "eqfs", "eqfs", base.from_float, fields);
base.export_element (obj, "LoadComposite", "eqvd", "eqvd", base.from_float, fields);
base.export_element (obj, "LoadComposite", "eqvs", "eqvs", base.from_float, fields);
base.export_element (obj, "LoadComposite", "h", "h", base.from_string, fields);
base.export_element (obj, "LoadComposite", "lfac", "lfac", base.from_float, fields);
base.export_element (obj, "LoadComposite", "pfrac", "pfrac", base.from_float, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LoadComposite_collapse" aria-expanded="true" aria-controls="LoadComposite_collapse" style="margin-left: 10px;">LoadComposite</a></legend>
<div id="LoadComposite_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ LoadDynamics.prototype.template.call (this) +
`
{{#epfd}}<div><b>epfd</b>: {{epfd}}</div>{{/epfd}}
{{#epfs}}<div><b>epfs</b>: {{epfs}}</div>{{/epfs}}
{{#epvd}}<div><b>epvd</b>: {{epvd}}</div>{{/epvd}}
{{#epvs}}<div><b>epvs</b>: {{epvs}}</div>{{/epvs}}
{{#eqfd}}<div><b>eqfd</b>: {{eqfd}}</div>{{/eqfd}}
{{#eqfs}}<div><b>eqfs</b>: {{eqfs}}</div>{{/eqfs}}
{{#eqvd}}<div><b>eqvd</b>: {{eqvd}}</div>{{/eqvd}}
{{#eqvs}}<div><b>eqvs</b>: {{eqvs}}</div>{{/eqvs}}
{{#h}}<div><b>h</b>: {{h}}</div>{{/h}}
{{#lfac}}<div><b>lfac</b>: {{lfac}}</div>{{/lfac}}
{{#pfrac}}<div><b>pfrac</b>: {{pfrac}}</div>{{/pfrac}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LoadComposite_collapse" aria-expanded="true" aria-controls="{{id}}_LoadComposite_collapse" style="margin-left: 10px;">LoadComposite</a></legend>
<div id="{{id}}_LoadComposite_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ LoadDynamics.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_epfd'>epfd: </label><div class='col-sm-8'><input id='{{id}}_epfd' class='form-control' type='text'{{#epfd}} value='{{epfd}}'{{/epfd}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_epfs'>epfs: </label><div class='col-sm-8'><input id='{{id}}_epfs' class='form-control' type='text'{{#epfs}} value='{{epfs}}'{{/epfs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_epvd'>epvd: </label><div class='col-sm-8'><input id='{{id}}_epvd' class='form-control' type='text'{{#epvd}} value='{{epvd}}'{{/epvd}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_epvs'>epvs: </label><div class='col-sm-8'><input id='{{id}}_epvs' class='form-control' type='text'{{#epvs}} value='{{epvs}}'{{/epvs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_eqfd'>eqfd: </label><div class='col-sm-8'><input id='{{id}}_eqfd' class='form-control' type='text'{{#eqfd}} value='{{eqfd}}'{{/eqfd}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_eqfs'>eqfs: </label><div class='col-sm-8'><input id='{{id}}_eqfs' class='form-control' type='text'{{#eqfs}} value='{{eqfs}}'{{/eqfs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_eqvd'>eqvd: </label><div class='col-sm-8'><input id='{{id}}_eqvd' class='form-control' type='text'{{#eqvd}} value='{{eqvd}}'{{/eqvd}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_eqvs'>eqvs: </label><div class='col-sm-8'><input id='{{id}}_eqvs' class='form-control' type='text'{{#eqvs}} value='{{eqvs}}'{{/eqvs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_h'>h: </label><div class='col-sm-8'><input id='{{id}}_h' class='form-control' type='text'{{#h}} value='{{h}}'{{/h}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lfac'>lfac: </label><div class='col-sm-8'><input id='{{id}}_lfac' class='form-control' type='text'{{#lfac}} value='{{lfac}}'{{/lfac}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_pfrac'>pfrac: </label><div class='col-sm-8'><input id='{{id}}_pfrac' class='form-control' type='text'{{#pfrac}} value='{{pfrac}}'{{/pfrac}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LoadComposite" };
super.submit (id, obj);
temp = document.getElementById (id + "_epfd").value; if ("" !== temp) obj["epfd"] = temp;
temp = document.getElementById (id + "_epfs").value; if ("" !== temp) obj["epfs"] = temp;
temp = document.getElementById (id + "_epvd").value; if ("" !== temp) obj["epvd"] = temp;
temp = document.getElementById (id + "_epvs").value; if ("" !== temp) obj["epvs"] = temp;
temp = document.getElementById (id + "_eqfd").value; if ("" !== temp) obj["eqfd"] = temp;
temp = document.getElementById (id + "_eqfs").value; if ("" !== temp) obj["eqfs"] = temp;
temp = document.getElementById (id + "_eqvd").value; if ("" !== temp) obj["eqvd"] = temp;
temp = document.getElementById (id + "_eqvs").value; if ("" !== temp) obj["eqvs"] = temp;
temp = document.getElementById (id + "_h").value; if ("" !== temp) obj["h"] = temp;
temp = document.getElementById (id + "_lfac").value; if ("" !== temp) obj["lfac"] = temp;
temp = document.getElementById (id + "_pfrac").value; if ("" !== temp) obj["pfrac"] = temp;
return (obj);
}
}
/**
* Generic non-linear dynamic (GNLD) load.
*
* This model can be used in mid-term and long-term voltage stability simulations (i.e., to study voltage collapse), as it can replace a more detailed representation of aggregate load, including induction motors, thermostatically controlled and static loads.
*
*/
class LoadGenericNonLinear extends LoadDynamics
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LoadGenericNonLinear;
if (null == bucket)
cim_data.LoadGenericNonLinear = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LoadGenericNonLinear[obj.id];
}
parse (context, sub)
{
let obj = LoadDynamics.prototype.parse.call (this, context, sub);
obj.cls = "LoadGenericNonLinear";
base.parse_element (/<cim:LoadGenericNonLinear.bs>([\s\S]*?)<\/cim:LoadGenericNonLinear.bs>/g, obj, "bs", base.to_float, sub, context);
base.parse_element (/<cim:LoadGenericNonLinear.bt>([\s\S]*?)<\/cim:LoadGenericNonLinear.bt>/g, obj, "bt", base.to_float, sub, context);
base.parse_attribute (/<cim:LoadGenericNonLinear.genericNonLinearLoadModelType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "genericNonLinearLoadModelType", sub, context);
base.parse_element (/<cim:LoadGenericNonLinear.ls>([\s\S]*?)<\/cim:LoadGenericNonLinear.ls>/g, obj, "ls", base.to_float, sub, context);
base.parse_element (/<cim:LoadGenericNonLinear.lt>([\s\S]*?)<\/cim:LoadGenericNonLinear.lt>/g, obj, "lt", base.to_float, sub, context);
base.parse_element (/<cim:LoadGenericNonLinear.tp>([\s\S]*?)<\/cim:LoadGenericNonLinear.tp>/g, obj, "tp", base.to_string, sub, context);
base.parse_element (/<cim:LoadGenericNonLinear.tq>([\s\S]*?)<\/cim:LoadGenericNonLinear.tq>/g, obj, "tq", base.to_string, sub, context);
let bucket = context.parsed.LoadGenericNonLinear;
if (null == bucket)
context.parsed.LoadGenericNonLinear = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = LoadDynamics.prototype.export.call (this, obj, false);
base.export_element (obj, "LoadGenericNonLinear", "bs", "bs", base.from_float, fields);
base.export_element (obj, "LoadGenericNonLinear", "bt", "bt", base.from_float, fields);
base.export_attribute (obj, "LoadGenericNonLinear", "genericNonLinearLoadModelType", "genericNonLinearLoadModelType", fields);
base.export_element (obj, "LoadGenericNonLinear", "ls", "ls", base.from_float, fields);
base.export_element (obj, "LoadGenericNonLinear", "lt", "lt", base.from_float, fields);
base.export_element (obj, "LoadGenericNonLinear", "tp", "tp", base.from_string, fields);
base.export_element (obj, "LoadGenericNonLinear", "tq", "tq", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LoadGenericNonLinear_collapse" aria-expanded="true" aria-controls="LoadGenericNonLinear_collapse" style="margin-left: 10px;">LoadGenericNonLinear</a></legend>
<div id="LoadGenericNonLinear_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ LoadDynamics.prototype.template.call (this) +
`
{{#bs}}<div><b>bs</b>: {{bs}}</div>{{/bs}}
{{#bt}}<div><b>bt</b>: {{bt}}</div>{{/bt}}
{{#genericNonLinearLoadModelType}}<div><b>genericNonLinearLoadModelType</b>: {{genericNonLinearLoadModelType}}</div>{{/genericNonLinearLoadModelType}}
{{#ls}}<div><b>ls</b>: {{ls}}</div>{{/ls}}
{{#lt}}<div><b>lt</b>: {{lt}}</div>{{/lt}}
{{#tp}}<div><b>tp</b>: {{tp}}</div>{{/tp}}
{{#tq}}<div><b>tq</b>: {{tq}}</div>{{/tq}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["genericNonLinearLoadModelTypeGenericNonLinearLoadModelKind"] = [{ id: '', selected: (!obj["genericNonLinearLoadModelType"])}]; for (let property in GenericNonLinearLoadModelKind) obj["genericNonLinearLoadModelTypeGenericNonLinearLoadModelKind"].push ({ id: property, selected: obj["genericNonLinearLoadModelType"] && obj["genericNonLinearLoadModelType"].endsWith ('.' + property)});
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["genericNonLinearLoadModelTypeGenericNonLinearLoadModelKind"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LoadGenericNonLinear_collapse" aria-expanded="true" aria-controls="{{id}}_LoadGenericNonLinear_collapse" style="margin-left: 10px;">LoadGenericNonLinear</a></legend>
<div id="{{id}}_LoadGenericNonLinear_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ LoadDynamics.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_bs'>bs: </label><div class='col-sm-8'><input id='{{id}}_bs' class='form-control' type='text'{{#bs}} value='{{bs}}'{{/bs}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_bt'>bt: </label><div class='col-sm-8'><input id='{{id}}_bt' class='form-control' type='text'{{#bt}} value='{{bt}}'{{/bt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_genericNonLinearLoadModelType'>genericNonLinearLoadModelType: </label><div class='col-sm-8'><select id='{{id}}_genericNonLinearLoadModelType' class='form-control custom-select'>{{#genericNonLinearLoadModelTypeGenericNonLinearLoadModelKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/genericNonLinearLoadModelTypeGenericNonLinearLoadModelKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ls'>ls: </label><div class='col-sm-8'><input id='{{id}}_ls' class='form-control' type='text'{{#ls}} value='{{ls}}'{{/ls}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lt'>lt: </label><div class='col-sm-8'><input id='{{id}}_lt' class='form-control' type='text'{{#lt}} value='{{lt}}'{{/lt}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tp'>tp: </label><div class='col-sm-8'><input id='{{id}}_tp' class='form-control' type='text'{{#tp}} value='{{tp}}'{{/tp}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_tq'>tq: </label><div class='col-sm-8'><input id='{{id}}_tq' class='form-control' type='text'{{#tq}} value='{{tq}}'{{/tq}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LoadGenericNonLinear" };
super.submit (id, obj);
temp = document.getElementById (id + "_bs").value; if ("" !== temp) obj["bs"] = temp;
temp = document.getElementById (id + "_bt").value; if ("" !== temp) obj["bt"] = temp;
temp = GenericNonLinearLoadModelKind[document.getElementById (id + "_genericNonLinearLoadModelType").value]; if (temp) obj["genericNonLinearLoadModelType"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#GenericNonLinearLoadModelKind." + temp; else delete obj["genericNonLinearLoadModelType"];
temp = document.getElementById (id + "_ls").value; if ("" !== temp) obj["ls"] = temp;
temp = document.getElementById (id + "_lt").value; if ("" !== temp) obj["lt"] = temp;
temp = document.getElementById (id + "_tp").value; if ("" !== temp) obj["tp"] = temp;
temp = document.getElementById (id + "_tq").value; if ("" !== temp) obj["tq"] = temp;
return (obj);
}
}
/**
* Aggregate loads are used to represent all or part of the real and reactive load from one or more loads in the static (power flow) data.
*
* This load is usually the aggregation of many individual load devices and the load model is an approximate representation of the aggregate response of the load devices to system disturbances.
* Standard aggregate load model comprised of static and/or dynamic components. A static load model represents the sensitivity of the real and reactive power consumed by the load to the amplitude and frequency of the bus voltage. A dynamic load model can be used to represent the aggregate response of the motor components of the load.
*
*/
class LoadAggregate extends LoadDynamics
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.LoadAggregate;
if (null == bucket)
cim_data.LoadAggregate = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.LoadAggregate[obj.id];
}
parse (context, sub)
{
let obj = LoadDynamics.prototype.parse.call (this, context, sub);
obj.cls = "LoadAggregate";
base.parse_attribute (/<cim:LoadAggregate.LoadMotor\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LoadMotor", sub, context);
base.parse_attribute (/<cim:LoadAggregate.LoadStatic\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LoadStatic", sub, context);
let bucket = context.parsed.LoadAggregate;
if (null == bucket)
context.parsed.LoadAggregate = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = LoadDynamics.prototype.export.call (this, obj, false);
base.export_attribute (obj, "LoadAggregate", "LoadMotor", "LoadMotor", fields);
base.export_attribute (obj, "LoadAggregate", "LoadStatic", "LoadStatic", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#LoadAggregate_collapse" aria-expanded="true" aria-controls="LoadAggregate_collapse" style="margin-left: 10px;">LoadAggregate</a></legend>
<div id="LoadAggregate_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ LoadDynamics.prototype.template.call (this) +
`
{{#LoadMotor}}<div><b>LoadMotor</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{LoadMotor}}");}); return false;'>{{LoadMotor}}</a></div>{{/LoadMotor}}
{{#LoadStatic}}<div><b>LoadStatic</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{LoadStatic}}");}); return false;'>{{LoadStatic}}</a></div>{{/LoadStatic}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_LoadAggregate_collapse" aria-expanded="true" aria-controls="{{id}}_LoadAggregate_collapse" style="margin-left: 10px;">LoadAggregate</a></legend>
<div id="{{id}}_LoadAggregate_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ LoadDynamics.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_LoadMotor'>LoadMotor: </label><div class='col-sm-8'><input id='{{id}}_LoadMotor' class='form-control' type='text'{{#LoadMotor}} value='{{LoadMotor}}'{{/LoadMotor}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_LoadStatic'>LoadStatic: </label><div class='col-sm-8'><input id='{{id}}_LoadStatic' class='form-control' type='text'{{#LoadStatic}} value='{{LoadStatic}}'{{/LoadStatic}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "LoadAggregate" };
super.submit (id, obj);
temp = document.getElementById (id + "_LoadMotor").value; if ("" !== temp) obj["LoadMotor"] = temp;
temp = document.getElementById (id + "_LoadStatic").value; if ("" !== temp) obj["LoadStatic"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["LoadMotor", "0..1", "1", "LoadMotor", "LoadAggregate"],
["LoadStatic", "0..1", "1", "LoadStatic", "LoadAggregate"]
]
)
);
}
}
return (
{
GenericNonLinearLoadModelKind: GenericNonLinearLoadModelKind,
StaticLoadModelKind: StaticLoadModelKind,
LoadGenericNonLinear: LoadGenericNonLinear,
LoadStatic: LoadStatic,
LoadMotor: LoadMotor,
LoadAggregate: LoadAggregate,
LoadComposite: LoadComposite,
LoadDynamics: LoadDynamics
}
);
}
);
|
lizhanhui/tddl
|
tddl-atom/src/main/java/com/taobao/tddl/atom/jdbc/TDataSourceWrapper.java
|
<reponame>lizhanhui/tddl<filename>tddl-atom/src/main/java/com/taobao/tddl/atom/jdbc/TDataSourceWrapper.java
package com.taobao.tddl.atom.jdbc;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import javax.sql.DataSource;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.taobao.tddl.atom.TAtomDbStatusEnum;
import com.taobao.tddl.atom.TAtomDbTypeEnum;
import com.taobao.tddl.atom.config.TAtomDsConfDO;
import com.taobao.tddl.atom.exception.AtomNotAvailableException;
import com.taobao.tddl.atom.utils.ConnRestrictEntry;
import com.taobao.tddl.atom.utils.ConnRestrictSlot;
import com.taobao.tddl.atom.utils.ConnRestrictor;
import com.taobao.tddl.atom.utils.CountPunisher;
import com.taobao.tddl.atom.utils.SmoothValve;
import com.taobao.tddl.atom.utils.TimesliceFlowControl;
import com.taobao.tddl.common.jdbc.sorter.ExceptionSorter;
import com.taobao.tddl.common.jdbc.sorter.MySQLExceptionSorter;
import com.taobao.tddl.common.jdbc.sorter.OracleExceptionSorter;
import com.taobao.tddl.common.utils.TStringUtil;
import com.taobao.tddl.monitor.Monitor;
import com.taobao.tddl.monitor.SnapshotValuesOutputCallBack;
import com.taobao.tddl.monitor.stat.AbstractStatLogWriter.LogCounter;
import com.taobao.tddl.monitor.stat.StatLogWriter;
import com.taobao.tddl.monitor.utils.NagiosUtils;
public class TDataSourceWrapper implements DataSource, SnapshotValuesOutputCallBack {
private static Log logger = LogFactory.getLog(TDataSourceWrapper.class);
private final DataSource targetDataSource;
/**
* 当前线程的threadCount值,如果进行了切换。 那么使用的是不同的Datasource包装类,不会相互影响。
* threadCount输出在切换过程中在那个时候不能反应准确的值。
* 但因为旧的被丢弃前也有用,等于在内存中维持了两份不同的TDataSourceWrapper. 因此线程计数不会额外增加。
*/
final AtomicInteger threadCount = new AtomicInteger(); // 包权限
final AtomicInteger threadCountReject = new AtomicInteger(); // 包权限
final AtomicInteger concurrentReadCount = new AtomicInteger(); // 包权限
final AtomicInteger concurrentWriteCount = new AtomicInteger(); // 包权限
volatile TimesliceFlowControl writeFlowControl; // 包权限
volatile TimesliceFlowControl readFlowControl; // 包权限
/**
* 写计数
*/
// final AtomicInteger writeTimes = new AtomicInteger();//包权限
final AtomicInteger writeTimesReject = new AtomicInteger(); // 包权限
/**
* 读计数
*/
// final AtomicInteger readTimes = new AtomicInteger();//包权限
final AtomicInteger readTimesReject = new AtomicInteger(); // 包权限
volatile ConnectionProperties connectionProperties = new ConnectionProperties(); // 包权限
/**
* 应用连接限制
*/
private ConnRestrictor connRestrictor;
// changyuan.lh: 并发连接数和阻塞等待的统计对象
private LogCounter statConnNumber;
private LogCounter statConnBlocking;
// final private Timer timer = new Timer();
// private volatile TimerTask timerTask = new TimerTaskC();
protected TAtomDsConfDO runTimeConf;
private static final Map<String, ExceptionSorter> exceptionSorters = new HashMap<String, ExceptionSorter>(2);
static {
exceptionSorters.put(TAtomDbTypeEnum.ORACLE.name(), new OracleExceptionSorter());
exceptionSorters.put(TAtomDbTypeEnum.MYSQL.name(), new MySQLExceptionSorter());
}
private final ReentrantLock lock = new ReentrantLock();
// private volatile boolean isNotAvailable = false; //是否不可用
private volatile SmoothValve smoothValve = new SmoothValve(0);
private volatile CountPunisher timeOutPunisher = new CountPunisher(new SmoothValve(0),
3000,
300); // 3秒钟之内超时300次则惩罚,不可能的阀值,相当于关闭了
private static final int default_retryBadDbInterval = 2000; // milliseconds
protected static int retryBadDbInterval; // milliseconds
static {
int interval = default_retryBadDbInterval;
String propvalue = System.getProperty("com.taobao.tddl.DBSelector.retryBadDbInterval");
if (propvalue != null) {
try {
interval = Integer.valueOf(propvalue.trim());
} catch (Exception e) {
logger.error("", e);
}
}
retryBadDbInterval = interval;
}
public TAtomDbStatusEnum getDbStatus() {
return connectionProperties.dbStatus;
}
public void setDbStatus(TAtomDbStatusEnum dbStatus) {
this.connectionProperties.dbStatus = dbStatus;
}
public static class ConnectionProperties {
public volatile TAtomDbStatusEnum dbStatus;
/**
* 当前数据库的名字
*/
public volatile String datasourceName;
// add by junyu,2012-4-17,日志统计使用
public volatile String ip;
public volatile String port;
public volatile String realDbName;
/**
* 写次数限制,0为不限制
*/
// public volatile int writeRestrictionTimes;
/**
* 读次数限制,0为不限制
*/
// public volatile int readRestrictionTimes;
/**
* 线程count限制,0为不限制
*/
public volatile int threadCountRestriction;
/**
* 允许并发读的最大个数,0为不限制
*/
public volatile int maxConcurrentReadRestrict;
/**
* 允许并发写的最大个数,0为不限制
*/
public volatile int maxConcurrentWriteRestrict;
}
public TDataSourceWrapper(DataSource targetDataSource, TAtomDsConfDO runTimeConf){
this.runTimeConf = runTimeConf;
this.targetDataSource = targetDataSource;
// timerTask = new TimerTaskC();
Monitor.addSnapshotValuesCallbask(this);
// Monitor.addGlobalConfigListener(globalConfigListener);
// timer.schedule(timerTask, 0,
// this.connectionProperties.timeSliceInMillis);
this.readFlowControl = new TimesliceFlowControl("读流量",
runTimeConf.getTimeSliceInMillis(),
runTimeConf.getReadRestrictTimes());
this.writeFlowControl = new TimesliceFlowControl("写流量",
runTimeConf.getTimeSliceInMillis(),
runTimeConf.getWriteRestrictTimes());
logger.warn("set thread count restrict " + runTimeConf.getThreadCountRestrict());
this.connectionProperties.threadCountRestriction = runTimeConf.getThreadCountRestrict();
// logger.warn("set write restrict times " +
// runTimeConf.getWriteRestrictTimes());
// this.connectionProperties.writeRestrictionTimes =
// runTimeConf.getWriteRestrictTimes();
// logger.warn("set read restrict times " +
// runTimeConf.getReadRestrictTimes());
// this.connectionProperties.readRestrictionTimes =
// runTimeConf.getReadRestrictTimes();
logger.warn("set maxConcurrentReadRestrict " + runTimeConf.getMaxConcurrentReadRestrict());
this.connectionProperties.maxConcurrentReadRestrict = runTimeConf.getMaxConcurrentReadRestrict();
logger.warn("set maxConcurrentWriteRestrict " + runTimeConf.getMaxConcurrentWriteRestrict());
this.connectionProperties.maxConcurrentWriteRestrict = runTimeConf.getMaxConcurrentWriteRestrict();
}
public void init() {
// changyuan.lh: 初始化连接分桶
final String datasourceKey = connectionProperties.datasourceName;
List<ConnRestrictEntry> connRestrictEntries = runTimeConf.getConnRestrictEntries();
if (connRestrictEntries != null) {
this.connRestrictor = new ConnRestrictor(datasourceKey, connRestrictEntries);
}
this.statConnNumber = Monitor.connStat(datasourceKey, "-", Monitor.KEY3_CONN_NUMBER);
this.statConnBlocking = Monitor.connStat(datasourceKey, "-", Monitor.KEY3_CONN_BLOCKING);
// timerTask = new TimerTaskC();
Monitor.addSnapshotValuesCallbask(this);
// Monitor.addGlobalConfigListener(globalConfigListener);
// timer.schedule(timerTask, 0,
// this.connectionProperties.timeSliceInMillis);
}
// 包权限,给下游对象调用
void countTimeOut() {
timeOutPunisher.count();
}
private volatile long lastRetryTime = 0;
@Override
public Connection getConnection() throws SQLException {
return getConnection(null, null);
}
/**
* 这里只做了tryLock连接尝试,真正的逻辑委派给getConnection0
*/
@Override
public Connection getConnection(String username, String password) throws SQLException {
SmoothValve valve = smoothValve;
try {
// modify by junyu,暂时去掉这个功能。
// if (!runTimeConf.isSingleInGroup() && timeOutPunisher.punish()) {
// //group里只剩一个时不做超时惩罚。再慢也得干活
// throw new AtomSlowPunishException(this.runTimeConf.getDbName() +
// "'s timeout " + timeOutPunisher); //超时惩罚
// }
if (valve.isNotAvailable()) {
boolean toTry = System.currentTimeMillis() - lastRetryTime > retryBadDbInterval;
if (toTry && lock.tryLock()) {
try {
Connection t = this.getConnection0(username, password); // 同一个时间只会有一个线程继续使用这个数据源。
// isNotAvailable = false; //用一个线程重试,执行成功则标记为可用,自动恢复
valve.setAvailable(); // 用一个线程重试,执行成功则标记为可用,自动恢复
return t;
} finally {
lastRetryTime = System.currentTimeMillis();
lock.unlock();
}
} else {
throw new AtomNotAvailableException(this.runTimeConf.getDbName() + " isNotAvailable"); // 其他线程fail-fast
}
} else {
if (valve.smoothThroughOnInitial()) {
return this.getConnection0(username, password);
} else {
throw new AtomNotAvailableException(this.runTimeConf.getDbName()
+ " squeezeThrough rejected on fatal reset"); // 未通过复位时的限流保护
}
}
} catch (SQLException e) {
ExceptionSorter exceptionSorter = exceptionSorters.get(TStringUtil.upperCase(this.runTimeConf.getDbType()));
if (exceptionSorter.isExceptionFatal(e)) {
NagiosUtils.addNagiosLog(NagiosUtils.KEY_DB_NOT_AVAILABLE + "|" + this.runTimeConf.getDbName(),
e.getMessage());
// isNotAvailable = true;
valve.setNotAvailable();
}
throw new SQLException("get connection failed,dbKey is "
+ (connectionProperties.datasourceName != null ? connectionProperties.datasourceName : this.runTimeConf.getDbName()),
e);
}
}
private Connection getConnection0(String username, String password) throws SQLException {
final long callMillis = System.currentTimeMillis();
ConnRestrictSlot connRestrictSlot = null;
TConnectionWrapper tconnectionWrapper;
try {
recordThreadCount();
if (connRestrictor != null) {
connRestrictSlot = connRestrictor.doRestrict(runTimeConf.getBlockingTimeout());
}
tconnectionWrapper = new TConnectionWrapper(getConnectionByTargetDataSource(username, password),
connRestrictSlot,
this);
} catch (SQLException e) {
if (connRestrictSlot != null) {
connRestrictSlot.freeConnection();
}
threadCount.decrementAndGet();
throw e;
} catch (RuntimeException e) {
if (connRestrictSlot != null) {
connRestrictSlot.freeConnection();
}
threadCount.decrementAndGet();
throw e;
} finally {
// changyuan.lh: 记录统计信息
final long connMillis = System.currentTimeMillis() - callMillis;
if (connRestrictSlot != null) {
connRestrictSlot.statConnection(connMillis);
}
addConnStat(connMillis);
}
return tconnectionWrapper;
}
/**
* changyuan.lh: 记录统计信息
*/
private final void addConnStat(final long connMillis) {
statConnNumber.stat(1, threadCount.get());
statConnBlocking.stat(1, connMillis);
}
private Connection getConnectionByTargetDataSource(String username, String password) throws SQLException {
if (username == null && password == null) {
return targetDataSource.getConnection();
} else {
return targetDataSource.getConnection(username, password);
}
}
private void recordThreadCount() throws SQLException {
int threadCountRestriction = connectionProperties.threadCountRestriction;
int currentThreadCount = threadCount.incrementAndGet();
if (threadCountRestriction != 0) {
if (currentThreadCount > threadCountRestriction) {
threadCountReject.incrementAndGet();
throw new SQLException("max thread count : " + currentThreadCount);
}
}
}
/**
* 设置
*
* @param datasourceName
*/
public synchronized void setDatasourceName(String datasourceName) {
this.connectionProperties.datasourceName = datasourceName;
}
public synchronized void setDatasourceIp(String ip) {
this.connectionProperties.ip = ip;
}
public synchronized void setDatasourcePort(String port) {
this.connectionProperties.port = port;
}
public synchronized void setDatasourceRealDbName(String realDbName) {
this.connectionProperties.realDbName = realDbName;
}
/**
* 设置时间片,在这个时候要重新制定计划。 bug fix : 以前没有重新制定schedule.导致这个设置是无效的
*
* @param timeSliceInMillis
*/
public synchronized void setTimeSliceInMillis(int timeSliceInMillis) {
if (timeSliceInMillis == 0) {
logger.warn("timeSliceInMills is 0,return ");
}
/*
* timerTask.cancel(); timer.purge(); timerTask = new TimerTaskC();
* timer.schedule(timerTask, 0, timeSliceInMillis);
*/
this.readFlowControl = new TimesliceFlowControl("读流量", timeSliceInMillis, runTimeConf.getReadRestrictTimes());
this.writeFlowControl = new TimesliceFlowControl("写流量", timeSliceInMillis, runTimeConf.getWriteRestrictTimes());
// this.connectionProperties.timeSliceInMillis = timeSliceInMillis;
}
/*
* public ConnectionProperties getConnectionProperties() { return
* connectionProperties; } public synchronized void
* setConnectionProperties(ConnectionProperties connectionProperties) {
* this.connectionProperties = connectionProperties; }
*/
/*
* private volatile Values lastReadWriteSnapshot = new Values(); private
* class TimerTaskC extends TimerTask {
* @Override public void run() { lastReadWriteSnapshot = new Values();
* lastReadWriteSnapshot.value1.set(readTimes.longValue());
* lastReadWriteSnapshot.value2.set(writeTimes.longValue());
* readTimes.set(0); writeTimes.set(0); } } private
* SnapshotValuesOutputCallBack snapshotValuesOutputCallBack = new
* SnapshotValuesOutputCallBack() {
* @Override public ConcurrentHashMap<String, Values> getValues() {
* ConcurrentHashMap<String, Values> concurrentHashMap = new
* ConcurrentHashMap<String, Values>(); String prefix =
* connectionProperties.datasourceName + "_"; // 添加threadCount Values
* threadCountValues = new Values();
* threadCountValues.value1.set(threadCount.longValue());
* threadCountValues.value2
* .set(connectionProperties.threadCountRestriction);
* concurrentHashMap.put(prefix + Key.THREAD_COUNT, threadCountValues);
* //添加读写拒绝次数 Values rejectCountValues = new Values();
* rejectCountValues.value1.set(readTimesReject.longValue());
* rejectCountValues.value2.set(writeTimesReject.longValue());
* concurrentHashMap.put(prefix + Key.READ_WRITE_TIMES_REJECT_COUNT,
* rejectCountValues); // 添加读写count concurrentHashMap.put(prefix +
* Key.READ_WRITE_TIMES, lastReadWriteSnapshot); //添加读写并发次数 Values
* rwConcurrent = new Values();
* rwConcurrent.value1.set(concurrentReadCount.longValue());
* rwConcurrent.value2.set(concurrentWriteCount.longValue());
* concurrentHashMap.put(prefix + Key.READ_WRITE_CONCURRENT, rwConcurrent);
* return concurrentHashMap; } }; private GlobalConfigListener
* globalConfigListener = new GlobalConfigListener() { public void
* onConfigReceive(Properties p) { for (Map.Entry<Object, Object> entry :
* p.entrySet()) { String key = ((String) entry.getKey()).trim(); String
* value = ((String) entry.getValue()).trim(); switch
* (TDDLConfigKey.valueOf(key)) { case SmoothValveProperties: { SmoothValve
* old = smoothValve; SmoothValve nnn = SmoothValve.parse(value); if (nnn !=
* null) { logger.warn("smoothValve switch from [" + old + "] to [" + nnn +
* "]"); smoothValve = nnn; } break; } case CountPunisherProperties: {
* CountPunisher old = timeOutPunisher; CountPunisher nnn =
* CountPunisher.parse(smoothValve, value); if (nnn != null) {
* logger.warn("timeOutPunisher switch from [" + old + "] to [" + nnn +
* "]"); timeOutPunisher = nnn; } break; } default: break; } } } }; public
* void destroy() {
* Monitor.removeSnapshotValuesCallback(snapshotValuesOutputCallBack);
* Monitor.removeGlobalConfigListener(globalConfigListener); }
*/
/*
* ========================================================================
* ===== jdbc接口方法,简单委派给targetDataSource
* ======================================================================
*/
@Override
public PrintWriter getLogWriter() throws SQLException {
return targetDataSource.getLogWriter();
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
targetDataSource.setLogWriter(out);
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
targetDataSource.setLoginTimeout(seconds);
}
@Override
public int getLoginTimeout() throws SQLException {
return targetDataSource.getLoginTimeout();
}
/**
* jdk1.6 新增接口
*/
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException {
if (isWrapperFor(iface)) {
return (T) this;
} else {
throw new SQLException("not a wrapper for " + iface);
}
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return TDataSourceWrapper.class.isAssignableFrom(iface);
}
@Override
public void snapshotValues(StatLogWriter statLog) {
String prefix = connectionProperties.datasourceName + "_";
// 添加threadCount
statLog.log(prefix + Key.THREAD_COUNT, threadCount.longValue(), connectionProperties.threadCountRestriction);
// 添加读写拒绝次数
statLog.log(prefix + Key.READ_WRITE_TIMES_REJECT_COUNT,
readTimesReject.longValue() + this.readFlowControl.getTotalRejectCount(),
writeTimesReject.longValue() + this.writeFlowControl.getTotalRejectCount());
// 添加读写count
statLog.log(prefix + Key.READ_WRITE_TIMES,
this.readFlowControl.getCurrentCount(),
this.writeFlowControl.getCurrentCount());
// 添加读写并发次数
statLog.log(prefix + Key.READ_WRITE_CONCURRENT,
this.concurrentReadCount.longValue(),
this.concurrentWriteCount.longValue());
}
}
|
npocmaka/Windows-Server-2003
|
ds/security/services/ca/certview/csviewm.h
|
//+--------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1996 - 1999
//
// File: certviewm.h
//
// Contents: CertView object map entries
//
//---------------------------------------------------------------------------
OBJECT_ENTRY(CLSID_CCertView, CCertView)
|
0system/0system.io.ZeroSystem
|
cores/time/for/moment/0-window.api.js
|
<gh_stars>1-10
exports.forLib = function (LIB) {
var exports = {};
exports.spin = function (context) {
// TODO: Adjust timezone based on config or preference.
console.log("Client time info:", JSON.stringify({
"Date:timezoneOffset": new Date().getTimezoneOffset(),
"Date": "" + new Date(),
"Date:localeTimeString": new Date().toLocaleTimeString(),
"moment": LIB.moment().format("dddd, MMMM Do YYYY, h:mm:ss a Z")
}, null, 4));
return {
moment: LIB.moment
}
}
return exports;
}
|
wiechula/AliPhysics
|
PWGCF/FEMTOSCOPY/AliFemto/AliFemtoCorrFctn3DSpherical.cxx
|
///////////////////////////////////////////////////////////////////////////
// //
// AliFemtoCorrFctn3DSpherical: a class to calculate 3D correlation //
// for pairs of identical particles, binned in spherical coordinates. //
// In analysis the function should be first created in a macro, then //
// added to the analysis, and at the end of the macro the procedure to //
// write out histograms should be called. //
// //
///////////////////////////////////////////////////////////////////////////
#include "AliFemtoCorrFctn3DSpherical.h"
#include <TMath.h>
#include <cstdio>
#ifdef __ROOT__
/// \cond CLASSIMP
ClassImp(AliFemtoCorrFctn3DSpherical);
/// \endcond
#endif
//____________________________
AliFemtoCorrFctn3DSpherical::AliFemtoCorrFctn3DSpherical(char* title, const int& nqbins, const float& QLo, const float& QHi, const int& nphibins, const int& ncthetabins):
fNumerator(0),
fDenominator(0) //,
// fPairCut(0x0)
{
// set up numerator
char tTitNum[101] = "Num";
strncat(tTitNum,title, 100);
fNumerator = new TH3D(tTitNum,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// set up denominator
char tTitDen[101] = "Den";
strncat(tTitDen,title, 100);
fDenominator = new TH3D(tTitDen,title,nqbins,QLo,QHi,nphibins,-TMath::Pi(),TMath::Pi(),ncthetabins,-1.0,1.0);
// to enable error bar calculation...
fNumerator->Sumw2();
fDenominator->Sumw2();
}
AliFemtoCorrFctn3DSpherical::AliFemtoCorrFctn3DSpherical(const AliFemtoCorrFctn3DSpherical& aCorrFctn) :
AliFemtoCorrFctn(aCorrFctn),
fNumerator(0),
fDenominator(0) //,
// fPairCut(0x0)
{
// Copy constructor
fNumerator = new TH3D(*aCorrFctn.fNumerator);
fDenominator = new TH3D(*aCorrFctn.fDenominator);
// fPairCut = aCorrFctn.fPairCut;
}
//____________________________
AliFemtoCorrFctn3DSpherical::~AliFemtoCorrFctn3DSpherical(){
// Destructor
delete fNumerator;
delete fDenominator;
}
//_________________________
AliFemtoCorrFctn3DSpherical& AliFemtoCorrFctn3DSpherical::operator=(const AliFemtoCorrFctn3DSpherical& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (fNumerator) delete fNumerator;
fNumerator = new TH3D(*aCorrFctn.fNumerator);
if (fDenominator) delete fDenominator;
fDenominator = new TH3D(*aCorrFctn.fDenominator);
// fPairCut = aCorrFctn.fPairCut;
return *this;
}
//_________________________
void AliFemtoCorrFctn3DSpherical::WriteOutHistos(){
// Write out all histograms to file
fNumerator->Write();
fDenominator->Write();
}
//______________________________
TList* AliFemtoCorrFctn3DSpherical::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fNumerator);
tOutputList->Add(fDenominator);
return tOutputList;
}
//_________________________
void AliFemtoCorrFctn3DSpherical::Finish(){
// here is where we should normalize, fit, etc...
}
//____________________________
AliFemtoString AliFemtoCorrFctn3DSpherical::Report(){
// Construct the report
string stemp = "PRF Frame Spherical 3D Correlation Function Report:\n";
char ctemp[100];
snprintf(ctemp , 100, "Number of entries in numerator:\t%E\n",fNumerator->GetEntries());
stemp += ctemp;
snprintf(ctemp , 100, "Number of entries in denominator:\t%E\n",fDenominator->GetEntries());
stemp += ctemp;
if (fPairCut){
snprintf(ctemp , 100, "Here is the PairCut specific to this CorrFctn\n");
stemp += ctemp;
stemp += fPairCut->Report();
}
else{
snprintf(ctemp , 100, "No PairCut specific to this CorrFctn\n");
stemp += ctemp;
}
//
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoCorrFctn3DSpherical::AddRealPair( AliFemtoPair* pair){
// perform operations on real pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fNumerator->Fill(tKR,tKP,tKC);
}
//____________________________
void AliFemtoCorrFctn3DSpherical::AddMixedPair( AliFemtoPair* pair){
// perform operations on mixed pairs
if (fPairCut){
if (!(fPairCut->Pass(pair))) return;
}
double tKO = pair->KOut();
double tKS = pair->KSide();
double tKL = pair->KLong();
double tKR = sqrt(tKO*tKO + tKS*tKS + tKL*tKL);
double tKC;
if ( fabs(tKR) < 1e-10 ) tKC = 0.0;
else tKC=tKL/tKR;
double tKP=atan2(tKS,tKO);
fDenominator->Fill(tKR,tKP,tKC);
}
|
scala-steward/csw
|
csw-event/csw-event-client/src/main/scala/csw/event/client/internal/redis/InitializationEvent.scala
|
<gh_stars>10-100
package csw.event.client.internal.redis
import csw.params.core.generics.KeyType.StringKey
import csw.params.events.{EventKey, SystemEvent}
import csw.prefix.models.Subsystem
private[event] object InitializationEvent {
private val initParam = StringKey.make("InitKey").set("IGNORE: Redis publisher initialization")
private val prefix = s"${Subsystem.CSW}.first.event"
private val eventKey = EventKey(s"$prefix.init")
def value: SystemEvent = SystemEvent(eventKey.source, eventKey.eventName, Set(initParam))
}
|
Small-Bodies-Node/ntl_archive_db_demo
|
import_and_persistence/test_files/official_data_sets/ihw-c-irspec-3-edr-gz-v1.0/software/decomp/c/tcclib/vertmenu.c
|
<reponame>Small-Bodies-Node/ntl_archive_db_demo
#include "tcclib.h"
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <stdio.h>
void VertMenu( MenuRec MP[], int numchoices, int x, int y, int xx, int yy )
{
register int i, ptr=0, longest=0;
int begx, begy;
int ch;
char *screen;
for (i=0; i<numchoices; ++i) {
if ( strlen( MP[i].Item ) > longest )
longest = strlen( MP[i].Item );
}
begx = x;
begy = y;
while ( begx+1+longest > 80 ) begx--;
while ( begy+1+numchoices > 25 ) begy--;
if ( begx < 0 ) begx = 0;
if ( begy < 0 ) begy = 0;
screen = (char *) calloc( 4000, 1 );
GetScreen( screen );
ExplodeBox( begx, begy, begx+1+longest, begy+1+numchoices );
for (i=0; i<numchoices; ++i)
AtSay( begx+1, begy+1+i, MP[i].Item );
for (;;) {
ChangeBlock( begx, begy, begx+1+longest, numchoices+begy+1, 0x07 );
ChangeBlock( begx+1, begy+1+ptr, begx+longest, begy+1+ptr, 0x70 );
AtSay( xx, yy, MP[ptr].Desc );
switch( ch = GComm() ) {
case CR:
if ( -1 == MP[ptr].func() ) {
PutScreen( screen );
free( screen );
return;
}
break;
case ESC:
PutScreen( screen );
free( screen );
return;
case DOWN:
if ( ++ptr >= numchoices )
ptr = 0;
break;
case UP:
if ( --ptr < 0 )
ptr = numchoices - 1;
break;
default:
i = ptr + 1;
while ( i != ptr ) {
if ( i >= numchoices ) i = 0;
if ( toupper(MP[i].Item[0]) == toupper(ch) ||
MP[i].FuncKey == ch ) {
ptr = i;
break;
}
i++;
}
break;
}
}
}
|
danilexn/camos
|
camos/plugins/extractsignal/extractsignal.py
|
<reponame>danilexn/camos<filename>camos/plugins/extractsignal/extractsignal.py
# -*- coding: utf-8 -*-
# Created on Sat Jun 05 2021
# Last modified on Mon Jun 07 2021
# Copyright (c) CaMOS Development Team. All Rights Reserved.
# Distributed under a MIT License. See LICENSE for more info.
import numpy as np
from PyQt5.QtCore import pyqtSignal
from camos.tasks.analysis import Analysis
from camos.utils.generategui import NumericInput, ImageInput
from camos.utils.units import get_time
class ExtractSignal(Analysis):
analysis_name = "Extract Signal"
plotReady = pyqtSignal()
required = ["image"]
def __init__(self, model=None, parent=None, signal=None):
super(ExtractSignal, self).__init__(
model, parent, signal, name=self.analysis_name
)
self.mask = None
self.image = None
self.sampling = 1
def _run(
self,
fps: NumericInput("Sampling Rate (Hz)", 10),
F0_time: NumericInput("Time Window ({})".format(get_time()), 10),
F0_perc: NumericInput("Percentile", 50),
_i_mask: ImageInput("Mask Image", 0),
_i_fluor: ImageInput("Fluorescence Image", 0),
):
# Set the variables from the UI
self.sampling = fps
mask = self.model.images[_i_mask].image(0)
image = self.model.images[_i_fluor]
self.imagename = self.model.names[_i_fluor]
# Get the ROIs from the mask
ROIs = np.unique(mask)[1:]
self.raw = np.zeros((len(ROIs), image.frames))
total = len(ROIs)
# Extract raw signals
for i, r in enumerate(ROIs):
cell = mask == r
self.raw[i, :] = np.average(image._image._imgs[:, cell], axis=(1))
self.intReady.emit(i * 100 / total)
# Process raw signals to get dF/F0
F = self.raw
N, frames = F.shape
# Code adapted from FluoroSNNAP
# Determine deltaF/F by subtracting each value with the
# mean of the lower 50% of previous 10-s values and dividing it
# by the mean of the lower 50% of previous 10-s values.
dF_cell = np.zeros(F.shape)
_int_idx = np.arange(0, frames + 1, fps * F0_time)
interval_idx = np.unique(_int_idx)
# For the first 10-s of data, take the min value for F0
F0 = np.min(F[:, 0 : interval_idx[1]], axis=1)
for k in range(interval_idx[1]):
dF_cell[:, k] = (F[:, k] - F0) / F0
for it in range(interval_idx[1], frames):
x = F[:, (it - F0_time) : it]
p = np.percentile(x, F0_perc, axis=1)
F0 = np.zeros(N)
for n in range(N):
F0[n] = np.mean(x[n, np.where(x[n, :] < p[n])])
dF_cell[:, it] = (F[:, it] - F0) / F0
self.output = dF_cell
|
ryanloney/openvino-1
|
tools/pot/openvino/tools/pot/api/metric.py
|
# Copyright (C) 2020-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from abc import ABC, abstractmethod
class Metric(ABC):
"""An abstract class representing an accuracy metric. """
def __init__(self):
""" Constructor """
self.reset()
@property
def value(self):
""" Returns accuracy metric value for the last model output. """
raise Exception('The value() property should be implemented to use this metric '
'with AccuracyAwareQuantization algorithm!')
@property
@abstractmethod
def avg_value(self):
""" Returns accuracy metric value for all model outputs. """
@abstractmethod
def update(self, output, target):
""" Calculates and updates accuracy metric value
:param output: model output
:param target: annotations
"""
@abstractmethod
def reset(self):
""" Reset accuracy metric """
def __call__(self, *args, **kwargs):
self.update(*args, **kwargs)
@property
def higher_better(self):
"""Attribute whether the metric should be increased"""
return True
@abstractmethod
def get_attributes(self):
"""
Returns a dictionary of metric attributes {metric_name: {attribute_name: value}}.
Required attributes: 'direction': 'higher-better' or 'higher-worse'
'type': metric type
"""
|
decilio4g/delicias-do-tchelo
|
node_modules/@styled-icons/remix-fill/Medal/Medal.esm.js
|
<reponame>decilio4g/delicias-do-tchelo
import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '@styled-icons/styled-icon';
export var Medal = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }),
React.createElement("path", { fill: "none", d: "M0 0h24v24H0z", key: "k0" }),
React.createElement("path", { d: "M12 7a8 8 0 110 16 8 8 0 010-16zm0 3.5l-1.323 2.68-2.957.43 2.14 2.085-.505 2.946L12 17.25l2.645 1.39-.505-2.945 2.14-2.086-2.957-.43L12 10.5zm1-8.501L18 2v3l-1.363 1.138A9.935 9.935 0 0013 5.049V2zm-2 0v3.05a9.935 9.935 0 00-3.636 1.088L6 5V2l5-.001z", key: "k1" })));
});
Medal.displayName = 'Medal';
export var MedalDimensions = { height: 24, width: 24 };
|
MikeAlexMartinez/railsbank-js
|
scripts/createInterLedgerTransfer.js
|
<gh_stars>0
const rp = require('request-promise');
/**
* returns a promise to move money between two ledgers that are assigned
* the same user.
*
* @param {Object} transaction
* @param {String} API_KEY
* @return {Promise}
*/
module.exports = function interLedgerTransfer(transaction, API_KEY) {
return new Promise(iLTP);
function iLTP(res, rej) {
const options = {
method: 'POST',
uri: 'https://api.railsbank.com/v1/customer/transactions/inter-ledger',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': API_KEY,
},
body: transaction,
json: true,
};
rp(options)
.then(success)
.catch(error);
function success(enduser) {
console.log("Transferred Money Successfully ----");
console.log("=======================");
res(enduser);
}
function error(err) {
console.log("!! Error Transferring Money !!");
console.log("=======================");
rej(err.error);
rej(err);
}
}
};
|
TheSledgeHammer/2.11BSD
|
contrib/gnu/gdb/dist/sim/sh64/sh-opc.h
|
<reponame>TheSledgeHammer/2.11BSD
/* Instruction opcode header for sh.
THIS FILE IS MACHINE GENERATED WITH CGEN.
Copyright 1996-2020 Free Software Foundation, Inc.
This file is part of the GNU Binutils and/or GDB, the GNU debugger.
This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SH_OPC_H
#define SH_OPC_H
/* Enum declaration for sh instruction types. */
typedef enum cgen_insn_type {
SH_INSN_INVALID, SH_INSN_ADD_COMPACT, SH_INSN_ADDI_COMPACT, SH_INSN_ADDC_COMPACT
, SH_INSN_ADDV_COMPACT, SH_INSN_AND_COMPACT, SH_INSN_ANDI_COMPACT, SH_INSN_ANDB_COMPACT
, SH_INSN_BF_COMPACT, SH_INSN_BFS_COMPACT, SH_INSN_BRA_COMPACT, SH_INSN_BRAF_COMPACT
, SH_INSN_BRK_COMPACT, SH_INSN_BSR_COMPACT, SH_INSN_BSRF_COMPACT, SH_INSN_BT_COMPACT
, SH_INSN_BTS_COMPACT, SH_INSN_CLRMAC_COMPACT, SH_INSN_CLRS_COMPACT, SH_INSN_CLRT_COMPACT
, SH_INSN_CMPEQ_COMPACT, SH_INSN_CMPEQI_COMPACT, SH_INSN_CMPGE_COMPACT, SH_INSN_CMPGT_COMPACT
, SH_INSN_CMPHI_COMPACT, SH_INSN_CMPHS_COMPACT, SH_INSN_CMPPL_COMPACT, SH_INSN_CMPPZ_COMPACT
, SH_INSN_CMPSTR_COMPACT, SH_INSN_DIV0S_COMPACT, SH_INSN_DIV0U_COMPACT, SH_INSN_DIV1_COMPACT
, SH_INSN_DIVU_COMPACT, SH_INSN_MULR_COMPACT, SH_INSN_DMULSL_COMPACT, SH_INSN_DMULUL_COMPACT
, SH_INSN_DT_COMPACT, SH_INSN_EXTSB_COMPACT, SH_INSN_EXTSW_COMPACT, SH_INSN_EXTUB_COMPACT
, SH_INSN_EXTUW_COMPACT, SH_INSN_FABS_COMPACT, SH_INSN_FADD_COMPACT, SH_INSN_FCMPEQ_COMPACT
, SH_INSN_FCMPGT_COMPACT, SH_INSN_FCNVDS_COMPACT, SH_INSN_FCNVSD_COMPACT, SH_INSN_FDIV_COMPACT
, SH_INSN_FIPR_COMPACT, SH_INSN_FLDS_COMPACT, SH_INSN_FLDI0_COMPACT, SH_INSN_FLDI1_COMPACT
, SH_INSN_FLOAT_COMPACT, SH_INSN_FMAC_COMPACT, SH_INSN_FMOV1_COMPACT, SH_INSN_FMOV2_COMPACT
, SH_INSN_FMOV3_COMPACT, SH_INSN_FMOV4_COMPACT, SH_INSN_FMOV5_COMPACT, SH_INSN_FMOV6_COMPACT
, SH_INSN_FMOV7_COMPACT, SH_INSN_FMOV8_COMPACT, SH_INSN_FMOV9_COMPACT, SH_INSN_FMUL_COMPACT
, SH_INSN_FNEG_COMPACT, SH_INSN_FRCHG_COMPACT, SH_INSN_FSCHG_COMPACT, SH_INSN_FSQRT_COMPACT
, SH_INSN_FSTS_COMPACT, SH_INSN_FSUB_COMPACT, SH_INSN_FTRC_COMPACT, SH_INSN_FTRV_COMPACT
, SH_INSN_JMP_COMPACT, SH_INSN_JSR_COMPACT, SH_INSN_LDC_GBR_COMPACT, SH_INSN_LDC_VBR_COMPACT
, SH_INSN_LDC_SR_COMPACT, SH_INSN_LDCL_GBR_COMPACT, SH_INSN_LDCL_VBR_COMPACT, SH_INSN_LDS_FPSCR_COMPACT
, SH_INSN_LDSL_FPSCR_COMPACT, SH_INSN_LDS_FPUL_COMPACT, SH_INSN_LDSL_FPUL_COMPACT, SH_INSN_LDS_MACH_COMPACT
, SH_INSN_LDSL_MACH_COMPACT, SH_INSN_LDS_MACL_COMPACT, SH_INSN_LDSL_MACL_COMPACT, SH_INSN_LDS_PR_COMPACT
, SH_INSN_LDSL_PR_COMPACT, SH_INSN_MACL_COMPACT, SH_INSN_MACW_COMPACT, SH_INSN_MOV_COMPACT
, SH_INSN_MOVI_COMPACT, SH_INSN_MOVI20_COMPACT, SH_INSN_MOVB1_COMPACT, SH_INSN_MOVB2_COMPACT
, SH_INSN_MOVB3_COMPACT, SH_INSN_MOVB4_COMPACT, SH_INSN_MOVB5_COMPACT, SH_INSN_MOVB6_COMPACT
, SH_INSN_MOVB7_COMPACT, SH_INSN_MOVB8_COMPACT, SH_INSN_MOVB9_COMPACT, SH_INSN_MOVB10_COMPACT
, SH_INSN_MOVL1_COMPACT, SH_INSN_MOVL2_COMPACT, SH_INSN_MOVL3_COMPACT, SH_INSN_MOVL4_COMPACT
, SH_INSN_MOVL5_COMPACT, SH_INSN_MOVL6_COMPACT, SH_INSN_MOVL7_COMPACT, SH_INSN_MOVL8_COMPACT
, SH_INSN_MOVL9_COMPACT, SH_INSN_MOVL10_COMPACT, SH_INSN_MOVL11_COMPACT, SH_INSN_MOVL12_COMPACT
, SH_INSN_MOVL13_COMPACT, SH_INSN_MOVW1_COMPACT, SH_INSN_MOVW2_COMPACT, SH_INSN_MOVW3_COMPACT
, SH_INSN_MOVW4_COMPACT, SH_INSN_MOVW5_COMPACT, SH_INSN_MOVW6_COMPACT, SH_INSN_MOVW7_COMPACT
, SH_INSN_MOVW8_COMPACT, SH_INSN_MOVW9_COMPACT, SH_INSN_MOVW10_COMPACT, SH_INSN_MOVW11_COMPACT
, SH_INSN_MOVA_COMPACT, SH_INSN_MOVCAL_COMPACT, SH_INSN_MOVCOL_COMPACT, SH_INSN_MOVT_COMPACT
, SH_INSN_MOVUAL_COMPACT, SH_INSN_MOVUAL2_COMPACT, SH_INSN_MULL_COMPACT, SH_INSN_MULSW_COMPACT
, SH_INSN_MULUW_COMPACT, SH_INSN_NEG_COMPACT, SH_INSN_NEGC_COMPACT, SH_INSN_NOP_COMPACT
, SH_INSN_NOT_COMPACT, SH_INSN_OCBI_COMPACT, SH_INSN_OCBP_COMPACT, SH_INSN_OCBWB_COMPACT
, SH_INSN_OR_COMPACT, SH_INSN_ORI_COMPACT, SH_INSN_ORB_COMPACT, SH_INSN_PREF_COMPACT
, SH_INSN_ROTCL_COMPACT, SH_INSN_ROTCR_COMPACT, SH_INSN_ROTL_COMPACT, SH_INSN_ROTR_COMPACT
, SH_INSN_RTS_COMPACT, SH_INSN_SETS_COMPACT, SH_INSN_SETT_COMPACT, SH_INSN_SHAD_COMPACT
, SH_INSN_SHAL_COMPACT, SH_INSN_SHAR_COMPACT, SH_INSN_SHLD_COMPACT, SH_INSN_SHLL_COMPACT
, SH_INSN_SHLL2_COMPACT, SH_INSN_SHLL8_COMPACT, SH_INSN_SHLL16_COMPACT, SH_INSN_SHLR_COMPACT
, SH_INSN_SHLR2_COMPACT, SH_INSN_SHLR8_COMPACT, SH_INSN_SHLR16_COMPACT, SH_INSN_STC_GBR_COMPACT
, SH_INSN_STC_VBR_COMPACT, SH_INSN_STCL_GBR_COMPACT, SH_INSN_STCL_VBR_COMPACT, SH_INSN_STS_FPSCR_COMPACT
, SH_INSN_STSL_FPSCR_COMPACT, SH_INSN_STS_FPUL_COMPACT, SH_INSN_STSL_FPUL_COMPACT, SH_INSN_STS_MACH_COMPACT
, SH_INSN_STSL_MACH_COMPACT, SH_INSN_STS_MACL_COMPACT, SH_INSN_STSL_MACL_COMPACT, SH_INSN_STS_PR_COMPACT
, SH_INSN_STSL_PR_COMPACT, SH_INSN_SUB_COMPACT, SH_INSN_SUBC_COMPACT, SH_INSN_SUBV_COMPACT
, SH_INSN_SWAPB_COMPACT, SH_INSN_SWAPW_COMPACT, SH_INSN_TASB_COMPACT, SH_INSN_TRAPA_COMPACT
, SH_INSN_TST_COMPACT, SH_INSN_TSTI_COMPACT, SH_INSN_TSTB_COMPACT, SH_INSN_XOR_COMPACT
, SH_INSN_XORI_COMPACT, SH_INSN_XORB_COMPACT, SH_INSN_XTRCT_COMPACT, SH_INSN_ADD
, SH_INSN_ADDL, SH_INSN_ADDI, SH_INSN_ADDIL, SH_INSN_ADDZL
, SH_INSN_ALLOCO, SH_INSN_AND, SH_INSN_ANDC, SH_INSN_ANDI
, SH_INSN_BEQ, SH_INSN_BEQI, SH_INSN_BGE, SH_INSN_BGEU
, SH_INSN_BGT, SH_INSN_BGTU, SH_INSN_BLINK, SH_INSN_BNE
, SH_INSN_BNEI, SH_INSN_BRK, SH_INSN_BYTEREV, SH_INSN_CMPEQ
, SH_INSN_CMPGT, SH_INSN_CMPGTU, SH_INSN_CMVEQ, SH_INSN_CMVNE
, SH_INSN_FABSD, SH_INSN_FABSS, SH_INSN_FADDD, SH_INSN_FADDS
, SH_INSN_FCMPEQD, SH_INSN_FCMPEQS, SH_INSN_FCMPGED, SH_INSN_FCMPGES
, SH_INSN_FCMPGTD, SH_INSN_FCMPGTS, SH_INSN_FCMPUND, SH_INSN_FCMPUNS
, SH_INSN_FCNVDS, SH_INSN_FCNVSD, SH_INSN_FDIVD, SH_INSN_FDIVS
, SH_INSN_FGETSCR, SH_INSN_FIPRS, SH_INSN_FLDD, SH_INSN_FLDP
, SH_INSN_FLDS, SH_INSN_FLDXD, SH_INSN_FLDXP, SH_INSN_FLDXS
, SH_INSN_FLOATLD, SH_INSN_FLOATLS, SH_INSN_FLOATQD, SH_INSN_FLOATQS
, SH_INSN_FMACS, SH_INSN_FMOVD, SH_INSN_FMOVDQ, SH_INSN_FMOVLS
, SH_INSN_FMOVQD, SH_INSN_FMOVS, SH_INSN_FMOVSL, SH_INSN_FMULD
, SH_INSN_FMULS, SH_INSN_FNEGD, SH_INSN_FNEGS, SH_INSN_FPUTSCR
, SH_INSN_FSQRTD, SH_INSN_FSQRTS, SH_INSN_FSTD, SH_INSN_FSTP
, SH_INSN_FSTS, SH_INSN_FSTXD, SH_INSN_FSTXP, SH_INSN_FSTXS
, SH_INSN_FSUBD, SH_INSN_FSUBS, SH_INSN_FTRCDL, SH_INSN_FTRCSL
, SH_INSN_FTRCDQ, SH_INSN_FTRCSQ, SH_INSN_FTRVS, SH_INSN_GETCFG
, SH_INSN_GETCON, SH_INSN_GETTR, SH_INSN_ICBI, SH_INSN_LDB
, SH_INSN_LDL, SH_INSN_LDQ, SH_INSN_LDUB, SH_INSN_LDUW
, SH_INSN_LDW, SH_INSN_LDHIL, SH_INSN_LDHIQ, SH_INSN_LDLOL
, SH_INSN_LDLOQ, SH_INSN_LDXB, SH_INSN_LDXL, SH_INSN_LDXQ
, SH_INSN_LDXUB, SH_INSN_LDXUW, SH_INSN_LDXW, SH_INSN_MABSL
, SH_INSN_MABSW, SH_INSN_MADDL, SH_INSN_MADDW, SH_INSN_MADDSL
, SH_INSN_MADDSUB, SH_INSN_MADDSW, SH_INSN_MCMPEQB, SH_INSN_MCMPEQL
, SH_INSN_MCMPEQW, SH_INSN_MCMPGTL, SH_INSN_MCMPGTUB, SH_INSN_MCMPGTW
, SH_INSN_MCMV, SH_INSN_MCNVSLW, SH_INSN_MCNVSWB, SH_INSN_MCNVSWUB
, SH_INSN_MEXTR1, SH_INSN_MEXTR2, SH_INSN_MEXTR3, SH_INSN_MEXTR4
, SH_INSN_MEXTR5, SH_INSN_MEXTR6, SH_INSN_MEXTR7, SH_INSN_MMACFXWL
, SH_INSN_MMACNFX_WL, SH_INSN_MMULL, SH_INSN_MMULW, SH_INSN_MMULFXL
, SH_INSN_MMULFXW, SH_INSN_MMULFXRPW, SH_INSN_MMULHIWL, SH_INSN_MMULLOWL
, SH_INSN_MMULSUMWQ, SH_INSN_MOVI, SH_INSN_MPERMW, SH_INSN_MSADUBQ
, SH_INSN_MSHALDSL, SH_INSN_MSHALDSW, SH_INSN_MSHARDL, SH_INSN_MSHARDW
, SH_INSN_MSHARDSQ, SH_INSN_MSHFHIB, SH_INSN_MSHFHIL, SH_INSN_MSHFHIW
, SH_INSN_MSHFLOB, SH_INSN_MSHFLOL, SH_INSN_MSHFLOW, SH_INSN_MSHLLDL
, SH_INSN_MSHLLDW, SH_INSN_MSHLRDL, SH_INSN_MSHLRDW, SH_INSN_MSUBL
, SH_INSN_MSUBW, SH_INSN_MSUBSL, SH_INSN_MSUBSUB, SH_INSN_MSUBSW
, SH_INSN_MULSL, SH_INSN_MULUL, SH_INSN_NOP, SH_INSN_NSB
, SH_INSN_OCBI, SH_INSN_OCBP, SH_INSN_OCBWB, SH_INSN_OR
, SH_INSN_ORI, SH_INSN_PREFI, SH_INSN_PTA, SH_INSN_PTABS
, SH_INSN_PTB, SH_INSN_PTREL, SH_INSN_PUTCFG, SH_INSN_PUTCON
, SH_INSN_RTE, SH_INSN_SHARD, SH_INSN_SHARDL, SH_INSN_SHARI
, SH_INSN_SHARIL, SH_INSN_SHLLD, SH_INSN_SHLLDL, SH_INSN_SHLLI
, SH_INSN_SHLLIL, SH_INSN_SHLRD, SH_INSN_SHLRDL, SH_INSN_SHLRI
, SH_INSN_SHLRIL, SH_INSN_SHORI, SH_INSN_SLEEP, SH_INSN_STB
, SH_INSN_STL, SH_INSN_STQ, SH_INSN_STW, SH_INSN_STHIL
, SH_INSN_STHIQ, SH_INSN_STLOL, SH_INSN_STLOQ, SH_INSN_STXB
, SH_INSN_STXL, SH_INSN_STXQ, SH_INSN_STXW, SH_INSN_SUB
, SH_INSN_SUBL, SH_INSN_SWAPQ, SH_INSN_SYNCI, SH_INSN_SYNCO
, SH_INSN_TRAPA, SH_INSN_XOR, SH_INSN_XORI
} CGEN_INSN_TYPE;
/* Index of `invalid' insn place holder. */
#define CGEN_INSN_INVALID SH_INSN_INVALID
/* Total number of insns in table. */
#define MAX_INSNS ((int) SH_INSN_XORI + 1)
/* This struct records data prior to insertion or after extraction. */
struct cgen_fields
{
int length;
long f_nil;
long f_anyof;
long f_op4;
long f_op8;
long f_op16;
long f_sub4;
long f_sub8;
long f_sub10;
long f_rn;
long f_rm;
long f_7_1;
long f_11_1;
long f_16_4;
long f_disp8;
long f_disp12;
long f_imm8;
long f_imm4;
long f_imm4x2;
long f_imm4x4;
long f_imm8x2;
long f_imm8x4;
long f_imm12x4;
long f_imm12x8;
long f_dn;
long f_dm;
long f_vn;
long f_vm;
long f_xn;
long f_xm;
long f_imm20_hi;
long f_imm20_lo;
long f_imm20;
long f_op;
long f_ext;
long f_rsvd;
long f_left;
long f_right;
long f_dest;
long f_left_right;
long f_tra;
long f_trb;
long f_likely;
long f_6_3;
long f_23_2;
long f_imm6;
long f_imm10;
long f_imm16;
long f_uimm6;
long f_uimm16;
long f_disp6;
long f_disp6x32;
long f_disp10;
long f_disp10x8;
long f_disp10x4;
long f_disp10x2;
long f_disp16;
};
#define CGEN_INIT_PARSE(od) \
{\
}
#define CGEN_INIT_INSERT(od) \
{\
}
#define CGEN_INIT_EXTRACT(od) \
{\
}
#define CGEN_INIT_PRINT(od) \
{\
}
#endif /* SH_OPC_H */
|
Martincho07/IG-mini-PT
|
practica1/main.cpp
|
<reponame>Martincho07/IG-mini-PT
/*********************************************************************************
* Main
*
* File: main.cpp
* Author: <NAME> (NIA: 756012)
* Author: <NAME> (NIA: 759533)
* Date: 22/10/2020
* Coms: Informática Gráfica, curso 2020-2021
**********************************************************************************/
#include <fstream>
#include <iostream>
#include "geometry.hpp"
#include "planet.hpp"
Planet readStation(std::istream &is, bool interactive) {
Vector3 axis;
Point3 center, refCity;
float inclination, azimuth;
float x, y, z;
// If interactive is false, supress the ouput
if (!interactive) {
std::cout.setstate(std::ios::failbit);
}
std::cout << "Enter a station:" << std::endl;
std::cout << "\tPlanet center: ";
is >> x >> y >> z;
center = Point3(x, y, z);
std::cout << "\tPlanet axis: ";
is >> x >> y >> z;
axis = Vector3(x, y, z);
std::cout << "\tReference city: ";
is >> x >> y >> z;
refCity = Point3(x, y, z);
std::cout << "\tStation inclination: ";
is >> inclination;
std::cout << "\tStation azimuth: ";
is >> azimuth;
// Restore cout status
std::cout.clear();
std::cout << center << axis << refCity << inclination << azimuth << std::endl;
return Planet(center, refCity, axis, inclination, azimuth);
}
int main(int argc, char **argv) {
Planet planet1, planet2;
// If there's a file as argument, read it
// Else, ask for the stations from standard input
if (argc > 1) {
std::filebuf fb;
if (fb.open(argv[1], std::ios::in)) {
std::istream is(&fb);
planet1 = readStation(is, false);
planet2 = readStation(is, false);
} else {
std::cout << "No se ha podido abrir el fichero: " << argv[1] << std::endl;
return 1;
}
} else {
std::cout << "Origin planet" << std::endl;
planet1 = readStation(std::cin, true);
std::cout << "\nDestination planet" << std::endl;
planet2 = readStation(std::cin, true);
}
std::cout << std::endl
<< "Trayectorias" << std::endl;
launch(planet1, planet2);
return 0;
}
|
apdoerL/condition-order-server
|
condition-quot/src/main/java/org/apdoer/condition/quot/source/deserializer/ZmqDeserializer.java
|
<filename>condition-quot/src/main/java/org/apdoer/condition/quot/source/deserializer/ZmqDeserializer.java
package org.apdoer.condition.quot.source.deserializer;
import org.apdoer.condition.quot.payload.QuotPriceMessageSourcePayload;
/**
* @author apdoer
* @version 1.0
* @date 2020/5/12 11:18
*/
public interface ZmqDeserializer extends Deserializer<String, QuotPriceMessageSourcePayload> {
}
|
mattjanssen/manhattan
|
angular/service/AuthenticationService.js
|
<filename>angular/service/AuthenticationService.js
'use strict';
module.exports = function ($http, $location, $q, $rootScope, API_URL) {
var AuthenticationService = {};
var API_KEY_STORAGE_KEY = 'k';
var API_KEY_URL_PARAM = 'key';
var LOGIN_URL = '/login/google';
var storage = localStorage;
var key = null;
loadCredentials();
AuthenticationService.getKey = getKey;
AuthenticationService.isLoggedIn = isLoggedIn;
AuthenticationService.login = login;
AuthenticationService.logout = logout;
// Register this function globally to use in templates.
// Inside components, access it using $root.isLoggedIn().
$rootScope.isLoggedIn = isLoggedIn;
return AuthenticationService;
/**
* Check the URL Parameters or LocalStorage for an API Key
*
* @return Promise
*/
function loadCredentials() {
key = $location.search()[API_KEY_URL_PARAM];
if (key) {
// Save the API key from the URL in storage.
storage.setItem(API_KEY_STORAGE_KEY, key);
// Remove the key from the URL and browser history.
$location.search(API_KEY_URL_PARAM, null);
$location.replace();
} else {
// Try to get the key from storage.
key = storage.getItem(API_KEY_STORAGE_KEY);
}
if (!key) {
// Credentials are missing. Enforce a logged-out state.
return $q.reject();
}
}
/**
* Get the User's API Key
*
* @return string
*/
function getKey() {
return key;
}
/**
* Check if Logged In
*
* @return boolean
*/
function isLoggedIn() {
return !!key;
};
/**
* Redirect User to Google OAuth Process
*/
function login() {
$http.get(API_URL + LOGIN_URL).then(function (success) {
window.location = success.data.data;
});
};
/**
* Clear Credentials and Trigger Logout if Logged In
*/
function logout() {
storage.removeItem(API_KEY_STORAGE_KEY);
key = null;
$rootScope.$emit('authentication.logout');
};
};
|
thedatanecdotes/DataAnecdotesWebsite
|
node_modules/@material-ui/icons/esm/SubdirectoryArrowLeftOutlined.js
|
<reponame>thedatanecdotes/DataAnecdotesWebsite
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon( /*#__PURE__*/React.createElement("path", {
d: "M11 9l1.42 1.42L8.83 14H18V4h2v12H8.83l3.59 3.58L11 21l-6-6 6-6z"
}), 'SubdirectoryArrowLeftOutlined');
|
mamico/relstorage
|
src/relstorage/adapters/mysql/tests/test_adapter.py
|
<reponame>mamico/relstorage
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2019 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..adapter import MySQLAdapter as Adapter
from ...tests import test_adapter
class MockVersionDetector(object):
def supports_good_stored_procs(self, _cursor):
return True
class MockConnection(object):
cursor = None
class MockDriver(object):
last_callproc_args = None
last_callproc_kwargs = None
last_callproc_multi_result = ((),)
def callproc_multi_result(self, _cur, *args, **kwargs):
self.last_callproc_args = args
self.last_callproc_kwargs = kwargs
return self.last_callproc_multi_result
class TestAdapter(test_adapter.AdapterTestBase):
def _makeOne(self, options):
return Adapter(options=options)
def _test_lock_database_and_move_ends_critical_section_on_commit(self, commit):
adapter = self._makeOne(None)
driver = adapter.driver = MockDriver()
driver.last_callproc_multi_result = (([42],),)
adapter.version_detector = MockVersionDetector()
result = adapter.lock_database_and_move(
MockConnection(),
None,
(),
commit=commit
)
self.assertEqual(result, (42, "-"))
self.assertEqual(
driver.last_callproc_kwargs,
{'exit_critical_phase': commit}
)
def test_lock_database_and_move_ends_critical_section_on_commit(self):
self._test_lock_database_and_move_ends_critical_section_on_commit(True)
def test_lock_database_and_move_keeps_critical_section_wo_commit(self):
self._test_lock_database_and_move_ends_critical_section_on_commit(False)
|
bibbityjibbity/NexusInterface
|
src/App/Overview/index.js
|
<filename>src/App/Overview/index.js<gh_stars>10-100
// External
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import styled from '@emotion/styled';
import { keyframes } from '@emotion/core';
import GA from 'lib/googleAnalytics';
// Internal
import Icon from 'components/Icon';
import Tooltip from 'components/Tooltip';
import { getDifficulty } from 'lib/core';
import { updateSettings } from 'lib/settings';
import { formatNumber, formatCurrency, formatRelativeTime } from 'lib/intl';
import { timing, consts } from 'styles';
import { isCoreConnected } from 'selectors';
import Globe from './Globe';
import { webGLAvailable } from 'consts/misc';
// Images
import logoIcon from 'icons/NXS_coin.svg';
import currencyIcons from 'data/currencyIcons';
import transactionIcon from 'icons/transaction.svg';
import chartIcon from 'icons/chart.svg';
import supplyIcon from 'icons/supply.svg';
import hours24Icon from 'icons/24hr.svg';
import nxsStakeIcon from 'icons/nxs-staking.svg';
import Connections0 from 'icons/Connections0.svg';
import Connections4 from 'icons/Connections4.svg';
import Connections8 from 'icons/Connections8.svg';
import Connections12 from 'icons/Connections12.svg';
import Connections14 from 'icons/Connections14.svg';
import Connections16 from 'icons/Connections16.svg';
import blockweight0 from 'icons/BlockWeight-0.svg';
import blockweight1 from 'icons/BlockWeight-1.svg';
import blockweight2 from 'icons/BlockWeight-2.svg';
import blockweight3 from 'icons/BlockWeight-3.svg';
import blockweight4 from 'icons/BlockWeight-4.svg';
import blockweight5 from 'icons/BlockWeight-5.svg';
import blockweight6 from 'icons/BlockWeight-6.svg';
import blockweight7 from 'icons/BlockWeight-7.svg';
import blockweight8 from 'icons/BlockWeight-8.svg';
import blockweight9 from 'icons/BlockWeight-9.svg';
import trust00 from 'icons/trust00.svg';
import trust10 from 'icons/trust00.svg';
import trust20 from 'icons/trust00.svg';
import trust30 from 'icons/trust00.svg';
import trust40 from 'icons/trust00.svg';
import trust50 from 'icons/trust00.svg';
import trust60 from 'icons/trust00.svg';
import trust70 from 'icons/trust00.svg';
import trust80 from 'icons/trust00.svg';
import trust90 from 'icons/trust00.svg';
import trust100 from 'icons/trust00.svg';
import nxsblocksIcon from 'icons/blockexplorer-invert-white.svg';
import interestIcon from 'icons/interest.svg';
import stakeIcon from 'icons/staking-white.svg';
import warningIcon from 'icons/warning.svg';
import questionMarkCircleIcon from 'icons/question-mark-circle.svg';
__ = __context('Overview');
const trustIcons = [
trust00,
trust10,
trust20,
trust30,
trust40,
trust50,
trust60,
trust70,
trust80,
trust90,
trust100,
];
const blockWeightIcons = [
blockweight0,
blockweight1,
blockweight2,
blockweight3,
blockweight4,
blockweight5,
blockweight6,
blockweight7,
blockweight8,
blockweight9,
blockweight9,
];
/**
* Formats the Difficulty to 3 decimal points
* @memberof Overview
* @param {*} diff
* @returns {Number} Diff but with 3 decimal point places
*/
const formatDiff = diff => (diff || 0).toFixed(3);
// React-Redux mandatory methods
const mapStateToProps = state => {
const {
core: { info, difficulty },
common: { blockDate },
market: {
cryptocompare: { rawNXSvalues, displayNXSvalues },
},
settings,
theme,
} = state;
const { synccomplete } = info;
const syncUnknown =
(!synccomplete && synccomplete !== 0) ||
synccomplete < 0 ||
synccomplete > 100;
const displayValues =
displayNXSvalues &&
displayNXSvalues.find(e => e.name === settings.fiatCurrency);
return {
coreConnected: isCoreConnected(state),
difficulty,
blockDate,
market: {
...(rawNXSvalues &&
rawNXSvalues.find(e => e.name === settings.fiatCurrency)),
displayMarketCap: displayValues && displayValues.marketCap,
},
settings,
theme,
coreInfo: info,
synchronizing: !syncUnknown && synccomplete !== 100,
};
};
const OverviewPage = styled.div({
width: '100%',
position: 'relative',
});
const slideRight = keyframes`
0% {
opacity: 0;
transform: translate(-100px,-50%);
}
100% {
opacity: 1;
transform: translate(0,-50%);
}
`;
const slideLeft = keyframes`
0% {
opacity: 0;
transform: translate(100px,-50%);
}
100% {
opacity: 1;
transform: translate(0,-50%);
}
`;
const Stats = styled.div(
{
position: 'absolute',
top: '50%',
transform: 'translateY(-50%)',
whiteSpace: 'nowrap',
// I don't like this but its a quick fix for super small screens.
'@media (min-height: 10px) and (max-height: 720px)': {
fontSize: '75%',
'& svg': {
transform: 'scale(0.75)',
},
},
},
({ left, compact }) =>
left && {
textAlign: 'right',
right: compact ? 'calc(56% + 80px)' : 'calc(70% + 80px)',
animation: `${timing.slow} ${consts.enhancedEaseOut} 0s ${slideRight}`,
[Stat]: {
justifyContent: 'flex-end',
},
[StatIcon]: {
marginLeft: 15,
},
},
({ right, compact }) =>
right && {
textAlign: 'left',
left: compact ? 'calc(56% + 80px)' : 'calc(70% + 80px)',
animation: `${timing.slow} ${consts.enhancedEaseOut} 0s ${slideLeft}`,
[Stat]: {
justifyContent: 'flex-start',
},
[StatIcon]: {
marginRight: 15,
},
}
);
const MinimalStats = styled.div({
fontSize: '45%',
textAlign: 'center',
display: 'flex',
margin: '0 auto',
marginTop: '-1em',
animation: `${timing.slow} ${consts.enhancedEaseOut} 0s ${slideRight}`,
justifyContent: 'center',
});
const Stat = styled.div(
({ theme }) => ({
display: 'block',
margin: '1.7em 0',
display: 'flex',
alignItems: 'center',
filter: `drop-shadow(0 0 5px #000)`,
color: theme.foreground,
}),
({ to, theme }) =>
to && {
cursor: 'pointer',
transitionProperty: 'filter',
transitionDuration: timing.normal,
transitionTimingFunction: 'ease-out',
'&:hover': {
filter: `drop-shadow(0 0 8px ${theme.primary}) brightness(120%)`,
},
}
);
const MinimalStat = styled.div(
({ theme }) =>
theme && {
display: 'flex',
alignItems: 'center',
background: 'rgb(0,0,0,0.5)',
filter: `drop-shadow(0 0 2px ` + theme.primaryAccent + `)`,
marginLeft: '1.5em',
[StatValue]: {
marginLeft: '0.5em',
height: '50%',
lineHeight: '50%',
whiteSpace: 'nowrap',
},
[StatLabel]: {
height: '50%',
marginTop: '0.50em',
whiteSpace: 'nowrap',
lineHeight: '50%',
},
}
);
const StatLabel = styled.div(({ theme }) => ({
fontWeight: 'bold',
letterSpacing: 0.5,
textTransform: 'uppercase',
fontSize: '.9em',
color: theme.primary,
}));
const StatValue = styled.div({
fontSize: '1.8em',
});
const StatIcon = styled(Icon)(({ theme }) => ({
width: 38,
height: 38,
color: theme.primary,
}));
const MaxmindCopyright = styled.div(({ theme }) => ({
position: 'fixed',
left: 6,
bottom: 3,
opacity: 0.4,
color: theme.primary,
zIndex: 1, // over the navigation bar
}));
const MaxmindLogo = styled.img({
display: 'block',
width: 181,
});
const BlockCountTooltip = ({ blockDate }) => (
<div style={{ textAlign: 'center' }}>
{__('Last updated\n%{time}', {
time: blockDate && formatRelativeTime(blockDate),
})}
</div>
);
/**
* Overview Page, The main page
*
* @class Overview
* @extends {Component}
*/
class Overview extends Component {
/**
*Creates an instance of Overview.
* @param {*} props
* @memberof Overview
*/
constructor(props) {
super(props);
this.fetchDifficulty();
}
/**
* Component Mount Callback
*
* @memberof Overview
*/
componentDidMount() {
GA.SendScreen('Overview');
}
/**
* Set by {NetworkGlobe}, ReDraws all Pillars and Archs
*
* @memberof Overview
*/
reDrawEverything() {}
/**
* Component Unmount Callback
*
* @memberof Overview
*/
componentWillUnmount() {
clearTimeout(this.diffFetcher);
}
/**
* Component Prop Update Callback
*
* @param {*} prevProps
* @returns
* @memberof Overview
*/
componentDidUpdate(prevProps) {
const {
settings,
coreInfo: { blocks, connections },
} = this.props;
const correctView =
settings.overviewDisplay !== 'minimalist' &&
settings.overviewDisplay !== 'none';
if (
settings.acceptedAgreement &&
webGLAvailable &&
settings.renderGlobe &&
correctView
) {
if (blocks != prevProps.blocks && blocks && prevProps.blocks) {
this.redrawCurves();
}
if (prevProps.connections && connections == 0) {
this.removeAllPoints();
this.reDrawEverything();
return;
}
if (connections && prevProps.connections !== connections) {
//Core Starting Up
this.reDrawEverything();
}
}
}
/**
* Get the Difficulty from the network
*
* @memberof Overview
*/
fetchDifficulty = async () => {
await getDifficulty();
this.diffFetcher = setTimeout(this.fetchDifficulty, 50000);
};
/**
* Returns the Block Date of the last given block
*
* @returns
* @memberof Overview
*/
blockDate() {
if (!this.props.blockDate) {
return __('Getting next block...');
} else {
return (
this.props.blockDate &&
this.props.blockDate.toLocaleString(this.props.settings.locale)
);
}
}
/**
* Returns the Connections icon based on how many connections the user has
*
* @returns
* @memberof Overview
*/
connectionsIcon() {
const con = this.props.connections;
if (con > 4 && con <= 6) {
return Connections4;
} else if (con > 6 && con <= 12) {
return Connections8;
} else if (con > 12 && con <= 14) {
return Connections12;
} else if (con > 14 && con <= 15) {
return Connections14;
} else if (con > 15) {
return Connections16;
} else {
return Connections0;
}
}
/**
* Returns the trust icon
*
* @returns
* @memberof Overview
*/
trustIcon() {
const tw = Math.round((this.props.coreInfo.trustweight || 0) / 10);
return trustIcons[tw];
}
/**
* Returns the block weight icon
*
* @returns
* @memberof Overview
*/
blockWeightIcon() {
const bw = Math.round((this.props.coreInfo.blockweight || 0) / 10);
return blockWeightIcons[bw];
}
/**
* Returns if the Globe should be rendered
*
* @returns
* @memberof Overview
*/
showingGlobe() {
return (
this.props.settings.acceptedAgreement &&
this.props.settings.renderGlobe &&
webGLAvailable
);
}
/**
* Add in Commas to a number
*
* @param {*} x
* @returns
* @memberof Overview
*/
numberWithCommas(x) {
if (typeof x === 'number')
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
/**
* Displays Wait for Core
*
* @memberof Overview
*/
waitForCore = stat =>
this.props.coreConnected ? stat : <span className="dim">-</span>;
/**
* Returns the weight stats for the overview page
*
* @memberof Overview
*/
returnWeightStats = () => {
const { coreInfo } = this.props;
const { blockweight, trustweight, stakeweight } = coreInfo || {};
return (
<React.Fragment>
<Stat>
<StatIcon icon={this.blockWeightIcon()} />
<div>
<StatLabel>{__('Block Weight')}</StatLabel>
<StatValue>
{this.waitForCore(
blockweight ? formatNumber(blockweight, 2) + '%' : 'N/A'
)}
</StatValue>
</div>
</Stat>
<Stat>
<StatIcon icon={this.trustIcon()} />
<div>
<StatLabel>{__('Trust Weight')}</StatLabel>
<StatValue>
{this.waitForCore(
trustweight ? formatNumber(trustweight, 2) + '%' : 'N/A'
)}
</StatValue>
</div>
</Stat>
<Stat>
<StatIcon icon={stakeIcon} />
<div>
<StatLabel>{__('Stake Weight')}</StatLabel>
<StatValue>
{this.waitForCore(
stakeweight ? formatNumber(stakeweight, 2) + '%' : 'N/A'
)}
</StatValue>
</div>
</Stat>
</React.Fragment>
);
};
/**
* Returns the Difficulty Stats for the Overview page when it is in Miner View
*
* @memberof Overview
*/
returnDifficultyStats = difficulty => {
return (
<React.Fragment>
<Stat>
<StatIcon icon={this.trustIcon()} />
<div>
<StatLabel>{__('Prime Difficulty')}</StatLabel>
<StatValue>
{!!difficulty ? (
formatNumber(difficulty.prime, 6)
) : (
<span className="dim">-</span>
)}
</StatValue>
</div>
</Stat>
<Stat>
<StatIcon icon={stakeIcon} />
<div>
<StatLabel>{__('Hash Difficulty')}</StatLabel>
<StatValue>
{!!difficulty ? (
formatNumber(difficulty.hash, 6)
) : (
<span className="dim">-</span>
)}
</StatValue>
</div>
</Stat>
<Stat>
<StatIcon icon={this.blockWeightIcon()} />
<div>
<StatLabel>{__('Stake Difficulty')}</StatLabel>
<StatValue>
{!!difficulty ? (
formatNumber(difficulty.stake, 6)
) : (
<span className="dim">-</span>
)}
</StatValue>
</div>
</Stat>
</React.Fragment>
);
};
// Mandatory React method
/**
* Component's Renderable JSX
*
* @returns
* @memberof Overview
*/
render() {
const {
coreInfo: {
coreConnected,
connections,
balance,
unconfirmedbalance,
stake,
newmint,
txtotal,
interestweight,
stakerate,
blocks,
},
blockDate,
market,
difficulty,
settings,
theme,
synchronizing,
} = this.props;
const { fiatCurrency } = settings;
if (settings.overviewDisplay === 'none') {
return <OverviewPage />;
}
if (settings.overviewDisplay === 'minimalist') {
return (
<OverviewPage>
<MinimalStats>
<MinimalStat>
<StatLabel>
{/* {stake > 0 ? (
<span>Balance and Stake</span>
) : ( */}
{__('Balance')}
{/* )} */}
(NXS) :
</StatLabel>
<StatValue>
{this.waitForCore(formatNumber(balance + unconfirmedbalance))}
</StatValue>
</MinimalStat>
{/* + (stake || 0) */}
<MinimalStat>
<StatLabel>
{__('Balance')} ({fiatCurrency})
</StatLabel>
<StatValue>
{market && market.price ? (
this.waitForCore(
formatCurrency(
(balance + unconfirmedbalance) * market.price,
fiatCurrency
)
)
) : (
<span className="dim">-</span>
)}
</StatValue>
</MinimalStat>
<MinimalStat>
<StatLabel>{__('Transactions')}</StatLabel>
<StatValue>{this.waitForCore(txtotal)}</StatValue>
</MinimalStat>
<MinimalStat>
<StatLabel>
{__('Market Price')} ({fiatCurrency})
</StatLabel>
<StatValue>
{market && market.price ? (
<>
{fiatCurrency === 'BTC'
? formatCurrency(market.price, fiatCurrency, 8)
: fiatCurrency !== 'BTC'
? formatCurrency(market.price, fiatCurrency, 2)
: ''}
</>
) : (
<span className="dim">-</span>
)}
</StatValue>
</MinimalStat>
<MinimalStat>
<StatLabel>
{__('24hr Change')} ({fiatCurrency} %)
</StatLabel>
<StatValue>
{market && typeof market.changePct24Hr === 'number' ? (
<>
{market.changePct24Hr > 0
? '+ '
: market.changePct24Hr < 0
? '- '
: ''}
{formatNumber(market.changePct24Hr, 2) + '%'}
</>
) : (
<span className="dim">-</span>
)}
</StatValue>
</MinimalStat>
<MinimalStat>
<StatLabel>{__('Connections')}</StatLabel>
<StatValue>{this.waitForCore(connections)}</StatValue>
</MinimalStat>
<MinimalStat>
<StatLabel>{__('Stake Rate')}</StatLabel>
<StatValue>
{this.waitForCore(
formatNumber(interestweight || stakerate, 2) + '%'
)}
</StatValue>
</MinimalStat>
<MinimalStat className="relative">
<StatLabel>{__('Block Count')}</StatLabel>
<StatValue>
{this.waitForCore(this.numberWithCommas(blocks))}
</StatValue>
</MinimalStat>
</MinimalStats>
</OverviewPage>
);
}
return (
<OverviewPage>
{!!this.showingGlobe() && (
<Globe
handleOnLineRender={e => (this.redrawCurves = e)}
handleRemoveAllPoints={e => (this.removeAllPoints = e)}
connections={connections}
pillarColor={theme.globePillarColor}
archColor={theme.globeArchColor}
globeColor={theme.globeColor}
lispPillarColor="#00ffff"
/>
)}
<Stats left compact={!this.showingGlobe()}>
<Stat
onClick={() => {
updateSettings({
displayFiatBalance: !settings.displayFiatBalance,
});
}}
to={coreConnected ? 'HackToGetProperStyling' : undefined}
>
<div>
<StatLabel>
{!!synchronizing && (
<Tooltip.Trigger
align="start"
tooltip={__(
'The balance displayed might not be up-to-date since the wallet is not yet fully synchronized'
)}
>
<Icon icon={warningIcon} className="space-right" />
</Tooltip.Trigger>
)}{' '}
<span className="v-align">
{__('Balance')} (
{settings.displayFiatBalance ? fiatCurrency : 'NXS'})
</span>
</StatLabel>
<StatValue>
{settings.overviewDisplay === 'balHidden' ? (
'-'
) : !settings.displayFiatBalance ? (
this.waitForCore(formatNumber(balance + unconfirmedbalance))
) : market && market.price ? (
this.waitForCore(
formatCurrency(
(balance + unconfirmedbalance) * market.price,
fiatCurrency
)
)
) : (
<span className="dim">-</span>
)}
</StatValue>
</div>
<StatIcon
icon={
settings.displayFiatBalance
? currencyIcons(fiatCurrency)
: logoIcon
}
/>
</Stat>
<Stat
as={coreConnected ? Link : undefined}
to={coreConnected ? '/Transactions' : undefined}
>
<div>
<StatLabel>
<Tooltip.Trigger
tooltip={__(
'Staking and mining rewards that need to get past 120 block-old to become available'
)}
align="start"
>
<Icon icon={questionMarkCircleIcon} />
</Tooltip.Trigger>{' '}
<span className="v-align">{__('Immature Balance')} (NXS)</span>
</StatLabel>
<StatValue>
{settings.overviewDisplay === 'balHidden'
? '-'
: this.waitForCore(formatNumber(stake + newmint))}
</StatValue>
</div>
<StatIcon icon={nxsStakeIcon} />
</Stat>
<Stat
as={coreConnected ? Link : undefined}
to={coreConnected ? '/Transactions' : undefined}
>
<div>
<StatLabel>{__('Transactions')}</StatLabel>
<StatValue>{this.waitForCore(txtotal)}</StatValue>
</div>
<StatIcon icon={transactionIcon} />
</Stat>
<Stat>
<div>
<StatLabel>
{__('Market Price')} ({fiatCurrency})
</StatLabel>
<StatValue>
{market && market.price ? (
<>
{fiatCurrency === 'BTC'
? formatCurrency(market.price, fiatCurrency, 8)
: fiatCurrency !== 'BTC'
? formatCurrency(market.price, fiatCurrency, 2)
: ''}
</>
) : (
<span className="dim">-</span>
)}
</StatValue>
</div>
<StatIcon icon={chartIcon} />
</Stat>
<Stat>
<div>
<StatLabel>
{__('Market Cap')} ({fiatCurrency})
</StatLabel>
<StatValue>
{market && market.displayMarketCap ? (
market.displayMarketCap
) : (
<span className="dim">-</span>
)}
</StatValue>
</div>
<StatIcon icon={supplyIcon} />
</Stat>
<Stat>
<div>
<StatLabel>
{__('24hr Change')} ({fiatCurrency} %)
</StatLabel>
<StatValue>
{market && typeof market.changePct24Hr === 'number' ? (
<>
{market.changePct24Hr > 0 && '+'}
{formatNumber(market.changePct24Hr, 2)}%
</>
) : (
<span className="dim">-</span>
)}
</StatValue>
</div>
<StatIcon icon={hours24Icon} />
</Stat>
</Stats>
<Stats right compact={!this.showingGlobe()}>
<Stat>
<StatIcon icon={this.connectionsIcon()} />
<div>
<StatLabel>{__('Connections')}</StatLabel>
<StatValue>{this.waitForCore(connections)}</StatValue>
</div>
</Stat>
<Tooltip.Trigger
position="left"
tooltip={!!blockDate && <BlockCountTooltip blockDate={blockDate} />}
>
<Stat className="relative">
<StatIcon icon={nxsblocksIcon} />
<div>
<StatLabel>{__('Block Count')}</StatLabel>
<StatValue>
{this.waitForCore(this.numberWithCommas(blocks))}
</StatValue>
</div>
</Stat>
</Tooltip.Trigger>
<Stat>
<StatIcon icon={interestIcon} />
<div>
<StatLabel>{__('Stake Rate')}</StatLabel>
<StatValue>
{this.waitForCore(
interestweight || stakerate
? formatNumber(interestweight || stakerate, 2) + '%'
: 'N/A'
)}
</StatValue>
</div>
</Stat>
{settings.overviewDisplay === 'miner'
? this.returnDifficultyStats(difficulty)
: this.returnWeightStats()}
</Stats>
</OverviewPage>
);
}
}
// Mandatory React-Redux method
export default connect(mapStateToProps)(Overview);
|
ujoychou/eco
|
net/protocol/Crypt.h
|
<gh_stars>1-10
#ifndef ECO_NET_CRYPT_H
#define ECO_NET_CRYPT_H
/*******************************************************************************
@ name
ByteCodeProtocol
@ function
protocol stack structure like this:
1.head: bytes length: uint16_t
2.original message length: uint16_t
3.encode message.
--------------------------------------------------------------------------------
@ history ver 1.0 @
@ records: ujoy modifyed on 2013-01-01.
1.create and init this class.
--------------------------------------------------------------------------------
* copyright(c) 2013 - 2015, ujoy, reserved all right.
*******************************************************************************/
#include <eco/ExportApi.h>
#include <eco/Type.h>
#include <eco/codec/ZlibFlate.h>
#include <string>
namespace eco{;
namespace net{;
////////////////////////////////////////////////////////////////////////////////
class Crypt
{
public:
/*@ message bytes size after encode.*/
virtual uint32_t byte_size(IN uint32_t size)
{
return size;
}
/*@ replace with encoded string.
* @ return: encoded string.
* @ para.origin_str: input original string data.
* @ para.start_pos: where encoded string start.
*/
virtual eco::String append_encode(
IN eco::String& origin_str,
IN uint32_t start_pos)
{
return std::move(origin_str);
}
/*@ decode string.
* @ return: return decoded original string.
* @ para.encode_str: input encoded string.
* @ para.start_pos: where encoded string start.
* @ para.encode_size: encoded string size.
*/
virtual eco::String decode(
IN eco::String& encode_str,
IN const uint32_t start_pos,
IN const uint32_t encode_size)
{
return std::move(encode_str);
}
public:
/*@ encode string.
* @ return: encoded string.
* @ para.origin_str: input original string data.
*/
inline eco::String encode(
IN eco::String& origin_str)
{
return encode(origin_str, 0);
}
// same with "append_encode".
inline eco::String encode(
IN eco::String& origin_str,
IN uint32_t start_pos)
{
return append_encode(origin_str, start_pos);
}
/*@ decode string.
* @ return: decoded original string.
* @ para.encode_str: input encoded string.
* @ para.start_pos: where encoded string start.
*/
inline eco::String decode(
IN eco::String& encode_str,
IN const uint32_t start_pos)
{
return decode(encode_str, start_pos, encode_str.size() - start_pos);
}
};
////////////////////////////////////////////////////////////////////////////////
template<typename Coder>
class CryptT : public Crypt
{
public:
/*@ message bytes size after encode.*/
virtual uint32_t get_byte_size(IN uint32_t size)
{
return size + ((size < 80) ? 20 : 0);
}
/*@ replace with encoded string.
* @ return: encoded string.
* @ para.origin_str: input original string data.
* @ para.start_pos: where encoded string start.
*/
virtual eco::String append_encode(
IN eco::String& origin_str,
IN uint32_t start_pos)
{
uint32_t origin_size =
static_cast<uint32_t>(origin_str.size() - start_pos);
uint16_t encode_size = Coder::get_byte_size(origin_size);
// append "exist data".
eco::String encode_str;
encode_str.reserve(start_pos + sizeof(uint32_t) + encode_size);
encode_str.append(origin_str.c_str(), start_pos);
// append "original data length".
append_hton(encode_str, origin_size);
// append "encoded data".
if (!Coder::append_encode(
encode_str, &origin_str[start_pos], origin_size))
{
return eco::String();
}
return std::move(encode_str);
}
/*@ decode string.
* @ return: return decoded original string.
* @ para.encode_str: input encoded string.
* @ para.start_pos: where encoded string start.
* @ para.encode_size: encoded string size.
*/
virtual eco::String decode(
IN eco::String& encode_str,
IN const uint32_t start_pos,
IN const uint32_t encode_size) override
{
const int sol = sizeof(uint32_t); // size of original data length.
if (encode_size <= sol) // original data length
{
ECO_THIS_ERROR(e_message_decode)
< "message has no 'original data length'";
return eco::String();
}
// decode: original data size.
uint32_t origin_size = ntoh32(&encode_str[start_pos]);
uint32_t encode_data_size = encode_size - sol;
if (origin_size < 1 || encode_data_size < 1)
{
ECO_THIS_ERROR(e_message_decode)
< "message original data length or encoded data length = 0.";
return eco::String();
}
// decode: original data.
eco::String origin_str;
origin_str.reserve(start_pos + origin_size);
origin_str.append(&encode_str[0], start_pos);
if (!Coder::append_decode(origin_str,
&encode_str[start_pos + sol], encode_data_size, origin_size))
{
ECO_THIS_ERROR(e_message_decode) < "coder append decode error.";
return eco::String();
}
return std::move(origin_str);
}
};
typedef eco::net::CryptT<eco::codec::zlib::Flate> CryptFlate;
}}
////////////////////////////////////////////////////////////////////////////////
#endif
|
VishalMewadaPackt/Go-Building-Web-Applications
|
Module 2/Chapter 7/meander/cost_level.go
|
<reponame>VishalMewadaPackt/Go-Building-Web-Applications
package meander
import (
"strings"
)
// Cost represents a cost level.
type Cost int8
// Cost enumerator represents various levels of Cost.
const (
_ Cost = iota
Cost1
Cost2
Cost3
Cost4
Cost5
)
var costStrings = map[string]Cost{
"$": Cost1,
"$$": Cost2,
"$$$": Cost3,
"$$$$": Cost4,
"$$$$$": Cost5,
}
func (l Cost) String() string {
for s, v := range costStrings {
if l == v {
return s
}
}
return "invalid"
}
// ParseCost parses the cost string into a Cost type.
func ParseCost(s string) Cost {
return costStrings[s]
}
// CostRange represents a range of Cost values.
type CostRange struct {
From Cost
To Cost
}
func (r CostRange) String() string {
return r.From.String() + "..." + r.To.String()
}
// ParseCostRange parses a cost range string into a CostRange.
func ParseCostRange(s string) *CostRange {
segs := strings.Split(s, "...")
return &CostRange{
From: ParseCost(segs[0]),
To: ParseCost(segs[1]),
}
}
|
brunolauze/openpegasus-providers-old
|
src/Providers/UNIXProviders/BGPAdminDistance/UNIX_BGPAdminDistanceDeps.h
|
<filename>src/Providers/UNIXProviders/BGPAdminDistance/UNIX_BGPAdminDistanceDeps.h
#if defined(PEGASUS_OS_HPUX)
# include "UNIX_BGPAdminDistanceDeps_HPUX.h"
#elif defined(PEGASUS_OS_LINUX)
# include "UNIX_BGPAdminDistanceDeps_LINUX.h"
#elif defined(PEGASUS_OS_DARWIN)
# include "UNIX_BGPAdminDistanceDeps_DARWIN.h"
#elif defined(PEGASUS_OS_AIX)
# include "UNIX_BGPAdminDistanceDeps_AIX.h"
#elif defined(PEGASUS_OS_FREEBSD)
# include "UNIX_BGPAdminDistanceDeps_FREEBSD.h"
#elif defined(PEGASUS_OS_SOLARIS)
# include "UNIX_BGPAdminDistanceDeps_SOLARIS.h"
#elif defined(PEGASUS_OS_ZOS)
# include "UNIX_BGPAdminDistanceDeps_ZOS.h"
#elif defined(PEGASUS_OS_VMS)
# include "UNIX_BGPAdminDistanceDeps_VMS.h"
#elif defined(PEGASUS_OS_TRU64)
# include "UNIX_BGPAdminDistanceDeps_TRU64.h"
#else
# include "UNIX_BGPAdminDistanceDeps_STUB.h"
#endif
|
Drakandes/Portfolio_NicolasPaulBonneau
|
Code en C++ de Mage War Online/Cactus.cpp
|
#include "stdafx.h"
#include "Cactus.h"
Cactus::Cactus()
{
if (!texture.loadFromFile("Cactus.png"))
{
std::cout << "Error while loading cactus texture" << std::endl;
}
if (!shadow_texture.loadFromFile("CactusShadow.png"))
{
std::cout << "Error while loading cactus shadow texture" << std::endl;
}
}
Cactus::~Cactus()
{
}
void Cactus::Init(sf::Vector2f position, sf::RenderWindow &window)
{
health = health_max;
type_cactus = GlobalFunction::getRandomRange(1, number_different_trees) - 1;
sprite_position = position;
sprite.setPosition(sprite_position);
sprite.setTexture(texture);
sprite.setOrigin(sprite_size_cutting.x / 2, sprite_size_cutting.y);
sprite.setTextureRect(sf::IntRect(type_cactus * sprite_size_cutting.x,0, sprite_size_cutting.x, sprite_size_cutting.y));
sprite_position_collision = sprite_position - sf::Vector2f(0, sprite_size_collision.y / 2);
rectangle_collision = GlobalFunction::CreateRectangle(sprite_size_collision, sprite_position_collision);
rectangle_collision.setOrigin(sprite_size_collision.x / 2, sprite_size_collision.y / 2);
rectangle_collision.setFillColor(sf::Color::Blue);
//window.draw(sprite);
shadow = GlobalFunction::CreateSprite(sprite.getPosition() + sf::Vector2f(0, sprite_size_cutting.y / 2 - 10), sf::Vector2f(sprite_size_cutting.x, sprite_size_cutting.y), shadow_texture);
shadow.setOrigin(sf::Vector2f(sprite_size_cutting.x / 2, sprite_size_cutting.y / 2));
shadow.setTextureRect(sf::IntRect(type_cactus * sprite_size_cutting.x, 0, sprite_size_cutting.x, sprite_size_cutting.y));
}
bool Cactus::CheckCollision(sf::FloatRect rect_collision, int id_object, sf::Vector2f position_object)
{
if (health > 0)
{
if (sprite.getGlobalBounds().intersects(rect_collision))
{
if (id_object == 1)
{
clock_health.restart();
health--;
}
return true;
}
}
return false;
}
void Cactus::HealthGestion()
{
if (clock_health.getElapsedTime().asSeconds() >= 30)
{
if (health < health_max)
{
health++;
sprite.setTextureRect(sf::IntRect(type_cactus * sprite_size_cutting.x, tile_cactus_height*(health_max - health), sprite_size_cutting.x, sprite_size_cutting.y));
shadow.setTextureRect(sf::IntRect(type_cactus * sprite_size_cutting.x, tile_cactus_height*(health_max - health), sprite_size_cutting.x, sprite_size_cutting.y));
}
if (health == health_max)
{
can_produce_material = true;
}
clock_health.restart();
}
}
sf::Vector2f Cactus::GetCurrentPosition()
{
return rectangle_collision.getPosition();
}
void Cactus::Draw(sf::RenderWindow &window)
{
//HealthGestion();
drawn = false;
if (health > 0)
{
window.draw(sprite);
//window.draw(rectangle_collision);
}
}
void Cactus::DrawShadow(sf::RenderWindow &window)
{
if (health > 0)
{
window.draw(shadow);
}
}
sf::Vector2f Cactus::GetCurrentPositionShadow()
{
return shadow.getPosition() + sf::Vector2f(0, 0);
}
bool Cactus::CanPush() { return true; }
float Cactus::GetDistancePushing() { return 3; }
float Cactus::GetDamage()
{
return 5;
}
void Cactus::DealWithCollision(std::shared_ptr<CollisionalObject> object_collided)
{
if (!CheckIfProjectileDisable())
{
int type_object = object_collided->GetTypeCollisionalObject();
sf::Vector2f position_self = GetCurrentPosition();
sf::Vector2f position_objet = object_collided->GetCurrentPosition();
sf::Vector2f size_object = object_collided->GetSize();
if (type_object == Player_E)
{
float damage_dealt = object_collided->GotDamaged(GetDamage(),-1,0);
float angle = GlobalFunction::GetRotationBetweenTwoPositions(position_self, position_objet);
float distance_added = 1;
if (angle < 315 && angle > 225)
{
sf::Vector2f new_position{ position_objet.x,position_self.y + sprite_size_collision.y / 2 + size_object.y / 2 + distance_added };
object_collided->TeleportEntity(new_position, NatureObject_E);
}
if (angle < 135 && angle > 45)
{
sf::Vector2f new_position{ position_objet.x,position_self.y - sprite_size_collision.y / 2 - size_object.y / 2 - distance_added };
object_collided->TeleportEntity(new_position, NatureObject_E);
}
if ((angle < 45 && angle > 0) || (angle > 315 && angle < 360))
{
sf::Vector2f new_position{ position_self.x - sprite_size_collision.x / 2 - size_object.x / 2 - distance_added, position_objet.y };
object_collided->TeleportEntity(new_position, NatureObject_E);
}
if (angle < 225 && angle > 135)
{
sf::Vector2f new_position{ position_self.x + sprite_size_collision.x / 2 + size_object.x / 2 + distance_added, position_objet.y };
object_collided->TeleportEntity(new_position, NatureObject_E);
}
object_collided->ChangeStunTime(0.13);
}
if (type_object == Monster_E)
{
if (CanPush())
{
object_collided->GetPushedAway(GetDistancePushing(), StrongPush, position_objet, position_self);
}
}
if (type_object == Projectile_E)
{
clock_health.restart();
health--;
if (health == 0)
{
if (GlobalFunction::getRandomRange(1, 1000) <= 500)
{
can_produce_material = false;
std::shared_ptr<M_MagicSand> material_created = std::shared_ptr<M_MagicSand>(new M_MagicSand);
material_created->Init(GetCurrentPosition(), ListObjectsSingleton::instance()->GetNewID());
ProjectileGestion::instance()->AddObjectToList(material_created);
MainQuadtree::instance()->insert(GetCurrentPosition(), material_created->GetSize(), material_created);
material_created.reset();
}
is_to_delete = true;
}
sprite.setTextureRect(sf::IntRect(type_cactus * sprite_size_cutting.x, tile_cactus_height*(health_max - health), sprite_size_cutting.x, sprite_size_cutting.y));
shadow.setTextureRect(sf::IntRect(type_cactus * sprite_size_cutting.x, tile_cactus_height*(health_max - health), sprite_size_cutting.x, sprite_size_cutting.y));
}
}
}
sf::Vector2f Cactus::GetSize()
{
return sf::Vector2f(sprite_size_cutting);
}
|
t3ctechnologies/Anchel_Core
|
src/main/java/com/t3c/anchel/core/repository/hibernate/DomainAccessRuleRepositoryImpl.java
|
/*
* LinShare is an open source filesharing software, part of the LinPKI software
* suite, developed by Linagora.
*
* Copyright (C) 2015-2016 LINAGORA
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version, provided you comply with the Additional Terms applicable for
* LinShare software by Linagora pursuant to Section 7 of the GNU Affero General
* Public License, subsections (b), (c), and (e), pursuant to which you must
* notably (i) retain the display of the “LinShare™” trademark/logo at the top
* of the interface window, the display of the “You are using the Open Source
* and free version of LinShare™, powered by Linagora © 2009–2016. Contribute to
* Linshare R&D by subscribing to an Enterprise offer!” infobox and in the
* e-mails sent with the Program, (ii) retain all hypertext links between
* LinShare and t3c.io, between linagora.com and Linagora, and (iii)
* refrain from infringing Linagora intellectual property rights over its
* trademarks and commercial brands. Other Additional Terms apply, see
* <http://www.linagora.com/licenses/> for more details.
*
* 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License and
* its applicable Additional Terms for LinShare along with this program. If not,
* see <http://www.gnu.org/licenses/> for the GNU Affero General Public License
* version 3 and <http://www.linagora.com/licenses/> for the Additional Terms
* applicable to LinShare software.
*/
package com.t3c.anchel.core.repository.hibernate;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.t3c.anchel.core.domain.entities.AbstractDomain;
import com.t3c.anchel.core.domain.entities.DomainAccessRule;
import com.t3c.anchel.core.repository.DomainAccessRuleRepository;
public class DomainAccessRuleRepositoryImpl extends AbstractRepositoryImpl<DomainAccessRule> implements DomainAccessRuleRepository {
public DomainAccessRuleRepositoryImpl(HibernateTemplate hibernateTemplate) {
super(hibernateTemplate);
}
@Override
public DomainAccessRule findById(long id) {
List<DomainAccessRule> domainAccessRule = findByCriteria(Restrictions.eq("id", id));
if (domainAccessRule == null || domainAccessRule.isEmpty()) {
return null;
} else if (domainAccessRule.size() == 1) {
return domainAccessRule.get(0);
} else {
throw new IllegalStateException("Id must be unique");
}
}
@Override
protected DetachedCriteria getNaturalKeyCriteria(DomainAccessRule entity) {
DetachedCriteria det = DetachedCriteria.forClass(DomainAccessRule.class);
det.add( Restrictions.eq("id", entity.getPersistenceId()));
return det;
}
@Override
public List<DomainAccessRule> findByDomain(AbstractDomain domain) {
return findByCriteria(Restrictions.eq("domain", domain));
}
@Override
public long countNumberAccessRulesByDomain(AbstractDomain domain) {
DetachedCriteria det = DetachedCriteria
.forClass(DomainAccessRule.class);
det.setProjection(Projections.rowCount());
det.add(Restrictions.eq("domain", domain));
return DataAccessUtils.longResult(findByCriteria(det));
}
}
|
hisarbalik/console
|
components/react/src/components/BackendModuleDisabled/styled.js
|
import styled from "styled-components";
export const Wrapper = styled.div`
width: 100%;
text-align: center;
font-size: 20px;
padding: 30px;
`;
|
pcbeard/hkxpack
|
core/src/main/java/com/dexesttp/hkxpack/data/HKXFile.java
|
package com.dexesttp.hkxpack.data;
import java.util.ArrayList;
import java.util.Collection;
/**
* A HKXFile contains all data carried by a HKX File in the form of a list of {@link HKXObject}, in a DOM format.
* <p>
* Main methods :
* {@link #getClassVersion()} / {@link #getContentsVersion()} retrieves the version of the file, used as a description parameter for the contents.
* {@link #add(HKXObject)} / {@link #addAll(HKXObject...)} adds a single or a collection of {@link HKXObject} to the file.
* {@link #getContentCollection()} retrieves all linked {@link HKXObject}.
*/
public class HKXFile {
private final transient String contentsversion;
private final transient int classversion;
private final transient Collection<HKXObject> content;
/**
* Creates a new {@link HKXFile}.
* @param contentsversion the contents version of this {@link HKXFile}.
* @param classversion the class version of this {@link HKXFile}.
*/
// TODO add ways to select between content/class version with a specific class.
public HKXFile(final String contentsversion, final int classversion) {
content = new ArrayList<>();
this.contentsversion = contentsversion;
this.classversion = classversion;
}
/**
* Get this {@link HKXFile}'s contents version.
* @return the contents version, as a {@link String}.
*/
public String getContentsVersion() {
return contentsversion;
}
/**
* Get this {@link HKXFile}'s class version.
* @return the class version, as {@link int}.
*/
public int getClassVersion() {
return classversion;
}
/**
* Retrieves all base {@link HKXObject}
* @return
*/
public Collection<HKXObject> getContentCollection() {
return content;
}
/**
* Add a {@link HKXObject} as a base element of the file.
* @param object the {@link HKXObject} to add to the {@link HKXFile}.
*/
public void add(final HKXObject object) {
content.add(object);
}
/**
* Add a collection of {@link HKXObject} as a base element of the file.
* @param hkxObjects the collection of {@link HKXObject} to add.
*/
public void addAll(final HKXObject... hkxObjects) {
for(final HKXObject object : hkxObjects) {
this.add(object);
}
}
}
|
syb0rg/tritium
|
include/cst_cg.h
|
#ifndef _CST_CG_H__
#define _CST_CG_H__
#include "cst_cart.h"
#include "cst_track.h"
#include "cst_wave.h"
#include "cst_audio.h"
#include "cst_synth.h" /* for dur_stat */
typedef struct cst_cg_db_struct {
const char *name;
const char * const *types;
int num_types;
const int sample_rate;
float f0_mean, f0_stddev;
/* Cluster trees */
const cst_cart * const *f0_trees;
const cst_cart * const *param_trees0; /* single or static */
const cst_cart * const *param_trees1; /* deltas */
const cst_cart * const *param_trees2; /* me str */
/* Model params e.g. mceps, deltas intersliced with stddevs */
const int num_channels0;
const int num_frames0;
const unsigned short * const * model_vectors0;
const int num_channels1;
const int num_frames1;
const unsigned short * const * model_vectors1;
const int num_channels2;
const int num_frames2;
const unsigned short * const * model_vectors2;
/* Currently shared between different models */
const float *model_min; /* for vector coeffs encoding */
const float *model_range; /* for vector coeffs encoding */
const float frame_advance;
/* duration model (cart + phonedurs) */
const dur_stat * const *dur_stats;
const cst_cart *dur_cart;
/* phone to states map */
const char * const * const *phone_states;
/* Other parameters */
const int do_mlpg; /* implies deltas are in the model_vectors */
const float *dynwin;
const int dynwinsize;
const float mlsa_alpha;
const float mlsa_beta;
const int multimodel;
const int mixed_excitation;
/* filters for Mixed Excitation */
const int ME_num;
const int ME_order;
const double * const *me_h;
const float gain;
} cst_cg_db;
/* Access model parameters, unpacking them as required */
#define CG_MODEL_VECTOR(M,N,X,Y) \
(M->model_min[Y]+((float)(M->N[X][Y])/65535.0*M->model_range[Y]))
CST_VAL_USER_TYPE_DCLS(cg_db,cst_cg_db)
cst_utterance *cg_synth(cst_utterance *utt);
cst_wave *mlsa_resynthesis(const cst_track *t,
const cst_track *str,
cst_cg_db *cg_db,
cst_audio_streaming_info *asc);
cst_track *mlpg(const cst_track *param_track, cst_cg_db *cg_db);
#endif
|
hefen1/chromium
|
storage/browser/fileapi/file_system_file_stream_reader.h
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_
#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_
#include "base/bind.h"
#include "base/files/file.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "storage/browser/blob/file_stream_reader.h"
#include "storage/browser/blob/shareable_file_reference.h"
#include "storage/browser/fileapi/file_system_url.h"
#include "storage/browser/storage_browser_export.h"
namespace base {
class FilePath;
class SequencedTaskRunner;
}
namespace content {
class FileSystemFileStreamReaderTest;
}
namespace storage {
class FileSystemContext;
// Generic FileStreamReader implementation for FileSystem files.
// Note: This generic implementation would work for any filesystems but
// remote filesystem should implement its own reader rather than relying
// on FileSystemOperation::GetSnapshotFile() which may force downloading
// the entire contents for remote files.
class STORAGE_EXPORT_PRIVATE FileSystemFileStreamReader
: public NON_EXPORTED_BASE(storage::FileStreamReader) {
public:
~FileSystemFileStreamReader() override;
// FileStreamReader overrides.
int Read(net::IOBuffer* buf,
int buf_len,
const net::CompletionCallback& callback) override;
int64 GetLength(const net::Int64CompletionCallback& callback) override;
private:
friend class storage::FileStreamReader;
friend class content::FileSystemFileStreamReaderTest;
FileSystemFileStreamReader(FileSystemContext* file_system_context,
const FileSystemURL& url,
int64 initial_offset,
const base::Time& expected_modification_time);
int CreateSnapshot(const base::Closure& callback,
const net::CompletionCallback& error_callback);
void DidCreateSnapshot(
const base::Closure& callback,
const net::CompletionCallback& error_callback,
base::File::Error file_error,
const base::File::Info& file_info,
const base::FilePath& platform_path,
const scoped_refptr<storage::ShareableFileReference>& file_ref);
scoped_refptr<FileSystemContext> file_system_context_;
FileSystemURL url_;
const int64 initial_offset_;
const base::Time expected_modification_time_;
scoped_ptr<storage::FileStreamReader> local_file_reader_;
scoped_refptr<storage::ShareableFileReference> snapshot_ref_;
bool has_pending_create_snapshot_;
base::WeakPtrFactory<FileSystemFileStreamReader> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FileSystemFileStreamReader);
};
} // namespace storage
#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_FILE_STREAM_READER_H_
|
znarthur/basic-live
|
basiclive/core/publications/models.py
|
<filename>basiclive/core/publications/models.py<gh_stars>0
from django.db import models
from django.utils.translation import ugettext as _
from model_utils.models import TimeStampedModel
from model_utils import Choices
from basiclive.utils import fields
from basiclive.utils import temporal
class SubjectArea(TimeStampedModel):
name = models.CharField(max_length=255, unique=True)
description = models.TextField(blank=True, null=True)
code = models.CharField(_('ASJC Code'), max_length=10)
parent = models.ForeignKey("SubjectArea", blank=True, null=True, related_name="children", on_delete=models.SET_NULL)
def __str__(self):
return self.name
class TagManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class Tag(TimeStampedModel):
name = models.CharField(max_length=255, unique=True)
description = models.TextField(blank=True)
objects = TagManager()
def __str__(self):
return self.name
def natural_key(self):
return self.name,
class Journal(TimeStampedModel):
title = models.TextField()
short_name = models.TextField(blank=True, null=True)
codes = fields.StringListField("ISSN", unique=True)
publisher = models.TextField(blank=True, null=True)
topics = models.ManyToManyField(SubjectArea, related_name='journals', blank=True)
metrics = models.ForeignKey('JournalProfile', null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.title
class JournalProfile(temporal.TemporalProfile):
owner = models.ForeignKey(Journal, on_delete=models.CASCADE, related_name='profiles')
sjr_rank = models.FloatField("SJR-Rank", default=0.0, null=True)
sjr_quartile = models.SmallIntegerField("SJR-Quartile", default=4, null=True)
impact_factor = models.FloatField("Impact Factor", default=0.0, null=True)
h_index = models.IntegerField("H-Index", default=1.0, null=True)
def __str__(self):
return "{} > {}".format(self.owner, self.effective.isoformat())
class Funder(TimeStampedModel):
name = models.TextField(unique=True)
code = models.CharField(max_length=50, null=True, blank=True)
def __str__(self):
return self.name
class Publication(TimeStampedModel):
TYPES = Choices(
('article', _('Peer-Reviewed Article')),
('proceeding', _('Conference Proceeding')),
('phd_thesis', _('Doctoral Thesis')),
('msc_thesis', _('Masters Thesis')),
('magazine', _('Magazine Article')),
('book', _('Book')),
('chapter', _('Book / Chapter')),
('patent', _('Patent')))
published = models.DateField(_('Published'))
authors = models.TextField()
#projects = models.ManyToManyField(Project, related_name="publications", blank=True)
code = models.CharField(max_length=255, null=True, unique=True)
keywords = fields.StringListField(blank=True)
abstract = models.TextField(null=True, blank=True)
kind = models.CharField(_('Type'), choices=TYPES, default=TYPES.article, max_length=20)
active = models.BooleanField(default=False)
comments = models.TextField(blank=True, null=True)
funders = models.ManyToManyField(Funder, related_name="publications", blank=True)
tags = models.ManyToManyField(Tag, related_name='publications', verbose_name='Tags', blank=True)
topics = models.ManyToManyField(SubjectArea, related_name="publications", verbose_name="Subject Areas", blank=True)
main_title = models.TextField(blank=True, null=True)
title = models.TextField()
editor = models.TextField(blank=True, null=True)
publisher = models.CharField(max_length=100, blank=True, null=True)
journal = models.ForeignKey(Journal, related_name='articles', on_delete=models.CASCADE, null=True)
volume = models.CharField(max_length=100, blank=True, null=True)
issue = models.CharField(max_length=20, blank=True, null=True)
pages = models.CharField(max_length=20, blank=True, null=True)
metrics = models.ForeignKey("Metric", null=True, on_delete=models.SET_NULL, related_name='publication')
def __str__(self):
return self.code
def cite(self):
return f"{self.authors} ({self.published.year}) {self.title}. {self.journal and self.journal.short_name or ''}. {self.code}"
class Metric(temporal.TemporalProfile):
owner = models.ForeignKey(Publication, null=True, on_delete=models.CASCADE, related_name='all_metrics')
citations = models.IntegerField(default=0)
mentions = models.IntegerField(default=0)
def __str__(self):
return '{}'.format(self.citations)
class Deposition(TimeStampedModel):
code = models.CharField(max_length=20, unique=True)
title = models.TextField()
authors = models.TextField()
#projects = models.ManyToManyField(Project, related_name="publications", blank=True)
doi = models.CharField(max_length=255, unique=True)
resolution = models.FloatField(default=0.0)
released = models.DateField()
deposited = models.DateField()
collected = models.DateField(null=True)
tags = models.ManyToManyField(Tag, related_name='depositions', verbose_name='Tags')
reference = models.ForeignKey(Publication, related_name='depositions', null=True, on_delete=models.SET_NULL)
citation = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.code
|
tanwang11/TWMedia
|
Example/Pods/TWFoundation/TWFoundation/Classes/Prefix/Font+twPrefix.h
|
<filename>Example/Pods/TWFoundation/TWFoundation/Classes/Prefix/Font+twPrefix.h<gh_stars>1-10
//
// Font+twPrefix.h
// TWTool_Example
//
// Created by TW on 2021/3/8.
// Copyright © 2021 tanwang11. All rights reserved.
//
#import <UIKit/UIKit.h>
#ifndef Font_twPrefix_h
#define Font_twPrefix_h
#define PFONT10 [UIFont systemFontOfSize:10]
#define PFONT11 [UIFont systemFontOfSize:11]
#define PFONT12 [UIFont systemFontOfSize:12]
#define PFONT13 [UIFont systemFontOfSize:13]
#define PFONT14 [UIFont systemFontOfSize:14]
#define PFONT15 [UIFont systemFontOfSize:15]
#define PFONT16 [UIFont systemFontOfSize:16]
#define PFONT18 [UIFont systemFontOfSize:18]
#define PFONT19 [UIFont systemFontOfSize:19]
#define PFONT20 [UIFont systemFontOfSize:20]
#endif /* Font_twPrefix_h */
|
acidburn0zzz/webpack
|
test/configCases/issues/issue-14974/test.filter.js
|
module.exports = function () {
return process.version.slice(0, 4) !== "v10."
};
|
ember-animation/liquid-fire
|
tests/dummy/app/controllers/scenarios/stef.js
|
import Controller from '@ember/controller';
export default Controller.extend({
isExpanded: true,
actions: {
toggle: function () {
this.toggleProperty('isExpanded');
},
},
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.