code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int combos[100][10];
int count;
long long int nCr(int n, int r){
int i;
long long int result = 1;
if(r > n/2) r = n - r;
for(i = 1; i <= r; ++i){
result *= (n-i+1);
result /= i;
}
return result;
}
int transformToDominant(int m, int r, double M[m][m], double N[m], int V[], int R[])
{
int i, j;
int n = m;
if (r == m)
{
double T[n][n+1];
double P[n];
for (i = 0; i < n; i++)
{
P[i] = N[R[i]];
for (j = 0; j < n; j++)
T[i][j] = M[R[i]][j];
}
for (i = 0; i < n; i++)
{
N[i] = P[i];
for (j = 0; j < n; j++)
M[i][j] = T[i][j];
}
return 1;
}
for (i = 0; i < n; i++)
{
if (V[i]) continue;
double sum = 0;
for (j = 0; j < n; j++)
sum += fabs(M[i][j]);
if (2 * fabs(M[i][r]) >= sum)
{
V[i] = 1;
R[r] = i;
if (transformToDominant(m, r + 1, M, N, V, R))
return 1;
V[i] = 0;
}
}
return 0;
}
int makeDominant(int m, double M[m][m], double N[m])
{
int i;
int visited[m];
for(i = 0; i < m; ++i) visited[i] = 0;
int rows[m];
return transformToDominant(m, 0, M, N, visited, rows);
}
double * gaussSeidel( int m, int n, double a[m][n], double b[m], double er, int itr){
int key, i, j;
double x0[n], sum;
double * x = (double *) malloc(n * sizeof(double));
double M[m][m];
double N[m];
for(i = 0; i < n; ++i){
x0[i] = 0;
x[i] = 0;
}
for(i = 0; i < m; ++i){
N[i] = b[i];
for(j = 0; j < m; ++j){
M[i][j] = a[i][combos[itr][j]];
}
}
makeDominant(m, M, N);
do{
key = 0;
for(i = 0; i < m; ++i){
sum = N[i];
for(j = 0; j < m; ++j)
if(j != i)
sum -= M[i][j] * x0[combos[itr][j]];
x[combos[itr][i]] = sum / M[i][i];
if(fabs((x[combos[itr][i]] - x0[combos[itr][i]]) / x[combos[itr][i]]) > er){
key = 1;
x0[combos[itr][i]] = x[combos[itr][i]];
}
}
}while(key == 1);
return x;
}
void concatCombination(int arr[], int data[], int start, int end,
int index, int r)
{
int i, j;
if (index == r){
for(j = 0; j < r; ++j){
combos[count][j] = data[j];
}
++count;
return;
}
for (i = start; i <= end && end-i+1 >= r-index; ++i)
{
data[index] = arr[i];
concatCombination(arr, data, i+1, end, index+1, r);
}
}
void getCombination(int arr[], int n, int r)
{
int data[r];
concatCombination(arr, data, 0, n-1, 0, r);
}
int main(){
int i, j, n, m;
double er;
printf("Enter the dimension of the matrix (m x n):\n");
scanf("%d%d", &m, &n);
long long int solCount = nCr(n, m);
printf("Enter the stopping Criteria (er) :\n");
scanf("%lf", &er);
printf("Enter the matrix : \n");
double a[m][n];
for(i = 0; i < m; ++i)
for(j = 0; j < n; ++j)
scanf("%lf", &a[i][j]);
printf("Enter the values of B : \n");
double b[m];
for(i = 0; i < m; ++i)
scanf("%lf", &b[i]);
count = 0;
int indices[n];
for(i = 0; i < n; ++i) indices[i] = i;
getCombination(indices, n, m);
if(count != solCount) printf("Error : All combinations not found!\n");
double * x[solCount];
printf("Solutions:\n\n");
for(j = 0; j < solCount; ++j){
printf("Solution %d:\n", j+1);
x[j] = gaussSeidel(m, n, a, b, er, j);
for(i = 0; i < n; ++i)
printf("x_%d = %lf\t", i+1, x[j][i]);
printf("\n\n");
}
printf("Total number of basic soultions = %d\n\n", count);
return 0;
}
| ArnabBir/Operation_Research_Lab | Assignment_1/GS_BFS_2.c | C | gpl-3.0 | 3,977 |
# Define some colors
GREEN=\e[1;32m
NC=\e[0m
# Tool chain setup
TOOLCHAIN = arm-none-eabi-
CC = $(TOOLCHAIN)gcc
# Directory macro
SRC = src
OBJ = obj
BIN = bin
# Architecture specific macro
CPU = arm1176jzf-s
CARGS = -mcpu=$(CPU) -fpic -ffreestanding -std=gnu99 -O2 -Wall -Wextra
SRC_FILES := $(wildcard $(SRC)/*.c)
OBJ_FILES := $(addprefix $(OBJ)/,$(notdir $(SRC_FILES:.c=.o)))
all: $(OBJ_FILES)
@echo "Building all target " $(SRC_FILES)
$(CC) $(CARGS) -c $(SRC)/startup.s -o $(OBJ)/startup.o
@echo "Linking final ELF file"
mkdir -p $(BIN)
$(CC) $(CARGS) -T $(SRC)/linker.ld -nostdlib $^ $(OBJ)/startup.o -o $(BIN)/kernel.elf
@echo -e "${GREEN}Build Success${NC}"
$(OBJ)/%.o: $(SRC)/%.c
mkdir -p $(OBJ)
$(CC) $(CARGS) -c -o $@ $<
$(OBJ) :
mkdir -p $@
run: all
qemu-system-arm -m 256 -M raspi2 -serial stdio -kernel bin/kernel.elf
clean :
$(RM) -r $(OBJ)/*
$(RM) -r $(BIN)/*
| dragon-ware/base | Makefile | Makefile | gpl-3.0 | 895 |
# This file is part of Korman.
#
# Korman 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 of the License, or
# (at your option) any later version.
#
# Korman 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 Korman. If not, see <http://www.gnu.org/licenses/>.
import bpy
from bpy.props import *
from PyHSPlasma import *
from .base import PlasmaModifierProperties
from ..prop_world import game_versions
from ...exporter import ExportError
from ... import idprops
class PlasmaVersionedNodeTree(idprops.IDPropMixin, bpy.types.PropertyGroup):
name = StringProperty(name="Name")
version = EnumProperty(name="Version",
description="Plasma versions this node tree exports under",
items=game_versions,
options={"ENUM_FLAG"},
default=set(list(zip(*game_versions))[0]))
node_tree = PointerProperty(name="Node Tree",
description="Node Tree to export",
type=bpy.types.NodeTree)
node_name = StringProperty(name="Node Ref",
description="Attach a reference to this node")
@classmethod
def _idprop_mapping(cls):
return {"node_tree": "node_tree_name"}
def _idprop_sources(self):
return {"node_tree_name": bpy.data.node_groups}
class PlasmaAdvancedLogic(PlasmaModifierProperties):
pl_id = "advanced_logic"
bl_category = "Logic"
bl_label = "Advanced"
bl_description = "Plasma Logic Nodes"
bl_icon = "NODETREE"
logic_groups = CollectionProperty(type=PlasmaVersionedNodeTree)
active_group_index = IntProperty(options={"HIDDEN"})
def export(self, exporter, bo, so):
version = exporter.mgr.getVer()
for i in self.logic_groups:
our_versions = [globals()[j] for j in i.version]
if version in our_versions:
if i.node_tree is None:
raise ExportError("'{}': Advanced Logic is missing a node tree for '{}'".format(bo.name, i.version))
# If node_name is defined, then we're only adding a reference. We will make sure that
# the entire node tree is exported once before the post_export step, however.
if i.node_name:
exporter.want_node_trees[i.node_tree.name] = (bo, so)
node = i.node_tree.nodes.get(i.node_name, None)
if node is None:
raise ExportError("Node '{}' does not exist in '{}'".format(i.node_name, i.node_tree.name))
# We are going to assume get_key will do the adding correctly. Single modifiers
# should fetch the appropriate SceneObject before doing anything, so this will
# be a no-op in that case. Multi modifiers should accept any SceneObject, however
node.get_key(exporter, so)
else:
exporter.node_trees_exported.add(i.node_tree.name)
i.node_tree.export(exporter, bo, so)
def harvest_actors(self):
actors = set()
for i in self.logic_groups:
actors.update(i.node_tree.harvest_actors())
return actors
class PlasmaSpawnPoint(PlasmaModifierProperties):
pl_id = "spawnpoint"
bl_category = "Logic"
bl_label = "Spawn Point"
bl_description = "Point at which avatars link into the Age"
def export(self, exporter, bo, so):
# Not much to this modifier... It's basically a flag that tells the engine, "hey, this is a
# place the avatar can show up." Nice to have a simple one to get started with.
spawn = exporter.mgr.add_object(pl=plSpawnModifier, so=so, name=self.key_name)
@property
def requires_actor(self):
return True
class PlasmaMaintainersMarker(PlasmaModifierProperties):
pl_id = "maintainersmarker"
bl_category = "Logic"
bl_label = "Maintainer's Marker"
bl_description = "Designates an object as the D'ni coordinate origin point of the Age."
bl_icon = "OUTLINER_DATA_EMPTY"
calibration = EnumProperty(name="Calibration",
description="State of repair for the Marker",
items=[
("kBroken", "Broken",
"A marker which reports scrambled coordinates to the KI."),
("kRepaired", "Repaired",
"A marker which reports blank coordinates to the KI."),
("kCalibrated", "Calibrated",
"A marker which reports accurate coordinates to the KI.")
])
def export(self, exporter, bo, so):
maintmark = exporter.mgr.add_object(pl=plMaintainersMarkerModifier, so=so, name=self.key_name)
maintmark.calibration = getattr(plMaintainersMarkerModifier, self.calibration)
@property
def requires_actor(self):
return True
| dpogue/korman | korman/properties/modifiers/logic.py | Python | gpl-3.0 | 5,501 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("JaneCacheConverter")]
[assembly: AssemblyDescription("Jane画像キャッシュ変換ツール")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("omega ◆j4b42RTPJo")]
[assembly: AssemblyProduct("JaneCacheConverter")]
[assembly: AssemblyCopyright("Copyright © omega ◆j4b42RTPJo 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("358537cd-3d5d-476b-94a5-7c7ba9f3f276")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.1.0")]
[assembly: AssemblyFileVersion("2.0.1.0")]
| omega227/JaneCacheConverter | JaneCacheConverter/JaneCacheConverter/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,710 |
<?php get_header(); ?>
<section class="intro-header">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="intro-message">
<h1>Wyvern</h1>
<h3>Built on Codeigniter</h3>
<hr class="intro-divider">
<ul class="list-inline intro-social-buttons">
<li><a href="https://twitter.com/SBootstrap" class="btn btn-default btn-lg"><i class="fa fa-twitter fa-fw"></i> <span class="network-name">Twitter</span></a>
</li>
<li><a href="https://github.com/IronSummitMedia/startbootstrap" class="btn btn-default btn-lg"><i class="fa fa-github fa-fw"></i> <span class="network-name">Github</span></a>
</li>
<li><a href="#" class="btn btn-default btn-lg"><i class="fa fa-linkedin fa-fw"></i> <span class="network-name">Linkedin</span></a>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- /.container -->
</section>
<!-- /.intro-header -->
<section id="about" data-speed="2" data-type="background">
<div class="content-section-a">
<div class="container">
<div class="row">
<div class="col-lg-5 col-sm-6">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h2 class="section-heading">Death to the Stock Photo:
<br>Special Thanks</h2>
<p class="lead">A special thanks to Death to the Stock Photo for providing the photographs that you see in this template. <a target="_blank" href="http://join.deathtothestockphoto.com/">Visit their website</a> to become a member.</p>
</div>
<div class="col-lg-5 col-lg-offset-2 col-sm-6">
<img class="img-responsive" src="img/ipad.png" alt="">
</div>
</div>
</div>
<!-- /.container -->
</div>
</section>
<!-- /.content-section-a -->
<section id="services" data-speed="2" data-type="background">
<div class="content-section-b">
<div class="container">
<div class="row">
<div class="col-lg-5 col-lg-offset-1 col-sm-push-6 col-sm-6">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h2 class="section-heading">3D Device Mockups
<br>by PSDCovers</h2>
<p class="lead">Turn your 2D designs into high quality, 3D product shots in seconds using free Photoshop actions by PSDCovers! <a target="_blank" href="http://www.psdcovers.com/">Visit their website</a> to download some of their awesome, free photoshop actions!</p>
</div>
<div class="col-lg-5 col-sm-pull-6 col-sm-6">
<img class="img-responsive" src="img/doge.png" alt="">
</div>
</div>
</div>
<!-- /.container -->
</div>
</section>
<!-- /.content-section-b -->
<section id="contact" data-speed="2" data-type="background">
<div class="content-section-a">
<div class="container">
<div class="row">
<div class="col-lg-5 col-sm-6">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h2 class="section-heading">Google Web Fonts and
<br>Font Awesome Icons</h2>
<p class="lead">This template features the 'Lato' font, part of the <a target="_blank" href="http://www.google.com/fonts">Google Web Font library</a>, as well as <a target="_blank" href="http://fontawesome.io">icons from Font Awesome</a>.</p>
</div>
<div class="col-lg-5 col-lg-offset-2 col-sm-6">
<img class="img-responsive" src="img/phones.png" alt="">
</div>
</div>
</div>
<!-- /.container -->
</div>
</section>
<!-- /.content-section-a -->
<div class="banner">
<div class="container">
<div class="row">
<div class="col-lg-6">
<h2>Connect to Start Bootstrap:</h2>
</div>
<div class="col-lg-6">
<ul class="list-inline banner-social-buttons">
<li><a href="https://twitter.com/SBootstrap" class="btn btn-default btn-lg"><i class="fa fa-twitter fa-fw"></i> <span class="network-name">Twitter</span></a>
</li>
<li><a href="https://github.com/IronSummitMedia/startbootstrap" class="btn btn-default btn-lg"><i class="fa fa-github fa-fw"></i> <span class="network-name">Github</span></a>
</li>
<li><a href="#" class="btn btn-default btn-lg"><i class="fa fa-linkedin fa-fw"></i> <span class="network-name">Linkedin</span></a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.container -->
</div>
<!-- /.banner -->
<?php get_modal(); ?>
<?php get_footer(); ?> | The-Website-Nursery/wyvern | application/views/themes/wyvern/default.php | PHP | gpl-3.0 | 5,386 |
/*
This file is part of cpp-ethereum.
cpp-ethereum 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 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file blockqueue.cpp
* @author Dimitry Khokhlov <dimitry@ethdev.com>
* @date 2015
* BlockQueue test functions.
*/
#include <libethereum/BlockQueue.h>
#include <test/tools/libtesteth/TestHelper.h>
#include <test/tools/libtesteth/BlockChainHelper.h>
#include <test/tools/libtesteth/JsonSpiritHeaders.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace dev::test;
BOOST_FIXTURE_TEST_SUITE(BlockQueueSuite, MainNetworkNoProofTestFixture)
BOOST_AUTO_TEST_CASE(BlockQueueImport)
{
TestBlock genesisBlock = TestBlockChain::defaultGenesisBlock();
TestBlockChain blockchain(genesisBlock);
TestBlockChain blockchain2(genesisBlock);
TestBlock block1;
TestTransaction transaction1 = TestTransaction::defaultTransaction(1);
block1.addTransaction(transaction1);
block1.mine(blockchain);
BlockQueue blockQueue;
blockQueue.setChain(blockchain.getInterface());
ImportResult res = blockQueue.import(&block1.bytes());
BOOST_REQUIRE_MESSAGE(res == ImportResult::Success, "Simple block import to BlockQueue should have return Success");
res = blockQueue.import(&block1.bytes());
BOOST_REQUIRE_MESSAGE(res == ImportResult::AlreadyKnown, "Simple block import to BlockQueue should have return AlreadyKnown");
blockQueue.clear();
blockchain.addBlock(block1);
res = blockQueue.import(&block1.bytes());
BOOST_REQUIRE_MESSAGE(res == ImportResult::AlreadyInChain, "Simple block import to BlockQueue should have return AlreadyInChain");
TestBlock block2;
block2.mine(blockchain);
BlockHeader block2Header = block2.blockHeader();
block2Header.setTimestamp(block2Header.timestamp() + 100);
block2.setBlockHeader(block2Header);
block2.updateNonce(blockchain);
res = blockQueue.import(&block2.bytes());
BOOST_REQUIRE_MESSAGE(res == ImportResult::FutureTimeKnown, "Simple block import to BlockQueue should have return FutureTimeKnown");
TestBlock block3;
block3.mine(blockchain);
BlockHeader block3Header = block3.blockHeader();
block3Header.clear();
block3.setBlockHeader(block3Header);
res = blockQueue.import(&block3.bytes());
BOOST_REQUIRE_MESSAGE(res == ImportResult::Malformed, "Simple block import to BlockQueue should have return Malformed");
TestBlock block4;
block4.mine(blockchain2);
blockchain2.addBlock(block4);
TestBlock block5;
block5.mine(blockchain2);
BlockHeader block5Header = block5.blockHeader();
block5Header.setTimestamp(block5Header.timestamp() + 100);
block5.setBlockHeader(block5Header);
block5.updateNonce(blockchain2);
res = blockQueue.import(&block5.bytes());
BOOST_REQUIRE_MESSAGE(res == ImportResult::FutureTimeUnknown, "Simple block import to BlockQueue should have return FutureTimeUnknown");
blockQueue.clear();
TestBlock block3a;
block3a.mine(blockchain2);
blockchain2.addBlock(block3a);
TestBlock block3b;
block3b.mine(blockchain2);
BlockHeader block3bHeader = block3b.blockHeader();
block3bHeader.setTimestamp(block3bHeader.timestamp() - 40);
block3b.setBlockHeader(block3bHeader);
block3b.updateNonce(blockchain2);
res = blockQueue.import(&block3b.bytes());
BOOST_REQUIRE_MESSAGE(res == ImportResult::UnknownParent, "Simple block import to BlockQueue should have return UnknownParent");
}
BOOST_AUTO_TEST_SUITE_END()
| ethereum/cpp-ethereum | test/unittests/libethereum/BlockQueue.cpp | C++ | gpl-3.0 | 4,095 |
# SauerTracker Banners
## How does it work?
It creates an image based on a theme and some variables. Simple as that. These variables can be player, server, or clan stats. You can either use built-in themes or create custom ones.
## How to use it?
*http://banners.sauertracker.net/player?name=...&theme=...*
*http://banners.sauertracker.net/server?host=...&port=...&theme=...*
*http://banners.sauertracker.net/clan?host=...&port=...&theme=...*
## Default themes:
The following themes are built-in (more themes will be added later):
- default (player, server, and clan)



## How to write themes?
A theme is a Handlebars template, which generates an SVG document, which is rendered and served as a PNG. Simple, no?
You can find help on writing Handlebars templates [here](http://handlebarsjs.com), and help on SVG [here](https://developer.mozilla.org/en-US/docs/Web/SVG).
You can also get a headstart by reading the code of the built-in themes.
The following Handlebars block helpers are also available:
```
{{#ifeq a b}} a == b {{else}} a != b {{/ifeq}}
{{#iflt a b}} a < b {{else}} a >= b {{/ifeq}}
{{#ifgt a b}} a > b {{else}} a <= b {{/ifeq}}
{{#iflte a b}} a <= b {{else}} a > b {{/ifeq}}
{{#ifgte a b}} a >= b {{else}} a < b {{/ifeq}}
```
To use external images, you can simply put their URL in an `image` element. However it is recommended that you use the `cache` directive to make the banner load faster. For example:
```
<image xlink:href="{{cache "http://i.imgur.com/xxxxxxx.png"}}" .../>
```
will cache http://i.imgur.com/xxxxxxx.png locally and replace it with the URL to the cached one.
For country flag URLs (24x24 pixels) use the following directive:
```
{{flag countryCode}}
```
And for mapshot URLs (1024x1024 pixels):
```
{{mapshot mapName}}
```
You have access to the object returned from the SauerTracker API path corresponding to the type of the template. For example, in a server theme template you can use:
```
{{server.description}}
{{server.rank}}
...
```
And in a player theme template you can use:
```
{{player.name}}
{{player.totalGames}}
{{player.games.0.serverdesc}}
...
```
note however that the inner 'player' object is merged with the outer object (no need for `player.player.*`).
Same goes for a clan theme template:
```
{{clan.name}}
{{clan.games.0.timestamp}}
{{clan.members.0.name}}
...
```
Refer to https://sauertracker.net/api for more information on the *server*, *player*, and *clan* API paths.
See [built-in themes](https://github.com/AngrySnout/SauerTracker-banners/tree/master/themes) for some examples.
## Notes and bugs
* Be careful when using in-line HTML with the foreignObject element. The results in some browsers might be different from the server generated images. You must experiment.
* When writing a custom template, make sure you have all the fonts you used installed on your computer, or else preview will not work regardless of whether they are available on the server or not.
## License
GNU General Public License v3.0
| AngrySnout/SauerTracker-banners | README.md | Markdown | gpl-3.0 | 3,235 |
#ifndef PQ_QUIT_STATE_H
#define PQ_QUIT_STATE_H
/*
* Lets you set whether to want to quit.
*
* 1 means yes, 0 means no.
*/
void pq_quit_state_set(int state);
/*
* Whether you want to quit.
*
* 1 means yes, 0 means no.
*/
int pq_quit_state(void);
#endif /* PQ_QUIT_STATE_H */
| daniel-araujo/proctal | src/pq/quit-state.h | C | gpl-3.0 | 286 |
/*
Copyright (C) 2010 jungil Han <jungil.Han@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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/>.
*/
#include "FileReader.h"
#include "Source/Setting/INIManager.h"
#include "Source/Config.h"
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QTextCodec>
#include <QtCore/QDebug>
#if QT_VERSION >= 0x040700 && PERFORMANCE_CHECK
#include <QtCore/QElapsedTimer>
#endif
#define APPEND_LINE 700
FileReader::FileReader(QWidget* requester, const QString& codec, QObject* parent)
: QThread(parent)
, m_requester(requester)
, m_codec(codec)
, m_isRunning(true)
{
connect(this, SIGNAL(finished()), this, SLOT(finished()));
}
FileReader::~FileReader()
{
clearList();
}
void FileReader::clearList()
{
while (!m_byteArrayList.isEmpty())
delete m_byteArrayList.takeFirst();
}
void FileReader::start(const QString& fileName)
{
m_fileName = fileName;
clearList();
QThread::start();
}
void FileReader::suspend()
{
disconnect();
m_isRunning = false;
}
void FileReader::run()
{
QFile file(m_fileName);
if (!file.open(QIODevice::ReadOnly))
return;
emit fileSizeNotify(m_requester, file.size());
emit fileNameNotify(m_requester, m_fileName);
emit readStarted(m_requester);
int line = 0;
int index = 0;
int progressBytes = 0;
bool codecDetected = false;
m_byteArrayList.append(new QString);
#if QT_VERSION >= 0x040700 && PERFORMANCE_CHECK
QElapsedTimer timer;
timer.start();
#endif
QTextStream textStream(&file);
if (m_codec != QString("System")) {
textStream.setAutoDetectUnicode(false);
textStream.setCodec(m_codec.toLocal8Bit());
}
while (!textStream.atEnd()) {
QString lineText = textStream.readLine() + "\n";
m_byteArrayList.at(index)->append(lineText);
if (!codecDetected) {
emit codecDected(textStream.codec()->name());
codecDetected = true;
}
if (!(++line % APPEND_LINE)) {
progressBytes += m_byteArrayList.at(index)->size();
emit readProgress(m_requester, m_byteArrayList.at(index), progressBytes * 100 / file.size());
m_byteArrayList.append(new QString);
++index;
if (!m_isRunning)
break;
}
}
emit readFinished(m_requester, m_byteArrayList.at(index));
#if QT_VERSION >= 0x040700 && PERFORMANCE_CHECK
qDebug() << "Text Codec: " << textStream.codec()->name();
qDebug() << "[Performance Check] FileReader: " << timer.elapsed() << "ms " << "Bytes: " << progressBytes;
#endif
}
void FileReader::finished()
{
emit finished(m_requester);
}
| jungilhan/monkeylogviewer | Source/FileLoader/FileReader.cpp | C++ | gpl-3.0 | 3,295 |
/*
* This file is protected by Copyright. Please refer to the COPYRIGHT file
* distributed with this source distribution.
*
* This file is part of GNUHAWK.
*
* GNUHAWK is free software: you can redistribute it and/or modify is under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* GNUHAWK 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 STREAM_TO_STREAMS_BB_2O_IMPL_BASE_H
#define STREAM_TO_STREAMS_BB_2O_IMPL_BASE_H
#include <boost/thread.hpp>
#include <ossie/Resource_impl.h>
#include <bulkio/bulkio.h>
#include "struct_props.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include "stream_to_streams_bb_2o_GnuHawkBlock.h"
#include <sstream>
#define NOOP 0
#define FINISH -1
#define NORMAL 1
class stream_to_streams_bb_2o_base;
template < typename TargetClass >
class ProcessThread
{
public:
ProcessThread(TargetClass *_target, float _delay) :
target(_target)
{
_mythread = 0;
_thread_running = false;
_udelay = (__useconds_t)(_delay * 1000000);
};
// kick off the thread
void start() {
if (_mythread == 0) {
_thread_running = true;
_mythread = new boost::thread(&ProcessThread::run, this);
}
};
// manage calls to target's service function
void run() {
int state = NORMAL;
while (_thread_running and (state != FINISH)) {
state = target->serviceFunction();
if (state == NOOP) {
boost::this_thread::sleep( boost::posix_time::microseconds( _udelay ) );
} else {
boost::this_thread::yield();
}
}
};
// stop thread and wait for termination
bool release(unsigned long secs = 0, unsigned long usecs = 0) {
_thread_running = false;
if (_mythread) {
if ((secs == 0) and (usecs == 0)){
_mythread->join();
} else {
boost::system_time waitime= boost::get_system_time() + boost::posix_time::seconds(secs) + boost::posix_time::microseconds(usecs) ;
if (!_mythread->timed_join(waitime)) {
return 0;
}
}
delete _mythread;
_mythread = 0;
}
return 1;
};
virtual ~ProcessThread(){
if (_mythread != 0) {
release(0);
_mythread = 0;
}
};
void updateDelay(float _delay) { _udelay = (__useconds_t)(_delay * 1000000); };
void stop() {
_thread_running = false;
if ( _mythread ) _mythread->interrupt();
};
bool threadRunning() { return _thread_running; };
private:
boost::thread *_mythread;
bool _thread_running;
TargetClass *target;
__useconds_t _udelay;
boost::condition_variable _end_of_run;
boost::mutex _eor_mutex;
};
class stream_to_streams_bb_2o_base : public GnuHawkBlock
{
public:
stream_to_streams_bb_2o_base(const char *uuid, const char *label);
void start() throw (CF::Resource::StartError, CORBA::SystemException);
void stop() throw (CF::Resource::StopError, CORBA::SystemException);
CORBA::Object_ptr getPort(const char* _id) throw (CF::PortSupplier::UnknownPort, CORBA::SystemException);
void releaseObject() throw (CF::LifeCycle::ReleaseError, CORBA::SystemException);
void initialize() throw (CF::LifeCycle::InitializeError, CORBA::SystemException);
~stream_to_streams_bb_2o_base();
void loadProperties();
protected:
ProcessThread<stream_to_streams_bb_2o_base> *serviceThread;
boost::mutex serviceThreadLock;
// Member variables exposed as properties
CORBA::Long item_size;
CORBA::Long nstreams;
std::vector<stream_id_struct_struct> stream_id_map;
// Ports
bulkio::InOctetPort *byte_in;
bulkio::OutOctetPort *byte_out_0;
bulkio::OutOctetPort *byte_out_1;
std::vector< std::string > inputPortOrder;
std::vector< std::string > outputPortOrder;
private:
void construct();
protected:
static const int RealMode=0;
static const int ComplexMode=1;
std::vector<std::vector<int> > io_mapping;
typedef boost::posix_time::ptime TimeMark;
typedef boost::posix_time::time_duration TimeDuration;
typedef BULKIO::PrecisionUTCTime TimeStamp;
//
// Enable or disable to adjusting of timestamp based on output rate
//
inline void maintainTimeStamp( bool onoff=false ) {
_maintainTimeStamp = onoff;
};
//
// Enable or disable throttling of processing
//
inline void setThrottle( bool onoff=false ) {
_throttle = onoff;
};
//
// getTargetDuration
//
// Target duration defines the expected time the service function requires
// to produce/consume elements. For source patterns, the data output rate
// will be used to defined the target duration. For sink patterns, the
// input rate of elements is used to define the target duration
//
virtual TimeDuration getTargetDuration();
//
// calcThrottle
//
// Calculate the duration about that we should sleep based on processing time
// based on value from getTargetDuration() minus processing time ( end time
// minus start time)
//
// If the value is a positive duration then the boost::this_thread::sleep
// method is called with 1/4 of the calculated duration.
//
virtual TimeDuration calcThrottle( TimeMark &stime,
TimeMark &etime );
//
// createBlock
//
// Create the actual GNU Radio Block to that will perform the work method. The resulting
// block object is assigned to gr_sptr
//
// Add property change callbacks for getter/setter methods
//
//
virtual void createBlock() = 0;
//
// setupIOMappings
//
// Sets up mappings for input and output ports and GnuRadio Stream indexes
//
// A Gnu Radio input or output streams will be created for each defined RedHawk port.
// The streams will be ordered 0..N-1 as they are defined in inputPortOrder and outputPortOrder
// lists created during Component initialization.
//
// For Gnu Radio blocks that define -1 for maximum number of input streams. The number of
// input streams created will be restricted to the number of RedHawk ports.
//
// RESOLVE - need to base mapping for -1 condition on "connections" and not streams
// RESOLVE - need to add parameters to define expected modes for input ports.. i.e. real or complex and
// not have to wait for SRI.
//
virtual void setupIOMappings();
//
// getNOutputStreams
//
// Called by setupIOMappings when the number of Gnu Radio output streams == -1 (variable ) and number of
// Redhawk ports == 1.
// @return uint32_t : Number of output streams to build
//
virtual uint32_t getNOutputStreams();
//
// createOutputSRI
//
// Called by setupIOMappings when an output mapping is defined. For each output mapping
// defined, a call to createOutputSRI will be issued with the associated output index.
// This default SRI and StreamID will be saved to the mapping and pushed down stream via pushSRI.
// The subclass is responsible for overriding behavior of this method. The index provide matches
// the stream index number that will be use by the Gnu Radio Block object
//
// @param idx : output stream index number to associate the returned SRI object with
// @return sri : default SRI object passed down stream over a RedHawk port
//
virtual BULKIO::StreamSRI createOutputSRI( int32_t oidx, int32_t &in_idx, std::string &ext );
virtual BULKIO::StreamSRI createOutputSRI( int32_t oidx);
//
// adjustOutputRate
//
// Called by seOutputStreamSRI method when pushing SRI down stream to adjust the
// the xdelta and/or ydelta values accordingly. The provided method will perform the following:
//
// gr_blocks, gr_sync_block - no modifications are performed
// gr_sync_decimator - sri.xdelta * gr_sptr->decimation()
// gr_sync_interpolator - sri.xdelta / gr_sptr->interpolate()
//
virtual void adjustOutputRate(BULKIO::StreamSRI &sri );
// callback when a new Stream ID is detected on the port so we can add to istream/ostream mapping list
void byte_in_newStreamCallback( BULKIO::StreamSRI &sri );
void processStreamIdChanges();
//
// setOutputSteamSRI
//
// Set the SRI context for an output stream from a Gnu Radio Block, when a pushPacket call occurs. Whenever the SRI is established
// for an output stream it is sent down stream to the next component.
//
virtual void setOutputStreamSRI( int streamIdx, BULKIO::StreamSRI &in_sri, bool sendSRI=true, bool setStreamID=true ) {
for (int i = 0; i < (int)io_mapping[streamIdx].size(); i++){
int o_idx = io_mapping[streamIdx][i];
_ostreams[o_idx]->adjustSRI(in_sri, o_idx, stream_id_map, outPorts, setStreamID, naming_service_name );
if ( sendSRI ) _ostreams[o_idx]->pushSRI();
}
}
//
// setOutputSteamSRI
//
// Use the same SRI context for all output streams from a Gnu Radio Block, when a pushPacket call occurs. Whenever the SRI is established
// for an output stream it is sent down stream to the next component.
//
virtual void setOutputStreamSRI( BULKIO::StreamSRI &in_sri , bool sendSRI = true, bool setStreamID = true ) {
OStreamList::iterator ostream=_ostreams.begin();
for( int o_idx=0; ostream != _ostreams.end(); o_idx++, ostream++ ) {
(*ostream)->adjustSRI(in_sri, o_idx, stream_id_map, outPorts, setStreamID, naming_service_name );
if ( sendSRI ) (*ostream)->pushSRI();
}
}
//
// gr_istream - Mapping of Provides Ports to Gnu Radio Stream indexes
//
// Gnu Radio Block input stream definition:
// Input = 1 .. N then each Provides Port type of X is mapped to a stream index 0..N-1
// This assumes the component will only have 1 input port type. (i.e float ports)
// Input = -1 and single Provides Port interface then each unique stream definition will map to a stream index 0..N
// Input = -1 and N Provides Port interface then each port will map to a stream index 0..N-1
//
// The mapping items are stored in a vector and maintain by setIOMappings and notifySRI methods, and
// the service function when "end of stream" happens.
//
struct gr_istream_base {
GNU_RADIO_BLOCK_PTR grb; // shared pointer to our gr_block
int _idx; // index of stream in gr_block
std::string streamID; // redhawk stream id
int _spe; // scalars per element
int _vlen; // vector length in items, the gr_block process data
int _hlen; // history length in items, the gr_blocks expects
bool _eos; // if EOS was received from port
bool _sri; // that we received an SRI call
// Functions for child to implement
virtual int SizeOfElement( int mode) = 0;
virtual uint64_t nelems () = 0;
virtual int read( int64_t ritems=-1 ) = 0;
virtual bool overrun() = 0;
virtual bool sriChanged() = 0;
virtual void *read_pointer( int32_t items ) = 0;
virtual void consume( int32_t n_items ) = 0;
virtual void consume_elements( int32_t inNelems ) = 0;
virtual void close() = 0;
virtual void resizeData(int newSize) = 0;
virtual void * getPort() = 0;
virtual std::string getPktStreamId() = 0;
virtual BULKIO::StreamSRI& getPktSri() = 0;
virtual bool pktNull() = 0;
virtual TimeStamp getPktTimeStamp() = 0;
gr_istream_base( GNU_RADIO_BLOCK_PTR in_grb, int idx, int mode, std::string &sid ) :
grb(in_grb), _idx(idx), streamID(sid), _spe(1), _vlen(1), _hlen(1), _eos(false), _sri(true)
{
};
gr_istream_base( GNU_RADIO_BLOCK_PTR in_grb, int idx, std::string &sid ) :
grb(in_grb), _idx(idx), streamID(sid), _spe(1), _vlen(1), _hlen(1), _eos(false), _sri(false)
{
};
//
// translate scalars per element for incoming data
// mode == 0 : real, mode == 1 : complex
static inline int ScalarsPerElement( int mode ) {
int spe=1;
if ( mode == 1 ) spe=2;
return spe;
};
//
// translate scalars per element for incoming data
// mode == 0 : real, mode == 1 : complex
static inline int ScalarsPerElement( BULKIO::StreamSRI &sri ) {
return ScalarsPerElement( sri.mode );
};
//
// return scalars per element
//
inline int spe () {
return _spe;
}
//
// set scalars per element
//
inline int spe( int mode ) {
_check( mode );
return _spe;
}
//
// return state if SRI was set
//
inline bool sri() {
return _sri;
}
inline bool sri( bool newSri ) {
_sri = newSri;
return _sri;
}
//
// return if End of Stream was seen
//
inline bool eos() {
return _eos;
}
inline bool eos( bool newEos ) {
_eos = newEos;
return _eos;
}
inline int vlen () {
return _vlen;
}
void _check( int inMode , bool force=false) {
// calc old history value
int32_t old_hlen = (_hlen-1) * (_vlen*_spe);
int32_t spe=ScalarsPerElement(inMode);
int32_t nvlen=_vlen;
bool newVlen=false;
bool newSpe=false;
try {
if ( grb && grb->input_signature() )
nvlen = grb->input_signature()->sizeof_stream_item(_idx) / SizeOfElement(inMode);
} catch(...) {
LOG_TRACE( stream_to_streams_bb_2o_base, "UNABLE TO SET VLEN, BAD INDEX:" << _idx );
}
if ( nvlen != _vlen && nvlen >= 1 ) {
_vlen=nvlen;
newVlen=true;
}
if ( spe != _spe ) {
_spe = spe;
newSpe = true;
}
if ( force || newSpe || newVlen ) {
// seed history for buffer with empty items
int32_t new_hlen = ( grb->history()-1)* ( _vlen * _spe );
if ( (old_hlen != new_hlen) && ( new_hlen > -1 ) ) {
_hlen = grb->history();
resizeData( new_hlen );
}
}
}
//
// reset our association to a GR Block
//
void associate( GNU_RADIO_BLOCK_PTR newBlock ) {
grb = newBlock;
if ( grb ) _check( _spe, true );
}
//
//
//
inline uint64_t nitems () {
uint64_t tmp = nelems();
if ( _vlen > 0 ) tmp /= _vlen;
return tmp;
}
uint64_t itemsToScalars( uint64_t N ) {
return N*_vlen*_spe;
};
};
template < typename IN_PORT_TYPE > struct gr_istream : gr_istream_base {
IN_PORT_TYPE *port; // RH port object
std::vector< typename IN_PORT_TYPE::NativeType > _data; // buffered data from port
typename IN_PORT_TYPE::dataTransfer *pkt; // pointer to last packet read from port
gr_istream( IN_PORT_TYPE *in_port, GNU_RADIO_BLOCK_PTR in_grb, int idx, int mode, std::string &sid ) :
gr_istream_base(in_grb, idx, mode, sid), port(in_port), _data(0), pkt(NULL)
{
_spe = ScalarsPerElement(mode);
_check(mode, true);
};
gr_istream( IN_PORT_TYPE *in_port, GNU_RADIO_BLOCK_PTR in_grb, int idx, std::string &sid ) :
gr_istream_base(in_grb, idx, sid), port(in_port), _data(0), pkt(NULL)
{
int mode=0;
_spe = ScalarsPerElement(mode);
_check(mode, true);
};
//
// Return the size of an element (sample) in bytes
//
inline int SizeOfElement(int mode ) {
return sizeof( typename IN_PORT_TYPE::NativeType)*ScalarsPerElement( mode);
};
//
// Return the size of an element (sample) in bytes
//
static inline int SizeOfElement( BULKIO::StreamSRI &sri ) {
return sizeof( typename IN_PORT_TYPE::NativeType)*ScalarsPerElement(sri);
}
inline uint64_t nelems () {
uint64_t tmp = _data.size();
if ( _spe > 0 ) tmp /= _spe;
return tmp;
}
// RESOLVE: need to allow for requests of certain size, and blocking and timeouts
int read( int64_t ritems=-1 ) {
int retval = -1;
typename IN_PORT_TYPE::dataTransfer *tpkt;
if ( port && _sri ) {
tpkt = port->getPacket( -1, streamID );
if ( tpkt == NULL ) {
if ( port != NULL && port->blocked() ) retval = 0;
} else {
_data.insert( _data.end(), tpkt->dataBuffer.begin(), tpkt->dataBuffer.end() );
if ( tpkt->sriChanged ) {
spe(tpkt->SRI.mode);
}
// resolve need to keep time stamp accurate for first sample of data.... we could loose this if we
// end having residual data left in the buffer when output_multiple and vlen are used
// by the gr_block - read and consume_elements need refactoring
_eos = tpkt->EOS;
if ( pkt != NULL ) delete pkt;
pkt = tpkt;
retval=nitems();
}
}
return retval;
}
inline bool overrun() {
return ( pkt && pkt->inputQueueFlushed);
}
inline bool sriChanged() {
return ( pkt && pkt->sriChanged );
}
inline std::string getPktStreamId() {
return pkt->streamID;
}
inline BULKIO::StreamSRI& getPktSri() {
return pkt->SRI;
}
inline bool pktNull() {
return pkt == NULL;
}
inline TimeStamp getPktTimeStamp() {
return pkt->T;
}
void *read_pointer( int32_t items ) {
uint32_t idx = itemsToScalars(items);
if ( idx < _data.size() )
return (void*) &_data[ idx ];
else
return (void*) &_data[0];
}
// compress data buffer for requested number of items
void consume( int32_t n_items ) {
if ( n_items > 0 ) {
consume_elements( n_items*_vlen );
}
}
// compress data buffer for requested number of items
void consume_elements( int32_t inNelems ) {
int d_idx = inNelems*_spe;
int n = std::distance( _data.begin() + d_idx, _data.end() );
if ( d_idx > 0 && n >= 0 ) {
std::copy( _data.begin() + d_idx, _data.end(), _data.begin() );
_data.resize(n);
}
}
// perform clean up of stream state and mapping
void close() {
_data.clear();
_vlen = 1;
_hlen=1;
_eos = false;
_sri = false;
if ( pkt ) {
delete pkt;
pkt=NULL;
}
}
void resizeData(int new_hlen) {
_data.resize( new_hlen );
}
void * getPort(){
return (void*) port;
}
};
// gr_ostream
//
// Provides a mapping of output ports to a Gnu Radio Block's output stream. These items
// are stored in a vector for managing output from the Gnu Radio Block and pushing
// the data down stream to the next component over the port object.
//
// Items in the vector are maintain by setIOMappings, notifySRI and the
// the service function when "end of stream" happens
//
struct gr_ostream_base {
GNU_RADIO_BLOCK_PTR grb; // shared pointer ot GR_BLOCK
int _idx; // output index (loose association)
std::string _ext; // extension to append to incoming StreamID
std::string streamID; // Stream Id to send down stream
BULKIO::StreamSRI sri; // SRI to send down stream
bool _m_tstamp; // set to true if we are maintaining outgoing time stamp
BULKIO::PrecisionUTCTime tstamp; // time stamp to use for pushPacket calls
bool _eos; // if EOS was sent
uint64_t _nelems; // number of elements in that have been pushed down stream
int _vlen; // vector length in items, to allocate output buffer for GR_BLOCK
// Functions for child to implement
virtual int SizeOfElement( int mode) = 0;
virtual void pushSRI() = 0;
virtual void pushSRI( BULKIO::StreamSRI &inSri ) = 0;
virtual uint64_t nelems() = 0;
virtual void resize( int32_t n_items ) = 0;
virtual void *write_pointer() = 0;
virtual int write( int32_t n_items, bool eos, TimeStamp &ts, bool adjust_ts=false ) = 0;
virtual int write( int32_t n_items, bool eos, bool adjust_ts ) = 0;
virtual int write( int32_t n_items, bool eos ) = 0;
virtual void close() = 0;
gr_ostream_base( GNU_RADIO_BLOCK_PTR ingrb, int idx, int mode, std::string &in_sid, const std::string &ext="" ) :
grb(ingrb), _idx(idx), _ext(ext), streamID(in_sid), _m_tstamp(false), _eos(false), _nelems(0), _vlen(1)
{
sri.hversion = 1;
sri.xstart = 0.0;
sri.xdelta = 1;
sri.xunits = BULKIO::UNITS_TIME;
sri.subsize = 0;
sri.ystart = 0.0;
sri.ydelta = 0.0;
sri.yunits = BULKIO::UNITS_NONE;
sri.mode = mode;
sri.streamID = streamID.c_str();
// RESOLVE sri.blocking=0; to block or not
tstamp.tcmode = BULKIO::TCM_CPU;
tstamp.tcstatus = (short)1;
tstamp.toff = 0.0;
setTimeStamp();
}
//
// translate scalars per element for incoming data
// mode == 0 : real, mode == 1 : complex
static inline int ScalarsPerElement( int mode ) {
int spe=1;
if ( mode == 1 ) spe=2;
return spe;
};
//
// translate scalars per element for incoming data
// mode == 0 : real, mode == 1 : complex
static inline int ScalarsPerElement( BULKIO::StreamSRI &sri ) {
return ScalarsPerElement( sri.mode );
};
//
// Establish and SRI context for this output stream
//
void setSRI( BULKIO::StreamSRI &inSri, int idx ) {
sri=inSri;
streamID = sri.streamID;
// check if history, spe and vlen need to be adjusted
_check(idx);
};
//
// Only adjust stream id and output rate for SRI object
//
void adjustSRI( BULKIO::StreamSRI &inSri, int idx, const std::vector<stream_id_struct_struct> &stream_id_map, PortSupplier_impl::RH_UsesPortMap& outPorts, bool setStreamID=true, const std::string &stream_tag="" ) {
if ( setStreamID ) {
std::vector<std::string> outPortNames;
for (RH_UsesPortMap::iterator port = outPorts.begin(); port != outPorts.end(); ++port ) {
outPortNames.push_back(port->first);
}
std::string s(inSri.streamID);
std::ostringstream t;
if (stream_id_map.size() != 0) {
for(int i = 0; i < (int)stream_id_map.size(); i++) {
if (outPortNames[idx] == stream_id_map[i].port_name) {
std::string stream = stream_id_map[i].stream_id;
t << inSri.streamID << "_";
stream = boost::replace_all_copy( stream, "%SID", t.str() );
stream = boost::replace_all_copy( stream, "%C", stream_tag + "_" );
t.str("");
t << idx << "_";
stream = boost::replace_all_copy( stream, "%D", t.str() );
streamID = stream;
sri.streamID = stream.c_str();
}
}
outPortNames.clear();
}
else {
t << s << _ext;
streamID = t.str();
sri.streamID = t.str().c_str();
}
}
double ret=inSri.xdelta;
if ( grb ) ret = ret *grb->relative_rate();
sri.xdelta = ret;
_check(idx);
};
//
// Set our stream ID ...
//
void setStreamID( std::string &sid ) {
streamID=sid;
};
//
// Return the number of scalars per element (sample) that we use
//
inline int spe() {
return ScalarsPerElement(sri.mode);
}
//
// return the state if EOS was pushed down stream
//
inline bool eos () {
return _eos;
}
//
// return the vector length to process data by the GR_BLOCK
//
inline int vlen() {
return _vlen;
}
inline bool eos ( bool inEos ) {
_eos=inEos;
return _eos;
}
void _check( int idx ) {
if ( grb ) {
int nvlen=1;
try {
if ( grb && grb->output_signature() )
nvlen = grb->output_signature()->sizeof_stream_item(idx) / SizeOfElement(sri.mode);
if ( nvlen != _vlen && nvlen >= 1 ) _vlen=nvlen;
} catch(...) {
LOG_TRACE( stream_to_streams_bb_2o_base, "UNABLE TO SET VLEN, BAD INDEX:" << _idx );
}
}
}
//
// establish and assocation with a new GR_BLOCK
//
void associate( GNU_RADIO_BLOCK_PTR newblock ) {
grb = newblock;
_check( _idx );
}
//
// return the number of items in the output buffer
//
inline uint64_t nitems () {
uint64_t tmp=nelems();
if ( _vlen > 0 ) tmp /= _vlen;
return tmp;
}
//
// return the number of scalars used for N number of items
//
inline uint64_t itemsToScalars( uint64_t N ) {
return N*_vlen*spe();
};
//
// return the number of output elements sent down stream
//
inline uint64_t oelems() {
return _nelems;
};
//
// return the number of output items sent down stream
//
inline uint64_t oitems() {
uint64_t tmp = _nelems;
if ( _vlen > 0 ) tmp /= _vlen;
return tmp;
};
//
// Turn time stamp calculations on or off
//
void setAutoAdjustTime( bool onoff ) {
_m_tstamp = onoff;
};
//
// sets time stamp value to be time of day
//
void setTimeStamp( ) {
struct timeval tmp_time;
struct timezone tmp_tz;
gettimeofday(&tmp_time, &tmp_tz);
tstamp.twsec = tmp_time.tv_sec;
tstamp.tfsec = tmp_time.tv_usec / 1e6;
};
//
// set time stamp value for the stream to a specific value, turns on
// stream's monitoring of time stamp
//
void setTimeStamp( TimeStamp &inTimeStamp, bool adjust_ts=true ) {
_m_tstamp = adjust_ts;
tstamp = inTimeStamp;
};
void forwardTimeStamp( int32_t noutput_items, TimeStamp &ts ) {
double twsec = ts.twsec;
double tfsec = ts.tfsec;
double sdelta=sri.xdelta;
sdelta = sdelta * noutput_items*_vlen;
double new_time = (twsec+tfsec)+sdelta;
ts.tfsec = std::modf( new_time, &ts.twsec );
};
void forwardTimeStamp( int32_t noutput_items ) {
double twsec = tstamp.twsec;
double tfsec = tstamp.tfsec;
double sdelta=sri.xdelta;
sdelta = sdelta * noutput_items*_vlen;
double new_time = (twsec+tfsec)+sdelta;
tstamp.tfsec = std::modf( new_time, &tstamp.twsec );
};
};
template < typename OUT_PORT_TYPE > struct gr_ostream : gr_ostream_base {
OUT_PORT_TYPE *port; // handle to Port object
std::string _ext; // extension to append to incoming StreamID
std::vector< typename OUT_PORT_TYPE::NativeType > _data; // output buffer used by GR_Block
gr_ostream( OUT_PORT_TYPE *out_port, GNU_RADIO_BLOCK_PTR ingrb, int idx, int mode, std::string &in_sid, std::string &ext="" ) :
gr_ostream_base(ingrb, idx, mode, in_sid, ext), port(out_port), _ext(ext),_data(0)
{
};
//
// Return the size of an element (sample) in bytes
//
inline int SizeOfElement(int mode ) {
return sizeof( typename OUT_PORT_TYPE::NativeType)*ScalarsPerElement( mode);
};
//
// Return the size of an element (sample) in bytes
//
static inline int SizeOfElement( BULKIO::StreamSRI &sri ) {
return sizeof( typename OUT_PORT_TYPE::NativeType)*ScalarsPerElement(sri);
};
//
// push our SRI object down stream
//
void pushSRI() {
if ( port ) port->pushSRI( sri );
};
//
// push incoming SRI object down stream, do not save this object
//
void pushSRI( BULKIO::StreamSRI &inSri ) {
if ( port ) port->pushSRI( inSri );
};
//
// return the number of elements (samples) in the output buffer
//
inline uint64_t nelems() {
uint64_t tmp = _data.size();
if ( spe() > 0 ) tmp /= spe();
return tmp;
};
//
// resize the output buffer to N number of items
//
void resize( int32_t n_items ) {
if ( _data.size() != (size_t)(n_items*spe()*_vlen) ) {
_data.resize( n_items*spe()*_vlen );
}
}
void *write_pointer(){
// push ostream's buffer address onto list of output buffers
return (void*) &(_data[0]);
}
//
// write data to output ports using the provided time stamp and adjust the time
// accordingly using the xdelta value of the SRI and the number of items
//
int write( int32_t n_items, bool eos, TimeStamp &ts, bool adjust_ts=false ) {
resize( n_items );
if ( port ) port->pushPacket( _data, ts, eos, streamID );
if ( adjust_ts ) forwardTimeStamp( n_items, ts );
_eos = eos;
_nelems += (n_items*_vlen);
return n_items;
};
//
// write data to the output port using the map object's timestamp
// if the adjust_ts value equals true. otherwise use time of
// day for the time stamp
//
int write( int32_t n_items, bool eos, bool adjust_ts ) {
if ( !adjust_ts ) setTimeStamp();
resize( n_items );
if ( port ) port->pushPacket( _data, tstamp, eos, streamID );
if ( adjust_ts ) forwardTimeStamp( n_items );
_eos = eos;
_nelems += (n_items*_vlen);
return n_items;
};
//
// write data to the output port using the map object's timestamp and
// adjust the time stamp if the maps's m_tstamp value == true
//
int write( int32_t n_items, bool eos ) {
if ( !_m_tstamp ) setTimeStamp();
resize( n_items );
if ( port ) port->pushPacket( _data, tstamp, eos, streamID );
if ( _m_tstamp ) forwardTimeStamp( n_items );
_eos = eos;
_nelems += n_items*_vlen;
return n_items;
};
// perform clean up on the stream state and map
void close() {
_data.clear();
_vlen=1;
_eos = false;
_m_tstamp=false;
};
};
typedef gr_vector_const_void_star GR_IN_BUFFERS;
typedef gr_vector_void_star GR_OUT_BUFFERS;
typedef gr_vector_int GR_BUFFER_LENGTHS;
int _analyzerServiceFunction( std::vector< gr_istream_base * > &istreams );
int _forecastAndProcess( bool &eos, std::vector< gr_istream_base * > &istreams );
int _generatorServiceFunction( std::vector< gr_ostream_base * > &ostreams );
int _transformerServiceFunction( std::vector< gr_istream_base * > &istreams,
std::vector< gr_ostream_base * > &ostreams );
int _forecastAndProcess( bool &eos, std::vector< gr_istream_base * > &istreams,
std::vector< gr_ostream_base * > &ostreams );
typedef std::deque< std::pair< void*, BULKIO::StreamSRI > > SRIQueue;
typedef std::vector< gr_istream_base * > IStreamList;
typedef std::vector< gr_ostream_base * > OStreamList;
// cache variables to transferring data to/from a GNU Radio Block
std::vector<bool> _input_ready;
GR_BUFFER_LENGTHS _ninput_items_required;
GR_BUFFER_LENGTHS _ninput_items;
GR_IN_BUFFERS _input_items;
GR_OUT_BUFFERS _output_items;
int32_t noutput_items;
boost::mutex _sriMutex;
SRIQueue _sriQueue;
// mapping of RH ports to GNU Radio streams
IStreamList _istreams;
OStreamList _ostreams;
bool sentEOS;
ENABLE_LOGGING;
protected:
bool _maintainTimeStamp;
bool _throttle;
TimeMark p_start_time;
TimeMark p_end_time;
public:
int serviceFunction()
{
int retval = NOOP;
retval = _transformerServiceFunction( _istreams, _ostreams );
p_end_time = boost::posix_time::microsec_clock::local_time();
if ( retval == NORMAL && _throttle ) {
TimeDuration delta = calcThrottle( p_start_time, p_end_time );
if ( delta.is_not_a_date_time() == false && delta.is_negative() == false ) {
LOG_TRACE( stream_to_streams_bb_2o_base, " SLEEP ...." << delta );
boost::this_thread::sleep( delta );
} else {
LOG_TRACE( stream_to_streams_bb_2o_base, " NO SLEEPING...." );
}
}
p_start_time = p_end_time;
LOG_TRACE( stream_to_streams_bb_2o_base, " serviceFunction: retval:" << retval);
return retval;
};
};
#endif
| RedhawkSDR/integration-gnuhawk | components/stream_to_streams_bb_2o/cpp/stream_to_streams_bb_2o_base.h | C | gpl-3.0 | 38,163 |
$(window).scroll(function (e) {
var $w = $(window).width();
var $h = $(window).height();
if ($w > 980 && $h > 400) {
if ($(this).scrollTop() >= 268) {
$("#index_nav.index_nav, #compatible").addClass("index_nav_fixed");
} else {
$("#index_nav.index_nav, #compatible").removeClass("index_nav_fixed");
}
$("#slides").css("height", 300 - ($(this).scrollTop()) + "px");
$("#slides img").css("opacity", (((250 - ($(this).scrollTop())) * 100) / 250) / 100);
$(".si-ctitle-c").css("opacity", (((250 - ($(this).scrollTop())) * 100) / 250) / 100);
}
});
| depweb2/platform | lib/index.js | JavaScript | gpl-3.0 | 634 |
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.core.localization;
import net.minecraft.util.StatCollector;
public enum WailaText
{
Crafting,
DeviceOnline, DeviceOffline, DeviceMissingChannel,
Locked, Unlocked, Showing,
Contains, Channels;
private final String root;
WailaText()
{
this.root = "waila.appliedenergistics2";
}
WailaText( final String r )
{
this.root = r;
}
public String getLocal()
{
return StatCollector.translateToLocal( this.getUnlocalized() );
}
public String getUnlocalized()
{
return this.root + '.' + this.toString();
}
}
| itachi1706/Applied-Energistics-2 | src/main/java/appeng/core/localization/WailaText.java | Java | gpl-3.0 | 1,368 |
#ifndef ANIMATIONROTATEMOVE_H
#define ANIMATIONROTATEMOVE_H
#include <QGraphicsItem>
#include "pictureanimation.h"
class AnimationRotateMove : public AbstractPictureAnimation
{
public:
QAbstractAnimation *getAnimationIn (AnimatedItem *target, int duration, int parentWidth);
QAbstractAnimation *getAnimationOut (AnimatedItem *target, int duration, int parentWidth);
};
#endif // ANIMATIONROTATEMOVE_H
| cachirulop/PhotoViewer | animationrotatemove.h | C | gpl-3.0 | 426 |
import os.path
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth import get_user_model
from avatar.settings import AVATAR_DEFAULT_URL, AVATAR_MAX_AVATARS_PER_USER
from avatar.util import get_primary_avatar
from avatar.models import Avatar
try:
from PIL import Image
dir(Image) # Placate PyFlakes
except ImportError:
import Image
def upload_helper(o, filename):
f = open(os.path.join(o.testdatapath, filename), "rb")
response = o.client.post(reverse('avatar_add'), {
'avatar': f,
}, follow=True)
f.close()
return response
class AvatarUploadTests(TestCase):
def setUp(self):
self.testdatapath = os.path.join(os.path.dirname(__file__), "testdata")
self.user = get_user_model().objects.create_user('test', 'lennon@thebeatles.com', 'testpassword')
self.user.save()
self.client.login(username='test', password='testpassword')
Image.init()
def testNonImageUpload(self):
response = upload_helper(self, "nonimagefile")
self.failUnlessEqual(response.status_code, 200)
self.failIfEqual(response.context['upload_avatar_form'].errors, {})
def testNormalImageUpload(self):
response = upload_helper(self, "test.png")
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(len(response.redirect_chain), 1)
self.failUnlessEqual(response.context['upload_avatar_form'].errors, {})
avatar = get_primary_avatar(self.user)
self.failIfEqual(avatar, None)
def testImageWithoutExtension(self):
# use with AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
response = upload_helper(self, "imagefilewithoutext")
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(len(response.redirect_chain), 0) # Redirect only if it worked
self.failIfEqual(response.context['upload_avatar_form'].errors, {})
def testImageWithWrongExtension(self):
# use with AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
response = upload_helper(self, "imagefilewithwrongext.ogg")
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(len(response.redirect_chain), 0) # Redirect only if it worked
self.failIfEqual(response.context['upload_avatar_form'].errors, {})
def testImageTooBig(self):
# use with AVATAR_MAX_SIZE = 1024 * 1024
response = upload_helper(self, "testbig.png")
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(len(response.redirect_chain), 0) # Redirect only if it worked
self.failIfEqual(response.context['upload_avatar_form'].errors, {})
def testDefaultUrl(self):
response = self.client.get(reverse('avatar_render_primary', kwargs={
'user': self.user.username,
'size': 80,
}))
loc = response['Location']
base_url = getattr(settings, 'STATIC_URL', None)
if not base_url:
base_url = settings.MEDIA_URL
self.assertTrue(base_url in loc)
self.assertTrue(loc.endswith(AVATAR_DEFAULT_URL))
def testNonExistingUser(self):
a = get_primary_avatar("nonexistinguser")
self.failUnlessEqual(a, None)
def testThereCanBeOnlyOnePrimaryAvatar(self):
for i in range(1, 10):
self.testNormalImageUpload()
count = Avatar.objects.filter(user=self.user, primary=True).count()
self.failUnlessEqual(count, 1)
def testDeleteAvatar(self):
self.testNormalImageUpload()
avatar = Avatar.objects.filter(user=self.user)
self.failUnlessEqual(len(avatar), 1)
response = self.client.post(reverse('avatar_delete'), {
'choices': [avatar[0].id],
}, follow=True)
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(len(response.redirect_chain), 1)
count = Avatar.objects.filter(user=self.user).count()
self.failUnlessEqual(count, 0)
def testDeletePrimaryAvatarAndNewPrimary(self):
self.testThereCanBeOnlyOnePrimaryAvatar()
primary = get_primary_avatar(self.user)
oid = primary.id
response = self.client.post(reverse('avatar_delete'), {
'choices': [oid],
})
primaries = Avatar.objects.filter(user=self.user, primary=True)
self.failUnlessEqual(len(primaries), 1)
self.failIfEqual(oid, primaries[0].id)
avatars = Avatar.objects.filter(user=self.user)
self.failUnlessEqual(avatars[0].id, primaries[0].id)
def testTooManyAvatars(self):
for i in range(0, AVATAR_MAX_AVATARS_PER_USER):
self.testNormalImageUpload()
count_before = Avatar.objects.filter(user=self.user).count()
response = upload_helper(self, "test.png")
count_after = Avatar.objects.filter(user=self.user).count()
self.failUnlessEqual(response.status_code, 200)
self.failUnlessEqual(len(response.redirect_chain), 0) # Redirect only if it worked
self.failIfEqual(response.context['upload_avatar_form'].errors, {})
self.failUnlessEqual(count_before, count_after)
# def testAvatarOrder
# def testReplaceAvatarWhenMaxIsOne
# def testHashFileName
# def testHashUserName
# def testChangePrimaryAvatar
# def testDeleteThumbnailAndRecreation
# def testAutomaticThumbnailCreation
| bhermansyah/DRR-datacenter | avatar/tests.py | Python | gpl-3.0 | 5,578 |
package DNA::Language::CommandLine::LanguageAnalysis;
# ABSTRACT:
=head1 SYNOPSIS
=cut
use Moose;
use Getopt::Long qw(GetOptionsFromArray);
use DNA::Language;
has 'args' => ( is => 'ro', isa => 'ArrayRef', required => 1 );
has 'script_name' => ( is => 'ro', isa => 'Str', required => 1 );
has 'help' => ( is => 'rw', isa => 'Bool', default => 0 );
has 'fasta_file' => ( is => 'rw', isa => 'Str' );
has 'rand_range' => ( is => 'rw', isa => 'Str' );
has 'total_number_of_bases' => ( is => 'rw', isa => 'Int' );
has 'mode' => ( is => 'rw', isa => 'Str', lazy => 1, default => q(real) );
has 'k' => ( is => 'rw', isa => 'Int', lazy => 1, default => 3 );
has 'host' => ( is => 'rw', isa => 'Str', lazy => 1, default => q() );
has 'branch' => ( is => 'rw', isa => 'Str', lazy => 1, default => q() );
has 'rmode' => ( is => 'rw', isa => 'Str', lazy => 1, default => q(ro) );
has 'test' => ( is => 'rw', isa => 'Bool', lazy => 1, default => 0 );
sub BUILD {
my ($self) = @_;
my ( $fasta_file, $mode, $k, $rand_range, $total_number_of_bases, $host, $branch,
$rmode, $test, $help );
GetOptionsFromArray(
$self->args,
'f|fasta:s' => \$fasta_file,
'rg|rand_range:s' => \$rand_range,
'n|tnb=s' => \$total_number_of_bases,
'm|mode:s' => \$mode,
'k|kgramm:s' => \$k,
'ho|host=s' => \$host,
'b|branch=s' => \$branch,
'r|rmode=s' => \$rmode,
't|test' => \$test,
'h|help' => \$help,
);
$self->mode($mode) if ( defined($mode) );
$self->k($k) if ( defined($k) );
$self->rand_range($rand_range) if ( defined($rand_range) );
$self->total_number_of_bases($total_number_of_bases)
if ( defined($total_number_of_bases) );
$self->host($host) if ( defined($host) );
$self->branch($branch) if ( defined($branch) );
$self->rmode($rmode) if ( defined($rmode) );
$self->test($test) if ( defined($test) );
}
sub run {
my($self) = @_;
( $self->rand_range && $self->total_number_of_bases && $self->fasta_file ) or die <<USAGE;
Usage:
-f|fasta <Options: fasta file to analyse >
-rg|rand_range <Options: range of the universe of random numbers to choose form when running under random mode. From (4 to infinity really)>
-tnb|total_number_of_bases <Options: to infinity and beyond>
-m|mode <Options: 'random','test' or 'real'>
-k|kgram <Options: 3 4 5 6 7 8 9 10 11>
-h|host <Options: 'ensembl' or 'genomes'>
-b|branch <Options: 'plants' or 'fungi' or 'protist' or 'metazoa' or 'bacteria'>
-r|rmode, <Options: 'ro', 'rw'>
-t|test <Options: 1 (run the test sub_routine) or 0 (don't run it)>
-?|help <Print this message>
USAGE
my $lanalysis = DNA::Language->new(
fasta_file => $self->fasta_file,
mode => $self->mode,
k => $self->k,
rand_range => $self->rand_range,
tnb => $self->total_number_of_bases,
host => $self->host,
branch => $self->branch,
rmode =>$self->rmode,
test => $self->test
);
$lanalysis->run;
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
| jssoares/DNA-Language | lib/DNA/Language/CommandLine/LanguageAnalysis.pm | Perl | gpl-3.0 | 3,382 |
/*
* This is an implementation of Viscous protocol.
* Copyright (C) 2017 Abhijit Mondal
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
/*
* InterfaceHnadler.cpp
*
* Created on: 06-Dec-2016
* Author: abhijit
*/
#include "ChannelHandler.hh"
#include <netinet/in.h>
#include <cstdlib>
#include <ctime>
#include "../InterfaceController/InterfaceMonitor.hh"
#include "../ChannelScheduler/SchedulerInterface.hh"
#include "../InterfaceController/Addresses.hh"
#include "../Packet.h"
#include "../PacketPool.hh"
namespace channelHandler{
ChannelHandler::ChannelHandler(BaseReliableObj* parent, appInt8 ifcLoc, RemoteAddr& rmadr, appInt8 ifcSrc, appInt8 ifcDst):
parent(parent)
, ifcMon(NULL)
, sender(NULL)
, remoteAddr(rmadr)
, remIp(0)
, ifcSrc(ifcSrc)
, ifcDst(ifcDst)
, id_((ifcSrc << 4) | (ifcDst&0x0f))
{
sender = getInterfaceSender()[ifcLoc];
ifcMon = parent->getInterfaceMontor();
// APP_ASSERT(sender);
}
ChannelHandler::~ChannelHandler() {
}
appInt &ChannelHandler::id(){
return id_;
}
appSInt ChannelHandler::recv(Packet *pkt){
//TODO
return 0;
}
appInt16 ChannelHandler::getSenderWindowSize(){
std::srand(std::time(0)); // use current time as seed for random generator
return std::rand()%57;
}
appSInt ChannelHandler::sendPacket(Packet *pkt){
return send(pkt);
}
void ChannelHandler::shutDown() {
APP_ASSERT(0 and "NOT IMPLEMENTED IN DERIVED CLASS");
}
appSInt ChannelHandler::send(Packet *pkt)
{
// appChar msg[2048];
// appInt dlen = 0;
PacketOptionalAbstractHeader *pktAckHdr = pkt->optHeaders;
//TODO handle pending acks more efficiently
// for(appInt i = 0; i < Packet::maxOptHeader; i++){
// PacketOptionalAbstractHeader *tmp = parent->pendingAcks().removeAck();
// if(!tmp)
// break;
// tmp->next = pktAckHdr;
// pktAckHdr = tmp;
// }
pkt->header.ifcsrc = ifcSrc;
pkt->header.ifcdst = ifcDst;
pkt->optHeaders = pktAckHdr;
// pkt->header.destIp = remIp;
// dlen = encodeHeader(pkt, (appByte *)msg, sizeof(msg));
// if(!dlen)
// return 0;
// return sender->sendPacket(msg, dlen, remoteAddr.ip, remoteAddr.port);
appSInt ret = 0;
if(sender)
ret = sender->sendPkt(pkt, remoteAddr.ip, remoteAddr.port);
else if(ifcMon){
ret = ifcMon->get(ifcSrc)->sendPkt(pkt, remoteAddr.ip, remoteAddr.port);
}
else
APP_ASSERT(0 and "No sender");
if(ret == -ERROR_NETWORK_CLOSED){
auto scheduler = dynamic_cast<scheduler::SchedulerInterface *>(parent);
if(!scheduler)
return -42;
scheduler->notifyDeadChannel(id());
}
return ret;
// else
// TODO
}
bool ChannelHandler::haveCell(){
return true;
}
appInt ChannelHandler::timeoutEvent(appTs time){
return 0;
}
//void ChannelHandler::setIfcId(appInt8 ifcSrc, appInt8 ifcDst) {
// this->ifcSrc = ifcSrc;
// this->ifcDst = ifcDst;
//}
void ChannelHandler::freePacket(Packet* pkt) {
if(pkt->header.flag&FLAG_DAT){
appFlowIdType tmp;
tmp.fingerPrint=pkt->header.fingerPrint;
tmp.flowId=pkt->header.flowId;
parent->recvAck(tmp, pkt->header.flowSeqNo);
STOP_PACKET_PROFILER_CLOCK(pkt)
}
getPacketPool().freePacket(pkt);
}
void ChannelHandler::sendFreeCellNotification() {
auto ifcSch = dynamic_cast<scheduler::SchedulerInterface *>(parent);
APP_ASSERT(ifcSch);
ifcSch->notifyFreeCell(id());
}
} //namespace channelHandler
| abhimp/Viscous | src/TunnelLib/ChannelHandler/ChannelHandler.cc | C++ | gpl-3.0 | 4,132 |
/**
*
*/
package com.mec.duke; | mectest1/HelloGUI | HelloDuke/test/com/mec/duke/package-info.java | Java | gpl-3.0 | 40 |
IQRA: Intelligent Quran Research Assistant
==========================================
The main purpose of this software is to provide a platform to enabling Mathematical analysis of the Holy Quran and to extract whatever ALLAH(SWT) permits of useful knowledge in the form of mathematical miracles confirming the authenticity of the Quran as a book of ALLAH(SWT) or mathematical proofs confirming Islamic concepts or rituals, in sha ALLAH.
Furthermore, we aim to provide a powerful search engine with many search techniques including simple search, similarity search, numerical search, statistical search and relational search, each having various options.
The above goals should be provided to end users with a very easy to use graphical user interface. Desirable feature include translation in any language, tafseer in any language, exact word meaning in any language, grammar in any language, recitation by any reciter, user-defined layouts, user-defined fonts and colors, Bookmark management and full text statistics.
Original authors: [Tariq Mahmood] (islamisoftware@gmail.com)
| islamisoftware/IQRA | README.md | Markdown | gpl-3.0 | 1,084 |
// ========================================================================================
// GRSFramework
// Copyright (C) 2016 by Gabriel Nützi <gnuetzi (at) gmail (døt) com>
//
// This Source Code Form is subject to the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version. If a copy of the GPL was not distributed with
// this file, you can obtain one at http://www.gnu.org/licenses/gpl-3.0.html.
// ========================================================================================
#ifndef GRSF_dynamics_collision_geometry_OOBB_hpp
#define GRSF_dynamics_collision_geometry_OOBB_hpp
#include "GRSF/common/Asserts.hpp"
#include "GRSF/common/TypeDefs.hpp"
#include "ApproxMVBB/OOBB.hpp"
using OOBB = ApproxMVBB::OOBB;
#endif // OOBB_hpp
| gabyx/GRSFramework | common/include/GRSF/dynamics/collision/geometry/OOBB.hpp | C++ | gpl-3.0 | 870 |
/*
* AC - A source-code copy detector
*
* For more information please visit: http://github.com/manuel-freire/ac2
*
* ****************************************************************************
*
* This file is part of AC, version 2.x
*
* AC is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* AC is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with AC. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ucm.fdi.ac.test;
import es.ucm.fdi.ac.Submission;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeMap;
/**
* This test counts the number of appearances of each token type. Distance
* is "euclidean distance" when the counters are considered as N-dimensional
* vectors.
*
* @author mfreire
*/
public class TokenCountTest extends TokenizingTest {
static final public String SUBJECT_TOKVECTOR = "tokenvector";
/** Creates a new instance of TokenCountTest */
public TokenCountTest() {
testKey = SUBJECT_TOKVECTOR;
}
/**
* All subjects will have been preprocessed before similarity is
* checked.
*/
public void preprocess(Submission s) {
super.preprocess(s);
String tokens = getTokens(s);
TreeMap<Integer, Integer> counter = new TreeMap<Integer, Integer>();
StringTokenizer st = new StringTokenizer(tokens, "\n\r\t ");
while (st.hasMoreTokens()) {
int token = tokenizer.tokenId(st.nextToken());
int count = counter.containsKey(token) ? counter.get(token) : 0;
// System.err.println(s.getId()+": incrementing "+token+" from "+count);
count = count + 1;
counter.put(token, count);
}
TreeMap<Integer, Double> normalizedCounter = new TreeMap<Integer, Double>();
int total = 0;
for (int k : counter.keySet()) {
int c = counter.get(k);
total += c * c;
}
double vectorLength = Math.sqrt(total);
for (int k : counter.keySet()) {
normalizedCounter.put(k, counter.get(k) / vectorLength);
// System.err.println("prevalence of "+k+" = "+normalizedCounter.get(k));
}
s.putData(SUBJECT_TOKVECTOR, normalizedCounter);
}
/**
* @return a number between 0 (most similar) and 1 (least similar)
*/
public float similarity(Submission sa, Submission sb) {
TreeMap<Integer, Double> ta, tb;
ta = (TreeMap<Integer, Double>) sa.getData(SUBJECT_TOKVECTOR);
tb = (TreeMap<Integer, Double>) sb.getData(SUBJECT_TOKVECTOR);
ArrayList<Integer> keys = new ArrayList<Integer>(ta.keySet());
keys.addAll(tb.keySet());
double total = 0;
double ca, cb, dk;
for (int k : keys) {
ca = ta.containsKey(k) ? ta.get(k) : 0;
cb = tb.containsKey(k) ? tb.get(k) : 0;
dk = ca - cb;
// System.err.println("ca - cb = "+ca+" - "+cb+" = "+dk);
total += dk * dk;
}
double distance = Math.sqrt(total);
// empirical overshooting, since distances tend to be much smaller than 2.0
return (float) Math.min(distance * 3, 1);
}
}
| manuel-freire/ac2 | ac-core/src/main/java/es/ucm/fdi/ac/test/TokenCountTest.java | Java | gpl-3.0 | 3,345 |
#!/usr/bin/env python3
"""Output a CSV file that can be imported to Petra"""
import os
import sys
import calendar
import csv
from csv_dict import CSVDict, CSVKeyMissing
def split_csv(table_file='Tabell.csv'):
"""Split account, cost center and project into three tables"""
account = []
cost_center = []
project = []
with open(table_file, newline='') as tablefile:
tablereader = csv.reader(tablefile, delimiter=';')
for row in tablereader:
if row[0] != '' and row[1] != '':
account.append([row[0], row[1]])
if row[3] != '' and row[4] != '':
cost_center.append([row[3], row[4]])
if row[6] != '' and row[7] != '':
project.append([row[6], row[7]])
with open('Konto.csv', 'w', newline='') as accountfile:
accountwriter = csv.writer(accountfile, delimiter=';')
for row in account:
accountwriter.writerow(row)
with open('Costcenter.csv', 'w', newline='') as ccfile:
ccwriter = csv.writer(ccfile, delimiter=';')
for row in cost_center:
ccwriter.writerow(row)
with open('Projekt.csv', 'w', newline='') as projectfile:
projectwriter = csv.writer(projectfile, delimiter=';')
for row in project:
projectwriter.writerow(row)
def _parse_trans_objects(trans):
"""
Handle an object list of a transaction.
The object list contains a cost center and project, formatted like so
['1', 'K0000', '6', 'P-00000000'].
Cost center (resultatenhet) is preceeded by a '1' and project by a '6', but the order
of the two could be reversed. Cost center always begins with 'K' and
project with 'P-'. The object list could also be empty.
Returns a tuple (cost_center, project), where any of the two could be
None in case the information is missing from the object list.
"""
cost_center = project = None
trans_it = iter(trans)
for idx in trans_it:
obj = next(trans_it)
if idx == '1' and obj.startswith('K'):
cost_center = obj
elif idx == '6' and obj.startswith('P-'):
project = obj
return (cost_center, project)
class PetraOutput:
"""Form an output file based on an SieData object and translation table"""
def __init__(self, sie_data, account_file, cost_center_file, project_file,
default_petra_cc='3200'):
self.sie_data = sie_data
self.default_petra_cc = default_petra_cc
# self.parse_tables(account_file, cost_center_file, project_file)
self.account = CSVDict(account_file)
self.cost_center = CSVDict(cost_center_file)
self.project = CSVDict(project_file)
self.table = []
self.ver_month = None
def populate_output_table(self):
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
# pylint: disable=invalid-name
"""Extract interesting informatin from the Sie data and form output"""
header = ['', 'CC', 'Account', 'Narrative', 'Reference', 'Date', 'Dt',
'Ct']
self.table.append(header)
program = self.sie_data.get_data('#PROGRAM')[0].data[0].split()[0]
verifications = self.sie_data.get_data('#VER')
ver_date = next(v.verdatum for v in verifications if v.verdatum.has_date)
self.ver_month = ver_date.format("%Y-%m")
description = "Imported from {} {}".format(program, self.ver_month)
checksum = format(sum(ver.sum_debit() for ver in verifications),
'.2f').rstrip('0').rstrip('.').replace('.',',')
day = calendar.monthrange(ver_date.year, ver_date.month)[1]
last_date_month = "{}/{:02}/{}".format(day, ver_date.month, ver_date.year)
self.table.append(['B', description, checksum, last_date_month, '', '', '',
''])
for ver in verifications:
if not ver.in_balance():
raise Exception('Inte i balans:', ver)
"""
# Contains 'Swetzén'
if ver.serie == 'A' and ver.vernr == '170071':
print(ver)
# Contains stange characters
if ver.serie == 'C' and ver.vernr == '170058':
print(ver)
# CC with 'XXXX'
if ver.serie == 'C' and ver.vernr == '170064':
print(ver)
# Rounding error?
if ver.serie == 'C' and ver.vernr == '170067':
print(ver)
"""
ref = "Visma Ver {}{}".format(ver.serie, ver.vernr)
text = "{} - {}".format(ref, ver.vertext)
date = ver.verdatum.format("%d/%m/%Y")
self.table.append(['J', text, 'GL', 'STD', 'SEK', '1', date, ''])
narr = ver.vertext # Default
for trans in ver.trans_list:
(visma_cc, visma_proj) = _parse_trans_objects(trans.objekt)
if not visma_proj or visma_proj == 'P-32000000': # Use visma_cc instead
if not visma_cc: # Use default
cc = self.default_petra_cc
else:
cc = self.cost_center[str(visma_cc)]['P_CC']
else:
cc = self.project[str(visma_proj)]['P_CC']
acct = self.account[str(trans.kontonr)]['P_Acct']
if trans.transtext and trans.kvantitet:
kvantitet = format(trans.kvantitet,
'.2f').rstrip('0').rstrip('.').replace('.',',')
narr = "{} {}".format(trans.transtext, kvantitet)
elif trans.transtext:
narr = trans.transtext
dt = trans.debit
ct = trans.credit
self.table.append(['T', cc, acct, narr, ref, date, dt, ct])
def print_output(self):
"""Print csv output to stdout"""
print("\n".join(','.join(str(r) for r in row) for row in self.table))
def write_output(self, filename=None, overwrite=False):
"""Write csv to file, abort if it already exists"""
writemode = 'w' if overwrite else 'x'
try:
for encoding in ['utf_8']:
if not filename:
filename = 'CSV/PYTHON/VtP_' + self.ver_month + encoding + '.csv'
try:
with open(filename, writemode, newline='', encoding=encoding) as csvfile:
csvwriter = csv.writer(csvfile, delimiter=';')
csvwriter.writerows(self.table)
# print("Encoding with ", encoding, "successful!")
except UnicodeEncodeError as err:
print("Encoding failed: ", err)
os.remove(filename)
except FileExistsError:
sys.exit("Kan inte skriva " + filename + ", filen finns redan.")
| jswetzen/sie-parse | petra_output.py | Python | gpl-3.0 | 6,907 |
<?php
/* DemandaBundle:Default:editDemanda.html.twig */
class __TwigTemplate_0da56489322089eadddb520cffe4e9d43e1e97bc0fddc91257b870e5c26e5f23 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("portadaDemanda.html.twig", "DemandaBundle:Default:editDemanda.html.twig", 1);
$this->blocks = array(
'cuerpo' => array($this, 'block_cuerpo'),
);
}
protected function doGetParent(array $context)
{
return "portadaDemanda.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_cuerpo($context, array $blocks = array())
{
// line 4
echo "
<div class=\"panel panel-default\">
<div class=\"panel-heading\">
<h1>
Editar Demanda
</h1>
<div class=\"col-md-12 text-center\">
<div class=\"list-group\">
<h3><small> Nombre Demanda: ";
// line 15
echo twig_escape_filter($this->env, $this->getAttribute(($context["demanda"] ?? null), "getNombre", array(), "method"), "html", null, true);
echo " </small></h3>
";
// line 16
if (((twig_first($this->env, $this->getAttribute($this->getAttribute($this->getAttribute($this->getAttribute(($context["app"] ?? null), "security", array()), "getToken", array(), "method"), "getUser", array(), "method"), "roles", array())) == "ROLE_SUPER_ADMIN") || ($this->getAttribute($this->getAttribute($this->getAttribute($this->getAttribute(($context["app"] ?? null), "security", array()), "getToken", array(), "method"), "getUser", array(), "method"), "getUsername", array(), "method") == $this->getAttribute(($context["demanda"] ?? null), "getAutor", array(), "method")))) {
// line 17
echo " <hr>
<a id=\"linkAdmin\" href=\"";
// line 18
echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("mostrarDemanda", array("idDemanda" => $this->getAttribute(($context["demanda"] ?? null), "id", array()))), "html", null, true);
echo "\" class=\"list-group-item\" > Volver a demanda: ";
echo twig_escape_filter($this->env, $this->getAttribute(($context["demanda"] ?? null), "getNombre", array(), "method"), "html", null, true);
echo " </a>
<hr>
";
}
// line 21
echo " </div>
</div>
</div>
<div class=\"panel-body\">
";
// line 26
$this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->setTheme(($context["formDemanda"] ?? null), array(0 => "bootstrap_3_layout.html.twig"));
// line 27
echo "
";
// line 28
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->renderBlock(($context["formDemanda"] ?? null), 'form_start', array("action" => $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("editDemanda"), "method" => "POST", "multipart" => "true"));
echo "
<div class=\"form-group\">
";
// line 31
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "nombre", array()), 'label');
echo "
";
// line 32
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "nombre", array()), 'errors');
echo "
";
// line 33
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "nombre", array()), 'widget', array("attr" => array("class" => "nombre")));
echo "
</div>
<div class=\"form-group\">
";
// line 37
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "descripcion", array()), 'label');
echo "
";
// line 38
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "descripcion", array()), 'errors');
echo "
";
// line 39
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "descripcion", array()), 'widget', array("attr" => array("class" => "descripcion")));
echo "
</div>
<div class=\"form-group\">
";
// line 43
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "condiciones", array()), 'label');
echo "
";
// line 44
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "condiciones", array()), 'errors');
echo "
";
// line 45
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "condiciones", array()), 'widget', array("attr" => array("class" => "condiciones")));
echo "
</div>
<div class='col-md-6'>
<div class=\"form-group\">
";
// line 50
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "fechaInicio", array()), 'label');
echo "
";
// line 51
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "fechaInicio", array()), 'widget', array("attr" => array("class" => "datepicker")));
echo "
</div>
</div>
<div class='col-md-6'>
<div class=\"form-group\">
";
// line 57
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "fechaFin", array()), 'label');
echo "
";
// line 58
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "fechaFin", array()), 'widget', array("attr" => array("class" => "datepicker")));
echo "
</div>
</div>
<div class=\"form-group\">
";
// line 63
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "contacto", array()), 'errors');
echo "
";
// line 64
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "contacto", array()), 'label');
echo "
";
// line 65
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "contacto", array()), 'widget', array("attr" => array("class" => "contacto")));
echo "
</div>
<div class=\"form-group\">
<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"200000\"/>
<input name=\"uploadedfile\" type=\"file\" accept=\"png\" />
";
// line 71
if (array_key_exists("mensaje", $context)) {
// line 72
echo " <span> ";
echo twig_escape_filter($this->env, ($context["mensaje"] ?? null), "html", null, true);
echo " </span>
";
}
// line 74
echo " </div>
<div class=\"form-group\">
";
// line 77
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "area", array()), 'label');
echo "
";
// line 78
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "area", array()), 'errors');
echo "
";
// line 79
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "area", array()), 'widget');
echo "
</div>
<div class=\"form-group\">
";
// line 83
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "rama", array()), 'label');
echo "
";
// line 84
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "rama", array()), 'errors');
echo "
";
// line 85
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "rama", array()), 'widget');
echo "
</div>
<div class=\"form-group\">
";
// line 89
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "disciplina", array()), 'label');
echo "
";
// line 90
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "disciplina", array()), 'errors');
echo "
";
// line 91
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "disciplina", array()), 'widget');
echo "
</div>
<div class=\"form-group\">
";
// line 95
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "tipo", array()), 'label');
echo "
";
// line 96
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "tipo", array()), 'errors');
echo "
";
// line 97
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->searchAndRenderBlock($this->getAttribute(($context["formDemanda"] ?? null), "tipo", array()), 'widget');
echo "
</div>
<br>
<br>
";
// line 104
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\FormExtension')->renderer->renderBlock(($context["formDemanda"] ?? null), 'form_end');
echo "
<br>
<br>
<br>
<br>
<script>
\$(\"#form_area\").change(function() {
var data = {
area_id: \$(this).val()
};
\$.ajax({
type: 'post',
url: '";
// line 119
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("select_rama");
echo "',
data: data,
success: function(data,url) {
var \$rama_selector = \$('#form_rama');
var \$disciplina_selector = \$('#form_disciplina');
\$disciplina_selector.html('<option value= > </option>');
\$rama_selector.html('<option value=\"' + data[0].toString() + '\">' + data[1].toString() + '</option>');
for (var i = 2, total = data.length; i < total;) {
\$rama_selector.append('<option value=\"' + data[i] + '\">' + data[i+1] + '</option>');
i=i+2;
}
}
});
});
\$(\"#form_rama\").change(function() {
var data = {
rama_id: \$(this).val()
};
\$.ajax({
type: 'post',
url: '";
// line 140
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("select_disciplina");
echo "',
data: data,
success: function(data,url) {
var \$rama_selector = \$('#form_disciplina');
\$rama_selector.html('<option value=\"' + data[0].toString() + '\">' + data[1].toString() + '</option>');
for (var i = 2, total = data.length; i < total;) {
\$rama_selector.append('<option value=\"' + data[i] + '\">' + data[i+1] + '</option>');
i=i+2;
}
}
});
});
</script>
";
// line 155
if ((null === $this->getAttribute(($context["demanda"] ?? null), "disciplina", array()))) {
// line 156
echo " <script>
var \$disciplina_selector = \$('#form_disciplina');
\$disciplina_selector.html('<option value= > </option>');
</script>
";
}
// line 161
echo "
<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css\" />
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment-with-locales.js\"></script>
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js\"></script>
<script src=\"";
// line 168
echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("js/selectFecha.js"), "html", null, true);
echo "\"></script>
</div>
</div>
</div>
";
}
public function getTemplateName()
{
return "DemandaBundle:Default:editDemanda.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 321 => 168, 312 => 161, 305 => 156, 303 => 155, 285 => 140, 261 => 119, 243 => 104, 233 => 97, 229 => 96, 225 => 95, 218 => 91, 214 => 90, 210 => 89, 203 => 85, 199 => 84, 195 => 83, 188 => 79, 184 => 78, 180 => 77, 175 => 74, 169 => 72, 167 => 71, 158 => 65, 154 => 64, 150 => 63, 142 => 58, 138 => 57, 129 => 51, 125 => 50, 117 => 45, 113 => 44, 109 => 43, 102 => 39, 98 => 38, 94 => 37, 87 => 33, 83 => 32, 79 => 31, 73 => 28, 70 => 27, 68 => 26, 61 => 21, 53 => 18, 50 => 17, 48 => 16, 44 => 15, 31 => 4, 28 => 3, 11 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("", "DemandaBundle:Default:editDemanda.html.twig", "/home/ubuntu/Escritorio/todo/TFG-LRR2/src/DemandaBundle/Resources/views/Default/editDemanda.html.twig");
}
}
| lorenmanu/TFG-GESTION-OFERTAS-DEMANDAS | app/cache/prod/twig/49/49faf420e0f70ff6260bd07d45a7e732e5935287ce85ee99dc8ce92c78632a47.php | PHP | gpl-3.0 | 17,515 |
/*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#include "Object.h"
struct CoordsXY;
enum TERRAIN_SURFACE_FLAGS
{
NONE = 0,
SMOOTH_WITH_SELF = 1 << 0,
SMOOTH_WITH_OTHER = 1 << 1,
CAN_GROW = 1 << 2,
};
class TerrainSurfaceObject final : public Object
{
private:
struct SpecialEntry
{
uint32_t Index{};
int32_t Length{};
int32_t Rotation{};
int32_t Variation{};
bool Grid{};
bool Underground{};
};
static constexpr auto NUM_IMAGES_IN_ENTRY = 19;
public:
rct_string_id NameStringId{};
uint32_t IconImageId{};
uint32_t PatternBaseImageId{};
uint32_t EntryBaseImageId{};
uint32_t NumEntries{};
uint32_t DefaultEntry{};
uint32_t DefaultGridEntry{};
uint32_t DefaultUndergroundEntry{};
std::vector<SpecialEntry> SpecialEntries;
std::vector<uint32_t> SpecialEntryMap;
colour_t Colour{};
uint8_t Rotations{};
money32 Price{};
TERRAIN_SURFACE_FLAGS Flags{};
explicit TerrainSurfaceObject(const rct_object_entry& entry)
: Object(entry)
{
}
void ReadJson(IReadObjectContext* context, json_t& root) override;
void Load() override;
void Unload() override;
void DrawPreview(rct_drawpixelinfo* dpi, int32_t width, int32_t height) const override;
uint32_t GetImageId(
const CoordsXY& position, int32_t length, int32_t rotation, int32_t offset, bool grid, bool underground) const;
};
| AaronVanGeffen/OpenRCT2 | src/openrct2/object/TerrainSurfaceObject.h | C | gpl-3.0 | 1,857 |
// Arrays contendo os elementos editados
var editedElements = [];
var selectedElementIndex = null;
var unsavedChanges = false;
function updateIframeMinHeight() {
var iframe = $('#app-tool-iframe');
var container = $('#app-iframe-container');
if (container.height() > iframe.height())
iframe.css('min-height', container.height());
return;
}
// Atualiza o texto do elemento selecionado no editor
function updateSelectedElement(element) {
var target = $('#app-selected-element-text');
var containerID = 'app-selected-element-text';
var selectedID = 'app-tool-preview-card-li-selected';
if (!element)
element = 'nenhum';
target.replaceWith('<span id="' + containerID + '">' + element + '</span>');
$('[data-selector="' + target.text() + '"]').parent().removeClass(selectedID);
$('[data-selector="' + element + '"]').parent().addClass(selectedID);
if (!$('#app-editor-controls').is(":visible")) {
$('#app-editor-greeting').slideToggle(250);
$('#app-editor-controls').slideToggle(250);
}
if (selectedElementIndex) {
enableUnsavedChangesWarning();
saveEditedElement(selectedElementIndex);
}
checkEditedElements(element);
return;
}
// Mostra/oculta overlay do elemento selecionado no iFrame
function showSelectionOverlay(element, visible) {
var iframe = $('#app-tool-iframe');
var overlay = 'app-tool-iframe-css-overlay';
// Injeta estilo do overlay dentro do iframe se ainda não existir
if (!iframe.contents().find('#' + overlay).length) {
iframe.contents().find('html').append('\
<style id="' + overlay + '"> .' + overlay + ' {\n\
background-color: rgba(255, 110, 64, 0.5) !important;\n\
} </style>');
}
if (visible)
iframe.contents().find(element).addClass(overlay);
else
iframe.contents().find(element).removeClass(overlay);
return;
}
// Adiciona elemento na lista de seletores e define os eventos do mouse
// Se o elemento já existe na lista de seletores, nada acontece
function addElementToTagList(element) {
if (!$('[data-selector="' + element + '"]').length) {
$('#app-tool-tag-container').append(
'<li class="app-tool-preview-card-li"><a href="#" data-selector="' +
element + '">' + element + '</a></li>');
var newElement = $('[data-selector="' + element + '"]');
newElement.click(function () {
updateSelectedElement(element);
});
newElement.mouseover(function () {
showSelectionOverlay(element, true);
});
newElement.mouseout(function () {
showSelectionOverlay(element, false);
});
}
return;
}
// Recebe uma string contendo um ou mais elementos (ex. várias classes ou IDs)
// e um prefixo e adiciona cada classe/ID individual na lista de elementos
function addMultipleElementToTagList(prefix, element) {
if (!prefix)
prefix = '';
if (element) {
if (String(element).indexOf(' ') !== -1) {
var tmp = String(element).split(' ');
for (var i = 0; i < tmp.length; i++) {
addElementToTagList(prefix + tmp[i]);
}
} else {
addElementToTagList(prefix + element);
}
}
return;
}
// Chama função ao redimensionar a janela
$(window).resize(updateIframeMinHeight);
// Escaneia e adiciona todos os elementos do iframe
// na lista de seletores ao carregar a página
$(document).ready(function () {
$('#app-tool-tag-container').css('max-height', $(window).height() * 0.65);
$('#app-tool-iframe').on('load', function () {
$('#app-tool-iframe').contents().find('*').each(function () {
addElementToTagList($(this).prop("nodeName").toLowerCase());
addMultipleElementToTagList('.', $(this).attr('class'));
addMultipleElementToTagList('#', $(this).attr('id'));
});
});
});
function enableUnsavedChangesWarning() {
if (!unsavedChanges) {
$(window).on('beforeunload', function () {
return 'Suas alterações serão perdidas!';
});
unsavedChanges = true;
}
return;
}
function loadElementIntoEditor(i) {
clearEditor();
updateMDLInput($('#margin'), editedElements[i].margin);
updateMDLInput($('#border'), editedElements[i].border);
updateMDLInput($('#padding'), editedElements[i].padding);
updateMDLInput($('#z-index'), editedElements[i].zindex);
updateMDLInput($('#left'), editedElements[i].left);
updateMDLInput($('#right'), editedElements[i].right);
updateMDLInput($('#top'), editedElements[i].top);
updateMDLInput($('#bottom'), editedElements[i].bottom);
updateMDLInput($('#width'), editedElements[i].width);
updateMDLInput($('#height'), editedElements[i].height);
updateMDLInput($('#min-width'), editedElements[i].minwidth);
updateMDLInput($('#min-height'), editedElements[i].minheight);
updateMDLInput($('#max-width'), editedElements[i].maxwidth);
updateMDLInput($('#max-height'), editedElements[i].maxheight);
updateMDLInput($('#background-image'), editedElements[i].backgroundimage);
updateMDLInput($('#background-color'), editedElements[i].backgroundcolor);
updateMDLInput($('#color'), editedElements[i].color);
updateMDLInput($('#font-family'), editedElements[i].fontfamily);
updateMDLInput($('#font-size'), editedElements[i].fontsize);
updateMDLInput($('#font-weight'), editedElements[i].fontweight);
updateMDLRadio('position', editedElements[i].position);
updateMDLRadio('overflow', editedElements[i].overflow);
updateMDLRadio('background-repeat', editedElements[i].backgroundrepeat);
updateMDLRadio('font-style', editedElements[i].fontstyle);
updateMDLRadio('text-align', editedElements[i].textalign);
updateMDLRadio('text-decoration', editedElements[i].textdecoration);
if (editedElements[i].fontvariant == 'small-caps') {
$('#small-caps').prop('checked', true);
$('#small-caps').parent().addClass('is-checked');
}
}
function saveEditedElement(i) {
editedElements[i].margin = $('#margin').val();
editedElements[i].border = $('#border').val();
editedElements[i].padding = $('#padding').val();
editedElements[i].zindex = $('#z-index').val();
editedElements[i].left = $('#left').val();
editedElements[i].right = $('#right').val();
editedElements[i].top = $('#top').val();
editedElements[i].bottom = $('#bottom').val();
editedElements[i].width = $('#width').val();
editedElements[i].height = $('#height').val();
editedElements[i].minwidth = $('#min-width').val();
editedElements[i].minheight = $('#min-height').val();
editedElements[i].maxwidth = $('#max-width').val();
editedElements[i].maxheight = $('#max-height').val();
editedElements[i].backgroundimage = $('#background-image').val();
editedElements[i].backgroundcolor = $('#background-color').val();
editedElements[i].color = $('#color').val();
editedElements[i].fontfamily = $('#font-family').val();
editedElements[i].fontsize = $('#font-size').val();
editedElements[i].fontweight = $('#font-weight').val();
editedElements[i].position = $('input[name=position]:checked').val();
editedElements[i].overflow = $('input[name=overflow]:checked').val();
editedElements[i].backgroundrepeat = $('input[name=background-repeat]:checked').val();
editedElements[i].fontstyle = $('input[name=font-style]:checked').val();
editedElements[i].textalign = $('input[name=text-align]:checked').val();
editedElements[i].textdecoration = $('input[name=text-decoration]:checked').val();
}
function checkEditedElements(selector) {
var index = null;
for (var i = 0; i < editedElements.length; i++)
{
if (editedElements[i].id == selector) {
selectedElementIndex = i;
loadElementIntoEditor(i);
return;
}
}
var newElement = {id: selector, margin: '', border: '', padding: '', zindex: '',
left: '', right: '', top: '', bottom: '', width: '', height: '', minwidth: '',
minheight: '', maxwidth: '', maxheight: '', backgroundcolor: '', backgroundimage: '',
color: '', fontfamilly: '', fontsize: '', fontweight: '', position: '', overflow: '',
backgroundrepeat: '', fontstyle: '', textalign: '', textdecoration: '', fontvariant: ''};
index = editedElements.push(newElement);
selectedElementIndex = index - 1;
loadElementIntoEditor(index - 1);
return;
}
// Atualiza o valor do campo informado
function updateMDLInput(element, value) {
if (value) {
element.val(String(value));
element.parent().addClass('is-dirty');
}
return;
}
// Seleciona botão no grupo de acordo com o valor informado
function updateMDLRadio(group, value) {
var target;
if (value) {
switch (group) {
case 'position':
if (value == 'initial')
target = $('#initial_p');
else
target = $('#' + value);
break;
case 'overflow':
if (value == 'initial')
target = $('#initial_d');
else
target = $('#' + value);
break;
case 'background-repeat':
if (value == 'initial')
target = $('#initial_b');
else
target = $('#' + value);
break;
case 'font-style':
if (value == 'initial')
target = $('#initial_f0');
else
target = $('#' + value);
break;
case 'text-align':
if (value == 'initial')
target = $('#initial_f1');
else if (value == 'left')
target = $('#left_f');
else if (value == 'right')
target = $('#right_f');
else
target = $('#' + value);
break;
case 'text-decoration':
// Em navegadores recentes, o campo text-decoration contém o valor combinado
// dos atributos text-decoration-line, text-decoration-color e text-decoration-style,
// então verificamos e dividimos a string antes de definir o target, se necessário
if (String(value).indexOf(' ') !== -1) {
var tmp = String(value).split(' ');
value = tmp[0];
}
if (value == 'initial')
target = $('#initial_f2');
else
target = $('#' + value);
break;
}
target.prop('checked', true);
target.parent().addClass('is-checked');
}
return;
}
function clearEditor() {
// Aba Posição
var inputElements = '#margin #border #padding #z-index #left #right #top #bottom ';
// Aba Dimensões
inputElements = inputElements.concat('#width #height #min-width #min-height #max-width #max-height ');
// Aba Preenchimento
inputElements = inputElements.concat('#background-image ');
// Aba Texto
inputElements = inputElements.concat('#font-family #font-size #font-weight ');
var tmp = String(inputElements).split(' ');
for (var i = 0; i < tmp.length; i++) {
$(tmp[i]).val('');
$(tmp[i]).parent().removeClass('is-dirty');
}
$('input:radio').parent().removeClass('is-checked');
$('input:checkbox').parent().removeClass('is-checked');
$('input:radio').removeAttr('checked');
$('input:checkbox').removeAttr('checked');
$('#background-color').val('#000000');
$('#app-button-background-color').prop('disabled', true);
$('#color').val('#000000');
$('#app-button-color').prop('disabled', true);
return;
}
/*
$('#color').on('input propertychange', function () {
$('#app-button-color').prop('disabled', false);
});
$('#background-color').change(function () {
$('#app-button-background-color').prop('disabled', false);
});
$('#app-button-color').click(function () {
alert('trigger');
$('#color').val('#000000');
$('#app-button-color').prop('disabled', true);
});
$('#app-button-background-color').click(function () {
$('#background-color').val('#000000');
$('#app-button-background-color').prop('disabled', true);
});
*/
function editorBackButton() {
window.location = '?url=index';
return;
}
| mbc07/css-tool | View/assets/js/tool.js | JavaScript | gpl-3.0 | 12,674 |
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package coop.tecso.grs.page;
import coop.tecso.grs.GrsMap;
/**
*
* @author Andrei
*
*/
public class PageInputTextarea extends PageTagImp {
// Events Constants
public static final String ONCHANGE_EVENT = "onchange";
// HTML TextArea Constants
public static final String ROWS_ATTRIBUTE = "rows";
public static final String COLS_ATTRIBUTE = "cols";
public static final String READONLY_ATTRIBUTE = "readonly";
public static final String DISABLED_ATTRIBUTE = "disabled";
// HTML Input Constants
public static final String NAME_ATTRIBUTE = "name";
public static final String TAG_NAME = "textarea";
// Variables
private String name = "";
private String readOnly = "";
private String rows = "";
private String cols = "";
private String disabled = "";
private String value = "";
private String onChange = "";
// Constructor
public PageInputTextarea(GrsPageContext context, GrsMap map) {
this.id = Page.toString(map,"name");
this.style = Page.toString(map,"style");
this.name = Page.toString(map,"name");
this.disabled = Page.toString(map,"disabled");
this.rows = Page.toString(map,"rows");
this.cols = Page.toString(map,"cols");
this.readOnly = Page.toString(map,"readOnly");
this.value= Page.toString(map,"value");
}
// Implemented Methods
public String tag() {
StringBuilder sb = new StringBuilder();
sb.append("<").append(TAG_NAME).append(" ");
sb.append(attribute(ID_ATTRIBUTE, id));
sb.append(attribute(STYLE_ATTRIBUTE, style));
sb.append(attribute(NAME_ATTRIBUTE, name));
if("true".equals(disabled)) sb.append(DISABLED_ATTRIBUTE).append(" ");
if("true".equals(readOnly)) sb.append(READONLY_ATTRIBUTE).append(" ");
sb.append(attribute(COLS_ATTRIBUTE,cols));
sb.append(attribute(ROWS_ATTRIBUTE,rows));
sb.append(">");
return sb.toString();
}
public String content() {
return value;
}
public String end() {
return "</" + TAG_NAME + ">";
}
// Getter&Setters
public void setOnChange(String onChange) {
this.onChange = onChange;
}
public String getOnChange() {
return onChange;
}
}
| avdata99/SIAT | siat-1.0-SOURCE/src/tools/grs/src/coop/tecso/grs/page/PageInputTextarea.java | Java | gpl-3.0 | 2,350 |
/*
* Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org>
*
* This file is part of OpenPnP.
*
* OpenPnP 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 of the
* License, or (at your option) any later version.
*
* OpenPnP 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 OpenPnP. If not, see
* <http://www.gnu.org/licenses/>.
*
* For more information about OpenPnP visit http://openpnp.org
*/
package org.openpnp.spi;
import java.io.Closeable;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.openpnp.model.Location;
import com.google.common.util.concurrent.FutureCallback;
/**
* Machine represents the pick and place machine itself. It provides the information and interface
* needed to cause the machine to do work. A Machine has one or more Heads. Unless otherwise noted,
* the methods in this class block while performing their operations.
*/
public interface Machine extends WizardConfigurable, PropertySheetHolder, Closeable {
/**
* Gets all active heads on the machine.
*
* @return
*/
public List<Head> getHeads();
public Head getHead(String id);
/**
* Gets a List of Signalers attached to the Machine.
*
* @return
*/
public List<Signaler> getSignalers();
public Signaler getSignaler(String id);
public Signaler getSignalerByName(String name);
/**
* Gets a List of Feeders attached to the Machine.
*
* @return
*/
public List<Feeder> getFeeders();
public Feeder getFeeder(String id);
public Feeder getFeederByName(String name);
/**
* Gets a List of Cameras attached to the Machine that are not attached to Heads.
*
* @return
*/
public List<Camera> getCameras();
public Camera getCamera(String id);
/**
* Get a list of Actuators that are attached to this Machine and not to a Head.
*
* @return
*/
public List<Actuator> getActuators();
/**
* Get the Actuator attached to this Machine and not to a Head that has the specified id.
*
* @param id
* @return
*/
public Actuator getActuator(String id);
public Actuator getActuatorByName(String name);
/**
* Commands all Heads to move to their home positions and reset their current positions to
* 0,0,0,0. Depending on the head configuration of the machine the home positions may not all be
* the same but the end result should be that any head commanded to move to a certain position
* will end up in the same position.
*/
public void home() throws Exception;
/**
* Returns whether the Machine is currently ready for commands.
*/
public boolean isEnabled();
/**
* Attempts to bring the Machine to a ready state or attempts to immediately stop it depending
* on the value of enabled.
*
* If true, this would include turning on motor drivers, turning on compressors, resetting
* solenoids, etc. If the Machine is unable to become ready for any reason it should throw an
* Exception explaining the reason. This method should block until the Machine is ready.
*
* After this method is called successfully, isEnabled() should return true unless the Machine
* encounters some error.
*
* If false, stops the machine and disables it as soon as possible. This may include turning off
* power to motors and stopping compressors. It is expected that the machine may need to be
* re-homed after this is called.
*
* If the Machine cannot be stopped for any reason, this method may throw an Exception
* explaining the reason but this should probably only happen in very extreme cases. This method
* should effectively be considered a software emergency stop. After this method returns,
* isEnabled() should return false until setEnabled(true) is successfully called again.
*/
public void setEnabled(boolean enabled) throws Exception;
public void addListener(MachineListener listener);
public void removeListener(MachineListener listener);
public List<Class<? extends Feeder>> getCompatibleFeederClasses();
public List<Class<? extends Camera>> getCompatibleCameraClasses();
public List<Class<? extends Nozzle>> getCompatibleNozzleClasses();
public List<Class<? extends Actuator>> getCompatibleActuatorClasses();
public void addFeeder(Feeder feeder) throws Exception;
public void removeFeeder(Feeder feeder);
public void addCamera(Camera camera) throws Exception;
public void removeCamera(Camera camera);
public void addActuator(Actuator actuator) throws Exception;
public void removeActuator(Actuator actuator);
public PnpJobProcessor getPnpJobProcessor();
public PasteDispenseJobProcessor getPasteDispenseJobProcessor();
public Future<Object> submit(Runnable runnable);
public <T> Future<T> submit(Callable<T> callable);
public <T> Future<T> submit(final Callable<T> callable, final FutureCallback<T> callback);
/**
* Submit a task to be run with access to the Machine. This is the primary entry point into
* executing any blocking operation on the Machine. If you are doing anything that results in
* the Machine doing something it should happen here.
*
* Tasks can be cancelled and interrupted via the returned Future. Tasks which operate in a loop
* should check Thread.currentThread().isInterrupted().
*
* When a task begins the MachineListeners are notified with machineBusy(true). When the task
* ends, if there are no more tasks to run then machineBusy(false) is called.
*
* TODO: When any task is running the driver for the machine is locked and any calls to the
* driver outside of the task will throw an Exception.
*
* If any tasks throws an Exception then all queued future tasks are cancelled.
*
* If a task includes a callback the callback is executed before the next task begins.
*
* TODO: By supplying a tag you can guarantee that there is only one of a certain type of task
* queued. Attempting to queue another task with the same tag will return null and the task will
* not be queued.
*
* @param callable
* @param callback
* @param ignoreEnabled True if the task should execute even if the machine is not enabled. This
* is specifically for enabling the machine and should not typically be used elsewhere.
*/
public <T> Future<T> submit(final Callable<T> callable, final FutureCallback<T> callback,
boolean ignoreEnabled);
public Head getDefaultHead() throws Exception;
public PartAlignment getPartAlignment();
public FiducialLocator getFiducialLocator();
public Location getDiscardLocation();
public void setSpeed(double speed);
public double getSpeed();
public Object getProperty(String name);
public void setProperty(String name, Object value);
}
| fca1/openpnp | src/main/java/org/openpnp/spi/Machine.java | Java | gpl-3.0 | 7,457 |
#pragma once
/*
* Copyright 2010-2016 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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 of the License, or
* (at your option) any later version.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../Engine/State.h"
#include <vector>
#include "SoldierSortUtil.h"
namespace OpenXcom
{
class TextButton;
class Window;
class Text;
class TextList;
class ComboBox;
class Base;
class Soldier;
template <typename TagType> class TaggedText;
struct SortFunctor;
/**
* Soldiers screen that lets the player
* manage all the soldiers in a base.
*/
class SoldiersState : public State
{
private:
TextButton *_btnOk, *_btnPsiTraining, *_btnTraining, *_btnMemorial, *_btnStats, *_btnRoles;
Window *_window;
Text *_txtTitle, *_txtName, *_txtRank, *_txtCraft;
ComboBox *_cbxSortBy;
TextList *_lstSoldiers;
Base *_base;
std::vector<Soldier *> _origSoldierOrder;
std::vector<SortFunctor *> _sortFunctors;
getStatFn_t _dynGetter;
//TextList *_lstSoldierStats;
TaggedText<int> *_txtTU, *_txtStamina, *_txtHealth, *_txtBravery, *_txtReactions, *_txtFiring,
*_txtThrowing, *_txtMelee, *_txtStrength, *_txtPsiStrength, *_txtPsiSkill;
Text *_txtTooltip;
std::string _currentTooltip;
bool _showStats, _showPsi;
///initializes the display list based on the craft soldier's list and the position to display
void initList(size_t scrl);
public:
/// Creates the Soldiers state.
SoldiersState(Base *base);
/// Cleans up the Soldiers state.
~SoldiersState();
/// Handler for changing the sort by combobox.
void cbxSortByChange(Action *action);
/// Updates the soldier names.
void init();
/// Handler for clicking the Soldiers reordering button.
void lstItemsLeftArrowClick(Action *action);
/// Moves a soldier up.
void moveSoldierUp(Action *action, unsigned int row, bool max = false);
/// Handler for clicking the Soldiers reordering button.
void lstItemsRightArrowClick(Action *action);
/// Moves a soldier down.
void moveSoldierDown(Action *action, unsigned int row, bool max = false);
/// Handler for clicking the OK button.
void btnOkClick(Action *action);
/// Handler for clicking the Psi Training button.
void btnPsiTrainingClick(Action *action);
void btnTrainingClick(Action *action);
/// Handler for clicking the Memorial button.
void btnMemorialClick(Action *action);
/// Handler for clicking the Inventory button.
void btnInventoryClick(Action *action);
/// Handler for clicking the Soldiers list.
void lstSoldiersClick(Action *action);
/// Handler for displaying tooltips.
void txtTooltipIn(Action *action);
/// Handler for hiding tooltips.
void txtTooltipOut(Action *action);
/// Handler for toggling the stats list.
void btnToggleStatsClick(Action *action);
/// Handler for sortable column headers.
void txtColumnHeaderClick(Action *action);
};
}
| Darineth/OpenXcom | src/Basescape/SoldiersState.h | C | gpl-3.0 | 3,338 |
/**
* Copyright (c) 2010-2014, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.stiebelheatpump.protocol;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.RXTXPort;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.concurrent.TimeoutException;
public class Connection {
private final String serialPortName;
private SerialPort serialPort;
/** baud rate of serial port */
private int baudRate;
private int timeout = 5000;
private DataOutputStream os;
private DataInputStream is;
private static final int INPUT_BUFFER_LENGTH = 1024;
private byte[] buffer = new byte[INPUT_BUFFER_LENGTH];
public static byte ESCAPE = (byte) 0x10;
public static byte HEADERSTART = (byte) 0x01;
public static byte END = (byte) 0x03;
public static byte GET = (byte) 0x00;
public static byte SET = (byte) 0x80;
public static byte STARTCOMMUNICATION = (byte) 0x02;
public static byte[] FOOTER = { ESCAPE, END };
public static byte[] DATAAVAILABLE = { ESCAPE, STARTCOMMUNICATION };
public static byte VERSIONREQUEST = (byte) 0xfd;
public static byte VERSIONCHECKSUM = (byte) 0xfe;
public static byte[] REQUESTMESSAGE = { HEADERSTART,GET,VERSIONCHECKSUM,VERSIONREQUEST,ESCAPE,END };
private static final Charset charset = Charset.forName("US-ASCII");
private static final int SLEEP_INTERVAL = 100;
/**
* Creates a Connection object. You must call <code>connect()</code> before calling <code>read()</code> in order to
* read data. The timeout is set by default to 5s.
*
* @param serialPort
* examples for serial port identifiers are on Linux "/dev/ttyS0" or "/dev/ttyUSB0" and on Windows "COM1"
*/
public Connection(String serialPort) {
if (serialPort == null) {
throw new IllegalArgumentException("serialPort may not be NULL");
}
serialPortName = serialPort;
}
/**
* Creates a Connection object. You must call <code>connect()</code> before calling <code>read()</code> in order to
* read data. The timeout is set by default to 5s.
*
* @param serialPort
* examples for serial port identifiers are on Linux "/dev/ttyS0" or "/dev/ttyUSB0" and on Windows "COM1"
*/
public Connection(String serialPort, int baudrate) {
if (serialPort == null) {
throw new IllegalArgumentException("serialPort may not be NULL");
}
this.serialPortName = serialPort;
this.baudRate = baudrate;
}
/**
* Sets the maximum time in ms to wait for new data from the remote device. A timeout of zero is interpreted as an
* infinite timeout.
*
* @param timeout
* the maximum time in ms to wait for new data.
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* Returns the timeout in ms.
*
* @return the timeout in ms.
*/
public int getTimeout() {
return timeout;
}
/**
* Opens the serial port associated with this connection.
*
* @throws IOException
* if any kind of error occurs opening the serial port.
*/
public void connect() throws IOException {
CommPortIdentifier portIdentifier;
try {
portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
} catch (NoSuchPortException e) {
throw new IOException("Serial port with given name does not exist", e);
}
if (portIdentifier.isCurrentlyOwned()) {
throw new IOException("Serial port is currently in use.");
}
RXTXPort commPort;
try {
commPort = portIdentifier.open(this.getClass().getName(), 2000);
} catch (PortInUseException e) {
throw new IOException("Serial port is currently in use.", e);
}
if (!(commPort instanceof SerialPort)) {
commPort.close();
throw new IOException("The specified CommPort is not a serial port");
}
serialPort = (SerialPort) commPort;
// Set the parameters of the connection.
setSerialPortParameters(baudRate);
try {
os = new DataOutputStream(serialPort.getOutputStream());
is = new DataInputStream(serialPort.getInputStream());
} catch (IOException e) {
serialPort.close();
serialPort = null;
throw new IOException("Error getting input or output or input stream from serial port", e);
}
}
/**
* Closes the serial port.
*/
public void disconnect() {
if (serialPort != null) {
try {
// close the i/o streams.
os.close();
is.close();
} catch (IOException ex) {
// don't care
}
// Close the port.
serialPort.close();
serialPort = null;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
/**
* Requests the firmware version from the stiebel heat pump using serial connection.
*
* @return A version string.
*
* @throws IOException
* if any kind of error other than timeout occurs while trying to read the remote device. Note that the
* connection is not closed when an IOException is thrown.
* @throws TimeoutException
* if no response at all (not even a single byte) was received from the meter within the timeout span.
*/
public String readVersion() throws IOException, TimeoutException {
if (serialPort == null) {
throw new IllegalStateException("Connection is not open.");
}
if(!startCommunication()){
return "No version";
}
short myNumber = getVersionInfo();
return String.valueOf(myNumber);
}
private short getVersionInfo() throws IOException {
// send version request
for (byte abyte : REQUESTMESSAGE){
os.write(abyte);
}
os.flush();
boolean readSuccessful = false;
int numBytesReadTotal = 0;
int timeval = 0;
// receive data are available "0x10 0x02"
while (timeout == 0 || timeval < timeout) {
if (is.available() > 0) {
int numBytesRead = is.read(buffer, numBytesReadTotal, INPUT_BUFFER_LENGTH - numBytesReadTotal);
numBytesReadTotal += numBytesRead;
if (numBytesRead > 0) {
timeval = 0;
}
if (numBytesReadTotal > 1 && buffer[numBytesReadTotal-1] == STARTCOMMUNICATION) {
readSuccessful = true;
break;
}
}
try {
Thread.sleep(SLEEP_INTERVAL);
} catch (InterruptedException e) {
}
timeval += SLEEP_INTERVAL;
}
if (!readSuccessful) {
throw new IOException("Did not receive any data available message !");
}
if (numBytesReadTotal != 2) {
throw new IOException("Data available message does not have length of 2!");
}
// send acknowledgment
os.write(ESCAPE);
os.flush();
readSuccessful = false;
numBytesReadTotal = 0;
timeval = 0;
buffer = new byte[INPUT_BUFFER_LENGTH];
// receive version information
while (timeout == 0 || timeval < timeout) {
if (is.available() > 0) {
int numBytesRead = is.read(buffer, numBytesReadTotal, INPUT_BUFFER_LENGTH - numBytesReadTotal);
numBytesReadTotal += numBytesRead;
if (numBytesRead > 0) {
timeval = 0;
}
if (numBytesReadTotal == 8 && buffer[numBytesReadTotal-1] == END) {
readSuccessful = true;
break;
}
}
try {
Thread.sleep(SLEEP_INTERVAL);
} catch (InterruptedException e) {
}
timeval += SLEEP_INTERVAL;
}
if (!readSuccessful) {
throw new IOException("Did not receive version info !");
}
if (numBytesReadTotal != 8) {
throw new IOException("Data available message does not have length of 8!");
}
if (buffer[numBytesReadTotal - 1] != END && buffer[numBytesReadTotal - 2] != ESCAPE) {
throw new IOException("Data message does not have footer!");
}
ByteBuffer versionBytes = ByteBuffer.wrap(buffer);
short myNumber = (short) versionBytes.getShort(4);
return myNumber;
}
private boolean startCommunication() throws IOException, TimeoutException {
boolean readSuccessful;
int numBytesReadTotal;
os.write(STARTCOMMUNICATION);
os.flush();
readSuccessful = false;
int timeval = 0;
numBytesReadTotal = 0;
while (timeout == 0 || timeval < timeout) {
if (is.available() > 0) {
int numBytesRead = is.read(buffer, numBytesReadTotal, INPUT_BUFFER_LENGTH - numBytesReadTotal);
numBytesReadTotal += numBytesRead;
if (numBytesRead > 0) {
timeval = 0;
}
if (buffer[0] == ESCAPE ) {
readSuccessful = true;
break;
}
}
try {
Thread.sleep(SLEEP_INTERVAL);
} catch (InterruptedException e) {
}
timeval += SLEEP_INTERVAL;
}
int offset = 0;
if (numBytesReadTotal == offset) {
throw new TimeoutException();
}
if (!readSuccessful) {
throw new IOException("Timeout while listening for Identification Message");
}
if (buffer[0] == ESCAPE){
System.out.println("Stiebel heatpump serial port ready for request.");
}else{
System.out.println("Stiebel heatpump serial port could not be connected with start communication request!");
}
return readSuccessful;
}
/**
* Sets the serial port parameters to xxxxbps-8N1
*
* @param baudrate
* used to initialize the serial connection
*/
protected void setSerialPortParameters(int baudrate) throws IOException {
try {
// Set serial port to xxxbps-8N1
serialPort.setSerialPortParams(baudRate,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException ex) {
throw new IOException(
"Unsupported serial port parameter for serial port");
}
}
}
| kreutpet/stiebelheatpump | org.stiebelheatpump/src/org/stiebelheatpump/protocol/Connection.java | Java | gpl-3.0 | 10,129 |
#
# various ascii art ============================================================
#shellcheck shell=bash disable=SC2015,SC2154,SC2207
pukeskull() {
##!/bin/sh
#
# ┳━┓┳━┓0┏┓┓┳━┓┏━┓┓ ┳
# ┃┳┛┃━┫┃┃┃┃┃━┃┃ ┃┃┃┃
# ┃┗┛┛ ┃┃┃┗┛┻━┛┛━┛┗┻┛
# ┳━┓┳ ┓┳┏ ┳━┓
# ┃━┛┃ ┃┣┻┓┣━
# ┇ ┗━┛┃ ┛┻━┛
# ┓━┓┳┏ ┳ ┓┳ ┳
# ┗━┓┣┻┓┃ ┃┃ ┃
# ━━┛┇ ┛┗━┛┗━┛┗━┛
#
# the worst color script
# by xero <http://0w.nz>
cat << 'EOF'
[1;37m .................
[1;37m .syhhso++++++++/++osyyhys+.
[1;37m -oddyo+o+++++++++++++++o+oo+osdms:
[1;37m :dmyo++oosssssssssssssssooooooo+/+ymm+`
[1;37m hmyo++ossyyhhddddddddddddhyyyssss+//+ymd-
[1;37m -mho+oosyhhhddmmmmmmmmmmmmmmddhhyyyso+//+hN+
[1;37m my+++syhhhhdmmNNNNNNNNNNNNmmmmmdhhyyyyo//+sd:
[1;37m hs//+oyhhhhdmNNNNNNNNNNNNNNNNNNmmdhyhhhyo//++y
[1;37m s+++shddhhdmmNNNNNNNNNNNNNNNNNNNNmdhhhdhyo/++/
[1;37m 'hs+shmmmddmNNNNNNNNNNNNNNNNNNNNNmddddddhs+oh/
[1;37m shsshdmmmmmNNMMMMMMMMMMMNNNNNNNNmmmmmmdhssdh-
[1;37m +ssohdmmmmNNNNNMMMMMMMMNNNNNNmmmmmNNmdhhhs:`
[1;37m -+oo++////++sydmNNNNNNNNNNNNNNNNNNNdyyys/--://+//:
[1;37m d/+hmNNNmmdddhhhdmNNNNNNNNNNNNNNNmdhyyyhhhddmmNmdyd-
[1;37m ++--+ymNMMNNNNNNmmmmNNNNNNNNNNNmdhddmNNMMMMMMNmhyss
[1;37m /d+` -+ydmNMMMMMMNNmNMMMMMMMmmmmNNMMMMMNNmh- :sdo
[1;37m sNo ` /ohdmNNMMMMNNMMMMMNNNMMMMMNmdyo/ ` hNh
[1;37m M+' ``-/oyhmNNMNhNMNhNMMMMNmho/ ` 'MN/
[1;37m d+' `-+osydh0w.nzmNNmho: 'mN:
[1;37m +o/ ` :oo+:s :+o/-` -dds
[1;37m :hdo [0;31mx[1;37m `-/ooss:':+ooo: ` [0;31m0[1;37m :sdm+
[1;37m +dNNNh+ :ydmNNm' `sddmyo +hmNmds
[1;37m dhNMMNNNNmddhsyhdmmNNNM: NNmNmhyo+oyyyhmNMMNmysd
[1;37m ydNNNNNh+/++ohmMMMMNMNh oNNNNNNNmho++++yddhyssy
[1;37m `:sNMMMMN' `mNMNNNd/`
[1;31mXXXX[0;31mXXXX[1;33mX[1;37m y/hMMNm/ .dXb. -hdmdy: ` [0;34mXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;37m `o+hNNds. -ymNNy- .yhys+/`` [0;34mXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;37m +-+//o/+odMNMMMNdmh++////-/s [0;34mXX[1;37mXXXX
[1;31mXXXX[0;31mXXX[1;37m mhNd -+d/+myo++ysy/hs -mNsdh/ [0;34mXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;37m mhMN+ dMm-/-smy-::dMN/sMMmdo [0;34mXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXX[1;37m NMy+NMMh oMMMs yMMMyNMMs+ [0;34mXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXX[1;37m dy-hMMm+dMMMdoNMMh ydo [1;34mX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mX [1;37m smm 'NMMy dms sm [1;34mXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXX [1;34mXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX
[1;31mXXXX[0;31mXXXX[1;33mXXXX[0;33mXXXX[1;35mXXXX[0;35mXXXX[1;32mXXXX[0;32mXXXX[1;34mXXXX[0;34mXXXX[1;37mXXXX[1;39m[0;49m
EOF
}
dennis_ritchie() {
#original artwork by https://sanderfocus.nl/portfolio/tech-heroes/
#converted to shell by #nixers @ irc.unix.chat.
cat << 'eof'
[38;5;255m,_ ,_==▄▂[0m
[38;5;255m, ▂▃▄▄▅▅[48;5;240m▅[48;5;20m▂[48;5;240m▅¾[0m. [38;5;199m/ [38;5;20m/[0m
[38;5;255m[48;5;20m▄[0m[38;5;255m[48;5;199m▆[38;5;16m[48;5;255m<´ [38;5;32m"[38;5;34m»[38;5;255m▓▓[48;5;32m▓[48;5;240m%[0m\ [38;5;199m/ [38;5;20m/ [38;5;45m/ [38;5;118m/[0m
[38;5;255m,[38;5;255m[48;5;240m▅[38;5;16m[48;5;255m7" [38;5;160m´[38;5;34m>[38;5;255m[48;5;39m▓▓[38;5;199m[48;5;255m▓[0m[38;5;255m% [38;5;20m/ [38;5;118m/ [38;5;199m> [38;5;118m/ [38;5;199m>[38;5;255m/[38;5;45m%[0m
[38;5;255m▐[48;5;240m[38;5;255m¶[48;5;240m[38;5;255m▓[48;5;255m [38;5;196m,[38;5;34m»[48;5;201m[38;5;255m▓▓[0m[38;5;255m¾´[0m [38;5;199m/[38;5;255m> %[38;5;199m/[38;5;118m%[38;5;255m/[38;5;199m/ [38;5;45m/ [38;5;199m/[0m
[38;5;255m[48;5;240m▓[48;5;255m[38;5;16m▃[48;5;16m[38;5;255m▅▅[38;5;16m[48;5;255m▅▃,,[38;5;32m▄[38;5;16m▅[38;5;255m[48;5;16m▅▅[38;5;255m[48;5;20mÆ[0m[38;5;255m\[0m[38;5;20m/[38;5;118m/[38;5;255m /[38;5;118m/[38;5;199m/[38;5;255m>[38;5;45m// [38;5;255m/[38;5;118m>[38;5;199m/ [38;5;20m/[0m
[48;5;20m[38;5;255mV[48;5;255m[38;5;16m║[48;5;20m[38;5;255m«[0m[38;5;255m¼.;[48;5;240m[38;5;255m→[48;5;255m[38;5;16m ║[0m[38;5;255m<«.,[48;5;25m[38;5;255m`[48;5;240m=[0m[38;5;20m/[38;5;199m/ [38;5;255m/>[38;5;45m/[38;5;118m/[38;5;255m%/[38;5;199m% / [38;5;20m/[0m
[38;5;20m//[48;5;255m[38;5;16m╠<´ -²,)[48;5;16m[38;5;255m(▓[48;5;255m[38;5;16m~"-[38;5;199m╝/[0m[38;5;255m¾[0m[38;5;199m/ [38;5;118m%[38;5;255m/[38;5;118m>[38;5;45m/ [38;5;118m/[38;5;199m>[0m
[38;5;20m/ / [38;5;118m/ [48;5;20m[38;5;255m▐[48;5;240m[38;5;16m%[48;5;255m -./▄▃▄[48;5;16m[38;5;255m▅[48;5;255m[38;5;16m▐[48;5;255m[38;5;16m, [38;5;199m/[48;5;199m[38;5;255m7[0m[38;5;20m/[38;5;199m/[38;5;255m;/[38;5;199m/[38;5;118m% [38;5;20m/ /[0m
[38;5;20m/ [38;5;199m/[38;5;255m/[38;5;45m/[38;5;118m/[38;5;255m[48;5;240m`[48;5;20m[38;5;255m▌[48;5;20m[38;5;255m▐[48;5;255m[38;5;16m %z[0m[38;5;255mWv xX[48;5;20m[38;5;255m▓[48;5;34m[38;5;255m▇[48;5;199m[38;255m▌[0m[38;5;20m/[38;5;199m/[38;5;255m&;[38;5;20m% [38;5;199m/ [38;5;20m/[0m
[38;5;20m/ / [38;5;255m/ [38;5;118m%[38;5;199m/[38;5;255m/%/[48;5;240m[38;5;255m¾[48;5;255m[38;5;16m½´[38;5;255m[48;5;16m▌[0m[38;5;246m▃▄[38;5;255m▄▄[38;5;246m▄▃▃[0m[48;5;16m[38;5;255m▐[38;5;255m[48;5;199m¶[48;5;20m[38;5;255m\[0m[38;5;20m/[0m[48;5;255m[38;5;240m&[0m [38;5;20m/[0m
[38;5;199m<[38;5;118m/ [38;5;45m/[38;5;255m</[38;5;118m%[38;5;255m/[38;5;45m/[38;5;255m`[48;5;16m▓[48;5;255m[38;5;16m![48;5;240m[38;5;255m%[48;5;16m[38;5;255m▓[0m[38;5;255m%[48;5;240m[38;5;255m╣[48;5;240m[38;5;255mW[0m[38;5;250mY<Y)[48;5;255m[38;5;16my&[0m[38;5;255m/`[48;5;240m\[0m
[38;5;20m/ [38;5;199m/ [38;5;199m%[38;5;255m/%[38;5;118m/[38;5;45m/[38;5;255m<[38;5;118m/[38;5;199m%[38;5;45m/[38;5;20m/[48;5;240m[38;5;255m\[38;5;16m[48;5;255mi7; ╠N[0m[38;5;246m>[38;5;255m)VY>[48;5;240m[38;5;255m7[0m[38;5;255m; [38;5;255m[48;5;240m\[0m[38;5;255m_[0m
[38;5;20m/ [38;5;255m/[38;5;118m<[38;5;255m/ [38;5;45m/[38;5;255m/<[38;5;199m/[38;5;20m/[38;5;199m/[38;5;20m<[38;5;255m_/%\[38;5;255m[48;5;16m▓[48;5;255m[38;5;16m V[0m[38;5;255m%[48;5;255m[38;5;16mW[0m[38;5;255m%£)XY[0m [38;5;240m_/%[38;5;255m‾\_,[0m
[38;5;199m/ [38;5;255m/ [38;5;199m/[38;5;255m/[38;5;118m%[38;5;199m/[48;5;240m[38;5;255m_,=-[48;5;20m-^[0m[38;5;255m/%/%%[48;5;255m[38;5;16m\¾%[0m[38;5;255m¶[0m[48;5;255m[38;5;16m%[0m[38;5;255m%}[0m [38;5;240m/%%%[38;5;20m%%[38;5;240m%;\,[0m
[38;5;45m%[38;5;20m/[38;5;199m< [38;5;20m/[48;5;20m[38;5;255m_/[48;5;240m [0m[38;5;255m%%%[38;5;240m%%[38;5;20m;[38;5;255mX[38;5;240m%[38;5;20m%[38;5;255m\%[38;5;240m%;, _/%%%;[38;5;20m,[38;5;240m \[0m
[38;5;118m/ [38;5;20m/ [38;5;240m%[38;5;20m%%%%[38;5;240m%;, [38;5;255m\[38;5;240m%[38;5;20m%[38;5;255ml[38;5;240m%%;// _/[38;5;20m%;,[0m [38;5;234mdmr[0m
[38;5;20m/ [38;5;240m%[38;5;20m%%;,[0m [38;5;255m<[38;5;20m;[38;5;240m\-=-/ /[0m
[38;5;20m;,[0m [38;5;240ml[0m
[38;5;255mUNIX is very simple, [38;5;45mIt just needs a[0m
[38;5;45mGENIUS to understand its simplicity![38;5;255m[0m
eof
}
fancy4tune() {
local -r myusage="
Description: Fancy fortune.
Usage: ${FUNCNAME[0]} [ -(-f)ile cowsay_file ] [ -(-m)sg 'message' ]
Example: ${FUNCNAME[0]} -f default -m 'Hello Lolcat!'
Notes: When misspelled or no --file given, a random will be used.
You can try: 'cowsay -l' for a list of available files.
Requires: fortune, cowsay and lolcat.\n\n"
local msg='' file=''
type -P fortune &> /dev/null && \
type -P cowsay &> /dev/null && \
type -P lolcat &> /dev/null || \
{ echo -ne "${myusage}" >&2; return 1; }
local -ar cowsay_files=( $(cowsay -l|awk 'NR != 1 { print $0 }') )
while [[ -n "${1}" ]]; do
case "${1}" in
-m|--msg) shift; local msg="${1}";;
-f|--file) shift; local file="${1}";;
*) echo -ne "${myusage}" >&2; return 1;;
esac
shift
done
# { [[ -n "${msg}" ]] && echo "${msg}" || fortune -s; } | \
# { [[ -n "${file}" && "${cowsay_files[*]}" =~ ${file} ]] && cowsay -f "${file}" || cowsay -f "${cowsay_files[$(shuf -n 1 -i 0-"$((${#cowsay_files[*]}-1))")]}"; } | \
# lolcat
{ [[ -n "${msg}" ]] && echo "${msg}" || fortune -s; } | \
{ [[ -n "${file}" && "${cowsay_files[*]}" =~ ${file} ]] && cowsay -f "${file}" || cowsay -f "${cowsay_files[$(( RANDOM % ${#cowsay_files[*]} ))]}"; } | \
lolcat
}
list_cow_files() {
for i in $(cowsay -l|awk 'NR != 1 { print $0 }'); do
funky4tune -m "Hello ${i} !" -f "${i}" || return 1
done
}
magiccow() {
# https://twitter.com/climagic/status/1299435679710154753
# Magic Cow answers for all. Works better with cowsay and lolcat.
# echo 'Yes!,Moooo!,Mooost likely!,Cannot predict cow!,Without a doubt!,My horses say no!,Ask again l8r!' | \
# tr ',' '\n' | sort -R | head -1 | { cowsay 2> /dev/null || cat; } | { lolcat 2> /dev/null || cat; }
local -ar answ=(
"It is certain." "It is decidedly so." "Without a doubt." "Yes – definitely." "You may rely on it."
"As I see it, yes." "Most likely." "Outlook good." "Yes." "Signs point to yes."
"Reply hazy, try again." "Ask again later." "Better not tell you now." "Cannot predict now." "Concentrate and ask again."
"Don't count on it." "My reply is no." "My sources say no." "Outlook not so good." "Very doubtful."
)
echo "${answ[$(( RANDOM % ${#answ[*]} ))]}" | \
{ type -P cowsay &> /dev/null && cowsay || cat; } | \
{ type -P lolcat &> /dev/null && lolcat || cat; }
}
mycountdown() {
local -r myusage="
Description: Fancy countdown.
Usage: ${FUNCNAME[0]} [#countdown seconds]
Example: ${FUNCNAME[0]} 60
Requires: figlet, lolcat and sox.\n"
#shellcheck disable=SC2015
type -P figlet &> /dev/null && \
type -P lolcat &> /dev/null && \
type -P play &> /dev/null || \
{ echo -e "${myusage}" >&2; return 1; }
for i in $(seq "${1:-10}" -1 0); do
clear
printf "%04d\n" "${i}" |figlet |lolcat
sleep 1
done
play -q -n synth .8 sine 4100 fade q 0.1 .3 0.1 repeat 3
}
touch_type(){
# https://twitter.com/climagic/status/1324072754228899840
# Simulate someone slowly typing out characters from a file.
# cat /etc/passwd | while read -N1 l ; do printf "$l" ; sleep 0.$[5000+$RANDOM] ; done
while read -rN1 l ; do printf "%c" "${l}" ; sleep "0.0$((1000+RANDOM))" ; done
}
# Static, Good luck with high lvl lang implementations of lolcat.
# Recomended lolcat is: https://github.com/jaseg/lolcat
type -P lolcat &> /dev/null && \
alias static='P=( " " █ ░ ▒ ▓ );while :;do printf "\e[$[RANDOM%LINES+1];$[RANDOM%COLUMNS+1]f${P[$RANDOM%5]}";done|lolcat'
# https://twitter.com/climagic/status/1327689059666419725
alias sunrise='p=3.14;for i in $( seq 0 0.04 100 );do r=$( printf "128+127*s($i)\n" |bc -l |cut -d. -f1) g=$( printf "128+127*s($i+$p*(1/3))\n" |bc -l |cut -d. -f1 ) b=$( printf "128+127*s($i+$p*(2/3))\n" |bc -l |cut -d. -f1 ); printf "\e[48;2;$r;$g;${b}m\n"; done'
| MichaelTd/libBash | dot.files/.bashrc.d/ascii.bash | Shell | gpl-3.0 | 13,061 |
# -*- coding: utf-8 -*-
"""
José Vicente Pérez
Granada University (Spain)
March, 2017
Testing suite for profiler.py
Last modified: 19 June 2017
"""
import time
import profiler as p
import praster as pr
import numpy as np
import matplotlib.pyplot as plt
print("Tests for TProfiler methods")
def test01():
"""
Creates a TProfiler from an array with profile_data
Test for get_x, get_y
"""
inicio = time.time()
print("=" * 40)
print("Test 01 para TProfiler")
print("Testing functions get_x(), get_y()")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
# Test 01 get and print x and y arrays
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
xi1 = perfil.get_x(True)
yi1 = perfil.get_y(True)
xi2 = perfil.get_x(False)
yi2 = perfil.get_y(False)
ax1.plot(xi1, yi1)
ax2.plot(xi2, yi2)
ax1.set_title("head = True")
ax2.set_title("head = False")
fig.tight_layout()
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test02():
"""
Creates a TProfiler from an array with profile_data
Test for get_l, get_z
"""
inicio = time.time()
print("=" * 40)
print("Test 02 para TProfiler")
print("Testing functions get_l(), get_z()")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
# Test 01 get and print x and y arrays
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
li1 = perfil.get_l(True)
zi1 = perfil.get_z(True)
ax1.plot(li1, zi1)
ax1.set_title("head = True")
li2 = perfil.get_l(False)
zi2 = perfil.get_z(False)
ax2.plot(li2, zi2)
ax2.set_title("head = False")
zi3 = perfil.get_z(True, True)
ax3.plot(li1, zi3)
ax3.set_title("Relative elevations, head = True")
zi4 = perfil.get_z(False, True)
ax4.plot(li2, zi4)
ax4.set_title("Relative elevations, head = False")
fig.tight_layout()
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test03():
"""
Creates a TProfiler from an array with profile_data
Test for raw_elevations and smooth
"""
inicio = time.time()
print("=" * 40)
print("Test 03 para TProfiler")
print("Testing functions smooth() and get_raw_z()")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
# Print raw elevations vs peaks removed elevations
fig = plt.figure(figsize=(12, 6))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
li = perfil.get_l(True)
zi = perfil.get_z(True)
raw_zi = perfil.get_raw_z(True)
ax1.plot(li, zi, label="Peaks removed")
ax1.plot(li, raw_zi, label="Raw elevations")
ax1.set_title("Raw elevations vs peak removed")
ax1.legend()
ax1.set_xlim((6850, 8950))
ax1.set_ylim((950, 1050))
# Test for smooth function
distance = 0
for n in range(5):
li = perfil.get_l(True)
zi = perfil.get_z(True)
perfil.smooth(distance)
ax2.plot(li, zi, label=str(distance) + " m")
distance += 50
ax2.set_title("Smooth with different distances")
ax2.legend()
ax2.set_xlim((8000, 9000))
ax2.set_ylim((950, 1000))
fig.tight_layout()
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test04():
"""
Creates a TProfiler from an array with profile_data
Test for get_area and get_slopes
"""
inicio = time.time()
print("=" * 40)
print("Test 04 para TProfiler")
print("Testing functions get_area() and get_slopes()")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
# Get slope area and plot in log scale
fig = plt.figure(figsize=(12, 6))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
for ax in (ax1, ax2, ax3, ax4):
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim((1000000, 100000000))
ax.set_ylim((0.001, 1))
ai = perfil.get_area(True)
s1 = perfil.get_slope()
ax1.plot(ai, s1, "b+")
ax1.set_title("Raw slopes (all)")
s2 = perfil.get_slope(threshold=0.9)
ax2.plot(ai, s2, "b+")
ax2.set_title("Slopes with threshold >= 0.9")
s3, lq3 = perfil.get_slope(threshold=0.9, lq=True)
ax3.plot(ai, lq3, "r+")
ax3.plot(ai, s3, "b+")
ax3.set_title("Slopes and low quality slopes (threshold 0.9)")
s4, lq4 = perfil.get_slope(threshold=0.9, lq=True, head=True)
a2 = perfil.get_area(head=True)
ax4.plot(a2, lq4, "r+")
ax4.plot(a2, s4, "b+")
ax4.set_title("Example 3 with head=True")
fig.tight_layout(pad=1)
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test05():
"""
Creates a TProfiler from an array with profile_data
Test for calculate slopes
"""
inicio = time.time()
print("=" * 40)
print("Test 05 para TProfiler")
print("Testing functions calculate slopes")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
reg_points = 4
# Get slope area and plot in log scale
fig = plt.figure(figsize=(12, 6))
for n in range(1, 9, 2):
ax1 = fig.add_subplot(4, 2, n)
ax2 = fig.add_subplot(4, 2, n+1)
perfil.calculate_slope(reg_points)
si = perfil.get_slope()
ai = perfil.get_area()
ax1.plot(ai, si, "b+")
ax1.set_xscale("log")
ax1.set_yscale("log")
ax1.set_xlim((1000000, 100000000))
ax1.set_ylim((0.001, 1))
ax1.set_title("reg_points = " + str(reg_points) + " (normal elevations)")
perfil.calculate_slope(reg_points, True)
si = perfil.get_slope(0.9)
ax2.plot(ai, si, "b+")
ax2.set_xscale("log")
ax2.set_yscale("log")
ax2.set_xlim((1000000, 100000000))
ax2.set_ylim((0.001, 1))
ax2.set_title("reg_points = " + str(reg_points) + " (raw elevations)")
reg_points += 4
fig.tight_layout(pad=1)
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test06():
"""
Creates a TProfiler from an array with profile_data
Test for calculate_chi() and get_chi()
"""
inicio = time.time()
print("=" * 40)
print("Test 06 para TProfiler")
print("Testing functions get_chi() and calculate_chi()")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
# Get slope area and plot in log scale
fig = plt.figure()
theta = 0.35
for n in range(1, 10):
ax = fig.add_subplot(3, 3, n)
perfil.thetaref = theta
perfil.calculate_chi()
chi = perfil.get_chi(False, True)
zi = perfil.get_z(False, True)
ax.plot(chi, zi)
ax.set_title("Thetaref = {0:.2f}".format(theta))
theta += 0.05
fig.tight_layout(pad=1)
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test07():
"""
Creates a TProfiler from an array with profile_data
Test for get_ksn()
"""
inicio = time.time()
print("=" * 40)
print("Test 07 para TProfiler")
print("Testing function get_ksn()")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
# Get slope area and plot in log scale
fig = plt.figure(figsize=(12, 6))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
li = perfil.get_l(True)
ksn1 = perfil.get_ksn()
ax1.plot(li, ksn1, "b+")
ax1.set_title("Raw ksn (all)")
ksn2 = perfil.get_ksn(threshold=0.9)
ax2.plot(li, ksn2, "b+")
ax2.set_title("Ksn with threshold >= 0.9")
ksn3, lq3 = perfil.get_ksn(threshold=0.9, lq=True)
ax3.plot(li, lq3, "r+")
ax3.plot(li, ksn3, "b+")
ax3.set_title("Ksn and low quality ksn (threshold 0.9)")
ksn4, lq4 = perfil.get_ksn(threshold=0.9, lq=True, head=False)
l2 = perfil.get_l(head=False)
ax4.plot(l2, lq4, "r+")
ax4.plot(l2, ksn4, "b+")
ax4.set_title("Example 3 with head=False")
fig.tight_layout(pad=1)
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test08():
"""
Creates a TProfiler from an array with profile_data
Test for calculate_ksn
"""
inicio = time.time()
print("=" * 40)
print("Test 08 para TProfiler")
print("Testing functions calculate_ksn()")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
reg_points = 4
fig = plt.figure(figsize=(12, 6))
for n in range(1, 9, 2):
ax1 = fig.add_subplot(4, 2, n)
ax2 = fig.add_subplot(4, 2, n + 1)
perfil.calculate_ksn(reg_points)
ksn = perfil.get_ksn()
li = perfil.get_l()
ax1.plot(li, ksn)
ax1.set_title("KSN with reg_points = " + str(reg_points) + " (normal elevations)")
perfil.calculate_ksn(reg_points, raw_z=True)
ksn = perfil.get_ksn()
ax2.plot(li, ksn)
ax2.set_title("KSN with reg_points = " + str(reg_points) + " (raw elevations)")
reg_points += 4
fig.tight_layout(pad=1)
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
def test09():
"""
Creates a TProfiler from an array with profile_data
Test for calculate_ksn
"""
inicio = time.time()
print("=" * 40)
print("Test 09 para TProfiler")
print("Testing ksn and SL plots")
print("Test in progress...")
# Test parameters
pf_data = np.load("data/in/darro_pfdata.npy")
dem = "data/in/darro25.tif"
demraster = pr.open_raster(dem)
srs = demraster.proj
cellsize = demraster.cellsize
# Creates the profile
perfil = p.TProfile(pf_data, cellsize, srs=srs)
reg_points = 12
fig = plt.figure()
ax = fig.add_subplot(111)
perfil.calculate_ksn(reg_points=reg_points)
perfil.calculate_slope(reg_points=reg_points)
li = perfil.get_l()
slope = perfil.get_slope()
ksn = perfil.get_ksn()
sl = slope * li
sl, = ax.plot(li, sl)
ax.set_ylabel("SL index")
ax.set_xlabel("Distance (m)")
twax = ax.twinx()
ksn, = twax.plot(li, ksn, color="r")
twax.set_ylabel("Ksn index")
twax.legend((sl, ksn), ("SL", "ksn"))
plt.show()
fin = time.time()
print("Test finalizado en " + str(fin - inicio) + " segundos")
print("=" * 40)
test01()
test02()
test03()
test04()
test05()
test06()
test07()
test08()
test09()
| geolovic/TProfiler | test/06_TProfiler_test.py | Python | gpl-3.0 | 12,892 |
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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/>.
#
import os
import sys
import binascii
from smtplib import SMTPException
from django.db import models
from django.dispatch import receiver
from django.conf import settings
from django.contrib.auth.signals import user_logged_in
from django.db.models.signals import post_save, post_migrate
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group, User, Permission
from django.utils import translation as django_translation
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives, get_connection
from django.utils.translation import LANGUAGE_SESSION_KEY
from social.apps.django_app.default.models import UserSocialAuth
from weblate.lang.models import Language
from weblate.trans.site import get_site_url, get_site_domain
from weblate.accounts.avatar import get_user_display
from weblate.trans.util import report_error
from weblate.trans.signals import user_pre_delete
from weblate import VERSION
from weblate.logger import LOGGER
from weblate.appsettings import ANONYMOUS_USER_NAME, SITE_TITLE
def send_mails(mails):
"""Sends multiple mails in single connection."""
try:
connection = get_connection()
connection.send_messages(mails)
except SMTPException as error:
LOGGER.error('Failed to send email: %s', error)
report_error(error, sys.exc_info())
def get_author_name(user, email=True):
"""Returns formatted author name with email."""
# Get full name from database
full_name = user.first_name
# Use username if full name is empty
if full_name == '':
full_name = user.username
# Add email if we are asked for it
if not email:
return full_name
return '%s <%s>' % (full_name, user.email)
def notify_merge_failure(subproject, error, status):
'''
Notification on merge failure.
'''
subscriptions = Profile.objects.subscribed_merge_failure(
subproject.project,
)
users = set()
mails = []
for subscription in subscriptions:
mails.append(
subscription.notify_merge_failure(subproject, error, status)
)
users.add(subscription.user_id)
for owner in subproject.project.owners.all():
mails.append(
owner.profile.notify_merge_failure(
subproject, error, status
)
)
# Notify admins
mails.append(
get_notification_email(
'en',
'ADMINS',
'merge_failure',
subproject,
{
'subproject': subproject,
'status': status,
'error': error,
}
)
)
send_mails(mails)
def notify_new_string(translation):
'''
Notification on new string to translate.
'''
mails = []
subscriptions = Profile.objects.subscribed_new_string(
translation.subproject.project, translation.language
)
for subscription in subscriptions:
mails.append(
subscription.notify_new_string(translation)
)
send_mails(mails)
def notify_new_language(subproject, language, user):
'''
Notify subscribed users about new language requests
'''
mails = []
subscriptions = Profile.objects.subscribed_new_language(
subproject.project,
user
)
users = set()
for subscription in subscriptions:
mails.append(
subscription.notify_new_language(subproject, language, user)
)
users.add(subscription.user_id)
for owner in subproject.project.owners.all():
mails.append(
owner.profile.notify_new_language(
subproject, language, user
)
)
# Notify admins
mails.append(
get_notification_email(
'en',
'ADMINS',
'new_language',
subproject,
{
'language': language,
'user': user,
},
user=user,
)
)
send_mails(mails)
def notify_new_translation(unit, oldunit, user):
'''
Notify subscribed users about new translation
'''
mails = []
subscriptions = Profile.objects.subscribed_any_translation(
unit.translation.subproject.project,
unit.translation.language,
user
)
for subscription in subscriptions:
mails.append(
subscription.notify_any_translation(unit, oldunit)
)
send_mails(mails)
def notify_new_contributor(unit, user):
'''
Notify about new contributor.
'''
mails = []
subscriptions = Profile.objects.subscribed_new_contributor(
unit.translation.subproject.project,
unit.translation.language,
user
)
for subscription in subscriptions:
mails.append(
subscription.notify_new_contributor(
unit.translation, user
)
)
send_mails(mails)
def notify_new_suggestion(unit, suggestion, user):
'''
Notify about new suggestion.
'''
mails = []
subscriptions = Profile.objects.subscribed_new_suggestion(
unit.translation.subproject.project,
unit.translation.language,
user
)
for subscription in subscriptions:
mails.append(
subscription.notify_new_suggestion(
unit.translation,
suggestion,
unit
)
)
send_mails(mails)
def notify_new_comment(unit, comment, user, report_source_bugs):
'''
Notify about new comment.
'''
mails = []
subscriptions = Profile.objects.subscribed_new_comment(
unit.translation.subproject.project,
comment.language,
user
)
for subscription in subscriptions:
mails.append(
subscription.notify_new_comment(unit, comment, user)
)
# Notify upstream
if comment.language is None and report_source_bugs != '':
send_notification_email(
'en',
report_source_bugs,
'new_comment',
unit.translation,
{
'unit': unit,
'comment': comment,
'subproject': unit.translation.subproject,
},
user=user,
)
send_mails(mails)
def get_notification_email(language, email, notification,
translation_obj=None, context=None, headers=None,
user=None, info=None):
'''
Renders notification email.
'''
cur_language = django_translation.get_language()
context = context or {}
headers = headers or {}
references = None
if 'unit' in context:
unit = context['unit']
references = '{0}/{1}/{2}/{3}'.format(
unit.translation.subproject.project.slug,
unit.translation.subproject.slug,
unit.translation.language.code,
unit.id
)
if references is not None:
references = '<{0}@{1}>'.format(references, get_site_domain())
headers['In-Reply-To'] = references
headers['References'] = references
try:
if info is None:
info = translation_obj.__unicode__()
LOGGER.info(
'sending notification %s on %s to %s',
notification,
info,
email
)
# Load user language
if language is not None:
django_translation.activate(language)
# Template name
context['subject_template'] = 'mail/{}_subject.txt'.format(
notification
)
# Adjust context
context['current_site_url'] = get_site_url()
if translation_obj is not None:
context['translation'] = translation_obj
context['translation_url'] = get_site_url(
translation_obj.get_absolute_url()
)
context['site_title'] = SITE_TITLE
# Render subject
subject = render_to_string(
context['subject_template'],
context
).strip()
# Render body
body = render_to_string(
'mail/{}.txt'.format(notification),
context
)
html_body = render_to_string(
'mail/{}.html'.format(notification),
context
)
# Define headers
headers['Auto-Submitted'] = 'auto-generated'
headers['X-AutoGenerated'] = 'yes'
headers['Precedence'] = 'bulk'
headers['X-Mailer'] = 'Weblate {}'.format(VERSION)
# Reply to header
if user is not None:
headers['Reply-To'] = user.email
# List of recipients
if email == 'ADMINS':
emails = [a[1] for a in settings.ADMINS]
else:
emails = [email]
# Create message
email = EmailMultiAlternatives(
settings.EMAIL_SUBJECT_PREFIX + subject,
body,
to=emails,
headers=headers,
)
email.attach_alternative(
html_body,
'text/html'
)
# Return the mail
return email
finally:
django_translation.activate(cur_language)
def send_notification_email(language, email, notification,
translation_obj=None, context=None, headers=None,
user=None, info=None):
'''
Renders and sends notification email.
'''
email = get_notification_email(
language, email, notification, translation_obj, context, headers,
user, info
)
send_mails([email])
class VerifiedEmail(models.Model):
'''
Storage for verified emails from auth backends.
'''
social = models.ForeignKey(UserSocialAuth)
email = models.EmailField(max_length=254)
def __unicode__(self):
return u'{0} - {1}'.format(
self.social.user.username,
self.email
)
class ProfileManager(models.Manager):
'''
Manager providing shortcuts for subscription queries.
'''
# pylint: disable=W0232
def subscribed_any_translation(self, project, language, user):
return self.filter(
subscribe_any_translation=True,
subscriptions=project,
languages=language
).exclude(
user=user
)
def subscribed_new_language(self, project, user):
return self.filter(
subscribe_new_language=True,
subscriptions=project,
).exclude(
user=user
)
def subscribed_new_string(self, project, language):
return self.filter(
subscribe_new_string=True,
subscriptions=project,
languages=language
)
def subscribed_new_suggestion(self, project, language, user):
ret = self.filter(
subscribe_new_suggestion=True,
subscriptions=project,
languages=language
)
# We don't want to filter out anonymous user
if user is not None and user.is_authenticated():
ret = ret.exclude(user=user)
return ret
def subscribed_new_contributor(self, project, language, user):
return self.filter(
subscribe_new_contributor=True,
subscriptions=project,
languages=language
).exclude(
user=user
)
def subscribed_new_comment(self, project, language, user):
ret = self.filter(
subscribe_new_comment=True,
subscriptions=project
).exclude(
user=user
)
# Source comments go to every subscriber
if language is not None:
ret = ret.filter(languages=language)
return ret
def subscribed_merge_failure(self, project):
return self.filter(subscribe_merge_failure=True, subscriptions=project)
class Profile(models.Model):
'''
User profiles storage.
'''
user = models.OneToOneField(User, unique=True, editable=False)
language = models.CharField(
verbose_name=_(u"Interface Language"),
max_length=10,
choices=settings.LANGUAGES
)
languages = models.ManyToManyField(
Language,
verbose_name=_('Translated languages'),
blank=True,
help_text=_('Choose languages to which you can translate.')
)
secondary_languages = models.ManyToManyField(
Language,
verbose_name=_('Secondary languages'),
related_name='secondary_profile_set',
blank=True,
)
suggested = models.IntegerField(default=0, db_index=True)
translated = models.IntegerField(default=0, db_index=True)
hide_completed = models.BooleanField(
verbose_name=_('Hide completed translations on dashboard'),
default=False
)
secondary_in_zen = models.BooleanField(
verbose_name=_('Show secondary translations in zen mode'),
default=True
)
hide_source_secondary = models.BooleanField(
verbose_name=_('Hide source if there is secondary language'),
default=False
)
subscriptions = models.ManyToManyField(
'trans.Project',
verbose_name=_('Subscribed projects'),
blank=True,
)
subscribe_any_translation = models.BooleanField(
verbose_name=_('Notification on any translation'),
default=False
)
subscribe_new_string = models.BooleanField(
verbose_name=_('Notification on new string to translate'),
default=False
)
subscribe_new_suggestion = models.BooleanField(
verbose_name=_('Notification on new suggestion'),
default=False
)
subscribe_new_contributor = models.BooleanField(
verbose_name=_('Notification on new contributor'),
default=False
)
subscribe_new_comment = models.BooleanField(
verbose_name=_('Notification on new comment'),
default=False
)
subscribe_merge_failure = models.BooleanField(
verbose_name=_('Notification on merge failure'),
default=False
)
subscribe_new_language = models.BooleanField(
verbose_name=_('Notification on new language request'),
default=False
)
SUBSCRIPTION_FIELDS = (
'subscribe_any_translation',
'subscribe_new_string',
'subscribe_new_suggestion',
'subscribe_new_contributor',
'subscribe_new_comment',
'subscribe_merge_failure',
'subscribe_new_language',
)
objects = ProfileManager()
def __unicode__(self):
return self.user.username
def get_user_display(self):
return get_user_display(self.user)
def get_user_display_link(self):
return get_user_display(self.user, True, True)
def get_user_name(self):
return get_user_display(self.user, False)
@models.permalink
def get_absolute_url(self):
return ('user_page', (), {
'user': self.user.username
})
@property
def last_change(self):
'''
Returns date of last change user has done in Weblate.
'''
try:
return self.user.change_set.all()[0].timestamp
except IndexError:
return None
def notify_user(self, notification, translation_obj,
context=None, headers=None, user=None):
'''
Wrapper for sending notifications to user.
'''
if context is None:
context = {}
if headers is None:
headers = {}
# Check whether user is still allowed to access this project
if not translation_obj.has_acl(self.user):
return
# Generate notification
return get_notification_email(
self.language,
self.user.email,
notification,
translation_obj,
context,
headers,
user=user
)
def notify_any_translation(self, unit, oldunit):
'''
Sends notification on translation.
'''
if oldunit.translated:
template = 'changed_translation'
else:
template = 'new_translation'
return self.notify_user(
template,
unit.translation,
{
'unit': unit,
'oldunit': oldunit,
}
)
def notify_new_language(self, subproject, language, user):
'''
Sends notification on new language request.
'''
return self.notify_user(
'new_language',
subproject,
{
'language': language,
'user': user,
},
user=user
)
def notify_new_string(self, translation):
'''
Sends notification on new strings to translate.
'''
return self.notify_user(
'new_string',
translation,
)
def notify_new_suggestion(self, translation, suggestion, unit):
'''
Sends notification on new suggestion.
'''
return self.notify_user(
'new_suggestion',
translation,
{
'suggestion': suggestion,
'unit': unit,
}
)
def notify_new_contributor(self, translation, user):
'''
Sends notification on new contributor.
'''
return self.notify_user(
'new_contributor',
translation,
{
'user': user,
}
)
def notify_new_comment(self, unit, comment, user):
'''
Sends notification about new comment.
'''
return self.notify_user(
'new_comment',
unit.translation,
{
'unit': unit,
'comment': comment,
'subproject': unit.translation.subproject,
},
user=user,
)
def notify_merge_failure(self, subproject, error, status):
'''
Sends notification on merge failure.
'''
return self.notify_user(
'merge_failure',
subproject,
{
'subproject': subproject,
'error': error,
'status': status,
}
)
@property
def full_name(self):
'''
Returns user's full name.
'''
return self.user.first_name
def set_lang(request, profile):
"""
Sets session language based on user preferences.
"""
request.session[LANGUAGE_SESSION_KEY] = profile.language
@receiver(user_logged_in)
def post_login_handler(sender, request, user, **kwargs):
'''
Signal handler for setting user language and
migrating profile if needed.
'''
# Warning about setting password
if (getattr(user, 'backend', '').endswith('.EmailAuth') and
not user.has_usable_password()):
request.session['show_set_password'] = True
# Ensure user has a profile
profile = Profile.objects.get_or_create(user=user)[0]
# Migrate django-registration based verification to python-social-auth
if (user.has_usable_password() and
not user.social_auth.filter(provider='email').exists()):
social = user.social_auth.create(
provider='email',
uid=user.email,
)
VerifiedEmail.objects.create(
social=social,
email=user.email,
)
# Set language for session based on preferences
set_lang(request, profile)
def create_groups(update):
'''
Creates standard groups and gives them permissions.
'''
guest_group, created = Group.objects.get_or_create(name='Guests')
if created or update:
guest_group.permissions.add(
Permission.objects.get(codename='can_see_git_repository'),
Permission.objects.get(codename='add_suggestion'),
)
group, created = Group.objects.get_or_create(name='Users')
if created or update:
group.permissions.add(
Permission.objects.get(codename='upload_translation'),
Permission.objects.get(codename='overwrite_translation'),
Permission.objects.get(codename='save_translation'),
Permission.objects.get(codename='save_template'),
Permission.objects.get(codename='accept_suggestion'),
Permission.objects.get(codename='delete_suggestion'),
Permission.objects.get(codename='vote_suggestion'),
Permission.objects.get(codename='ignore_check'),
Permission.objects.get(codename='upload_dictionary'),
Permission.objects.get(codename='add_dictionary'),
Permission.objects.get(codename='change_dictionary'),
Permission.objects.get(codename='delete_dictionary'),
Permission.objects.get(codename='lock_translation'),
Permission.objects.get(codename='can_see_git_repository'),
Permission.objects.get(codename='add_comment'),
Permission.objects.get(codename='add_suggestion'),
Permission.objects.get(codename='use_mt'),
)
owner_permissions = (
Permission.objects.get(codename='author_translation'),
Permission.objects.get(codename='upload_translation'),
Permission.objects.get(codename='overwrite_translation'),
Permission.objects.get(codename='commit_translation'),
Permission.objects.get(codename='update_translation'),
Permission.objects.get(codename='push_translation'),
Permission.objects.get(codename='automatic_translation'),
Permission.objects.get(codename='save_translation'),
Permission.objects.get(codename='save_template'),
Permission.objects.get(codename='accept_suggestion'),
Permission.objects.get(codename='vote_suggestion'),
Permission.objects.get(codename='override_suggestion'),
Permission.objects.get(codename='delete_comment'),
Permission.objects.get(codename='delete_suggestion'),
Permission.objects.get(codename='ignore_check'),
Permission.objects.get(codename='upload_dictionary'),
Permission.objects.get(codename='add_dictionary'),
Permission.objects.get(codename='change_dictionary'),
Permission.objects.get(codename='delete_dictionary'),
Permission.objects.get(codename='lock_subproject'),
Permission.objects.get(codename='reset_translation'),
Permission.objects.get(codename='lock_translation'),
Permission.objects.get(codename='can_see_git_repository'),
Permission.objects.get(codename='add_comment'),
Permission.objects.get(codename='delete_comment'),
Permission.objects.get(codename='add_suggestion'),
Permission.objects.get(codename='use_mt'),
Permission.objects.get(codename='edit_priority'),
Permission.objects.get(codename='edit_flags'),
Permission.objects.get(codename='manage_acl'),
Permission.objects.get(codename='download_changes'),
Permission.objects.get(codename='view_reports'),
)
group, created = Group.objects.get_or_create(name='Managers')
if created or update:
group.permissions.add(*owner_permissions)
group, created = Group.objects.get_or_create(name='Owners')
if created or update:
group.permissions.add(*owner_permissions)
created = True
try:
anon_user = User.objects.get(
username=ANONYMOUS_USER_NAME,
)
created = False
if anon_user.is_active:
raise ValueError(
'Anonymous user ({}) already exists and enabled, '
'please change ANONYMOUS_USER_NAME setting.'.format(
ANONYMOUS_USER_NAME,
)
)
except User.DoesNotExist:
anon_user = User.objects.create(
username=ANONYMOUS_USER_NAME,
is_active=False,
)
if created or update:
anon_user.set_unusable_password()
anon_user.groups.clear()
anon_user.groups.add(guest_group)
def move_users():
'''
Moves users to default group.
'''
group = Group.objects.get(name='Users')
for user in User.objects.all():
user.groups.add(group)
def remove_user(user):
'''
Removes user account.
'''
# Send signal (to commit any pending changes)
user_pre_delete.send(instance=user, sender=user.__class__)
# Change username
user.username = 'deleted-{0}'.format(user.pk)
while User.objects.filter(username=user.username).exists():
user.username = 'deleted-{0}-{1}'.format(
user.pk,
binascii.b2a_hex(os.urandom(5))
)
# Remove user information
user.first_name = 'Deleted User'
user.last_name = ''
user.email = 'noreply@weblate.org'
# Disable the user
user.is_active = False
user.set_unusable_password()
user.save()
# Remove all social auth associations
user.social_auth.all().delete()
@receiver(post_migrate)
def sync_create_groups(sender, **kwargs):
'''
Create groups on syncdb.
'''
if sender.label == 'accounts':
create_groups(False)
@receiver(post_save, sender=User)
def create_profile_callback(sender, instance, created=False, **kwargs):
'''
Automatically adds user to Users group.
'''
if created:
# Add user to Users group if it exists
try:
group = Group.objects.get(name='Users')
instance.groups.add(group)
except Group.DoesNotExist:
pass
| quinox/weblate | weblate/accounts/models.py | Python | gpl-3.0 | 26,496 |
<?php
/**
* Created by PhpStorm.
* User: Temporary
* Date: 6/30/2017
* Time: 1:56 PM
*/
//start database connection
include('../dbConnStart.php');
//create database
$sql = "CREATE DATABASE shoppingCart";
if($conn->query($sql) === TRUE){
$msg = "Database created successfully";
} else {
$msg = "Error creating database: " . $conn->error;
}
//close database connection
$conn->close();
$msg = $msg . "<br>";
$msg = $msg . "<a href='../index.php'> Return to main page</a>";
echo $msg; | MarcoVanderEecken/ShoppingCart | databaseSetup/createDB.php | PHP | gpl-3.0 | 553 |
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#if defined(V8_TARGET_ARCH_X64)
#include "x64/lithium-codegen-x64.h"
#include "code-stubs.h"
#include "stub-cache.h"
namespace v8 {
namespace internal {
// When invoking builtins, we need to record the safepoint in the middle of
// the invoke instruction sequence generated by the macro assembler.
class SafepointGenerator : public CallWrapper {
public:
SafepointGenerator(LCodeGen* codegen,
LPointerMap* pointers,
Safepoint::DeoptMode mode)
: codegen_(codegen),
pointers_(pointers),
deopt_mode_(mode) { }
virtual ~SafepointGenerator() { }
virtual void BeforeCall(int call_size) const {
codegen_->EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - call_size);
}
virtual void AfterCall() const {
codegen_->RecordSafepoint(pointers_, deopt_mode_);
}
private:
LCodeGen* codegen_;
LPointerMap* pointers_;
Safepoint::DeoptMode deopt_mode_;
};
#define __ masm()->
bool LCodeGen::GenerateCode() {
HPhase phase("Z_Code generation", chunk());
ASSERT(is_unused());
status_ = GENERATING;
// Open a frame scope to indicate that there is a frame on the stack. The
// MANUAL indicates that the scope shouldn't actually generate code to set up
// the frame (that is done in GeneratePrologue).
FrameScope frame_scope(masm_, StackFrame::MANUAL);
return GeneratePrologue() &&
GenerateBody() &&
GenerateDeferredCode() &&
GenerateJumpTable() &&
GenerateSafepointTable();
}
void LCodeGen::FinishCode(Handle<Code> code) {
ASSERT(is_done());
code->set_stack_slots(GetStackSlotCount());
code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
PopulateDeoptimizationData(code);
}
void LChunkBuilder::Abort(const char* reason) {
info()->set_bailout_reason(reason);
status_ = ABORTED;
}
void LCodeGen::Comment(const char* format, ...) {
if (!FLAG_code_comments) return;
char buffer[4 * KB];
StringBuilder builder(buffer, ARRAY_SIZE(buffer));
va_list arguments;
va_start(arguments, format);
builder.AddFormattedList(format, arguments);
va_end(arguments);
// Copy the string before recording it in the assembler to avoid
// issues when the stack allocated buffer goes out of scope.
int length = builder.position();
Vector<char> copy = Vector<char>::New(length + 1);
memcpy(copy.start(), builder.Finalize(), copy.length());
masm()->RecordComment(copy.start());
}
bool LCodeGen::GeneratePrologue() {
ASSERT(is_generating());
ProfileEntryHookStub::MaybeCallEntryHook(masm_);
#ifdef DEBUG
if (strlen(FLAG_stop_at) > 0 &&
info_->function()->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
__ int3();
}
#endif
// Strict mode functions need to replace the receiver with undefined
// when called as functions (without an explicit receiver
// object). rcx is zero for method calls and non-zero for function
// calls.
if (!info_->is_classic_mode() || info_->is_native()) {
Label begin;
__ bind(&begin);
Label ok;
__ testq(rcx, rcx);
__ j(zero, &ok, Label::kNear);
// +1 for return address.
int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize;
__ LoadRoot(kScratchRegister, Heap::kUndefinedValueRootIndex);
__ movq(Operand(rsp, receiver_offset), kScratchRegister);
__ bind(&ok);
ASSERT(!FLAG_age_code ||
(kSizeOfOptimizedStrictModePrologue == ok.pos() - begin.pos()));
}
__ push(rbp); // Caller's frame pointer.
__ movq(rbp, rsp);
__ push(rsi); // Callee's context.
__ push(rdi); // Callee's JS function.
// Reserve space for the stack slots needed by the code.
int slots = GetStackSlotCount();
if (slots > 0) {
if (FLAG_debug_code) {
__ Set(rax, slots);
__ movq(kScratchRegister, kSlotsZapValue, RelocInfo::NONE);
Label loop;
__ bind(&loop);
__ push(kScratchRegister);
__ decl(rax);
__ j(not_zero, &loop);
} else {
__ subq(rsp, Immediate(slots * kPointerSize));
#ifdef _MSC_VER
// On windows, you may not access the stack more than one page below
// the most recently mapped page. To make the allocated area randomly
// accessible, we write to each page in turn (the value is irrelevant).
const int kPageSize = 4 * KB;
for (int offset = slots * kPointerSize - kPageSize;
offset > 0;
offset -= kPageSize) {
__ movq(Operand(rsp, offset), rax);
}
#endif
}
}
// Possibly allocate a local context.
int heap_slots = scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
if (heap_slots > 0 ||
(scope()->is_qml_mode() && scope()->is_global_scope())) {
Comment(";;; Allocate local context");
// Argument to NewContext is the function, which is still in rdi.
__ push(rdi);
if (heap_slots <= FastNewContextStub::kMaximumSlots) {
FastNewContextStub stub((heap_slots < 0)?0:heap_slots);
__ CallStub(&stub);
} else {
__ CallRuntime(Runtime::kNewFunctionContext, 1);
}
RecordSafepoint(Safepoint::kNoLazyDeopt);
// Context is returned in both rax and rsi. It replaces the context
// passed to us. It's saved in the stack and kept live in rsi.
__ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi);
// Copy any necessary parameters into the context.
int num_parameters = scope()->num_parameters();
for (int i = 0; i < num_parameters; i++) {
Variable* var = scope()->parameter(i);
if (var->IsContextSlot()) {
int parameter_offset = StandardFrameConstants::kCallerSPOffset +
(num_parameters - 1 - i) * kPointerSize;
// Load parameter from stack.
__ movq(rax, Operand(rbp, parameter_offset));
// Store it in the context.
int context_offset = Context::SlotOffset(var->index());
__ movq(Operand(rsi, context_offset), rax);
// Update the write barrier. This clobbers rax and rbx.
__ RecordWriteContextSlot(rsi, context_offset, rax, rbx, kSaveFPRegs);
}
}
Comment(";;; End allocate local context");
}
// Trace the call.
if (FLAG_trace) {
__ CallRuntime(Runtime::kTraceEnter, 0);
}
return !is_aborted();
}
bool LCodeGen::GenerateBody() {
ASSERT(is_generating());
bool emit_instructions = true;
for (current_instruction_ = 0;
!is_aborted() && current_instruction_ < instructions_->length();
current_instruction_++) {
LInstruction* instr = instructions_->at(current_instruction_);
if (instr->IsLabel()) {
LLabel* label = LLabel::cast(instr);
emit_instructions = !label->HasReplacement();
}
if (emit_instructions) {
Comment(";;; @%d: %s.", current_instruction_, instr->Mnemonic());
instr->CompileToNative(this);
}
}
EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
return !is_aborted();
}
bool LCodeGen::GenerateJumpTable() {
for (int i = 0; i < jump_table_.length(); i++) {
__ bind(&jump_table_[i].label);
__ Jump(jump_table_[i].address, RelocInfo::RUNTIME_ENTRY);
}
return !is_aborted();
}
bool LCodeGen::GenerateDeferredCode() {
ASSERT(is_generating());
if (deferred_.length() > 0) {
for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
LDeferredCode* code = deferred_[i];
__ bind(code->entry());
Comment(";;; Deferred code @%d: %s.",
code->instruction_index(),
code->instr()->Mnemonic());
code->Generate();
__ jmp(code->exit());
}
}
// Deferred code is the last part of the instruction sequence. Mark
// the generated code as done unless we bailed out.
if (!is_aborted()) status_ = DONE;
return !is_aborted();
}
bool LCodeGen::GenerateSafepointTable() {
ASSERT(is_done());
safepoints_.Emit(masm(), GetStackSlotCount());
return !is_aborted();
}
Register LCodeGen::ToRegister(int index) const {
return Register::FromAllocationIndex(index);
}
XMMRegister LCodeGen::ToDoubleRegister(int index) const {
return XMMRegister::FromAllocationIndex(index);
}
Register LCodeGen::ToRegister(LOperand* op) const {
ASSERT(op->IsRegister());
return ToRegister(op->index());
}
XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
ASSERT(op->IsDoubleRegister());
return ToDoubleRegister(op->index());
}
bool LCodeGen::IsInteger32Constant(LConstantOperand* op) const {
return op->IsConstantOperand() &&
chunk_->LookupLiteralRepresentation(op).IsInteger32();
}
bool LCodeGen::IsTaggedConstant(LConstantOperand* op) const {
return op->IsConstantOperand() &&
chunk_->LookupLiteralRepresentation(op).IsTagged();
}
int LCodeGen::ToInteger32(LConstantOperand* op) const {
HConstant* constant = chunk_->LookupConstant(op);
ASSERT(chunk_->LookupLiteralRepresentation(op).IsInteger32());
ASSERT(constant->HasInteger32Value());
return constant->Integer32Value();
}
double LCodeGen::ToDouble(LConstantOperand* op) const {
HConstant* constant = chunk_->LookupConstant(op);
ASSERT(constant->HasDoubleValue());
return constant->DoubleValue();
}
Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
HConstant* constant = chunk_->LookupConstant(op);
ASSERT(chunk_->LookupLiteralRepresentation(op).IsTagged());
return constant->handle();
}
Operand LCodeGen::ToOperand(LOperand* op) const {
// Does not handle registers. In X64 assembler, plain registers are not
// representable as an Operand.
ASSERT(op->IsStackSlot() || op->IsDoubleStackSlot());
int index = op->index();
if (index >= 0) {
// Local or spill slot. Skip the frame pointer, function, and
// context in the fixed part of the frame.
return Operand(rbp, -(index + 3) * kPointerSize);
} else {
// Incoming parameter. Skip the return address.
return Operand(rbp, -(index - 1) * kPointerSize);
}
}
void LCodeGen::WriteTranslation(LEnvironment* environment,
Translation* translation,
int* arguments_index,
int* arguments_count) {
if (environment == NULL) return;
// The translation includes one command per value in the environment.
int translation_size = environment->values()->length();
// The output frame height does not include the parameters.
int height = translation_size - environment->parameter_count();
// Function parameters are arguments to the outermost environment. The
// arguments index points to the first element of a sequence of tagged
// values on the stack that represent the arguments. This needs to be
// kept in sync with the LArgumentsElements implementation.
*arguments_index = -environment->parameter_count();
*arguments_count = environment->parameter_count();
WriteTranslation(environment->outer(),
translation,
arguments_index,
arguments_count);
int closure_id = *info()->closure() != *environment->closure()
? DefineDeoptimizationLiteral(environment->closure())
: Translation::kSelfLiteralId;
switch (environment->frame_type()) {
case JS_FUNCTION:
translation->BeginJSFrame(environment->ast_id(), closure_id, height);
break;
case JS_CONSTRUCT:
translation->BeginConstructStubFrame(closure_id, translation_size);
break;
case JS_GETTER:
ASSERT(translation_size == 1);
ASSERT(height == 0);
translation->BeginGetterStubFrame(closure_id);
break;
case JS_SETTER:
ASSERT(translation_size == 2);
ASSERT(height == 0);
translation->BeginSetterStubFrame(closure_id);
break;
case ARGUMENTS_ADAPTOR:
translation->BeginArgumentsAdaptorFrame(closure_id, translation_size);
break;
}
// Inlined frames which push their arguments cause the index to be
// bumped and a new stack area to be used for materialization.
if (environment->entry() != NULL &&
environment->entry()->arguments_pushed()) {
*arguments_index = *arguments_index < 0
? GetStackSlotCount()
: *arguments_index + *arguments_count;
*arguments_count = environment->entry()->arguments_count() + 1;
}
for (int i = 0; i < translation_size; ++i) {
LOperand* value = environment->values()->at(i);
// spilled_registers_ and spilled_double_registers_ are either
// both NULL or both set.
if (environment->spilled_registers() != NULL && value != NULL) {
if (value->IsRegister() &&
environment->spilled_registers()[value->index()] != NULL) {
translation->MarkDuplicate();
AddToTranslation(translation,
environment->spilled_registers()[value->index()],
environment->HasTaggedValueAt(i),
environment->HasUint32ValueAt(i),
*arguments_index,
*arguments_count);
} else if (
value->IsDoubleRegister() &&
environment->spilled_double_registers()[value->index()] != NULL) {
translation->MarkDuplicate();
AddToTranslation(
translation,
environment->spilled_double_registers()[value->index()],
false,
false,
*arguments_index,
*arguments_count);
}
}
AddToTranslation(translation,
value,
environment->HasTaggedValueAt(i),
environment->HasUint32ValueAt(i),
*arguments_index,
*arguments_count);
}
}
void LCodeGen::AddToTranslation(Translation* translation,
LOperand* op,
bool is_tagged,
bool is_uint32,
int arguments_index,
int arguments_count) {
if (op == NULL) {
// TODO(twuerthinger): Introduce marker operands to indicate that this value
// is not present and must be reconstructed from the deoptimizer. Currently
// this is only used for the arguments object.
translation->StoreArgumentsObject(arguments_index, arguments_count);
} else if (op->IsStackSlot()) {
if (is_tagged) {
translation->StoreStackSlot(op->index());
} else if (is_uint32) {
translation->StoreUint32StackSlot(op->index());
} else {
translation->StoreInt32StackSlot(op->index());
}
} else if (op->IsDoubleStackSlot()) {
translation->StoreDoubleStackSlot(op->index());
} else if (op->IsArgument()) {
ASSERT(is_tagged);
int src_index = GetStackSlotCount() + op->index();
translation->StoreStackSlot(src_index);
} else if (op->IsRegister()) {
Register reg = ToRegister(op);
if (is_tagged) {
translation->StoreRegister(reg);
} else if (is_uint32) {
translation->StoreUint32Register(reg);
} else {
translation->StoreInt32Register(reg);
}
} else if (op->IsDoubleRegister()) {
XMMRegister reg = ToDoubleRegister(op);
translation->StoreDoubleRegister(reg);
} else if (op->IsConstantOperand()) {
HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
int src_index = DefineDeoptimizationLiteral(constant->handle());
translation->StoreLiteral(src_index);
} else {
UNREACHABLE();
}
}
void LCodeGen::CallCodeGeneric(Handle<Code> code,
RelocInfo::Mode mode,
LInstruction* instr,
SafepointMode safepoint_mode,
int argc) {
EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - masm()->CallSize(code));
ASSERT(instr != NULL);
LPointerMap* pointers = instr->pointer_map();
RecordPosition(pointers->position());
__ call(code, mode);
RecordSafepointWithLazyDeopt(instr, safepoint_mode, argc);
// Signal that we don't inline smi code before these stubs in the
// optimizing code generator.
if (code->kind() == Code::BINARY_OP_IC ||
code->kind() == Code::COMPARE_IC) {
__ nop();
}
}
void LCodeGen::CallCode(Handle<Code> code,
RelocInfo::Mode mode,
LInstruction* instr) {
CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT, 0);
}
void LCodeGen::CallRuntime(const Runtime::Function* function,
int num_arguments,
LInstruction* instr) {
ASSERT(instr != NULL);
ASSERT(instr->HasPointerMap());
LPointerMap* pointers = instr->pointer_map();
RecordPosition(pointers->position());
__ CallRuntime(function, num_arguments);
RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0);
}
void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
int argc,
LInstruction* instr) {
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
__ CallRuntimeSaveDoubles(id);
RecordSafepointWithRegisters(
instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
}
void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment,
Safepoint::DeoptMode mode) {
if (!environment->HasBeenRegistered()) {
// Physical stack frame layout:
// -x ............. -4 0 ..................................... y
// [incoming arguments] [spill slots] [pushed outgoing arguments]
// Layout of the environment:
// 0 ..................................................... size-1
// [parameters] [locals] [expression stack including arguments]
// Layout of the translation:
// 0 ........................................................ size - 1 + 4
// [expression stack including arguments] [locals] [4 words] [parameters]
// |>------------ translation_size ------------<|
int frame_count = 0;
int jsframe_count = 0;
int args_index = 0;
int args_count = 0;
for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
++frame_count;
if (e->frame_type() == JS_FUNCTION) {
++jsframe_count;
}
}
Translation translation(&translations_, frame_count, jsframe_count, zone());
WriteTranslation(environment, &translation, &args_index, &args_count);
int deoptimization_index = deoptimizations_.length();
int pc_offset = masm()->pc_offset();
environment->Register(deoptimization_index,
translation.index(),
(mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
deoptimizations_.Add(environment, environment->zone());
}
}
void LCodeGen::DeoptimizeIf(Condition cc, LEnvironment* environment) {
RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
ASSERT(environment->HasBeenRegistered());
int id = environment->deoptimization_index();
Address entry = Deoptimizer::GetDeoptimizationEntry(id, Deoptimizer::EAGER);
if (entry == NULL) {
Abort("bailout was not prepared");
return;
}
if (cc == no_condition) {
__ Jump(entry, RelocInfo::RUNTIME_ENTRY);
} else {
// We often have several deopts to the same entry, reuse the last
// jump entry if this is the case.
if (jump_table_.is_empty() ||
jump_table_.last().address != entry) {
jump_table_.Add(JumpTableEntry(entry), zone());
}
__ j(cc, &jump_table_.last().label);
}
}
void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
int length = deoptimizations_.length();
if (length == 0) return;
Handle<DeoptimizationInputData> data =
factory()->NewDeoptimizationInputData(length, TENURED);
Handle<ByteArray> translations = translations_.CreateByteArray();
data->SetTranslationByteArray(*translations);
data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
Handle<FixedArray> literals =
factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
for (int i = 0; i < deoptimization_literals_.length(); i++) {
literals->set(i, *deoptimization_literals_[i]);
}
data->SetLiteralArray(*literals);
data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
// Populate the deoptimization entries.
for (int i = 0; i < length; i++) {
LEnvironment* env = deoptimizations_[i];
data->SetAstId(i, env->ast_id());
data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
data->SetArgumentsStackHeight(i,
Smi::FromInt(env->arguments_stack_height()));
data->SetPc(i, Smi::FromInt(env->pc_offset()));
}
code->set_deoptimization_data(*data);
}
int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) {
int result = deoptimization_literals_.length();
for (int i = 0; i < deoptimization_literals_.length(); ++i) {
if (deoptimization_literals_[i].is_identical_to(literal)) return i;
}
deoptimization_literals_.Add(literal, zone());
return result;
}
void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
ASSERT(deoptimization_literals_.length() == 0);
const ZoneList<Handle<JSFunction> >* inlined_closures =
chunk()->inlined_closures();
for (int i = 0, length = inlined_closures->length();
i < length;
i++) {
DefineDeoptimizationLiteral(inlined_closures->at(i));
}
inlined_function_count_ = deoptimization_literals_.length();
}
void LCodeGen::RecordSafepointWithLazyDeopt(
LInstruction* instr, SafepointMode safepoint_mode, int argc) {
if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
} else {
ASSERT(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS);
RecordSafepointWithRegisters(
instr->pointer_map(), argc, Safepoint::kLazyDeopt);
}
}
void LCodeGen::RecordSafepoint(
LPointerMap* pointers,
Safepoint::Kind kind,
int arguments,
Safepoint::DeoptMode deopt_mode) {
ASSERT(kind == expected_safepoint_kind_);
const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
Safepoint safepoint = safepoints_.DefineSafepoint(masm(),
kind, arguments, deopt_mode);
for (int i = 0; i < operands->length(); i++) {
LOperand* pointer = operands->at(i);
if (pointer->IsStackSlot()) {
safepoint.DefinePointerSlot(pointer->index(), zone());
} else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
safepoint.DefinePointerRegister(ToRegister(pointer), zone());
}
}
if (kind & Safepoint::kWithRegisters) {
// Register rsi always contains a pointer to the context.
safepoint.DefinePointerRegister(rsi, zone());
}
}
void LCodeGen::RecordSafepoint(LPointerMap* pointers,
Safepoint::DeoptMode deopt_mode) {
RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode);
}
void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) {
LPointerMap empty_pointers(RelocInfo::kNoPosition, zone());
RecordSafepoint(&empty_pointers, deopt_mode);
}
void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
int arguments,
Safepoint::DeoptMode deopt_mode) {
RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode);
}
void LCodeGen::RecordPosition(int position) {
if (position == RelocInfo::kNoPosition) return;
masm()->positions_recorder()->RecordPosition(position);
}
void LCodeGen::DoLabel(LLabel* label) {
if (label->is_loop_header()) {
Comment(";;; B%d - LOOP entry", label->block_id());
} else {
Comment(";;; B%d", label->block_id());
}
__ bind(label->label());
current_block_ = label->block_id();
DoGap(label);
}
void LCodeGen::DoParallelMove(LParallelMove* move) {
resolver_.Resolve(move);
}
void LCodeGen::DoGap(LGap* gap) {
for (int i = LGap::FIRST_INNER_POSITION;
i <= LGap::LAST_INNER_POSITION;
i++) {
LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
LParallelMove* move = gap->GetParallelMove(inner_pos);
if (move != NULL) DoParallelMove(move);
}
}
void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
DoGap(instr);
}
void LCodeGen::DoParameter(LParameter* instr) {
// Nothing to do.
}
void LCodeGen::DoCallStub(LCallStub* instr) {
ASSERT(ToRegister(instr->result()).is(rax));
switch (instr->hydrogen()->major_key()) {
case CodeStub::RegExpConstructResult: {
RegExpConstructResultStub stub;
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
break;
}
case CodeStub::RegExpExec: {
RegExpExecStub stub;
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
break;
}
case CodeStub::SubString: {
SubStringStub stub;
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
break;
}
case CodeStub::NumberToString: {
NumberToStringStub stub;
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
break;
}
case CodeStub::StringAdd: {
StringAddStub stub(NO_STRING_ADD_FLAGS);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
break;
}
case CodeStub::StringCompare: {
StringCompareStub stub;
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
break;
}
case CodeStub::TranscendentalCache: {
TranscendentalCacheStub stub(instr->transcendental_type(),
TranscendentalCacheStub::TAGGED);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
break;
}
default:
UNREACHABLE();
}
}
void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
// Nothing to do.
}
void LCodeGen::DoModI(LModI* instr) {
if (instr->hydrogen()->HasPowerOf2Divisor()) {
Register dividend = ToRegister(instr->left());
int32_t divisor =
HConstant::cast(instr->hydrogen()->right())->Integer32Value();
if (divisor < 0) divisor = -divisor;
Label positive_dividend, done;
__ testl(dividend, dividend);
__ j(not_sign, &positive_dividend, Label::kNear);
__ negl(dividend);
__ andl(dividend, Immediate(divisor - 1));
__ negl(dividend);
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
__ j(not_zero, &done, Label::kNear);
DeoptimizeIf(no_condition, instr->environment());
} else {
__ jmp(&done, Label::kNear);
}
__ bind(&positive_dividend);
__ andl(dividend, Immediate(divisor - 1));
__ bind(&done);
} else {
Label done, remainder_eq_dividend, slow, do_subtraction, both_positive;
Register left_reg = ToRegister(instr->left());
Register right_reg = ToRegister(instr->right());
Register result_reg = ToRegister(instr->result());
ASSERT(left_reg.is(rax));
ASSERT(result_reg.is(rdx));
ASSERT(!right_reg.is(rax));
ASSERT(!right_reg.is(rdx));
// Check for x % 0.
if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) {
__ testl(right_reg, right_reg);
DeoptimizeIf(zero, instr->environment());
}
__ testl(left_reg, left_reg);
__ j(zero, &remainder_eq_dividend, Label::kNear);
__ j(sign, &slow, Label::kNear);
__ testl(right_reg, right_reg);
__ j(not_sign, &both_positive, Label::kNear);
// The sign of the divisor doesn't matter.
__ neg(right_reg);
__ bind(&both_positive);
// If the dividend is smaller than the nonnegative
// divisor, the dividend is the result.
__ cmpl(left_reg, right_reg);
__ j(less, &remainder_eq_dividend, Label::kNear);
// Check if the divisor is a PowerOfTwo integer.
Register scratch = ToRegister(instr->temp());
__ movl(scratch, right_reg);
__ subl(scratch, Immediate(1));
__ testl(scratch, right_reg);
__ j(not_zero, &do_subtraction, Label::kNear);
__ andl(left_reg, scratch);
__ jmp(&remainder_eq_dividend, Label::kNear);
__ bind(&do_subtraction);
const int kUnfolds = 3;
// Try a few subtractions of the dividend.
__ movl(scratch, left_reg);
for (int i = 0; i < kUnfolds; i++) {
// Reduce the dividend by the divisor.
__ subl(left_reg, right_reg);
// Check if the dividend is less than the divisor.
__ cmpl(left_reg, right_reg);
__ j(less, &remainder_eq_dividend, Label::kNear);
}
__ movl(left_reg, scratch);
// Slow case, using idiv instruction.
__ bind(&slow);
// Sign extend eax to edx.
// (We are using only the low 32 bits of the values.)
__ cdq();
// Check for (0 % -x) that will produce negative zero.
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
Label positive_left;
Label done;
__ testl(left_reg, left_reg);
__ j(not_sign, &positive_left, Label::kNear);
__ idivl(right_reg);
// Test the remainder for 0, because then the result would be -0.
__ testl(result_reg, result_reg);
__ j(not_zero, &done, Label::kNear);
DeoptimizeIf(no_condition, instr->environment());
__ bind(&positive_left);
__ idivl(right_reg);
__ bind(&done);
} else {
__ idivl(right_reg);
}
__ jmp(&done, Label::kNear);
__ bind(&remainder_eq_dividend);
__ movl(result_reg, left_reg);
__ bind(&done);
}
}
void LCodeGen::DoMathFloorOfDiv(LMathFloorOfDiv* instr) {
ASSERT(instr->right()->IsConstantOperand());
const Register dividend = ToRegister(instr->left());
int32_t divisor = ToInteger32(LConstantOperand::cast(instr->right()));
const Register result = ToRegister(instr->result());
switch (divisor) {
case 0:
DeoptimizeIf(no_condition, instr->environment());
return;
case 1:
if (!result.is(dividend)) {
__ movl(result, dividend);
}
return;
case -1:
if (!result.is(dividend)) {
__ movl(result, dividend);
}
__ negl(result);
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
DeoptimizeIf(zero, instr->environment());
}
if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
DeoptimizeIf(overflow, instr->environment());
}
return;
}
uint32_t divisor_abs = abs(divisor);
if (IsPowerOf2(divisor_abs)) {
int32_t power = WhichPowerOf2(divisor_abs);
if (divisor < 0) {
__ movsxlq(result, dividend);
__ neg(result);
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
DeoptimizeIf(zero, instr->environment());
}
__ sar(result, Immediate(power));
} else {
if (!result.is(dividend)) {
__ movl(result, dividend);
}
__ sarl(result, Immediate(power));
}
} else {
Register reg1 = ToRegister(instr->temp());
Register reg2 = ToRegister(instr->result());
// Find b which: 2^b < divisor_abs < 2^(b+1).
unsigned b = 31 - CompilerIntrinsics::CountLeadingZeros(divisor_abs);
unsigned shift = 32 + b; // Precision +1bit (effectively).
double multiplier_f =
static_cast<double>(static_cast<uint64_t>(1) << shift) / divisor_abs;
int64_t multiplier;
if (multiplier_f - floor(multiplier_f) < 0.5) {
multiplier = static_cast<int64_t>(floor(multiplier_f));
} else {
multiplier = static_cast<int64_t>(floor(multiplier_f)) + 1;
}
// The multiplier is a uint32.
ASSERT(multiplier > 0 &&
multiplier < (static_cast<int64_t>(1) << 32));
// The multiply is int64, so sign-extend to r64.
__ movsxlq(reg1, dividend);
if (divisor < 0 &&
instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
__ neg(reg1);
DeoptimizeIf(zero, instr->environment());
}
__ movq(reg2, multiplier, RelocInfo::NONE);
// Result just fit in r64, because it's int32 * uint32.
__ imul(reg2, reg1);
__ addq(reg2, Immediate(1 << 30));
__ sar(reg2, Immediate(shift));
}
}
void LCodeGen::DoDivI(LDivI* instr) {
LOperand* right = instr->right();
ASSERT(ToRegister(instr->result()).is(rax));
ASSERT(ToRegister(instr->left()).is(rax));
ASSERT(!ToRegister(instr->right()).is(rax));
ASSERT(!ToRegister(instr->right()).is(rdx));
Register left_reg = rax;
// Check for x / 0.
Register right_reg = ToRegister(right);
if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) {
__ testl(right_reg, right_reg);
DeoptimizeIf(zero, instr->environment());
}
// Check for (0 / -x) that will produce negative zero.
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
Label left_not_zero;
__ testl(left_reg, left_reg);
__ j(not_zero, &left_not_zero, Label::kNear);
__ testl(right_reg, right_reg);
DeoptimizeIf(sign, instr->environment());
__ bind(&left_not_zero);
}
// Check for (-kMinInt / -1).
if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
Label left_not_min_int;
__ cmpl(left_reg, Immediate(kMinInt));
__ j(not_zero, &left_not_min_int, Label::kNear);
__ cmpl(right_reg, Immediate(-1));
DeoptimizeIf(zero, instr->environment());
__ bind(&left_not_min_int);
}
// Sign extend to rdx.
__ cdq();
__ idivl(right_reg);
// Deoptimize if remainder is not 0.
__ testl(rdx, rdx);
DeoptimizeIf(not_zero, instr->environment());
}
void LCodeGen::DoMulI(LMulI* instr) {
Register left = ToRegister(instr->left());
LOperand* right = instr->right();
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
__ movl(kScratchRegister, left);
}
bool can_overflow =
instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
if (right->IsConstantOperand()) {
int right_value = ToInteger32(LConstantOperand::cast(right));
if (right_value == -1) {
__ negl(left);
} else if (right_value == 0) {
__ xorl(left, left);
} else if (right_value == 2) {
__ addl(left, left);
} else if (!can_overflow) {
// If the multiplication is known to not overflow, we
// can use operations that don't set the overflow flag
// correctly.
switch (right_value) {
case 1:
// Do nothing.
break;
case 3:
__ leal(left, Operand(left, left, times_2, 0));
break;
case 4:
__ shll(left, Immediate(2));
break;
case 5:
__ leal(left, Operand(left, left, times_4, 0));
break;
case 8:
__ shll(left, Immediate(3));
break;
case 9:
__ leal(left, Operand(left, left, times_8, 0));
break;
case 16:
__ shll(left, Immediate(4));
break;
default:
__ imull(left, left, Immediate(right_value));
break;
}
} else {
__ imull(left, left, Immediate(right_value));
}
} else if (right->IsStackSlot()) {
__ imull(left, ToOperand(right));
} else {
__ imull(left, ToRegister(right));
}
if (can_overflow) {
DeoptimizeIf(overflow, instr->environment());
}
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
// Bail out if the result is supposed to be negative zero.
Label done;
__ testl(left, left);
__ j(not_zero, &done, Label::kNear);
if (right->IsConstantOperand()) {
if (ToInteger32(LConstantOperand::cast(right)) < 0) {
DeoptimizeIf(no_condition, instr->environment());
} else if (ToInteger32(LConstantOperand::cast(right)) == 0) {
__ cmpl(kScratchRegister, Immediate(0));
DeoptimizeIf(less, instr->environment());
}
} else if (right->IsStackSlot()) {
__ orl(kScratchRegister, ToOperand(right));
DeoptimizeIf(sign, instr->environment());
} else {
// Test the non-zero operand for negative sign.
__ orl(kScratchRegister, ToRegister(right));
DeoptimizeIf(sign, instr->environment());
}
__ bind(&done);
}
}
void LCodeGen::DoBitI(LBitI* instr) {
LOperand* left = instr->left();
LOperand* right = instr->right();
ASSERT(left->Equals(instr->result()));
ASSERT(left->IsRegister());
if (right->IsConstantOperand()) {
int right_operand = ToInteger32(LConstantOperand::cast(right));
switch (instr->op()) {
case Token::BIT_AND:
__ andl(ToRegister(left), Immediate(right_operand));
break;
case Token::BIT_OR:
__ orl(ToRegister(left), Immediate(right_operand));
break;
case Token::BIT_XOR:
__ xorl(ToRegister(left), Immediate(right_operand));
break;
default:
UNREACHABLE();
break;
}
} else if (right->IsStackSlot()) {
switch (instr->op()) {
case Token::BIT_AND:
__ andl(ToRegister(left), ToOperand(right));
break;
case Token::BIT_OR:
__ orl(ToRegister(left), ToOperand(right));
break;
case Token::BIT_XOR:
__ xorl(ToRegister(left), ToOperand(right));
break;
default:
UNREACHABLE();
break;
}
} else {
ASSERT(right->IsRegister());
switch (instr->op()) {
case Token::BIT_AND:
__ andl(ToRegister(left), ToRegister(right));
break;
case Token::BIT_OR:
__ orl(ToRegister(left), ToRegister(right));
break;
case Token::BIT_XOR:
__ xorl(ToRegister(left), ToRegister(right));
break;
default:
UNREACHABLE();
break;
}
}
}
void LCodeGen::DoShiftI(LShiftI* instr) {
LOperand* left = instr->left();
LOperand* right = instr->right();
ASSERT(left->Equals(instr->result()));
ASSERT(left->IsRegister());
if (right->IsRegister()) {
ASSERT(ToRegister(right).is(rcx));
switch (instr->op()) {
case Token::ROR:
__ rorl_cl(ToRegister(left));
break;
case Token::SAR:
__ sarl_cl(ToRegister(left));
break;
case Token::SHR:
__ shrl_cl(ToRegister(left));
if (instr->can_deopt()) {
__ testl(ToRegister(left), ToRegister(left));
DeoptimizeIf(negative, instr->environment());
}
break;
case Token::SHL:
__ shll_cl(ToRegister(left));
break;
default:
UNREACHABLE();
break;
}
} else {
int value = ToInteger32(LConstantOperand::cast(right));
uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
switch (instr->op()) {
case Token::ROR:
if (shift_count != 0) {
__ rorl(ToRegister(left), Immediate(shift_count));
}
break;
case Token::SAR:
if (shift_count != 0) {
__ sarl(ToRegister(left), Immediate(shift_count));
}
break;
case Token::SHR:
if (shift_count == 0 && instr->can_deopt()) {
__ testl(ToRegister(left), ToRegister(left));
DeoptimizeIf(negative, instr->environment());
} else {
__ shrl(ToRegister(left), Immediate(shift_count));
}
break;
case Token::SHL:
if (shift_count != 0) {
__ shll(ToRegister(left), Immediate(shift_count));
}
break;
default:
UNREACHABLE();
break;
}
}
}
void LCodeGen::DoSubI(LSubI* instr) {
LOperand* left = instr->left();
LOperand* right = instr->right();
ASSERT(left->Equals(instr->result()));
if (right->IsConstantOperand()) {
__ subl(ToRegister(left),
Immediate(ToInteger32(LConstantOperand::cast(right))));
} else if (right->IsRegister()) {
__ subl(ToRegister(left), ToRegister(right));
} else {
__ subl(ToRegister(left), ToOperand(right));
}
if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
DeoptimizeIf(overflow, instr->environment());
}
}
void LCodeGen::DoConstantI(LConstantI* instr) {
ASSERT(instr->result()->IsRegister());
__ Set(ToRegister(instr->result()), instr->value());
}
void LCodeGen::DoConstantD(LConstantD* instr) {
ASSERT(instr->result()->IsDoubleRegister());
XMMRegister res = ToDoubleRegister(instr->result());
double v = instr->value();
uint64_t int_val = BitCast<uint64_t, double>(v);
// Use xor to produce +0.0 in a fast and compact way, but avoid to
// do so if the constant is -0.0.
if (int_val == 0) {
__ xorps(res, res);
} else {
Register tmp = ToRegister(instr->temp());
__ Set(tmp, int_val);
__ movq(res, tmp);
}
}
void LCodeGen::DoConstantT(LConstantT* instr) {
Handle<Object> value = instr->value();
if (value->IsSmi()) {
__ Move(ToRegister(instr->result()), value);
} else {
__ LoadHeapObject(ToRegister(instr->result()),
Handle<HeapObject>::cast(value));
}
}
void LCodeGen::DoJSArrayLength(LJSArrayLength* instr) {
Register result = ToRegister(instr->result());
Register array = ToRegister(instr->value());
__ movq(result, FieldOperand(array, JSArray::kLengthOffset));
}
void LCodeGen::DoFixedArrayBaseLength(LFixedArrayBaseLength* instr) {
Register result = ToRegister(instr->result());
Register array = ToRegister(instr->value());
__ movq(result, FieldOperand(array, FixedArrayBase::kLengthOffset));
}
void LCodeGen::DoMapEnumLength(LMapEnumLength* instr) {
Register result = ToRegister(instr->result());
Register map = ToRegister(instr->value());
__ EnumLength(result, map);
}
void LCodeGen::DoElementsKind(LElementsKind* instr) {
Register result = ToRegister(instr->result());
Register input = ToRegister(instr->value());
// Load map into |result|.
__ movq(result, FieldOperand(input, HeapObject::kMapOffset));
// Load the map's "bit field 2" into |result|. We only need the first byte.
__ movzxbq(result, FieldOperand(result, Map::kBitField2Offset));
// Retrieve elements_kind from bit field 2.
__ and_(result, Immediate(Map::kElementsKindMask));
__ shr(result, Immediate(Map::kElementsKindShift));
}
void LCodeGen::DoValueOf(LValueOf* instr) {
Register input = ToRegister(instr->value());
Register result = ToRegister(instr->result());
ASSERT(input.is(result));
Label done;
// If the object is a smi return the object.
__ JumpIfSmi(input, &done, Label::kNear);
// If the object is not a value type, return the object.
__ CmpObjectType(input, JS_VALUE_TYPE, kScratchRegister);
__ j(not_equal, &done, Label::kNear);
__ movq(result, FieldOperand(input, JSValue::kValueOffset));
__ bind(&done);
}
void LCodeGen::DoDateField(LDateField* instr) {
Register object = ToRegister(instr->date());
Register result = ToRegister(instr->result());
Smi* index = instr->index();
Label runtime, done, not_date_object;
ASSERT(object.is(result));
ASSERT(object.is(rax));
Condition cc = masm()->CheckSmi(object);
DeoptimizeIf(cc, instr->environment());
__ CmpObjectType(object, JS_DATE_TYPE, kScratchRegister);
DeoptimizeIf(not_equal, instr->environment());
if (index->value() == 0) {
__ movq(result, FieldOperand(object, JSDate::kValueOffset));
} else {
if (index->value() < JSDate::kFirstUncachedField) {
ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
__ movq(kScratchRegister, stamp);
__ cmpq(kScratchRegister, FieldOperand(object,
JSDate::kCacheStampOffset));
__ j(not_equal, &runtime, Label::kNear);
__ movq(result, FieldOperand(object, JSDate::kValueOffset +
kPointerSize * index->value()));
__ jmp(&done);
}
__ bind(&runtime);
__ PrepareCallCFunction(2);
#ifdef _WIN64
__ movq(rcx, object);
__ movq(rdx, index, RelocInfo::NONE);
#else
__ movq(rdi, object);
__ movq(rsi, index, RelocInfo::NONE);
#endif
__ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
__ bind(&done);
}
}
void LCodeGen::DoBitNotI(LBitNotI* instr) {
LOperand* input = instr->value();
ASSERT(input->Equals(instr->result()));
__ not_(ToRegister(input));
}
void LCodeGen::DoThrow(LThrow* instr) {
__ push(ToRegister(instr->value()));
CallRuntime(Runtime::kThrow, 1, instr);
if (FLAG_debug_code) {
Comment("Unreachable code.");
__ int3();
}
}
void LCodeGen::DoAddI(LAddI* instr) {
LOperand* left = instr->left();
LOperand* right = instr->right();
ASSERT(left->Equals(instr->result()));
if (right->IsConstantOperand()) {
__ addl(ToRegister(left),
Immediate(ToInteger32(LConstantOperand::cast(right))));
} else if (right->IsRegister()) {
__ addl(ToRegister(left), ToRegister(right));
} else {
__ addl(ToRegister(left), ToOperand(right));
}
if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) {
DeoptimizeIf(overflow, instr->environment());
}
}
void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
LOperand* left = instr->left();
LOperand* right = instr->right();
ASSERT(left->Equals(instr->result()));
HMathMinMax::Operation operation = instr->hydrogen()->operation();
if (instr->hydrogen()->representation().IsInteger32()) {
Label return_left;
Condition condition = (operation == HMathMinMax::kMathMin)
? less_equal
: greater_equal;
Register left_reg = ToRegister(left);
if (right->IsConstantOperand()) {
Immediate right_imm =
Immediate(ToInteger32(LConstantOperand::cast(right)));
__ cmpq(left_reg, right_imm);
__ j(condition, &return_left, Label::kNear);
__ movq(left_reg, right_imm);
} else if (right->IsRegister()) {
Register right_reg = ToRegister(right);
__ cmpq(left_reg, right_reg);
__ j(condition, &return_left, Label::kNear);
__ movq(left_reg, right_reg);
} else {
Operand right_op = ToOperand(right);
__ cmpq(left_reg, right_op);
__ j(condition, &return_left, Label::kNear);
__ movq(left_reg, right_op);
}
__ bind(&return_left);
} else {
ASSERT(instr->hydrogen()->representation().IsDouble());
Label check_nan_left, check_zero, return_left, return_right;
Condition condition = (operation == HMathMinMax::kMathMin) ? below : above;
XMMRegister left_reg = ToDoubleRegister(left);
XMMRegister right_reg = ToDoubleRegister(right);
__ ucomisd(left_reg, right_reg);
__ j(parity_even, &check_nan_left, Label::kNear); // At least one NaN.
__ j(equal, &check_zero, Label::kNear); // left == right.
__ j(condition, &return_left, Label::kNear);
__ jmp(&return_right, Label::kNear);
__ bind(&check_zero);
XMMRegister xmm_scratch = xmm0;
__ xorps(xmm_scratch, xmm_scratch);
__ ucomisd(left_reg, xmm_scratch);
__ j(not_equal, &return_left, Label::kNear); // left == right != 0.
// At this point, both left and right are either 0 or -0.
if (operation == HMathMinMax::kMathMin) {
__ orpd(left_reg, right_reg);
} else {
// Since we operate on +0 and/or -0, addsd and andsd have the same effect.
__ addsd(left_reg, right_reg);
}
__ jmp(&return_left, Label::kNear);
__ bind(&check_nan_left);
__ ucomisd(left_reg, left_reg); // NaN check.
__ j(parity_even, &return_left, Label::kNear);
__ bind(&return_right);
__ movsd(left_reg, right_reg);
__ bind(&return_left);
}
}
void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
XMMRegister left = ToDoubleRegister(instr->left());
XMMRegister right = ToDoubleRegister(instr->right());
XMMRegister result = ToDoubleRegister(instr->result());
// All operations except MOD are computed in-place.
ASSERT(instr->op() == Token::MOD || left.is(result));
switch (instr->op()) {
case Token::ADD:
__ addsd(left, right);
break;
case Token::SUB:
__ subsd(left, right);
break;
case Token::MUL:
__ mulsd(left, right);
break;
case Token::DIV:
__ divsd(left, right);
break;
case Token::MOD:
__ PrepareCallCFunction(2);
__ movaps(xmm0, left);
ASSERT(right.is(xmm1));
__ CallCFunction(
ExternalReference::double_fp_operation(Token::MOD, isolate()), 2);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
__ movaps(result, xmm0);
break;
default:
UNREACHABLE();
break;
}
}
void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
ASSERT(ToRegister(instr->left()).is(rdx));
ASSERT(ToRegister(instr->right()).is(rax));
ASSERT(ToRegister(instr->result()).is(rax));
BinaryOpStub stub(instr->op(), NO_OVERWRITE);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
__ nop(); // Signals no inlined code.
}
int LCodeGen::GetNextEmittedBlock(int block) {
for (int i = block + 1; i < graph()->blocks()->length(); ++i) {
LLabel* label = chunk_->GetLabel(i);
if (!label->HasReplacement()) return i;
}
return -1;
}
void LCodeGen::EmitBranch(int left_block, int right_block, Condition cc) {
int next_block = GetNextEmittedBlock(current_block_);
right_block = chunk_->LookupDestination(right_block);
left_block = chunk_->LookupDestination(left_block);
if (right_block == left_block) {
EmitGoto(left_block);
} else if (left_block == next_block) {
__ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block));
} else if (right_block == next_block) {
__ j(cc, chunk_->GetAssemblyLabel(left_block));
} else {
__ j(cc, chunk_->GetAssemblyLabel(left_block));
if (cc != always) {
__ jmp(chunk_->GetAssemblyLabel(right_block));
}
}
}
void LCodeGen::DoBranch(LBranch* instr) {
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Representation r = instr->hydrogen()->value()->representation();
if (r.IsInteger32()) {
Register reg = ToRegister(instr->value());
__ testl(reg, reg);
EmitBranch(true_block, false_block, not_zero);
} else if (r.IsDouble()) {
XMMRegister reg = ToDoubleRegister(instr->value());
__ xorps(xmm0, xmm0);
__ ucomisd(reg, xmm0);
EmitBranch(true_block, false_block, not_equal);
} else {
ASSERT(r.IsTagged());
Register reg = ToRegister(instr->value());
HType type = instr->hydrogen()->value()->type();
if (type.IsBoolean()) {
__ CompareRoot(reg, Heap::kTrueValueRootIndex);
EmitBranch(true_block, false_block, equal);
} else if (type.IsSmi()) {
__ SmiCompare(reg, Smi::FromInt(0));
EmitBranch(true_block, false_block, not_equal);
} else {
Label* true_label = chunk_->GetAssemblyLabel(true_block);
Label* false_label = chunk_->GetAssemblyLabel(false_block);
ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types();
// Avoid deopts in the case where we've never executed this path before.
if (expected.IsEmpty()) expected = ToBooleanStub::all_types();
if (expected.Contains(ToBooleanStub::UNDEFINED)) {
// undefined -> false.
__ CompareRoot(reg, Heap::kUndefinedValueRootIndex);
__ j(equal, false_label);
}
if (expected.Contains(ToBooleanStub::BOOLEAN)) {
// true -> true.
__ CompareRoot(reg, Heap::kTrueValueRootIndex);
__ j(equal, true_label);
// false -> false.
__ CompareRoot(reg, Heap::kFalseValueRootIndex);
__ j(equal, false_label);
}
if (expected.Contains(ToBooleanStub::NULL_TYPE)) {
// 'null' -> false.
__ CompareRoot(reg, Heap::kNullValueRootIndex);
__ j(equal, false_label);
}
if (expected.Contains(ToBooleanStub::SMI)) {
// Smis: 0 -> false, all other -> true.
__ Cmp(reg, Smi::FromInt(0));
__ j(equal, false_label);
__ JumpIfSmi(reg, true_label);
} else if (expected.NeedsMap()) {
// If we need a map later and have a Smi -> deopt.
__ testb(reg, Immediate(kSmiTagMask));
DeoptimizeIf(zero, instr->environment());
}
const Register map = kScratchRegister;
if (expected.NeedsMap()) {
__ movq(map, FieldOperand(reg, HeapObject::kMapOffset));
if (expected.CanBeUndetectable()) {
// Undetectable -> false.
__ testb(FieldOperand(map, Map::kBitFieldOffset),
Immediate(1 << Map::kIsUndetectable));
__ j(not_zero, false_label);
}
}
if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) {
// spec object -> true.
__ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE);
__ j(above_equal, true_label);
}
if (expected.Contains(ToBooleanStub::STRING)) {
// String value -> false iff empty.
Label not_string;
__ CmpInstanceType(map, FIRST_NONSTRING_TYPE);
__ j(above_equal, ¬_string, Label::kNear);
__ cmpq(FieldOperand(reg, String::kLengthOffset), Immediate(0));
__ j(not_zero, true_label);
__ jmp(false_label);
__ bind(¬_string);
}
if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) {
// heap number -> false iff +0, -0, or NaN.
Label not_heap_number;
__ CompareRoot(map, Heap::kHeapNumberMapRootIndex);
__ j(not_equal, ¬_heap_number, Label::kNear);
__ xorps(xmm0, xmm0);
__ ucomisd(xmm0, FieldOperand(reg, HeapNumber::kValueOffset));
__ j(zero, false_label);
__ jmp(true_label);
__ bind(¬_heap_number);
}
// We've seen something for the first time -> deopt.
DeoptimizeIf(no_condition, instr->environment());
}
}
}
void LCodeGen::EmitGoto(int block) {
block = chunk_->LookupDestination(block);
int next_block = GetNextEmittedBlock(current_block_);
if (block != next_block) {
__ jmp(chunk_->GetAssemblyLabel(block));
}
}
void LCodeGen::DoGoto(LGoto* instr) {
EmitGoto(instr->block_id());
}
inline Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
Condition cond = no_condition;
switch (op) {
case Token::EQ:
case Token::EQ_STRICT:
cond = equal;
break;
case Token::LT:
cond = is_unsigned ? below : less;
break;
case Token::GT:
cond = is_unsigned ? above : greater;
break;
case Token::LTE:
cond = is_unsigned ? below_equal : less_equal;
break;
case Token::GTE:
cond = is_unsigned ? above_equal : greater_equal;
break;
case Token::IN:
case Token::INSTANCEOF:
default:
UNREACHABLE();
}
return cond;
}
void LCodeGen::DoCmpIDAndBranch(LCmpIDAndBranch* instr) {
LOperand* left = instr->left();
LOperand* right = instr->right();
int false_block = chunk_->LookupDestination(instr->false_block_id());
int true_block = chunk_->LookupDestination(instr->true_block_id());
Condition cc = TokenToCondition(instr->op(), instr->is_double());
if (left->IsConstantOperand() && right->IsConstantOperand()) {
// We can statically evaluate the comparison.
double left_val = ToDouble(LConstantOperand::cast(left));
double right_val = ToDouble(LConstantOperand::cast(right));
int next_block =
EvalComparison(instr->op(), left_val, right_val) ? true_block
: false_block;
EmitGoto(next_block);
} else {
if (instr->is_double()) {
// Don't base result on EFLAGS when a NaN is involved. Instead
// jump to the false block.
__ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right));
__ j(parity_even, chunk_->GetAssemblyLabel(false_block));
} else {
int32_t value;
if (right->IsConstantOperand()) {
value = ToInteger32(LConstantOperand::cast(right));
__ cmpl(ToRegister(left), Immediate(value));
} else if (left->IsConstantOperand()) {
value = ToInteger32(LConstantOperand::cast(left));
if (right->IsRegister()) {
__ cmpl(ToRegister(right), Immediate(value));
} else {
__ cmpl(ToOperand(right), Immediate(value));
}
// We transposed the operands. Reverse the condition.
cc = ReverseCondition(cc);
} else {
if (right->IsRegister()) {
__ cmpl(ToRegister(left), ToRegister(right));
} else {
__ cmpl(ToRegister(left), ToOperand(right));
}
}
}
EmitBranch(true_block, false_block, cc);
}
}
void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
Register left = ToRegister(instr->left());
Register right = ToRegister(instr->right());
int false_block = chunk_->LookupDestination(instr->false_block_id());
int true_block = chunk_->LookupDestination(instr->true_block_id());
__ cmpq(left, right);
EmitBranch(true_block, false_block, equal);
}
void LCodeGen::DoCmpConstantEqAndBranch(LCmpConstantEqAndBranch* instr) {
Register left = ToRegister(instr->left());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
__ cmpq(left, Immediate(instr->hydrogen()->right()));
EmitBranch(true_block, false_block, equal);
}
void LCodeGen::DoIsNilAndBranch(LIsNilAndBranch* instr) {
Register reg = ToRegister(instr->value());
int false_block = chunk_->LookupDestination(instr->false_block_id());
// If the expression is known to be untagged or a smi, then it's definitely
// not null, and it can't be a an undetectable object.
if (instr->hydrogen()->representation().IsSpecialization() ||
instr->hydrogen()->type().IsSmi()) {
EmitGoto(false_block);
return;
}
int true_block = chunk_->LookupDestination(instr->true_block_id());
Heap::RootListIndex nil_value = instr->nil() == kNullValue ?
Heap::kNullValueRootIndex :
Heap::kUndefinedValueRootIndex;
__ CompareRoot(reg, nil_value);
if (instr->kind() == kStrictEquality) {
EmitBranch(true_block, false_block, equal);
} else {
Heap::RootListIndex other_nil_value = instr->nil() == kNullValue ?
Heap::kUndefinedValueRootIndex :
Heap::kNullValueRootIndex;
Label* true_label = chunk_->GetAssemblyLabel(true_block);
Label* false_label = chunk_->GetAssemblyLabel(false_block);
__ j(equal, true_label);
__ CompareRoot(reg, other_nil_value);
__ j(equal, true_label);
__ JumpIfSmi(reg, false_label);
// Check for undetectable objects by looking in the bit field in
// the map. The object has already been smi checked.
Register scratch = ToRegister(instr->temp());
__ movq(scratch, FieldOperand(reg, HeapObject::kMapOffset));
__ testb(FieldOperand(scratch, Map::kBitFieldOffset),
Immediate(1 << Map::kIsUndetectable));
EmitBranch(true_block, false_block, not_zero);
}
}
Condition LCodeGen::EmitIsObject(Register input,
Label* is_not_object,
Label* is_object) {
ASSERT(!input.is(kScratchRegister));
__ JumpIfSmi(input, is_not_object);
__ CompareRoot(input, Heap::kNullValueRootIndex);
__ j(equal, is_object);
__ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset));
// Undetectable objects behave like undefined.
__ testb(FieldOperand(kScratchRegister, Map::kBitFieldOffset),
Immediate(1 << Map::kIsUndetectable));
__ j(not_zero, is_not_object);
__ movzxbl(kScratchRegister,
FieldOperand(kScratchRegister, Map::kInstanceTypeOffset));
__ cmpb(kScratchRegister, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
__ j(below, is_not_object);
__ cmpb(kScratchRegister, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
return below_equal;
}
void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) {
Register reg = ToRegister(instr->value());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Label* true_label = chunk_->GetAssemblyLabel(true_block);
Label* false_label = chunk_->GetAssemblyLabel(false_block);
Condition true_cond = EmitIsObject(reg, false_label, true_label);
EmitBranch(true_block, false_block, true_cond);
}
Condition LCodeGen::EmitIsString(Register input,
Register temp1,
Label* is_not_string) {
__ JumpIfSmi(input, is_not_string);
Condition cond = masm_->IsObjectStringType(input, temp1, temp1);
return cond;
}
void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
Register reg = ToRegister(instr->value());
Register temp = ToRegister(instr->temp());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Label* false_label = chunk_->GetAssemblyLabel(false_block);
Condition true_cond = EmitIsString(reg, temp, false_label);
EmitBranch(true_block, false_block, true_cond);
}
void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Condition is_smi;
if (instr->value()->IsRegister()) {
Register input = ToRegister(instr->value());
is_smi = masm()->CheckSmi(input);
} else {
Operand input = ToOperand(instr->value());
is_smi = masm()->CheckSmi(input);
}
EmitBranch(true_block, false_block, is_smi);
}
void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
Register input = ToRegister(instr->value());
Register temp = ToRegister(instr->temp());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
__ JumpIfSmi(input, chunk_->GetAssemblyLabel(false_block));
__ movq(temp, FieldOperand(input, HeapObject::kMapOffset));
__ testb(FieldOperand(temp, Map::kBitFieldOffset),
Immediate(1 << Map::kIsUndetectable));
EmitBranch(true_block, false_block, not_zero);
}
void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
Token::Value op = instr->op();
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Handle<Code> ic = CompareIC::GetUninitialized(op);
CallCode(ic, RelocInfo::CODE_TARGET, instr);
Condition condition = TokenToCondition(op, false);
__ testq(rax, rax);
EmitBranch(true_block, false_block, condition);
}
static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
InstanceType from = instr->from();
InstanceType to = instr->to();
if (from == FIRST_TYPE) return to;
ASSERT(from == to || to == LAST_TYPE);
return from;
}
static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
InstanceType from = instr->from();
InstanceType to = instr->to();
if (from == to) return equal;
if (to == LAST_TYPE) return above_equal;
if (from == FIRST_TYPE) return below_equal;
UNREACHABLE();
return equal;
}
void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
Register input = ToRegister(instr->value());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Label* false_label = chunk_->GetAssemblyLabel(false_block);
__ JumpIfSmi(input, false_label);
__ CmpObjectType(input, TestType(instr->hydrogen()), kScratchRegister);
EmitBranch(true_block, false_block, BranchCondition(instr->hydrogen()));
}
void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) {
Register input = ToRegister(instr->value());
Register result = ToRegister(instr->result());
__ AssertString(input);
__ movl(result, FieldOperand(input, String::kHashFieldOffset));
ASSERT(String::kHashShift >= kSmiTagSize);
__ IndexFromHash(result, result);
}
void LCodeGen::DoHasCachedArrayIndexAndBranch(
LHasCachedArrayIndexAndBranch* instr) {
Register input = ToRegister(instr->value());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
__ testl(FieldOperand(input, String::kHashFieldOffset),
Immediate(String::kContainsCachedArrayIndexMask));
EmitBranch(true_block, false_block, equal);
}
// Branches to a label or falls through with the answer in the z flag.
// Trashes the temp register.
void LCodeGen::EmitClassOfTest(Label* is_true,
Label* is_false,
Handle<String> class_name,
Register input,
Register temp,
Register temp2) {
ASSERT(!input.is(temp));
ASSERT(!input.is(temp2));
ASSERT(!temp.is(temp2));
__ JumpIfSmi(input, is_false);
if (class_name->IsEqualTo(CStrVector("Function"))) {
// Assuming the following assertions, we can use the same compares to test
// for both being a function type and being in the object type range.
STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
FIRST_SPEC_OBJECT_TYPE + 1);
STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
LAST_SPEC_OBJECT_TYPE - 1);
STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
__ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp);
__ j(below, is_false);
__ j(equal, is_true);
__ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE);
__ j(equal, is_true);
} else {
// Faster code path to avoid two compares: subtract lower bound from the
// actual type and do a signed compare with the width of the type range.
__ movq(temp, FieldOperand(input, HeapObject::kMapOffset));
__ movzxbl(temp2, FieldOperand(temp, Map::kInstanceTypeOffset));
__ subq(temp2, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
__ cmpq(temp2, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE -
FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
__ j(above, is_false);
}
// Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range.
// Check if the constructor in the map is a function.
__ movq(temp, FieldOperand(temp, Map::kConstructorOffset));
// Objects with a non-function constructor have class 'Object'.
__ CmpObjectType(temp, JS_FUNCTION_TYPE, kScratchRegister);
if (class_name->IsEqualTo(CStrVector("Object"))) {
__ j(not_equal, is_true);
} else {
__ j(not_equal, is_false);
}
// temp now contains the constructor function. Grab the
// instance class name from there.
__ movq(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset));
__ movq(temp, FieldOperand(temp,
SharedFunctionInfo::kInstanceClassNameOffset));
// The class name we are testing against is a symbol because it's a literal.
// The name in the constructor is a symbol because of the way the context is
// booted. This routine isn't expected to work for random API-created
// classes and it doesn't have to because you can't access it with natives
// syntax. Since both sides are symbols it is sufficient to use an identity
// comparison.
ASSERT(class_name->IsSymbol());
__ Cmp(temp, class_name);
// End with the answer in the z flag.
}
void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
Register input = ToRegister(instr->value());
Register temp = ToRegister(instr->temp());
Register temp2 = ToRegister(instr->temp2());
Handle<String> class_name = instr->hydrogen()->class_name();
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Label* true_label = chunk_->GetAssemblyLabel(true_block);
Label* false_label = chunk_->GetAssemblyLabel(false_block);
EmitClassOfTest(true_label, false_label, class_name, input, temp, temp2);
EmitBranch(true_block, false_block, equal);
}
void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
Register reg = ToRegister(instr->value());
int true_block = instr->true_block_id();
int false_block = instr->false_block_id();
__ Cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map());
EmitBranch(true_block, false_block, equal);
}
void LCodeGen::DoInstanceOf(LInstanceOf* instr) {
InstanceofStub stub(InstanceofStub::kNoFlags);
__ push(ToRegister(instr->left()));
__ push(ToRegister(instr->right()));
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
Label true_value, done;
__ testq(rax, rax);
__ j(zero, &true_value, Label::kNear);
__ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
__ jmp(&done, Label::kNear);
__ bind(&true_value);
__ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex);
__ bind(&done);
}
void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) {
class DeferredInstanceOfKnownGlobal: public LDeferredCode {
public:
DeferredInstanceOfKnownGlobal(LCodeGen* codegen,
LInstanceOfKnownGlobal* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() {
codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_);
}
virtual LInstruction* instr() { return instr_; }
Label* map_check() { return &map_check_; }
private:
LInstanceOfKnownGlobal* instr_;
Label map_check_;
};
DeferredInstanceOfKnownGlobal* deferred;
deferred = new(zone()) DeferredInstanceOfKnownGlobal(this, instr);
Label done, false_result;
Register object = ToRegister(instr->value());
// A Smi is not an instance of anything.
__ JumpIfSmi(object, &false_result);
// This is the inlined call site instanceof cache. The two occurences of the
// hole value will be patched to the last map/result pair generated by the
// instanceof stub.
Label cache_miss;
// Use a temp register to avoid memory operands with variable lengths.
Register map = ToRegister(instr->temp());
__ movq(map, FieldOperand(object, HeapObject::kMapOffset));
__ bind(deferred->map_check()); // Label for calculating code patching.
Handle<JSGlobalPropertyCell> cache_cell =
factory()->NewJSGlobalPropertyCell(factory()->the_hole_value());
__ movq(kScratchRegister, cache_cell, RelocInfo::GLOBAL_PROPERTY_CELL);
__ cmpq(map, Operand(kScratchRegister, 0));
__ j(not_equal, &cache_miss, Label::kNear);
// Patched to load either true or false.
__ LoadRoot(ToRegister(instr->result()), Heap::kTheHoleValueRootIndex);
#ifdef DEBUG
// Check that the code size between patch label and patch sites is invariant.
Label end_of_patched_code;
__ bind(&end_of_patched_code);
ASSERT(true);
#endif
__ jmp(&done);
// The inlined call site cache did not match. Check for null and string
// before calling the deferred code.
__ bind(&cache_miss); // Null is not an instance of anything.
__ CompareRoot(object, Heap::kNullValueRootIndex);
__ j(equal, &false_result, Label::kNear);
// String values are not instances of anything.
__ JumpIfNotString(object, kScratchRegister, deferred->entry());
__ bind(&false_result);
__ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
__ bind(deferred->exit());
__ bind(&done);
}
void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr,
Label* map_check) {
{
PushSafepointRegistersScope scope(this);
InstanceofStub::Flags flags = static_cast<InstanceofStub::Flags>(
InstanceofStub::kNoFlags | InstanceofStub::kCallSiteInlineCheck);
InstanceofStub stub(flags);
__ push(ToRegister(instr->value()));
__ PushHeapObject(instr->function());
static const int kAdditionalDelta = 10;
int delta =
masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta;
ASSERT(delta >= 0);
__ push_imm32(delta);
// We are pushing three values on the stack but recording a
// safepoint with two arguments because stub is going to
// remove the third argument from the stack before jumping
// to instanceof builtin on the slow path.
CallCodeGeneric(stub.GetCode(),
RelocInfo::CODE_TARGET,
instr,
RECORD_SAFEPOINT_WITH_REGISTERS,
2);
ASSERT(delta == masm_->SizeOfCodeGeneratedSince(map_check));
LEnvironment* env = instr->GetDeferredLazyDeoptimizationEnvironment();
safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
// Move result to a register that survives the end of the
// PushSafepointRegisterScope.
__ movq(kScratchRegister, rax);
}
__ testq(kScratchRegister, kScratchRegister);
Label load_false;
Label done;
__ j(not_zero, &load_false);
__ LoadRoot(rax, Heap::kTrueValueRootIndex);
__ jmp(&done);
__ bind(&load_false);
__ LoadRoot(rax, Heap::kFalseValueRootIndex);
__ bind(&done);
}
void LCodeGen::DoCmpT(LCmpT* instr) {
Token::Value op = instr->op();
Handle<Code> ic = CompareIC::GetUninitialized(op);
CallCode(ic, RelocInfo::CODE_TARGET, instr);
Condition condition = TokenToCondition(op, false);
Label true_value, done;
__ testq(rax, rax);
__ j(condition, &true_value, Label::kNear);
__ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
__ jmp(&done, Label::kNear);
__ bind(&true_value);
__ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex);
__ bind(&done);
}
void LCodeGen::DoReturn(LReturn* instr) {
if (FLAG_trace) {
// Preserve the return value on the stack and rely on the runtime
// call to return the value in the same register.
__ push(rax);
__ CallRuntime(Runtime::kTraceExit, 1);
}
__ movq(rsp, rbp);
__ pop(rbp);
__ Ret((GetParameterCount() + 1) * kPointerSize, rcx);
}
void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) {
Register result = ToRegister(instr->result());
__ LoadGlobalCell(result, instr->hydrogen()->cell());
if (instr->hydrogen()->RequiresHoleCheck()) {
__ CompareRoot(result, Heap::kTheHoleValueRootIndex);
DeoptimizeIf(equal, instr->environment());
}
}
void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) {
ASSERT(ToRegister(instr->global_object()).is(rax));
ASSERT(ToRegister(instr->result()).is(rax));
__ Move(rcx, instr->name());
RelocInfo::Mode mode = instr->for_typeof() ? RelocInfo::CODE_TARGET :
RelocInfo::CODE_TARGET_CONTEXT;
Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
CallCode(ic, mode, instr);
}
void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) {
Register value = ToRegister(instr->value());
Handle<JSGlobalPropertyCell> cell_handle = instr->hydrogen()->cell();
// If the cell we are storing to contains the hole it could have
// been deleted from the property dictionary. In that case, we need
// to update the property details in the property dictionary to mark
// it as no longer deleted. We deoptimize in that case.
if (instr->hydrogen()->RequiresHoleCheck()) {
// We have a temp because CompareRoot might clobber kScratchRegister.
Register cell = ToRegister(instr->temp());
ASSERT(!value.is(cell));
__ movq(cell, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL);
__ CompareRoot(Operand(cell, 0), Heap::kTheHoleValueRootIndex);
DeoptimizeIf(equal, instr->environment());
// Store the value.
__ movq(Operand(cell, 0), value);
} else {
// Store the value.
__ movq(kScratchRegister, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL);
__ movq(Operand(kScratchRegister, 0), value);
}
// Cells are always rescanned, so no write barrier here.
}
void LCodeGen::DoStoreGlobalGeneric(LStoreGlobalGeneric* instr) {
ASSERT(ToRegister(instr->global_object()).is(rdx));
ASSERT(ToRegister(instr->value()).is(rax));
__ Move(rcx, instr->name());
Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
? isolate()->builtins()->StoreIC_Initialize_Strict()
: isolate()->builtins()->StoreIC_Initialize();
CallCode(ic, RelocInfo::CODE_TARGET_CONTEXT, instr);
}
void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
Register context = ToRegister(instr->context());
Register result = ToRegister(instr->result());
__ movq(result, ContextOperand(context, instr->slot_index()));
if (instr->hydrogen()->RequiresHoleCheck()) {
__ CompareRoot(result, Heap::kTheHoleValueRootIndex);
if (instr->hydrogen()->DeoptimizesOnHole()) {
DeoptimizeIf(equal, instr->environment());
} else {
Label is_not_hole;
__ j(not_equal, &is_not_hole, Label::kNear);
__ LoadRoot(result, Heap::kUndefinedValueRootIndex);
__ bind(&is_not_hole);
}
}
}
void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
Register context = ToRegister(instr->context());
Register value = ToRegister(instr->value());
Operand target = ContextOperand(context, instr->slot_index());
Label skip_assignment;
if (instr->hydrogen()->RequiresHoleCheck()) {
__ CompareRoot(target, Heap::kTheHoleValueRootIndex);
if (instr->hydrogen()->DeoptimizesOnHole()) {
DeoptimizeIf(equal, instr->environment());
} else {
__ j(not_equal, &skip_assignment);
}
}
__ movq(target, value);
if (instr->hydrogen()->NeedsWriteBarrier()) {
HType type = instr->hydrogen()->value()->type();
SmiCheck check_needed =
type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
int offset = Context::SlotOffset(instr->slot_index());
Register scratch = ToRegister(instr->temp());
__ RecordWriteContextSlot(context,
offset,
value,
scratch,
kSaveFPRegs,
EMIT_REMEMBERED_SET,
check_needed);
}
__ bind(&skip_assignment);
}
void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
Register object = ToRegister(instr->object());
Register result = ToRegister(instr->result());
if (instr->hydrogen()->is_in_object()) {
__ movq(result, FieldOperand(object, instr->hydrogen()->offset()));
} else {
__ movq(result, FieldOperand(object, JSObject::kPropertiesOffset));
__ movq(result, FieldOperand(result, instr->hydrogen()->offset()));
}
}
void LCodeGen::EmitLoadFieldOrConstantFunction(Register result,
Register object,
Handle<Map> type,
Handle<String> name,
LEnvironment* env) {
LookupResult lookup(isolate());
type->LookupDescriptor(NULL, *name, &lookup);
ASSERT(lookup.IsFound() || lookup.IsCacheable());
if (lookup.IsField()) {
int index = lookup.GetLocalFieldIndexFromMap(*type);
int offset = index * kPointerSize;
if (index < 0) {
// Negative property indices are in-object properties, indexed
// from the end of the fixed part of the object.
__ movq(result, FieldOperand(object, offset + type->instance_size()));
} else {
// Non-negative property indices are in the properties array.
__ movq(result, FieldOperand(object, JSObject::kPropertiesOffset));
__ movq(result, FieldOperand(result, offset + FixedArray::kHeaderSize));
}
} else if (lookup.IsConstantFunction()) {
Handle<JSFunction> function(lookup.GetConstantFunctionFromMap(*type));
__ LoadHeapObject(result, function);
} else {
// Negative lookup.
// Check prototypes.
Handle<HeapObject> current(HeapObject::cast((*type)->prototype()));
Heap* heap = type->GetHeap();
while (*current != heap->null_value()) {
__ LoadHeapObject(result, current);
__ Cmp(FieldOperand(result, HeapObject::kMapOffset),
Handle<Map>(current->map()));
DeoptimizeIf(not_equal, env);
current =
Handle<HeapObject>(HeapObject::cast(current->map()->prototype()));
}
__ LoadRoot(result, Heap::kUndefinedValueRootIndex);
}
}
// Check for cases where EmitLoadFieldOrConstantFunction needs to walk the
// prototype chain, which causes unbounded code generation.
static bool CompactEmit(SmallMapList* list,
Handle<String> name,
int i,
Isolate* isolate) {
Handle<Map> map = list->at(i);
// If the map has ElementsKind transitions, we will generate map checks
// for each kind in __ CompareMap(..., ALLOW_ELEMENTS_TRANSITION_MAPS).
if (map->HasElementsTransition()) return false;
LookupResult lookup(isolate);
map->LookupDescriptor(NULL, *name, &lookup);
return lookup.IsField() || lookup.IsConstantFunction();
}
void LCodeGen::DoLoadNamedFieldPolymorphic(LLoadNamedFieldPolymorphic* instr) {
Register object = ToRegister(instr->object());
Register result = ToRegister(instr->result());
int map_count = instr->hydrogen()->types()->length();
bool need_generic = instr->hydrogen()->need_generic();
if (map_count == 0 && !need_generic) {
DeoptimizeIf(no_condition, instr->environment());
return;
}
Handle<String> name = instr->hydrogen()->name();
Label done;
bool all_are_compact = true;
for (int i = 0; i < map_count; ++i) {
if (!CompactEmit(instr->hydrogen()->types(), name, i, isolate())) {
all_are_compact = false;
break;
}
}
for (int i = 0; i < map_count; ++i) {
bool last = (i == map_count - 1);
Handle<Map> map = instr->hydrogen()->types()->at(i);
Label check_passed;
__ CompareMap(object, map, &check_passed, ALLOW_ELEMENT_TRANSITION_MAPS);
if (last && !need_generic) {
DeoptimizeIf(not_equal, instr->environment());
__ bind(&check_passed);
EmitLoadFieldOrConstantFunction(
result, object, map, name, instr->environment());
} else {
Label next;
bool compact = all_are_compact ? true :
CompactEmit(instr->hydrogen()->types(), name, i, isolate());
__ j(not_equal, &next, compact ? Label::kNear : Label::kFar);
__ bind(&check_passed);
EmitLoadFieldOrConstantFunction(
result, object, map, name, instr->environment());
__ jmp(&done, all_are_compact ? Label::kNear : Label::kFar);
__ bind(&next);
}
}
if (need_generic) {
__ Move(rcx, name);
Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
CallCode(ic, RelocInfo::CODE_TARGET, instr);
}
__ bind(&done);
}
void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) {
ASSERT(ToRegister(instr->object()).is(rax));
ASSERT(ToRegister(instr->result()).is(rax));
__ Move(rcx, instr->name());
Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize();
CallCode(ic, RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
Register function = ToRegister(instr->function());
Register result = ToRegister(instr->result());
// Check that the function really is a function.
__ CmpObjectType(function, JS_FUNCTION_TYPE, result);
DeoptimizeIf(not_equal, instr->environment());
// Check whether the function has an instance prototype.
Label non_instance;
__ testb(FieldOperand(result, Map::kBitFieldOffset),
Immediate(1 << Map::kHasNonInstancePrototype));
__ j(not_zero, &non_instance, Label::kNear);
// Get the prototype or initial map from the function.
__ movq(result,
FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
// Check that the function has a prototype or an initial map.
__ CompareRoot(result, Heap::kTheHoleValueRootIndex);
DeoptimizeIf(equal, instr->environment());
// If the function does not have an initial map, we're done.
Label done;
__ CmpObjectType(result, MAP_TYPE, kScratchRegister);
__ j(not_equal, &done, Label::kNear);
// Get the prototype from the initial map.
__ movq(result, FieldOperand(result, Map::kPrototypeOffset));
__ jmp(&done, Label::kNear);
// Non-instance prototype: Fetch prototype from constructor field
// in the function's map.
__ bind(&non_instance);
__ movq(result, FieldOperand(result, Map::kConstructorOffset));
// All done.
__ bind(&done);
}
void LCodeGen::DoLoadElements(LLoadElements* instr) {
Register result = ToRegister(instr->result());
Register input = ToRegister(instr->object());
__ movq(result, FieldOperand(input, JSObject::kElementsOffset));
if (FLAG_debug_code) {
Label done, ok, fail;
__ CompareRoot(FieldOperand(result, HeapObject::kMapOffset),
Heap::kFixedArrayMapRootIndex);
__ j(equal, &done, Label::kNear);
__ CompareRoot(FieldOperand(result, HeapObject::kMapOffset),
Heap::kFixedCOWArrayMapRootIndex);
__ j(equal, &done, Label::kNear);
Register temp((result.is(rax)) ? rbx : rax);
__ push(temp);
__ movq(temp, FieldOperand(result, HeapObject::kMapOffset));
__ movzxbq(temp, FieldOperand(temp, Map::kBitField2Offset));
__ and_(temp, Immediate(Map::kElementsKindMask));
__ shr(temp, Immediate(Map::kElementsKindShift));
__ cmpl(temp, Immediate(GetInitialFastElementsKind()));
__ j(less, &fail, Label::kNear);
__ cmpl(temp, Immediate(TERMINAL_FAST_ELEMENTS_KIND));
__ j(less_equal, &ok, Label::kNear);
__ cmpl(temp, Immediate(FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND));
__ j(less, &fail, Label::kNear);
__ cmpl(temp, Immediate(LAST_EXTERNAL_ARRAY_ELEMENTS_KIND));
__ j(less_equal, &ok, Label::kNear);
__ bind(&fail);
__ Abort("Check for fast or external elements failed");
__ bind(&ok);
__ pop(temp);
__ bind(&done);
}
}
void LCodeGen::DoLoadExternalArrayPointer(
LLoadExternalArrayPointer* instr) {
Register result = ToRegister(instr->result());
Register input = ToRegister(instr->object());
__ movq(result, FieldOperand(input,
ExternalPixelArray::kExternalPointerOffset));
}
void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
Register arguments = ToRegister(instr->arguments());
Register length = ToRegister(instr->length());
Register result = ToRegister(instr->result());
// There are two words between the frame pointer and the last argument.
// Subtracting from length accounts for one of them add one more.
if (instr->index()->IsRegister()) {
__ subl(length, ToRegister(instr->index()));
} else {
__ subl(length, ToOperand(instr->index()));
}
__ movq(result, Operand(arguments, length, times_pointer_size, kPointerSize));
}
template <class T>
inline void LCodeGen::PrepareKeyForKeyedOp(T* hydrogen_instr, LOperand* key) {
if (ArrayOpClobbersKey<T>(hydrogen_instr)) {
// Even though the HLoad/StoreKeyed (in this case) instructions force
// the input representation for the key to be an integer, the input
// gets replaced during bound check elimination with the index argument
// to the bounds check, which can be tagged, so that case must be
// handled here, too.
Register key_reg = ToRegister(key);
if (hydrogen_instr->key()->representation().IsTagged()) {
__ SmiToInteger64(key_reg, key_reg);
} else if (hydrogen_instr->IsDehoisted()) {
// Sign extend key because it could be a 32 bit negative value
// and the dehoisted address computation happens in 64 bits
__ movsxlq(key_reg, key_reg);
}
}
}
void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
ElementsKind elements_kind = instr->elements_kind();
LOperand* key = instr->key();
PrepareKeyForKeyedOp(instr->hydrogen(), key);
Operand operand(BuildFastArrayOperand(
instr->elements(),
key,
elements_kind,
0,
instr->additional_index()));
if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
XMMRegister result(ToDoubleRegister(instr->result()));
__ movss(result, operand);
__ cvtss2sd(result, result);
} else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
__ movsd(ToDoubleRegister(instr->result()), operand);
} else {
Register result(ToRegister(instr->result()));
switch (elements_kind) {
case EXTERNAL_BYTE_ELEMENTS:
__ movsxbq(result, operand);
break;
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
case EXTERNAL_PIXEL_ELEMENTS:
__ movzxbq(result, operand);
break;
case EXTERNAL_SHORT_ELEMENTS:
__ movsxwq(result, operand);
break;
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ movzxwq(result, operand);
break;
case EXTERNAL_INT_ELEMENTS:
__ movsxlq(result, operand);
break;
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
__ movl(result, operand);
if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
__ testl(result, result);
DeoptimizeIf(negative, instr->environment());
}
break;
case EXTERNAL_FLOAT_ELEMENTS:
case EXTERNAL_DOUBLE_ELEMENTS:
case FAST_ELEMENTS:
case FAST_SMI_ELEMENTS:
case FAST_DOUBLE_ELEMENTS:
case FAST_HOLEY_ELEMENTS:
case FAST_HOLEY_SMI_ELEMENTS:
case FAST_HOLEY_DOUBLE_ELEMENTS:
case DICTIONARY_ELEMENTS:
case NON_STRICT_ARGUMENTS_ELEMENTS:
UNREACHABLE();
break;
}
}
}
void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
XMMRegister result(ToDoubleRegister(instr->result()));
LOperand* key = instr->key();
PrepareKeyForKeyedOp<HLoadKeyed>(instr->hydrogen(), key);
if (instr->hydrogen()->RequiresHoleCheck()) {
int offset = FixedDoubleArray::kHeaderSize - kHeapObjectTag +
sizeof(kHoleNanLower32);
Operand hole_check_operand = BuildFastArrayOperand(
instr->elements(),
key,
FAST_DOUBLE_ELEMENTS,
offset,
instr->additional_index());
__ cmpl(hole_check_operand, Immediate(kHoleNanUpper32));
DeoptimizeIf(equal, instr->environment());
}
Operand double_load_operand = BuildFastArrayOperand(
instr->elements(),
key,
FAST_DOUBLE_ELEMENTS,
FixedDoubleArray::kHeaderSize - kHeapObjectTag,
instr->additional_index());
__ movsd(result, double_load_operand);
}
void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
Register result = ToRegister(instr->result());
LOperand* key = instr->key();
PrepareKeyForKeyedOp<HLoadKeyed>(instr->hydrogen(), key);
// Load the result.
__ movq(result,
BuildFastArrayOperand(instr->elements(),
key,
FAST_ELEMENTS,
FixedArray::kHeaderSize - kHeapObjectTag,
instr->additional_index()));
// Check for the hole value.
if (instr->hydrogen()->RequiresHoleCheck()) {
if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
Condition smi = __ CheckSmi(result);
DeoptimizeIf(NegateCondition(smi), instr->environment());
} else {
__ CompareRoot(result, Heap::kTheHoleValueRootIndex);
DeoptimizeIf(equal, instr->environment());
}
}
}
void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
if (instr->is_external()) {
DoLoadKeyedExternalArray(instr);
} else if (instr->hydrogen()->representation().IsDouble()) {
DoLoadKeyedFixedDoubleArray(instr);
} else {
DoLoadKeyedFixedArray(instr);
}
}
Operand LCodeGen::BuildFastArrayOperand(
LOperand* elements_pointer,
LOperand* key,
ElementsKind elements_kind,
uint32_t offset,
uint32_t additional_index) {
Register elements_pointer_reg = ToRegister(elements_pointer);
int shift_size = ElementsKindToShiftSize(elements_kind);
if (key->IsConstantOperand()) {
int constant_value = ToInteger32(LConstantOperand::cast(key));
if (constant_value & 0xF0000000) {
Abort("array index constant value too big");
}
return Operand(elements_pointer_reg,
((constant_value + additional_index) << shift_size)
+ offset);
} else {
ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size);
return Operand(elements_pointer_reg,
ToRegister(key),
scale_factor,
offset + (additional_index << shift_size));
}
}
void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) {
ASSERT(ToRegister(instr->object()).is(rdx));
ASSERT(ToRegister(instr->key()).is(rax));
Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Initialize();
CallCode(ic, RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
Register result = ToRegister(instr->result());
if (instr->hydrogen()->from_inlined()) {
__ lea(result, Operand(rsp, -2 * kPointerSize));
} else {
// Check for arguments adapter frame.
Label done, adapted;
__ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
__ Cmp(Operand(result, StandardFrameConstants::kContextOffset),
Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
__ j(equal, &adapted, Label::kNear);
// No arguments adaptor frame.
__ movq(result, rbp);
__ jmp(&done, Label::kNear);
// Arguments adaptor frame present.
__ bind(&adapted);
__ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
// Result is the frame pointer for the frame if not adapted and for the real
// frame below the adaptor frame if adapted.
__ bind(&done);
}
}
void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
Register result = ToRegister(instr->result());
Label done;
// If no arguments adaptor frame the number of arguments is fixed.
if (instr->elements()->IsRegister()) {
__ cmpq(rbp, ToRegister(instr->elements()));
} else {
__ cmpq(rbp, ToOperand(instr->elements()));
}
__ movl(result, Immediate(scope()->num_parameters()));
__ j(equal, &done, Label::kNear);
// Arguments adaptor frame present. Get argument length from there.
__ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
__ SmiToInteger32(result,
Operand(result,
ArgumentsAdaptorFrameConstants::kLengthOffset));
// Argument length is in result register.
__ bind(&done);
}
void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
Register receiver = ToRegister(instr->receiver());
Register function = ToRegister(instr->function());
// If the receiver is null or undefined, we have to pass the global
// object as a receiver to normal functions. Values have to be
// passed unchanged to builtins and strict-mode functions.
Label global_object, receiver_ok;
// Do not transform the receiver to object for strict mode
// functions.
__ movq(kScratchRegister,
FieldOperand(function, JSFunction::kSharedFunctionInfoOffset));
__ testb(FieldOperand(kScratchRegister,
SharedFunctionInfo::kStrictModeByteOffset),
Immediate(1 << SharedFunctionInfo::kStrictModeBitWithinByte));
__ j(not_equal, &receiver_ok, Label::kNear);
// Do not transform the receiver to object for builtins.
__ testb(FieldOperand(kScratchRegister,
SharedFunctionInfo::kNativeByteOffset),
Immediate(1 << SharedFunctionInfo::kNativeBitWithinByte));
__ j(not_equal, &receiver_ok, Label::kNear);
// Normal function. Replace undefined or null with global receiver.
__ CompareRoot(receiver, Heap::kNullValueRootIndex);
__ j(equal, &global_object, Label::kNear);
__ CompareRoot(receiver, Heap::kUndefinedValueRootIndex);
__ j(equal, &global_object, Label::kNear);
// The receiver should be a JS object.
Condition is_smi = __ CheckSmi(receiver);
DeoptimizeIf(is_smi, instr->environment());
__ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, kScratchRegister);
DeoptimizeIf(below, instr->environment());
__ jmp(&receiver_ok, Label::kNear);
__ bind(&global_object);
// TODO(kmillikin): We have a hydrogen value for the global object. See
// if it's better to use it than to explicitly fetch it from the context
// here.
__ movq(receiver, ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX));
__ movq(receiver,
FieldOperand(receiver, JSGlobalObject::kGlobalReceiverOffset));
__ bind(&receiver_ok);
}
void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
Register receiver = ToRegister(instr->receiver());
Register function = ToRegister(instr->function());
Register length = ToRegister(instr->length());
Register elements = ToRegister(instr->elements());
ASSERT(receiver.is(rax)); // Used for parameter count.
ASSERT(function.is(rdi)); // Required by InvokeFunction.
ASSERT(ToRegister(instr->result()).is(rax));
// Copy the arguments to this function possibly from the
// adaptor frame below it.
const uint32_t kArgumentsLimit = 1 * KB;
__ cmpq(length, Immediate(kArgumentsLimit));
DeoptimizeIf(above, instr->environment());
__ push(receiver);
__ movq(receiver, length);
// Loop through the arguments pushing them onto the execution
// stack.
Label invoke, loop;
// length is a small non-negative integer, due to the test above.
__ testl(length, length);
__ j(zero, &invoke, Label::kNear);
__ bind(&loop);
__ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize));
__ decl(length);
__ j(not_zero, &loop);
// Invoke the function.
__ bind(&invoke);
ASSERT(instr->HasPointerMap());
LPointerMap* pointers = instr->pointer_map();
RecordPosition(pointers->position());
SafepointGenerator safepoint_generator(
this, pointers, Safepoint::kLazyDeopt);
ParameterCount actual(rax);
__ InvokeFunction(function, actual, CALL_FUNCTION,
safepoint_generator, CALL_AS_METHOD);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
void LCodeGen::DoPushArgument(LPushArgument* instr) {
LOperand* argument = instr->value();
EmitPushTaggedOperand(argument);
}
void LCodeGen::DoDrop(LDrop* instr) {
__ Drop(instr->count());
}
void LCodeGen::DoThisFunction(LThisFunction* instr) {
Register result = ToRegister(instr->result());
__ movq(result, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset));
}
void LCodeGen::DoContext(LContext* instr) {
Register result = ToRegister(instr->result());
__ movq(result, rsi);
}
void LCodeGen::DoOuterContext(LOuterContext* instr) {
Register context = ToRegister(instr->context());
Register result = ToRegister(instr->result());
__ movq(result,
Operand(context, Context::SlotOffset(Context::PREVIOUS_INDEX)));
}
void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
__ push(rsi); // The context is the first argument.
__ PushHeapObject(instr->hydrogen()->pairs());
__ Push(Smi::FromInt(instr->hydrogen()->flags()));
CallRuntime(Runtime::kDeclareGlobals, 3, instr);
}
void LCodeGen::DoGlobalObject(LGlobalObject* instr) {
Register result = ToRegister(instr->result());
__ movq(result, instr->qml_global()?QmlGlobalObjectOperand():GlobalObjectOperand());
}
void LCodeGen::DoGlobalReceiver(LGlobalReceiver* instr) {
Register global = ToRegister(instr->global());
Register result = ToRegister(instr->result());
__ movq(result, FieldOperand(global, GlobalObject::kGlobalReceiverOffset));
}
void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
int arity,
LInstruction* instr,
CallKind call_kind,
RDIState rdi_state) {
bool can_invoke_directly = !function->NeedsArgumentsAdaption() ||
function->shared()->formal_parameter_count() == arity;
LPointerMap* pointers = instr->pointer_map();
RecordPosition(pointers->position());
if (can_invoke_directly) {
if (rdi_state == RDI_UNINITIALIZED) {
__ LoadHeapObject(rdi, function);
}
// Change context.
__ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
// Set rax to arguments count if adaption is not needed. Assumes that rax
// is available to write to at this point.
if (!function->NeedsArgumentsAdaption()) {
__ Set(rax, arity);
}
// Invoke function.
__ SetCallKind(rcx, call_kind);
if (*function == *info()->closure()) {
__ CallSelf();
} else {
__ call(FieldOperand(rdi, JSFunction::kCodeEntryOffset));
}
// Set up deoptimization.
RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0);
} else {
// We need to adapt arguments.
SafepointGenerator generator(
this, pointers, Safepoint::kLazyDeopt);
ParameterCount count(arity);
__ InvokeFunction(function, count, CALL_FUNCTION, generator, call_kind);
}
// Restore context.
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
void LCodeGen::DoCallConstantFunction(LCallConstantFunction* instr) {
ASSERT(ToRegister(instr->result()).is(rax));
CallKnownFunction(instr->function(),
instr->arity(),
instr,
CALL_AS_METHOD,
RDI_UNINITIALIZED);
}
void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LUnaryMathOperation* instr) {
Register input_reg = ToRegister(instr->value());
__ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
Heap::kHeapNumberMapRootIndex);
DeoptimizeIf(not_equal, instr->environment());
Label done;
Register tmp = input_reg.is(rax) ? rcx : rax;
Register tmp2 = tmp.is(rcx) ? rdx : input_reg.is(rcx) ? rdx : rcx;
// Preserve the value of all registers.
PushSafepointRegistersScope scope(this);
Label negative;
__ movl(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset));
// Check the sign of the argument. If the argument is positive, just
// return it. We do not need to patch the stack since |input| and
// |result| are the same register and |input| will be restored
// unchanged by popping safepoint registers.
__ testl(tmp, Immediate(HeapNumber::kSignMask));
__ j(not_zero, &negative);
__ jmp(&done);
__ bind(&negative);
Label allocated, slow;
__ AllocateHeapNumber(tmp, tmp2, &slow);
__ jmp(&allocated);
// Slow case: Call the runtime system to do the number allocation.
__ bind(&slow);
CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr);
// Set the pointer to the new heap number in tmp.
if (!tmp.is(rax)) {
__ movq(tmp, rax);
}
// Restore input_reg after call to runtime.
__ LoadFromSafepointRegisterSlot(input_reg, input_reg);
__ bind(&allocated);
__ movq(tmp2, FieldOperand(input_reg, HeapNumber::kValueOffset));
__ shl(tmp2, Immediate(1));
__ shr(tmp2, Immediate(1));
__ movq(FieldOperand(tmp, HeapNumber::kValueOffset), tmp2);
__ StoreToSafepointRegisterSlot(input_reg, tmp);
__ bind(&done);
}
void LCodeGen::EmitIntegerMathAbs(LUnaryMathOperation* instr) {
Register input_reg = ToRegister(instr->value());
__ testl(input_reg, input_reg);
Label is_positive;
__ j(not_sign, &is_positive);
__ negl(input_reg); // Sets flags.
DeoptimizeIf(negative, instr->environment());
__ bind(&is_positive);
}
void LCodeGen::DoMathAbs(LUnaryMathOperation* instr) {
// Class for deferred case.
class DeferredMathAbsTaggedHeapNumber: public LDeferredCode {
public:
DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen,
LUnaryMathOperation* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() {
codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
}
virtual LInstruction* instr() { return instr_; }
private:
LUnaryMathOperation* instr_;
};
ASSERT(instr->value()->Equals(instr->result()));
Representation r = instr->hydrogen()->value()->representation();
if (r.IsDouble()) {
XMMRegister scratch = xmm0;
XMMRegister input_reg = ToDoubleRegister(instr->value());
__ xorps(scratch, scratch);
__ subsd(scratch, input_reg);
__ andpd(input_reg, scratch);
} else if (r.IsInteger32()) {
EmitIntegerMathAbs(instr);
} else { // Tagged case.
DeferredMathAbsTaggedHeapNumber* deferred =
new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
Register input_reg = ToRegister(instr->value());
// Smi check.
__ JumpIfNotSmi(input_reg, deferred->entry());
__ SmiToInteger32(input_reg, input_reg);
EmitIntegerMathAbs(instr);
__ Integer32ToSmi(input_reg, input_reg);
__ bind(deferred->exit());
}
}
void LCodeGen::DoMathFloor(LUnaryMathOperation* instr) {
XMMRegister xmm_scratch = xmm0;
Register output_reg = ToRegister(instr->result());
XMMRegister input_reg = ToDoubleRegister(instr->value());
if (CpuFeatures::IsSupported(SSE4_1)) {
CpuFeatures::Scope scope(SSE4_1);
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
// Deoptimize if minus zero.
__ movq(output_reg, input_reg);
__ subq(output_reg, Immediate(1));
DeoptimizeIf(overflow, instr->environment());
}
__ roundsd(xmm_scratch, input_reg, Assembler::kRoundDown);
__ cvttsd2si(output_reg, xmm_scratch);
__ cmpl(output_reg, Immediate(0x80000000));
DeoptimizeIf(equal, instr->environment());
} else {
Label negative_sign, done;
// Deoptimize on negative inputs.
__ xorps(xmm_scratch, xmm_scratch); // Zero the register.
__ ucomisd(input_reg, xmm_scratch);
DeoptimizeIf(parity_even, instr->environment());
__ j(below, &negative_sign, Label::kNear);
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
// Check for negative zero.
Label positive_sign;
__ j(above, &positive_sign, Label::kNear);
__ movmskpd(output_reg, input_reg);
__ testq(output_reg, Immediate(1));
DeoptimizeIf(not_zero, instr->environment());
__ Set(output_reg, 0);
__ jmp(&done);
__ bind(&positive_sign);
}
// Use truncating instruction (OK because input is positive).
__ cvttsd2si(output_reg, input_reg);
// Overflow is signalled with minint.
__ cmpl(output_reg, Immediate(0x80000000));
DeoptimizeIf(equal, instr->environment());
__ jmp(&done, Label::kNear);
// Non-zero negative reaches here.
__ bind(&negative_sign);
// Truncate, then compare and compensate.
__ cvttsd2si(output_reg, input_reg);
__ cvtlsi2sd(xmm_scratch, output_reg);
__ ucomisd(input_reg, xmm_scratch);
__ j(equal, &done, Label::kNear);
__ subl(output_reg, Immediate(1));
DeoptimizeIf(overflow, instr->environment());
__ bind(&done);
}
}
void LCodeGen::DoMathRound(LUnaryMathOperation* instr) {
const XMMRegister xmm_scratch = xmm0;
Register output_reg = ToRegister(instr->result());
XMMRegister input_reg = ToDoubleRegister(instr->value());
Label done;
// xmm_scratch = 0.5
__ movq(kScratchRegister, V8_INT64_C(0x3FE0000000000000), RelocInfo::NONE);
__ movq(xmm_scratch, kScratchRegister);
Label below_half;
__ ucomisd(xmm_scratch, input_reg);
// If input_reg is NaN, this doesn't jump.
__ j(above, &below_half, Label::kNear);
// input = input + 0.5
// This addition might give a result that isn't the correct for
// rounding, due to loss of precision, but only for a number that's
// so big that the conversion below will overflow anyway.
__ addsd(xmm_scratch, input_reg);
// Compute Math.floor(input).
// Use truncating instruction (OK because input is positive).
__ cvttsd2si(output_reg, xmm_scratch);
// Overflow is signalled with minint.
__ cmpl(output_reg, Immediate(0x80000000));
DeoptimizeIf(equal, instr->environment());
__ jmp(&done);
__ bind(&below_half);
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
// Bailout if negative (including -0).
__ movq(output_reg, input_reg);
__ testq(output_reg, output_reg);
DeoptimizeIf(negative, instr->environment());
} else {
// Bailout if below -0.5, otherwise round to (positive) zero, even
// if negative.
// xmm_scrach = -0.5
__ movq(kScratchRegister, V8_INT64_C(0xBFE0000000000000), RelocInfo::NONE);
__ movq(xmm_scratch, kScratchRegister);
__ ucomisd(input_reg, xmm_scratch);
DeoptimizeIf(below, instr->environment());
}
__ xorl(output_reg, output_reg);
__ bind(&done);
}
void LCodeGen::DoMathSqrt(LUnaryMathOperation* instr) {
XMMRegister input_reg = ToDoubleRegister(instr->value());
ASSERT(ToDoubleRegister(instr->result()).is(input_reg));
__ sqrtsd(input_reg, input_reg);
}
void LCodeGen::DoMathPowHalf(LUnaryMathOperation* instr) {
XMMRegister xmm_scratch = xmm0;
XMMRegister input_reg = ToDoubleRegister(instr->value());
ASSERT(ToDoubleRegister(instr->result()).is(input_reg));
// Note that according to ECMA-262 15.8.2.13:
// Math.pow(-Infinity, 0.5) == Infinity
// Math.sqrt(-Infinity) == NaN
Label done, sqrt;
// Check base for -Infinity. According to IEEE-754, double-precision
// -Infinity has the highest 12 bits set and the lowest 52 bits cleared.
__ movq(kScratchRegister, V8_INT64_C(0xFFF0000000000000), RelocInfo::NONE);
__ movq(xmm_scratch, kScratchRegister);
__ ucomisd(xmm_scratch, input_reg);
// Comparing -Infinity with NaN results in "unordered", which sets the
// zero flag as if both were equal. However, it also sets the carry flag.
__ j(not_equal, &sqrt, Label::kNear);
__ j(carry, &sqrt, Label::kNear);
// If input is -Infinity, return Infinity.
__ xorps(input_reg, input_reg);
__ subsd(input_reg, xmm_scratch);
__ jmp(&done, Label::kNear);
// Square root.
__ bind(&sqrt);
__ xorps(xmm_scratch, xmm_scratch);
__ addsd(input_reg, xmm_scratch); // Convert -0 to +0.
__ sqrtsd(input_reg, input_reg);
__ bind(&done);
}
void LCodeGen::DoPower(LPower* instr) {
Representation exponent_type = instr->hydrogen()->right()->representation();
// Having marked this as a call, we can use any registers.
// Just make sure that the input/output registers are the expected ones.
// Choose register conforming to calling convention (when bailing out).
#ifdef _WIN64
Register exponent = rdx;
#else
Register exponent = rdi;
#endif
ASSERT(!instr->right()->IsRegister() ||
ToRegister(instr->right()).is(exponent));
ASSERT(!instr->right()->IsDoubleRegister() ||
ToDoubleRegister(instr->right()).is(xmm1));
ASSERT(ToDoubleRegister(instr->left()).is(xmm2));
ASSERT(ToDoubleRegister(instr->result()).is(xmm3));
if (exponent_type.IsTagged()) {
Label no_deopt;
__ JumpIfSmi(exponent, &no_deopt);
__ CmpObjectType(exponent, HEAP_NUMBER_TYPE, rcx);
DeoptimizeIf(not_equal, instr->environment());
__ bind(&no_deopt);
MathPowStub stub(MathPowStub::TAGGED);
__ CallStub(&stub);
} else if (exponent_type.IsInteger32()) {
MathPowStub stub(MathPowStub::INTEGER);
__ CallStub(&stub);
} else {
ASSERT(exponent_type.IsDouble());
MathPowStub stub(MathPowStub::DOUBLE);
__ CallStub(&stub);
}
}
void LCodeGen::DoRandom(LRandom* instr) {
class DeferredDoRandom: public LDeferredCode {
public:
DeferredDoRandom(LCodeGen* codegen, LRandom* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() { codegen()->DoDeferredRandom(instr_); }
virtual LInstruction* instr() { return instr_; }
private:
LRandom* instr_;
};
DeferredDoRandom* deferred = new(zone()) DeferredDoRandom(this, instr);
// Having marked this instruction as a call we can use any
// registers.
ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
// Choose the right register for the first argument depending on
// calling convention.
#ifdef _WIN64
ASSERT(ToRegister(instr->global_object()).is(rcx));
Register global_object = rcx;
#else
ASSERT(ToRegister(instr->global_object()).is(rdi));
Register global_object = rdi;
#endif
static const int kSeedSize = sizeof(uint32_t);
STATIC_ASSERT(kPointerSize == 2 * kSeedSize);
__ movq(global_object,
FieldOperand(global_object, GlobalObject::kNativeContextOffset));
static const int kRandomSeedOffset =
FixedArray::kHeaderSize + Context::RANDOM_SEED_INDEX * kPointerSize;
__ movq(rbx, FieldOperand(global_object, kRandomSeedOffset));
// rbx: FixedArray of the native context's random seeds
// Load state[0].
__ movl(rax, FieldOperand(rbx, ByteArray::kHeaderSize));
// If state[0] == 0, call runtime to initialize seeds.
__ testl(rax, rax);
__ j(zero, deferred->entry());
// Load state[1].
__ movl(rcx, FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize));
// state[0] = 18273 * (state[0] & 0xFFFF) + (state[0] >> 16)
// Only operate on the lower 32 bit of rax.
__ movl(rdx, rax);
__ andl(rdx, Immediate(0xFFFF));
__ imull(rdx, rdx, Immediate(18273));
__ shrl(rax, Immediate(16));
__ addl(rax, rdx);
// Save state[0].
__ movl(FieldOperand(rbx, ByteArray::kHeaderSize), rax);
// state[1] = 36969 * (state[1] & 0xFFFF) + (state[1] >> 16)
__ movl(rdx, rcx);
__ andl(rdx, Immediate(0xFFFF));
__ imull(rdx, rdx, Immediate(36969));
__ shrl(rcx, Immediate(16));
__ addl(rcx, rdx);
// Save state[1].
__ movl(FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize), rcx);
// Random bit pattern = (state[0] << 14) + (state[1] & 0x3FFFF)
__ shll(rax, Immediate(14));
__ andl(rcx, Immediate(0x3FFFF));
__ addl(rax, rcx);
__ bind(deferred->exit());
// Convert 32 random bits in rax to 0.(32 random bits) in a double
// by computing:
// ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
__ movl(rcx, Immediate(0x49800000)); // 1.0 x 2^20 as single.
__ movd(xmm2, rcx);
__ movd(xmm1, rax);
__ cvtss2sd(xmm2, xmm2);
__ xorps(xmm1, xmm2);
__ subsd(xmm1, xmm2);
}
void LCodeGen::DoDeferredRandom(LRandom* instr) {
__ PrepareCallCFunction(1);
__ CallCFunction(ExternalReference::random_uint32_function(isolate()), 1);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
// Return value is in rax.
}
void LCodeGen::DoMathLog(LUnaryMathOperation* instr) {
ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
TranscendentalCacheStub stub(TranscendentalCache::LOG,
TranscendentalCacheStub::UNTAGGED);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoMathTan(LUnaryMathOperation* instr) {
ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
TranscendentalCacheStub stub(TranscendentalCache::TAN,
TranscendentalCacheStub::UNTAGGED);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoMathCos(LUnaryMathOperation* instr) {
ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
TranscendentalCacheStub stub(TranscendentalCache::COS,
TranscendentalCacheStub::UNTAGGED);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoMathSin(LUnaryMathOperation* instr) {
ASSERT(ToDoubleRegister(instr->result()).is(xmm1));
TranscendentalCacheStub stub(TranscendentalCache::SIN,
TranscendentalCacheStub::UNTAGGED);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoUnaryMathOperation(LUnaryMathOperation* instr) {
switch (instr->op()) {
case kMathAbs:
DoMathAbs(instr);
break;
case kMathFloor:
DoMathFloor(instr);
break;
case kMathRound:
DoMathRound(instr);
break;
case kMathSqrt:
DoMathSqrt(instr);
break;
case kMathPowHalf:
DoMathPowHalf(instr);
break;
case kMathCos:
DoMathCos(instr);
break;
case kMathSin:
DoMathSin(instr);
break;
case kMathTan:
DoMathTan(instr);
break;
case kMathLog:
DoMathLog(instr);
break;
default:
UNREACHABLE();
}
}
void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
ASSERT(ToRegister(instr->function()).is(rdi));
ASSERT(instr->HasPointerMap());
if (instr->known_function().is_null()) {
LPointerMap* pointers = instr->pointer_map();
RecordPosition(pointers->position());
SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
ParameterCount count(instr->arity());
__ InvokeFunction(rdi, count, CALL_FUNCTION, generator, CALL_AS_METHOD);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
} else {
CallKnownFunction(instr->known_function(),
instr->arity(),
instr,
CALL_AS_METHOD,
RDI_CONTAINS_TARGET);
}
}
void LCodeGen::DoCallKeyed(LCallKeyed* instr) {
ASSERT(ToRegister(instr->key()).is(rcx));
ASSERT(ToRegister(instr->result()).is(rax));
int arity = instr->arity();
Handle<Code> ic =
isolate()->stub_cache()->ComputeKeyedCallInitialize(arity);
CallCode(ic, RelocInfo::CODE_TARGET, instr);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
void LCodeGen::DoCallNamed(LCallNamed* instr) {
ASSERT(ToRegister(instr->result()).is(rax));
int arity = instr->arity();
RelocInfo::Mode mode = RelocInfo::CODE_TARGET;
Handle<Code> ic =
isolate()->stub_cache()->ComputeCallInitialize(arity, mode);
__ Move(rcx, instr->name());
CallCode(ic, mode, instr);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
void LCodeGen::DoCallFunction(LCallFunction* instr) {
ASSERT(ToRegister(instr->function()).is(rdi));
ASSERT(ToRegister(instr->result()).is(rax));
int arity = instr->arity();
CallFunctionStub stub(arity, NO_CALL_FUNCTION_FLAGS);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
void LCodeGen::DoCallGlobal(LCallGlobal* instr) {
ASSERT(ToRegister(instr->result()).is(rax));
int arity = instr->arity();
RelocInfo::Mode mode = RelocInfo::CODE_TARGET_CONTEXT;
Handle<Code> ic =
isolate()->stub_cache()->ComputeCallInitialize(arity, mode);
__ Move(rcx, instr->name());
CallCode(ic, mode, instr);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
}
void LCodeGen::DoCallKnownGlobal(LCallKnownGlobal* instr) {
ASSERT(ToRegister(instr->result()).is(rax));
CallKnownFunction(instr->target(),
instr->arity(),
instr,
CALL_AS_FUNCTION,
RDI_UNINITIALIZED);
}
void LCodeGen::DoCallNew(LCallNew* instr) {
ASSERT(ToRegister(instr->constructor()).is(rdi));
ASSERT(ToRegister(instr->result()).is(rax));
CallConstructStub stub(NO_CALL_FUNCTION_FLAGS);
__ Set(rax, instr->arity());
CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
}
void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
CallRuntime(instr->function(), instr->arity(), instr);
}
void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
Register object = ToRegister(instr->object());
Register value = ToRegister(instr->value());
int offset = instr->offset();
if (!instr->transition().is_null()) {
if (!instr->hydrogen()->NeedsWriteBarrierForMap()) {
__ Move(FieldOperand(object, HeapObject::kMapOffset),
instr->transition());
} else {
Register temp = ToRegister(instr->temp());
__ Move(kScratchRegister, instr->transition());
__ movq(FieldOperand(object, HeapObject::kMapOffset), kScratchRegister);
// Update the write barrier for the map field.
__ RecordWriteField(object,
HeapObject::kMapOffset,
kScratchRegister,
temp,
kSaveFPRegs,
OMIT_REMEMBERED_SET,
OMIT_SMI_CHECK);
}
}
// Do the store.
HType type = instr->hydrogen()->value()->type();
SmiCheck check_needed =
type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
if (instr->is_in_object()) {
__ movq(FieldOperand(object, offset), value);
if (instr->hydrogen()->NeedsWriteBarrier()) {
Register temp = ToRegister(instr->temp());
// Update the write barrier for the object for in-object properties.
__ RecordWriteField(object,
offset,
value,
temp,
kSaveFPRegs,
EMIT_REMEMBERED_SET,
check_needed);
}
} else {
Register temp = ToRegister(instr->temp());
__ movq(temp, FieldOperand(object, JSObject::kPropertiesOffset));
__ movq(FieldOperand(temp, offset), value);
if (instr->hydrogen()->NeedsWriteBarrier()) {
// Update the write barrier for the properties array.
// object is used as a scratch register.
__ RecordWriteField(temp,
offset,
value,
object,
kSaveFPRegs,
EMIT_REMEMBERED_SET,
check_needed);
}
}
}
void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) {
ASSERT(ToRegister(instr->object()).is(rdx));
ASSERT(ToRegister(instr->value()).is(rax));
__ Move(rcx, instr->hydrogen()->name());
Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
? isolate()->builtins()->StoreIC_Initialize_Strict()
: isolate()->builtins()->StoreIC_Initialize();
CallCode(ic, RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DeoptIfTaggedButNotSmi(LEnvironment* environment,
HValue* value,
LOperand* operand) {
if (value->representation().IsTagged() && !value->type().IsSmi()) {
Condition cc;
if (operand->IsRegister()) {
cc = masm()->CheckSmi(ToRegister(operand));
} else {
cc = masm()->CheckSmi(ToOperand(operand));
}
DeoptimizeIf(NegateCondition(cc), environment);
}
}
void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
DeoptIfTaggedButNotSmi(instr->environment(),
instr->hydrogen()->length(),
instr->length());
DeoptIfTaggedButNotSmi(instr->environment(),
instr->hydrogen()->index(),
instr->index());
if (instr->length()->IsRegister()) {
Register reg = ToRegister(instr->length());
if (!instr->hydrogen()->length()->representation().IsTagged()) {
__ AssertZeroExtended(reg);
}
if (instr->index()->IsConstantOperand()) {
int constant_index =
ToInteger32(LConstantOperand::cast(instr->index()));
if (instr->hydrogen()->length()->representation().IsTagged()) {
__ Cmp(reg, Smi::FromInt(constant_index));
} else {
__ cmpq(reg, Immediate(constant_index));
}
} else {
Register reg2 = ToRegister(instr->index());
if (!instr->hydrogen()->index()->representation().IsTagged()) {
__ AssertZeroExtended(reg2);
}
__ cmpq(reg, reg2);
}
} else {
Operand length = ToOperand(instr->length());
if (instr->index()->IsConstantOperand()) {
int constant_index =
ToInteger32(LConstantOperand::cast(instr->index()));
if (instr->hydrogen()->length()->representation().IsTagged()) {
__ Cmp(length, Smi::FromInt(constant_index));
} else {
__ cmpq(length, Immediate(constant_index));
}
} else {
__ cmpq(length, ToRegister(instr->index()));
}
}
DeoptimizeIf(below_equal, instr->environment());
}
void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
ElementsKind elements_kind = instr->elements_kind();
LOperand* key = instr->key();
PrepareKeyForKeyedOp<HStoreKeyed>(instr->hydrogen(), key);
Operand operand(BuildFastArrayOperand(
instr->elements(),
key,
elements_kind,
0,
instr->additional_index()));
if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) {
XMMRegister value(ToDoubleRegister(instr->value()));
__ cvtsd2ss(value, value);
__ movss(operand, value);
} else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) {
__ movsd(operand, ToDoubleRegister(instr->value()));
} else {
Register value(ToRegister(instr->value()));
switch (elements_kind) {
case EXTERNAL_PIXEL_ELEMENTS:
case EXTERNAL_BYTE_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
__ movb(operand, value);
break;
case EXTERNAL_SHORT_ELEMENTS:
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
__ movw(operand, value);
break;
case EXTERNAL_INT_ELEMENTS:
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
__ movl(operand, value);
break;
case EXTERNAL_FLOAT_ELEMENTS:
case EXTERNAL_DOUBLE_ELEMENTS:
case FAST_ELEMENTS:
case FAST_SMI_ELEMENTS:
case FAST_DOUBLE_ELEMENTS:
case FAST_HOLEY_ELEMENTS:
case FAST_HOLEY_SMI_ELEMENTS:
case FAST_HOLEY_DOUBLE_ELEMENTS:
case DICTIONARY_ELEMENTS:
case NON_STRICT_ARGUMENTS_ELEMENTS:
UNREACHABLE();
break;
}
}
}
void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
XMMRegister value = ToDoubleRegister(instr->value());
LOperand* key = instr->key();
PrepareKeyForKeyedOp<HStoreKeyed>(instr->hydrogen(), key);
if (instr->NeedsCanonicalization()) {
Label have_value;
__ ucomisd(value, value);
__ j(parity_odd, &have_value); // NaN.
__ Set(kScratchRegister, BitCast<uint64_t>(
FixedDoubleArray::canonical_not_the_hole_nan_as_double()));
__ movq(value, kScratchRegister);
__ bind(&have_value);
}
Operand double_store_operand = BuildFastArrayOperand(
instr->elements(),
key,
FAST_DOUBLE_ELEMENTS,
FixedDoubleArray::kHeaderSize - kHeapObjectTag,
instr->additional_index());
__ movsd(double_store_operand, value);
}
void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
Register value = ToRegister(instr->value());
Register elements = ToRegister(instr->elements());
LOperand* key = instr->key();
PrepareKeyForKeyedOp<HStoreKeyed>(instr->hydrogen(), key);
Operand operand =
BuildFastArrayOperand(instr->elements(),
key,
FAST_ELEMENTS,
FixedArray::kHeaderSize - kHeapObjectTag,
instr->additional_index());
if (instr->hydrogen()->NeedsWriteBarrier()) {
ASSERT(!instr->key()->IsConstantOperand());
HType type = instr->hydrogen()->value()->type();
SmiCheck check_needed =
type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
// Compute address of modified element and store it into key register.
Register key_reg(ToRegister(key));
__ lea(key_reg, operand);
__ movq(Operand(key_reg, 0), value);
__ RecordWrite(elements,
key_reg,
value,
kSaveFPRegs,
EMIT_REMEMBERED_SET,
check_needed);
} else {
__ movq(operand, value);
}
}
void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
if (instr->is_external()) {
DoStoreKeyedExternalArray(instr);
} else if (instr->hydrogen()->value()->representation().IsDouble()) {
DoStoreKeyedFixedDoubleArray(instr);
} else {
DoStoreKeyedFixedArray(instr);
}
}
void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) {
ASSERT(ToRegister(instr->object()).is(rdx));
ASSERT(ToRegister(instr->key()).is(rcx));
ASSERT(ToRegister(instr->value()).is(rax));
Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode)
? isolate()->builtins()->KeyedStoreIC_Initialize_Strict()
: isolate()->builtins()->KeyedStoreIC_Initialize();
CallCode(ic, RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
Register object_reg = ToRegister(instr->object());
Register new_map_reg = ToRegister(instr->new_map_temp());
Handle<Map> from_map = instr->original_map();
Handle<Map> to_map = instr->transitioned_map();
ElementsKind from_kind = from_map->elements_kind();
ElementsKind to_kind = to_map->elements_kind();
Label not_applicable;
__ Cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map);
__ j(not_equal, ¬_applicable);
__ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT);
if (IsSimpleMapChangeTransition(from_kind, to_kind)) {
__ movq(FieldOperand(object_reg, HeapObject::kMapOffset), new_map_reg);
// Write barrier.
ASSERT_NE(instr->temp(), NULL);
__ RecordWriteField(object_reg, HeapObject::kMapOffset, new_map_reg,
ToRegister(instr->temp()), kDontSaveFPRegs);
} else if (IsFastSmiElementsKind(from_kind) &&
IsFastDoubleElementsKind(to_kind)) {
Register fixed_object_reg = ToRegister(instr->temp());
ASSERT(fixed_object_reg.is(rdx));
ASSERT(new_map_reg.is(rbx));
__ movq(fixed_object_reg, object_reg);
CallCode(isolate()->builtins()->TransitionElementsSmiToDouble(),
RelocInfo::CODE_TARGET, instr);
} else if (IsFastDoubleElementsKind(from_kind) &&
IsFastObjectElementsKind(to_kind)) {
Register fixed_object_reg = ToRegister(instr->temp());
ASSERT(fixed_object_reg.is(rdx));
ASSERT(new_map_reg.is(rbx));
__ movq(fixed_object_reg, object_reg);
CallCode(isolate()->builtins()->TransitionElementsDoubleToObject(),
RelocInfo::CODE_TARGET, instr);
} else {
UNREACHABLE();
}
__ bind(¬_applicable);
}
void LCodeGen::DoStringAdd(LStringAdd* instr) {
EmitPushTaggedOperand(instr->left());
EmitPushTaggedOperand(instr->right());
StringAddStub stub(NO_STRING_CHECK_IN_STUB);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
class DeferredStringCharCodeAt: public LDeferredCode {
public:
DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); }
virtual LInstruction* instr() { return instr_; }
private:
LStringCharCodeAt* instr_;
};
DeferredStringCharCodeAt* deferred =
new(zone()) DeferredStringCharCodeAt(this, instr);
StringCharLoadGenerator::Generate(masm(),
ToRegister(instr->string()),
ToRegister(instr->index()),
ToRegister(instr->result()),
deferred->entry());
__ bind(deferred->exit());
}
void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
Register string = ToRegister(instr->string());
Register result = ToRegister(instr->result());
// TODO(3095996): Get rid of this. For now, we need to make the
// result register contain a valid pointer because it is already
// contained in the register pointer map.
__ Set(result, 0);
PushSafepointRegistersScope scope(this);
__ push(string);
// Push the index as a smi. This is safe because of the checks in
// DoStringCharCodeAt above.
STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue);
if (instr->index()->IsConstantOperand()) {
int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
__ Push(Smi::FromInt(const_index));
} else {
Register index = ToRegister(instr->index());
__ Integer32ToSmi(index, index);
__ push(index);
}
CallRuntimeFromDeferred(Runtime::kStringCharCodeAt, 2, instr);
__ AssertSmi(rax);
__ SmiToInteger32(rax, rax);
__ StoreToSafepointRegisterSlot(result, rax);
}
void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
class DeferredStringCharFromCode: public LDeferredCode {
public:
DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); }
virtual LInstruction* instr() { return instr_; }
private:
LStringCharFromCode* instr_;
};
DeferredStringCharFromCode* deferred =
new(zone()) DeferredStringCharFromCode(this, instr);
ASSERT(instr->hydrogen()->value()->representation().IsInteger32());
Register char_code = ToRegister(instr->char_code());
Register result = ToRegister(instr->result());
ASSERT(!char_code.is(result));
__ cmpl(char_code, Immediate(String::kMaxAsciiCharCode));
__ j(above, deferred->entry());
__ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex);
__ movq(result, FieldOperand(result,
char_code, times_pointer_size,
FixedArray::kHeaderSize));
__ CompareRoot(result, Heap::kUndefinedValueRootIndex);
__ j(equal, deferred->entry());
__ bind(deferred->exit());
}
void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
Register char_code = ToRegister(instr->char_code());
Register result = ToRegister(instr->result());
// TODO(3095996): Get rid of this. For now, we need to make the
// result register contain a valid pointer because it is already
// contained in the register pointer map.
__ Set(result, 0);
PushSafepointRegistersScope scope(this);
__ Integer32ToSmi(char_code, char_code);
__ push(char_code);
CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr);
__ StoreToSafepointRegisterSlot(result, rax);
}
void LCodeGen::DoStringLength(LStringLength* instr) {
Register string = ToRegister(instr->string());
Register result = ToRegister(instr->result());
__ movq(result, FieldOperand(string, String::kLengthOffset));
}
void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
LOperand* input = instr->value();
ASSERT(input->IsRegister() || input->IsStackSlot());
LOperand* output = instr->result();
ASSERT(output->IsDoubleRegister());
if (input->IsRegister()) {
__ cvtlsi2sd(ToDoubleRegister(output), ToRegister(input));
} else {
__ cvtlsi2sd(ToDoubleRegister(output), ToOperand(input));
}
}
void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
LOperand* input = instr->value();
LOperand* output = instr->result();
LOperand* temp = instr->temp();
__ LoadUint32(ToDoubleRegister(output),
ToRegister(input),
ToDoubleRegister(temp));
}
void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
LOperand* input = instr->value();
ASSERT(input->IsRegister() && input->Equals(instr->result()));
Register reg = ToRegister(input);
__ Integer32ToSmi(reg, reg);
}
void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
class DeferredNumberTagU: public LDeferredCode {
public:
DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() {
codegen()->DoDeferredNumberTagU(instr_);
}
virtual LInstruction* instr() { return instr_; }
private:
LNumberTagU* instr_;
};
LOperand* input = instr->value();
ASSERT(input->IsRegister() && input->Equals(instr->result()));
Register reg = ToRegister(input);
DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr);
__ cmpl(reg, Immediate(Smi::kMaxValue));
__ j(above, deferred->entry());
__ Integer32ToSmi(reg, reg);
__ bind(deferred->exit());
}
void LCodeGen::DoDeferredNumberTagU(LNumberTagU* instr) {
Label slow;
Register reg = ToRegister(instr->value());
Register tmp = reg.is(rax) ? rcx : rax;
// Preserve the value of all registers.
PushSafepointRegistersScope scope(this);
Label done;
// Load value into xmm1 which will be preserved across potential call to
// runtime (MacroAssembler::EnterExitFrameEpilogue preserves only allocatable
// XMM registers on x64).
__ LoadUint32(xmm1, reg, xmm0);
if (FLAG_inline_new) {
__ AllocateHeapNumber(reg, tmp, &slow);
__ jmp(&done, Label::kNear);
}
// Slow case: Call the runtime system to do the number allocation.
__ bind(&slow);
// Put a valid pointer value in the stack slot where the result
// register is stored, as this register is in the pointer map, but contains an
// integer value.
__ StoreToSafepointRegisterSlot(reg, Immediate(0));
CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr);
if (!reg.is(rax)) __ movq(reg, rax);
// Done. Put the value in xmm1 into the value of the allocated heap
// number.
__ bind(&done);
__ movsd(FieldOperand(reg, HeapNumber::kValueOffset), xmm1);
__ StoreToSafepointRegisterSlot(reg, reg);
}
void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
class DeferredNumberTagD: public LDeferredCode {
public:
DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); }
virtual LInstruction* instr() { return instr_; }
private:
LNumberTagD* instr_;
};
XMMRegister input_reg = ToDoubleRegister(instr->value());
Register reg = ToRegister(instr->result());
Register tmp = ToRegister(instr->temp());
DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr);
if (FLAG_inline_new) {
__ AllocateHeapNumber(reg, tmp, deferred->entry());
} else {
__ jmp(deferred->entry());
}
__ bind(deferred->exit());
__ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg);
}
void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
// TODO(3095996): Get rid of this. For now, we need to make the
// result register contain a valid pointer because it is already
// contained in the register pointer map.
Register reg = ToRegister(instr->result());
__ Move(reg, Smi::FromInt(0));
{
PushSafepointRegistersScope scope(this);
CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr);
// Ensure that value in rax survives popping registers.
__ movq(kScratchRegister, rax);
}
__ movq(reg, kScratchRegister);
}
void LCodeGen::DoSmiTag(LSmiTag* instr) {
ASSERT(instr->value()->Equals(instr->result()));
Register input = ToRegister(instr->value());
ASSERT(!instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow));
__ Integer32ToSmi(input, input);
}
void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
ASSERT(instr->value()->Equals(instr->result()));
Register input = ToRegister(instr->value());
if (instr->needs_check()) {
Condition is_smi = __ CheckSmi(input);
DeoptimizeIf(NegateCondition(is_smi), instr->environment());
} else {
__ AssertSmi(input);
}
__ SmiToInteger32(input, input);
}
void LCodeGen::EmitNumberUntagD(Register input_reg,
XMMRegister result_reg,
bool deoptimize_on_undefined,
bool deoptimize_on_minus_zero,
LEnvironment* env) {
Label load_smi, done;
// Smi check.
__ JumpIfSmi(input_reg, &load_smi, Label::kNear);
// Heap number map check.
__ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
Heap::kHeapNumberMapRootIndex);
if (deoptimize_on_undefined) {
DeoptimizeIf(not_equal, env);
} else {
Label heap_number;
__ j(equal, &heap_number, Label::kNear);
__ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex);
DeoptimizeIf(not_equal, env);
// Convert undefined to NaN. Compute NaN as 0/0.
__ xorps(result_reg, result_reg);
__ divsd(result_reg, result_reg);
__ jmp(&done, Label::kNear);
__ bind(&heap_number);
}
// Heap number to XMM conversion.
__ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset));
if (deoptimize_on_minus_zero) {
XMMRegister xmm_scratch = xmm0;
__ xorps(xmm_scratch, xmm_scratch);
__ ucomisd(xmm_scratch, result_reg);
__ j(not_equal, &done, Label::kNear);
__ movmskpd(kScratchRegister, result_reg);
__ testq(kScratchRegister, Immediate(1));
DeoptimizeIf(not_zero, env);
}
__ jmp(&done, Label::kNear);
// Smi to XMM conversion
__ bind(&load_smi);
__ SmiToInteger32(kScratchRegister, input_reg);
__ cvtlsi2sd(result_reg, kScratchRegister);
__ bind(&done);
}
void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr) {
Label done, heap_number;
Register input_reg = ToRegister(instr->value());
// Heap number map check.
__ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset),
Heap::kHeapNumberMapRootIndex);
if (instr->truncating()) {
__ j(equal, &heap_number, Label::kNear);
// Check for undefined. Undefined is converted to zero for truncating
// conversions.
__ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex);
DeoptimizeIf(not_equal, instr->environment());
__ Set(input_reg, 0);
__ jmp(&done, Label::kNear);
__ bind(&heap_number);
__ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
__ cvttsd2siq(input_reg, xmm0);
__ Set(kScratchRegister, V8_UINT64_C(0x8000000000000000));
__ cmpq(input_reg, kScratchRegister);
DeoptimizeIf(equal, instr->environment());
} else {
// Deoptimize if we don't have a heap number.
DeoptimizeIf(not_equal, instr->environment());
XMMRegister xmm_temp = ToDoubleRegister(instr->temp());
__ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
__ cvttsd2si(input_reg, xmm0);
__ cvtlsi2sd(xmm_temp, input_reg);
__ ucomisd(xmm0, xmm_temp);
DeoptimizeIf(not_equal, instr->environment());
DeoptimizeIf(parity_even, instr->environment()); // NaN.
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
__ testl(input_reg, input_reg);
__ j(not_zero, &done);
__ movmskpd(input_reg, xmm0);
__ andl(input_reg, Immediate(1));
DeoptimizeIf(not_zero, instr->environment());
}
}
__ bind(&done);
}
void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
class DeferredTaggedToI: public LDeferredCode {
public:
DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() { codegen()->DoDeferredTaggedToI(instr_); }
virtual LInstruction* instr() { return instr_; }
private:
LTaggedToI* instr_;
};
LOperand* input = instr->value();
ASSERT(input->IsRegister());
ASSERT(input->Equals(instr->result()));
Register input_reg = ToRegister(input);
DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr);
__ JumpIfNotSmi(input_reg, deferred->entry());
__ SmiToInteger32(input_reg, input_reg);
__ bind(deferred->exit());
}
void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
LOperand* input = instr->value();
ASSERT(input->IsRegister());
LOperand* result = instr->result();
ASSERT(result->IsDoubleRegister());
Register input_reg = ToRegister(input);
XMMRegister result_reg = ToDoubleRegister(result);
EmitNumberUntagD(input_reg, result_reg,
instr->hydrogen()->deoptimize_on_undefined(),
instr->hydrogen()->deoptimize_on_minus_zero(),
instr->environment());
}
void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
LOperand* input = instr->value();
ASSERT(input->IsDoubleRegister());
LOperand* result = instr->result();
ASSERT(result->IsRegister());
XMMRegister input_reg = ToDoubleRegister(input);
Register result_reg = ToRegister(result);
if (instr->truncating()) {
// Performs a truncating conversion of a floating point number as used by
// the JS bitwise operations.
__ cvttsd2siq(result_reg, input_reg);
__ movq(kScratchRegister, V8_INT64_C(0x8000000000000000), RelocInfo::NONE);
__ cmpq(result_reg, kScratchRegister);
DeoptimizeIf(equal, instr->environment());
} else {
__ cvttsd2si(result_reg, input_reg);
__ cvtlsi2sd(xmm0, result_reg);
__ ucomisd(xmm0, input_reg);
DeoptimizeIf(not_equal, instr->environment());
DeoptimizeIf(parity_even, instr->environment()); // NaN.
if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
Label done;
// The integer converted back is equal to the original. We
// only have to test if we got -0 as an input.
__ testl(result_reg, result_reg);
__ j(not_zero, &done, Label::kNear);
__ movmskpd(result_reg, input_reg);
// Bit 0 contains the sign of the double in input_reg.
// If input was positive, we are ok and return 0, otherwise
// deoptimize.
__ andl(result_reg, Immediate(1));
DeoptimizeIf(not_zero, instr->environment());
__ bind(&done);
}
}
}
void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
LOperand* input = instr->value();
Condition cc = masm()->CheckSmi(ToRegister(input));
DeoptimizeIf(NegateCondition(cc), instr->environment());
}
void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
LOperand* input = instr->value();
Condition cc = masm()->CheckSmi(ToRegister(input));
DeoptimizeIf(cc, instr->environment());
}
void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
Register input = ToRegister(instr->value());
__ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset));
if (instr->hydrogen()->is_interval_check()) {
InstanceType first;
InstanceType last;
instr->hydrogen()->GetCheckInterval(&first, &last);
__ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
Immediate(static_cast<int8_t>(first)));
// If there is only one type in the interval check for equality.
if (first == last) {
DeoptimizeIf(not_equal, instr->environment());
} else {
DeoptimizeIf(below, instr->environment());
// Omit check for the last type.
if (last != LAST_TYPE) {
__ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
Immediate(static_cast<int8_t>(last)));
DeoptimizeIf(above, instr->environment());
}
}
} else {
uint8_t mask;
uint8_t tag;
instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
if (IsPowerOf2(mask)) {
ASSERT(tag == 0 || IsPowerOf2(tag));
__ testb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset),
Immediate(mask));
DeoptimizeIf(tag == 0 ? not_zero : zero, instr->environment());
} else {
__ movzxbl(kScratchRegister,
FieldOperand(kScratchRegister, Map::kInstanceTypeOffset));
__ andb(kScratchRegister, Immediate(mask));
__ cmpb(kScratchRegister, Immediate(tag));
DeoptimizeIf(not_equal, instr->environment());
}
}
}
void LCodeGen::DoCheckFunction(LCheckFunction* instr) {
Register reg = ToRegister(instr->value());
Handle<JSFunction> target = instr->hydrogen()->target();
if (isolate()->heap()->InNewSpace(*target)) {
Handle<JSGlobalPropertyCell> cell =
isolate()->factory()->NewJSGlobalPropertyCell(target);
__ movq(kScratchRegister, cell, RelocInfo::GLOBAL_PROPERTY_CELL);
__ cmpq(reg, Operand(kScratchRegister, 0));
} else {
__ Cmp(reg, target);
}
DeoptimizeIf(not_equal, instr->environment());
}
void LCodeGen::DoCheckMapCommon(Register reg,
Handle<Map> map,
CompareMapMode mode,
LEnvironment* env) {
Label success;
__ CompareMap(reg, map, &success, mode);
DeoptimizeIf(not_equal, env);
__ bind(&success);
}
void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
LOperand* input = instr->value();
ASSERT(input->IsRegister());
Register reg = ToRegister(input);
Label success;
SmallMapList* map_set = instr->hydrogen()->map_set();
for (int i = 0; i < map_set->length() - 1; i++) {
Handle<Map> map = map_set->at(i);
__ CompareMap(reg, map, &success, REQUIRE_EXACT_MAP);
__ j(equal, &success);
}
Handle<Map> map = map_set->last();
DoCheckMapCommon(reg, map, REQUIRE_EXACT_MAP, instr->environment());
__ bind(&success);
}
void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
XMMRegister value_reg = ToDoubleRegister(instr->unclamped());
Register result_reg = ToRegister(instr->result());
__ ClampDoubleToUint8(value_reg, xmm0, result_reg);
}
void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
ASSERT(instr->unclamped()->Equals(instr->result()));
Register value_reg = ToRegister(instr->result());
__ ClampUint8(value_reg);
}
void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
ASSERT(instr->unclamped()->Equals(instr->result()));
Register input_reg = ToRegister(instr->unclamped());
XMMRegister temp_xmm_reg = ToDoubleRegister(instr->temp_xmm());
Label is_smi, done, heap_number;
__ JumpIfSmi(input_reg, &is_smi);
// Check for heap number
__ Cmp(FieldOperand(input_reg, HeapObject::kMapOffset),
factory()->heap_number_map());
__ j(equal, &heap_number, Label::kNear);
// Check for undefined. Undefined is converted to zero for clamping
// conversions.
__ Cmp(input_reg, factory()->undefined_value());
DeoptimizeIf(not_equal, instr->environment());
__ movq(input_reg, Immediate(0));
__ jmp(&done, Label::kNear);
// Heap number
__ bind(&heap_number);
__ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset));
__ ClampDoubleToUint8(xmm0, temp_xmm_reg, input_reg);
__ jmp(&done, Label::kNear);
// smi
__ bind(&is_smi);
__ SmiToInteger32(input_reg, input_reg);
__ ClampUint8(input_reg);
__ bind(&done);
}
void LCodeGen::DoCheckPrototypeMaps(LCheckPrototypeMaps* instr) {
ASSERT(instr->temp()->Equals(instr->result()));
Register reg = ToRegister(instr->temp());
Handle<JSObject> holder = instr->holder();
Handle<JSObject> current_prototype = instr->prototype();
// Load prototype object.
__ LoadHeapObject(reg, current_prototype);
// Check prototype maps up to the holder.
while (!current_prototype.is_identical_to(holder)) {
DoCheckMapCommon(reg, Handle<Map>(current_prototype->map()),
ALLOW_ELEMENT_TRANSITION_MAPS, instr->environment());
current_prototype =
Handle<JSObject>(JSObject::cast(current_prototype->GetPrototype()));
// Load next prototype object.
__ LoadHeapObject(reg, current_prototype);
}
// Check the holder map.
DoCheckMapCommon(reg, Handle<Map>(current_prototype->map()),
ALLOW_ELEMENT_TRANSITION_MAPS, instr->environment());
}
void LCodeGen::DoAllocateObject(LAllocateObject* instr) {
class DeferredAllocateObject: public LDeferredCode {
public:
DeferredAllocateObject(LCodeGen* codegen, LAllocateObject* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() { codegen()->DoDeferredAllocateObject(instr_); }
virtual LInstruction* instr() { return instr_; }
private:
LAllocateObject* instr_;
};
DeferredAllocateObject* deferred =
new(zone()) DeferredAllocateObject(this, instr);
Register result = ToRegister(instr->result());
Register scratch = ToRegister(instr->temp());
Handle<JSFunction> constructor = instr->hydrogen()->constructor();
Handle<Map> initial_map(constructor->initial_map());
int instance_size = initial_map->instance_size();
ASSERT(initial_map->pre_allocated_property_fields() +
initial_map->unused_property_fields() -
initial_map->inobject_properties() == 0);
// Allocate memory for the object. The initial map might change when
// the constructor's prototype changes, but instance size and property
// counts remain unchanged (if slack tracking finished).
ASSERT(!constructor->shared()->IsInobjectSlackTrackingInProgress());
__ AllocateInNewSpace(instance_size,
result,
no_reg,
scratch,
deferred->entry(),
TAG_OBJECT);
__ bind(deferred->exit());
if (FLAG_debug_code) {
Label is_in_new_space;
__ JumpIfInNewSpace(result, scratch, &is_in_new_space);
__ Abort("Allocated object is not in new-space");
__ bind(&is_in_new_space);
}
// Load the initial map.
Register map = scratch;
__ LoadHeapObject(scratch, constructor);
__ movq(map, FieldOperand(scratch, JSFunction::kPrototypeOrInitialMapOffset));
if (FLAG_debug_code) {
__ AssertNotSmi(map);
__ cmpb(FieldOperand(map, Map::kInstanceSizeOffset),
Immediate(instance_size >> kPointerSizeLog2));
__ Assert(equal, "Unexpected instance size");
__ cmpb(FieldOperand(map, Map::kPreAllocatedPropertyFieldsOffset),
Immediate(initial_map->pre_allocated_property_fields()));
__ Assert(equal, "Unexpected pre-allocated property fields count");
__ cmpb(FieldOperand(map, Map::kUnusedPropertyFieldsOffset),
Immediate(initial_map->unused_property_fields()));
__ Assert(equal, "Unexpected unused property fields count");
__ cmpb(FieldOperand(map, Map::kInObjectPropertiesOffset),
Immediate(initial_map->inobject_properties()));
__ Assert(equal, "Unexpected in-object property fields count");
}
// Initialize map and fields of the newly allocated object.
ASSERT(initial_map->instance_type() == JS_OBJECT_TYPE);
__ movq(FieldOperand(result, JSObject::kMapOffset), map);
__ LoadRoot(scratch, Heap::kEmptyFixedArrayRootIndex);
__ movq(FieldOperand(result, JSObject::kElementsOffset), scratch);
__ movq(FieldOperand(result, JSObject::kPropertiesOffset), scratch);
if (initial_map->inobject_properties() != 0) {
__ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
for (int i = 0; i < initial_map->inobject_properties(); i++) {
int property_offset = JSObject::kHeaderSize + i * kPointerSize;
__ movq(FieldOperand(result, property_offset), scratch);
}
}
}
void LCodeGen::DoDeferredAllocateObject(LAllocateObject* instr) {
Register result = ToRegister(instr->result());
Handle<JSFunction> constructor = instr->hydrogen()->constructor();
Handle<Map> initial_map(constructor->initial_map());
int instance_size = initial_map->instance_size();
// TODO(3095996): Get rid of this. For now, we need to make the
// result register contain a valid pointer because it is already
// contained in the register pointer map.
__ Set(result, 0);
PushSafepointRegistersScope scope(this);
__ Push(Smi::FromInt(instance_size));
CallRuntimeFromDeferred(Runtime::kAllocateInNewSpace, 1, instr);
__ StoreToSafepointRegisterSlot(result, rax);
}
void LCodeGen::DoArrayLiteral(LArrayLiteral* instr) {
Handle<FixedArray> literals(instr->environment()->closure()->literals());
ElementsKind boilerplate_elements_kind =
instr->hydrogen()->boilerplate_elements_kind();
// Deopt if the array literal boilerplate ElementsKind is of a type different
// than the expected one. The check isn't necessary if the boilerplate has
// already been converted to TERMINAL_FAST_ELEMENTS_KIND.
if (CanTransitionToMoreGeneralFastElementsKind(
boilerplate_elements_kind, true)) {
__ LoadHeapObject(rax, instr->hydrogen()->boilerplate_object());
__ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
// Load the map's "bit field 2".
__ movb(rbx, FieldOperand(rbx, Map::kBitField2Offset));
// Retrieve elements_kind from bit field 2.
__ and_(rbx, Immediate(Map::kElementsKindMask));
__ cmpb(rbx, Immediate(boilerplate_elements_kind <<
Map::kElementsKindShift));
DeoptimizeIf(not_equal, instr->environment());
}
// Set up the parameters to the stub/runtime call.
__ PushHeapObject(literals);
__ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
// Boilerplate already exists, constant elements are never accessed.
// Pass an empty fixed array.
__ Push(isolate()->factory()->empty_fixed_array());
// Pick the right runtime function or stub to call.
int length = instr->hydrogen()->length();
if (instr->hydrogen()->IsCopyOnWrite()) {
ASSERT(instr->hydrogen()->depth() == 1);
FastCloneShallowArrayStub::Mode mode =
FastCloneShallowArrayStub::COPY_ON_WRITE_ELEMENTS;
FastCloneShallowArrayStub stub(mode, length);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
} else if (instr->hydrogen()->depth() > 1) {
CallRuntime(Runtime::kCreateArrayLiteral, 3, instr);
} else if (length > FastCloneShallowArrayStub::kMaximumClonedLength) {
CallRuntime(Runtime::kCreateArrayLiteralShallow, 3, instr);
} else {
FastCloneShallowArrayStub::Mode mode =
boilerplate_elements_kind == FAST_DOUBLE_ELEMENTS
? FastCloneShallowArrayStub::CLONE_DOUBLE_ELEMENTS
: FastCloneShallowArrayStub::CLONE_ELEMENTS;
FastCloneShallowArrayStub stub(mode, length);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
}
void LCodeGen::EmitDeepCopy(Handle<JSObject> object,
Register result,
Register source,
int* offset) {
ASSERT(!source.is(rcx));
ASSERT(!result.is(rcx));
// Only elements backing stores for non-COW arrays need to be copied.
Handle<FixedArrayBase> elements(object->elements());
bool has_elements = elements->length() > 0 &&
elements->map() != isolate()->heap()->fixed_cow_array_map();
// Increase the offset so that subsequent objects end up right after
// this object and its backing store.
int object_offset = *offset;
int object_size = object->map()->instance_size();
int elements_offset = *offset + object_size;
int elements_size = has_elements ? elements->Size() : 0;
*offset += object_size + elements_size;
// Copy object header.
ASSERT(object->properties()->length() == 0);
int inobject_properties = object->map()->inobject_properties();
int header_size = object_size - inobject_properties * kPointerSize;
for (int i = 0; i < header_size; i += kPointerSize) {
if (has_elements && i == JSObject::kElementsOffset) {
__ lea(rcx, Operand(result, elements_offset));
} else {
__ movq(rcx, FieldOperand(source, i));
}
__ movq(FieldOperand(result, object_offset + i), rcx);
}
// Copy in-object properties.
for (int i = 0; i < inobject_properties; i++) {
int total_offset = object_offset + object->GetInObjectPropertyOffset(i);
Handle<Object> value = Handle<Object>(object->InObjectPropertyAt(i));
if (value->IsJSObject()) {
Handle<JSObject> value_object = Handle<JSObject>::cast(value);
__ lea(rcx, Operand(result, *offset));
__ movq(FieldOperand(result, total_offset), rcx);
__ LoadHeapObject(source, value_object);
EmitDeepCopy(value_object, result, source, offset);
} else if (value->IsHeapObject()) {
__ LoadHeapObject(rcx, Handle<HeapObject>::cast(value));
__ movq(FieldOperand(result, total_offset), rcx);
} else {
__ movq(rcx, value, RelocInfo::NONE);
__ movq(FieldOperand(result, total_offset), rcx);
}
}
if (has_elements) {
// Copy elements backing store header.
__ LoadHeapObject(source, elements);
for (int i = 0; i < FixedArray::kHeaderSize; i += kPointerSize) {
__ movq(rcx, FieldOperand(source, i));
__ movq(FieldOperand(result, elements_offset + i), rcx);
}
// Copy elements backing store content.
int elements_length = elements->length();
if (elements->IsFixedDoubleArray()) {
Handle<FixedDoubleArray> double_array =
Handle<FixedDoubleArray>::cast(elements);
for (int i = 0; i < elements_length; i++) {
int64_t value = double_array->get_representation(i);
int total_offset =
elements_offset + FixedDoubleArray::OffsetOfElementAt(i);
__ movq(rcx, value, RelocInfo::NONE);
__ movq(FieldOperand(result, total_offset), rcx);
}
} else if (elements->IsFixedArray()) {
Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements);
for (int i = 0; i < elements_length; i++) {
int total_offset = elements_offset + FixedArray::OffsetOfElementAt(i);
Handle<Object> value(fast_elements->get(i));
if (value->IsJSObject()) {
Handle<JSObject> value_object = Handle<JSObject>::cast(value);
__ lea(rcx, Operand(result, *offset));
__ movq(FieldOperand(result, total_offset), rcx);
__ LoadHeapObject(source, value_object);
EmitDeepCopy(value_object, result, source, offset);
} else if (value->IsHeapObject()) {
__ LoadHeapObject(rcx, Handle<HeapObject>::cast(value));
__ movq(FieldOperand(result, total_offset), rcx);
} else {
__ movq(rcx, value, RelocInfo::NONE);
__ movq(FieldOperand(result, total_offset), rcx);
}
}
} else {
UNREACHABLE();
}
}
}
void LCodeGen::DoFastLiteral(LFastLiteral* instr) {
int size = instr->hydrogen()->total_size();
ElementsKind boilerplate_elements_kind =
instr->hydrogen()->boilerplate()->GetElementsKind();
// Deopt if the array literal boilerplate ElementsKind is of a type different
// than the expected one. The check isn't necessary if the boilerplate has
// already been converted to TERMINAL_FAST_ELEMENTS_KIND.
if (CanTransitionToMoreGeneralFastElementsKind(
boilerplate_elements_kind, true)) {
__ LoadHeapObject(rbx, instr->hydrogen()->boilerplate());
__ movq(rcx, FieldOperand(rbx, HeapObject::kMapOffset));
// Load the map's "bit field 2".
__ movb(rcx, FieldOperand(rcx, Map::kBitField2Offset));
// Retrieve elements_kind from bit field 2.
__ and_(rcx, Immediate(Map::kElementsKindMask));
__ cmpb(rcx, Immediate(boilerplate_elements_kind <<
Map::kElementsKindShift));
DeoptimizeIf(not_equal, instr->environment());
}
// Allocate all objects that are part of the literal in one big
// allocation. This avoids multiple limit checks.
Label allocated, runtime_allocate;
__ AllocateInNewSpace(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT);
__ jmp(&allocated);
__ bind(&runtime_allocate);
__ Push(Smi::FromInt(size));
CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
__ bind(&allocated);
int offset = 0;
__ LoadHeapObject(rbx, instr->hydrogen()->boilerplate());
EmitDeepCopy(instr->hydrogen()->boilerplate(), rax, rbx, &offset);
ASSERT_EQ(size, offset);
}
void LCodeGen::DoObjectLiteral(LObjectLiteral* instr) {
Handle<FixedArray> literals(instr->environment()->closure()->literals());
Handle<FixedArray> constant_properties =
instr->hydrogen()->constant_properties();
// Set up the parameters to the stub/runtime call.
__ PushHeapObject(literals);
__ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
__ Push(constant_properties);
int flags = instr->hydrogen()->fast_elements()
? ObjectLiteral::kFastElements
: ObjectLiteral::kNoFlags;
flags |= instr->hydrogen()->has_function()
? ObjectLiteral::kHasFunction
: ObjectLiteral::kNoFlags;
__ Push(Smi::FromInt(flags));
// Pick the right runtime function or stub to call.
int properties_count = constant_properties->length() / 2;
if (instr->hydrogen()->depth() > 1) {
CallRuntime(Runtime::kCreateObjectLiteral, 4, instr);
} else if (flags != ObjectLiteral::kFastElements ||
properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) {
CallRuntime(Runtime::kCreateObjectLiteralShallow, 4, instr);
} else {
FastCloneShallowObjectStub stub(properties_count);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
}
void LCodeGen::DoToFastProperties(LToFastProperties* instr) {
ASSERT(ToRegister(instr->value()).is(rax));
__ push(rax);
CallRuntime(Runtime::kToFastProperties, 1, instr);
}
void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) {
Label materialized;
// Registers will be used as follows:
// rcx = literals array.
// rbx = regexp literal.
// rax = regexp literal clone.
int literal_offset =
FixedArray::OffsetOfElementAt(instr->hydrogen()->literal_index());
__ LoadHeapObject(rcx, instr->hydrogen()->literals());
__ movq(rbx, FieldOperand(rcx, literal_offset));
__ CompareRoot(rbx, Heap::kUndefinedValueRootIndex);
__ j(not_equal, &materialized, Label::kNear);
// Create regexp literal using runtime function
// Result will be in rax.
__ push(rcx);
__ Push(Smi::FromInt(instr->hydrogen()->literal_index()));
__ Push(instr->hydrogen()->pattern());
__ Push(instr->hydrogen()->flags());
CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr);
__ movq(rbx, rax);
__ bind(&materialized);
int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
Label allocated, runtime_allocate;
__ AllocateInNewSpace(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT);
__ jmp(&allocated);
__ bind(&runtime_allocate);
__ push(rbx);
__ Push(Smi::FromInt(size));
CallRuntime(Runtime::kAllocateInNewSpace, 1, instr);
__ pop(rbx);
__ bind(&allocated);
// Copy the content into the newly allocated memory.
// (Unroll copy loop once for better throughput).
for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
__ movq(rdx, FieldOperand(rbx, i));
__ movq(rcx, FieldOperand(rbx, i + kPointerSize));
__ movq(FieldOperand(rax, i), rdx);
__ movq(FieldOperand(rax, i + kPointerSize), rcx);
}
if ((size % (2 * kPointerSize)) != 0) {
__ movq(rdx, FieldOperand(rbx, size - kPointerSize));
__ movq(FieldOperand(rax, size - kPointerSize), rdx);
}
}
void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) {
// Use the fast case closure allocation code that allocates in new
// space for nested functions that don't need literals cloning.
Handle<SharedFunctionInfo> shared_info = instr->shared_info();
bool pretenure = instr->hydrogen()->pretenure();
if (!pretenure && shared_info->num_literals() == 0) {
FastNewClosureStub stub(shared_info->language_mode());
__ Push(shared_info);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
} else {
__ push(rsi);
__ Push(shared_info);
__ PushRoot(pretenure ?
Heap::kTrueValueRootIndex :
Heap::kFalseValueRootIndex);
CallRuntime(Runtime::kNewClosure, 3, instr);
}
}
void LCodeGen::DoTypeof(LTypeof* instr) {
LOperand* input = instr->value();
EmitPushTaggedOperand(input);
CallRuntime(Runtime::kTypeof, 1, instr);
}
void LCodeGen::EmitPushTaggedOperand(LOperand* operand) {
ASSERT(!operand->IsDoubleRegister());
if (operand->IsConstantOperand()) {
Handle<Object> object = ToHandle(LConstantOperand::cast(operand));
if (object->IsSmi()) {
__ Push(Handle<Smi>::cast(object));
} else {
__ PushHeapObject(Handle<HeapObject>::cast(object));
}
} else if (operand->IsRegister()) {
__ push(ToRegister(operand));
} else {
__ push(ToOperand(operand));
}
}
void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
Register input = ToRegister(instr->value());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
Label* true_label = chunk_->GetAssemblyLabel(true_block);
Label* false_label = chunk_->GetAssemblyLabel(false_block);
Condition final_branch_condition =
EmitTypeofIs(true_label, false_label, input, instr->type_literal());
if (final_branch_condition != no_condition) {
EmitBranch(true_block, false_block, final_branch_condition);
}
}
Condition LCodeGen::EmitTypeofIs(Label* true_label,
Label* false_label,
Register input,
Handle<String> type_name) {
Condition final_branch_condition = no_condition;
if (type_name->Equals(heap()->number_symbol())) {
__ JumpIfSmi(input, true_label);
__ CompareRoot(FieldOperand(input, HeapObject::kMapOffset),
Heap::kHeapNumberMapRootIndex);
final_branch_condition = equal;
} else if (type_name->Equals(heap()->string_symbol())) {
__ JumpIfSmi(input, false_label);
__ CmpObjectType(input, FIRST_NONSTRING_TYPE, input);
__ j(above_equal, false_label);
__ testb(FieldOperand(input, Map::kBitFieldOffset),
Immediate(1 << Map::kIsUndetectable));
final_branch_condition = zero;
} else if (type_name->Equals(heap()->boolean_symbol())) {
__ CompareRoot(input, Heap::kTrueValueRootIndex);
__ j(equal, true_label);
__ CompareRoot(input, Heap::kFalseValueRootIndex);
final_branch_condition = equal;
} else if (FLAG_harmony_typeof && type_name->Equals(heap()->null_symbol())) {
__ CompareRoot(input, Heap::kNullValueRootIndex);
final_branch_condition = equal;
} else if (type_name->Equals(heap()->undefined_symbol())) {
__ CompareRoot(input, Heap::kUndefinedValueRootIndex);
__ j(equal, true_label);
__ JumpIfSmi(input, false_label);
// Check for undetectable objects => true.
__ movq(input, FieldOperand(input, HeapObject::kMapOffset));
__ testb(FieldOperand(input, Map::kBitFieldOffset),
Immediate(1 << Map::kIsUndetectable));
final_branch_condition = not_zero;
} else if (type_name->Equals(heap()->function_symbol())) {
STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
__ JumpIfSmi(input, false_label);
__ CmpObjectType(input, JS_FUNCTION_TYPE, input);
__ j(equal, true_label);
__ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE);
final_branch_condition = equal;
} else if (type_name->Equals(heap()->object_symbol())) {
__ JumpIfSmi(input, false_label);
if (!FLAG_harmony_typeof) {
__ CompareRoot(input, Heap::kNullValueRootIndex);
__ j(equal, true_label);
}
__ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input);
__ j(below, false_label);
__ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
__ j(above, false_label);
// Check for undetectable objects => false.
__ testb(FieldOperand(input, Map::kBitFieldOffset),
Immediate(1 << Map::kIsUndetectable));
final_branch_condition = zero;
} else {
__ jmp(false_label);
}
return final_branch_condition;
}
void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) {
Register temp = ToRegister(instr->temp());
int true_block = chunk_->LookupDestination(instr->true_block_id());
int false_block = chunk_->LookupDestination(instr->false_block_id());
EmitIsConstructCall(temp);
EmitBranch(true_block, false_block, equal);
}
void LCodeGen::EmitIsConstructCall(Register temp) {
// Get the frame pointer for the calling frame.
__ movq(temp, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
// Skip the arguments adaptor frame if it exists.
Label check_frame_marker;
__ Cmp(Operand(temp, StandardFrameConstants::kContextOffset),
Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
__ j(not_equal, &check_frame_marker, Label::kNear);
__ movq(temp, Operand(rax, StandardFrameConstants::kCallerFPOffset));
// Check the marker in the calling frame.
__ bind(&check_frame_marker);
__ Cmp(Operand(temp, StandardFrameConstants::kMarkerOffset),
Smi::FromInt(StackFrame::CONSTRUCT));
}
void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
// Ensure that we have enough space after the previous lazy-bailout
// instruction for patching the code here.
int current_pc = masm()->pc_offset();
if (current_pc < last_lazy_deopt_pc_ + space_needed) {
int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
__ Nop(padding_size);
}
}
void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
last_lazy_deopt_pc_ = masm()->pc_offset();
ASSERT(instr->HasEnvironment());
LEnvironment* env = instr->environment();
RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
}
void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
DeoptimizeIf(no_condition, instr->environment());
}
void LCodeGen::DoDeleteProperty(LDeleteProperty* instr) {
LOperand* obj = instr->object();
LOperand* key = instr->key();
EmitPushTaggedOperand(obj);
EmitPushTaggedOperand(key);
ASSERT(instr->HasPointerMap());
LPointerMap* pointers = instr->pointer_map();
RecordPosition(pointers->position());
// Create safepoint generator that will also ensure enough space in the
// reloc info for patching in deoptimization (since this is invoking a
// builtin)
SafepointGenerator safepoint_generator(
this, pointers, Safepoint::kLazyDeopt);
__ Push(Smi::FromInt(strict_mode_flag()));
__ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, safepoint_generator);
}
void LCodeGen::DoIn(LIn* instr) {
LOperand* obj = instr->object();
LOperand* key = instr->key();
EmitPushTaggedOperand(key);
EmitPushTaggedOperand(obj);
ASSERT(instr->HasPointerMap());
LPointerMap* pointers = instr->pointer_map();
RecordPosition(pointers->position());
SafepointGenerator safepoint_generator(
this, pointers, Safepoint::kLazyDeopt);
__ InvokeBuiltin(Builtins::IN, CALL_FUNCTION, safepoint_generator);
}
void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
PushSafepointRegistersScope scope(this);
__ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
__ CallRuntimeSaveDoubles(Runtime::kStackGuard);
RecordSafepointWithLazyDeopt(instr, RECORD_SAFEPOINT_WITH_REGISTERS, 0);
ASSERT(instr->HasEnvironment());
LEnvironment* env = instr->environment();
safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
}
void LCodeGen::DoStackCheck(LStackCheck* instr) {
class DeferredStackCheck: public LDeferredCode {
public:
DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
: LDeferredCode(codegen), instr_(instr) { }
virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); }
virtual LInstruction* instr() { return instr_; }
private:
LStackCheck* instr_;
};
ASSERT(instr->HasEnvironment());
LEnvironment* env = instr->environment();
// There is no LLazyBailout instruction for stack-checks. We have to
// prepare for lazy deoptimization explicitly here.
if (instr->hydrogen()->is_function_entry()) {
// Perform stack overflow check.
Label done;
__ CompareRoot(rsp, Heap::kStackLimitRootIndex);
__ j(above_equal, &done, Label::kNear);
StackCheckStub stub;
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
last_lazy_deopt_pc_ = masm()->pc_offset();
__ bind(&done);
RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
} else {
ASSERT(instr->hydrogen()->is_backwards_branch());
// Perform stack overflow check if this goto needs it before jumping.
DeferredStackCheck* deferred_stack_check =
new(zone()) DeferredStackCheck(this, instr);
__ CompareRoot(rsp, Heap::kStackLimitRootIndex);
__ j(below, deferred_stack_check->entry());
EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
last_lazy_deopt_pc_ = masm()->pc_offset();
__ bind(instr->done_label());
deferred_stack_check->SetExit(instr->done_label());
RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
// Don't record a deoptimization index for the safepoint here.
// This will be done explicitly when emitting call and the safepoint in
// the deferred code.
}
}
void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
// This is a pseudo-instruction that ensures that the environment here is
// properly registered for deoptimization and records the assembler's PC
// offset.
LEnvironment* environment = instr->environment();
environment->SetSpilledRegisters(instr->SpilledRegisterArray(),
instr->SpilledDoubleRegisterArray());
// If the environment were already registered, we would have no way of
// backpatching it with the spill slot operands.
ASSERT(!environment->HasBeenRegistered());
RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
ASSERT(osr_pc_offset_ == -1);
osr_pc_offset_ = masm()->pc_offset();
}
void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
__ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
DeoptimizeIf(equal, instr->environment());
Register null_value = rdi;
__ LoadRoot(null_value, Heap::kNullValueRootIndex);
__ cmpq(rax, null_value);
DeoptimizeIf(equal, instr->environment());
Condition cc = masm()->CheckSmi(rax);
DeoptimizeIf(cc, instr->environment());
STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
__ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx);
DeoptimizeIf(below_equal, instr->environment());
Label use_cache, call_runtime;
__ CheckEnumCache(null_value, &call_runtime);
__ movq(rax, FieldOperand(rax, HeapObject::kMapOffset));
__ jmp(&use_cache, Label::kNear);
// Get the set of properties to enumerate.
__ bind(&call_runtime);
__ push(rax);
CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr);
__ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset),
Heap::kMetaMapRootIndex);
DeoptimizeIf(not_equal, instr->environment());
__ bind(&use_cache);
}
void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
Register map = ToRegister(instr->map());
Register result = ToRegister(instr->result());
Label load_cache, done;
__ EnumLength(result, map);
__ Cmp(result, Smi::FromInt(0));
__ j(not_equal, &load_cache);
__ LoadRoot(result, Heap::kEmptyFixedArrayRootIndex);
__ jmp(&done);
__ bind(&load_cache);
__ LoadInstanceDescriptors(map, result);
__ movq(result,
FieldOperand(result, DescriptorArray::kEnumCacheOffset));
__ movq(result,
FieldOperand(result, FixedArray::SizeFor(instr->idx())));
__ bind(&done);
Condition cc = masm()->CheckSmi(result);
DeoptimizeIf(cc, instr->environment());
}
void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
Register object = ToRegister(instr->value());
__ cmpq(ToRegister(instr->map()),
FieldOperand(object, HeapObject::kMapOffset));
DeoptimizeIf(not_equal, instr->environment());
}
void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
Register object = ToRegister(instr->object());
Register index = ToRegister(instr->index());
Label out_of_object, done;
__ SmiToInteger32(index, index);
__ cmpl(index, Immediate(0));
__ j(less, &out_of_object);
__ movq(object, FieldOperand(object,
index,
times_pointer_size,
JSObject::kHeaderSize));
__ jmp(&done, Label::kNear);
__ bind(&out_of_object);
__ movq(object, FieldOperand(object, JSObject::kPropertiesOffset));
__ negl(index);
// Index is now equal to out of object property index plus 1.
__ movq(object, FieldOperand(object,
index,
times_pointer_size,
FixedArray::kHeaderSize - kPointerSize));
__ bind(&done);
}
#undef __
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_X64
| qtproject/qtjsbackend | src/3rdparty/v8/src/x64/lithium-codegen-x64.cc | C++ | gpl-3.0 | 180,943 |
---
title: jump
category: transitions
---
~~~haskell
jump :: Time -> [ParamPattern] -> ParamPattern
~~~
Jumps directly into the given pattern, this is essentially the _no transition_-transition.
Variants of `jump` provide more useful capabilities, see `jumpIn` and `jumpMod`
| tidalcycles/tidalcycles.github.io | _functions/transitions/jump.md | Markdown | gpl-3.0 | 278 |
<html><head><title>EC 1.13.1.11</title></head>
<base href="http://www.chem.qmul.ac.uk/iubmb/enzyme/EC1/13/1/11.html">
<body>
<center><b>IUBMB Enzyme Nomenclature</b><p>
<h1><b>EC 1.13.1.11</b></h1></center>
<b>Transferred entry:</b> now <a href="../99/1.html">EC 1.13.99.1</a> inositol oxygenase<p>
<center><small>[EC 1.13.1.11 created 1961 as EC 1.99.2.6, transferred1965 to EC 1.13.1.11, deleted 1972]</small></center><p>
<hr>
Return to <a href="../1/">EC 1.13.1 home page</a><br>
Return to <a href="../">EC 1.13 home page</a><br>
Return to <a href="../../">EC 1 home page</a><br>
Return to <a href="../../../">Enzymes home page</a><br>
Return to <a href="../../../../">IUBMB Biochemical Nomenclature home page</a><p>
</body></html>
| dmrib/enzymes-in-crisis | data/www.chem.qmul.ac.uk/iubmb/enzyme/EC1/13/1/11.html | HTML | gpl-3.0 | 742 |
// Copyright (C) 2013 Michael Biggs. See the COPYING file at the top-level
// directory of this distribution and at http://shok.io/code/copyright.html
#include "ProcCall.h"
#include "Expression.h"
#include "CompileError.h"
#include "Function.h"
#include <memory>
#include <string>
#include <vector>
using std::auto_ptr;
using std::string;
using std::vector;
using namespace compiler;
void ProcCall::setup() {
if (children.size() < 1) {
throw CompileError("ProcCall must have >= 1 children");
}
Variable* var = dynamic_cast<Variable*>(children.at(0));
if (!var) {
throw CompileError("ProcCall first child must be a Variable");
}
m_object = &var->getObject();
/*
if (!m_object->isFunction()) {
throw CompileError("ProcCall cannot call a non-function");
}
*/
for (child_iter i = children.begin()+1; i != children.end(); ++i) {
Expression* exp = dynamic_cast<Expression*>(*i);
if (!exp) {
throw CompileError("ProcCall params must be Expressions");
}
m_paramexps.push_back(exp);
m_paramtypes.push_back(&exp->type());
}
// Verify that the function has a signature for these param types
/*
if (!m_object->takesArgs(m_paramtypes)) {
throw CompileError("Function " + m_object->print() + " does not accept the provided parameters");
}
*/
}
void ProcCall::compile() {
// The expressions of m_paramexps have all been compiled. Call the function
// on their resulting objects. The object being called gets ownership of the
// params.
param_vec params;
for (exp_iter i = m_paramexps.begin(); i != m_paramexps.end(); ++i) {
// TODO: ask the object for the argument names it wants to use (on the
// specific signature we're calling)
params.push_back((*i)->getObject("(some arg)").release());
}
//auto_ptr<Object> ret = m_object->call(params);
}
void ProcCall::computeType() {
// ProcCall type is the return type of the function
//m_type = m_object->getPossibleReturnTypes(m_paramtypes);
}
| nfomon/shok | compiler/ProcCall.cpp | C++ | gpl-3.0 | 1,989 |
<tr>
{columns}
</tr> | XG-Project/XG-Project-v2 | styles/views/galaxy/galaxy_row_container.php | PHP | gpl-3.0 | 23 |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>couple/cfd/force command — CFDEMcoupling v3.X documentation</title>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="top" title="CFDEMcoupling v3.X documentation" href="index.html"/>
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="CFDEMcoupling_Manual.html" class="icon icon-home"> CFDEMcoupling
</a>
<div class="version">
v3.X
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<!-- Local TOC -->
<div class="local-toc"><ul>
<li><a class="reference internal" href="#">couple/cfd/force command</a><ul>
<li><a class="reference internal" href="#syntax">Syntax</a></li>
<li><a class="reference internal" href="#examples">Examples</a></li>
<li><a class="reference internal" href="#description">Description</a></li>
<li><a class="reference internal" href="#restrictions">Restrictions</a></li>
<li><a class="reference internal" href="#default">Default</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="CFDEMcoupling_Manual.html">CFDEMcoupling</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="CFDEMcoupling_Manual.html">Docs</a> »</li>
<li>couple/cfd/force command</li>
<li class="wy-breadcrumbs-aside">
<a href="http://www.cfdem.com"> Website</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="couple-cfd-force-command">
<span id="index-0"></span><h1>couple/cfd/force command<a class="headerlink" href="#couple-cfd-force-command" title="Permalink to this headline">¶</a></h1>
<div class="section" id="syntax">
<h2>Syntax<a class="headerlink" href="#syntax" title="Permalink to this headline">¶</a></h2>
<div class="highlight-python"><div class="highlight"><pre>fix ID group-ID couple/cfd/force
</pre></div>
</div>
<ul class="simple">
<li>ID, group-ID are documented in <tt class="xref doc docutils literal"><span class="pre">fix</span></tt> command</li>
<li>couple/cfd = style name of this fix command</li>
</ul>
</div>
<div class="section" id="examples">
<h2>Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>fix cfd all couple/cfd couple_every 100 mpi
fix cfd2 all couple/cfd/force</p>
</div>
<div class="section" id="description">
<h2>Description<a class="headerlink" href="#description" title="Permalink to this headline">¶</a></h2>
<p>The command couple/cfd/force can only be used in combination with <a class="reference internal" href="fix_couple_cfd.html"><em>fix_couple_cfd</em></a>. This model transfers the force that the fluid exceeds on each particle to the DEM calculation. At every coupling time step the force term, which contains contributions from all force models active in the CFD calculation, is passed on to LIGGGHTS(R). This (constant) term is then used in the particle calculations at every DEM time step until the next coupling takes place.</p>
</div>
<div class="section" id="restrictions">
<h2>Restrictions<a class="headerlink" href="#restrictions" title="Permalink to this headline">¶</a></h2>
<p>None</p>
<p><strong>Related Commands:</strong>
<a class="reference internal" href="fix_couple_cfd.html"><em>fix couple/cfd</em></a></p>
</div>
<div class="section" id="default">
<h2>Default<a class="headerlink" href="#default" title="Permalink to this headline">¶</a></h2>
<p>None</p>
</div>
</div>
</div>
</div>
<footer>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2016, DCS Computing GmbH, JKU Linz.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'./',
VERSION:'v3.X',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<script type="text/javascript" src="_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html> | CFDEMproject/CFDEMcoupling-NanoSim-PUBLIC | doc/_build/html/fix_couple_cfd_force.html | HTML | gpl-3.0 | 6,290 |
CREATE TABLE "list_of_apps_contest" (
"name" text,
"website" text
);
| talos/docker4data | data/socrata/data.govloop.com/list_of_apps_contest/schema.sql | SQL | gpl-3.0 | 71 |
/* xoreos - A reimplementation of BioWare's Aurora engine
*
* xoreos is the legal property of its developers, whose names
* can be found in the AUTHORS file distributed with this source
* distribution.
*
* xoreos 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
* of the License, or (at your option) any later version.
*
* xoreos 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 xoreos. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file
* Render queue, for efficient OpenGL render calls.
*/
#include <cassert>
#include "external/glm/gtc/type_ptr.hpp"
#include "src/graphics/render/renderqueue.h"
#include "src/common/util.h"
#include <algorithm>
namespace Graphics {
namespace Render {
bool compareShader(const RenderQueue::RenderQueueNode &a, const RenderQueue::RenderQueueNode &b)
{
if (a.program < b.program)
return false;
else if (a.program > b.program)
return true;
if (a.material < b.material) // node_program values are equal.
return false;
else if (a.material > b.material)
return true;
else // node material values are equal, compare mesh values next.
return (a.mesh <= b.mesh ? false : true);
// No, surfaces are not compared here.
}
bool compareDepth(const RenderQueue::RenderQueueNode &a, const RenderQueue::RenderQueueNode &b) {
return (a.reference <= b.reference);
//return (a.reference.lengthSquared() <= b.reference.lengthSquared());
}
RenderQueue::RenderQueue(uint32 precache) : _nodeArray(precache), _cameraReference(0.0f, 0.0f, 0.0f) {
// _nodeArray.reserve(1000);
}
RenderQueue::~RenderQueue()
{
_nodeArray.clear();
}
void RenderQueue::setCameraReference(const glm::vec3 &reference) {
_cameraReference = reference;
}
void RenderQueue::queueItem(Shader::ShaderProgram *program, Shader::ShaderSurface *surface, Shader::ShaderMaterial *material, Mesh::Mesh *mesh, const glm::mat4 *transform, float alpha) {
if (program->glid == 0) {
return;
}
glm::vec3 ref((*transform)[3]);
ref += mesh->getCentre();
ref -= _cameraReference;
// Length squared of ref serves as a suitable depth sorting value.
_nodeArray.push_back(RenderQueueNode(program, surface, material, mesh, transform, alpha, glm::dot(ref, ref)));
}
void RenderQueue::queueItem(Shader::ShaderRenderable *renderable, const glm::mat4 *transform, float alpha) {
if (renderable->getProgram()->glid == 0) {
return;
}
glm::vec3 ref((*transform)[3]);
ref -= _cameraReference;
// Length squared of ref serves as a suitable depth sorting value.
_nodeArray.push_back(RenderQueueNode(renderable->getProgram(), renderable->getSurface(), renderable->getMaterial(), renderable->getMesh(), transform, alpha, glm::dot(ref, ref)));
}
void RenderQueue::sortShader() {
if (_nodeArray.size() > 1) {
std::sort(_nodeArray.begin(), _nodeArray.end(), compareShader);
}
}
void RenderQueue::sortDepth() {
if (_nodeArray.size() > 1) {
std::sort(_nodeArray.begin(), _nodeArray.end(), compareDepth);
}
}
void RenderQueue::render() {
if (_nodeArray.size() == 0) {
return;
}
Shader::ShaderProgram *currentProgram = 0;
Shader::ShaderMaterial *currentMaterial = 0;
Shader::ShaderSurface *currentSurface = 0;
Mesh::Mesh *currentMesh = 0;
uint32 i = 0;
uint32 limit = _nodeArray.size();
while (i < limit) {
assert(_nodeArray[i].program);
if (currentProgram != _nodeArray[i].program) {
currentProgram = _nodeArray[i].program;
glUseProgram(currentProgram->glid);
if (currentSurface != 0) {
currentSurface->unbindGLState();
}
if (currentMaterial != 0) {
currentMaterial->unbindGLState();
}
currentMaterial = 0;
currentSurface = 0;
}
assert(_nodeArray[i].material);
if (currentMaterial != _nodeArray[i].material) {
if (currentMaterial != 0) {
currentMaterial->unbindGLState();
}
currentMaterial = _nodeArray[i].material;
currentMaterial->bindProgramNoFade(currentProgram);
currentMaterial->bindGLState();
}
assert(_nodeArray[i].surface);
assert(_nodeArray[i].mesh);
if (currentSurface != _nodeArray[i].surface) {
if (currentSurface != 0) {
currentSurface->unbindGLState();
}
currentSurface = _nodeArray[i].surface;
currentSurface->bindGLState();
}
currentSurface = _nodeArray[i].surface;
currentMesh = _nodeArray[i].mesh;
currentMesh->renderBind(); // Binds VAO ready for rendering.
// There's at least one mesh to be rendering here.
assert(_nodeArray[i].transform);
assert(currentSurface);
assert(currentMaterial);
currentSurface->bindProgram(currentProgram, _nodeArray[i].transform);
//currentSurface->bindObjectModelview(currentProgram, _nodeArray[i].transform);
bindBoneUniforms(currentProgram, currentSurface, currentMesh);
currentMaterial->bindFade(currentProgram, _nodeArray[i].alpha);
currentMesh->render();
++i; // Move to next object.
while ((i < limit) && (_nodeArray[i].mesh == currentMesh) && (_nodeArray[i].material == currentMaterial) && (_nodeArray[i].surface == currentSurface)) {
// Next object is basically the same, but will have a different object modelview transform. So rebind that, and render again.
assert(_nodeArray[i].transform);
currentSurface->bindObjectModelview(currentProgram, _nodeArray[i].transform);
bindBoneUniforms(currentProgram, currentSurface, currentMesh);
currentMaterial->bindFade(currentProgram, _nodeArray[i].alpha);
currentMesh->render();
++i;
}
// Done rendering, unbind the mesh, and onwards into the queue.
currentMesh->renderUnbind();
}
if (currentMaterial) {
currentMaterial->unbindGLState();
}
if (currentSurface) {
currentSurface->unbindGLState();
}
glUseProgram(0);
glActiveTexture(GL_TEXTURE0);
}
void RenderQueue::clear() {
_nodeArray.clear();
}
void RenderQueue::bindBoneUniforms(Shader::ShaderProgram *program, Shader::ShaderSurface *surface, Mesh::Mesh *mesh) {
surface->bindBindPose(program, mesh->getBindPosePtr());
const std::vector<float> &boneTransforms = mesh->getBoneTransforms();
if (!boneTransforms.empty())
surface->bindBoneTransforms(program, boneTransforms.data());
}
} // namespace Render
} // namespace Graphics
| Supermanu/xoreos | src/graphics/render/renderqueue.cpp | C++ | gpl-3.0 | 6,486 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Rapidly-exploring Random Trees: F:/GitHub/Rapidly-exploringRandomTrees/src/app/heightmappanel -> classes Relation</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Rapidly-exploring Random Trees
 <span id="projectnumber">0.1</span>
</div>
<div id="projectbrief">Project of Artificial Intelligence for Robotics at the University Paris 6</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.12 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_5194e5fea318fda12687127c23f8aba1.html">app</a></li><li class="navelem"><a class="el" href="dir_da266843aa8258a5abd13e4ce55c9036.html">heightmappanel</a></li> </ul>
</div>
</div><!-- top -->
<div class="contents">
<h3>heightmappanel → classes Relation</h3><table class="dirtab"><tr class="dirtab"><th class="dirtab">File in src/app/heightmappanel</th><th class="dirtab">Includes file in src/classes</th></tr><tr class="dirtab"><td class="dirtab"><a class="el" href="heightmapframe_8h.html">heightmapframe.h</a></td><td class="dirtab"><a class="el" href="config_8h.html">config.h</a></td></tr><tr class="dirtab"><td class="dirtab"><a class="el" href="heightmapviewpanel_8cpp.html">heightmapviewpanel.cpp</a></td><td class="dirtab"><a class="el" href="threadgenerator_8h.html">threadgenerator.h</a></td></tr><tr class="dirtab"><td class="dirtab"><a class="el" href="heightmapviewpanel_8h.html">heightmapviewpanel.h</a></td><td class="dirtab"><a class="el" href="dir_c6ab66d9cfc792cef8c079468da561dc.html">environment</a> / <a class="el" href="vertex_8h.html">vertex.h</a></td></tr></table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.12
</small></address>
</body>
</html>
| ThibaultGigant/Rapidly-exploringRandomTrees | doc/html/dir_000009_000010.html | HTML | gpl-3.0 | 3,973 |
#define MODULE_LOG_PREFIX "dvbapi"
#include "globals.h"
#ifdef HAVE_DVBAPI
#include "oscam-config.h"
#include "oscam-ecm.h"
#include "oscam-string.h"
#include "module-dvbapi.h"
#include "module-dvbapi-chancache.h"
extern DEMUXTYPE demux[MAX_DEMUX];
static LLIST *channel_cache;
void dvbapi_save_channel_cache(void)
{
if(boxtype_is("dbox2")) return; // dont save channelcache on these boxes, they lack resources and will crash!
if (USE_OPENXCAS) // Why?
return;
char fname[256];
int32_t result = 0;
get_config_filename(fname, sizeof(fname), "oscam.ccache");
FILE *file = fopen(fname, "w");
if(!file)
{
cs_log("dvbapi channelcache can't write to file %s", fname);
return;
}
LL_ITER it = ll_iter_create(channel_cache);
struct s_channel_cache *c;
while((c = ll_iter_next(&it)))
{
result = fprintf(file, "%04X,%06X,%04X,%04X,%06X\n", c->caid, c->prid, c->srvid, c->pid, c->chid);
if(result < 0)
{
fclose(file);
result = remove(fname);
if(!result)
{
cs_log("error writing cache -> cache file removed!");
}
else
{
cs_log("error writing cache -> cache file could not be removed either!");
}
return;
}
}
fclose(file);
cs_log("dvbapi channelcache saved to %s", fname);
}
void dvbapi_load_channel_cache(void)
{
if(boxtype_is("dbox2")) return; // dont load channelcache on these boxes, they lack resources and will crash!
if (USE_OPENXCAS) // Why?
return;
char fname[256];
char line[1024];
FILE *file;
struct s_channel_cache *c;
get_config_filename(fname, sizeof(fname), "oscam.ccache");
file = fopen(fname, "r");
if(!file)
{
cs_log_dbg(D_TRACE, "dvbapi channelcache can't read from file %s", fname);
return;
}
int32_t i = 1;
int32_t valid = 0;
char *ptr, *saveptr1 = NULL;
char *split[6];
memset(line, 0, sizeof(line));
while(fgets(line, sizeof(line), file))
{
if(!line[0] || line[0] == '#' || line[0] == ';')
{ continue; }
for(i = 0, ptr = strtok_r(line, ",", &saveptr1); ptr && i < 6 ; ptr = strtok_r(NULL, ",", &saveptr1), i++)
{
split[i] = ptr;
}
valid = (i == 5);
if(valid)
{
if(!cs_malloc(&c, sizeof(struct s_channel_cache)))
{ continue; }
c->caid = a2i(split[0], 4);
c->prid = a2i(split[1], 6);
c->srvid = a2i(split[2], 4);
c->pid = a2i(split[3], 4);
c->chid = a2i(split[4], 6);
if(valid && c->caid != 0)
{
if(!channel_cache)
{
channel_cache = ll_create("channel cache");
}
ll_append(channel_cache, c);
}
else
{
NULLFREE(c);
}
}
}
fclose(file);
cs_log("dvbapi channelcache loaded from %s", fname);
}
struct s_channel_cache *dvbapi_find_channel_cache(int32_t demux_id, int32_t pidindex, int8_t caid_and_prid_only)
{
struct s_ecmpids *p = &demux[demux_id].ECMpids[pidindex];
struct s_channel_cache *c;
LL_ITER it;
if(!channel_cache)
{ channel_cache = ll_create("channel cache"); }
it = ll_iter_create(channel_cache);
while((c = ll_iter_next(&it)))
{
if(caid_and_prid_only)
{
if(p->CAID == c->caid && (p->PROVID == c->prid || p->PROVID == 0)) // PROVID ==0 some provider no provid in PMT table
{ return c; }
}
else
{
if(demux[demux_id].program_number == c->srvid
&& p->CAID == c->caid
&& p->ECM_PID == c->pid
&& (p->PROVID == c->prid || p->PROVID == 0)) // PROVID ==0 some provider no provid in PMT table
{
#ifdef WITH_DEBUG
char buf[ECM_FMT_LEN];
ecmfmt(c->caid, 0, c->prid, c->chid, c->pid, c->srvid, 0, 0, 0, 0, buf, ECM_FMT_LEN, 0, 0);
cs_log_dbg(D_DVBAPI, "Demuxer %d found in channel cache: %s", demux_id, buf);
#endif
return c;
}
}
}
return NULL;
}
int32_t dvbapi_edit_channel_cache(int32_t demux_id, int32_t pidindex, uint8_t add)
{
struct s_ecmpids *p = &demux[demux_id].ECMpids[pidindex];
struct s_channel_cache *c;
LL_ITER it;
int32_t count = 0;
if(!channel_cache)
{ channel_cache = ll_create("channel cache"); }
it = ll_iter_create(channel_cache);
while((c = ll_iter_next(&it)))
{
if(demux[demux_id].program_number == c->srvid
&& p->CAID == c->caid
&& p->ECM_PID == c->pid
&& (p->PROVID == c->prid || p->PROVID == 0))
{
if(add && p->CHID == c->chid)
{
return 0; //already added
}
ll_iter_remove_data(&it);
count++;
}
}
if(add)
{
if(!cs_malloc(&c, sizeof(struct s_channel_cache)))
{ return count; }
c->srvid = demux[demux_id].program_number;
c->caid = p->CAID;
c->pid = p->ECM_PID;
c->prid = p->PROVID;
c->chid = p->CHID;
ll_append(channel_cache, c);
#ifdef WITH_DEBUG
char buf[ECM_FMT_LEN];
ecmfmt(c->caid, 0, c->prid, c->chid, c->pid, c->srvid, 0, 0, 0, 0, buf, ECM_FMT_LEN, 0, 0);
cs_log_dbg(D_DVBAPI, "Demuxer %d added to channel cache: %s", demux_id, buf);
#endif
count++;
}
return count;
}
#endif
| digrobot/oscam | module-dvbapi-chancache.c | C | gpl-3.0 | 4,768 |
describe("Portal.filter.combiner.DataDownloadCqlBuilder", function() {
var builder;
beforeEach(function() {
var filters =[
{
constructor: Portal.filter.GeometryFilter, // Is Geometry filter
isVisualised: returns(true),
hasValue: returns(true),
getCql: returns('cql1')
},
{
isVisualised: returns(false), // Not visualised
hasValue: returns(true),
getCql: returns('cql2')
},
{
isVisualised: returns(true),
hasValue: returns(false), // No value
getCql: returns('cql3')
},
{
isVisualised: returns(true),
hasValue: returns(true),
getCql: returns('cql4')
}
];
builder = new Portal.filter.combiner.DataDownloadCqlBuilder({
filters: filters
});
});
describe('buildCql', function() {
it('returns correct CQL', function() {
expect(builder.buildCql()).toBe('cql1 AND cql2 AND cql4');
});
});
});
| aodn/aodn-portal | src/test/javascript/portal/filter/combiner/DataDownloadCqlBuilderSpec.js | JavaScript | gpl-3.0 | 1,188 |
# ----------------------------------------------------------------------------------------------------------------------
# GX Framework (c) 2009-2011 Jörg A. Uzarek <uzarek@runlevelnull.de>
# File: GX/Model.pm
# ----------------------------------------------------------------------------------------------------------------------
package GX::Model;
# ----------------------------------------------------------------------------------------------------------------------
# Class setup
# ----------------------------------------------------------------------------------------------------------------------
use GX::Class;
extends 'GX::Component::Singleton';
build;
# ----------------------------------------------------------------------------------------------------------------------
# Export mechanism
# ----------------------------------------------------------------------------------------------------------------------
__PACKAGE__->_install_import_method;
# ----------------------------------------------------------------------------------------------------------------------
# Private Methods
# ----------------------------------------------------------------------------------------------------------------------
sub _validate_class_name {
return $_[1] =~ /^(?:[_a-zA-Z]\w*::)+?Model(?:::[_a-zA-Z]\w*)+$/;
}
1;
__END__
=head1 NAME
GX::Model - Model component base class
=head1 SYNOPSIS
None.
=head1 DESCRIPTION
This module provides the L<GX::Model> class which extends the
L<GX::Component::Singleton> class.
=head1 AUTHOR
JE<ouml>rg A. Uzarek E<lt>uzarek@runlevelnull.deE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (c) 2009-2011 JE<ouml>rg A. Uzarek.
This module is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License Version 3 as published by the
Free Software Foundation.
=cut
| gitpan/GX | lib/GX/Model.pm | Perl | gpl-3.0 | 1,876 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#include "../jucer_Headers.h"
#include "jucer_CodeHelpers.h"
//==============================================================================
namespace FileHelpers
{
static int64 calculateMemoryHashCode (const void* data, const size_t numBytes)
{
int64 t = 0;
for (size_t i = 0; i < numBytes; ++i)
t = t * 65599 + static_cast <const uint8*> (data)[i];
return t;
}
int64 calculateStreamHashCode (InputStream& in)
{
int64 t = 0;
const int bufferSize = 4096;
HeapBlock <uint8> buffer;
buffer.malloc (bufferSize);
for (;;)
{
const int num = in.read (buffer, bufferSize);
if (num <= 0)
break;
for (int i = 0; i < num; ++i)
t = t * 65599 + buffer[i];
}
return t;
}
int64 calculateFileHashCode (const File& file)
{
ScopedPointer <FileInputStream> stream (file.createInputStream());
return stream != nullptr ? calculateStreamHashCode (*stream) : 0;
}
bool overwriteFileWithNewDataIfDifferent (const File& file, const void* data, size_t numBytes)
{
if (file.getSize() == (int64) numBytes
&& calculateMemoryHashCode (data, numBytes) == calculateFileHashCode (file))
return true;
if (file.exists())
return file.replaceWithData (data, numBytes);
return file.getParentDirectory().createDirectory() && file.appendData (data, numBytes);
}
bool overwriteFileWithNewDataIfDifferent (const File& file, const MemoryOutputStream& newData)
{
return overwriteFileWithNewDataIfDifferent (file, newData.getData(), newData.getDataSize());
}
bool overwriteFileWithNewDataIfDifferent (const File& file, const String& newData)
{
const char* const utf8 = newData.toUTF8();
return overwriteFileWithNewDataIfDifferent (file, utf8, strlen (utf8));
}
bool containsAnyNonHiddenFiles (const File& folder)
{
DirectoryIterator di (folder, false);
while (di.next())
if (! di.getFile().isHidden())
return true;
return false;
}
String unixStylePath (const String& path) { return path.replaceCharacter ('\\', '/'); }
String windowsStylePath (const String& path) { return path.replaceCharacter ('/', '\\'); }
String currentOSStylePath (const String& path)
{
#if JUCE_WINDOWS
return windowsStylePath (path);
#else
return unixStylePath (path);
#endif
}
bool isAbsolutePath (const String& path)
{
return File::isAbsolutePath (path)
|| path.startsWithChar ('/') // (needed because File::isAbsolutePath will ignore forward-slashes on Windows)
|| path.startsWithChar ('$')
|| path.startsWithChar ('~')
|| (CharacterFunctions::isLetter (path[0]) && path[1] == ':')
|| path.startsWithIgnoreCase ("smb:");
}
String appendPath (const String& path, const String& subpath)
{
if (isAbsolutePath (subpath))
return unixStylePath (subpath);
String path1 (unixStylePath (path));
if (! path1.endsWithChar ('/'))
path1 << '/';
return path1 + unixStylePath (subpath);
}
bool shouldPathsBeRelative (String path1, String path2)
{
path1 = unixStylePath (path1);
path2 = unixStylePath (path2);
const int len = jmin (path1.length(), path2.length());
int commonBitLength = 0;
for (int i = 0; i < len; ++i)
{
if (CharacterFunctions::toLowerCase (path1[i]) != CharacterFunctions::toLowerCase (path2[i]))
break;
++commonBitLength;
}
return path1.substring (0, commonBitLength).removeCharacters ("/:").isNotEmpty();
}
String getRelativePathFrom (const File& file, const File& sourceFolder)
{
#if ! JUCE_WINDOWS
// On a non-windows machine, we can't know if a drive-letter path may be relative or not.
if (CharacterFunctions::isLetter (file.getFullPathName()[0]) && file.getFullPathName()[1] == ':')
return file.getFullPathName();
#endif
return file.getRelativePathFrom (sourceFolder);
}
// removes "/../" bits from the middle of the path
String simplifyPath (String::CharPointerType p)
{
#if JUCE_WINDOWS
if (CharacterFunctions::indexOf (p, CharPointer_ASCII ("/../")) >= 0
|| CharacterFunctions::indexOf (p, CharPointer_ASCII ("\\..\\")) >= 0)
#else
if (CharacterFunctions::indexOf (p, CharPointer_ASCII ("/../")) >= 0)
#endif
{
StringArray toks;
#if JUCE_WINDOWS
toks.addTokens (p, "\\/", StringRef());
#else
toks.addTokens (p, "/", StringRef());
#endif
while (toks[0] == ".")
toks.remove (0);
for (int i = 1; i < toks.size(); ++i)
{
if (toks[i] == ".." && toks [i - 1] != "..")
{
toks.removeRange (i - 1, 2);
i = jmax (0, i - 2);
}
}
return toks.joinIntoString ("/");
}
return p;
}
String simplifyPath (const String& path)
{
#if JUCE_WINDOWS
if (path.contains ("\\..\\") || path.contains ("/../"))
#else
if (path.contains ("/../"))
#endif
return simplifyPath (path.getCharPointer());
return path;
}
}
| eriser/helm | JUCE/extras/Introjucer/Source/Utility/jucer_FileHelpers.cpp | C++ | gpl-3.0 | 6,821 |
package com.ardublock.ui;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JComponent;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.ardublock.core.Context;
import com.ardublock.ui.listener.ArdublockWorkspaceListener;
import com.ardublock.ui.listener.GenerateCodeButtonListener;
import com.ardublock.ui.listener.NewButtonListener;
import com.ardublock.ui.listener.OpenButtonListener;
import com.ardublock.ui.listener.OpenblocksFrameListener;
import com.ardublock.ui.listener.SaveAsButtonListener;
import com.ardublock.ui.listener.SaveButtonListener;
import edu.mit.blocks.controller.WorkspaceController;
import edu.mit.blocks.workspace.SearchBar;
import edu.mit.blocks.workspace.SearchableContainer;
import edu.mit.blocks.workspace.Workspace;
public class OpenblocksFrame extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 2841155965906223806L;
private Context context;
private JFileChooser fileChooser;
private FileFilter ffilter;
private ResourceBundle uiMessageBundle;
private JPanel workspacePanel;
private SearchBar searchBar;
public void addListener(OpenblocksFrameListener ofl)
{
context.registerOpenblocksFrameListener(ofl);
}
public String makeFrameTitle()
{
String title = Context.APP_NAME + " - ROKENBOK Edition - " + context.getSaveFileName();
if (context.isWorkspaceChanged())
{
title = title + " *";
}
return title;
}
public OpenblocksFrame()
{
context = Context.getContext();
this.setTitle(makeFrameTitle());
this.setSize(new Dimension(1024, 900));
this.setLayout(new BorderLayout());
//put the frame to the center of screen
this.setLocationRelativeTo(null);
//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
uiMessageBundle = ResourceBundle.getBundle("com/ardublock/block/ardublock");
fileChooser = new JFileChooser();
ffilter = new FileNameExtensionFilter(uiMessageBundle.getString("ardublock.file.suffix"), "abp");
fileChooser.setFileFilter(ffilter);
fileChooser.addChoosableFileFilter(ffilter);
initOpenBlocks();
}
private void initOpenBlocks()
{
final Context context = Context.getContext();
final Workspace workspace = context.getWorkspace();
final WorkspaceController workspaceController = context.getWorkspaceController();
JComponent workspaceComponent = workspaceController.getWorkspacePanel();
// WTF I can't add worksapcelistener by workspace contrller
workspace.addWorkspaceListener(new ArdublockWorkspaceListener(this));
/* final SearchBar sb = new SearchBar("Search blocks",
"Search for blocks in the drawers and workspace", workspace);
for (SearchableContainer con : workspaceController.getAllSearchableContainers()) {
sb.addSearchableContainer(con);
}
sb.getComponent().setPreferredSize(new Dimension(130, 23)); */
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout());
JButton newButton = new JButton(uiMessageBundle.getString("ardublock.ui.new"));
newButton.addActionListener(new NewButtonListener(this));
JButton saveButton = new JButton(uiMessageBundle.getString("ardublock.ui.save"));
saveButton.addActionListener(new SaveButtonListener(this));
JButton saveAsButton = new JButton(uiMessageBundle.getString("ardublock.ui.saveAs"));
saveAsButton.addActionListener(new SaveAsButtonListener(this));
JButton openButton = new JButton(uiMessageBundle.getString("ardublock.ui.load"));
openButton.addActionListener(new OpenButtonListener(this));
JButton generateButton = new JButton(uiMessageBundle.getString("ardublock.ui.upload"));
generateButton.addActionListener(new GenerateCodeButtonListener(this, context));
JButton serialMonitorButton = new JButton(uiMessageBundle.getString("ardublock.ui.serialMonitor"));
serialMonitorButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
context.getEditor().handleSerial();
}
});
JButton saveImageButton = new JButton(uiMessageBundle.getString("ardublock.ui.saveImage"));
saveImageButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
Dimension size = workspace.getCanvasSize();
System.out.println("size: " + size);
BufferedImage bi = new BufferedImage(2560, 2560, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D)bi.createGraphics();
double theScaleFactor = (300d/72d);
g.scale(theScaleFactor,theScaleFactor);
workspace.getBlockCanvas().getPageAt(0).getJComponent().paint(g);
try{
final JFileChooser fc = new JFileChooser();
fc.setSelectedFile(new File("ardublock.png"));
int returnVal = fc.showSaveDialog(workspace.getBlockCanvas().getJComponent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
ImageIO.write(bi,"png",file);
}
} catch (Exception e1) {
} finally {
g.dispose();
}
}
});
//buttons.add(sb.getComponent());
buttons.add(newButton);
buttons.add(saveButton);
buttons.add(saveAsButton);
buttons.add(openButton);
buttons.add(generateButton);
buttons.add(serialMonitorButton);
JPanel bottomPanel = new JPanel();
JButton websiteButton = new JButton(uiMessageBundle.getString("ardublock.ui.website"));
websiteButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
URL url;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
url = new URL("http://ardublock.com");
desktop.browse(url.toURI());
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
JButton ArduROKwebsiteButton = new JButton("ArduBlock Updates");
ArduROKwebsiteButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
URL url;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
url = new URL("https://github.com/Aerospacesmith/ardublock/releases/latest");
desktop.browse(url.toURI());
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
JButton ROKwebsiteButton = new JButton("ROKduino Video Tutorials");
ROKwebsiteButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
URL url;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
url = new URL("https://rokenbokeducation.org/education/student-videos");
desktop.browse(url.toURI());
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
JLabel versionLabel = new JLabel("Installed Version: " + uiMessageBundle.getString("ardublock.ui.version"));
bottomPanel.add(saveImageButton);
//bottomPanel.add(websiteButton);
bottomPanel.add(ROKwebsiteButton);
bottomPanel.add(ArduROKwebsiteButton);
bottomPanel.add(versionLabel);
this.add(buttons, BorderLayout.NORTH);
this.add(bottomPanel, BorderLayout.SOUTH);
this.add(workspace, BorderLayout.CENTER);
}
public void doOpenArduBlockFile()
{
if (context.isWorkspaceChanged())
{
int optionValue = JOptionPane.showOptionDialog(this, uiMessageBundle.getString("message.content.open_unsaved"), uiMessageBundle.getString("message.title.question"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.YES_OPTION);
if (optionValue == JOptionPane.YES_OPTION)
{
doSaveArduBlockFile();
this.loadFile();
}
else
{
if (optionValue == JOptionPane.NO_OPTION)
{
this.loadFile();
}
}
}
else
{
this.loadFile();
}
this.setTitle(makeFrameTitle());
}
private void loadFile()
{
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION)
{
File savedFile = fileChooser.getSelectedFile();
if (!savedFile.exists())
{
JOptionPane.showOptionDialog(this, uiMessageBundle.getString("message.file_not_found"), uiMessageBundle.getString("message.title.error"), JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, null, JOptionPane.OK_OPTION);
return ;
}
try
{
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
context.loadArduBlockFile(savedFile);
context.setWorkspaceChanged(false);
}
catch (IOException e)
{
JOptionPane.showOptionDialog(this, uiMessageBundle.getString("message.file_not_found"), uiMessageBundle.getString("message.title.error"), JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE, null, null, JOptionPane.OK_OPTION);
e.printStackTrace();
}
finally
{
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
public void doSaveArduBlockFile()
{
if (!context.isWorkspaceChanged())
{
return ;
}
String saveString = getArduBlockString();
if (context.getSaveFilePath() == null)
{
chooseFileAndSave(saveString);
}
else
{
File saveFile = new File(context.getSaveFilePath());
writeFileAndUpdateFrame(saveString, saveFile);
}
}
public void doSaveAsArduBlockFile()
{
if (context.isWorkspaceEmpty())
{
return ;
}
String saveString = getArduBlockString();
chooseFileAndSave(saveString);
}
private void chooseFileAndSave(String ardublockString)
{
File saveFile = letUserChooseSaveFile();
saveFile = checkFileSuffix(saveFile);
if (saveFile == null)
{
return ;
}
if (saveFile.exists() && !askUserOverwriteExistedFile())
{
return ;
}
writeFileAndUpdateFrame(ardublockString, saveFile);
}
private String getArduBlockString()
{
WorkspaceController workspaceController = context.getWorkspaceController();
return workspaceController.getSaveString();
}
private void writeFileAndUpdateFrame(String ardublockString, File saveFile)
{
try
{
saveArduBlockToFile(ardublockString, saveFile);
context.setWorkspaceChanged(false);
this.setTitle(this.makeFrameTitle());
}
catch (IOException e)
{
e.printStackTrace();
}
}
private File letUserChooseSaveFile()
{
int chooseResult;
chooseResult = fileChooser.showSaveDialog(this);
if (chooseResult == JFileChooser.APPROVE_OPTION)
{
return fileChooser.getSelectedFile();
}
return null;
}
private boolean askUserOverwriteExistedFile()
{
int optionValue = JOptionPane.showOptionDialog(this, uiMessageBundle.getString("message.content.overwrite"), uiMessageBundle.getString("message.title.question"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.YES_OPTION);
return (optionValue == JOptionPane.YES_OPTION);
}
private void saveArduBlockToFile(String ardublockString, File saveFile) throws IOException
{
context.saveArduBlockFile(saveFile, ardublockString);
context.setSaveFileName(saveFile.getName());
context.setSaveFilePath(saveFile.getAbsolutePath());
}
public void doNewArduBlockFile()
{
if (context.isWorkspaceChanged())
{
int optionValue = JOptionPane.showOptionDialog(this, uiMessageBundle.getString("message.question.newfile_on_workspace_changed"), uiMessageBundle.getString("message.title.question"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, JOptionPane.YES_OPTION);
if (optionValue != JOptionPane.YES_OPTION)
{
return ;
}
}
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
context.resetWorksapce();
context.setWorkspaceChanged(false);
this.setTitle(this.makeFrameTitle());
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
private File checkFileSuffix(File saveFile)
{
String filePath = saveFile.getAbsolutePath();
if (filePath.endsWith(".abp"))
{
return saveFile;
}
else
{
return new File(filePath + ".abp");
}
}
}
| Aerospacesmith/ardublock | src/main/java/com/ardublock/ui/OpenblocksFrame.java | Java | gpl-3.0 | 12,843 |
/*
$License:
Copyright (C) 2011-2012 InvenSense Corporation, All Rights Reserved.
See included License.txt for License information.
$
*/
/*******************************************************************************
*
* $Id:$
*
******************************************************************************/
/**
* @defgroup Start_Manager start_manager
* @brief Motion Library - Start Manager
* Start Manager
*
* @{
* @file start_manager.c
* @brief This handles all the callbacks when inv_start_mpl() is called.
*/
#include <string.h>
#include "log.h"
#include "start_manager.h"
typedef inv_error_t (*inv_start_cb_func) ();
struct inv_start_cb_t {
int num_cb;
inv_start_cb_func start_cb[INV_MAX_START_CB];
};
static struct inv_start_cb_t inv_start_cb;
/** Initilize the start manager. Typically called by inv_start_mpl();
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_init_start_manager (void) {
memset (&inv_start_cb, 0, sizeof (inv_start_cb) );
return INV_SUCCESS;
}
/** Removes a callback from start notification
* @param[in] start_cb function to remove from start notification
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_unregister_mpl_start_notification (inv_error_t (*start_cb) (void) ) {
int kk;
for (kk = 0; kk < inv_start_cb.num_cb; ++kk) {
if (inv_start_cb.start_cb[kk] == start_cb) {
// Found the match
if (kk != (inv_start_cb.num_cb - 1) ) {
memmove (&inv_start_cb.start_cb[kk],
&inv_start_cb.start_cb[kk + 1],
(inv_start_cb.num_cb - kk - 1) *sizeof (inv_start_cb_func) );
}
inv_start_cb.num_cb--;
return INV_SUCCESS;
}
}
return INV_ERROR_INVALID_PARAMETER;
}
/** Register a callback to receive when inv_start_mpl() is called.
* @param[in] start_cb Function callback that will be called when inv_start_mpl() is
* called.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_register_mpl_start_notification (inv_error_t (*start_cb) (void) ) {
if (inv_start_cb.num_cb >= INV_MAX_START_CB) {
return INV_ERROR_INVALID_PARAMETER;
}
inv_start_cb.start_cb[inv_start_cb.num_cb] = start_cb;
inv_start_cb.num_cb++;
return INV_SUCCESS;
}
/** Callback all the functions that want to be notified when inv_start_mpl() was
* called.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_execute_mpl_start_notification (void) {
inv_error_t result, first_error;
int kk;
first_error = INV_SUCCESS;
for (kk = 0; kk < inv_start_cb.num_cb; ++kk) {
result = inv_start_cb.start_cb[kk]();
if (result && (first_error == INV_SUCCESS) ) {
first_error = result;
}
}
return first_error;
}
/**
* @}
*/
| imran27/myfiles | motion_driver_6.12/msp430/eMD-6.0/core/mllite/start_manager.c | C | gpl-3.0 | 2,903 |
/* ========================================================================
* Pure Mask JS: puremask.js v0.1
* http://romulobrasil.com
* Copyright (c) 2014 Rômulo Brasil
* ========================================================================
*/
'use strict';
var PureMask = function() {
return {
format : function(element, placeholder) {
var el = document.querySelector(element);
var maskForm = el.dataset.mask;
el.maxLength = maskForm.length;
var e = el.value.length;
if(placeholder === true) {
el.placeholder = maskForm;
}
el.addEventListener('keydown', function (e){
if (e.keyCode === 8 || e.keyCode === 46) {
} else {
formato(maskForm);
}
});
function formato(mask) {
var text = '';
var data = el.value;
var c, m, i, x;
for (i = 0, x = 1; x && i < mask.length; ++i) {
c = data.charAt(i);
m = mask.charAt(i);
switch (mask.charAt(i)) {
case '#' : if (/\d/.test(c)) {text += c;} else {x = 0;} break;
case 'A' : if (/[a-z]/i.test(c)) {text += c;} else {x = 0;} break;
case 'N' : if (/[a-z0-9]/i.test(c)) {text += c;} else {x = 0;} break;
case 'X' : text += c; break;
default : text += m; break;
}
}
el.value = text;
}
}
};
}(); | adrianomargarin/curso-js-vendabem | cursojs/static/aulas/js/puremask.js | JavaScript | gpl-3.0 | 1,799 |
#include "common_header.h"
namespace {
using ArrayType = std::vector<std::string_view>;
/**
* @reference Program to check if two strings are same or not
* https://www.geeksforgeeks.org/program-to-check-if-two-strings-are-same-or-not/
*/
/** Check if two strings are same ignoring their cases
*
* @reference https://www.geeksforgeeks.org/check-if-two-strings-are-same-ignoring-their-cases/
*/
inline auto
CaseInsensitiveCompare(const std::string_view lhs, const std::string_view rhs) {
return std::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend(),
[](const auto a, const auto b) {
return std::tolower(a) == std::tolower(b);
});
}
/**
* @reference Check if One String Swap Can Make Strings Equal
* https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/
*
* You are given two strings s1 and s2 of equal length. A string swap is an operation
* where you choose two indices in a string (not necessarily different) and swap the
* characters at these indices. Return true if it is possible to make both strings
* equal by performing at most one string swap on exactly one of the strings. Otherwise,
* return false.
*/
constexpr auto
EqualAfterOneSwap(const std::string_view one, const std::string_view another) {
if (one.size() != another.size()) {
return false;
}
int diffs[2] = {};
int diff_count = 0;
for (std::size_t i = 0; i < one.size(); ++i) {
if (one[i] != another[i]) {
if (diff_count == 2) {
return false;
}
diffs[diff_count++] = i;
}
}
return diff_count == 0 or
(diff_count == 2 and
one[diffs[0]] == another[diffs[1]] and
one[diffs[1]] == another[diffs[0]]);
}
/**
* @reference Buddy Strings
* https://leetcode.com/problems/buddy-strings/
*
* Given two strings s and goal, return true if you can swap two letters in s so the
* result is equal to goal, otherwise, return false. Swapping letters is defined as
* taking two indices i and j (0-indexed) such that i != j and swapping the characters
* at s[i] and s[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
* s and goal consist of lowercase letters.
*/
constexpr auto
EqualAfterOneSwapNoSameIndices(const std::string_view one,
const std::string_view another) {
if (one.size() != another.size()) {
return false;
}
int diffs[2] = {};
int diff_count = 0;
int counts[26] = {};
for (std::size_t i = 0; i < one.size(); ++i) {
if (one[i] != another[i]) {
if (diff_count == 2) {
return false;
}
diffs[diff_count++] = i;
}
++counts[one[i] - 'a'];
}
if (diff_count == 0) {
for (const auto c : counts) {
if (c > 1) {
return true;
}
}
return false;
}
return diff_count == 2 and
one[diffs[0]] == another[diffs[1]] and
one[diffs[1]] == another[diffs[0]];
}
/**
* @reference Check If Two String Arrays are Equivalent
* https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/
*
* Given two string arrays word1 and word2, return true if the two arrays represent the
* same string, and false otherwise.
* A string is represented by an array if the array elements concatenated in order forms
* the string.
* word1[i] and word2[i] consist of lowercase letters.
*/
auto ArrayStringsAreEqual(const ArrayType &word1, const ArrayType &word2) {
std::size_t w_i = 0, w_j = 0;
std::size_t c_m = 0, c_n = 0; // char pointers
while (w_i < word1.size() and w_j < word2.size()) {
if (word1[w_i][c_m++] != word2[w_j][c_n++]) {
return false;
}
if (c_m >= word1[w_i].size()) {
++w_i;
c_m = 0;
}
if (c_n >= word2[w_j].size()) {
++w_j;
c_n = 0;
}
}
return w_i == word1.size() and w_j == word2.size();
}
}//namespace
THE_BENCHMARK(CaseInsensitiveCompare, "Geeks", "geeks");
SIMPLE_TEST(CaseInsensitiveCompare, TestSAMPLE1, true, "Geeks", "geeks");
SIMPLE_TEST(CaseInsensitiveCompare, TestSAMPLE2, false, "Geek", "geeksforgeeks");
THE_BENCHMARK(EqualAfterOneSwap, "bank", "kanb");
SIMPLE_TEST(EqualAfterOneSwap, TestSAMPLE1, true, "bank", "kanb");
SIMPLE_TEST(EqualAfterOneSwap, TestSAMPLE2, false, "attack", "defend");
SIMPLE_TEST(EqualAfterOneSwap, TestSAMPLE3, true, "kelb", "kelb");
SIMPLE_TEST(EqualAfterOneSwap, TestSAMPLE4, false, "abcd", "dcba");
THE_BENCHMARK(EqualAfterOneSwapNoSameIndices, "bank", "kanb");
SIMPLE_TEST(EqualAfterOneSwapNoSameIndices, TestSAMPLE1, true, "bank", "kanb");
SIMPLE_TEST(EqualAfterOneSwapNoSameIndices, TestSAMPLE2, false, "attack", "defend");
SIMPLE_TEST(EqualAfterOneSwapNoSameIndices, TestSAMPLE3, true, "ab", "ba");
SIMPLE_TEST(EqualAfterOneSwapNoSameIndices, TestSAMPLE4, false, "abcd", "dcba");
SIMPLE_TEST(EqualAfterOneSwapNoSameIndices, TestSAMPLE5, false, "ab", "ab");
SIMPLE_TEST(EqualAfterOneSwapNoSameIndices, TestSAMPLE6, true, "aa", "aa");
SIMPLE_TEST(EqualAfterOneSwapNoSameIndices, TestSAMPLE7, true, "aaaaaaabc",
"aaaaaaacb");
const ArrayType SAMPLE1L = {"ab", "c"};
const ArrayType SAMPLE1R = {"a", "bc"};
const ArrayType SAMPLE2R = {"bc", "a"};
const ArrayType SAMPLE3R = {"a", "cb"};
const ArrayType SAMPLE4L = {"abc", "d", "defg"};
const ArrayType SAMPLE4R = {"abcddefg"};
THE_BENCHMARK(ArrayStringsAreEqual, SAMPLE1L, SAMPLE1R);
SIMPLE_TEST(ArrayStringsAreEqual, TestSAMPLE1, true, SAMPLE1L, SAMPLE1R);
SIMPLE_TEST(ArrayStringsAreEqual, TestSAMPLE2, false, SAMPLE1L, SAMPLE2R);
SIMPLE_TEST(ArrayStringsAreEqual, TestSAMPLE3, false, SAMPLE1L, SAMPLE3R);
SIMPLE_TEST(ArrayStringsAreEqual, TestSAMPLE4, true, SAMPLE4L, SAMPLE4R);
| yyang-even/algorithms | text/string_comparison.cpp | C++ | gpl-3.0 | 5,956 |
/**
* RuleSet Library
* Copyright (C) 2013 Khaled Bakhit
*
* This file is part of RuleSet Library.
*
* RuleSet Library 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 of the License, or
* (at your option) any later version.
*
* RuleSet Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with RuleSet Library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.khaledbakhit.api.rslib.parsers;
import com.khaledbakhit.api.rslib.interfaces.Parser;
import com.khaledbakhit.api.rslib.LaunchSetup;
import com.khaledbakhit.api.rslib.ruleset.RuleSet;
import java.util.LinkedList;
/**
* RuleSetParser parses input RuleSet files.
* @author Khaled Bakhit
* @since 4.0
* @version 18/08/2013
*/
public abstract class RuleSetParser implements Parser<LinkedList<RuleSet>>
{
/**
* LaunchSetup Object contains input configuration.
*/
protected LaunchSetup sp;
/**
* The default RuleSet parser defined by library.
*/
private static RuleSetParser DEFAULT_PARSER;
/**
* RuleSetParser constructor.
* @param sp LaunchSetup Object containing input configuration.
*/
public RuleSetParser(LaunchSetup sp)
{
this.sp= sp;
}
/**
* Get the default RuleSetParser defined by the library.
* @param sp LaunchSetup Object containing input configuration.
* @return Default RuleSetParser Object defined by library.
*/
public static RuleSetParser getDefaultRuleSetParser(LaunchSetup sp)
{
if(DEFAULT_PARSER!=null)
return DEFAULT_PARSER;
DEFAULT_PARSER= new DefaultRuleSetParser(sp);
return DEFAULT_PARSER;
}
/**
* Set the default RuleSetParser Object.
* @param parser RuleSetParser Object to consider default.
*/
public static void setDefaultMetricsParser(RuleSetParser parser)
{
DEFAULT_PARSER= parser;
}
}
| kbakhit/RuleSet_Library | src/com/khaledbakhit/api/rslib/parsers/RuleSetParser.java | Java | gpl-3.0 | 2,301 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MyConnection
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Model m;
public MainWindow()
{
InitializeComponent();
m= new Model();
this.DataContext = m;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
phonesGrid.ItemsSource = m.PFData1;
}
private void Window_Closed(object sender, EventArgs e)
{
}
private void updateButton_Click(object sender, RoutedEventArgs e)
{
}
private void deleteButton_Click(object sender, RoutedEventArgs e)
{
}
}
}
| p21816/Dasha | IT Step/ADOnet/MyConnection/MainWindow.xaml.cs | C# | gpl-3.0 | 1,189 |
/*
Copyright 2011 MCForge
Author: fenderrock87
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.opensource.org/licenses/ecl2.php
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
namespace MCForge
{
public static class Extensions
{
public static string Truncate(this string source, int maxLength)
{
if (source.Length > maxLength)
{
source = source.Substring(0, maxLength);
}
return source;
}
public static byte[] GZip(this byte[] bytes)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true);
gs.Write(bytes, 0, bytes.Length);
gs.Close();
ms.Position = 0;
bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
ms.Close();
ms.Dispose();
}
return bytes;
}
public static byte[] Decompress(this byte[] gzip)
{
// Create a GZIP stream with decompression mode.
// ... Then create a buffer and write into while reading from the GZIP stream.
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
public static string[] Slice(this string[] str, int offset)
{
return str.Slice(offset, 0);
}
public static string[] Slice(this string[] str, int offset, int length)
{
IEnumerable<string> tmp = str.ToList();
if (offset > 0)
{
tmp = str.Skip(offset);
}
else throw new NotImplementedException("This function only supports positive integers for offset");
if(length > 0)
{
tmp = tmp.Take(length);
}
else if (length == 0)
{
// Do nothing
}
else throw new NotImplementedException("This function only supports non-negative integers for length");
return tmp.ToArray();
}
public static string Capitalize(this string str)
{
return str.Substring(0, 1).ToUpper() + str.Remove(0, 1);
}
public static string Concatenate<T>(this List<T> list, string separator)
{
string str = "";
if (list.Count > 0)
{
foreach (T obj in list)
str += separator + obj.ToString();
str = str.Remove(0, separator.Length);
}
return str;
}
}
}
| Cazzar/MCaznowl-Lava | Util/Extensions.cs | C# | gpl-3.0 | 3,889 |
whatcolorisit
=============
••• What color is it? •••
••• Processing.js code to modulate colors according to the time of day
A clock that changes colors progressively with the passing of time (en)
Um relógio que muda de cor progressivamente com o passar do tempo (pt)
Version: 0.1 beta (.js)
Release date of this version: December 29th 2014
Acknowledgements:
This software is based on What color is it, a project by http://scn9a.org/
This version implements a different algorithm to translate time into colors
The original project can be found here: http://whatcolourisit.scn9a.org/
Developed by: SUMBIOUN [at http://sumbioun.org/]
Programmer: pedro veneroso [at http://pedroveneroso.com/]
Get in contact at people@sumbioun.org
License: GNU GPL v3.0
Read the license at:
http://sumbioun.org/licenses/gnu-v3_0.txt
Indie software sketch developed in December, 2014
Belo Horizonte, Brasil
at http://whatcolorisit.sumbioun.com/
Free to copy, modify and distribute.
| sumbioun/whatcolorisit | README.md | Markdown | gpl-3.0 | 1,067 |
package org.coinvent;
public class HdtpRequests {
public enum HdtpRequest
{ NEW, NEXT, CLOSE, NOACTION}
public enum ReadType
{READ, NOREAD}
public enum ActiveType
{PENDING, OPEN, CLOSED}
}
| coinvent/coinvent | simple-server/src/org/coinvent/HdtpRequests.java | Java | gpl-3.0 | 209 |
## What's new in version 0-2-1?
### Bug Fixes
* Fixed setup.py and import paths
### Contributors
* Simon Hilpert
| znes/renpass_gis | whatsnew/v0-2-1.md | Markdown | gpl-3.0 | 119 |
/*
* simple 2d SOM
* TODO: implementation could be much better..
* many passes for SOM, probability distribution modification
* (using histrogram modification to wanted distribution)
* to correct SOMs f^2/3 or f^/1/3 error in probability vs
* number of representing vectors in SOM.
* learning should happen in two/many passes etc. (Haykin's book)
* etc. etc.
*/
#ifndef SOM_h
#define SOM_h
#include <vector>
#include <string>
#include <exception>
#include <stdexcept>
namespace whiteice
{
template <typename T>
class SOM
{
public:
// creates 2d som lattice with given height, width and data dimension
// width and height must be powers of 2, otherwise exception is throwed
SOM(unsigned int width = 2, unsigned int height = 2, unsigned int dimension = 1)
throw(std::logic_error);
virtual ~SOM();
// run SOM with given data
bool learn(const std::vector< std::vector<T> >& data) throw();
// returns distance in feature space
T som_distance(const std::vector<T>& v,
const std::vector<T>& w) const throw();
// returns index to vector representing given vector
unsigned int representing_vector(const std::vector<T>& v) const throw();
// returns som vector for given vector index
std::vector<T>& operator[](unsigned int index) const throw(std::out_of_range);
// randomizes som values
bool randomize() const throw();
// loads SOM data from file
bool load(const std::string& filename) throw();
// saves SOM data to file
bool save(const std::string& filename) const throw();
// returns number of som vectors
unsigned int size() const throw(){ return som.size(); }
private:
// finds closest som representation
// vector index for given vector
unsigned int find_closest(const std::vector<T>& data)
const throw();
// normalizes length of the vector to 1
// or keeps it zero if it's zero
void normalize_length(std::vector<T>& v) const throw();
// calculates squared distance between vectors in som lattice
T som_sqr_distance(unsigned int index1,
unsigned int index2) const throw();
// calculates |x - y|^2
T vector_sqr_distance(const std::vector<T>& x,
const std::vector<T>& y) const throw() ;
// moves all vectors in winners neighbourhood
// towards data vector
bool move_towards(unsigned int winner,
const std::vector<T>& data) throw();
// finds closests som representation
// vector index for given vector
unsigned int find_closests(const std::vector<T>& data)
const throw();
// open()s graphic display/window
bool open_visualization() throw();
bool close_visualization() throw();
bool draw_visualization() throw();
std::vector< std::vector<T> > som;
std::vector<T> umatrix;
unsigned int wbits; // 2^wbits = width
unsigned int width, height;
unsigned int dimension;
float initial_learning_rate;
float initial_variance_distance;
float target_variance_distance;
float learning_rate;
float variance_distance;
bool graphics_on;
bool show_visualization;
bool show_eta;
};
}
#include "SOM.cpp"
#endif
| cslr/dinrhiw2 | src/neuralnetwork/SOM/old/SOM.h | C | gpl-3.0 | 3,474 |
package org.epics.ca.examples;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import org.epics.ca.*;
import org.epics.ca.data.*;
public class Example
{
public static void main( String[] args )
{
// Note:
// To run these tests the EpicsChannelAccessTestServer should be started and running
// in the local network environment.
// Configure the CA library context and start it.
final Properties properties = new Properties();
// Note: no properties need to be set if the SoftIOC and the library are running on the same network.
try ( Context context = new Context( properties ) )
{
// 1.0 Create a Channel
System.out.print( "Creating a DOUBLE channel... " );
final Channel<Double> dblCh = context.createChannel( "adc01", Double.class );
System.out.println( "OK." );
// 2.0 Add a ConnectionListener
System.out.print( "Adding a connection listener... " );
final Listener connectionListener = dblCh.addConnectionListener (( channel, state ) -> System.out.println (channel.getName () + " is connected? " + state));
System.out.println( "OK." );
// 2.1 Remove a ConnectionListener.
// Note: this is achieved automatically if the listener is created using a try-catch-resources construct.
System.out.print( "Removing a connection listener... " );
connectionListener.close();
System.out.println( "OK." );
// 2.2 Add an AccessRightsListener
System.out.print( "Adding an access rights listener... " );
final Listener accessRightsListener = dblCh.addAccessRightListener (( channel, rights ) -> System.out.println (channel.getName () + " is rights? " + rights));
System.out.println( "OK." );
// 2.3 Remove an AccessRightsListener.
// Note: this is achieved automatically if the listener is created using a try-catch-resources construct.
System.out.print( "Removing an access rights listener... " );
accessRightsListener.close();
System.out.println( "OK." );
// 3.0 Connect asynchronously to the channel.
// Wait until connected or TimeoutException
System.out.print( "Connecting asynchronously... " );
dblCh.connectAsync().get();
System.out.println( "OK." );
// 4.0 Asynchronously put a DOUBLE value to the channel. Don't wait for confirmation.
System.out.print( "Putting DOUBLE value asynchronously, without waiting for completion... " );
dblCh.putNoWait( 3.11 );
System.out.println( "OK." );
// 4.1 Asynchronously put a floating point value to the channel. Wait for confirmation.
System.out.print( "Putting DOUBLE value asynchronously, then waiting for completion... " );
final CompletableFuture<Status> fp = dblCh.putAsync( 12.8 );
System.out.println( "OK. Data returned: '" + fp.get() + "'." );
// 5.0 Asynchronously get a DOUBLE from the channel.
System.out.print( "Getting DOUBLE value asynchronously, then waiting for completion... " );
final CompletableFuture<Double> fd = dblCh.getAsync();
System.out.println( "OK. Data returned: '" + fd.get() + "'." );
// 5.1 Asynchronously get a DOUBLE with ALARM metadata.
System.out.print( "Getting DOUBLE value asynchronously with ALARM metadata, then waiting for completion... " );
final CompletableFuture<Alarm<Double>> fal = dblCh.getAsync( Alarm.class );
final Alarm<Double> dal = fal.get();
System.out.println( "OK. Data returned: '" + dal.getValue() + ", " + dal.getAlarmStatus() + ", " + dal.getAlarmSeverity () + "'." );
// 5.2 Asynchronously get a DOUBLE with TIMESTAMP metadata.
System.out.print( "Getting DOUBLE value asynchronously with TIMESTAMP metadata, then waiting for completion... " );
final CompletableFuture<Timestamped<Double>> fts = dblCh.getAsync( Timestamped.class );
final Timestamped<Double> dts = fts.get();
System.out.println( "OK. Data returned: '" + dts.getValue() + ", " + dts.getAlarmStatus() + ", " + dts.getAlarmSeverity() + ", " + new Date( dts.getMillis ()) + "'." );
// 5.3 Asynchronously get a DOUBLE with GRAPHIC metadata.
System.out.print( "Getting DOUBLE value asynchronously with GRAPHIC metadata, then waiting for completion... " );
final CompletableFuture<Graphic<Double, Double>> fgr = dblCh.getAsync( Graphic.class );
final Graphic<Double, Double> dgr = fgr.get();
System.out.println( "OK. Data returned: '" + dgr.getValue() + ", " + dgr.getAlarmStatus() + ", " + dgr.getAlarmSeverity() + ", " + dgr.getLowerDisplay() + ", " + dgr.getUpperDisplay() + "'." );
// 5.4 Asynchronously get a DOUBLE with CONTROL metadata.
System.out.print( "Getting DOUBLE value asynchronously with CONTROL metadata, then waiting for completion... " );
final CompletableFuture<Control<Double, Double>> fc = dblCh.getAsync( Control.class );
final Control<Double, Double> dc = fc.get();
System.out.println( "OK. Data returned: '" + dc.getValue () + ", " + dc.getAlarmStatus() + ", " + dc.getAlarmSeverity() + ", " + dc.getLowerControl() + ", " + dc.getUpperControl() + "'." );
// 6.0 Asynchronously get a DOUBLE ARRAY from a newly created channel.
System.out.print( "Getting DOUBLE ARRAY value asynchronously, then waiting for completion... " );
final Channel<double[]> dblArrCh = context.createChannel( "adc01", double[].class).connectAsync().get();
final CompletableFuture<double[]> fda = dblArrCh.getAsync();
System.out.println( "OK. Data returned: '" + Arrays.toString( fda.get()) + "'." );
// 6.1 Asynchronously get a DOUBLE ARRAY with GRAPHIC metadata.
System.out.print( "Getting DOUBLE ARRAY value asynchronously, with GRAPHIC metadata, then waiting for completion... " );
final CompletableFuture<Graphic<double[], Double>> fdagr = dblArrCh.getAsync( Graphic.class );
final Graphic<double[], Double> dagr = fdagr.get();
System.out.println( "OK. Data returned: '" + Arrays.toString( dagr.getValue()) + ", " + dagr.getAlarmStatus() + ", " + dagr.getAlarmSeverity() + ", " + dagr.getLowerDisplay() + " " + dagr.getUpperDisplay() + "'." );
// 7.1 Asynchronously get a GRAPHIC ENUM from channel of underlying type 'DBR_Enum.type'.
System.out.print( "Getting GRAPHIC ENUM value asynchronously, then waiting for completion... " );
final Channel<Short> enumCh = context.createChannel( "enum", Short.class ).connectAsync().get();
final CompletableFuture<GraphicEnum> fge = enumCh.getAsync( GraphicEnum.class );
final GraphicEnum ge = fge.get();
System.out.println( "OK. Data returned: '" + ge.getValue() + ", " + Arrays.toString( ge.getLabels() ) + "'." );
// 7.2 Asynchronously get a GRAPHIC ENUM ARRAY from channel of underlying type 'DBR_Enum.type'.
System.out.print( "Getting GRAPHIC ENUM ARRAY value asynchronously, then waiting for completion... " );
final Channel<short[]> enumArrCh = context.createChannel( "enum", short[].class ).connectAsync().get();
final CompletableFuture<GraphicEnumArray> fgea = enumArrCh.getAsync( GraphicEnumArray.class );
final GraphicEnumArray gea = fgea.get();
System.out.println( "OK. Data returned: '" + Arrays.toString( gea.getValue() ) + ", " + Arrays.toString( gea.getLabels () ) + "'." );
// 8.0 Synchronously get a GRAPHIC ENUM from channel of underlying type 'DBR_Enum.type'.
System.out.print( "Getting GRAPHIC ENUM value synchronously, then waiting for completion... " );
final GraphicEnum ges = enumCh.get( GraphicEnum.class );
System.out.println( "OK. Data returned: '" + Arrays.toString( ges.getLabels() ) + "'." );
// 9.0 Asynchronously put a SHORT value to channel of underlying type 'DBR_Enum.type'. Don't wait for confirmation.
System.out.print( "Putting SHORT value asynchronously, without waiting for completion... " );
enumCh.putNoWait( (short) 99 );
System.out.println( "OK." );
// 10.0 Monitor a DOUBLE.
System.out.print( "Monitoring DOUBLE, waiting for notifications..." );
final Monitor<Double> mon = dblCh.addValueMonitor(x -> System.out.println( "OK. Data returned: '" + x + "'." ) );
// Sleep here to allow monitor information to be posted before moving on to other examples.
Thread.sleep(100);
// 10.1 Close a Monitor.
System.out.print( "Closing Monitor... " );
mon.close();
System.out.println( "OK." );
// 10.2 Monitor a DOUBLE with ALARM information.
System.out.print( "Monitoring DOUBLE, requesting ALARM information, waiting for notifications... " );
try ( final Monitor<Alarm<Double>> ignored = dblCh.addMonitor( Alarm.class, value -> {
if ( value != null )
{
System.out.println( "OK. Data returned: '" + value.getAlarmStatus() + ", " + value.getAlarmSeverity() + ", " + value.getValue () + "'." );
}
} ) )
{
// Sleep here to allow monitor information to be posted before moving on to other examples.
Thread.sleep(100);
}
// Sleep here to allow monitor information to be posted before moving on to other examples.
Thread.sleep(100);
// 10.3 Monitor a DOUBLE with TIMESTAMP information.
System.out.print( "Monitoring DOUBLE, requesting TIMESTAMP information, waiting for notifications... " );
try ( final Monitor<Timestamped<Double>> ignored = dblCh.addMonitor( Timestamped.class, value -> {
if ( value != null )
{
System.out.println( "OK. Data returned: '" + value.getAlarmStatus() + ", " + value.getAlarmSeverity() + ", " + new Date (value.getMillis ()) + ", " + value.getValue () + "'." );
}
}
) )
{
// Sleep here to allow monitor information to be posted before moving on to other examples.
Thread.sleep(100);
}
// Sleep here to allow monitor information to be posted before moving on to other examples.
Thread.sleep(100);
// 11.0 Create a channel, asynchronously connect to it.
System.out.print( "Creating DOUBLE channel... " );
final Channel<Double> dblSyncCh = context.createChannel ("adc04", Double.class );
System.out.println( "OK." );
System.out.print( "Using connectAsync followed by ThenAccept... " );
dblSyncCh.connectAsync ().thenAccept( (chan) -> System.out.println( "OK. Channel: '" + chan.getName () + ", connection state: " + chan.getConnectionState() + "." ) );
// Sleep here to allow information to be posted before moving on to other examples.
Thread.sleep(100);
// 12.0 Create channels of mixed types and wait for them all to connect.
System.out.print( "Creating an INTEGER channel... " );
final Channel<Integer> intCh = context.createChannel("adc02", Integer.class );
System.out.println( "OK." );
System.out.print( "Creating a STRING channel... " );
final Channel<String> strCh = context.createChannel("adc03", String.class );
System.out.println( "OK." );
System.out.print( "Waiting for MULTIPLE channels of MIXED types to connect... " );
CompletableFuture<?> f = CompletableFuture.allOf( intCh.connectAsync (), strCh.connectAsync () ).thenAccept (( v ) -> System.out.println ( "OK: ALL channels of MIXED types connected." ) );
f.get();
// 13.0 Synchronously get a DOUBLE from the channel.
System.out.print( "Getting DOUBLE synchronously... " );
double dv = dblCh.get ();
System.out.println( "OK. Data returned: '" + dv + "'." );
// 13.1 Synchronously get a DOUBLE from the channel with ALARM information
System.out.print( "Getting DOUBLE synchronously with ALARM information... " );
final Alarm<Double> dval = dblCh.get( Alarm.class );
System.out.println( "OK. Data returned: '" + dval.getValue() + ", " + dval.getAlarmStatus() + ", " + dval.getAlarmSeverity() + "'." );
// 13.1 Synchronously get a DOUBLE from the channel with TIMESTAMP information
System.out.print( "Getting DOUBLE synchronously with TIMESTAMP information... " );
final Timestamped<Double> dvts = dblCh.get( Timestamped.class );
System.out.println( "OK. Data returned: '" + dvts.getValue() + ", " + dvts.getAlarmStatus() + ", " + dvts.getAlarmSeverity() + ", " + new Date( dvts.getMillis ()) + "'." );
// 14.0 Monnitor a DOUBLE using try-with-resourced``
System.out.print( "Monitoring DOUBLE using try-with-resources... " );
try ( final Monitor<Double> ignored = dblCh.addValueMonitor( v -> System.out.println( "OK. Data returned: '" + v + "'." ) ) )
{
// Sleep here to allow monitor information to be posted before moving on to other examples.
Thread.sleep(100);
}
System.out.println( "OK." );
// TODO
// In the future the library should probably introduce some way of checking that the
// monitor is closed, but currently the interface has nothing to support this.
}
catch( Exception ex )
{
System.out.println ( "\nThe example program FAILED, with the following exception: " + ex );
System.exit( -1 );
}
System.out.println( "\nThe example program SUCCEEDED, and ran to completion." );
}
}
| channelaccess/ca | src/main/java/org/epics/ca/examples/Example.java | Java | gpl-3.0 | 13,903 |
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[2];
atomic_int atom_0_r1_1;
atomic_int atom_1_r1_1;
void *t0(void *arg){
label_1:;
int v2_r1 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v3_r3 = v2_r1 ^ v2_r1;
int v4_r3 = v3_r3 + 1;
atomic_store_explicit(&vars[1], v4_r3, memory_order_seq_cst);
int v14 = (v2_r1 == 1);
atomic_store_explicit(&atom_0_r1_1, v14, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v6_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v8_r3 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v9_r4 = v8_r3 ^ v8_r3;
int v10_r4 = v9_r4 + 1;
atomic_store_explicit(&vars[0], v10_r4, memory_order_seq_cst);
int v15 = (v6_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v15, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[0], 0);
atomic_init(&vars[1], 0);
atomic_init(&atom_0_r1_1, 0);
atomic_init(&atom_1_r1_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v11 = atomic_load_explicit(&atom_0_r1_1, memory_order_seq_cst);
int v12 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v13_conj = v11 & v12;
if (v13_conj == 1) assert(0);
return 0;
}
| nidhugg/nidhugg | tests/litmus/C-tests/LB0029.c | C | gpl-3.0 | 1,521 |
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="paragraph">This a paragraph</p>
<script type="text/javascript" src="../jquery.min.js"></script>
<script type="text/javascript" src="3.js"></script>
</body>
</html> | Tech-engine/jquery-tutorials-series | 3/index.php | PHP | gpl-3.0 | 242 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="vi" sourcelanguage="en">
<context>
<name>Alert</name>
<message>
<source>Close (%1)</source>
<translation>Đóng lại (%1)</translation>
</message>
<message>
<source>Collapse</source>
<translation>Xổ xuống</translation>
</message>
<message>
<source>Expand</source>
<translation>Mở rộng</translation>
</message>
</context>
<context>
<name>AlertLayer</name>
<message>
<source>Dismiss Alert</source>
<translation>Bỏ qua cảnh báo</translation>
</message>
<message>
<source>Ctrl+D</source>
<translation>Ctrl+D</translation>
</message>
</context>
<context>
<name>DailyProgress</name>
<message numerus="yes">
<source>%L1% of %Ln minute(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<source>%L1% of %Ln word(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<source>%Ln word(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<source>%Ln minute(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message>
<source>0%</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DailyProgressDialog</name>
<message>
<source>Daily Progress</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Longest streak</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Current streak</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>N/A</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
</translation>
</message>
<message>
<source>%1 &ndash; %2</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DailyProgressLabel</name>
<message>
<source>%L1% of daily goal</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DictionaryDialog</name>
<message>
<source>Set Language</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Document</name>
<message>
<source>(Untitled %1)</source>
<translation type="unfinished">(Chưa đặt tiêu đề %1)</translation>
</message>
<message>
<source>%1 (Read-Only)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Sorry</source>
<translation>Rất tiếc</translation>
</message>
<message>
<source>Unable to save '%1'.</source>
<translation>Không thể lưu '%1'.</translation>
</message>
<message>
<source>Save File As</source>
<translation>Lưu tập tin thành</translation>
</message>
<message>
<source>Unable to overwrite '%1'.</source>
<translation>Không thể ghi đè lên '%1'.</translation>
</message>
<message>
<source>Rename File</source>
<translation>Đổi tên tập tin</translation>
</message>
<message>
<source>Unable to rename '%1'.</source>
<translation>Không thể đổi tên '%1'.</translation>
</message>
<message>
<source>Reload File?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Reload the file '%1' from disk?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All unsaved changes will be lost.</source>
<translation>Tất cả các thay đổi chưa lưu sẽ bị mất.</translation>
</message>
<message>
<source>Reload</source>
<translation>Tải lại</translation>
</message>
<message>
<source>Untitled %1</source>
<translation type="unfinished">Chưa đặt tiêu đề %1</translation>
</message>
<message>
<source>Question</source>
<translation>Câu hỏi</translation>
</message>
<message>
<source>Saving as plain text will discard all formatting. Discard formatting?</source>
<translation>Lưu dưới dạng văn bản thông thường sẽ bỏ qua tất cả các chỉnh sửa về hiển thị. Bỏ qua toàn bộ các hiển thị?</translation>
</message>
</context>
<context>
<name>DocumentWatcher</name>
<message>
<source>File Changed</source>
<translation>Đã thay đổi tập tin</translation>
</message>
<message>
<source>The file '%1' was changed by another program.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Do you want to reload the file?</source>
<translation>Bạn có muốn tải lại tập tin?</translation>
</message>
<message>
<source>Reload</source>
<translation>Tải lại</translation>
</message>
<message>
<source>Ignore</source>
<translation>Bỏ qua</translation>
</message>
<message>
<source>File Deleted</source>
<translation>Đã xóa tập tin</translation>
</message>
<message>
<source>The file %1 was deleted by another program.</source>
<translation>Tập tin %1 đã bị xóa bởi một ứng dụng khác.</translation>
</message>
<message>
<source>Do you want to save or close the file?</source>
<translation>Bạn có muốn lưu hoặc đóng lại tập tin này?</translation>
</message>
</context>
<context>
<name>DocxReader</name>
<message>
<source>Unable to open archive.</source>
<translation type="unfinished">Không thể mở phần lưu trữ.</translation>
</message>
</context>
<context>
<name>FindDialog</name>
<message>
<source>Search for:</source>
<translation>Tìm kiếm cho:</translation>
</message>
<message>
<source>Replace with:</source>
<translation>Thay thế với:</translation>
</message>
<message>
<source>Ignore case</source>
<translation>Bỏ qua trường hợp chữ in hoa</translation>
</message>
<message>
<source>Whole words only</source>
<translation>Chỉ toàn bộ các từ này</translation>
</message>
<message>
<source>Regular expressions</source>
<translation>Phép toán thông thường</translation>
</message>
<message>
<source>Search up</source>
<translation>Tìm kiếm phía trên</translation>
</message>
<message>
<source>Search down</source>
<translation>Tìm kiếm phía dưới</translation>
</message>
<message>
<source>&Find</source>
<translation>&Tìm kiếm</translation>
</message>
<message>
<source>&Replace</source>
<translation>Th&ay thế</translation>
</message>
<message>
<source>Replace &All</source>
<translation>Tha&y thế tất cả</translation>
</message>
<message>
<source>Find</source>
<translation>Tìm</translation>
</message>
<message>
<source>Replace</source>
<translation>Thay thế</translation>
</message>
<message numerus="yes">
<source>Replace %n instance(s)?</source>
<translation>
<numerusform>Thay thế %n tiến trình?</numerusform>
</translation>
</message>
<message>
<source>Question</source>
<translation>Câu hỏi</translation>
</message>
<message>
<source>Sorry</source>
<translation>Rất tiếc</translation>
</message>
<message>
<source>Phrase not found.</source>
<translation>Không tìm thấy cụm từ.</translation>
</message>
</context>
<context>
<name>FormatManager</name>
<message>
<source>OpenDocument Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Office Open XML</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rich Text Format</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Plain Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All Supported Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>OpenDocument Flat XML</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Highlighter</name>
<message>
<source>Add</source>
<translation>Thêm</translation>
</message>
<message>
<source>Check Spelling...</source>
<translation>Kiểm tra lỗi chính tả...</translation>
</message>
<message>
<source>(No suggestions found)</source>
<translation>(Không tìm thấy lời đề nghị nào)</translation>
</message>
</context>
<context>
<name>ImageButton</name>
<message>
<source>Open Image</source>
<translation>Mở hình ảnh</translation>
</message>
<message>
<source>Images(%1)</source>
<translation>Hình ảnh(%1)</translation>
</message>
</context>
<context>
<name>LocaleDialog</name>
<message>
<source>Select application language:</source>
<translation>Chọn ngôn ngữ của ứng dụng:</translation>
</message>
<message>
<source><System Language></source>
<translation><Ngôn ngữ Hệ thống></translation>
</message>
<message>
<source>Note</source>
<translation>Ghi chú</translation>
</message>
<message>
<source>Please restart this application for the change in language to take effect.</source>
<translation>Xin vui lòng khởi động lại ứng dụng này để áp dụng thao tác thay đổi ngôn ngữ.</translation>
</message>
</context>
<context>
<name>OdtReader</name>
<message>
<source>Unable to open archive.</source>
<translation type="unfinished">Không thể mở phần lưu trữ.</translation>
</message>
</context>
<context>
<name>PreferencesDialog</name>
<message>
<source>Preferences</source>
<translation>Tùy biến</translation>
</message>
<message>
<source>General</source>
<translation>Tổng quan</translation>
</message>
<message>
<source>Statistics</source>
<translation>Thống kê</translation>
</message>
<message>
<source>Toolbar</source>
<translation>Thanh công cụ</translation>
</message>
<message>
<source>Spell Checking</source>
<translation>Đang kiểm tra lỗi chính tả</translation>
</message>
<message>
<source>Select Dictionary</source>
<translation>Chọn Từ Điển</translation>
</message>
<message>
<source>Sorry</source>
<translation>Rất tiếc</translation>
</message>
<message>
<source>Unable to open archive.</source>
<translation>Không thể mở phần lưu trữ.</translation>
</message>
<message>
<source>The archive does not contain a usable dictionary.</source>
<translation>Phần lưu trữ không chứa từ điển nào có thể sử dụng được.</translation>
</message>
<message>
<source>Question</source>
<translation>Câu hỏi</translation>
</message>
<message>
<source>Shortcuts</source>
<translation>Phím tắt</translation>
</message>
<message>
<source>One or more shortcuts conflict. Do you wish to proceed?</source>
<translation>Một hoặc nhiều phím tắt hơn bị xung đột. Bạn có muốn tiếp tục?</translation>
</message>
<message>
<source>The dictionary "%1" already exists. Do you want to replace it?</source>
<translation>Từ điển "%1" đã có sẵn. Bạn có muốn thay thế từ điển này không?</translation>
</message>
<message>
<source>Daily Goal</source>
<translation>Mục tiêu mỗi ngày</translation>
</message>
<message>
<source>None</source>
<translation>Không</translation>
</message>
<message>
<source>Minutes:</source>
<translation>Phút:</translation>
</message>
<message>
<source>Words:</source>
<translation>Từ:</translation>
</message>
<message>
<source>Editing</source>
<translation>Đang chỉnh sửa</translation>
</message>
<message>
<source>Always vertically center</source>
<translation>Vị trí luôn thẳng đứng ở giữa</translation>
</message>
<message>
<source>Block insertion cursor</source>
<translation>Khóa việc chèn con trỏ</translation>
</message>
<message>
<source>Smooth fonts</source>
<translation>Kiểu chữ dễ nhìn</translation>
</message>
<message>
<source>Typewriter sounds</source>
<translation>Âm thanh đánh máy khi gõ</translation>
</message>
<message>
<source>Smart quotes:</source>
<translation>Trích dẫn thông minh:</translation>
</message>
<message>
<source>Double</source>
<translation>Gấp đôi</translation>
</message>
<message>
<source>Single</source>
<translation>Đơn lẻ</translation>
</message>
<message>
<source>Scenes</source>
<translation>Khung cảnh</translation>
</message>
<message>
<source>Divider:</source>
<translation>Người chia cắt:</translation>
</message>
<message>
<source>Saving</source>
<translation>Đang lưu</translation>
</message>
<message>
<source>Remember cursor position</source>
<translation>Nhớ vị trí trỏ chuột</translation>
</message>
<message>
<source>Word count</source>
<translation>Tổng số từ</translation>
</message>
<message>
<source>Page count</source>
<translation>Tổng số trang</translation>
</message>
<message>
<source>Paragraph count</source>
<translation>Tổng số đoạn văn</translation>
</message>
<message>
<source>Character count</source>
<translation>Tổng số ký tự</translation>
</message>
<message>
<source>Characters:</source>
<translation>Ký tự:</translation>
</message>
<message>
<source>Paragraphs:</source>
<translation>Đoạn văn:</translation>
</message>
<message>
<source>Word Count Algorithm</source>
<translation>Thuật toán tính toán tổng số chữ</translation>
</message>
<message>
<source>Reset daily progress for today to zero?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Write byte order mark in plain text files</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default format:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Reset Today</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>History</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remember history</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show streaks</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Minimum progress for streaks:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Detect word boundaries</source>
<translation>Phát hiện việc bo tròn các chữ</translation>
</message>
<message>
<source>Divide character count by six</source>
<translation>Chia các ký tự bởi nhóm có số lượng sáu</translation>
</message>
<message>
<source>Count each letter as a word</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page Count Algorithm</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style</source>
<translation>Giao diện</translation>
</message>
<message>
<source>Icons Only</source>
<translation>Chỉ hiển thị biểu tượng</translation>
</message>
<message>
<source>Text Only</source>
<translation>Chỉ hiển thị chữ</translation>
</message>
<message>
<source>Text Alongside Icons</source>
<translation>Chữ kèm theo biểu tượng</translation>
</message>
<message>
<source>Text Under Icons</source>
<translation>Chữ dưới biểu tượng</translation>
</message>
<message>
<source>Text Position:</source>
<translation>Vị trí chữ:</translation>
</message>
<message>
<source>Actions</source>
<translation>Thao tác</translation>
</message>
<message>
<source>Move Up</source>
<translation>Di chuyển lên</translation>
</message>
<message>
<source>Move Down</source>
<translation>Di chuyển xuống</translation>
</message>
<message>
<source>Add Separator</source>
<translation>Thêm dấu phân cách</translation>
</message>
<message>
<source>Command</source>
<translation>Lệnh</translation>
</message>
<message>
<source>Shortcut</source>
<translation>Phím tắt</translation>
</message>
<message>
<source>Action</source>
<translation>Thao tác</translation>
</message>
<message>
<source>Check spelling as you type</source>
<translation>Kiểm tra ngữ pháp khi gõ</translation>
</message>
<message>
<source>Ignore words in UPPERCASE</source>
<translation>Bỏ qua các từ IN HOA</translation>
</message>
<message>
<source>Ignore words with numbers</source>
<translation>Bỏ qua các từ kèm theo số</translation>
</message>
<message>
<source>Language</source>
<translation>Ngôn ngữ</translation>
</message>
<message>
<source>Add</source>
<translation>Thêm</translation>
</message>
<message>
<source>Remove</source>
<translation>Loại bỏ</translation>
</message>
<message>
<source>Personal Dictionary</source>
<translation>Từ điển tự tạo</translation>
</message>
<message>
<source>Remove current dictionary?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>User Interface</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Always show scrollbar</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Always show top bar</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Always show bottom bar</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>RtfReader</name>
<message>
<source>Not a supported RTF file.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>RtfTokenizer</name>
<message>
<source>Unexpectedly reached end of file.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SceneList</name>
<message>
<source>Ctrl+Shift+Down</source>
<translation>Ctrl+Shift+Down</translation>
</message>
<message>
<source>Move Scenes Up</source>
<translation>Chuyển cảnh lên</translation>
</message>
<message>
<source>Ctrl+Shift+Up</source>
<translation>Ctrl+Shift+Up</translation>
</message>
<message>
<source>Toggle Scene List</source>
<translation>Chuyển đổi danh sách các cảnh</translation>
</message>
<message>
<source>Shift+F4</source>
<translation>Shift+F4</translation>
</message>
<message>
<source>Show scene list (%1)</source>
<translation>Hiển thị danh sách cảnh (%1)</translation>
</message>
<message>
<source>Hide scene list (%1)</source>
<translation>Ẩn danh sách cảnh (%1)</translation>
</message>
<message>
<source>Filter</source>
<translation>Lọc dữ liệu</translation>
</message>
<message>
<source>Move Scenes Down</source>
<translation>Chuyển cảnh xuống</translation>
</message>
<message>
<source>Resize scene list</source>
<translation>Chỉnh lại kích thước danh sách cảnh</translation>
</message>
</context>
<context>
<name>Session</name>
<message>
<source>Default</source>
<translation>Mặc định</translation>
</message>
</context>
<context>
<name>SessionManager</name>
<message>
<source>Manage Sessions</source>
<translation>Quản lý phiên làm việc</translation>
</message>
<message>
<source>S&essions</source>
<translation>P&hiên làm việc</translation>
</message>
<message>
<source>New</source>
<translation>Tạo mới</translation>
</message>
<message>
<source>Duplicate</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rename</source>
<translation>Đổi tên</translation>
</message>
<message>
<source>Delete</source>
<translation>Xóa</translation>
</message>
<message>
<source>Switch To</source>
<translation>Chuyển sang</translation>
</message>
<message>
<source>New Session</source>
<translation>Phiên làm việc mới</translation>
</message>
<message>
<source>Duplicate Session</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rename Session</source>
<translation>Đổi tên phiên làm việc</translation>
</message>
<message>
<source>Question</source>
<translation>Câu hỏi</translation>
</message>
<message>
<source>Delete selected session?</source>
<translation>Xóa phiên làm việc đã được chọn?</translation>
</message>
<message>
<source>Session name:</source>
<translation>Tên phiên làm việc:</translation>
</message>
<message>
<source>Sorry</source>
<translation>Rất tiếc</translation>
</message>
<message>
<source>The requested session name is already in use.</source>
<translation>Tên của phiên làm việc được yêu cầu hiện đang được sử dụng.</translation>
</message>
<message>
<source>&New...</source>
<translation>&Tạo mới...</translation>
</message>
<message>
<source>Ctrl+Shift+N</source>
<translation>Ctrl+Shift+N</translation>
</message>
<message>
<source>&Manage...</source>
<translation>&Quản lý...</translation>
</message>
<message>
<source>Ctrl+Shift+M</source>
<translation>Ctrl+Shift+M</translation>
</message>
</context>
<context>
<name>ShortcutEdit</name>
<message>
<source>Clear</source>
<translation>Dọn dẹp</translation>
</message>
<message>
<source>Reset to Default</source>
<translation>Chuyển về mặc định</translation>
</message>
<message>
<source>Shortcut:</source>
<translation>Phím tắt:</translation>
</message>
</context>
<context>
<name>SmartQuote</name>
<message>
<source>Replacing quotation marks...</source>
<translation>Thay đổi các phần đánh dấu trích dẫn..</translation>
</message>
<message>
<source>Please Wait</source>
<translation>Vui lòng đợi</translation>
</message>
</context>
<context>
<name>SpellChecker</name>
<message>
<source>Check Spelling</source>
<translation>Kiểm tra ngữ pháp</translation>
</message>
<message>
<source>&Add</source>
<translation>&Thêm</translation>
</message>
<message>
<source>&Ignore</source>
<translation>&Bỏ qua</translation>
</message>
<message>
<source>I&gnore All</source>
<translation>Bỏ q&ua tất cả</translation>
</message>
<message>
<source>&Change</source>
<translation>Th&ay đổi</translation>
</message>
<message>
<source>C&hange All</source>
<translation>Tha&y đổi tất cả</translation>
</message>
<message>
<source>Not in dictionary:</source>
<translation>Không có trong từ điển:</translation>
</message>
<message>
<source>Change to:</source>
<translation>Thay đổi sang:</translation>
</message>
<message>
<source>Checking spelling...</source>
<translation>Đang thực hiện việc kiểm tra ngữ pháp...</translation>
</message>
<message>
<source>Cancel</source>
<translation>Hủy bỏ</translation>
</message>
<message>
<source>Please wait</source>
<translation>Vui lòng đợi</translation>
</message>
<message>
<source>Continue checking at beginning of file?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Spell check complete.</source>
<translation>Đã thực hiện xong thao tác kiểm tra ngữ pháp.</translation>
</message>
</context>
<context>
<name>SymbolsDialog</name>
<message>
<source>Symbols</source>
<translation>Biểu tượng</translation>
</message>
<message>
<source>Recently used symbols</source>
<translation>Các biểu tượng được dùng gần đây</translation>
</message>
<message>
<source>All symbols</source>
<translation>Tất cả biểu tượng</translation>
</message>
<message>
<source>Details</source>
<translation>Chi tiết</translation>
</message>
<message>
<source>Name:</source>
<translation>Tên:</translation>
</message>
<message>
<source>Insert</source>
<translation>Chèn</translation>
</message>
</context>
<context>
<name>SymbolsModel</name>
<message>
<source>Blocks</source>
<translation>Khối</translation>
</message>
<message>
<source>Scripts</source>
<translation>Kịch bản</translation>
</message>
</context>
<context>
<name>Theme</name>
<message>
<source>Untitled %1</source>
<translation>Chưa đặt tiêu đề %1</translation>
</message>
</context>
<context>
<name>ThemeDialog</name>
<message>
<source>Name:</source>
<translation>Tên:</translation>
</message>
<message>
<source>No Image</source>
<translation>Không có hình ảnh</translation>
</message>
<message>
<source>Tiled</source>
<translation>Xếp theo ô</translation>
</message>
<message>
<source>Centered</source>
<translation>Ở giữa</translation>
</message>
<message>
<source>Stretched</source>
<translation>Trải rộng ra</translation>
</message>
<message>
<source>Scaled</source>
<translation>Theo tỉ lệ</translation>
</message>
<message>
<source>Zoomed</source>
<translation>Phóng to</translation>
</message>
<message>
<source>Opacity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Position:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Width:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Round Text Background Corners</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Radius:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Blur Text Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text Background Drop Shadow</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Vertical Offset:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Margins</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Window:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Indent first line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Above:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Below:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove</source>
<translation>Loại bỏ</translation>
</message>
<message>
<source>Edit Theme</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Window Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Type:</source>
<translation>Loại:</translation>
</message>
<message>
<source>Color:</source>
<translation>Màu:</translation>
</message>
<message>
<source>Image:</source>
<translation>Hình ảnh:</translation>
</message>
<message>
<source> pixels</source>
<translation>điểm ảnh</translation>
</message>
<message>
<source>Left</source>
<translation>Bên tay trái</translation>
</message>
<message>
<source>Text Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Right</source>
<translation>Bên tay phải</translation>
</message>
<message>
<source>Text</source>
<translation>Văn bản</translation>
</message>
<message>
<source>Font:</source>
<translation>Kiểu chữ:</translation>
</message>
<message>
<source>Misspelled:</source>
<translation>Sai ngữ pháp:</translation>
</message>
<message>
<source>Line Spacing</source>
<translation>Khoảng trống giữa các dòng</translation>
</message>
<message>
<source>Single</source>
<translation>Đơn lẻ</translation>
</message>
<message>
<source>1.5 Lines</source>
<translation>1.5 dòng</translation>
</message>
<message>
<source>Double</source>
<translation>Gấp đôi</translation>
</message>
<message>
<source>Proportional</source>
<translation>Tỉ lệ cân xứng</translation>
</message>
<message>
<source>Height:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Paragraph Spacing</source>
<translation>Khoảng cách giữa các đoạn văn</translation>
</message>
<message>
<source>Tab Width:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New Theme</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ThemeManager</name>
<message>
<source>Themes</source>
<translation>Giao diện</translation>
</message>
<message>
<source>Default</source>
<translation type="unfinished">Mặc định</translation>
</message>
<message>
<source>Gentle Blues</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Old School</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Space Dreams</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Writing Desk</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New</source>
<translation type="unfinished">Tạo mới</translation>
</message>
<message>
<source>Duplicate</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Custom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit</source>
<translation type="unfinished">Chỉnh sửa</translation>
</message>
<message>
<source>Delete</source>
<translation type="unfinished">Xóa</translation>
</message>
<message>
<source>Import</source>
<translation>Nhập dữ liệu</translation>
</message>
<message>
<source>Export</source>
<translation>Xuất dữ liệu</translation>
</message>
<message>
<source>Question</source>
<translation>Câu hỏi</translation>
</message>
<message>
<source>Delete theme '%1'?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Themes (%1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Import Theme</source>
<translation>Nhập dữ liệu về giao diện</translation>
</message>
<message>
<source>Export Theme</source>
<translation>Xuất dữ liệu về giao diện</translation>
</message>
<message>
<source>Bitter Skies</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enchantment</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Spy Games</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Tranquility</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Timer</name>
<message>
<source><b>%1</b> - %2</source>
<translation><b>%1</b> - %2</translation>
</message>
<message>
<source>Question</source>
<translation>Câu hỏi</translation>
</message>
<message>
<source>Delete timer?</source>
<translation>Xóa phần đếm thời gian?</translation>
</message>
<message>
<source><b>Words:</b> %L1</source>
<translation><b>Số lượng từ:</b> %L1</translation>
</message>
<message>
<source><b>Pages:</b> %L1</source>
<translation><b>Số lượng trang:</b> %L1</translation>
</message>
<message>
<source><b>Paragraphs:</b> %L1</source>
<translation><b>Số lượng đoạn văn:</b> %L1</translation>
</message>
<message>
<source><b>Characters:</b> %L1 / %L2</source>
<translation><b>Số lượng ký tự:</b> %L1 / %L2</translation>
</message>
<message>
<source>Set Delay</source>
<translation>Đặt độ trễ</translation>
</message>
<message>
<source>Set Time</source>
<translation>Đặt thời gian</translation>
</message>
<message>
<source>Delay:</source>
<translation>Độ trễ:</translation>
</message>
<message>
<source>Time:</source>
<translation>Thời gian:</translation>
</message>
<message>
<source>HH:mm:ss</source>
<translation>HH:mm:ss</translation>
</message>
<message>
<source>Alarm</source>
<translation>Hẹn giờ</translation>
</message>
<message>
<source>Type:</source>
<translation>Loại:</translation>
</message>
<message>
<source>Memo:</source>
<translation>Ghi chú:</translation>
</message>
<message>
<source>Edit</source>
<translation>Chỉnh sửa</translation>
</message>
<message>
<source>Delete</source>
<translation>Xóa</translation>
</message>
</context>
<context>
<name>TimerDisplay</name>
<message>
<source>HH:mm:ss</source>
<translation>HH:mm:ss</translation>
</message>
<message>
<source>No timers running</source>
<translation>Hiện không có phần đếm thời gian nào</translation>
</message>
</context>
<context>
<name>TimerManager</name>
<message>
<source>Timers</source>
<translation>Bộ đếm thời gian</translation>
</message>
<message>
<source>New</source>
<translation>Tạo mới</translation>
</message>
<message>
<source>Recent</source>
<translation>Gần đây</translation>
</message>
<message>
<source>Question</source>
<translation>Câu hỏi</translation>
</message>
<message>
<source>Cancel editing timers?</source>
<translation>Hủy bỏ việc chỉnh sửa bộ đếm giờ?</translation>
</message>
<message>
<source>+HH:mm:ss</source>
<translation>+HH:mm:ss</translation>
</message>
<message>
<source>%1 - %2</source>
<translation>%1 - %2</translation>
</message>
</context>
<context>
<name>Window</name>
<message>
<source>Loading themes</source>
<translation>Đang tải dữ liệu giao diện</translation>
</message>
<message>
<source>Loading sounds</source>
<translation>Đang tải dữ liệu âm thanh</translation>
</message>
<message>
<source>Untitled</source>
<translation>Chưa đặt tiêu đề</translation>
</message>
<message>
<source>Open File</source>
<translation>Mở tập tin</translation>
</message>
<message>
<source>About FocusWriter</source>
<translation>Dịch bởi Phan Anh</translation>
</message>
<message>
<source>FocusWriter</source>
<translation>FocusWriter</translation>
</message>
<message>
<source>A simple fullscreen word processor</source>
<translation>Một phần mềm soạn thảo văn bản toàn màn hình dạng đơn giản</translation>
</message>
<message>
<source>Copyright &copy; 2008-%1 Graeme Gott</source>
<translation>Bản quyền &copy; 2008-%1 Graeme Gott</translation>
</message>
<message>
<source>Released under the <a href=%1>GPL 3</a> license</source>
<translation>Phát hành dựa theo giấy phép <a href=%1>GPL 3</a></translation>
</message>
<message>
<source>Uses icons from the <a href=%1>Oxygen</a> icon theme</source>
<translation>Sử dụng bộ biểu tượng từ <a href=%1>Oxygen</a></translation>
</message>
<message>
<source>Used under the <a href=%1>LGPL 3</a> license</source>
<translation>Sử dụng dựa trên giấy phép <a href=%1>LGPL 3</a></translation>
</message>
<message>
<source>Characters: %L1 / %L2</source>
<translation>Số ký tự: %L1 / %L2</translation>
</message>
<message>
<source>Pages: %L1</source>
<translation>Số trang: %L1</translation>
</message>
<message>
<source>Paragraphs: %L1</source>
<translation>Số đoạn văn: %L1</translation>
</message>
<message>
<source>Words: %L1</source>
<translation>Số từ: %L1</translation>
</message>
<message>
<source>Opening %1</source>
<translation>Đang mở %1</translation>
</message>
<message>
<source>(Untitled %1)</source>
<translation>(Chưa đặt tiêu đề %1)</translation>
</message>
<message>
<source>List all documents</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Switch to Next Document</source>
<translation>Chuyển sang một tài liệu mới</translation>
</message>
<message>
<source>Switch to Previous Document</source>
<translation>Chuyển sang tài liệu trước đó</translation>
</message>
<message>
<source>Switch to First Document</source>
<translation>Chuyển sang tài liệu đầu tiên</translation>
</message>
<message>
<source>Switch to Last Document</source>
<translation>Chuyển sang tài liệu cuối cùng</translation>
</message>
<message>
<source>Switch to Document %1</source>
<translation>Chuyển sang tài liệu %1</translation>
</message>
<message>
<source>Loading settings</source>
<translation>Đang tải thiết lập</translation>
</message>
<message>
<source>Emergency cache is not writable.</source>
<translation>Phần bộ nhớ đệm trong trường hợp khẩn cấp hiện không thể ghi dữ liệu vào.</translation>
</message>
<message>
<source>Warning</source>
<translation>Cảnh báo</translation>
</message>
<message>
<source>FocusWriter was not shut down cleanly.</source>
<translation>FocusWriter đã không được tắt theo đúng cách.</translation>
</message>
<message>
<source>Restore from the emergency cache?</source>
<translation>Khôi phục dữ liệu từ phần bộ nhớ đệm khẩn cấp?</translation>
</message>
<message>
<source>Some files could not be opened.</source>
<translation>Không thể mở một số tập tin.</translation>
</message>
<message>
<source>Some files were opened Read-Only.</source>
<translation>Một vài tập tin được mở dưới chế độ Chỉ Được-Đọc</translation>
</message>
<message>
<source>'%1' is newer than the cached copy.</source>
<translation>'%1' mới hơn bản dữ liệu được sao chép trong bộ nhớ đệm.</translation>
</message>
<message>
<source>Overwrite newer file?</source>
<translation>Viết đè dữ liệu lên tập tin mới hơn?</translation>
</message>
<message>
<source>Save Changes?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Save changes to the file '%1' before closing?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Your changes will be lost if you don't save them.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Unable to load typewriter sounds.</source>
<translation>Không thể tải âm thanh tạo hiệu ứng gõ chữ.</translation>
</message>
<message>
<source>&File</source>
<translation>&Tập tin</translation>
</message>
<message>
<source>&New</source>
<translation>&Tạo mới</translation>
</message>
<message>
<source>&Open...</source>
<translation>&Mở...</translation>
</message>
<message>
<source>Reloa&d</source>
<translation>Tải l&ại</translation>
</message>
<message>
<source>&Save</source>
<translation>&Lưu</translation>
</message>
<message>
<source>Save &As...</source>
<translation>Lưu &Dưới Dạng...</translation>
</message>
<message>
<source>&Rename...</source>
<translation>&Đổi tên...</translation>
</message>
<message>
<source>Save A&ll</source>
<translation>Lưu T&ất Cả</translation>
</message>
<message>
<source>Manage Sessions</source>
<translation>Quản lý phiên làm việc</translation>
</message>
<message>
<source>New Session</source>
<translation>Phiên làm việc mới</translation>
</message>
<message>
<source>&Print...</source>
<translation>&In dữ liệu...</translation>
</message>
<message>
<source>&Close</source>
<translation>Đ&óng lại</translation>
</message>
<message>
<source>&Quit</source>
<translation>Th&oát</translation>
</message>
<message>
<source>Ctrl+Q</source>
<translation>Ctrl+Q</translation>
</message>
<message>
<source>&Edit</source>
<translation>C&hỉnh sửa</translation>
</message>
<message>
<source>&Undo</source>
<translation>Hủ&y thao tác</translation>
</message>
<message>
<source>&Redo</source>
<translation>Lặ&p lại thao tác</translation>
</message>
<message>
<source>Cu&t</source>
<translation>Cắ&t</translation>
</message>
<message>
<source>&Copy</source>
<translation>S&ao chép</translation>
</message>
<message>
<source>&Paste</source>
<translation>D&án</translation>
</message>
<message>
<source>Paste &Unformatted</source>
<translation>Dán vào dữ liệu ch&ưa chỉnh sửa</translation>
</message>
<message>
<source>Ctrl+Shift+V</source>
<translation>Ctrl+Shift+V</translation>
</message>
<message>
<source>Select &All</source>
<translation>Chọn tấ&t cả</translation>
</message>
<message>
<source>Select &Scene</source>
<translation>Chọn c&ảnh</translation>
</message>
<message>
<source>Ctrl+Shift+A</source>
<translation>Ctrl+Shift+A</translation>
</message>
<message>
<source>Fo&rmat</source>
<translation>Đị&nh dạng</translation>
</message>
<message>
<source>&Bold</source>
<translation>&In đậm</translation>
</message>
<message>
<source>&Italic</source>
<translation>I&n nghiêng</translation>
</message>
<message>
<source>&Underline</source>
<translation>&Gạch dưới</translation>
</message>
<message>
<source>Stri&kethrough</source>
<translation>G&ạch xuyên qua</translation>
</message>
<message>
<source>Ctrl+K</source>
<translation>Ctrl+K</translation>
</message>
<message>
<source>Sup&erscript</source>
<translation>Chữ t&rồi lên</translation>
</message>
<message>
<source>Ctrl+^</source>
<translation>Ctrl+^</translation>
</message>
<message>
<source>&Subscript</source>
<translation>Chữ s&ụp xuống</translation>
</message>
<message>
<source>Ctrl+_</source>
<translation>Ctrl+_</translation>
</message>
<message>
<source>Align &Left</source>
<translation>Canh lề b&ên trái</translation>
</message>
<message>
<source>Ctrl+{</source>
<translation>Ctrl+{</translation>
</message>
<message>
<source>Align &Center</source>
<translation>Canh lề c&hính giữa</translation>
</message>
<message>
<source>Ctrl+|</source>
<translation>Ctrl+|</translation>
</message>
<message>
<source>Align &Right</source>
<translation>Canh lề bên p&hải</translation>
</message>
<message>
<source>Ctrl+}</source>
<translation>Ctrl+}</translation>
</message>
<message>
<source>Align &Justify</source>
<translation>Canh lề đ&ều hai bên</translation>
</message>
<message>
<source>Ctrl+J</source>
<translation>Ctrl+J</translation>
</message>
<message>
<source>&Decrease Indent</source>
<translation>Giả&m mức lùi dòng</translation>
</message>
<message>
<source>Ctrl+<</source>
<translation>Ctrl+<</translation>
</message>
<message>
<source>I&ncrease Indent</source>
<translation>Tă&ng mức lùi dòng</translation>
</message>
<message>
<source>Ctrl+></source>
<translation>Ctrl+></translation>
</message>
<message>
<source>Le&ft to Right Block</source>
<translation>Khối văn bản từ tr&ái sang phải</translation>
</message>
<message>
<source>Ri&ght to Left Block</source>
<translation>Khối văn bản từ ph&ải sang trái</translation>
</message>
<message>
<source>&Tools</source>
<translation>Cô&ng cụ</translation>
</message>
<message>
<source>&Find...</source>
<translation>Tì&m kiếm...</translation>
</message>
<message>
<source>Find &Next</source>
<translation>Tìm tiế&p theo</translation>
</message>
<message>
<source>Find Pre&vious</source>
<translation>Tìm tr&ước đó</translation>
</message>
<message>
<source>&Replace...</source>
<translation>Th&ay thế...</translation>
</message>
<message>
<source>Ctrl+R</source>
<translation>Ctrl+R</translation>
</message>
<message>
<source>Smart &Quotes</source>
<translation>Trích dẫn thô&ng minh:</translation>
</message>
<message>
<source>Update &Document</source>
<translation>Cập nhật tà&i liệu</translation>
</message>
<message>
<source>Update &Selection</source>
<translation>Cập nhật v&ùng lựa chọn</translation>
</message>
<message>
<source>&Spelling...</source>
<translation>Kiểm tr&a lỗi chính tả...</translation>
</message>
<message>
<source>F7</source>
<translation>F7</translation>
</message>
<message>
<source>Set &Language...</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>&Timers...</source>
<translation>B&ộ đếm thời gian</translation>
</message>
<message>
<source>S&ymbols...</source>
<translation>Biể&u tượng...</translation>
</message>
<message>
<source>&Daily Progress</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>&Settings</source>
<translation>Thiế&t lập</translation>
</message>
<message>
<source>Show &Toolbar</source>
<translation>Hiển thị th&anh công cụ</translation>
</message>
<message>
<source>Show &Menu Icons</source>
<translation>Hiển thị biểu tượng men&u</translation>
</message>
<message>
<source>F&ocused Text</source>
<translation>Tập tr&ung vào văn bản</translation>
</message>
<message>
<source>&Fullscreen</source>
<translation>Toàn mà&n hình</translation>
</message>
<message>
<source>F11</source>
<translation>F11</translation>
</message>
<message>
<source>Esc</source>
<translation>Esc</translation>
</message>
<message>
<source>M&inimize</source>
<translation>T&hu nhỏ</translation>
</message>
<message>
<source>Ctrl+M</source>
<translation>Ctrl+M</translation>
</message>
<message>
<source>&Themes...</source>
<translation>G&iao diện...</translation>
</message>
<message>
<source>&Preferences...</source>
<translation>Tùy biế&n...</translation>
</message>
<message>
<source>Focus Off</source>
<translation>Tắt phần tập trung</translation>
</message>
<message>
<source>Focus One Line</source>
<translation>Tập trung vào một dòng văn bản</translation>
</message>
<message>
<source>Focus Three Lines</source>
<translation>Tập trung vào ba dòng văn bản</translation>
</message>
<message>
<source>&Paragraph</source>
<translation>&Đoạn văn</translation>
</message>
<message>
<source>Focus Paragraph</source>
<translation>Tập trung vào đoạn văn</translation>
</message>
<message>
<source>&Help</source>
<translation>Dịch bởi P&han Anh</translation>
</message>
<message>
<source>Application &Language...</source>
<translation>Ngôn ngữ hiển th&ị...</translation>
</message>
<message>
<source>Some files were unsupported and could not be opened.</source>
<translation>Một số tập tin không được hỗ trợ nên sẽ không thể mở được.</translation>
</message>
<message>
<source>&Off</source>
<translation>T&ắt</translation>
</message>
<message>
<source>One &Line</source>
<translation>Một D&òng</translation>
</message>
<message>
<source>&Three Lines</source>
<translation>B&a Dòng</translation>
</message>
<message>
<source>&About</source>
<translation>Thô&ng tin</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Thô&ng tin về Qt</translation>
</message>
<message>
<source>Pa&ge Setup...</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>&Heading</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading &1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading &2</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading &3</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading &4</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading &5</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading &6</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>&Normal</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update Document Smart Quotes</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update Selection Smart Quotes</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Ctrl+Shift+`</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>main</name>
<message>
<source>Files to open in current session.</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| gottcode/focuswriter | translations/focuswriter_vi.ts | TypeScript | gpl-3.0 | 58,290 |
/*
* Copyright (C) 2016 Salvatore D'Angelo
* This file is part of Mr Snake project.
* This file derives from the Mr Nom project developed by Mario Zechner for the Beginning Android
* Games book (chapter 6).
*
* Mr Snake 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 of the License, or
* (at your option) any later version.
*
* Mr Snake 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.
*/
package org.androidforfun.mrsnake.view;
import org.androidforfun.framework.Screen;
import org.androidforfun.framework.impl.AndroidGame;
/*
* This class represents the main activity of the Mr Snake game.
*
* @author Salvatore D'Angelo
*/
public class MrSnakeGame extends AndroidGame {
/*
* The first screen of the Mr Snake game is the LoadingScreen used to load all the assets in memory.
* Usually these screen have a progress bar that represents the percentace of work done. In our
* case we avoided this complication because the assets are loaded very quickly.
*/
public Screen getStartScreen() {
return new LoadingScreen();
}
} | sasadangelo/MrSnake | app/src/main/java/org/androidforfun/mrsnake/view/MrSnakeGame.java | Java | gpl-3.0 | 1,472 |
"use strict";
var SimpleBot = function () {
this.name = 'SimpleBot';
};
SimpleBot.prototype.getMove = function (game) {
var nMaxConsequentFails = 1000,
nMaxCleverTryFails = 900;
for (var consequentFails = 0; consequentFails < nMaxConsequentFails; ++consequentFails) {
var tryCoord = {
x: _.random(game.size - 1),
y: _.random(game.size - 1)
};
var squareCoord = game.squareCoordByCell(tryCoord);
var isStupidMove = !game.getSquare(squareCoord).empty();
if (game.isAllowedMove(tryCoord) && (!isStupidMove || consequentFails > nMaxCleverTryFails)) {
return tryCoord;
}
}
throw 'No moves detected';
};
| sochka/TicTacToeExtended-canvas | js/simple_bot.js | JavaScript | gpl-3.0 | 656 |
/*
* This file is part of switcher-myplugin.
*
* libswitcher is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include "switcher/quiddity-manager.hpp"
#include "switcher/quiddity-basic-test.hpp"
#ifdef HAVE_CONFIG_H
#include "../../config.h"
#endif
int
main() {
{
switcher::QuiddityManager::ptr manager =
switcher::QuiddityManager::make_manager("test_manager");
#ifdef HAVE_CONFIG_H
gchar *usr_plugin_dir = g_strdup_printf("./%s", LT_OBJDIR);
manager->scan_directory_for_plugins(usr_plugin_dir);
g_free(usr_plugin_dir);
#else
return 1;
#endif
assert(switcher::QuiddityBasicTest::test_full(manager, "OSCctl"));
assert(switcher::QuiddityBasicTest::test_full(manager, "shmOSCsink"));
} // end of scope is releasing the manager
return 0;
}
| nicobou/ubuntu-switcher | plugins/osc/check_osc.cpp | C++ | gpl-3.0 | 1,536 |
/**
* Copyright 2011-2016, Sybila, Systems Biology Laboratory and individual
* contributors by the @authors tag.
*
* This file is part of Parasim.
*
* Parasim 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 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
package org.sybila.parasim.extension.projectmanager.model.projectimpl;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sybila.parasim.extension.projectmanager.names.ExperimentSuffixes;
/**
*
* @author <a href="mailto:xvejpust@fi.muni.cz">Tomáš Vejpustek</a>
*/
public class FileManager {
private static final Logger LOGGER = LoggerFactory.getLogger(FileManager.class);
private final File dir;
private final ExperimentSuffixes suffix;
public FileManager(File directory, ExperimentSuffixes fileExtension) {
if (directory == null) {
throw new IllegalArgumentException("Argument (directory) is null.");
}
if (!directory.isDirectory()) {
throw new IllegalArgumentException("Target file is not a directory.");
}
dir = directory;
suffix = fileExtension;
}
public File getFile(String name) {
if (suffix != null) {
name = suffix.add(name);
}
return new File(dir, name);
}
public String[] getFiles() {
String[] names = dir.list(new FilenameFilter() {
@Override
public boolean accept(File file, String string) {
return string.endsWith(suffix.getSuffix());
}
});
String[] result = new String[names.length];
for (int i = 0; i < names.length; i++) {
result[i] = suffix.remove(names[i]);
}
return result;
}
public File createFile(String name) {
File target = getFile(name);
try {
if (target.createNewFile()) {
return target;
} else {
return null;
}
} catch (IOException ioe) {
LOGGER.warn("Unable to create file `" + target.toString() + "'.", ioe);
return null;
}
}
public void deleteFile(String name) {
File target = getFile(name);
if (!target.delete()) {
target.deleteOnExit();
LOGGER.error("Unable to delete `" + target.toString() + "'. Will try removing it on program exit.");
}
}
}
| VojtechBruza/parasim | extensions/project-manager-simple/src/main/java/org/sybila/parasim/extension/projectmanager/model/projectimpl/FileManager.java | Java | gpl-3.0 | 3,029 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nikse.SubtitleEdit.Core.Common;
namespace Nikse.SubtitleEdit.Core.SubtitleFormats
{
public class JsonType8b : SubtitleFormat
{
public override string Extension => ".json";
public override string Name => "JSON Type 8b";
public override bool IsMine(List<string> lines, string fileName)
{
var subtitle = new Subtitle();
LoadSubtitle(subtitle, lines, fileName);
if (_errorCount >= subtitle.Paragraphs.Count)
{
return false;
}
var avgDurSecs = subtitle.Paragraphs.Average(p => p.Duration.TotalSeconds);
return avgDurSecs < 60 && avgDurSecs > 0.1;
}
public override string ToText(Subtitle subtitle, string title)
{
var sb = new StringBuilder(@"[");
int count = 0;
foreach (Paragraph p in subtitle.Paragraphs)
{
if (count > 0)
{
sb.Append(',');
}
sb.Append("{\"start_time\":");
sb.Append(p.StartTime.TotalMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
sb.Append(",\"end_time\":");
sb.Append(p.EndTime.TotalMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
sb.Append(",\"text\":\"");
sb.Append(Json.EncodeJsonText(p.Text));
sb.Append("\"}");
count++;
}
sb.Append(']');
return sb.ToString().Trim();
}
public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName)
{
_errorCount = 0;
var sb = new StringBuilder();
foreach (string s in lines)
{
sb.Append(s);
}
string allText = sb.ToString().Trim();
if (!(allText.StartsWith("{", StringComparison.Ordinal) || allText.StartsWith("[", StringComparison.Ordinal)))
{
return;
}
foreach (string line in allText.Split('{', '}', '[', ']'))
{
string s = line.Trim();
if (s.Length > 10)
{
string start = Json.ReadTag(s, "start_time");
string end = Json.ReadTag(s, "end_time");
string text = Json.ReadTag(s, "text");
if (start != null && end != null && text != null)
{
if (double.TryParse(start, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var startMs) &&
double.TryParse(end, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var endMs))
{
subtitle.Paragraphs.Add(new Paragraph(Json.DecodeJsonText(text), startMs, endMs));
}
else
{
_errorCount++;
}
}
else
{
_errorCount++;
}
}
}
subtitle.Renumber();
}
}
}
| hhgyu/subtitleedit | src/libse/SubtitleFormats/JsonType8b.cs | C# | gpl-3.0 | 3,504 |
FAULTY_CHUNKSERVERS=YES source test_suites/TestTemplates/test_xor_writing.inc
| lizardfs/lizardfs | tests/test_suites/LongSystemTests/test_xor_writing_faulty_chunkservers.sh | Shell | gpl-3.0 | 78 |
<?php get_header(); ?>
<!-- Sayfa -->
<div id="sayfa" class="blog" itemprop="mainContentOfPage" itemscope="itemscope" itemtype="http://schema.org/Blog">
<div class="ortala">
<div class="sayfasabit">
<!-- Sayfa Sol -->
<div class="sayfa-sol">
<!-- Yazi -->
<?php while ( have_posts() ) : the_post(); get_template_part('content'); endwhile; ?>
<!-- Yazi Bitisi -->
<!-- Sayfalama -->
<?php
the_posts_pagination( array(
'prev_text' => __( 'Previous page', '4Piksel' ),
'next_text' => __( 'Next page', '4Piksel' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', '4Piksel' ) . ' </span>',
) );
?>
<!-- Sayfalama Bitis -->
</div>
<!-- Sayfa Sol Bitis -->
<?php get_sidebar(); ?>
</div>
</div>
</div>
<!-- Sayfa Bitis -->
<?php get_footer(); ?> | 4Piksel/4Piksel-Lite | archive.php | PHP | gpl-3.0 | 1,135 |
#coding: utf-8
from __future__ import unicode_literals, absolute_import
import logging
import json
from django.utils.dateparse import parse_datetime
from django.utils import timezone
from wechatpy.exceptions import WeChatClientException
from common import wechat_client
from .local_parser import LocalParser
from remind.models import Remind
from .exceptions import ParseError
logger = logging.getLogger(__name__)
def parse(text, **kwargs):
"""Returns a Remind"""
# Try to parse by rules and then turn to wechat API since wechat API is unstable and inaccurate.
logger.info('Trying to parse "%s" using rules.', text)
reminder = LocalParser().parse_by_rules(text)
if not reminder:
logger.info('Failed to parse time from "%s" using rules, try wechat api.', text)
reminder = parse_by_wechat_api(text, **kwargs)
if reminder.time <= timezone.now(): # GMT and UTC time can compare with each other
raise ParseError('/:no%s已经过去了,请重设一个将来的提醒。\n\n消息: %s' % (
reminder.time.strftime('%Y-%m-%d %H:%M'), text))
return reminder
def parse_by_wechat_api(text, **kwargs):
"""
{
"errcode": 0,
"query": "提醒我上午十点开会",
"semantic": {
"details": {
"answer": "",
"context_info": {},
"datetime": {
"date": "2015-12-23",
"date_lunar": "2015-11-13",
"time": "10:00:00",
"time_ori": "上午十点",
"type": "DT_ORI",
"week": "3"
},
"event": "开会",
"hit_str": "提醒 我 上午 十点 开会 ",
"remind_type": "0"
},
"intent": "SEARCH"
},
"type": "remind"
}
"""
try:
wechat_result = wechat_client.semantic.search(
query=text,
category='remind',
city='上海', # F**k, weixin always needs the city param, hard-code one.
**kwargs
)
except WeChatClientException as e:
logger.info('Failed to parse using wechat api ' + str(e))
raise
# wechat_result = json.loads(parse_by_wechat_api.__doc__)
logger.debug('Semantic result from wechat, %s',
json.dumps(wechat_result, ensure_ascii=False))
dt_str = '%s %s+08:00' % (
wechat_result['semantic']['details']['datetime']['date'],
wechat_result['semantic']['details']['datetime']['time'],
) # there could be nothing in details
dt = parse_datetime(dt_str)
return Remind(time=dt,
desc=wechat_result.get('query', ''),
event=wechat_result['semantic']['details'].get('event', ''))
def parse_by_boson(text):
pass
| polyrabbit/WeCron | WeCron/wxhook/todo_parser/__init__.py | Python | gpl-3.0 | 2,854 |
---
layout: default
permalink: /introduction/
custom_js:
- jquery.min
- anchor.min
- ace.min
- mode-haskell.min
- bundle
- index
---
{%pagination #chapter1%}
# Introduction - Starting Out, Nice and Easy
## 1. Functional Programming?
Functional Programming (FP) can be thought of as a method of writing computer programs where *specification* takes precedence over direct manipulation of computer memory and executable *instructions*. This is a bit of an oversimplification, as FP offers quite a bit more benefits that simply allowing a programmer to program *differently*.
Nonetheless, direct memory manipulation is (probably) the more familiar programming concept. In fact, it is the primary idealogy behind languages like C, Java and Python. The languages allow developers to freely manipulate information stored in memory. Through these languages, programmers compose instructions for the computer to `read` and `write` data. For example, let's consider the following code snippet written in Python:
```python
x = 3
y = x + 2
print(x, y)
```
To those familiar with programming in *imperative* languages (like Python), we know that the above code executes from top to bottom, line by line. Given this, we can reason that the following occurs when the code is executed by a computer:
1. The value `3` is stored inside a variable named `x`.
2. The value stored in the variable `x` is read from memory, the value `2` is added to it and is stored in the new variable `y` (*Note*: the value stored in `x` is unchanged).
3. Both variables `x` and `y` are read from memory and stored inside a tuple, resulting in the value `(3, 5)` being printed onto the console.
4. Once the end of the program is reached, the program terminates.
With this, we can say that the code snippet *reflects* how a computer would peform the above computation. While in certain situations, a programmer might find this method of programming useful (indeed, *necessary* at times), programming in such a way is not always desirable or necessary.
On the other hand, while functional languages don't (quite) offer the seamless access to computer memory and don't (necessarily) feature an inherit structure in the order in which code is executed (we'll get back to this point later), functional languages offer something unique and powerful that imperative languages do not. To illustrate our point, let's take the standard, poster-child example of functional programming: `quicksort`. Let's first recall how `quicksort` is implemented by writing some pseudocode:
1. Choose a `pivot` element inside the given array/list
2. Split the array into two new arrays, one containing elements less than `pivot` (`ls1`) and the other containing elements greater than`pivot` (`ls2`), arbitrarily breaking ties.
3. Recur on both of the new lists to sort them.
4. Place the `pivot` element in between the newly sorted lists (e.g. result = `ls1` + `pivot` + `ls2`).
The above pseudocode, more or less, reflects how to implement `quicksort` in an imperative language. To do this, the programmer would need to design the individual *steps* in such a way that the computer executing the code peforms each of the above points in the correct manner. Now, let's see how to implement `quicksort` in Haskell, a pure, functional programming language:
```haskell
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = xsLess ++ [x] ++ xsMore
where xsLess = quicksort (filter (<= x) xs)
xsMore = quicksort (filter (> x) xs)
```
Yes. 5 lines, and, with some inlining, we can compress the above definition down into 3 lines. Writing short code, however, is *not* the only reason to write in a language like Haskell. If we take the time to study the code above, we can see that it's *not* designed as a step-by-step instruction of what a computer should do to peform the intended computation but more as a *specification* of what the computation itself is supposed to do. When we write code using a functional language, we do not need to worry about what the computer actually needs to do. We simply focus on designing the proper logic around so that it peforms as intended. Thus, at the cost of some performance (i.e., imperative code *generally* performs slightly better than functional code), we alleviate the need to design all the intermediary steps of a computation and instead are allowed to work at a *higher-level* of designing computer programs.
We won't go into much more detail about the differences between imperative and functional code. For now, it is important to clearly state that there are benefits and pitfalls in designing computer programs in both manners of writing code.
## 2. What We're Doing Here
This is **Пroject λamp** (PL), a simple, down to earth introduction to the vast and ever-expanding world of functional programming. This project can be thought of as a tutorial into the core concepts of languages that feature some functional programming ideals and as well as those that rely heavily on them.
For this book, we are using the *PureScript* programming language, a flavor of Haskell. Unlike Haskell, PureScript is intended for use as a *JavaScript replacement*, giving us the needed flexibility for developing a browser-based teaching tool that not only *teaches* functional programming but also allows users to interact with working code within their browser. We are taking direct inspiration from *[Eloquent JavaScript](http://eloquentjavascript.net/)*, which provides much of the same utility for learning the JavaScript programming language.
We must clarify that this book is **not** a book that teaches PureScript (one can find that [here](https://leanpub.com/purescript/read)). Our goal is to provide a seamless and hands-on experience of learning functional languages (like Haskell and PureScript), because we believe that this method of learning is valueable, especially when it comes to learning about functional programming and its core concepts and ideals.
## 3. How to Use this Book
Throughout this book, one will find *many* code examples, most of which are written in PureScript (sometimes made to look like Haskell) and all of which are user-interactable. That is, if one should desire to mess around with the given examples, one is able (in fact, *encouraged*) to do so!
It should be mentioned, however, that, unlike a language like JavaScript, a purely functional language does not have easy access to *effectful computations*, the simplest example of which is `print`. To those more familiar with languages that allow the free-reign usage of `print` functions, this might take some getting used to. One should not be too wary, as functional languages offer something that is also quite useful, some would argue *more* so than being able to interact seamlessly with the console, which brings us to our next point.
In this book, we let **exercises** do the talking, a liberty that is present due in part to an advantage of certain functional languages. We hope that the reader will soon come to understand what we mean by this.
# Exercises
### i. Quicksort in PureScript
{%
repl_only quicksort
#quicksort :: forall a. (Ord a) => List a -> List a
quicksort Nil = Nil
quicksort (x:xs) = xsLess <> (singleton x) <> xsMore
where xsLess = quicksort (filter (\a -> a <= x) xs)
xsMore = quicksort (filter (\a -> a > x) xs)%}
**NOTE:** To compile editable PureScript code, click into the snippet you want executed and press `CTRL + ENTER`, or on OS X press `CMD + ENTER`. If compilation goes well, nothing happens! This *generally* means everything went well. If something went wrong, you will receive an error message in red underneath the editor--try it out by removing the last `)` in the above editable code.
What do you suppose the first line of the code (the *type declaration*) says about this function? `quicksort` is a function that, well, sorts `List`s *quickly*. What sorts of `List`s does this function work with? It might come as a surprise to hear, but one should not have to worry about understanding *how* the code sorts `List`s to answer this question. We, however, have included a `REPL` to interact with the code above (and for *all* other PureScript code on this page). Try a few things and see what happens!
How about:
```haskell
quicksort (89:81:13:71:52:Nil)
```
### ii. Dabble in Types
What do you think the *types* are of the following function definitions?
{%
basic type-declaration#id x = x
const x y = x%}
**HINT**: Look back at exercise 1. What does the variable `a` mean in the type declaration for `quicksort`?
If you don't see any errors, chances are, you added the correct types!
{%pagination #chapter1%}
| lazywithclass/project-lamp | website/book/intro.markdown | Markdown | gpl-3.0 | 8,698 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>GNU Radio 3.6.4.2 C++ API: gr_skiphead Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 3.6.4.2 C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('classgr__skiphead.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#friends">Friends</a> </div>
<div class="headertitle">
<div class="title">gr_skiphead Class Reference<div class="ingroups"><a class="el" href="group__slicedice__blk.html">Slicing and Dicing Streams</a></div></div> </div>
</div><!--header-->
<div class="contents">
<!-- doxytag: class="gr_skiphead" --><!-- doxytag: inherits="gr_block" -->
<p>skips the first N items, from then on copies items to the outputUseful for building test cases and sources which have metadata or junk at the start
<a href="classgr__skiphead.html#details">More...</a></p>
<p><code>#include <<a class="el" href="gr__skiphead_8h_source.html">gr_skiphead.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for gr_skiphead:</div>
<div class="dyncontent">
<div class="center">
<img src="classgr__skiphead.png" usemap="#gr_skiphead_map" alt=""/>
<map id="gr_skiphead_map" name="gr_skiphead_map">
<area href="structgr__block.html" alt="gr_block" shape="rect" coords="0,0,81,24"/>
</map>
</div></div>
<p><a href="classgr__skiphead-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">int </td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__skiphead.html#a91b916781b405d2982db9aab2e16f868">general_work</a> (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items)</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">compute output items from input items <a href="#a91b916781b405d2982db9aab2e16f868"></a><br/></td></tr>
<tr><td colspan="2"><h2><a name="friends"></a>
Friends</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="gr__core__api_8h.html#a8b8937b0c61edd85ab57ce8203543248">GR_CORE_API</a> <a class="el" href="classboost_1_1shared__ptr.html">gr_skiphead_sptr</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__skiphead.html#aa003d0cd01695c642d48ec5f6b260921">gr_make_skiphead</a> (size_t itemsize, <a class="el" href="stdint_8h.html#aec6fcb673ff035718c238c8c9d544c47">uint64_t</a> nitems_to_skip)</td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>skips the first N items, from then on copies items to the output</p>
<p>Useful for building test cases and sources which have metadata or junk at the start </p>
</div><hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="a91b916781b405d2982db9aab2e16f868"></a><!-- doxytag: member="gr_skiphead::general_work" ref="a91b916781b405d2982db9aab2e16f868" args="(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">int <a class="el" href="classgr__skiphead.html#a91b916781b405d2982db9aab2e16f868">gr_skiphead::general_work</a> </td>
<td>(</td>
<td class="paramtype">int </td>
<td class="paramname"><em>noutput_items</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">gr_vector_int & </td>
<td class="paramname"><em>ninput_items</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">gr_vector_const_void_star & </td>
<td class="paramname"><em>input_items</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">gr_vector_void_star & </td>
<td class="paramname"><em>output_items</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>compute output items from input items </p>
<dl class="params"><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">noutput_items</td><td>number of output items to write on each output stream </td></tr>
<tr><td class="paramname">ninput_items</td><td>number of input items available on each input stream </td></tr>
<tr><td class="paramname">input_items</td><td>vector of pointers to the input items, one entry per input stream </td></tr>
<tr><td class="paramname">output_items</td><td>vector of pointers to the output items, one entry per output stream</td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd>number of items actually written to each output stream, or -1 on EOF. It is OK to return a value less than noutput_items. -1 <= return value <= noutput_items</dd></dl>
<p>general_work must call consume or consume_each to indicate how many items were consumed on each input stream. </p>
<p>Reimplemented from <a class="el" href="structgr__block.html#adf59080d10f322e3816b7ac8f7cb2a7c">gr_block</a>.</p>
</div>
</div>
<hr/><h2>Friends And Related Function Documentation</h2>
<a class="anchor" id="aa003d0cd01695c642d48ec5f6b260921"></a><!-- doxytag: member="gr_skiphead::gr_make_skiphead" ref="aa003d0cd01695c642d48ec5f6b260921" args="(size_t itemsize, uint64_t nitems_to_skip)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="gr__core__api_8h.html#a8b8937b0c61edd85ab57ce8203543248">GR_CORE_API</a> <a class="el" href="classboost_1_1shared__ptr.html">gr_skiphead_sptr</a> <a class="el" href="classgr__skiphead.html#aa003d0cd01695c642d48ec5f6b260921">gr_make_skiphead</a> </td>
<td>(</td>
<td class="paramtype">size_t </td>
<td class="paramname"><em>itemsize</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="stdint_8h.html#aec6fcb673ff035718c238c8c9d544c47">uint64_t</a> </td>
<td class="paramname"><em>nitems_to_skip</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td><code> [friend]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="gr__skiphead_8h_source.html">gr_skiphead.h</a></li>
</ul>
</div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="classgr__skiphead.html">gr_skiphead</a> </li>
<li class="footer">Generated on Mon Oct 14 2013 11:58:20 for GNU Radio 3.6.4.2 C++ API by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html>
| aviralchandra/Sandhi | build/gr36/docs/doxygen/html/classgr__skiphead.html | HTML | gpl-3.0 | 8,657 |
from settings import CONTENT_SERVER
"""
context processor applied to all requests
"""
def settings_cp(request):
return {'content_server': CONTENT_SERVER}
| elifeasley/metacademy-application | app_server/context_processors/global_cp.py | Python | gpl-3.0 | 160 |
/**
* \file IMP/rmf/geometry_io.h
* \brief Handle read/write of geometry data from/to files.
*
* Copyright 2007-2017 IMP Inventors. All rights reserved.
*
*/
#ifndef IMPRMF_GEOMETRY_IO_H
#define IMPRMF_GEOMETRY_IO_H
#include <IMP/rmf/rmf_config.h>
#include <IMP/display/declare_Geometry.h>
#include <RMF/NodeHandle.h>
#include <RMF/FileHandle.h>
IMPRMF_BEGIN_NAMESPACE
/** \name Geometry I/O
The geometry I/O support currently handles geometry composed of
- IMP::display::SegmentGeometry
- IMP::display::CylinderGeometry
- IMP::display::SphereGeometry
Other types can be supported when requested. Be aware, many
more complex geometry types are automatically decomposed into
the above types and are so, more or less, supported.
@{
*/
//! Add geometries to the file.
IMPRMFEXPORT void add_geometries(RMF::FileHandle file,
const display::GeometriesTemp &r);
//! Add geometries to a given parent node.
IMPRMFEXPORT void add_geometries(RMF::NodeHandle parent,
const display::GeometriesTemp &r);
//! Add geometries, assuming they do not move between frames.
/** This can be space saving compared to resaving
the constant position each frame. */
IMPRMFEXPORT void add_static_geometries(RMF::FileHandle parent,
const display::GeometriesTemp &r);
//! Add a single geometry to the file.
IMPRMFEXPORT void add_geometry(RMF::FileHandle file, display::Geometry *r);
//! Create geometry objects for the geometry nodes found in the file.
IMPRMFEXPORT display::Geometries create_geometries(RMF::FileConstHandle parent);
//! Link the passed geometry objects to corresponding ones in the file.
/** \note The geometries must be in the same order;
we don't search around for matches.
*/
IMPRMFEXPORT void link_geometries(RMF::FileConstHandle parent,
const display::GeometriesTemp &r);
/** @} */
IMPRMF_END_NAMESPACE
#endif /* IMPRMF_GEOMETRY_IO_H */
| shanot/imp | modules/rmf/include/geometry_io.h | C | gpl-3.0 | 2,040 |
<!DOCTYPE HTML>
<html>
<head>
<title>运营巡检记录</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<meta content="yes" name="apple-mobile-web-app-capable" />
<meta content="telephone=no" name="format-detection" />
<meta name="browsermode" content="application">
<meta name="renderer" content="webkit">
<link rel="stylesheet" type="text/css" href="static/css/main.css?TIMESTAMP" />
<link rel="stylesheet" type="text/css" href="static/vn/style.css?TIMESTAMP" />
<link rel="stylesheet" type="text/css" href="static/css/global.css?TIMESTAMP" />
<link rel="stylesheet" type="text/css" href="static/css/base.css?TIMESTAMP" />
<style type="text/css">
label#page-title {
height: .85rem;
background: rgba(0, 147, 245, 0.93);
color: #fff;
text-align: center;
line-height: .85rem;
font-size: 0.3rem;
z-index: 2;
}
</style>
<link rel="stylesheet" type="text/css" href="static/css/swiper.min.css?TIMESTAMP" />
<style type="text/css">body{ margin-bottom: 0;}</style>
</head>
<body class="">
<section class="g-head">
<a class="vn06 " id="back-btn" ></a>
<label id="page-title">运营巡检记录</label>
</section>
<div class="gc_tab">
<div class="gc_work1 " id="sortby">
<div class="gcw6">
<span class="gcw2">排序</span> <i class="gcw3 vn09"></i>
</div>
</div>
<div class="gc_work1 " id="filter">
<div class="gcw6">
<span class="gcw2">筛选</span> <i class="gcw3 vn09"></i>
</div>
</div>
</div>
<ul class="g-list" id="opers"></ul>
<div class="g-add vn32 actionbtn hidden" id="new-oper" onclick="MobileBridge.pageLink('$title$', 'offline://oper.new.html', 0);" href="javascript:void(0);"></div>
<script type="text/javascript" src="static/js/jquery-3.1.1.min.js?TIMESTAMP" charset="utf-8"></script>
<script type="text/javascript" src="static/js/jquery.cookie.js?TIMESTAMP" charset="utf-8"></script>
<script type="text/javascript" src="static/js/syp_v1.js?TIMESTAMP"></script>
<script type="text/javascript" src="static/js/user_permission.js?TIMESTAMP"></script>
<script type="text/javascript" src="static/js/crfs.js?TIMESTAMP" charset="utf-8"></script>
<script type="text/javascript" src="static/js/global.js?TIMESTAMP" charset="utf-8"></script>
<script type="text/javascript" src="static/js/app.js?TIMESTAMP" charset="utf-8"></script>
<script type="text/javascript"></script>
<script type="text/javascript" src="static/js/hdapi.js?TIMESTAMP"></script>
<script type="text/javascript" src="static/js/crfs.js?TIMESTAMP"></script>
<script type="text/javascript">
var resultHandler = undefined;
var goBackHandler = undefined;
var mymessagesHandler = undefined;
var load_more_handler = undefined;
var user_process_permissions_handler=undefined;
(function ($) {
if(userinfo.permissions.indexOf("/cre-app/operInspect/create") < 0) {
$("#new-oper").remove();
}
$.each(['show', 'hide'], function (i, ev) {
var el = $.fn[ev];
$.fn[ev] = function () {
this.trigger(ev);
return el.apply(this, arguments);
};
});
})(jQuery);
var dH = 0,wH = 0;
$('#back-btn').click(function(e){
e.preventDefault();
goBack()
});
function goBack()
{
if(typeof goBackHandler === 'function')
{
goBackHandler();
}
else
window.history.back();
}
function scanResult(message)
{
if(typeof resultHandler === 'function')
{
resultHandler(message);
}
}
function get_value(val)
{
if(val)
return val.toString();
if($.isNumeric(val))
return val.toString();
return '';
}
function get_clean_category_name(category) {
var names={
clean:"清洁",
garbageRemoval:"垃圾清理",
materialSupplement:"物资补充",
other:"其它",
}
if(category!=undefined)
{
return names[category.cleanClass]+get_value(category.fineClass);
}
return "";
}
function get_source_type_name(code) {
var names={
tenant:"商户",
department:"部门"
}
return names[code];
}
function intval(val)
{
return val - 0;
}
function get_area_type_name(code) {
var names={
publicArea:"公区",
rentArea:"租区"
}
return names[code];
}
function get_task_type_name(code) {
var names={
wrokRecordCard:"工作记录卡",
cleanWorkRecord:"保洁工单"
}
return names[code];
}
function get_emergency_type_name(code) {
var names={
dangerous:"危险",
urgent:"紧急",
general:"一般",
reservation:"预约",
postComplement:"后补工咭",
}
return names[code];
}
function get_bill_type_name(code)
{
var names={
"oper.maintainBill":"维修单",
"oper.complaintBill":"投诉单",
"property.device.inspect":"设备巡视单",
"wrokRecordCard":"工作记录卡",
"cleanWorkRecord":"保洁工单",
"investment.tenant.contract_newer":"新合同申请",
"sales.salesInput":"销售数据录入单",
}
return names[code];
}
function get_biz_type_name(code) {
var names={
ineffect:"未生效",
effect:"已生效(待办)",
canceled:"已取消",
delivered:"已转交",
solved:"已解决",
finished:"已完成",
started:"已发起",
}
return names[code];
}
function get_now_full(withoutseconds)
{
var now = new Date();
var month =now.getMonth() -0 +1;
var day =now.getDate() -0 ;
var hours =now.getHours() -0 ;
var minutes =now.getMinutes() -0 ;
var seconds =now.getSeconds() -0 ;
if(month< 10)
month = "0"+month;
if(day< 10)
day = "0"+day;
if(hours< 10)
hours = "0"+hours;
if(minutes< 10)
minutes = "0"+minutes;
if(seconds< 10)
seconds = "0"+seconds;
if(withoutseconds)
return now.getFullYear()+"-"+month+"-"+day+' '+hours+":"+minutes;
return now.getFullYear()+"-"+month+"-"+day+' '+hours+":"+minutes+":"+seconds;
}
function format_hd_time(datetime, addsecond) {
if(addsecond)
return datetime.replace('T',' ').replace(/\-/g,'.')+':00';
return datetime.replace('T',' ').replace(/\-/g,'.');
}
function start_with(str, needle)
{
if(str.length < needle.length)
return false;
return str.substr(0, needle.length) == needle;
}
function get_day_format()
{
var date = new Date();
var dayNames=[
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
];
var y = date.getFullYear(),
m = date.getMonth()+1,
d = date.getDate(),
w = date.getDay();
if(m < 10)
m = "0"+m;
if(d < 10)
d = "0"+d;
return {
date: y+"-"+m+"-"+d,
day:dayNames[w]
};
}
function get_date_format(date)
{
var mdate = new Date(date);
var y = mdate.getFullYear(),
m = mdate.getMonth()+1,
d = mdate.getDate(),
w = mdate.getDay();
if(m < 10)
m = "0"+m;
if(d < 10)
d = "0"+d;
return y+"-"+m+"-"+d;
}
function save_storage(key, value)
{
window.localStorage[key]=JSON.stringify(value);
}
function get_storage(key)
{
var value = window.localStorage[key];
try
{
return JSON.parse(value);
}
catch(err)
{
value = undefined;
}
}
function remove_storage(key)
{
window.localStorage.removeItem(key);
}
function update_height()
{
dH = $(document).height();
}
function convertDataURLToBlob(dataURL)
{
var arr = dataURL.split(',');
var code = window.atob(arr[1]);
var aBuffer = new window.ArrayBuffer(code.length);
var uBuffer = new window.Uint8Array(aBuffer);
for(var i = 0; i < code.length; i++)
{
uBuffer[i] = code.charCodeAt(i);
}
var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder;
if(Builder)
{
var builder = new Builder;
builder.append(aBuffer);
return builder.getBlob(format);
}
else
{
// return new window.Blob([ uBuffer ]);
return new window.Blob([ aBuffer ], {type: arr[0].match(/:(.*?);/)[1]});
}
}
function changeBlobImageQuality(blob, callback, format, quality)
{
format = format || 'image/jpeg';
quality = quality || 0.6; // 经测试0.9最合适
var fr = new FileReader();
fr.onload = function(e)
{
var dataURL = e.target.result;
var img = new Image();
img.onload = function()
{
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var oldWidth = img.width;
var oldHeight = img.height;
var newWidth = img.width;//window.screen.width;
var newHeight = Math.floor(oldHeight / oldWidth * newWidth);
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
// ctx.drawImage(img, 0, 0);
var newDataURL = canvas.toDataURL(format, quality);
if(callback) callback(convertDataURLToBlob(newDataURL), img);
canvas = null;
};
img.src = dataURL;
};
fr.readAsDataURL(blob); // blob 转 dataURL
function dataURLtoBlob(dataurl)
{
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
len = bstr.length,
u8arr = new Uint8Array(len);
while (len--) u8arr[len] = bstr.charCodeAt(len);
return new Blob([u8arr], {type: mime});
}
}
function get_attachment_url(itemid)
{
return $.HDAPI.server + '/HDMediaService-web/fileget?fileID='+itemid;
}
function downscaleImage(dataUrl, newWidth, imageType, imageArguments) {
"use strict";
var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
// Provide default values
imageType = imageType || "image/jpeg";
imageArguments = imageArguments || 0.7;
// Create a temporary image so that we can compute the height of the downscaled image.
image = new Image();
image.src = dataUrl;
oldWidth = image.width;
oldHeight = image.height;
newHeight = Math.floor(oldHeight / oldWidth * newWidth)
// Create a temporary canvas to draw the downscaled image on.
canvas = document.createElement("canvas");
canvas.width = newWidth;
canvas.height = newHeight;
var ctx = canvas.getContext("2d");
// Draw the downscaled image on the canvas and return the new data URL.
ctx.drawImage(image, 0, 0, newWidth, newHeight);
newDataUrl = canvas.toDataURL(imageType, imageArguments);
return newDataUrl;
}
function formatDate(date) {
var d = new Date(date);
var seconds = d.getSeconds();
var minutes = d.getMinutes();
var day = d.getDate();
var month = d.getMonth();
var hours = d.getHours();
var year = d.getFullYear();
if(seconds < 10)
seconds = '0'+seconds;
if(minutes < 10)
minutes = '0'+minutes;
if(day < 10)
day = '0'+day;
if(hours < 10)
hours = '0'+hours;
month = month - 0 + 1;
if(month < 10)
month = '0'+ month;
return year+'-'+month+'-'+day+' '+hours+':'+minutes+':'+seconds;
}
function formatNumber(num)
{
if(num===undefined)
return "";
if(num==="")
return "";
if(num==null)
return "";
return +(Math.round(num + "e+2") + "e-2");
}
function checkMobile(sMobile){
/**
* 手机号码:
* 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
* 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
* 联通号段: 130,131,132,155,156,185,186,145,176,1709
* 电信号段: 133,153,180,181,189,177,1700
*/
if((/^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$/.test(sMobile)))
return true;
/**
* 中国移动:China Mobile
* 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
*/
if((/(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\d{8}$)|(^1705\d{7}$)/.test(sMobile)))
return true;
/**
* 中国联通:China Unicom
* 130,131,132,155,156,185,186,145,176,1709
*/
if((/(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\d{8}$)|(^1709\d{7}$)/.test(sMobile)))
return true;
/**
* 中国电信:China Telecom
* 133,153,180,181,189,177,1700
*/
if((/(^1(33|53|77|8[019])\d{8}$)|(^1700\d{7}$)/.test(sMobile)))
return true;
return false;
}
function compress_upload_image(file, callback)
{
if (file) {
changeBlobImageQuality(file, function(newBlob, image){
var data = new FormData();
if (newBlob) {
var uploadFile = new File( [newBlob], file.name, {type: newBlob.type});
data.append('file', newBlob, file.name);
$.ajax({
url: $.HDAPI.server + '/cre-agency-app-server/rest/1/media/upload/',
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "JSON",
type: 'POST',
}).done(function(result){
if(result.success)
{
var img = {
id: result.body,
name: file.name,
size: file.size,
fileType: file.type,
md5: null
};
if( (callback) && (typeof callback === 'function') )
callback(img, image);
}
else
{
if( (callback) && (typeof callback === 'function') )
callback(false, image);
}
});
}
});
}
}
$(function(){
$('.timepicker').click(function(e){
$(this).find('input[type="date"], input[type="datetime-local"]').focus();
});
$('.actionbtn').click(function(e){
var next = $(this).attr('href');
if(next !=undefined && next !='' && next.indexOf('javascript:void(0)') < 0) {
goto_url("//");
// window.location=next;
}
});
$('#leftbutton').click(function(e){
e.preventDefault();
});
var _no_more = '<li style="line-height: 4rem; text-align: center; font-size: 1rem; color: #717171;">没有更多啦</li>';
$(document).ready(function(){
dH = $(document).height();
wH = $(window).height();
});
$(window).scroll(function(){
var offset_top = $(this).scrollTop();
if( dH-offset_top-wH<20){
if(typeof load_more_handler === 'function')
load_more_handler();
}
});
var process_permissions=[];
$.HDAPI.query_user_process_permissions({
userId: userinfo.code,
prefixs:[
// 'investment.tenant.contract_newer',
// 'sales.salesinput',
// 'oper.maintainBill',
// 'oper.complaintBill',
// 'property.device.inspect.register',
// 'property.device.repair',
// 'property.operInspect.inspect',
'',
]
}, function(result){
if(result.success)
{
if(typeof user_process_permissions_handler === 'function')
{
process_permissions=result.body;
user_process_permissions_handler(result.body);
}
}
});
$.HDAPI.getUserMessages( userinfo.code, function(result){
if(result.success)
{
if(typeof mymessagesHandler === 'function')
{
mymessagesHandler(result.body);
}
}
else
{
if(typeof mymessagesHandler === 'function')
showMessage(result.message);
}
});
if($("footer a").length==3) {
$("footer a").css("width","33.333%")
}else if($("footer a").length==2) {
$("footer a").css("width","50%")
}
});
</script>
<script type="text/javascript">
$(function(){
m_loading.html();//loading 启动
resultHandler = function(message){
};
goBackHandler = function (argument) {
goto_url("/");
}
if(userinfo.permissions.indexOf("/cre-app/operInspect/create") >= 0) {
user_process_permissions_handler=function(permissions){
for(perm in permissions)
{
if(start_with(permissions[perm], 'property.operInspect.inspect'))
{
$('#new-oper').removeClass('hidden');
break;
}
}
};
}
$(".g-tab div").click(function(){
swiper.slideTo($(this).index());
});
var orderby={
field:'createInfo.time',
direction:'desc'
};
var bizState = '.all';
$("#sortby").click(function(){
gcw.html(orderby.direction, function(order){
if(orderby.direction != order)
{
orderby.direction = order;
query_opers(0);
}
});
});
//等级
$("#filter").click(function(){
yy_state.html(bizState, function(state){
if(bizState != state)
{
bizState = state;
query_opers(0);
}
});
});
function setup_hooks()
{
$('.oper-item').click(function(e){
var oper = $(this).data('oper');
save_storage('oper', oper);
goto_url("oper.view.html");
});
}
function adon(index){
$(".g-tab").find("div").eq(index).addClass("on").siblings("div").removeClass("on");
}
function create_oper_item(oper, overtime)
{
var images={
ineffect:"static/images/ineffect.png",
dealing:"static/images/dealing.png",
finished: "static/images/finished.png",
solved:"static/images/solved.png",
};
if(oper.bizState == 'dealing' && oper.expectTime<format_hd_time(get_now_full()))
{
images={
ineffect:"static/images/ineffect.png",
dealing:"static/images/dealing.overtime.png",
finished: "static/images/finished.png",
solved:"static/images/solved.png",
};
}
//updatecynthia
if((oper.bizState == 'solved') && oper.endTime>oper.expectTime )
{
images={
ineffect:"static/images/ineffect.png",
dealing:"static/images/dealing.png",
finished: "static/images/finished.png",
solved:"static/images/solved.overtime.png"
};
}
//updatecynthia
if((oper.bizState == 'finished') && oper.endTime>oper.expectTime )
{
images={
ineffect:"static/images/ineffect.png",
dealing:"static/images/dealing.png",
finished: "static/images/finished.overtime.png",
solved:"static/images/solved.png"
};
}
var item = $('<li class="oper-item"></li>');
$(item).append('<div class="side_img"><img src="'+images[oper.bizState]+'"/></div>');
$(item).append('<div class="g-list-title jm_1">'+oper.inspectTopic+'</div>');
if(oper.inspector)
$(item).append('<div class="g-list-text">巡检人:'+oper.inspector.name+'</div>');
else
$(item).append('<div class="g-list-text">巡检人:</div>');
$(item).append('<div class="g-list-text">巡检时间:'+oper.createInfo.time+'</div>');
$(item).append('<div class="g-list-text">单号:'+oper.billNumber+'</div>');
$(item).append('<div class="vn05 g-list-yjt"></div>');
$(item).data('oper', oper);
return item;
}
function add_item_to_list(oper, overtime)
{
// if(overtime)
// {
// if(oper.expectTime >= oper.endTime)
// return;
// }
$('#opers').append(create_oper_item(oper, overtime));
}
var curpage = undefined;
var can_loading = true;
load_more_handler = function(){
var page = undefined;
if(curpage == undefined )
page = 0;
else
page = curpage -0 + 1;
if(can_loading)
{
query_opers(page);
}
};
function query_opers(page){
var state = bizState.split('.')[0];
var overtime = bizState.split('.')[1]=='overtime';
if(state=='')
state = undefined;
var data = {
pageSize: 10,
page: page,
order: orderby,
bizState:state,
userGroups:userGroups,
stores: stores_uuids,
};
if(page == 0)
$('#opers').children().remove();
can_loading = false;
$.HDAPI.query_oper_inspect(data, function(result){
if(result.success)
{
m_loading.remove();//loading 移除
$(result.body.records).each(function(idx, device){
add_item_to_list(device, overtime);
});
setup_hooks();
curpage = page;
can_loading = (result.body.pageCount-1 != page);
}else
{
m_loading.remove();//loading 移除
showMessage(result.message);
}
update_height();
});
}
query_opers(0);
});
</script>
</body>
</html>
| jay16/pm-bi | public/modules/hd_cre/opers.html | HTML | gpl-3.0 | 22,219 |
#ifndef TRSCRIPT_H
#define TRSCRIPT_H
// trscript.h
// 9/20/2014 jichi
#include "sakurakit/skglobal.h"
#include <string>
class TranslationScriptPerformerPrivate;
class TranslationScriptPerformer
{
SK_CLASS(TranslationScriptPerformer)
SK_DISABLE_COPY(TranslationScriptPerformer)
SK_DECLARE_PRIVATE(TranslationScriptPerformerPrivate)
// - Construction -
public:
TranslationScriptPerformer();
~TranslationScriptPerformer();
// Initialization
/// Return the number of loaded rules
int size() const;
/// Return whether the script has been loaded, thread-safe
bool isEmpty() const;
/// Clear the loaded script
void clear();
/// Add script from file
bool loadScript(const std::wstring &path);
// Replacement
// Rewrite the text according to the script, thread-safe
std::wstring transform(const std::wstring &text, int category = -1, bool mark = false) const;
// Render option
//std::wstring linkStyle() const;
//void setLinkStyle(const std::wstring &css);
};
#endif // TRSCRIPT_H
| Dangetsu/vnr | Frameworks/Sakura/cpp/libs/trscript/trscript.h | C | gpl-3.0 | 1,033 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>GNU Radio 7f75d35b C++ API: OFDM Blocks</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 7f75d35b C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('group__ofdm__blk.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> </div>
<div class="headertitle">
<div class="title">OFDM Blocks</div> </div>
<div class="ingroups"><a class="el" href="group__block.html">GNU Radio C++ Signal Processing Blocks</a></div></div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__ofdm__bpsk__demapper.html">gr_ofdm_bpsk_demapper</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">take a vector of complex constellation points in from an FFT and demodulate to a stream of bits. Simple BPSK version. <a href="classgr__ofdm__bpsk__demapper.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classgr__ofdm__frame__sink2.html">gr_ofdm_frame_sink2</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Takes an OFDM symbol in, demaps it into bits of 0's and 1's, packs them into packets, and sends to to a message queue sink.NOTE: The mod input parameter simply chooses a pre-defined demapper/slicer. Eventually, we want to be able to pass in a reference to an object to do the demapping and slicing for a given modulation type. <a href="classgr__ofdm__frame__sink2.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__dvbt__ofdm__frame__sink.html">digital_dvbt_ofdm_frame_sink</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Specific class for DVBT OFDM demmaping. Takes an OFDM symbol in, demaps it into bits of 0's and 1's, packs them into packets, and sends to to a message queue sink.NOTE: The mod input parameter simply chooses a pre-defined demapper/slicer. Eventually, we want to be able to pass in a reference to an object to do the demapping and slicing for a given modulation type. <a href="classdigital__dvbt__ofdm__frame__sink.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__dvbt__ofdm__mapper__bcv.html">digital_dvbt_ofdm_mapper_bcv</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Specific class for the DVBT.Takes a stream of bytes in and maps to a vector of complex constellation points suitable for IFFT input to be used in an ofdm modulator. Abstract class must be subclassed with specific mapping. <a href="classdigital__dvbt__ofdm__mapper__bcv.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__ofdm__cyclic__prefixer.html">digital_ofdm_cyclic_prefixer</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">adds a cyclic prefix vector to an input size long ofdm symbol(vector) and converts vector to a stream output_size long. <a href="classdigital__ofdm__cyclic__prefixer.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__ofdm__frame__acquisition.html">digital_ofdm_frame_acquisition</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">take a vector of complex constellation points in from an FFT and performs a correlation and equalization.This block takes the output of an FFT of a received OFDM symbol and finds the start of a frame based on two known symbols. It also looks at the surrounding bins in the FFT output for the correlation in case there is a large frequency shift in the data. This block assumes that the fine frequency shift has already been corrected and that the samples fall in the middle of one FFT bin. <a href="classdigital__ofdm__frame__acquisition.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__ofdm__frame__sink.html">digital_ofdm_frame_sink</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Takes an OFDM symbol in, demaps it into bits of 0's and 1's, packs them into packets, and sends to to a message queue sink.NOTE: The mod input parameter simply chooses a pre-defined demapper/slicer. Eventually, we want to be able to pass in a reference to an object to do the demapping and slicing for a given modulation type. <a href="classdigital__ofdm__frame__sink.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__ofdm__insert__preamble.html">digital_ofdm_insert_preamble</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">insert "pre-modulated" preamble symbols before each payload. <a href="classdigital__ofdm__insert__preamble.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__ofdm__mapper__bcv.html">digital_ofdm_mapper_bcv</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">take a stream of bytes in and map to a vector of complex constellation points suitable for IFFT input to be used in an ofdm modulator. Abstract class must be subclassed with specific mapping. <a href="classdigital__ofdm__mapper__bcv.html#details">More...</a><br/></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classdigital__ofdm__sampler.html">digital_ofdm_sampler</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">does the rest of the OFDM stuff <a href="classdigital__ofdm__sampler.html#details">More...</a><br/></td></tr>
</table>
</div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="footer">Generated on Thu Sep 27 2012 10:49:29 for GNU Radio 7f75d35b C++ API by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html>
| katsikas/gnuradio | build/docs/doxygen/html/group__ofdm__blk.html | HTML | gpl-3.0 | 8,101 |
# encoding: utf-8
class System::Admin::SocialUpdates::AttachFilesController < Gis::Controller::Admin::Base
include System::Controller::Scaffold
include System::Controller::Admin::Auth
layout "admin/gis/inline"
def initialize_scaffold
Page.title = "更新情報添付ファイル管理"
return authentication_error(403) unless Core.user.has_auth?(:manager)
@is_role_admin = Core.user.has_auth?(:manager)
if @is_role_admin==true
@p_group_id = nz(params[:p_group_id],0)
else
@p_group_id = nz(params[:p_group_id],Site.user_group.id)
end
@model = Misc::SocialUpdatePhotos
@parent_model = params[:model_name]
end
def index
item = Misc::SocialUpdatePhotos.new#.readable
item.and :tmp_id , params[:social_update_id]
item.and :model_name, @parent_model
@items = item.find(:all)
@item = Misc::SocialUpdatePhotos.new({
:tmp_id => params[:social_update_id],
:model_name => @parent_model
})
_index @items
end
def new
@item = Misc::SocialUpdatePhotos.new({
:tmp_id => params[:social_update_id],
:model_name => @parent_model
})
end
def create
@item = Misc::SocialUpdatePhotos.new()
@item.tmp_id = params[:social_update_id]
if @item.save_with_file(params[:item])
flash[:notice] = "ファイルを登録しました。"
else
flash[:notice] = "ファイルの登録に失敗しました。"
end
return redirect_to url_for(:action => :index, :model_name=>@item.model_name)
end
def destroy
@item = Misc::SocialUpdatePhotos.where(:id => params[:id]).first
return http_error(404) if @item.blank?
return authentication_error(403) unless @item.deletable?
@item.destroy
flash[:notice] = "ファイルを削除しました。"
return redirect_to url_for(:action => :index, :model_name=>@item.model_name)
end
end
| joruri/joruri-maps | app/controllers/system/admin/social_updates/attach_files_controller.rb | Ruby | gpl-3.0 | 1,886 |
// list of points object, map_type dependant
// fields:
// .pt_index
// .pt
var river_points = [];
var current_parcours_id;
var current_deb; // debarquement (1) ou embarquement (0)
var current_river_obj;
/* Creates a point object */
function Point(lat,lon,previous_pt) {
this.lat = lat; // latitude in decimal degrees
this.lon = lon; // longitude in decimal degrees
//[optional] ele : elevation in m
//[optional] elelbl : elevation label
if(typeof(previous_pt)=='undefined') {
this.dist = 0.0;
}
else {
//console.log('plat='+previous_pt.lat);
this.dist = previous_pt.dist + geodeticDist(previous_pt.lat,previous_pt.lon,lat,lon);
}
//console.log('thisdist='+this.dist);
}
function getRiver(name) {
$.getJSON('/river/'+name, loadRiverToMap).fail(function(err){$("#svrresponse").html(err.responseText);});
}
function nextRiver(name) {
console.log('nextRiver');
}
function prevRiver(name) {
console.log('prevRiver');
}
function setEmbDeb(elem,river,parcours_id,deb) {
$(".emb_deb").css("color","black");
elem.style.color = 'red';
current_parcours_id=parcours_id;
current_deb=deb;
console.log('setEmbDeb(%s,%d,%d)',river,parcours_id,deb);
}
function setEmb(elem,river,parcours_id) {
setEmbDeb(elem,river,parcours_id,0);
}
function setDeb(elem,river,parcours_id) {
setEmbDeb(elem,river,parcours_id,1);
}
function save() {
$.get('/flush',function(){$("#svrresponse").html('OK');}).fail(function(err){$("#svrresponse").html(err.responseText);});
}
function search_river(evt,river_name) {
if(evt.keyCode==13) { // Enter
getRiver(river_name);
}
else if(evt.keyCode==40) { // Down
nextRiver(river_name);
}
else if(evt.keyCode==38) { // Up
prevRiver(river_name);
}
}
function selPathsChange() {
var i;
var sel=$('input[name=paths_sel]');
for(i=0;i<sel.length;i++) {
toogleRiverPath(i,sel[i].checked);
}
}
function splitPaths() {
if ($('#split_btn').attr('value')==='Apply split') {
var i;
var sel=$('input[name=paths_sel]');
var names=[];
for(i=0;i<sel.length;i++) {
names.push($('#path'+i+'_name').val());
}
console.log("names=%o",names);
$.getJSON('/split_paths/'+current_river_obj._id+'/'+names.join('^'),
function(river_obj){
$("#svrresponse").html('OK');
clearMapObjects();
$("#river_name_input").attr('value','');
}).fail(function(err){$("#svrresponse").html(err.responseText);});
} else {
var i;
var sel=$('input[name=paths_sel]');
var html='';
for(i=0;i<sel.length;i++) {
html += 'Path'+i+'<input type="text" id="path'+i+'_name" name="path'+i+'_name" value="'+current_river_obj._id+'"/>';
}
$('#split_btn').attr('value','Apply split');
$('#split_names').html(html);
}
}
function removeUnselectedPaths() {
var i;
var sel=$('input[name=paths_sel]');
to_remove_list = [];
for(i=0;i<sel.length;i++) {
if (!sel[i].checked) {
to_remove_list.push(i);
}
}
$.getJSON('/remove_paths/'+current_river_obj._id+'/'+to_remove_list.join(','),
function(river_obj){
$("#svrresponse").html('OK');
loadRiverToMap(river_obj);
}).fail(function(err){$("#svrresponse").html(err.responseText);});
}
function mergeSelectedPaths() {
var i;
var sel=$('input[name=paths_sel]');
var to_merge_list = [];
for(i=0;i<sel.length;i++) {
if (sel[i].checked) {
to_merge_list.push(i);
}
}
console.log("to_merge_list=%o",to_merge_list);
if(to_merge_list.length!=2) {
$("#svrresponse").html('Error: Can only merge two paths');
} else {
// Try to merge consecutive paths
var d1 = geodeticDist(current_river_obj.osm.paths[to_merge_list[0]][0][0],
current_river_obj.osm.paths[to_merge_list[0]][0][1],
current_river_obj.osm.paths[to_merge_list[1]][current_river_obj.osm.paths[to_merge_list[1]].length-1][0],
current_river_obj.osm.paths[to_merge_list[1]][current_river_obj.osm.paths[to_merge_list[1]].length-1][1]);
var d2 = geodeticDist(current_river_obj.osm.paths[to_merge_list[1]][0][0],
current_river_obj.osm.paths[to_merge_list[1]][0][1],
current_river_obj.osm.paths[to_merge_list[0]][current_river_obj.osm.paths[to_merge_list[0]].length-1][0],
current_river_obj.osm.paths[to_merge_list[0]][current_river_obj.osm.paths[to_merge_list[0]].length-1][1]);
console.log('d1='+d1+' d2='+d2);
if ((d1>1000)&&(d2>1000)) {
$("#svrresponse").html('Error: Paths are more than 1km one from another');
} else {
if (d1<d2) {
$.getJSON('/merge_paths_a_after_b/'+current_river_obj._id+'/'+to_merge_list[0]+'/'+to_merge_list[1],
function(river_obj){
$("#svrresponse").html('OK');
loadRiverToMap(river_obj);
}).fail(function(err){$("#svrresponse").html(err.responseText);});
} else {
$.getJSON('/merge_paths_a_after_b/'+current_river_obj._id+'/'+to_merge_list[1]+'/'+to_merge_list[0],
function(river_obj){
$("#svrresponse").html('OK');
loadRiverToMap(river_obj);
}).fail(function(err){$("#svrresponse").html(err.responseText);});
}
}
}
/*
var j;
var to_merge_commands = [];
while(1) {
// Get closest paths
var min_d = 1000;
var min_a = -1;
var min_b = -1;
for(i=0;i<to_merge_list.length;i++) {
for(j=0;j<to_merge_list.length;j++) {
console.log("%o %o %o",current_river_obj.osm.paths,to_merge_list,i);
//to_merge_list is bijective
if ((i!=j)&&(typeof(current_river_obj.osm.paths[to_merge_list[i]]!=='undefined'))&&(typeof(current_river_obj.osm.paths[to_merge_list[j]]!=='undefined'))) {
var d = geodeticDist(current_river_obj.osm.paths[to_merge_list[i]][0][0],
current_river_obj.osm.paths[to_merge_list[i]][0][1],
current_river_obj.osm.paths[to_merge_list[j]][current_river_obj.osm.paths[to_merge_list[j]].length-1][0],
current_river_obj.osm.paths[to_merge_list[j]][current_river_obj.osm.paths[to_merge_list[j]].length-1][1]);
if (d<min_d) {
min_d = d;
min_a = to_merge_list[i];
min_b = to_merge_list[j];
}
}
}
}
if (min_d<1000) {
current_river_obj.osm.paths[min_b].push.apply(current_river_obj.osm.paths[min_b], current_river_obj.osm.paths[min_a]);
delete current_river_obj.osm.paths[min_a];
to_merge_commands.push([min_a,min_b]);
to_merge_list.splice(
}
else {
break;
}
}
var nbpaths_of_to_merge_list = 0;
for(i=0;i<nbpaths_of_to_merge_list.length;i++) {
if (typeof(current_river_obj.osm.paths[to_merge_list[i]]!=='undefined')) {
nbpaths_of_to_merge_list += 1;
}
}
if (nbpaths_of_to_merge_list==1) {
console.log(to_merge_commands);
} else {
$("#svrresponse").html('Cannot find consecutive paths in selected list');
}*/
}
function routeCkFiumi2Html(r) {
return '<a href="'+r.src_url+'" target="_blank">' + r.name + '</a> (' + r.wwgrade + ',' + r.length + 'km,' + r.duration + 'h)'
+ '<ul><li><b>Start:</b> ' + r.start + '</li><li><b>End:</b> ' + r.end + '</li></ul>';
}
function dispDist(d) {
if (d>1000.0) {
return Math.round(d/1000.0) + ' km';
}
else return Math.round(d) + ' m';
}
function loadRiverToMap(river_obj) {
console.log(river_obj);
clearMapObjects();
current_river_obj = river_obj;
// Names
$("#river_name_evo").html('name_evo' in river_obj?(river_obj['name_evo']+' ('+river_obj.evo.length+')'):'/');
$("#river_name_rivermap").html('name_rivermap' in river_obj?(river_obj['name_rivermap']+' ('+river_obj.rivermap.length+')'):'/');
$("#river_name_ckfiumi").html('name_ckfiumi' in river_obj?(river_obj['name_ckfiumi']+' ('+river_obj.ckfiumi.length+')'):'/');
// OSM
river_points = [];
var i;
var j;
var pts=[];
var pathshtml='';
for(i=0;i<river_obj.osm.paths.length;i++) {
pathshtml += ' <span ondblclick="zoomToPath('+i+');" onmouseover="highlightPath(this,'+i+');" onmouseout="unhighlightPath(this,'+i+');"><input type="checkbox" name="paths_sel" value="path'+i+'" onclick="selPathsChange();" checked> Path #'+i+'</span>';
pts[i]=[];
var lg = 0.0;
for(j=0;j<river_obj.osm.paths[i].length;j++) {
pts[i][j] = {"lat": river_obj.osm.paths[i][j][0], "lng": river_obj.osm.paths[i][j][1], "lon": river_obj.osm.paths[i][j][1]};
if (j<river_obj.osm.paths[i].length-1) {
lg += geodeticDist(river_obj.osm.paths[i][j][0],river_obj.osm.paths[i][j][1],river_obj.osm.paths[i][j+1][0],river_obj.osm.paths[i][j+1][1]);
}
}
pathshtml += ' (' + dispDist(lg) + ')';
}
pathshtml += '<input type="button" value="Merge selected" onclick="mergeSelectedPaths();"> <input type="button" value="Remove unselected" onclick="removeUnselectedPaths();"> <input type="button" id="split_btn" value="Split all" onclick="splitPaths();"><span id="split_names"></span>';
$("#paths").html(pathshtml);
addRiverPaths(pts);
// Evo
if ("evo" in river_obj) {
var html='';
for(i=0;i<river_obj.evo.length;i++) {
html += '<h2>EVO</h2><span class="source">(<a href="'+river_obj.evo[i].src_url+'" target="_blank">source</a>)</span>';
if ("presentation" in river_obj.evo[i]) {
html += '<h3>Presentation</h3><p>'+river_obj.evo[i].presentation+'</p>';
}
if ("parcours" in river_obj.evo[i]) {
var k=-1;
html += '<h3>Parcours</h3><ul><li>'+river_obj.evo[i].parcours.map(function(p) { k++; return p.name + ' (' + p.cotation + ',' + p.duree + ')' + '<ul><li onClick="setEmb(this,\''+river_obj['name']+'\','+k+');" class="emb_deb">Emb:'+p.embarquement+'</li><li onClick="setDeb(this,\''+river_obj['name']+'\','+k+');" class="emb_deb">Deb:'+p.debarquement+'</li></ul>'; }).join('</li><li>')+'</li></ul>'
}
}
$("#evo").html(html);
}
// RiverMap
if ("rivermap" in river_obj) {
var html='';
for(i=0;i<river_obj.rivermap.length;i++) {
if ("routes_rivermap" in river_obj.rivermap[i]) {
var k=-1;
html += '<h2>RiverMap</h2><ul><li>'+river_obj.rivermap[i].routes_rivermap.map(function(p) { k++; return ''+k+': ' +p.name + ': ' + p.length + ' km '+p.ww_class }).join('</li><li>')+'</li></ul>'
for(k=0;k<river_obj.rivermap[i].routes_rivermap.length;k++) {
addPointRivermap(river_obj.rivermap[i].routes_rivermap[k].start,'S'+k);
addPointRivermap(river_obj.rivermap[i].routes_rivermap[k].end,'E'+k);
}
}
}
$("#rivermap").html(html);
}
// CKFiumi
if ("ckfiumi" in river_obj) {
var html='';
for(i=0;i<river_obj.ckfiumi.length;i++) {
html += '<h2>CKFiumi</h2>';
if ("regions" in river_obj.ckfiumi[i]) {
html += river_obj.ckfiumi[i].regions + ' ';
}
if ("provinces" in river_obj.ckfiumi[i]) {
html += river_obj.ckfiumi[i].provinces;
}
if ("routes_ckfiumi" in river_obj.ckfiumi[i]) {
html += '<h3>Routes</h3><ul><li>'+river_obj.ckfiumi[i].routes_ckfiumi.map(routeCkFiumi2Html).join('</li><li>')+'</li></ul>';
}
}
$("#ckfiumi").html(html);
}
}
function lg2pt(evt,lg) {
if(evt.keyCode==13) { // Enter
computelg2pt(parseInt(lg));
}
}
function computelg2pt(lg) {
if(current_river_obj.osm.paths.length!=1) {
$("#lg2pterror").html("Valid only if one path");
} else {
var i=0;
var l=0.0;
while(l<lg) {
if (i+2 > current_river_obj.osm.paths[0].length) {
$("#lg2pterror").html("Length bigger than river");
return;
}
l += geodeticDist(current_river_obj.osm.paths[0][i][0],current_river_obj.osm.paths[0][i][1],current_river_obj.osm.paths[0][i+1][0],current_river_obj.osm.paths[0][i+1][1]);
i++;
}
console.log(current_river_obj.osm.paths[0][i]);
addPoint(new Point(current_river_obj.osm.paths[0][i][0],current_river_obj.osm.paths[0][i][1]));
}
}
| fparrel/wwsupdb | static/javascript/prepare.js | JavaScript | gpl-3.0 | 13,391 |
var __v=[
{
"Id": 945,
"Chapter": 310,
"Name": "wxWizard",
"Sort": 0
}
] | zuiwuchang/king-document | data/chapters/310.js | JavaScript | gpl-3.0 | 89 |
/*
* Driver for Microtune MT2131 "QAM/8VSB single chip tuner"
*
* Copyright (c) 2006 Steven Toth <stoth@linuxtv.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __MT2131_PRIV_H__
#define __MT2131_PRIV_H__
/* Regs */
#define MT2131_PWR 0x07
#define MT2131_UPC_1 0x0b
#define MT2131_AGC_RL 0x10
#define MT2131_MISC_2 0x15
/* frequency values in KHz */
#define MT2131_IF1 1220
#define MT2131_IF2 44000
#define MT2131_FREF 16000
struct mt2131_priv
{
struct mt2131_config *cfg;
struct i2c_adapter *i2c;
u32 frequency;
};
#endif /* __MT2131_PRIV_H__ */
| williamfdevine/PrettyLinux | drivers/media/tuners/mt2131_priv.h | C | gpl-3.0 | 1,327 |
/**
* Tests of our experiment data set attributes.
*/
package test.junit.org.optimizationBenchmarking.evaluator.attributes; | optimizationBenchmarking/evaluator-attributes | src/test/java/test/junit/org/optimizationBenchmarking/evaluator/attributes/package-info.java | Java | gpl-3.0 | 128 |
package com.factory_simple.impl;
import com.factory_simple.father.Operation;
/**
* Created by zzp on 2015/12/9.
*/
public class OperateAdd extends Operation{
@Override
public double getResult() {
return getNumA() + getNumB();
}
}
| zzp0425/java_mode | src/com/factory_simple/impl/OperateAdd.java | Java | gpl-3.0 | 255 |
#include <stdio.h>
#include <samerlib/stack.h>
#include <samerlib/queue.h>
#include <samerlib/map.h>
#define TEST_MAP
int main() {
#ifdef TEST_STACK
int x, y, z, *a, i;
stack *s = new_stack();
x = 1;
y = 2;
z = 4;
for (i = 0; i < 8; i++) {
stack_push(s, &x);
}
stack_push(s, &x);
stack_push(s, &y);
stack_push(s, &z);
while ((a = (int *) stack_pop(s)) != NULL) {
printf("%d", *a);
}
printf("\n");
#endif /* TEST_STACK */
#ifdef TEST_QUEUE
int x, y, z, *a, i;
queue *q = new_queue();
x = 1;
y = 3;
z = 5;
for (i = 0; i < 4; i++) {
queue_push_right(q, &y);
}
queue_push_left(q, &x);
queue_push_right(q, &z);
printf("%d %d\n", q->start, q->end);
while ((a = (int *) queue_pop_right(q)) != NULL) {
printf("%d", *a);
}
printf("\n");
#endif /* TEST_QUEUE */
#ifdef TEST_MAP
map *m = new_map();
map_add(m, "bro", 1);
fprintf(stderr, "%p", map_get(m, "bro"));
free_map(m);
fprintf(stderr, "donezo\n");
#endif /* TEST_MAP */
return 0;
}
| samertm/samerlib | test.c | C | gpl-3.0 | 1,250 |
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component, PropTypes } from 'react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import Loading from '../Loading';
import Status from '../Status';
import Tokens from '../Tokens';
import Actions from '../Actions';
import styles from './application.css';
const muiTheme = getMuiTheme({
palette: {
primary1Color: '#27ae60'
}
});
export default class Application extends Component {
static childContextTypes = {
muiTheme: PropTypes.object
}
static propTypes = {
isLoading: PropTypes.bool.isRequired,
contract: PropTypes.object
};
render () {
const { isLoading, contract } = this.props;
if (isLoading) {
return (
<Loading />
);
}
return (
<div className={ styles.application }>
<Status
address={ contract.address }
fee={ contract.fee } />
<Actions />
<Tokens />
</div>
);
}
getChildContext () {
return {
muiTheme
};
}
}
| kushti/mpt | js/src/dapps/tokenreg/Application/application.js | JavaScript | gpl-3.0 | 1,704 |
/*
* File: main.cpp
* Author: uli
*
* WARNING: This program may be vulnerable to format string attacks
*
* Created on 29. Juli 2009, 13:13
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "lodepng.h"
#define IMGPIX(i,x,y) images[i][(y) * width + (x)] //intvalue
#define MODE_HORIZONTAL 1
#define MODE_VERTICAL 2
/*
*
*/
int main(int argc, char** argv)
{
if (argc < 5) //Vertical/horizontal + 2 images
{
printf("Not enough arguments");
printf("Usage: isect [h/v] [images]");
exit(2);
}
char** inputImageFilenames = argv + 2;
//Check which mode (horizontal/vertical) to use
char directionSpecifier[2];
int mode;
if (strcmp(argv[1], "h") == 0 || strcmp(argv[1], "horizontal") == 0) {
mode = MODE_HORIZONTAL;
strcpy(directionSpecifier, "h");
}
else if (strcmp(argv[1], "v") == 0 || strcmp(argv[1], "vertical") == 0) {
mode = MODE_VERTICAL;
strcpy(directionSpecifier, "v");
}
else {
printf("Invalid mode: %s", argv[1]);
exit(0);
}
int inputImageCount = argc - 2;
int** images = (int**) malloc(sizeof (int*) * inputImageCount);
unsigned char* buffer;
size_t imagesize, buffersize;
int width, height;
//Read all images
LodePNG_Decoder decoder;
LodePNG_Decoder_init(&decoder);
for (int i = 0; i < inputImageCount; i++) {
LodePNG_loadFile(&buffer, &buffersize, inputImageFilenames[i]);
LodePNG_decode(&decoder, (unsigned char**)(&images[i]), &imagesize, buffer, buffersize);
width = decoder.infoPng.width;
height = decoder.infoPng.height;
free(buffer);
}
//Process the images
LodePNG_Encoder encoder;
LodePNG_Encoder_init(&encoder);
LodePNG_InfoPng_copy(&encoder.infoPng, &decoder.infoPng);
LodePNG_InfoRaw_copy(&encoder.infoRaw, &decoder.infoRaw); /*the decoder has written the PNG colortype in the infoRaw too*/
//Calculate the extends of the images to be saved
int saveImageWidth = -1;
int saveImageHeight = -1;
size_t saveImageCount = -1;
if (mode == MODE_HORIZONTAL) {
saveImageHeight = width;
saveImageWidth = inputImageCount;
saveImageCount = height;
}
else if (mode == MODE_VERTICAL) {
saveImageHeight = height;
saveImageWidth = inputImageCount;
saveImageCount = width;
}
//Allocate the images array
int** saveImages = malloc(sizeof (int*) * saveImageCount);
for (int i = 0; i < inputImageCount; i++) {
saveImages[i] = malloc(sizeof (int) * saveImageWidth * saveImageHeight);
}
//Process the images
if (mode == MODE_HORIZONTAL) {
for (int i = 0; i < inputImageCount; i++) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
printf("exe i=%i y=%i x=%i\n",i,y,x);
fflush(stdout);
int x = images[i][y * width + x];
//int x = (int) images[i];
printf("\n\n%i\n\n",x);
fflush(stdout);
saveImages[y][x * inputImageCount + i] = images[i][y * width + x];
}
}
}
}
else if (mode == MODE_VERTICAL) {
for (int i = 0; i < inputImageCount; i++) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
saveImages[x][x * inputImageCount + i] = images[i][y * width + x];
}
}
}
}
//Free the input image memory
for (int i = 0; i < inputImageCount; i++) {
free(images[i]);
}
free(images);
//Write all images and free the memory
for (unsigned i = 0; i < inputImageCount; i++) {
LodePNG_encode(&encoder, &buffer, &buffersize, (unsigned char*)saveImages[i],
decoder.infoPng.width, decoder.infoPng.height);
//Construct the output filename string...
char* filenameBuffer = (char*) malloc(sizeof (char) * strlen(inputImageFilenames[i]) + 256); //256 should be enough to hold the direction specifier number
sprintf(filenameBuffer, "%s-%s-%i.png", inputImageFilenames[i], directionSpecifier, i);
//...and write the image to the associated file
LodePNG_saveFile(buffer, buffersize, filenameBuffer);
//Free the unneeded data
free(filenameBuffer);
free(saveImages[i]);
}
free(saveImages);
LodePNG_Decoder_cleanup(&decoder);
LodePNG_Encoder_cleanup(&encoder);
return (EXIT_SUCCESS);
}
| ulikoehler/xraysim | ImageSectionizer/main.c | C | gpl-3.0 | 4,654 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Sat Dec 19 22:20:09 CET 2015 -->
<title>OutgoingEmailBL (Genji Scrum Tool & Issue Tracking API Documentation 5.0.1)</title>
<meta name="date" content="2015-12-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="OutgoingEmailBL (Genji Scrum Tool & Issue Tracking API Documentation 5.0.1)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OtherSiteConfigTO.JSONFIELDS.html" title="interface in com.aurel.track.admin.server.siteConfig"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailTO.html" title="class in com.aurel.track.admin.server.siteConfig"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/aurel/track/admin/server/siteConfig/OutgoingEmailBL.html" target="_top">Frames</a></li>
<li><a href="OutgoingEmailBL.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.aurel.track.admin.server.siteConfig</div>
<h2 title="Class OutgoingEmailBL" class="title">Class OutgoingEmailBL</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.aurel.track.admin.server.siteConfig.OutgoingEmailBL</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">OutgoingEmailBL</span>
extends java.lang.Object</pre>
<div class="block">It manages handling of the server configuration for outgoing e-mail connections.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailBL.html#OutgoingEmailBL()">OutgoingEmailBL</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.List<<a href="../../../../../../com/aurel/track/util/IntegerStringBean.html" title="class in com.aurel.track.util">IntegerStringBean</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailBL.html#getSecurityConnectionsModes(java.util.Locale)">getSecurityConnectionsModes</a></strong>(java.util.Locale locale)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../com/aurel/track/util/emailHandling/SMTPMailSettings.html" title="class in com.aurel.track.util.emailHandling">SMTPMailSettings</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailBL.html#getSMTPMailSettings(com.aurel.track.beans.TSiteBean)">getSMTPMailSettings</a></strong>(<a href="../../../../../../com/aurel/track/beans/TSiteBean.html" title="class in com.aurel.track.beans">TSiteBean</a> site)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailBL.html#testOutgoingEmail(com.aurel.track.beans.TSiteBean,%20com.aurel.track.admin.server.siteConfig.OutgoingEmailTO,%20java.lang.String,%20java.util.List,%20java.util.Locale)">testOutgoingEmail</a></strong>(<a href="../../../../../../com/aurel/track/beans/TSiteBean.html" title="class in com.aurel.track.beans">TSiteBean</a> siteBean,
<a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailTO.html" title="class in com.aurel.track.admin.server.siteConfig">OutgoingEmailTO</a> outgoingEmailTO,
java.lang.String emailTestTo,
java.util.List<<a href="../../../../../../com/aurel/track/json/ControlError.html" title="class in com.aurel.track.json">ControlError</a>> errors,
java.util.Locale locale)</code>
<div class="block">This routine tries to connect to the SMTP server with the current
configuration parameters in <code>siteApp</code>, the <code>TSiteBean</code> object stored
in the application context.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="OutgoingEmailBL()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>OutgoingEmailBL</h4>
<pre>public OutgoingEmailBL()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getSMTPMailSettings(com.aurel.track.beans.TSiteBean)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getSMTPMailSettings</h4>
<pre>public static <a href="../../../../../../com/aurel/track/util/emailHandling/SMTPMailSettings.html" title="class in com.aurel.track.util.emailHandling">SMTPMailSettings</a> getSMTPMailSettings(<a href="../../../../../../com/aurel/track/beans/TSiteBean.html" title="class in com.aurel.track.beans">TSiteBean</a> site)</pre>
</li>
</ul>
<a name="testOutgoingEmail(com.aurel.track.beans.TSiteBean, com.aurel.track.admin.server.siteConfig.OutgoingEmailTO, java.lang.String, java.util.List, java.util.Locale)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>testOutgoingEmail</h4>
<pre>public static java.lang.String testOutgoingEmail(<a href="../../../../../../com/aurel/track/beans/TSiteBean.html" title="class in com.aurel.track.beans">TSiteBean</a> siteBean,
<a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailTO.html" title="class in com.aurel.track.admin.server.siteConfig">OutgoingEmailTO</a> outgoingEmailTO,
java.lang.String emailTestTo,
java.util.List<<a href="../../../../../../com/aurel/track/json/ControlError.html" title="class in com.aurel.track.json">ControlError</a>> errors,
java.util.Locale locale)</pre>
<div class="block">This routine tries to connect to the SMTP server with the current
configuration parameters in <code>siteApp</code>, the <code>TSiteBean</code> object stored
in the application context.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>siteBean</code> - </dd><dd><code>errors</code> - </dd>
<dt><span class="strong">Returns:</span></dt><dd>the protocol of the connection attempt</dd></dl>
</li>
</ul>
<a name="getSecurityConnectionsModes(java.util.Locale)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getSecurityConnectionsModes</h4>
<pre>public static java.util.List<<a href="../../../../../../com/aurel/track/util/IntegerStringBean.html" title="class in com.aurel.track.util">IntegerStringBean</a>> getSecurityConnectionsModes(java.util.Locale locale)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OtherSiteConfigTO.JSONFIELDS.html" title="interface in com.aurel.track.admin.server.siteConfig"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/aurel/track/admin/server/siteConfig/OutgoingEmailTO.html" title="class in com.aurel.track.admin.server.siteConfig"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/aurel/track/admin/server/siteConfig/OutgoingEmailBL.html" target="_top">Frames</a></li>
<li><a href="OutgoingEmailBL.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><a href="http://www.trackplus.com">Genji Scrum Tool & Issue Tracking API Documentation</a> <i>Copyright © 2015 Steinbeis Task Management Solutions. All Rights Reserved.</i></small></p>
</body>
</html>
| trackplus/Genji | docs/com/aurel/track/admin/server/siteConfig/OutgoingEmailBL.html | HTML | gpl-3.0 | 13,268 |
var class_resa___pro_1_1_formularios_1_1_agregar_solicitud =
[
[ "AgregarSolicitud", "class_resa___pro_1_1_formularios_1_1_agregar_solicitud.html#a412476c1dcd5f6c8d56fe23a6ffdf7f0", null ],
[ "Dispose", "class_resa___pro_1_1_formularios_1_1_agregar_solicitud.html#a0bb7825df5bd3bfaf1ff574ffaf92297", null ],
[ "VEmail", "class_resa___pro_1_1_formularios_1_1_agregar_solicitud.html#a82942b118e0a793b872442f768279496", null ],
[ "VerificacionFechas", "class_resa___pro_1_1_formularios_1_1_agregar_solicitud.html#a8e655cd96c4fcb124ff84095c56e0e55", null ]
]; | ezequielgm25/Resa | V1.0/Documentos/Manual del sistema/HTML/class_resa___pro_1_1_formularios_1_1_agregar_solicitud.js | JavaScript | gpl-3.0 | 571 |
/*
* pin 'em up
*
* Copyright (C) 2007-2013 by Mario Ködding
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*
*/
package net.sourceforge.pinemup.ui.swing.tray;
import net.sourceforge.pinemup.core.CategoryManager;
import net.sourceforge.pinemup.core.i18n.I18N;
import net.sourceforge.pinemup.core.model.Category;
import net.sourceforge.pinemup.ui.swing.menus.logic.CategoryMenuLogic;
import net.sourceforge.pinemup.ui.swing.menus.logic.CategoryMenuLogic.CategoryAction;
import net.sourceforge.pinemup.ui.swing.menus.logic.GeneralMenuLogic;
import net.sourceforge.pinemup.ui.swing.menus.logic.GeneralMenuLogic.GeneralAction;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.util.ArrayList;
import java.util.List;
public class TrayMenu extends PopupMenu {
private static final long serialVersionUID = 4859510599893727949L;
private Menu categoriesMenu;
private MenuItem manageCategoriesItem;
private final TrayMenuLogic trayMenuLogic;
public TrayMenu(TrayMenuLogic trayMenuLogic) {
super("pin 'em up");
this.trayMenuLogic = trayMenuLogic;
initWithNewLanguage();
}
public final void initWithNewLanguage() {
removeAll();
// add basic items
for (MenuItem item : getBasicMenuItems()) {
add(item);
}
addSeparator();
// categories menus
categoriesMenu = new Menu(I18N.getInstance().getString("menu.categorymenu"));
add(categoriesMenu);
// category actions
manageCategoriesItem = new MenuItem(I18N.getInstance().getString("menu.categorymenu.managecategoriesitem"));
manageCategoriesItem.setActionCommand(TrayMenuLogic.ACTION_MANAGE_CATEGORIES);
manageCategoriesItem.addActionListener(trayMenuLogic);
createCategoriesMenu();
// im-/export menu
addSeparator();
Menu imExMenu = new Menu(I18N.getInstance().getString("menu.notesimexport"));
MenuItem serverUploadItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.serveruploaditem"));
serverUploadItem.setActionCommand(TrayMenuLogic.ACTION_UPLOAD_TO_SERVER);
serverUploadItem.addActionListener(trayMenuLogic);
imExMenu.add(serverUploadItem);
MenuItem serverDownloadItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.serverdownloaditem"));
serverDownloadItem.setActionCommand(TrayMenuLogic.ACTION_DOWNLOAD_FROM_SERVER);
serverDownloadItem.addActionListener(trayMenuLogic);
imExMenu.add(serverDownloadItem);
imExMenu.addSeparator();
MenuItem exportItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.textexportitem"));
exportItem.setActionCommand(TrayMenuLogic.ACTION_EXPORT);
exportItem.addActionListener(trayMenuLogic);
imExMenu.add(exportItem);
add(imExMenu);
// other items
addSeparator();
MenuItem showSettingsDialogItem = new MenuItem(I18N.getInstance().getString("menu.settingsitem"));
showSettingsDialogItem.setActionCommand(TrayMenuLogic.ACTION_SHOW_SETTINGS_DIALOG);
showSettingsDialogItem.addActionListener(trayMenuLogic);
add(showSettingsDialogItem);
// help menu
Menu helpMenu = new Menu(I18N.getInstance().getString("menu.help"));
MenuItem updateItem = new MenuItem(I18N.getInstance().getString("menu.help.updatecheckitem"));
updateItem.setActionCommand(TrayMenuLogic.ACTION_CHECK_FOR_UPDATES);
updateItem.addActionListener(trayMenuLogic);
helpMenu.add(updateItem);
helpMenu.addSeparator();
MenuItem aboutItem = new MenuItem(I18N.getInstance().getString("menu.help.aboutitem"));
aboutItem.setActionCommand(TrayMenuLogic.ACTION_SHOW_ABOUT_DIALOG);
aboutItem.addActionListener(trayMenuLogic);
helpMenu.add(aboutItem);
add(helpMenu);
addSeparator();
// close item
MenuItem closeItem = new MenuItem(I18N.getInstance().getString("menu.exititem"));
closeItem.setActionCommand(TrayMenuLogic.ACTION_EXIT_APPLICATION);
closeItem.addActionListener(trayMenuLogic);
add(closeItem);
}
public void createCategoriesMenu() {
categoriesMenu.removeAll();
for (Menu m : getCategoryMenus()) {
categoriesMenu.add(m);
}
categoriesMenu.addSeparator();
categoriesMenu.add(manageCategoriesItem);
}
private List<Menu> getCategoryMenus() {
List<Menu> categoryMenus = new ArrayList<>();
for (Category cat : CategoryManager.getInstance().getCategories()) {
categoryMenus.add(createCategoryActionsMenu(cat.getName(), cat));
}
return categoryMenus;
}
private Menu createCategoryActionsMenu(String title, Category c) {
Menu menu = new Menu(title);
CategoryMenuLogic catMenuLogic = new CategoryMenuLogic(c);
int i = 0;
for (CategoryAction action : CategoryAction.values()) {
MenuItem menuItem = new MenuItem(I18N.getInstance().getString(action.getI18nKey()));
menuItem.setActionCommand(action.toString());
menuItem.addActionListener(catMenuLogic);
menu.add(menuItem);
if (i == 2) {
menu.addSeparator();
}
i++;
}
return menu;
}
private List<MenuItem> getBasicMenuItems() {
GeneralMenuLogic basicMenuLogic = new GeneralMenuLogic();
List<MenuItem> menuItems = new ArrayList<>();
for (GeneralAction action : GeneralAction.values()) {
MenuItem menuItem = new MenuItem(I18N.getInstance().getString(action.getI18nKey()));
menuItem.setActionCommand(action.toString());
menuItem.addActionListener(basicMenuLogic);
menuItems.add(menuItem);
}
return menuItems;
}
}
| mariok/pinemup | src/main/java/net/sourceforge/pinemup/ui/swing/tray/TrayMenu.java | Java | gpl-3.0 | 6,335 |
<?php
/**
*
* MySQL Class
*
* File: mysqlClass.php
* Created: 10-04-20
* $LastModified: Sex 23 Abr 2010 21:07:13 BRT
*
* See the enclosed file LICENSE for license information (GPL). If you
* did not receive this file, see http://www.gnu.org/licenses/gpl.txt.
*
* @author Rosivaldo Ramalho <rosivaldo {at} gmail.com>
* @package db
* @version 0.0.0.1-alpha
*
*/
require_once 'dbClass.php';
class mysqlClass extends dbClass {
protected function doConnect() {
$this->conn = mysql_pconnect($this->host . ':' . $this->port,
$this->user,
$this->pass);
if ( ! $this->conn) {
$this->setError(mysql_error());
throw new Exception('Connection not initialized. Error:' . $this->getError());
}
else {
$this->setError('');
mysql_select_db($this->db, $this->conn);
}
}
protected function doQuery($sql) {
if ($this->hasError())
return false;
else {
$this->doConnect();
$handler = mysql_query($sql, $this->conn);
if ( ! $handler) {
$this->setError(mysql_error());
return false;
} else {
$this->setError('');
return $handler;
}
}
}
protected function setError($text) {
$this->error = $text;
}
public function getError() {
return $this->error;
}
public function hasError() {
return ($this->error != '');
}
# TODO add a refresh flag, so if the array is completed there won't be necessary to retrieve data again
public function loadTables() {
$qryHandler = $this->doQuery("show tables");
if ($this->hasError())
throw new Exception($this->getError());
if (mysql_num_rows($qryHandler) > 0) {
if (!empty($this->tables))
unset($this->tables);
$this->tables = array();
while ($row = mysql_fetch_row($qryHandler))
array_push($this->tables, $row[0]);
}
mysql_free_result($qryHandler);
}
public function getTables() {
$this->loadTables();
return $this->tables;
}
public function getFields($table) {
$this->loadFields($table);
return $this->tables[$table];
}
# TODO add a refresh flag, so if the array is completed there won't be necessary to retrieve data again
public function loadFields($table) {
$qryHandler = $this->doQuery("show columns from " . $table);
if ($this->hasError())
throw new Exception($this->getError());
if (mysql_num_rows($qryHandler) > 0) {
if (!empty($this->tables[$table]))
unset($this->tables[$table]);
$this->tables[$table] = array();
while ($row = mysql_fetch_assoc($qryHandler))
array_push($this->tables[$table], $row);
}
mysql_free_result($qryHandler);
}
}
?>
| rosivaldo/auto-crud | src/db/mysqlClass.php | PHP | gpl-3.0 | 2,643 |
package org.sol.script.agility.course;
import org.sol.core.script.Methods;
import java.util.LinkedList;
import java.util.List;
public class Course {
private final Methods methods;
private final Courses internal;
private final LinkedList<Obstacle> obstacles;
private final boolean canBank;
private int obstacleNumber;
private boolean bankTime;
private boolean failable = false;
public Course(final Courses internal, final Methods methods) {
this.methods = methods;
this.internal = internal;
this.obstacles = new LinkedList<Obstacle>();
this.canBank = internal.getBankArea() != null;
for (final Obstacles obstacle : Obstacles.values()) {
Obstacle ob = obstacle.getObstacle();
if (ob.getCourse() == internal) {
obstacles.add(ob);
if (ob.isInArea(methods)) {
ob.state = Obstacle.State.IN_PROGRESS;
this.obstacleNumber = ob.getOrdinal();
}
}
}
}
public Obstacle getPreviousObstacle() {
return obstacleNumber > 0 ? obstacles.get(obstacleNumber - 1) : obstacles.getLast();
}
public Obstacle getCurrentObstacle() {
return obstacles.get(obstacleNumber);
}
public Obstacle getNextObstacle() {
return obstacleNumber == obstacles.size() - 1 ? obstacles.getFirst() : obstacles.get(obstacleNumber + 1);
}
public void setToPrevObstacle() {
this.obstacleNumber = obstacleNumber > 0 ? obstacleNumber - 1 : obstacles.size() - 1;
}
public void setToNextObstacle() {
this.obstacleNumber = (obstacleNumber + 1) % obstacles.size();
}
public int getObstacleNumber() {
return obstacleNumber;
}
public void setObstacleNumber(final int obstacleNumber) {
this.obstacleNumber = obstacleNumber;
}
public boolean isBankTime() {
return bankTime;
}
public void setBankTime(final boolean bankTime) {
this.bankTime = bankTime;
}
public Courses getInternal() {
return this.internal;
}
public List<Obstacle> getObstacles() {
return this.obstacles;
}
} | malsadig/rsbotscripts | src/org/sol/script/agility/course/Course.java | Java | gpl-3.0 | 2,217 |
@extends('layouts.app')
<!-- Main Content -->
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">@lang('auth.reset_password')</div>
<div class="panel-body">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('/password/email') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">@lang('auth.email_address')</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required>
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
@lang('auth.send_password_reset_link')
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
| benoit-development/ScoresKeeper | resources/views/auth/passwords/email.blade.php | PHP | gpl-3.0 | 1,946 |
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Code/Dev/appNativa/source/rareobjc/../rare/core/com/appnativa/rare/util/ListHelper.java
//
// Created by decoteaud on 3/11/16.
//
#ifndef _RAREListHelper_H_
#define _RAREListHelper_H_
@class IOSIntArray;
@class IOSObjectArray;
@class RAREDropInformation;
@class RAREFocusEvent;
@class RAREListHelper_RunTypeEnum;
@class RAREaListItemRenderer;
@class RAREaWidget;
@protocol RAREiHyperlinkListener;
@protocol RAREiListHandler;
@protocol RAREiPlatformComponent;
@protocol RAREiTransferable;
#import "JreEmulation.h"
#include "java/lang/Enum.h"
#include "java/lang/Runnable.h"
@interface RAREListHelper : NSObject {
}
+ (NSString *)CALL_SUPER_METHOD;
+ (NSString *)HYPERLINK_LISTENER_KEY;
+ (void)copySelectedItemsWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withInt:(int)index
withBoolean:(BOOL)insertMode
withBoolean:(BOOL)delete_ OBJC_METHOD_FAMILY_NONE;
+ (id)deleteItemsWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withIntArray:(IOSIntArray *)sels
withBoolean:(BOOL)returnData;
+ (BOOL)focusEventWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withRAREFocusEvent:(RAREFocusEvent *)e
withBoolean:(BOOL)focusOwner;
+ (BOOL)importDataWithRAREaWidget:(RAREaWidget *)widget
withRAREiListHandler:(id<RAREiListHandler>)listComponent
withRAREiTransferable:(id<RAREiTransferable>)t
withRAREDropInformation:(RAREDropInformation *)drop;
+ (void)installItemLinkListenerWithRAREiPlatformComponent:(id<RAREiPlatformComponent>)c
withRAREiHyperlinkListener:(id<RAREiHyperlinkListener>)l;
+ (void)flashHilightWithRAREiListHandler:(id<RAREiListHandler>)list
withInt:(int)row
withBoolean:(BOOL)on
withInt:(int)count
withJavaLangRunnable:(id<JavaLangRunnable>)runnable;
+ (void)runLaterWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withRAREListHelper_RunTypeEnum:(RAREListHelper_RunTypeEnum *)type;
+ (void)runOnEventThreadWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withRAREListHelper_RunTypeEnum:(RAREListHelper_RunTypeEnum *)type;
+ (void)setSelectionsWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withNSObjectArray:(IOSObjectArray *)a;
+ (NSString *)getWidgetAttributeWithRAREaWidget:(RAREaWidget *)widget
withRAREiListHandler:(id<RAREiListHandler>)listComponent
withNSString:(NSString *)name;
+ (void)runItWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withRAREListHelper_RunTypeEnum:(RAREListHelper_RunTypeEnum *)type;
- (id)init;
@end
typedef RAREListHelper ComAppnativaRareUtilListHelper;
typedef enum {
RAREListHelper_RunType_REFRESH = 0,
RAREListHelper_RunType_CLEAR = 1,
} RAREListHelper_RunType;
@interface RAREListHelper_RunTypeEnum : JavaLangEnum < NSCopying > {
}
+ (RAREListHelper_RunTypeEnum *)REFRESH;
+ (RAREListHelper_RunTypeEnum *)CLEAR;
+ (IOSObjectArray *)values;
+ (RAREListHelper_RunTypeEnum *)valueOfWithNSString:(NSString *)name;
- (id)copyWithZone:(NSZone *)zone;
- (id)initWithNSString:(NSString *)__name withInt:(int)__ordinal;
@end
@interface RAREListHelper_Runner : NSObject < JavaLangRunnable > {
@public
__weak id<RAREiListHandler> listComponent_;
RAREListHelper_RunTypeEnum *type_;
}
- (id)initWithRAREiListHandler:(id<RAREiListHandler>)listComponent
withRAREListHelper_RunTypeEnum:(RAREListHelper_RunTypeEnum *)type;
- (void)run;
- (void)copyAllFieldsTo:(RAREListHelper_Runner *)other;
@end
J2OBJC_FIELD_SETTER(RAREListHelper_Runner, type_, RAREListHelper_RunTypeEnum *)
@interface RAREListHelper_$1 : NSObject < JavaLangRunnable > {
@public
RAREaListItemRenderer *val$r_;
BOOL val$on_;
int val$row_;
id<RAREiListHandler> val$list_;
int val$count_;
id<JavaLangRunnable> val$runnable_;
}
- (void)run;
- (id)initWithRAREaListItemRenderer:(RAREaListItemRenderer *)capture$0
withBoolean:(BOOL)capture$1
withInt:(int)capture$2
withRAREiListHandler:(id<RAREiListHandler>)capture$3
withInt:(int)capture$4
withJavaLangRunnable:(id<JavaLangRunnable>)capture$5;
@end
J2OBJC_FIELD_SETTER(RAREListHelper_$1, val$r_, RAREaListItemRenderer *)
J2OBJC_FIELD_SETTER(RAREListHelper_$1, val$list_, id<RAREiListHandler>)
J2OBJC_FIELD_SETTER(RAREListHelper_$1, val$runnable_, id<JavaLangRunnable>)
#endif // _RAREListHelper_H_
| appnativa/rare | source/rareobjc/include/com/appnativa/rare/util/ListHelper.h | C | gpl-3.0 | 4,813 |
using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE;
namespace GitPlugin.Commands
{
public class GitIgnore : ItemCommandBase
{
public GitIgnore()
: base(true, true)
{
}
public override void OnExecute(SelectedItem item, string fileName, OutputWindowPane pane)
{
RunGitEx("gitignore", fileName);
}
}
}
| avish/gitextensions | GitPlugin/Commands/GitIgnore.cs | C# | gpl-3.0 | 417 |
using EloBuddy;
using LeagueSharp.Common;
namespace ReformedAIO.Champions.Ashe.OrbwalkingMode.Combo
{
#region Using Directives
using System;
using System.Linq;
using LeagueSharp;
using LeagueSharp.Common;
using ReformedAIO.Champions.Ashe.Logic;
using RethoughtLib.FeatureSystem.Abstract_Classes;
#endregion
internal sealed class QCombo : ChildBase
{
#region Fields
// private QLogic qLogic;
#endregion
#region Public Properties
public override string Name { get; set; } = "[Q]";
#endregion
#region Methods
protected override void OnDisable(object sender, FeatureBaseEventArgs eventArgs)
{
base.OnDisable(sender, eventArgs);
Game.OnUpdate -= OnUpdate;
}
protected override void OnEnable(object sender, FeatureBaseEventArgs eventArgs)
{
base.OnEnable(sender, eventArgs);
Game.OnUpdate += OnUpdate;
}
protected override void OnLoad(object sender, FeatureBaseEventArgs eventArgs)
{
base.OnLoad(sender, eventArgs);
Menu.AddItem(new MenuItem("QMana", "Mana %").SetValue(new Slider(0, 0, 50)));
Menu.AddItem(new MenuItem("AAQ", "AA Before Q").SetValue(true).SetTooltip("Wont cancel AA with Q"));
// qLogic = new QLogic();
}
private void OnUpdate(EventArgs args)
{
if (Menu.Item("QMana").GetValue<Slider>().Value > Variable.Player.ManaPercent
|| !Variable.Spells[SpellSlot.Q].IsReady())
{
return;
}
RangersFocus();
}
private void RangersFocus()
{
var target = HeroManager.Enemies.Where(Orbwalking.InAutoAttackRange).FirstOrDefault();
if (target == null || !target.IsValid || (Menu.Item("AAQ").GetValue<bool>() && ObjectManager.Player.Spellbook.IsAutoAttacking)) return;
Variable.Spells[SpellSlot.Q].Cast();
//qLogic.Kite(target);
}
#endregion
}
} | tk8226/YamiPortAIO-v2 | Core/AIO Ports/ReformedAIO/Champions/Ashe/OrbwalkingMode/Combo/QCombo.cs | C# | gpl-3.0 | 2,117 |
/*
* This file is part of Cleanflight.
*
* Cleanflight 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 of the License, or
* (at your option) any later version.
*
* Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "platform.h"
#include "system.h"
#include "io.h"
#include "adc.h"
#include "adc_impl.h"
void adcInit(drv_adc_config_t *init)
{
ADC_InitTypeDef ADC_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
uint8_t i;
uint8_t configuredAdcChannels = 0;
memset(&adcConfig, 0, sizeof(adcConfig));
#if !defined(VBAT_ADC_PIN) && !defined(EXTERNAL1_ADC_PIN) && !defined(RSSI_ADC_PIN) && !defined(CURRENT_METER_ADC_PIN)
UNUSED(init);
#endif
#ifdef VBAT_ADC_PIN
if (init->enableVBat) {
IOInit(IOGetByTag(IO_TAG(VBAT_ADC_PIN)), OWNER_SYSTEM, RESOURCE_ADC);
IOConfigGPIO(IOGetByTag(IO_TAG(VBAT_ADC_PIN)), IO_CONFIG(GPIO_Mode_AN, 0, GPIO_OType_OD, GPIO_PuPd_NOPULL));
adcConfig[ADC_BATTERY].adcChannel = VBAT_ADC_CHANNEL;
adcConfig[ADC_BATTERY].dmaIndex = configuredAdcChannels++;
adcConfig[ADC_BATTERY].enabled = true;
adcConfig[ADC_BATTERY].sampleTime = ADC_SampleTime_480Cycles;
}
#endif
#ifdef EXTERNAL1_ADC_PIN
if (init->enableExternal1) {
IOInit(IOGetByTag(IO_TAG(EXTERNAL1_ADC_PIN)), OWNER_SYSTEM, RESOURCE_ADC);
IOConfigGPIO(IOGetByTag(IO_TAG(EXTERNAL1_ADC_PIN)), IO_CONFIG(GPIO_Mode_AN, 0, GPIO_OType_OD, GPIO_PuPd_NOPULL));
adcConfig[ADC_EXTERNAL1].adcChannel = EXTERNAL1_ADC_CHANNEL;
adcConfig[ADC_EXTERNAL1].dmaIndex = configuredAdcChannels++;
adcConfig[ADC_EXTERNAL1].enabled = true;
adcConfig[ADC_EXTERNAL1].sampleTime = ADC_SampleTime_480Cycles;
}
#endif
#ifdef RSSI_ADC_PIN
if (init->enableRSSI) {
IOInit(IOGetByTag(IO_TAG(RSSI_ADC_PIN)), OWNER_SYSTEM, RESOURCE_ADC);
IOConfigGPIO(IOGetByTag(IO_TAG(RSSI_ADC_PIN)), IO_CONFIG(GPIO_Mode_AN, 0, GPIO_OType_OD, GPIO_PuPd_NOPULL));
adcConfig[ADC_RSSI].adcChannel = RSSI_ADC_CHANNEL;
adcConfig[ADC_RSSI].dmaIndex = configuredAdcChannels++;
adcConfig[ADC_RSSI].enabled = true;
adcConfig[ADC_RSSI].sampleTime = ADC_SampleTime_480Cycles;
}
#endif
#ifdef CURRENT_METER_ADC_PIN
if (init->enableCurrentMeter) {
IOInit(IOGetByTag(IO_TAG(CURRENT_METER_ADC_PIN)), OWNER_SYSTEM, RESOURCE_ADC);
IOConfigGPIO(IOGetByTag(IO_TAG(CURRENT_METER_ADC_PIN)), IO_CONFIG(GPIO_Mode_AN, 0, GPIO_OType_OD, GPIO_PuPd_NOPULL));
adcConfig[ADC_CURRENT].adcChannel = CURRENT_METER_ADC_CHANNEL;
adcConfig[ADC_CURRENT].dmaIndex = configuredAdcChannels++;
adcConfig[ADC_CURRENT].enabled = true;
adcConfig[ADC_CURRENT].sampleTime = ADC_SampleTime_480Cycles;
}
#endif
//RCC_ADCCLKConfig(RCC_ADC12PLLCLK_Div256); // 72 MHz divided by 256 = 281.25 kHz
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
DMA_DeInit(DMA2_Stream4);
DMA_StructInit(&DMA_InitStructure);
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&ADC1->DR;
DMA_InitStructure.DMA_Channel = DMA_Channel_0;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)adcValues;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
DMA_InitStructure.DMA_BufferSize = configuredAdcChannels;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = configuredAdcChannels > 1 ? DMA_MemoryInc_Enable : DMA_MemoryInc_Disable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_Init(DMA2_Stream4, &DMA_InitStructure);
DMA_Cmd(DMA2_Stream4, ENABLE);
// calibrate
/*
ADC_VoltageRegulatorCmd(ADC1, ENABLE);
delay(10);
ADC_SelectCalibrationMode(ADC1, ADC_CalibrationMode_Single);
ADC_StartCalibration(ADC1);
while(ADC_GetCalibrationStatus(ADC1) != RESET);
ADC_VoltageRegulatorCmd(ADC1, DISABLE);
*/
ADC_CommonInitTypeDef ADC_CommonInitStructure;
ADC_CommonStructInit(&ADC_CommonInitStructure);
ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div8;
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled;
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&ADC_CommonInitStructure);
ADC_StructInit(&ADC_InitStructure);
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_CC1;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = configuredAdcChannels;
ADC_InitStructure.ADC_ScanConvMode = configuredAdcChannels > 1 ? ENABLE : DISABLE; // 1=scan more that one channel in group
ADC_Init(ADC1, &ADC_InitStructure);
uint8_t rank = 1;
for (i = 0; i < ADC_CHANNEL_COUNT; i++) {
if (!adcConfig[i].enabled) {
continue;
}
ADC_RegularChannelConfig(ADC1, adcConfig[i].adcChannel, rank++, adcConfig[i].sampleTime);
}
ADC_DMARequestAfterLastTransferCmd(ADC1, ENABLE);
ADC_DMACmd(ADC1, ENABLE);
ADC_Cmd(ADC1, ENABLE);
ADC_SoftwareStartConv(ADC1);
}
| simondlevy/BreezySTM32 | f4/adc_stm32f4xx.c | C | gpl-3.0 | 6,200 |
/* xoreos - A reimplementation of BioWare's Aurora engine
*
* xoreos is the legal property of its developers, whose names
* can be found in the AUTHORS file distributed with this source
* distribution.
*
* xoreos 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
* of the License, or (at your option) any later version.
*
* xoreos 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 xoreos. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file
* List box widget for the Odyssey engine.
*/
#include "src/common/util.h"
#include "src/common/string.h"
#include "src/common/strutil.h"
#include "src/aurora/gff3file.h"
#include "src/graphics/graphics.h"
#include "src/sound/sound.h"
#include "src/engines/aurora/util.h"
#include "src/engines/odyssey/listbox.h"
#include "src/engines/odyssey/protoitem.h"
#include "src/engines/odyssey/scrollbar.h"
namespace Engines {
namespace Odyssey {
WidgetListBox::WidgetListBox(GUI &gui, const Common::UString &tag) :
Widget(gui, tag),
_protoItem(0),
_scrollbar(0),
_itemWidgetFactoryFunc(0),
_padding(0),
_leftScrollbar(false),
_itemSelectionEnabled(false),
_adjustHeight(false),
_hideScrollbar(true),
_selectedIndex(-1),
_startIndex(0),
_numVisibleItems(0),
_textColorChanged(false),
_textR(0.0f), _textG(0.0f), _textB(0.0f), _textA(0.0f),
_borderColorChanged(false),
_borderR(0.0f), _borderG(0.0f), _borderB(0.0f), _borderA(0.0f) {
}
void WidgetListBox::load(const Aurora::GFF3Struct &gff) {
Widget::load(gff);
_padding = gff.getSint("PADDING");
_leftScrollbar = gff.getBool("LEFTSCROLLBAR");
if (gff.hasField("SCROLLBAR"))
createScrollbar(gff.getStruct("SCROLLBAR"));
if (gff.hasField("PROTOITEM"))
_protoItem = &gff.getStruct("PROTOITEM");
}
void WidgetListBox::setItemSelectionEnabled(bool itemSelectionEnabled) {
_itemSelectionEnabled = itemSelectionEnabled;
if (!_itemSelectionEnabled)
_selectedIndex = -1;
applyChangesToItemWidgets();
}
void WidgetListBox::setAdjustHeight(bool adjustHeight) {
_adjustHeight = adjustHeight;
}
void WidgetListBox::setHideScrollbar(bool hideScrollbar) {
_hideScrollbar = hideScrollbar;
}
void WidgetListBox::setPadding(uint32_t padding) {
_padding = padding;
}
void WidgetListBox::setItemTextColor(float r, float g, float b, float a) {
_textColorChanged = true;
_textR = r;
_textG = g;
_textB = b;
_textA = a;
applyChangesToItemWidgets();
}
void WidgetListBox::setItemBorderColor(float r, float g, float b, float a) {
_borderColorChanged = true;
_borderR = r;
_borderG = g;
_borderB = b;
_borderA = a;
applyChangesToItemWidgets();
}
void WidgetListBox::addItem(const Common::UString &contents) {
_items.push_back(contents);
}
void WidgetListBox::removeAllItems() {
_startIndex = 0;
_items.clear();
}
void WidgetListBox::createItemWidgets(uint32_t count) {
if ((!_protoItem) || (!_itemWidgets.empty()))
return;
for (uint32_t i = 0; i < count; ++i) {
Common::UString tag = Common::String::format("%s_ITEM_%u", _tag.c_str(), i);
WidgetProtoItem *item = createItemWidget(tag);
item->load(*_protoItem);
addChild(*item);
addSub(*item);
_itemWidgets.push_back(item);
}
positionItemWidgets();
applyChangesToItemWidgets();
}
void WidgetListBox::refreshItemWidgets() {
if (_itemWidgets.empty())
return;
_numVisibleItems = 0;
float totalHeight = 0;
float x, y, z;
getPosition(x, y, z);
y += _height;
GfxMan.lockFrame();
bool heightExceeded = false;
for (size_t i = 0; i < _itemWidgets.size(); ++i) {
WidgetProtoItem *itemWidget = _itemWidgets[i];
bool visible = false;
if (!heightExceeded) {
int itemIndex = _startIndex + i;
if (itemIndex < (int)_items.size()) { // have item to display?
Common::UString &contents = _items[itemIndex];
if (_adjustHeight) {
float textHeight = itemWidget->getTextHeight(contents);
if (totalHeight + textHeight > getHeight())
heightExceeded = true;
else {
float iX, iY, iZ;
itemWidget->getPosition(iX, iY, iZ);
itemWidget->setPosition(iX, y -= textHeight + _padding, iZ);
itemWidget->setHeight(textHeight);
totalHeight += textHeight + _padding;
}
}
if (!heightExceeded) {
itemWidget->setContents(contents);
itemWidget->setHighlight(itemIndex == _selectedIndex);
visible = true;
}
}
}
if (visible) {
itemWidget->setInvisible(false);
if (isVisible())
itemWidget->show();
++_numVisibleItems;
} else {
if (isVisible())
itemWidget->hide();
itemWidget->setInvisible(true);
}
}
if (_hideScrollbar) {
if (_numVisibleItems < (int)_items.size()) {
_scrollbar->setInvisible(false);
if (isVisible())
_scrollbar->show();
} else {
if (isVisible())
_scrollbar->hide();
_scrollbar->setInvisible(true);
}
}
GfxMan.unlockFrame();
}
void WidgetListBox::selectItemByWidgetTag(const Common::UString &tag) {
if (!tag.beginsWith(_tag + "_ITEM_"))
return;
Common::UString tmp(tag);
tmp.replaceAll(_tag + "_ITEM_", "");
int index = -1;
Common::parseString(tmp, index);
if ((index >= 0) && (_selectedIndex != _startIndex + index)) {
_selectedIndex = _startIndex + index;
playSound(_soundSelectItem, Sound::kSoundTypeSFX);
refreshItemWidgets();
}
}
void WidgetListBox::selectItemByIndex(int index) {
if ((index < 0) || (static_cast<size_t>(index) >= _items.size()))
return;
_selectedIndex = index;
}
void WidgetListBox::selectNextItem() {
if (_itemSelectionEnabled) {
bool selectionChanged = false;
if ((_selectedIndex < 0) && (!_items.empty())) {
_selectedIndex = 0;
selectionChanged = true;
refreshItemWidgets();
} else if (_selectedIndex < (int)_items.size() - 1) {
++_selectedIndex;
if (_selectedIndex - _startIndex >= _numVisibleItems)
_startIndex = _selectedIndex - _numVisibleItems + 1;
selectionChanged = true;
refreshItemWidgets();
}
if (selectionChanged)
playSound(_soundSelectItem, Sound::kSoundTypeSFX);
} else if (_startIndex + _numVisibleItems < (int)_items.size()) {
++_startIndex;
refreshItemWidgets();
}
}
void WidgetListBox::selectPreviousItem() {
if (_itemSelectionEnabled) {
bool selectionChanged = false;
if ((_selectedIndex < 0) && (!_items.empty())) {
_selectedIndex = 0;
selectionChanged = true;
refreshItemWidgets();
} else if (_selectedIndex > 0) {
--_selectedIndex;
if (_selectedIndex < _startIndex)
_startIndex = _selectedIndex;
selectionChanged = true;
refreshItemWidgets();
}
if (selectionChanged)
playSound(_soundSelectItem, Sound::kSoundTypeSFX);
} else if (_startIndex > 0) {
--_startIndex;
refreshItemWidgets();
}
}
int WidgetListBox::getSelectedIndex() const {
return _selectedIndex;
}
void WidgetListBox::setItemWidgetFactoryFunction(const ItemWidgetFactoryFunc &f) {
_itemWidgetFactoryFunc = f;
}
void WidgetListBox::setHeight(float height) {
float deltaHeight = height - _height;
Widget::setHeight(height);
if (_scrollbar) {
height = _scrollbar->getHeight();
_scrollbar->setHeight(height + deltaHeight);
}
}
void WidgetListBox::subActive(Engines::Widget &widget) {
if (_itemSelectionEnabled)
selectItemByWidgetTag(widget.getTag());
else
raiseCallbackActive(widget);
}
void WidgetListBox::setSoundSelectItem(const Common::UString &resRef) {
_soundSelectItem = resRef;
applyChangesToItemWidgets();
}
void WidgetListBox::setSoundHoverItem(const Common::UString &resRef) {
_soundHoverItem = resRef;
applyChangesToItemWidgets();
}
void WidgetListBox::setSoundClickItem(const Common::UString &resRef) {
_soundClickItem = resRef;
applyChangesToItemWidgets();
}
WidgetProtoItem *WidgetListBox::createItemWidget(const Common::UString &tag) {
if (!_itemWidgetFactoryFunc)
return new WidgetProtoItem(*_gui, tag, this);
return _itemWidgetFactoryFunc(*_gui, tag);
}
void WidgetListBox::createScrollbar(const Aurora::GFF3Struct &gff) {
_scrollbar = new WidgetScrollbar(*_gui, _tag + "#" + gff.getString("TAG"));
_scrollbar->load(gff);
float x, y, z;
getPosition(x, y, z);
if (_leftScrollbar)
_scrollbar->setPosition(x, y, -1.0f);
else
_scrollbar->setPosition(x + _width - _scrollbar->getWidth(), y, -1.0f);
_scrollbar->setHeight(_height);
addChild(*_scrollbar);
addSub(*_scrollbar);
}
void WidgetListBox::positionItemWidgets() {
float x, y, z;
getPosition(x, y, z);
if (_scrollbar && _leftScrollbar)
x += _scrollbar->getWidth() + _scrollbar->getBorderDimension();
y += _height;
z -= 1.0f;
size_t count = _itemWidgets.size();
for (size_t i = 0; i < count; ++i) {
_itemWidgets[i]->setPosition(x, y -= _itemWidgets[i]->getHeight() + _padding, z);
}
}
void WidgetListBox::applyChangesToItemWidgets() {
for (size_t i = 0; i < _itemWidgets.size(); ++i) {
_itemWidgets[i]->setDisableHighlight(_itemSelectionEnabled);
if (_textColorChanged)
_itemWidgets[i]->setTextColor(_textR, _textG, _textB, _textA);
if (_borderColorChanged)
_itemWidgets[i]->setBorderColor(_borderR, _borderG, _borderB, _borderA);
_itemWidgets[i]->setSoundHover(_soundHoverItem);
_itemWidgets[i]->setSoundClick(_soundClickItem);
}
}
void WidgetListBox::mouseWheel(uint8_t UNUSED(state), int UNUSED(x), int y) {
if ((y == 0) || !_adjustHeight)
return;
_startIndex = MIN(
MAX(_startIndex - y, 0),
MAX<int>(_itemWidgets.size() - _numVisibleItems, 0)
);
refreshItemWidgets();
}
} // End of namespace Odyssey
} // End of namespace Engines
| xoreos/xoreos | src/engines/odyssey/listbox.cpp | C++ | gpl-3.0 | 9,829 |
<?php
/***********************************************************************
N-13 News is a free news publishing system
Copyright (C) 2011 Chris Watt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
GNU 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/>.
***********************************************************************/
if (!defined('ABSPATH')){ die(); }
$totalnews = DataAccess::fetch("SELECT COUNT(id) AS totalnews FROM " . NEWS_ARTICLES);
$totalnews = $totalnews['0']['totalnews'];
$totalcomments = DataAccess::fetch("SELECT COUNT(id) AS totalcomments FROM " . NEWS_COMMENTS);
$totalcomments = $totalcomments['0']['totalcomments'];
$totalusers = DataAccess::fetch("SELECT COUNT(uid) AS totalusers FROM " . NEWS_USERS);
$totalusers = $totalusers['0']['totalusers'];
$totalsmilies = DataAccess::fetch("SELECT COUNT(id) AS totalsmilies FROM " . NEWS_SMILIES);
$totalsmilies = $totalsmilies['0']['totalsmilies'];
$totalfilters = DataAccess::fetch("SELECT COUNT(id) AS totalfilters FROM " . NEWS_FILTER);
$totalfilters = $totalfilters['0']['totalfilters'];
$totalcats = DataAccess::fetch("SELECT COUNT(id) AS totalcats FROM " . NEWS_CATS);
$totalcats = $totalcats['0']['totalcats'];
$totaltemplates = DataAccess::fetch("SELECT COUNT(id) AS totaltemplates FROM " . NEWS_TEMPLATES);
$totaltemplates = $totaltemplates['0']['totaltemplates'];
$numaccess = DataAccess::fetch("SELECT COUNT(uid) AS numaccess FROM " . NEWS_ACCESS);
$numaccess = $numaccess['0']['numaccess'];
$totalimages = DataAccess::fetch("SELECT COUNT(uid) AS numimages FROM " . NEWS_IMAGES);
$totalimages = $totalimages['0']['numimages'];
$totalfiles = DataAccess::fetch("SELECT COUNT(uid) AS numfiles FROM " . NEWS_FILES);
$totalfiles = $totalfiles['0']['numfiles'];
$totalrss = DataAccess::fetch("SELECT COUNT(feedid) AS numrss FROM " . NEWS_FEEDS);
$totalrss = $totalrss['0']['numrss'];
$sentto = $_SESSION['uid'];
$unreadmessages = DataAccess::fetch("SELECT COUNT(uid) AS unread FROM " . NEWS_PRIVATE . " WHERE sentto = '$sentto' AND viewed = '1'");
$unreadmessages = $unreadmessages['0']['unread'];
$f = '';
$f = $f . " (" . $unreadmessages . ")";
echo ' <div id="pageLeft">
<div id="pageIconHome"></div><!--icon-->
<div id="titleHome">N-13 News<br />' . $version . '</div>
</div><!--leftside-->';
echo '<div id="pageRight">';
echo "<div id=\"headerBox\">".$langmsg['home'][1]." " . $_SESSION['name'] . "</div>";
if(ini_get("register_globals")){
echo "<div class=\"error-warning\">";
echo $langmsg['home'][3];
echo "</div><br />";
}
//try delete install dir
if(file_exists(ABSPATH . "install/index.php")){
function deleteinstall(){
global $langmsg;
echo "<form method=\"post\" action=\"?\">";
echo "<div class=\"error-warning\">";
echo $langmsg['home'][4] . "<br /><br />" . $langmsg['home'][21];
echo " <input type=\"submit\" value=\"".$langmsg['submitfield'][8]."\" name=\"Delete\" />
</div></form><br />";
}
$_POST['Delete'] = (empty($_POST['Delete'])) ? '' : $_POST['Delete'];
if(!$_POST['Delete']){
deleteinstall();
}else{
if(!@unlink("install/index.php")){
echo "<span class=error>";
echo $langmsg['home'][5];
echo "</span>";
}
}
}
echo "<div class=subheaders><span style=\"float: right; margin-right: 0px\">" . $langmsg['home'][20] . $f ."</span>".$langmsg['home'][0] . "</div>";
echo "<div class=\"subheaders_body displaytable\">";
echo "<table border=\"0\" cellpadding=\"0\" style=\"text-align: left; border-collapse: collapse\" bordercolor=\"#111111\" width=\"100%\">\n";
echo " <tr>\n";
echo " <td>\n";
echo " " . $langmsg['home'][6] . "</td>\n";
echo " <td>\n";
echo " <div class=\"ok\">$totalnews</div></td>\n";
echo " <td>\n";
echo " " . $langmsg['home'][23] . "</td>\n";
echo " <td>\n";
echo " <div class=\"ok\">$totalimages</div></td>\n";
echo " </tr>\n";
echo " <tr>\n";
echo " <td>\n";
echo " " . $langmsg['home'][7] . "</td>\n";
echo " <td>\n";
echo " <div class=\"ok\">$totalcomments</div></td>\n";
echo " <td>\n";
echo " " . $langmsg['home'][24] . "</td>\n";
echo " <td>\n";
echo "<div class=ok>$totalfiles</div></td>\n";
echo " </tr>\n";
echo " <tr>\n";
echo " <td>" . $langmsg['home'][8] . "</td>\n";
echo " <td><div class=ok>$totalusers</div></td>\n";
echo " <td>" . $langmsg['home'][25] . "</td>\n";
echo " <td><div class=ok>$totalrss</div></td>\n";
echo " </tr>\n";
echo "<tr>\n";
echo "<td>" . $langmsg['home'][9] . "</td>\n";
echo "<td><div class=ok>$totalsmilies</div></td>\n";
echo "<td>". $langmsg['home'][16] . "</td><td><span class=ok>$version</span></td>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $langmsg['home'][10] . "</td>\n";
echo "<td><div class=ok>$totalfilters</div></td>\n";
echo "<td>". $langmsg['home'][17] . "</td><td id=\"latestversion\">Checking for updates</td>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $langmsg['home'][11] . "</td>\n";
echo "<td><div class=ok>$totalcats</div></td>\n";
echo "<td colspan=\"2\" id=\"messagebox\"></td>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $langmsg['home'][12] . "</td>\n";
echo "<td><div class=ok>$totaltemplates</div></td>\n";
echo "</tr>";
echo "<tr>";
echo "<td>" . $langmsg['home'][13] . "</td>\n";
echo "<td><div class=ok>$numaccess</div></td>\n";
echo "<td><a href=\"?action=accesslogs\">" . $langmsg['home'][18] . "</a></td><td></td>";
echo "</tr>";
echo "</table>\n";
echo "</div>";
echo " </div><!--rightside-->
</div><!--pageCont-->";
$_SESSION['beenalerted'] = (empty($_SESSION['beenalerted'])) ? '' : $_SESSION['beenalerted'];
if($_SESSION['beenalerted'] == false){
$_SESSION['beenalerted'] = true;
$alertmsg = DataAccess::fetch("SELECT alertmsg FROM " . NEWS_USERS . " WHERE user = ?", $_SESSION['name']);
$alertmsg = $alertmsg['0']['alertmsg'];
if($alertmsg == "1"){
$uid = $_SESSION['uid'];
$m = count(DataAccess::fetch("SELECT * FROM " . NEWS_PRIVATE . " WHERE sentto = ? AND viewed = ?", $uid, "1"));
if($m > 0){
echo "<script language=\"javascript\">";
echo "if(confirm('You have $m unread message(s). Would you like to view them now?')){
window.location = '?action=private&type=';
}";
echo "</script>";
}
}
}
?> | tectronics/n-13news | modules/home.php | PHP | gpl-3.0 | 6,894 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_33) on Fri Aug 03 11:42:59 PDT 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
com.hp.hpl.jena.sparql.pfunction (Apache Jena ARQ)
</TITLE>
<META NAME="date" CONTENT="2012-08-03">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.hp.hpl.jena.sparql.pfunction (Apache Jena ARQ)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../com/hp/hpl/jena/sparql/path/eval/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/library/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/hp/hpl/jena/sparql/pfunction/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package com.hp.hpl.jena.sparql.pfunction
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Interface Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PropertyFunction.html" title="interface in com.hp.hpl.jena.sparql.pfunction">PropertyFunction</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PropertyFunctionFactory.html" title="interface in com.hp.hpl.jena.sparql.pfunction">PropertyFunctionFactory</A></B></TD>
<TD>Interface for extension factories registered with the extension registry.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PFuncAssignToObject.html" title="class in com.hp.hpl.jena.sparql.pfunction">PFuncAssignToObject</A></B></TD>
<TD>Common case: take a node (subject) and
calculate something else, assign it to a
variable (object)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PFuncAssignToSubject.html" title="class in com.hp.hpl.jena.sparql.pfunction">PFuncAssignToSubject</A></B></TD>
<TD>Common case: take a node (object) and
calculate something else, assign it to a
variable (subject)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PFuncSimple.html" title="class in com.hp.hpl.jena.sparql.pfunction">PFuncSimple</A></B></TD>
<TD>Common, simple case:
arguments are not lists
attempt to put values in for any bound variables
call the implementation with one binding at a time
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PFuncSimpleAndList.html" title="class in com.hp.hpl.jena.sparql.pfunction">PFuncSimpleAndList</A></B></TD>
<TD>Common, simple case:
subject arguments is not a list
object is a list
call the implementation with one binding at a time
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/ProcedurePF.html" title="class in com.hp.hpl.jena.sparql.pfunction">ProcedurePF</A></B></TD>
<TD>Adapter between property functions and server procedures
When called, this wrapper reconstructs the usual property function calling conventions.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PropertyFunctionBase.html" title="class in com.hp.hpl.jena.sparql.pfunction">PropertyFunctionBase</A></B></TD>
<TD>Basic property function handler that calls the implementation
subclass one binding at a time</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PropertyFunctionEval.html" title="class in com.hp.hpl.jena.sparql.pfunction">PropertyFunctionEval</A></B></TD>
<TD>Basic property function handler that calls the implementation
subclass one binding at a time after evaluating the arguments (if bound).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PropertyFunctionRegistry.html" title="class in com.hp.hpl.jena.sparql.pfunction">PropertyFunctionRegistry</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PropFuncArg.html" title="class in com.hp.hpl.jena.sparql.pfunction">PropFuncArg</A></B></TD>
<TD>Class representing an argument (subject or object position) of a property function.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/PropFuncArgType.html" title="class in com.hp.hpl.jena.sparql.pfunction">PropFuncArgType</A></B></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../com/hp/hpl/jena/sparql/path/eval/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../../com/hp/hpl/jena/sparql/pfunction/library/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/hp/hpl/jena/sparql/pfunction/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Licenced under the Apache License, Version 2.0
</BODY>
</HTML>
| decoit/Visa-Topologie-Editor | backend/lib/jena/javadoc-arq/com/hp/hpl/jena/sparql/pfunction/package-summary.html | HTML | gpl-3.0 | 10,576 |
using EloBuddy;
using LeagueSharp;
namespace ExorAIO.Champions.Nunu
{
/// <summary>
/// The logics class.
/// </summary>
internal partial class Logics
{
/// <summary>
/// Called on do-cast.
/// </summary>
/// <param name="(sender as Obj_AI_Hero)">The (sender as Obj_AI_Hero).</param>
/// <param name="args">The args.</param>
public static void Weaving(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) {}
}
} | concko/PortAIO | Champion/Nunu/Properties/Modes/PvP/Weaving.cs | C# | gpl-3.0 | 502 |
package edu.berkeley.nlp.util;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import edu.berkeley.nlp.math.SloppyMath;
/**
* A priority queue based on a binary heap. Note that this implementation does
* not efficiently support containment, removal, or element promotion
* (decreaseKey) -- these methods are therefore not yet implemented. It is a
* maximum priority queue, so next() gives the highest-priority object.
*
* @author Dan Klein
*/
public class PriorityQueue<E> implements Iterator<E>, Serializable, Cloneable, PriorityQueueInterface<E>
{
private static final long serialVersionUID = 1L;
int size;
int capacity;
E[] elements;
double[] priorities;
public static class MinPriorityQueue<E> implements PriorityQueueInterface<E>
{
private PriorityQueue<E> pq = new PriorityQueue<E>();
public boolean hasNext() {
return pq.hasNext();
}
public E next() {
return pq.next();
}
public void remove() {
pq.remove();
}
public E peek() {
return pq.peek();
}
public double getPriority() {
return -pq.getPriority();
}
public int size() {
return pq.size();
}
public boolean isEmpty() {
return pq.isEmpty();
}
public void put(E key, double priority) {
pq.put(key, -priority);
}
public List<E> toSortedList() {
return pq.toSortedList();
}
}
protected void grow(int newCapacity) {
// E[] newElements = (E[]) new Object[newCapacity];
// double[] newPriorities = new double[newCapacity];
// if (size > 0) {
// System.arraycopy(elements, 0, newElements, 0, priorities.length);
// System.arraycopy(priorities, 0, newPriorities, 0, priorities.length);
// }
elements = elements == null ? (E[]) new Object[newCapacity] : Arrays.copyOf(elements, newCapacity);
priorities = priorities == null ? new double[newCapacity] : Arrays.copyOf(priorities, newCapacity);
capacity = newCapacity;
}
private int parent(int loc) {
return (loc - 1) / 2;
}
private int leftChild(int loc) {
return 2 * loc + 1;
}
private int rightChild(int loc) {
return 2 * loc + 2;
}
private void heapifyUp(int loc_) {
if (loc_ == 0) return;
int loc = loc_;
int parent = parent(loc);
while (loc != 0 && priorities[loc] > priorities[parent]) {
swap(loc, parent);
loc = parent;
parent = parent(loc);
// heapifyUp(parent);
}
}
private void heapifyDown(int loc_) {
int loc = loc_;
int max = loc;
while (true) {
int leftChild = leftChild(loc);
if (leftChild < size()) {
double priority = priorities[loc];
double leftChildPriority = priorities[leftChild];
if (leftChildPriority > priority) max = leftChild;
int rightChild = rightChild(loc);
if (rightChild < size()) {
double rightChildPriority = priorities[rightChild(loc)];
if (rightChildPriority > priority && rightChildPriority > leftChildPriority) max = rightChild;
}
}
if (max == loc) break;
swap(loc, max);
loc = max;
}
// heapifyDown(max);
}
private void swap(int loc1, int loc2) {
double tempPriority = priorities[loc1];
E tempElement = elements[loc1];
priorities[loc1] = priorities[loc2];
elements[loc1] = elements[loc2];
priorities[loc2] = tempPriority;
elements[loc2] = tempElement;
}
private void removeFirst() {
if (size < 1) return;
swap(0, size - 1);
size--;
heapifyDown(0);
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#hasNext()
*/
public boolean hasNext() {
return !isEmpty();
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#next()
*/
public E next() {
E first = peek();
removeFirst();
return first;
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#peek()
*/
public E peek() {
if (size() > 0) return elements[0];
throw new NoSuchElementException();
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#getPriority()
*/
public double getPriority() {
if (size() > 0) return priorities[0];
throw new NoSuchElementException();
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#size()
*/
public int size() {
return size;
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#isEmpty()
*/
public boolean isEmpty() {
return size == 0;
}
/*
* (non-Javadoc)
*
* @see edu.berkeley.nlp.util.PriorityQueueInterface#add(E, double)
*/
public boolean add(E key, double priority) {
if (size == capacity) {
grow(2 * capacity + 1);
}
elements[size] = key;
priorities[size] = priority;
heapifyUp(size);
size++;
return true;
}
public void put(E key, double priority) {
add(key, priority);
}
/**
* Returns a representation of the queue in decreasing priority order.
*/
@Override
public String toString() {
return toString(size(), false);
}
/**
* Returns a representation of the queue in decreasing priority order,
* displaying at most maxKeysToPrint elements and optionally printing one
* element per line.
*
* @param maxKeysToPrint
* @param multiline
* TODO
*/
public String toString(int maxKeysToPrint, boolean multiline) {
PriorityQueue<E> pq = clone();
StringBuilder sb = new StringBuilder(multiline ? "" : "[");
int numKeysPrinted = 0;
NumberFormat f = NumberFormat.getInstance();
f.setMaximumFractionDigits(5);
while (numKeysPrinted < maxKeysToPrint && pq.hasNext()) {
double priority = pq.getPriority();
E element = pq.next();
sb.append(element == null ? "null" : element.toString());
sb.append(" : ");
sb.append(f.format(priority));
if (numKeysPrinted < size() - 1) sb.append(multiline ? "\n" : ", ");
numKeysPrinted++;
}
if (numKeysPrinted < size()) sb.append("...");
if (!multiline) sb.append("]");
return sb.toString();
}
/**
* Returns a counter whose keys are the elements in this priority queue, and
* whose counts are the priorities in this queue. In the event there are
* multiple instances of the same element in the queue, the counter's count
* will be the sum of the instances' priorities.
*
* @return
*/
public Counter<E> asCounter() {
PriorityQueue<E> pq = clone();
Counter<E> counter = new Counter<E>();
while (pq.hasNext()) {
double priority = pq.getPriority();
E element = pq.next();
counter.incrementCount(element, priority);
}
return counter;
}
/**
* Returns a clone of this priority queue. Modifications to one will not
* affect modifications to the other.
*/
@Override
public PriorityQueue<E> clone() {
PriorityQueue<E> clonePQ = new PriorityQueue<E>();
clonePQ.size = size;
clonePQ.capacity = capacity;
clonePQ.elements = elements == null ? null : Arrays.copyOf(elements, capacity);
clonePQ.priorities = priorities == null ? null : Arrays.copyOf(priorities, capacity);
// if (size() > 0) {
// clonePQ.elements.addAll(elements);
// System.arraycopy(priorities, 0, clonePQ.priorities, 0, size());
// }
return clonePQ;
}
public PriorityQueue() {
this(15);
}
public PriorityQueue(int capacity) {
int legalCapacity = 0;
while (legalCapacity < capacity) {
legalCapacity = 2 * legalCapacity + 1;
}
grow(legalCapacity);
}
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
System.out.println(pq);
pq.put("one", 1);
System.out.println(pq);
pq.put("three", 3);
System.out.println(pq);
pq.put("one", 1.1);
System.out.println(pq);
pq.put("two", 2);
System.out.println(pq);
System.out.println(pq.toString(2, false));
while (pq.hasNext()) {
System.out.println(pq.next());
}
}
public List<E> toSortedList() {
List<E> l = new ArrayList<E>(size());
PriorityQueue<E> pq = clone();
while (pq.hasNext()) {
l.add(pq.next());
}
return l;
}
public void clear() {
this.size = 0;
}
}
| timfeu/berkeleycoref-bansalklein | code/edu/berkeley/nlp/util/PriorityQueue.java | Java | gpl-3.0 | 8,224 |
<?php
/**
* @license GPLv3, http://www.gnu.org/copyleft/gpl.html
* @copyright Metaways Infosystems GmbH, 2013
* @copyright Aimeos (aimeos.org), 2014
* @package TYPO3_Aimeos
*/
namespace Aimeos\Aimeos\Controller;
use Aimeos\Aimeos\Base;
/**
* Abstract class with common functionality for all controllers.
*
* @package TYPO3_Aimeos
*/
abstract class AbstractController
extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
private $context;
private static $locale;
/**
* Creates a new configuration object.
*
* @return MW_Config_Interface Configuration object
*/
protected function getConfig()
{
$settings = (array) $this->settings;
if( isset( $this->settings['typo3']['tsconfig'] ) )
{
$tsconfig = Base::parseTS( $this->settings['typo3']['tsconfig'] );
$settings = \TYPO3\CMS\Extbase\Utility\ArrayUtility::arrayMergeRecursiveOverrule( $settings, $tsconfig );
}
return Base::getConfig( $settings );
}
/**
* Returns the context item
*
* @return \MShop_Context_Item_Interface Context item
*/
protected function getContext()
{
if( !isset( $this->context ) )
{
$templatePaths = Base::getAimeos()->getCustomPaths( 'client/html' );
$config = $this->getConfig( $this->settings );
$context = Base::getContext( $config );
$localI18n = ( isset( $this->settings['i18n'] ) ? $this->settings['i18n'] : array() );
$locale = $this->getLocale( $context );
$langid = $locale->getLanguageId();
$context->setLocale( $locale );
$context->setI18n( Base::getI18n( array( $langid ), $localI18n ) );
$context->setView( Base::getView( $config, $this->uriBuilder, $templatePaths, $this->request, $langid ) );
if( TYPO3_MODE === 'FE' && $GLOBALS['TSFE']->loginUser == 1 )
{
$context->setEditor( $GLOBALS['TSFE']->fe_user->user['username'] );
$context->setUserId( $GLOBALS['TSFE']->fe_user->user[$GLOBALS['TSFE']->fe_user->userid_column] );
}
$this->context = $context;
}
return $this->context;
}
/**
* Returns the locale object for the context
*
* @param \MShop_Context_Item_Interface $context Context object
* @return \MShop_Locale_Item_Interface Locale item object
*/
protected function getLocale( \MShop_Context_Item_Interface $context )
{
if( !isset( self::$locale ) )
{
$session = $context->getSession();
$config = $context->getConfig();
$sitecode = $config->get( 'mshop/locale/site', 'default' );
$name = $config->get( 'typo3/param/name/site', 'loc-site' );
if( $this->request->hasArgument( $name ) === true ) {
$sitecode = $this->request->getArgument( $name );
}
$langid = $config->get( 'mshop/locale/language', '' );
$name = $config->get( 'typo3/param/name/language', 'loc-language' );
if( isset( $GLOBALS['TSFE']->config['config']['language'] ) ) {
$langid = $GLOBALS['TSFE']->config['config']['language'];
}
if( $this->request->hasArgument( $name ) === true ) {
$langid = $this->request->getArgument( $name );
}
$currency = $config->get( 'mshop/locale/currency', '' );
$name = $config->get( 'typo3/param/name/currency', 'loc-currency' );
if( $this->request->hasArgument( $name ) === true ) {
$currency = $this->request->getArgument( $name );
}
$localeManager = \MShop_Locale_Manager_Factory::createManager( $context );
self::$locale = $localeManager->bootstrap( $sitecode, $langid, $currency );
}
return self::$locale;
}
/**
* Returns the output of the client and adds the header.
*
* @param Client_Html_Interface $client Html client object
* @return string HTML code for inserting into the HTML body
*/
protected function getClientOutput( \Client_Html_Interface $client )
{
$client->setView( $this->getContext()->getView() );
$client->process();
$this->response->addAdditionalHeaderData( (string) $client->getHeader() );
return $client->getBody();
}
/**
* Initializes the object before the real action is called.
*/
protected function initializeAction()
{
$this->uriBuilder->setArgumentPrefix( 'ai' );
}
/**
* Disables Fluid views for performance reasons.
*
* return Tx_Extbase_MVC_View_ViewInterface View object
*/
protected function resolveView()
{
return null;
}
}
| nos3/aimeos-typo3 | Classes/Controller/AbstractController.php | PHP | gpl-3.0 | 4,242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.