text
stringlengths 3
181k
| src
stringlengths 5
1.02k
|
---|---|
package de.itoast.pairingtimer;
import javax.swing.*;
import java.awt.*;
public class TimerPanel extends JPanel {
private final PiePainter piePainter = new PiePainter();
private AngleTimer timer;
private TimerConfiguration timerConfiguration;
public TimerPanel(final TimerConfiguration timerConfiguration) {
this.timerConfiguration = timerConfiguration;
timer = new PairingTimer(timerConfiguration, this);
this.setLayout(new BorderLayout());
this.setDoubleBuffered(true);
}
@Override
protected void paintComponent(Graphics graphics) {
piePainter.draw(graphics, timer, this.getBounds(), TimeUtil.remainingTimeToString(timer.getSecondsLeft()));
}
public void setTimer(AngleTimer timer) {
this.timer = timer;
}
public void toggle() {
if (this.timer.isCancelled()) {
this.timer = timer.resume();
} else {
this.timer.cancel();
}
}
public String getToggleText() {
return this.timer.isCancelled() ? "Start timer" : "Stop timer";
}
public void restart() {
if (this.timer.isCancelled()) {
this.timer = new PairingTimer(timerConfiguration, this);
} else {
this.timer.cancel();
this.timer = new PairingTimer(timerConfiguration, this);
this.timer.start();
}
}
}
| lastcosmonaut/3ptimer-src/main/java/de/itoast/pairingtimer/TimerPanel.java |
# What is the probability of rolling a sum of 3 with two 6 sided dice?
Contents
There are no other combinations that sum to 3, so we have 2 out of a total of 36 combinations that sum to 3. Therefore, the answer is 2/36 = 1/18.
## What are the odds of rolling a sum of 3 with two six sided dice?
Probabilities for the two dice
Total Number of combinations Probability
2 1 2.78%
3 2 5.56%
4 3 8.33%
5 4 11.11%
## What is the probability of rolling a sum of 3?
We divide the total number of ways to obtain each sum by the total number of outcomes in the sample space, or 216. The results are: Probability of a sum of 3: 1/216 = 0.5% Probability of a sum of 4: 3/216 = 1.4%
## What is the probability of rolling two six sided dice and obtaining at least one 3?
The probability of NOT rolling a 3 with one die is 5/6 so the probability of NOT rolling a 3 with a roll of two dice is 25/36. The probability of rolling at least one 3 is 1–25/36=11/36, a bit less than 1/3.
## What is the probability of rolling a 3 with two die?
6 Sided Dice probability (worked example for two dice).
Two (6-sided) dice roll probability table.
IMPORTANT: Can you bet on DraftKings in Nevada?
Roll a… Probability
3 2/36 (5.556%)
4 3/36 (8.333%)
5 4/36 (11.111%)
6 5/36 (13.889%)
## When two sided dice are rolled There are 36 possible outcomes?
Every time you add an additional die, the number of possible outcomes is multiplied by 6: 2 dice 36, 3 dice 36*6 = 216 possible outcomes.
## What is the probability that in 3 rolls of a pair of six sided dice exactly one total of 7 is rolled?
With 2, 6-sided dice, there are 6² (or (36)) possible number groups. Of these 36 number groups, 6 of them (see above) sum to 7. Therefore the Probability of achieving a sum of 7 by rolling the 2 dice is ( 6/36 ) = ( 1/6 ) = 0.1667 = =16.67%.
## What is the probability of you rolling a sum of 7?
For each of the possible outcomes add the numbers on the two dice and count how many times this sum is 7. If you do so you will find that the sum is 7 for 6 of the possible outcomes. Thus the sum is a 7 in 6 of the 36 outcomes and hence the probability of rolling a 7 is 6/36 = 1/6. | finemath-3plus |
module.exports = [
'none',
'inherit',
'initial',
'auto',
'normal',
'transparent',
'!important'
]
| vonagam/compact-stylus-lib/js/dictionaries/values.js |
#!/usr/bin/env python
import glob
import logging
from lxml import html
import os
import requests
import shutil
import sys
import time
import urllib
# Logging
logging.basicConfig(level=logging.INFO)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s : %(levelname)-8s : %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
# Locations
HOME = os.path.dirname(os.path.realpath(__file__))
CWD = os.getcwd()
# Make folder if it doesn't exist
ARCHIVE = '%s/nimona' % CWD
if not os.path.isdir(ARCHIVE):
logging.info('Creating archive: %s' % ARCHIVE)
os.makedirs(ARCHIVE)
# Find last node in our archive...
files = glob.glob('%s/*.jpg' % ARCHIVE)
if files:
next_node = int(os.path.basename(files[-1]).split('-')[0]) + 1
else:
next_node = 22 # This is the first page
logging.info('Next node: %s' % next_node)
# Get the last node on the site
r = requests.get('http://gingerhaze.com/nimona')
p = html.fromstring(r.text)
last_node = int(p.xpath('///div[contains(@class, "node")]/@id')[0].split('-')[1])
logging.info('Last node: %s' % last_node)
# UP AND ATOM
for i in range(next_node, last_node+1):
logging.info('GET node: %s' % next_node)
r = requests.get('http://gingerhaze.com/node/%s' % next_node)
# Skip errors
if not r.ok:
logging.info('SKIP no node found...')
continue
# Get Image
p = html.fromstring(r.text)
m = p.xpath('//img[@typeof="foaf:Image"]/@src')
# Skip to next page, doesn't have image...
if not len(m):
logging.info('SKIP No image found...')
else:
img = m[0]
logging.info('IMG FOUND: %s' % img)
# Download Image
dl = '%s/%04d-%s' % (ARCHIVE,
next_node,
urllib.unquote(os.path.basename(img))
)
logging.info('SAVING to %s' % dl)
r = requests.get(img, stream=True)
with open(dl, 'wb') as f:
shutil.copyfileobj(r.raw, f)
# DEBUG
# sys.exit()
next_node += 1
# Be nice
time.sleep(1)
| lhl/nimona_downloader-update-local.py |
Analysis for the Unlimited Rejection Case
In this section, we assume that the number of allowed rejections is unlimited, that is, \(\Delta_{u}=+\infty\) for \(u\in U\). This means that we can ignore the constraint (2) in LP (Off). The main result of this section is to prove that Algorithm 1 is \(1/2\)-competitive for this case. For that purpose, we first modify the instance as in the previous section, and we will bound \(\tilde{R}_{1}^{\Delta_{u}}\) from below.
We observe that, when executing the algorithm for the modified instance, the remaining budget \(d\) of the vertex \(u\) is infinite in the whole process. For simplicity, we denote \(R_{t}=\tilde{R}_{t}^{\infty}\) and \(Q_{t}=Q_{t}^{\infty}\). Then, by (8), it holds that
\[Q_{t}=q_{t}^{\prime}\left(w_{t}^{\prime}+\sum_{\ell=1}^{T-t}\Pr[C_{t}=\ell]R_{t +\ell}\right)+(1-q_{t}^{\prime})R_{t+1}.\]
Moreover, it follows from (7) that
\[R_{t}=\max\left\{p_{t}^{\prime}Q_{t}+(1-p_{t}^{\prime})R_{t+1},R_{t+1}\right\}. \tag{9}\]
We note that \(R_{T}=p_{T}^{\prime}q_{T}^{\prime}w_{T}^{\prime}\). We can make the first term in (9) simpler as \(B_{t}w_{t}^{\prime}+A_{t}R_{t+1}+B_{t}\sum_{\ell=2}^{T-t}\Pr[C_{t}=\ell]R_{t+\ell}\), where \(B_{t}=p_{t}^{\prime}q_{t}^{\prime}\) and \(A_{t}=p_{t}^{\prime}q_{t}^{\prime}\Pr[C_{t}=1]+p_{t}^{\prime}(1-q_{t}^{\prime} )+(1-p_{t}^{\prime})\) for each \(t\in[T]\). We note that \(A_{t}=p_{t}^{\prime}q_{t}^{\prime}\Pr[C_{t}=1]+1-p_{t}^{\prime}q_{t}^{\prime}=1 -B_{t}\Pr[C_{t}\geq 2]\).
A lower bound on \(R_{1}\) is obtained by minimizing \(R_{1}\) subject to the condition (9). The minimization problem can be formulated as a linear programming problem as below. Note that we do not need to solve the LP, but use it for analysis.4
Footnote 4: Such LP is called a factor-revealing LP.
\[\begin{array}{rl}\min&R_{1}\\ \mbox{s.t.}&R_{t}\geq B_{t}w_{t}^{\prime}+A_{t}R_{t+1}+B_{t}\sum_{\ell=2}^{T-t} \Pr[C_{t}=\ell]R_{t+\ell}\ \ (t\in[T-1])\\ &R_{t}\geq R_{t+1}\ \ (t\in[T-1])\\ &R_{T}\geq B_{T}w_{T}^{\prime}\\ &R_{t}\geq 0\ \ \ (t\in[T]),\end{array} \tag{10}\]
Then the optimal value of the above LP gives a lower bound of \(R_{1}\). The dual of LP (10) is given by
\[\begin{array}{rl}\max&\sum_{t=1}^{T}B_{t}w_{t}^{\prime}\alpha_{t}\\ \mbox{s.t.}&\alpha_{1}+\beta_{1}\leq 1\\ &\alpha_{2}+\beta_{2}\leq A_{1}\alpha_{1}+\beta_{1}\\ &\alpha_{t}+\beta_{t}\leq\sum_{\ell=1}^{t-2}\alpha_{\ell}B_{\ell}\Pr[C_{\ell}= t-\ell]+A_{t-1}\alpha_{t-1}+\beta_{t-1}\ \ (3\leq t\leq T-1)\\ &\alpha_{T}\leq\sum_{\ell=1}^{T-2}\alpha_{\ell}B_{\ell}\Pr[C_{\ell}=T-\ell]+A_ {T-1}\alpha_{T-1}+\beta_{T-1}\\ &\alpha_{t}\geq 0\ \ \ (t\in[T])\\ &\beta_{t}\geq 0\ \ \ (t\in[T-1]).\end{array} \tag{11}\]
To show a lower bound on LP (10), we construct a feasible solution to the dual LP (11). Let \(\gamma\leq 1/2\). We set \(\alpha_{t}=\gamma\) for \(t\in[T]\), \(\beta_{1}=1-\gamma\), \(\beta_{2}=\beta_{1}-\gamma+A_{1}\gamma\), and \(\beta_{t}=\beta_{t-1}-\gamma+A_{t-1}\gamma+\sum_{\ell=1}^{t-2}B_{\ell}\Pr[C_{ \ell}=t-\ell]\gamma\)\((3\leq t\leq T-1)\).
**Lemma 3**.: _For \(0\leq\gamma\leq 1/2\), \(\alpha_{t}\) and \(\beta_{t}\) defined as above are feasible to (11)._
Proof.: By the construction, we can see that they satisfy the first, second and third constraints in (11). In fact, these constraints are satisfied with equality as \(\alpha_{t}=\gamma\) for any \(t\). It remains to show that \(\beta_{t}\) is non-negative, and that they satisfy the fourth constraint.
**Claim 1**.: _For \(t\geq 2\), we have_
\[\beta_{t}=1-\gamma-\gamma\sum_{t^{\prime}<t}B_{t^{\prime}}\Pr[C_{t^{\prime}} \geq t-t^{\prime}+1]. \tag{12}\]Proof of Claim.: By a simple calculation, we have
\[\beta_{2} =1-\gamma-\gamma+(1-B_{1}\Pr[C_{1}\geq 2])\gamma\] \[=1-\gamma-\gamma\sum_{t^{\prime}<2}B_{t^{\prime}}\Pr[C_{t^{\prime} }\geq 2-t^{\prime}+1].\]
Moreover, by induction, it holds that, for any \(t\geq 3\),
\[\beta_{t} =\beta_{t-1}+\gamma\sum_{\ell=1}^{t-2}B_{\ell}\Pr[C_{\ell}=t- \ell]-(1-A_{t-1})\gamma\] \[=\left(1-\gamma-\gamma\sum_{t^{\prime}<t-1}B_{t^{\prime}}\Pr[C_{t ^{\prime}}\geq t-t^{\prime}]\right)+\gamma\sum_{t^{\prime}<t-1}B_{t^{\prime}} \Pr[C_{t^{\prime}}=t-t^{\prime}]-(B_{t-1}\Pr[C_{t-1}\geq 2])\gamma\] \[=1-\gamma-\gamma\sum_{t^{\prime}<t}B_{t^{\prime}}\Pr[C_{t^{\prime }}\geq t-t^{\prime}+1].\]
Thus the claim holds.
By (12), we see that, for \(t=2,\ldots,T-1\),
\[\beta_{t} =1-\gamma-\gamma\sum_{t^{\prime}<t}B_{t^{\prime}}\Pr[C_{t^{\prime }}\geq t-t^{\prime}+1]\] \[=1-\gamma-\gamma\left(\sum_{t^{\prime}<t}\sum_{e\in E_{u}}x_{e,t^ {\prime}}^{*}q_{e}\Pr[C_{e}\geq t-t^{\prime}+1]\right)\] \[\geq 1-2\gamma\quad(\because(1)).\]
Since \(\gamma\leq 1/2\), it turns out that \(\beta_{t}\) is nonnegative for any \(t\).
Finally, let us check that the fourth constraint is satisfied. The RHS is equal to \(-\gamma(1-A_{T-1}-\sum_{t=1}^{T-2}B_{\ell}\Pr[C_{\ell}=T-\ell])\). Since \(A_{T-1}=1-B_{T-1}\Pr[C_{T-1}\geq 2]\), the RHS is at least \(-\gamma B_{T-1}\Pr[C_{T-1}\geq 2]\). Since \(\beta_{T-1}=1-\gamma-\gamma\sum_{t^{\prime}<T-1}B_{t^{\prime}}\Pr[C_{t^{\prime }}\geq T-t^{\prime}+1]\) by (12), the fourth constraint is satisfied if
\[1 \geq\left(1+\sum_{t^{\prime}<T}B_{t^{\prime}}\Pr[C_{t^{\prime}} \geq T-t^{\prime}+1]\right)\gamma\] \[=\left(1+\sum_{t^{\prime}<T}\sum_{e\in E_{u}}x_{e,t^{\prime}}^{*} q_{e}\Pr[C_{e}\geq T-t^{\prime}+1]\right)\gamma. \tag{13}\]
Since \(0\leq\sum_{t^{\prime}<T}\sum_{e\in E_{u}}x_{e,t^{\prime}}^{*}q_{e}\Pr[C_{e} \geq T-t^{\prime}+1]\leq 1\) by (1), the RHS is at most \(2\gamma\). Since \(\gamma\leq 1/2\), (13) holds, and hence the fourth constraint is satisfied.
Therefore, \(\alpha_{t}\) and \(\beta_{t}\) defined as above are feasible to (11). The objective value for this solution is \(\sum_{t}B_{t}w_{t}^{\prime}\gamma=\gamma\sum_{t}p_{t}^{\prime}q_{t}^{\prime}w_ {t}^{\prime}\). It follows from the LP duality theorem that the optimal value of LP (10) is at least \(\gamma\sum_{t}p_{t}^{\prime}q_{t}^{\prime}w_{t}^{\prime}\). This is maximized when \(\gamma=1/2\), and in this case, \(R_{1}\) is lower-bounded by \(\frac{1}{2}\sum_{t}p_{t}^{\prime}q_{t}^{\prime}w_{t}^{\prime}\). Since \(\sum_{t}p_{t}^{\prime}q_{t}^{\prime}w_{t}^{\prime}=\sum_{t}\sum_{e\in E_{u}}w_{ e}q_{e}x_{e,t}^{*}\), we obtain \(R_{1}\geq\frac{1}{2}\sum_{t}\sum_{e\in E_{u}}w_{e}q_{e}x_{e,t}^{*}\).
Summarizing, we have \(\sum_{u\in U}R_{1}^{\Delta_{u}}\geq\frac{1}{2}\mathbb{E}[\mathrm{OPT}(I)]\) by Lemma 1, which implies the following theorem.
**Theorem 1**.: _Algorithm 1 is \(1/2\)-competitive for the problem with unlimited rejections._ | 2203.07605v1.mmd |
/*
* Copyright (c) 2015. Germain Consulting, subject to the GPL3 licence
*
*/
package consulting.germain.snakegame.enums;
/**
* Created by mark_local on 11/09/2015.
* enum of the possible snake directions expressed as compass points
*/
public enum SnakeDirection {
/** y decreasing */
NORTH
/** x increasing */
, EAST
/** y increasing */
, SOUTH
/** x decreasing */
, WEST
}
| mg-gittest/snake-game-app/src/main/java/consulting/germain/snakegame/enums/SnakeDirection.java |
//
// STDebugTool.h
// STDebugKit
//
// Created by Thomas Dupont on 03/09/13.
/***********************************************************************************
*
* Copyright (c) 2013 Thomas Dupont
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
***********************************************************************************/
#import <Foundation/Foundation.h>
typedef void(^STDebugToolAction)(id o);
@interface STDebugTool : NSObject
+ (STDebugTool*)debugToolNamed:(NSString*)name action:(STDebugToolAction)action;
+ (STDebugTool*)debugToolNamed:(NSString*)name viewControllerClass:(Class)c;
@property (nonatomic, strong) NSString* toolName;
@property (nonatomic, strong) STDebugToolAction toolAction;
- (void)setToolAction:(STDebugToolAction)action;
@property (nonatomic, strong) Class toolClass;
@property (nonatomic, assign) NSInteger order;
@end
| iSofTom/STDebugKit-STDebugKit/STDebugTool.h |
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
bool isPalindrome(string& s) {
int i = 0, j = s.size() - 1;
while (i < j) {
while (i < j && !isalnum(s[i])) {
++i;
}
while (i < j && !isalnum(s[j])) {
--j;
}
if (tolower(s[i]) != tolower(s[j])) {
return false;
}
++i, --j;
}
return true;
}
};
| jaredkoontz/lintcode-C++/valid-palindrome.cpp |
Free Worksheets, Lessons, Quizzes
Ascending Order Numbers Activity 17
Ascending Order Numbers Activity 17: Move the given numbers in ascending order or from smallest to largest.
Do you know what ‘Ascending Order’ means? We say the numbers are in ascending order, when the numbers are arranged from the smallest to the largest. In this way we place the numbers in an increasing order. For example, look at these numbers; 491, 233, 807, 955 and 770. How to arrange these numbers in ascending order? First pick up the smallest out of all the given numbers. Then the second smallest, and so on until the largest. Likewise, in the given series of numbers 233, 491, 770, 807 and 955 are arranged in ascending order. With these online worksheets you can improve your ability in ordering numbers in ascending order by arranging numbers from the smallest to the largest. Learn ascending order by arranging numbers from least to greatest. Enjoy ordering numbers in ascending order!
[{ "question": "36 48 60 72 84", "img":"ascending-order.jpg", "imgalter":"ordering numbers ascending order least to greatest worksheet1", "clue":"The picture shows how ascending order works." }, { "question": "32 34 36 38 40", "img":"ascending-order.jpg", "imgalter":"Ascending Order Numbers Activity 17 ordering numbers ascending order least to greatest worksheet2", "clue":"The picture shows how ascending order works." }, { "question": "48 51 54 57 60", "img":"ascending-order.jpg", "imgalter":"ordering numbers ascending order least to greatest worksheet3", "clue":"The picture shows how ascending order works." }, { "question": "64 68 72 76 80", "img":"ascending-order.jpg", "imgalter":"ordering numbers ascending order least to greatest worksheet4", "clue":"The picture shows how ascending order works." }, { "question": "80 85 90 95 100", "img":"ascending-order.jpg", "imgalter":"ordering numbers ascending order least to greatest worksheet5", "clue":"The picture shows how ascending order works." } ] | finemath-3plus |
var litmus = require('litmus'),
micro = require('../lib/micro');
module.exports = new litmus.Test(module, function () {
var test = this;
function testRoute (route, shouldMatch, shouldNotMatch) {
var Webapp = micro.webapp();
Webapp.get(route, function (request, response) {
var params = Array.prototype.slice.apply(arguments);
params.shift();
params.shift();
params.shift();
response.handled = true;
response.params = params;
});
function testResponseMatched (response, url, params) {
test.async('route: \'' + route + '\', url: \'' + url + '\'', function (done) {
var check = function (response) {
test.ok(response.handled, 'route \'' + route + '\' should match \'' + url + '\'');
test.is(response.params, params, 'params for route \'' + route + '\' applied to \'' + url + '\'');
done.resolve();
};
if (response.then) {
response.then(check);
}
else {
check(response);
}
});
}
function testResponseDidNotMatch (response, url) {
test.async('route: \'' + route + '\', url: \'' + url + '\'', function (done) {
var check = function (response) {
test.nok(response.handled, 'route \'' + route + '\' should not match \'' + url + '\'');
done.resolve();
};
if (response.then) {
response.then(check);
}
else {
check(response);
}
});
}
var webapp = new Webapp(), response;
for (var i in shouldMatch) {
response = {};
webapp.handle({ method: 'GET', url: i }, response);
testResponseMatched(
response,
i,
shouldMatch[i]
);
}
for (var i = 0, l = shouldNotMatch.length; i < l; i++) {
response = {};
webapp.handle({ method: 'GET', url: shouldNotMatch[i] }, response);
testResponseDidNotMatch(
response,
shouldNotMatch[i]
);
}
}
test.plan(48);
testRoute(
'/',
{ '/' : [] },
[ '/blah', '//' ]
);
testRoute(
'/some/url.html',
{ '/some/url.html' : [] },
[ '/', '/some/url.htm', '/some/url.htmll', 'prefix/some/url.html' ]
);
testRoute(
'/:named',
{
'/hello' : [ { named : 'hello' } ],
'/with-hyphens-and_underscores' : [ { named : 'with-hyphens-and_underscores' } ]
},
[ '/', '/no.dots', '/*', '/+' ]
);
testRoute(
'/multiple/:named/:params',
{
'/multiple/one/two' : [ { named : 'one', params : 'two' } ],
'/multiple/A-Z0-9/A_Z0_9' : [ { named : 'A-Z0-9', params : 'A_Z0_9' } ]
},
[ '/multiple/no.dots/blah' ]
);
testRoute(
'/*',
{ '/hello' : [ 'hello' ], '/h-y-p-h-e-n-s' : [ 'h-y-p-h-e-n-s' ], '/under_score_s' : [ 'under_score_s' ] },
[ '/', '//', '/+', '/hello/', '/hello/hello' ]
);
testRoute(
'/:named[a{3,4}]',
{ '/aaa' : [ { named : 'aaa' } ], '/aaaa' : [ { named : 'aaaa' } ] },
[ '/', '/aa', '/aaaaa' ]
);
testRoute(
'/*[a{3,4}]',
{ '/aaa' : [ 'aaa' ], '/aaaa' : [ 'aaaa' ] },
[ '/', '/aa', '/aaaaa' ]
);
});
| usenode/micro.js-tests/routing.js |
package com.github.jankroken.commandline.util;
public class Constants {
public static final String[] EMPTY_STRING_ARRAY = new String[]{};
}
| jankroken/commandline-src/main/java/com/github/jankroken/commandline/util/Constants.java |
ScalaJS.data.scala_scalajs_js_EvalError$ = new ScalaJS.ClassTypeData({
scala_scalajs_js_EvalError$: 0
}, false, "scala.scalajs.js.EvalError$", ScalaJS.data.scala_scalajs_js_Object, {
scala_scalajs_js_EvalError$: 1,
scala_scalajs_js_Object: 1,
scala_scalajs_js_Any: 1,
java_lang_Object: 1
});
//@ sourceMappingURL=EvalError$.js.map
| ignaciocases/hermeneumatics-node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/scalajs/js/EvalError$.js |
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: '10.30.76.13',
port: 3306,
database: 'm3',
user: 'root',
password: 'kjs2005'
});
module.exports.pool = pool;
| zzragida/NodeExamples-restapi/db.js |
// https://leetcode.com/problems/linked-list-cycle/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(0) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) return false;
auto hare = head;
auto tortoise = head;
while (hare && hare->next != 0) {
hare = hare->next->next;
tortoise = tortoise->next;
if (tortoise == hare) return true;
}
return false;
}
};
| AriaFallah/leetcode-c++/LinkedListCycle.cpp |
model.jsonModel = {
services: [
{
name: "alfresco/services/LoggingService",
config: {
loggingPreferences: {
enabled: true,
all: true
}
}
},
"alfresco/services/UploadService"
],
widgets: [
{
name: "alfresco/upload/AlfFileDrop",
config: {
destinationNodeRef: "workspace://SpacesStore/671536ac-1a87-48a4-9be6-8af97906b71a"
}
},
{
id: "BAD_FILE_DATA",
name: "alfresco/buttons/AlfButton",
config: {
label: "Bad File Data",
publishTopic: "ALF_UPLOAD_REQUEST",
publishPayload: {
files: [
{
size: 0,
name: "Zero Bytes File"
}
],
targetData: {
destination: "some://fake/node"
}
}
}
},
{
id: "NO_FILES_UPLOAD",
name: "alfresco/buttons/AlfButton",
config: {
label: "Provide No Files",
publishTopic: "ALF_UPLOAD_REQUEST",
publishPayload: {
files: [],
targetData: {
destination: "some://fake/node"
}
}
}
},
{
id: "SINGLE_UPLOAD",
name: "alfresco/buttons/AlfButton",
config: {
label: "Single File Upload",
publishTopic: "ALF_UPLOAD_REQUEST",
publishPayload: {
files: [
{
size: 100,
name: "100 Bytes File"
}
],
targetData: {
destination: "some://fake/node"
}
}
}
},
{
id: "MULTI_UPLOAD",
name: "alfresco/buttons/AlfButton",
config: {
label: "Multiple File Upload",
publishTopic: "ALF_UPLOAD_REQUEST",
publishPayload: {
files: [
{
size: 100,
name: "100 Bytes File"
},
{
size: 500,
name: "500 Bytes File"
},
{
size: 700,
name: "700 Bytes File"
},
{
size: 987,
name: "987 Bytes File"
}
],
targetData: {
destination: "some://fake/node"
}
}
}
},
{
name: "aikauTesting/mockservices/UploadMockXhr"
},
{
name: "alfresco/logging/SubscriptionLog"
},
{
name: "aikauTesting/TestCoverageResults"
}
]
}; | nzheyuti/Aikau-aikau/src/test/resources/testApp/WEB-INF/classes/alfresco/site-webscripts/alfresco/upload/Upload.get.js |
/**
* Copyright (C) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.protoeditor.psi;
import com.intellij.lang.ASTNode;
public class ProtoMessageDefinition extends AbstractProtoDefinition {
public ProtoMessageDefinition(ASTNode astNode) {
super(astNode);
}
}
| googlearchive/intellij-protocol-buffer-editor-old-src/com/google/protoeditor/psi/ProtoMessageDefinition.java |
/*
* Titor - Assembler
* Copyright (C) 2012,2013 Sean Ryan Moore
*
* 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 "asmutil.h"
// This assembler is a little strange in the manner of which it operates.
// Instead of assembling and then doing backpatching at link time it parses and extracts labels on the first pass
// it takes those labels and throws them into either the local or the global symbol tables.
// On the second pass each parsed file is turned into machine code through what would normally be called assembly by looking
// up and substituting those label values and translating the arguments into binary machine instructions.
const QString error = "titor";
const QString stage = "assembler";
const QString msg = error+": "+stage+": ";
int main(int argc, char** argv){
try{
if(argc != 3){
throw TitorError (
INCORRECT_ARG_NUMBER,
QString()+argv[0]+" <asm source> <hex file>"
);
}
StreamManager s;
TitorAssembler titor;
// read in the source
QUtfStream& sfile = s.spawnU(argv[1], READ);
QString source(sfile.readAll());
// translate the source
titor.assemble(source);
// open the program output
QDataStream& machine = s.spawnD(argv[2], WRITE);
titor.reportCode(machine);
return 0;
}
catch(TitorError e){
qerr << msg << e.m_error << endl;
return e.m_code;
}
};
| titorgalaxy/Titor-meta/asm/main.cpp |
/**
* Manage the instance of a custom `window.localStorage`
*
* This only encapsulates the setup / teardown logic so that it can easily be
* reused with different implementations (i.e. a spy or a [fake][1])
*
* [1]: https://stackoverflow.com/a/41434763/1708147
*
* @param {() => any} fn Function that returns the object to use for localStorage
*/
const useLocalStorage = fn => {
const origLocalStorage = window.localStorage;
let currentLocalStorage;
Object.defineProperty(window, 'localStorage', {
get: () => currentLocalStorage,
});
beforeEach(() => {
currentLocalStorage = fn();
});
afterEach(() => {
currentLocalStorage = origLocalStorage;
});
};
/**
* Create an object with the localStorage interface but `jest.fn()` implementations.
*/
export const createLocalStorageSpy = () => ({
clear: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
});
/**
* Before each test, overwrite `window.localStorage` with a spy implementation.
*/
export const useLocalStorageSpy = () => useLocalStorage(createLocalStorageSpy);
| stoplightio/gitlabhq-spec/frontend/helpers/local_storage_helper.js |
//
// Context.h
// Example_03
//
// Created by 找塑料 on 16/4/21.
// Copyright © 2016年 Nihility-Ming. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "UnauthorizedState.h"
@interface Context : NSObject
{
@private
id<State> _state;
}
@property (assign, nonatomic, readonly, getter=isAuthorized) BOOL authorized;
@property (strong, nonatomic, readonly) NSString *userId;
- (void)changeStateToAuthorizedWithUserId:(NSString *)userId;
- (void)changeStateToUnauthorized;
@end
| Nihility-Ming/Design_Patterns_In_Objective-C-行为型模式/状态模式/Example_02/Example_03/Context.h |
scaffolds = """
(begin
(define pp (bhammer (sga_preprocess READS)))
(define sp (spades pp))
(define id (idba pp))
(define gam (gam_ngs sp id))
(quast (upload (sspace pp gam)) (upload (get scaffolds sp)) (upload (get scaffolds id)))
)
"""
auto333 = """
(begin
(define pp (bhammer READS))
(define kval (get best_k (kmergenie READS)))
(define vt (begin (setparam hash_length kval) (velvet pp)))
(define ki (begin (setparam k kval) (kiki pp)))
(define sp (spades pp))
(define id (idba pp))
(define ma (masurca pp))
(define di (discovar pp))
(define allsort (sort (list sp id vt ki ma di) > :key (lambda (c) (get ale_score (ale c)))))
(define gam (gam_ngs (slice allsort 0 3)))
(tar (all_files (quast gam di ma id sp ki vt) :name analysis))
)
"""
super = """
(begin
(define pp (bhammer READS))
(define kval (get best_k (kmergenie READS)))
(define vt (begin (setparam hash_length kval) (velvet pp)))
(define sp (spades pp))
(define id (idba pp))
(define ma (masurca pp))
(define di (discovar pp))
(define gam (gam_ngs (sort (list sp id vt ma di) > :key (lambda (c) (n50 c)))))
(tar (all_files (quast (upload gam) (upload sp) (upload id) (upload vt) (upload ma) (upload di))) :name analysis)
)
"""
auto = """
(begin
(define pp (bhammer READS))
(define kval (get best_k (kmergenie READS)))
(define vt (begin (setparam hash_length kval) (velvet pp)))
(define sp (spades pp))
(define allsort (sort (list sp vt) > :key (lambda (c) (get ale_score (ale c)))))
(define gam (gam_ngs allsort))
(define newsort (sort (list gam sp vt) > :key (lambda (c) (get ale_score (ale c)))))
(tar (all_files (quast newsort) :name analysis))
)
"""
| cbun/assembly-lib/assembly/recipes.py |
import BattleshipGame from '../src/battleship-game.js';
import Matrix from '../src/matrix.js';
import Grid from '../src/grid.js';
describe('BattleshipGame', () => {
it('should ensure two players are provided', () => {
expect(() => new BattleshipGame()).toThrow();
expect(() => new BattleshipGame({ })).toThrow();
expect(() => new BattleshipGame({ players: null })).toThrow();
})
it('should default to creating a 10×10 grid', () => {
const player1 = jasmine.createSpyObj('player', ['dispatchEvent']);
const player2 = jasmine.createSpyObj('player', ['dispatchEvent']);
const players = [player1, player2];
const game = new BattleshipGame({ players });
expect(game.rules.grid).toEqual([10, 10]);
})
it('should allow creation of arbitrary size grids', () => {
const player1 = jasmine.createSpyObj('player', ['dispatchEvent']);
const player2 = jasmine.createSpyObj('player', ['dispatchEvent']);
const players = [player1, player2];
const rules = Object.assign(BattleshipGame.DEFAULT_RULES, {
grid: [20, 30]
});
const game = new BattleshipGame({ players, rules });
expect(game.rules.grid).toEqual([20, 30]);
})
it('should ensure grid dimensions are greater than 0', () => {
const player1 = jasmine.createSpyObj('player', ['dispatchEvent']);
const player2 = jasmine.createSpyObj('player', ['dispatchEvent']);
const players = [player1, player2];
expect(() => {
const rules = Object.assign(BattleshipGame.DEFAULT_RULES, {
grid: [0, 10]
});
new BattleshipGame({ players, rules });
}).toThrow();
expect(() => {
const rules = Object.assign(BattleshipGame.DEFAULT_RULES, {
grid: [10, 0]
});
new BattleshipGame({ players, rules });
}).toThrow();
})
it('should allow a player to place ships', () => {
const player1 = jasmine.createSpyObj('player', ['dispatchEvent']);
const player2 = jasmine.createSpyObj('player', ['dispatchEvent']);
const players = [player1, player2];
const game = new BattleshipGame({ players });
const state = game.playerStates.get(player1);
const [shipA] = state.grid.ships;
shipA.position = [0, 0];
})
it('should allow a player to mark placement phase as complete', () => {
const player1 = jasmine.createSpyObj('player', ['dispatchEvent']);
const player2 = jasmine.createSpyObj('player', ['dispatchEvent']);
const players = [player1, player2];
const rules = Object.assign(BattleshipGame.DEFAULT_RULES, {
ships: [
Matrix.rectangle(1, 1)
]
});
const game = new BattleshipGame({ players, rules });
const state = game.playerStates.get(player1);
state.ready = true;
})
/*
todo: this is really testing PlayerState so should be part of the player state
we're also really trying to see if the game reacts to a player dispatching
an attack request
it('should allow a player to fire a shot', () => {
const player1 = jasmine.createSpyObj('player', ['dispatchEvent']);
const player2 = jasmine.createSpyObj('player', ['dispatchEvent']);
const players = [player1, player2];
const rules = Object.assign(BattleshipGame.DEFAULT_RULES, {
ships: [
Matrix.rectangle(1, 1)
]
});
const game = new BattleshipGame({ players, rules });
const shotEventSpy = jasmine.createSpy();
game.addEventListener('shot-fired', shotEventSpy);
const state1 = game.playerStates.get(player1);
const state2 = game.playerStates.get(player2);
const [shipA] = state2.grid.ships;
shipA.position = [0, 0];
game.start();
state1.fire(player2, [0, 0]);
// assert we got a shot event as expected
expect(shotEventSpy).toHaveBeenCalled();
// With({
// type: 'shot-fired',
// target: game,
// attacker: player1,
// defender: player2,
// shot: {
// hit: true,
// sank: true
// }
// });
})
*/
})
| meandmycode/certainly-not-battleships-module/spec/battleship-game-spec.js |
# physics
posted by on .
A car that weighs 15,000 N is initially moving at 60 km/hr when the brakes are applied. The car is brought to a stop in 30 m. Assuming the force applied by the brakes is constant, determine the magnitude of the braking force.
• physics - ,
Force x (stopping distance)
= (initial kinetic energy)
= (1/2) M V^2
For the kinetic energy, you will have to convert the weight (N) to mass (kg) and the 60 km/hr initial velocity to m/s. I assume you know how to do this.
• physics - ,
Thanks you for your quick reply. I really appreciated it, although I still cannot find the way to get the answer which is 7,086.7 N.
• physics - ,
m = 15,000/9.8 = 1530 kg
v = 60,000 m/3600 s = 16.7 m/s
(1/2) m v^2 = 212,500 Joules
F (30) = 212,500
F = 7083 N
• physics - ,
Make certain you convert the weight 15000N to mass.
Force= .5 M V^2/distance=
= .5 (Weight/g)V^2 /distance3=
= .5(15,000/9.8)*16.66^2 /30
and that gives the right answer. | finemath-3plus |
'use strict';
var express = require('express'),
Grid = require('gridfs-stream'),
errorHandler = require('errorhandler'),
config = require('meanio').loadConfig(),
fs = require('fs'),
appPath = process.cwd();
var mean = require('meanio');
module.exports = function(options, db) {
// Register app dependency;
mean.register('app', function(access, database) {
require(appPath + '/config/express')(app, access.passport, database.connection);
return app;
});
// Express settings
var app = express();
var gfs = new Grid(db.connection.db, db.mongo);
app.get('/modules/aggregated.js', function(req, res) {
res.setHeader('content-type', 'text/javascript');
mean.aggregated('js', req.query.group ? req.query.group : 'footer', function(data) {
res.send(data);
});
});
function themeHandler(req, res) {
res.setHeader('content-type', 'text/css');
gfs.files.findOne({
filename: 'theme.css'
}, function(err, file) {
if (!file) {
fs.createReadStream(config.root + '/bower_components/bootstrap/dist/css/bootstrap.css').pipe(res);
} else {
// streaming to gridfs
var readstream = gfs.createReadStream({
filename: 'theme.css'
});
//error handling, e.g. file does not exist
readstream.on('error', function(err) {
console.log('An error occurred!', err.message);
throw err;
});
readstream.pipe(res);
}
});
}
// We override this file to allow us to swap themes
// We keep the same public path so we can make use of the bootstrap assets
app.get('/bower_components/bootstrap/dist/css/bootstrap.css', themeHandler);
app.get('/modules/aggregated.css', function(req, res) {
res.setHeader('content-type', 'text/css');
mean.aggregated('css', req.query.group ? req.query.group : 'header', function(data) {
res.send(data);
});
});
app.use(function(req,res,next){
req.manifest = options.webapp ? options.webapp.route : null;
next();
});
app.use('/packages', express.static(config.root + '/packages'));
app.use('/bower_components', express.static(config.root + '/bower_components'));
mean.events.on('modulesEnabled', function() {
for (var name in mean.modules) {
app.use('/' + name, express.static(config.root + '/' + mean.modules[name].source + '/' + name.toLowerCase() + '/public'));
}
// We are going to catch everything else here
app.route('*').get(function(req, res, next) {
if (!mean.template) return next();
mean.template(req, res, next);
});
// Assume "not found" in the error msgs is a 404. this is somewhat
// silly, but valid, you can do whatever you like, set properties,
// use instanceof etc.
app.use(function(err, req, res, next) {
// Treat as 404
if (~err.message.indexOf('not found')) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not found'
});
});
// Error handler - has to be last
if (process.env.NODE_ENV === 'development') {
app.use(errorHandler());
}
});
//WEBAPP CONFIG
if (!!options.webapp.route){
app.get(options.webapp.route,options.webapp.cb);
}
return app;
};
| Luka111/TDRAnketa-node_modules/meanio/lib/bootstrap.js |
Як унікальны менскі заказьнік зьмяншаюць дзеля дарагіх дамоў і рэстарана (мапа) - Салiдарнасць
Як унікальны менскі заказьнік зьмяншаюць дзеля дарагіх дамоў і рэстарана (мапа)
За апошнія гады ад тэрыторыі заказьніка «Лебядзіны» каля Менску адрэзалі пад будаўніцтва 8 га зямлі. Радыё Свабода прасачыла, як мяняліся межы «Лебядзінага» і як заказьнік атачае забудова.
Рэспубліканскіх біялягічных заказьнікаў у Менскім раёне два. Адзін — «Сьціклева», на паўднёвым усходзе сталіцы. Другі — «Лебядзіны», на паўночным усходзе. Хоць ён цалкам у межах гораду, але заўсёды адзначаўся вялізнай біялягічнай разнастайнасьцю. Арнітолягі заўважалі тут вельмі рэдкія віды птушак, а менчукі лёгка дабіраліся сюды на гарадзкім транспарце.
Цяпер «Лебядзіны» знакаміты скандальнай будоўляй і шыкоўным рэстаранам.
Разьбіраемся, як гэта стала магчымым.
Як мянялі межы «Лебядзінага»
У 2007 годзе плошча рэспубліканскага біялягічнага заказьніка «Лебядзіны» складала 51,5235 га. Пра гэта сьведчыць пастанова Савету міністраў Беларусі. У красавіку 2015 году, па дадзеных Міністэрства прыродных рэсурсаў і аховы навакольнага асяродзьдзя Беларусі, плошча «Лебядзінага» складае ўжо 43,49 га. То бок за гэты час плошча скарацілася на 8,0335 га.
5 сьнежня 2018 году прэзыдэнт выдае ўказ, паводле якога зь ляндшафтна-рэкрэацыйнай зоны заказьніка ў межах праспэкту Пераможцаў і вуліцы Ратамскай выключылі ўчастак плошчай 1,57 гектара і ўключылі яго ў склад ляндшафтна-рэкрэацыйнай падзоны. Юрыдычна гэта азначае, што тэрыторыя пераведзена з зоны зь нізкай рэкрэацыйнай нагрузкай — у зону з высокай рэкрэацыйнай нагрузкай.
Гэтым жа прэзыдэнцкім указам 0,13 га тэрыторыі заказьніка, якая лічылася пад асаблівай аховай, перавялі ў разрад прыроднай ляндшафтна-рэкрэацыйнай тэрыторыі зь нізкай рэкрэацыйнай нагрузкай.
На практыцы ўсе гэтыя зьмены азначаюць, што названую «зялёную» тэрыторыю раней нельга было забудоўваць — а цяпер можна.
Зьмены, пра якія тут гаворка, фактычна ўзаконілі будаўніцтва кампаніяй «Тапас» рэстарана каля заказьніка «Лебядзіны» на тэрыторыі, што раней лічылася буфэрнай паміж заказьні | c4-be |
//
// AppDelegate.h
//
//
// Created by Mizushima Kota on 12/06/12.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "HTTPServer.h"
@class TRViewController;
@interface TRAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) TRViewController *viewController;
@end
| kmizu/TiREST-Classes/TRAppDelegate.h |
/***********************************************************************************
**
** GumpWorldMap.h
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#ifndef GUMPWORLDMAP_H
#define GUMPWORLDMAP_H
//----------------------------------------------------------------------------------
class CGumpWorldMap : public CGump
{
public:
int Width = MIN_WORLD_MAP_WIDTH;
int Height = MIN_WORLD_MAP_HEIGHT;
protected:
int m_Scale = 2;
public:
int GetScale() { return m_Scale; };
void SetScale(int val);
protected:
int m_Map = 0;
public:
int GetMap() { return m_Map; };
void SetMap(int val);
protected:
bool m_LinkWithPlayer = true;
public:
bool GetLinkWithPlayer() { return m_LinkWithPlayer; };
void SetLinkWithPlayer(bool val);
int OffsetX = 0;
int OffsetY = 0;
bool Called = false;
int CurrentOffsetX = 0;
int CurrentOffsetY = 0;
private:
static constexpr int ID_GWM_MINIMIZE = 1;
static constexpr int ID_GWM_RESIZE = 2;
static constexpr int ID_GWM_MAP = 3;
static constexpr int ID_GWM_LINK_WITH_PLAYER = 4;
static constexpr int ID_GWM_MAP_LIST = 10;
static constexpr int ID_GWM_SCALE_LIST = 20;
static constexpr int MIN_WORLD_MAP_HEIGHT = 300;
static constexpr int MIN_WORLD_MAP_WIDTH = 400;
int m_StartResizeWidth{ 0 };
int m_StartResizeHeight{ 0 };
bool m_MapMoving{ false };
void FixOffsets(int &offsetX, int &offsetY, int &width, int &height);
void GetScaledDimensions(int &width, int &height, int &playerX, int &playerY);
void GetCurrentCenter(int &x, int &y, int &mouseX, int &mouseY);
void ScaleOffsets(int newScale, int mouseX, int mouseY);
void LoadMap(int map);
int GetCurrentMap();
CGUIButton *m_Minimizer{ NULL };
CGUIResizepic *m_Background{ NULL };
CGUIResizeButton *m_Resizer{ NULL };
CGUIText *Text{ NULL };
CGUICheckbox *m_Checkbox{ NULL };
CGUIScissor *m_Scissor{ NULL };
CGUIWorldMapTexture *m_MapData{ NULL };
CGUIComboBox *m_ComboboxScale{ NULL };
CGUIComboBox *m_ComboboxMap{ NULL };
protected:
virtual void CalculateGumpState();
public:
CGumpWorldMap(short x, short y);
virtual ~CGumpWorldMap();
void UpdateSize();
virtual bool CanBeDisplayed() { return Called; }
virtual void GenerateFrame(bool stop);
virtual void PrepareContent();
GUMP_BUTTON_EVENT_H;
GUMP_CHECKBOX_EVENT_H;
GUMP_COMBOBOX_SELECTION_EVENT_H;
GUMP_RESIZE_START_EVENT_H;
GUMP_RESIZE_EVENT_H;
GUMP_RESIZE_END_EVENT_H;
virtual void OnLeftMouseButtonDown();
virtual void OnLeftMouseButtonUp();
virtual bool OnLeftMouseButtonDoubleClick();
virtual void OnMidMouseButtonScroll(bool up);
};
//----------------------------------------------------------------------------------
#endif
//----------------------------------------------------------------------------------
| Hotride/OrionUO-OrionUO/Gumps/GumpWorldMap.h |
Related Works
**Bilevel optimization via AID and ITD.** AID and ITD are two popular approaches to reduce the computational challenging in approximating the outer-level gradient (which is often called hypergradient in the literature). In particular, AID-based bilevel algorithms (Domke, 2012; Pedregosa, 2016; Gould et al., 2016; Liao et al., 2018; Grazzi et al., 2020; Lorraine et al., 2020; Ji and Liang, 2021; MacKay et al., 2019) approximate the hypergraident efficiently via implicit differentiation combined with a linear system solver. ITD-based approaches (Domke, 2012; Maclaurin et al., 2015; Franceschi et al., 2017, 2018; Shaban et al., 2019; Grazzi et al., 2020; MacKay et al., 2019) approximate the inner-level problem using a dynamic system. For example, Franceschi et al. (2017, 2018) computed the hypergradient via reverse or forward mode in automatic differentiation. This paper proposes a novel contrained optimization based approach for bilevel optimization.
**Optimization theory for bilevel optimization.** Some works such as (Franceschi et al., 2018; Shaban et al., 2019) analyzed the asymptotic convergence performance of AID- and ITD-based bilevel algorithms. Other works Ghadimi and Wang (2018); Rajeswaran et al. (2019); Grazzi et al. (2020); Ji et al. (2020, 2021); Ji and Liang (2021) provided convergence rate analysis for various AID- and ITD-based approaches and their variants in applications such as meta-learning. Recent works Hong et al. (2020); Ji et al. (2021); Yang et al. (2021); Khanduri et al. (2021); Chen et al. (2021); Guo and Yang (2021) developed convergence rate analysis for their proposed stochastic bilevel optimizers. This paper provides the first-known convergence rate analysis for the setting with multiple inner minima.
**Bilevel optimization with multiple inner minima.** Sabach and Shtern in Sabach and Shtern (2017) proposed a bilevel gradient sequential averaging method (BiG-SAM) for _single_-variable bilevel optimization (i.e., without variable \(x\)), and provided an asymptotic convergence analysis for this algorithm. For general bilevel problems, the authors in Liu et al. (2020); Li et al. (2020) used an idea similar to BiG-SAM, and proposed a gradient aggregation approach for the general bilevel problem in eq. (1) with an asymptotic convergence guarantee. Further, Liu et. al. Liu et al. (2021) proposed a constrained optimization method and further applied the log-barrier interior-point method for solving the constrained problem. Differently from the above studies that update the outer variable \(x\) after fully updating \(y\), our PDBO and Proximal-PDBO algorithms treat both \(x\) and \(y\) together as a single updating variable \(z\). Further, we characterize the first known convergence rate guarantee for the type of bilevel problems with multiple inner minima.
We further mention that Liu et al. in Liu et al. (2021) proposed an initialization auxiliary algorithm for the bilevel problems with a nonconvex inner objective function.
## 2 Problem Formulation
We study a bilevel optimization problem given in eq. (1), which is restated below
\[\min_{x\in\mathcal{X},y\in\mathcal{S}_{x}}f(x,y)\quad\text{with}\quad\mathcal{S}_ {x}=\operatorname*{arg\,min}_{y\in\mathcal{Y}}g(x,y),\]
where the outer- and inner-level objective functions \(f(x,y)\) and \(g(x,y)\) are continuously differentiable, and the supports \(\mathcal{X}\) and \(\mathcal{Y}\) are convex and closed subsets of \(\mathbb{R}^{p}\) and \(\mathbb{R}^{d}\), respectively. For a fixed \(x\in\mathcal{X}\), \(\mathcal{S}_{x}\) is the set of all \(y\in\mathcal{Y}\) that yields the minimal value of \(g(x,\cdot)\). In this paper, we consider the function \(g\) that is a convex function on \(y\) for any fixed \(x\) (as specified in Assumption 1). The convexity of \(g(x,y)\) on \(y\) still allows the inner function \(g(x,\cdot)\) to have multiple global minimal points, and the challenge for bilevel algorithm design due to multiple inner minima still remains. Further, the set \(\mathcal{S}_{x}\) of minimizers is convex due to convexity of \(g(x,y)\) w.r.t. \(y\). We note that \(g(x,y)\) and the outer function \(f(x,y)\) can be nonconvex w.r.t \((x,y)\) in general or satisfy certain convexity-type conditions which we will specify for individual cases. We further take the standard gradient Lipschitz assumption on the inner and outer objective functions. The formal statements of our assumptions are presented below.
**Assumption 1**.: _The objective functions \(f(x,y)\) and \(g(x,y)\) are gradient Lipschitz functions. There exists \(\rho_{f},\rho_{g}\geq 0\), such that, for any \(z=(x,y)\in\mathcal{X}\times\mathcal{Y}\) and \(z^{\prime}=(x^{\prime},y^{\prime})\in\mathcal{X}\times\mathcal{Y}\), the following inequalities hold_
\[\|\nabla f(z)-\nabla f(z^{\prime})\|_{2}\leq\rho_{f}\|z-z^{\prime}\|_{2}, \qquad\qquad\qquad\|\nabla g(z)-\nabla g(z^{\prime})\|_{2}\leq\rho_{g}\|z-z^{ \prime}\|_{2}.\]
_Moreover, for any fixed \(x\in\mathcal{X}\), we assume \(g(x,y)\) is a convex function on \(y\), and the following inequality holds for all \(x,x^{\prime}\in\mathcal{X}\) and \(y,y^{\prime}\in\mathcal{Y}\)_
\[g(x^{\prime},y^{\prime})\geq g(x,y)+\langle\nabla_{x}g(x,y),x^{\prime}-x \rangle+\langle\nabla_{y}g(x,y),y^{\prime}-y\rangle-\tfrac{\rho_{g}}{2}\|x-x^ {\prime}\|_{2}^{2}.\]
To solve the bilevel problem in eq. (1), one challenge is that it is not easy to explicitly characterize the set \(\mathcal{S}_{x}\) of the minimal points of \(g(x,y)\). This motivates the idea to describe such a set implicitly via a constraint. A common practice is to utilize the so-called lower-level value function (LLVF) to reformulate the problem to an equivalent single-level optimization Dempe & Zemkoho (2020). Specifically, let \(g^{*}(x)\coloneqq\min_{y\in\mathcal{Y}}g(x,y)\). Clearly, the set \(\mathcal{S}_{x}\) can be described as \(\mathcal{S}_{x}=\{y\in\mathcal{Y}:g(x,y)\leq g^{*}(x)\}\). In this way, the bilevel problem in eq. (1) can be equivalently reformulated to the following constrained optimization problem:
\[\min_{x\in\mathcal{X},y\in\mathcal{Y}}f(x,y)\quad\text{s.t.}\quad g(x,y)\leq g ^{*}(x).\]
Since \(g(x,y)\) is convex with respect to \(y\), \(g^{*}(x)\) in the constraint can be obtained efficiently via various convex minimization algorithms such as gradient descent.
To further simplify the notation, we let \(z=(x,y)\in\mathbb{R}^{p+d}\), \(\mathcal{Z}=\mathcal{X}\times\mathcal{Y}\), \(f(z):=f(x,y)\), \(g(z):=g(x,y)\), and \(g^{*}(z):=g^{*}(x)\). As stated earlier, both \(\mathcal{X}\) and \(\mathcal{Y}\) are bounded and closed set. The boundedness of \(\mathcal{Z}\) is then immediately established, and we denote \(D_{\mathcal{Z}}=\sup_{z,z^{\prime}\in\mathcal{Z}}\|z-z^{\prime}\|_{2}\). The equivalent single-level constrained optimization could be expressed as follows.
\[\min_{z\in\mathcal{Z}}f(z)\quad\text{s.t.}\quad\quad h(z)\coloneqq g(z)-g^{*}( z)\leq 0. \tag{2}\]
Thus, solving the bilevel problem in eq. (1) is converted to solving an equivalent single-level optimization in eq. (2). To enable the algorithm design for the constrained optimization problem in eq. (2), we further maketwo standard changes to the constraint function. (i) Since the constraint is nonsmooth, i.e., \(g^{*}(z):=g^{*}(x)\) is nonsmooth in general, the design of gradient-based algorithm is not direct. We thus relax the constraint by replacing \(g^{*}(z)\) with a smooth term
\[\tilde{g}^{*}(z):=\tilde{g}^{*}(x)=\min_{y\in\mathcal{Y}}\big{\{} \tilde{g}(x,y)\coloneqq g(x,y)+\tfrac{\alpha}{2}\|y\|^{2}\big{\}},\]
where \(\alpha>0\) is a small prescribed constant. It can be shown that for a given \(x\), \(\tilde{g}(x,y)\) has a unique minimal point, and the function \(\tilde{g}^{*}(x)\) becomes differentiable with respect to \(x\). Hence, the constraint becomes \(g(z)-\tilde{g}^{*}(z)\leq 0\), which is differentiable. (ii) The constraint is not sufficiently strictly feasible, i.e., the constraint cannot be satisfied with a certain margin on every \(x\in\mathcal{X}\), due to which it is difficult to design an algorithm with convergence guarantee. We hence further relax the constraint by introducing a positive small constant \(\delta\) so that the constraint becomes \(g(z)-\tilde{g}^{*}(z)-\delta\leq 0\) that admits strict feasible points such that the constraint is less than \(-\delta\). Given the above two relaxations, our algorithm design will be based on the following best-structured constrained optimization problem
\[\min_{z\in\mathcal{Z}}f(z)\quad\text{s.t.}\quad\tilde{h}(z)\coloneqq g(z)- \tilde{g}^{*}(z)-\delta\leq 0. \tag{3}\]
## 3 Primal-Dual Bilevel Optimizer (PDBO)
In this section, we first propose a simple PDBO algorithm, and then show that PDBO converges under certain convexity-type conditions. We handle more general \(f\) and \(g\) in Section 4. | 2203.01123v2.mmd |
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/scenario1_Events.html", {
ready: function (element, options) {
document.getElementById("registerReadingChanged").addEventListener("click", registerUnregisterReadingChanged, false);
document.getElementById("registerReadingChanged").disabled = true;
Windows.Devices.Sensors.Pedometer.getDefaultAsync().then(function (pedometer) {
if (!pedometer) {
WinJS.log && WinJS.log("No Pedomter found", "sample", "error");
}
else {
WinJS.log && WinJS.log("Default Pedometer opened", "sample", "status");
pedometer.reportInterval = 1000;
}
defaultPedometer = pedometer;
// enable button if pedometer is successfully opened
document.getElementById("registerReadingChanged").disabled = false;
},
function error(e) {
WinJS.log && WinJS.log("Error when opening default pedometer. " + e.message, "sample", "error");
}
)
},
unload: function () {
document.removeEventListener("visibilitychange", visibilityChangeHandler, false);
document.getElementById("registerReadingChanged").innerText = "Register ReadingChanged";
// Return the report interval to its default to release resources while the sensor is not in use
if (defaultPedometer) {
defaultPedometer.reportInterval = 0;
defaultPedometer.removeEventListener("readingchanged", onReadingChanged);
registeredForEvent = false;
}
}
});
var registeredForEvent = false;
var defaultPedometer = null;
var totalStepsCount = 0;
var unknownStepsCount = 0;
var walkingStepsCount = 0;
var runningStepsCount = 0;
function visibilityChangeHandler() {
// This is the event handler for VisibilityChanged events. You would register for these notifications
// if handling sensor data when the app is not visible could cause unintended actions in the app.
if (document.msVisibilityState === "visible") {
// Re-enable sensor input. No need to restore the desired reportInterval (it is restored for us upon app resume)
defaultPedometer.addEventListener("readingchanged", onReadingChanged);
} else {
// Disable sensor input. No need to restore the default reportInterval (resources will be released upon app suspension)
defaultPedometer.removeEventListener("readingchanged", onReadingChanged);
}
}
/// <summary>
/// Helper function to register/un-register to the 'readingchanged' event of the default pedometer
/// </summary>
function registerUnregisterReadingChanged() {
if (registeredForEvent) {
WinJS.log && WinJS.log("Unregistering for event invoked", "sample", "error");
defaultPedometer.removeEventListener("readingchanged", onReadingChanged, false);
document.getElementById("registerReadingChanged").innerText = "Register ReadingChanged";
registeredForEvent = false;
document.removeEventListener("visibilitychange", visibilityChangeHandler, false);
WinJS.log && WinJS.log("Unregsitered for event", "sample", "status");
}
else {
document.addEventListener("visibilitychange", visibilityChangeHandler, false);
defaultPedometer.addEventListener("readingchanged", onReadingChanged);
document.getElementById("registerReadingChanged").innerText = "Unregister ReadingChanged";
registeredForEvent = true;
WinJS.log && WinJS.log("Regsitered for event", "sample", "status");
}
}
/// <summary>
/// Invoked when the underlying pedometer sees a change in the step count for a step kind.
/// </summary>
/// <param name="sender">unused</param>
function onReadingChanged(e) {
var reading = e.reading;
var newStepsTaken = 0;
var readingTimeStamp = document.getElementById("readingTimeStamp");
var duration = 0;
// Event can still be in queue after unload is called
// so check if elements are still loaded.
// update html page
if (readingTimeStamp) {
readingTimeStamp.innerText = reading.timestamp;
switch (reading.stepKind) {
case Windows.Devices.Sensors.PedometerStepKind.unknown:
newStepsTaken = reading.cumulativeSteps - unknownStepsCount;
unknownStepsCount = reading.cumulativeSteps;
document.getElementById("unknownCount").innerHTML = unknownStepsCount;
document.getElementById("unknownDuration").innerHTML = reading.cumulativeStepsDuration;
break;
case Windows.Devices.Sensors.PedometerStepKind.walking:
newStepsTaken = reading.cumulativeSteps - walkingStepsCount;
walkingStepsCount = reading.cumulativeSteps;
document.getElementById("walkingCount").innerHTML = walkingStepsCount;
document.getElementById("walkingDuration").innerHTML = reading.cumulativeStepsDuration;
break;
case Windows.Devices.Sensors.PedometerStepKind.running:
newStepsTaken = reading.cumulativeSteps - runningStepsCount;
runningStepsCount = reading.cumulativeSteps;
document.getElementById("runningCount").innerHTML = runningStepsCount;
document.getElementById("runningDuration").innerHTML = reading.cumulativeStepsDuration;
break;
default:
WinJS.log && WinJS.log("Invalid Step Kind", "sample", "error");
break;
}
totalStepsCount += newStepsTaken;
document.getElementById("totalStepsCount").innerText = totalStepsCount.toString();
WinJS.log && WinJS.log("Getting readings", "sample", "status");
}
}
})();
| justasmal/Windows-universal-samples-pedometer/js/js/scenario1_events.js |
module.exports = SoftSetHook;
function SoftSetHook(value) {
if (!(this instanceof SoftSetHook)) {
return new SoftSetHook(value);
}
this.value = value;
}
SoftSetHook.prototype.hook = function (node, propertyName) {
if (node[propertyName] !== this.value) {
node[propertyName] = this.value;
}
};
| emkay/node-on-the-road-node_modules/mercury/node_modules/virtual-hyperscript/hooks/soft-set-hook.js |
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_map<string, int> wordIndexes;
size_t maxLen = 0;
for (int i = 0, n = wordDict.size(); i < n; ++i) {
wordIndexes.emplace(wordDict[i], i);
maxLen = max(maxLen, wordDict[i].size());
}
const auto PB = s.data(), PE = PB + s.size();
unordered_map<const char*, unique_ptr<vector<Ids>>> cache;
cache[PE] = myMakeUnique();
auto pIdsVec = myWordBreak(PB, PE, maxLen, wordIndexes, cache);
vector<string> ret;
if (pIdsVec) {
for (auto& ids : *pIdsVec) {
ret.emplace_back();
for (auto i : ids) {
ret.back().append(wordDict[i] + ' ');
}
if (!ret.empty()) ret.back().pop_back();
}
}
return ret;
}
private:
using Ids = vector<int>;
inline unique_ptr<vector<Ids>> myMakeUnique() {
return unique_ptr<vector<Ids>>(new vector<Ids>());
}
vector<Ids>* myWordBreak(const char* const PB, const char* const PE, const size_t maxLen,
const unordered_map<string, int>& wordIndexes,
unordered_map<const char*, unique_ptr<vector<Ids>>>& cache) {
// found in cache
auto it = cache.find(PB);
if (it != cache.end()) return it->second.get();
// default
cache[PB] = nullptr;
string word;
word.reserve(maxLen);
const auto ITWE = wordIndexes.end();
auto itw = ITWE;
for (auto p = PB; p < PE && word.size() < maxLen; ++p) {
word.append(1, *p);
itw = wordIndexes.find(word);
// found word
if (itw != ITWE) {
auto pIdsVec = myWordBreak(p + 1, PE, maxLen, wordIndexes, cache);
if (pIdsVec) {
if (!cache[PB]) cache[PB] = myMakeUnique();
auto& idsVec = *cache[PB];
if (pIdsVec->empty()) {
idsVec.emplace_back(1, itw->second);
} else {
for (auto& ids : *pIdsVec) {
idsVec.emplace_back(1, itw->second);
idsVec.back().insert(idsVec.back().end(), ids.begin(), ids.end());
}
}
}
}
}
return cache[PB].get();
}
};
| longztian/cpp-leetcode/140_Word_Break_II.cpp |
(function(window)
{
var Gitana = window.Gitana;
Gitana.BillingProviderConfigurationMap = Gitana.AbstractPlatformObjectMap.extend(
/** @lends Gitana.BillingProviderConfigurationMap.prototype */
{
/**
* @constructs
* @augments Gitana.AbstractMap
*
* @class Map of billing provider configurations
*
* @param {Gitana.Platform} platform Gitana platform instance.
* @param [Object] object
*/
constructor: function(platform, object)
{
this.objectType = function() { return "Gitana.BillingProviderConfigurationMap"; };
//////////////////////////////////////////////////////////////////////////////////////////////
//
// CALL THROUGH TO BASE CLASS (at the end)
//
//////////////////////////////////////////////////////////////////////////////////////////////
this.base(platform, object);
},
/**
* @override
*/
clone: function()
{
return this.getFactory().billingProviderConfigurationMap(this.getPlatform(), this);
},
/**
* @param json
*/
buildObject: function(json)
{
return this.getFactory().billingProviderConfiguration(this.getPlatform(), json);
}
});
})(window);
| gitana/gitana-javascript-driver-js/gitana/platform/BillingProviderConfigurationMap.js |
ChapskyDay в Минске - стоимость входа, отзывы о событии на afisha.relax.by
ChapskyDay
Возрастное ограничение 18+ 15 жніўня адзін з выдатнейшых мэраў Мінска, Ян Караль Чапскі святкуе Дзень народзінаў. «Аліварыя» запрашае ўсіх, хто любіць і шануе беларускую гісторыю і марыць зрабіць свой горад лепш, падняць келіх піва ў гонар графа Чапскага!
Менавіта ў гэты дзень лепшыя піўныя бары Мінска напоўняцца гулам і весялосцю, звонам келіхаў і шумнымі кампаніямі. Запрашаем кожнага на маштабнае піўное свята ў лепшых барах горада. Смачнае піва, незвычайныя пачастункі і мора прызоў – усе для гасцей #ChapskyDay. 15 жніўня з 20:00 да 23:00 - ТЫ. ПАВІНЕН. БЫЦЬ. У БАРЫ. #ChapskyDay святкуюць: • У Ратуши (вул. Герцэна, 1)
• Закон Бутерброда (вул. Рэвалюцыйная, 12)
• TNT Rock Club (вул. Рэвалюцыйная, 9)
• Doodah King Bar (вул. Берсана, 14)
• Бар «Койот» , (пр-т Незалежнасці, 117а)
Все события твоего города в мобильном приложении relax.by. Найди «relax.by» в своем маркете: App Store, Google Play! Отзывы MAKSIMCHUK VALERIA 22 августа 2015 в 02:46
Самое интересное всегда 18+) Ну ничего. Прежде пускай узнают о том, кто вообще такой Чапский. Да и всем бы не помешало. КУКУРУЗИНА ЖЕНЯ 23 августа 2015 в 00:04
Кстати, неплохое пиво пробовали. Видели этот трамвай, и катались. Честно, даже не думала, что Минск способен на такие праздники. Скорей бы уже везде так. ПУШКО ВАЛЕНТИН 24 августа 2015 в 10:21
Ой, а мы не попали( Но так интересно! Если бы все выходные такие праздники проводились, было бы вообще круто! ЗАВИРОВ ДАНИИЛ 24 августа 2015 в 22:23
Эх) побольше бы таких трамваев и побольше бы дней на то, чтобы они ходили))))) ОСТАВЬТЕ ОТЗЫВ | c4-be |
Single Frauen Bielefeld. Aktuelles aus OWL - Neue Westfälische
Arminia Bielefeld Trotz Führung: Arminia verliert beim Heimdebüt von Neuhaus . Arminia Bielefeld muss sich bei der Heimpremiere von Uwe Neuhaus dem 1.
Single frauen bielefeld (Page 7 of 29)
Aktuelles aus OWL - Neue Westfälische → Aktuelles aus OWL - Neue Westfälische
Topics: 1 to 29 of 321
1 Topic by Moore 2019-05-24 11:32:19
1 Reply by Ramirez 2019-05-24 12:13:40
Re: Single frauen bielefeld
2 Reply by Thompson 2019-05-24 12:34:52
3 Reply by Adams 2019-05-24 12:47:56
4 Reply by Ross 2019-05-24 13:39:26
5 Reply by Nguyen 2019-05-24 14:33:57
6 Reply by Rodriguez 2019-05-24 14:35:34
7 Reply by Cook 2019-05-24 14:47:34
8 Reply by Roberts 2019-05-24 15:33:03
9 Reply by Anderson 2019-05-24 15:34:37
2019-05-24 10:32 Arminia Bielefeld Trotz Führung: Arminia verliert beim Heimdebüt von Neuhaus . Arminia Bielefeld muss sich bei der Heimpremiere von Uwe Neuhaus dem 1.
10 Reply by Young 2019-05-24 16:29:10
11 Reply by Baker 2019-05-24 16:56:15
12 Reply by Powell 2019-05-24 17:17:32
Hall → Single frauen bielefeld | c4-de |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "NSThread.h"
@interface MCWorkerThread : NSThread
{
}
+ (id)theThread;
- (void)main;
@end
| matthewsot/CocoaSharp-Headers/PrivateFrameworks/ManagedConfiguration/MCWorkerThread.h |
//
// AppDelegate.h
// 2-综合多视图布局
//
// Created by mac on 16/6/17.
// Copyright (c) 2016年 mac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| zhaoxiaobin156/net-6.17day5/2-综合多视图布局/2-综合多视图布局/AppDelegate.h |
/*!
* medium-editor-insert-plugin v0.2.9 - jQuery insert plugin for MediumEditor
*
* https://github.com/orthes/medium-editor-insert-plugin
*
* Copyright (c) 2014 Pavel Linkesch (http://linkesch.sk)
* Released under the MIT license
*/
(function ($) {
$.fn.mediumInsert.registerAddon('embeds', {
/**
* Embed default options
*/
default: {
urlPlaceholder: 'type or paste url here'
},
/**
* Embeds initial function
* @return {void}
*/
init : function (options) {
this.options = $.extend(this.default, options);
this.$el = $.fn.mediumInsert.insert.$el;
this.setEmbedButtonEvents();
this.preparePreviousEmbeds();
},
insertButton : function (buttonLabels) {
var label = 'Embed';
if (buttonLabels == 'fontawesome' || typeof buttonLabels === 'object' && !!(buttonLabels.fontawesome)) {
label = '<i class="fa fa-code"></i>';
}
return '<button data-addon="embeds" data-action="add" class="medium-editor-action mediumInsert-action">' + label + '</button>';
},
/**
* Add embed to $placeholder
* @param {element} $placeholder $placeholder to add embed to
* @return {void}
*/
add : function ($placeholder) {
$.fn.mediumInsert.insert.deselect();
var formHtml = '<div class="medium-editor-toolbar-form-anchor mediumInsert-embedsWire" style="display: block;"><input type="text" value="" placeholder="' + this.options.urlPlaceholder + '" class="mediumInsert-embedsText"></div>';
$(formHtml).appendTo($placeholder.prev());
setTimeout(function () {
$placeholder.prev().find('input').focus();
}, 50);
$.fn.mediumInsert.insert.deselect();
this.currentPlaceholder = $placeholder;
$(".mediumInsert-embedsText").focus();
},
/**
* Make existing embeds interactive
*
* @return {void}
*/
preparePreviousEmbeds: function () {
this.$el.find('.mediumInsert-embeds').each(function() {
var $parent = $(this).parent();
$parent.html('<div class="mediumInsert-placeholder" draggable="true">' + $parent.html() + '</div>');
});
},
setEmbedButtonEvents : function () {
var that = this;
$(document).on('keypress', 'input.mediumInsert-embedsText', function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
that.setEnterActionEvents();
that.removeToolbar();
}
});
this.$el.on('blur', '.mediumInsert-embedsText', function () {
that.removeToolbar();
});
},
setEnterActionEvents : function () {
var that = this;
if ($.fn.mediumInsert.settings.enabled === false) {
return false;
}
var url = $("input.mediumInsert-embedsText").val();
if (!url) {
return false;
}
var embed_tag = that.convertUrlToEmbedTag(url);
if (!embed_tag) {
alert('Incorrect URL format specified');
return false;
} else {
embed_tag = $('<div class="mediumInsert-embeds"></div>').append(embed_tag);
that.currentPlaceholder.append(embed_tag);
that.currentPlaceholder.closest('[data-medium-element]').trigger('keyup').trigger('input');
}
},
removeToolbar : function () {
$(".mediumInsert-embedsWire").remove();
},
convertUrlToEmbedTag : function (url) {
var embed_tag = url.replace(/\n?/g, '').replace(/^((http(s)?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/(watch\?v=|v\/)?)([a-zA-Z0-9-_]+)(.*)?$/, '<div class="video"><iframe width="420" height="315" src="//www.youtube.com/embed/$7" frameborder="0" allowfullscreen></iframe></div>')
.replace(/http:\/\/vimeo\.com\/(\d+)$/, '<iframe src="//player.vimeo.com/video/$1" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>')
// TWITTER EMBEDDING NEEDS REWORK! Serialized version of embeded Twitter status is unusable because the Twitter script complitely removes blockquote element and replaces it with iframe
//.replace(/https:\/\/twitter\.com\/(\w+)\/status\/(\d+)\/?$/, '<blockquote class="twitter-tweet" lang="en"><a href="https://twitter.com/$1/statuses/$2"></a></blockquote><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>')
// FACEBOOK EMBEDDING NEEDS REWORK! Similarly to Twitter, FB script removes .fb-post element and replaces it with iframe, which is unusable after serializing editor's content
//.replace(/https:\/\/www\.facebook\.com\/(\w+)\/posts\/(\d+)$/, '<div id="fb-root"></div><script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));</script><div class="fb-post" data-href="https://www.facebook.com/$1/posts/$2"></div>')
.replace(/http:\/\/instagram\.com\/p\/(.+)\/?$/, '<span class="instagram"><iframe src="//instagram.com/p/$1/embed/" width="612" height="710" frameborder="0" scrolling="no" allowtransparency="true"></iframe></span>');
return /<("[^"]*"|'[^']*'|[^'">])*>/.test(embed_tag) ? embed_tag : false;
}
});
}(jQuery));
| dakshshah96/cdnjs-ajax/libs/medium-editor-insert-plugin/0.2.9/js/addons/medium-editor-insert-embeds.js |
module.exports = ctx => ({
"map": {inline: false},
"plugins": {
"cssnano": {preset: 'default'},
"postcss-cssnext": {},
"postcss-import": {},
"postcss-url": {},
"autoprefixer": {},
"postcss-custom-properties": {},
"postcss-calc": {},
}
});
| hungryfat92/hungryfat92.github.io-postcss.config.js |
# frozen_string_literal: true
require 'rails_helper'
# @note this class is an abstract base, so this test implements a couple
# subclasses to test various scenarios
RSpec.describe WorkHistories::PaperTrailChangeBaseComponent, type: :component do
let(:user) { build_stubbed :user }
let(:paper_trail_version) { instance_spy('PaperTrail::Version', item_type: 'ExpectedItemType') }
before do
no_item_type_class = Class.new(described_class)
stub_const('NoItemType', no_item_type_class)
has_item_type_class = Class.new(described_class) do
def expected_item_type
'ExpectedItemType'
end
end
stub_const('HasItemType', has_item_type_class)
end
describe '#initialize' do
context 'when the subclass does not implement #expected_item_type' do
it do
expect {
NoItemType.new(user: user, paper_trail_version: paper_trail_version)
}.to raise_error(NotImplementedError)
end
end
context 'when the subclass does implement #expected_item_type' do
it 'requires paper_trail_version to apply to the specified class' do
expect {
allow(paper_trail_version).to receive(:item_type).and_return 'DifferentClass'
HasItemType.new(
user: user,
paper_trail_version: paper_trail_version
)
}.to raise_error(ArgumentError)
expect {
allow(paper_trail_version).to receive(:item_type).and_return 'ExpectedItemType'
HasItemType.new(
user: user,
paper_trail_version: paper_trail_version
)
}.not_to raise_error
end
end
end
describe '#render?' do
subject { component.render? }
let(:component) { HasItemType.new(user: user, paper_trail_version: paper_trail_version) }
context 'when the PaperTrail::Version has changed_by_system = true' do
before { allow(paper_trail_version).to receive(:changed_by_system).and_return(true) }
it { is_expected.to eq false }
end
context 'when the PaperTrail::Version has changed_by_system = false' do
before { allow(paper_trail_version).to receive(:changed_by_system).and_return(false) }
it { is_expected.to eq true }
end
end
describe '#i18n_key' do
context 'when the subclass does not implement #i18n_key' do
it do
expect {
HasItemType.new(user: user, paper_trail_version: paper_trail_version)
.send(:i18n_key)
}.to raise_error(NotImplementedError).with_message(/Implement #i18n_key/)
end
end
end
end
| psu-stewardship/scholarsphere-spec/components/work_histories/paper_trail_change_base_component_spec.rb |
'''
PREFIX SUM
The task is to find the prefix sum of every element of a given array.
Prefix sum equals to the sum of all element from start to the current element of the array.
'''
def prefix_sum(array, length):
prefix_array = array
'''
We maintain a prefix array where prefix_array[i] = prefix_array[i-1] + array[i].
As, prefix sum of element i = prefix sum of element i-1 + element i.
'''
for i in range(1, length):
prefix_array[i] = prefix_array[i-1] + array[i]
print("The prefix array is: ")
for i in range(0,length):
print(prefix_array[i], end=' ')
length = int(input())
array = []
for i in range(0, length):
array.append(int(input()))
prefix_sum(array, length)
'''
Input : array = {3,2,4,6,7}
Output: The prefix sum array is:
3 5 9 15 22
'''
| jainaman224/Algo_Ds_Notes-Prefix_Sum/Prefix_Sum.py |
package lilypad.packet.common;
public interface PacketCodecProvider {
public PacketCodec<?> getByOpcode(int opcode);
}
| LilyPad/JLilyPad-packet-common/src/main/java/lilypad/packet/common/PacketCodecProvider.java |
/**
* @addtogroup MC_SPID mcSpid - service provider ID.
*
* <!-- Copyright Giesecke & Devrient GmbH 2011-2012 -->
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* @ingroup MC_DATA_TYPES
* @{
*/
#ifndef MC_SPID_H_
#define MC_SPID_H_
/** Service provider Identifier type. */
typedef uint32_t mcSpid_t;
/** SPID value used as free marker in root containers. */
static const mcSpid_t MC_SPID_FREE = 0xFFFFFFFF;
/** Reserved SPID value. */
static const mcSpid_t MC_SPID_RESERVED = 0;
/** SPID for system applications. */
static const mcSpid_t MC_SPID_SYSTEM = 0xFFFFFFFE;
#endif // MC_SPID_H_
/** @} */
| s20121035/rk3288_android5.1_repo-hardware/rockchip/mobicore/common/MobiCore/inc/mcSpid.h |
"use strict";
angular.module('arethusa.core').directive('navbarNotifier', function() {
return {
restrict: 'A',
replace: true,
templateUrl: 'templates/arethusa.core/navbar_notifier.html'
};
});
| Masoumeh/arethusa-app/js/arethusa.core/directives/navbar_notifier.js |
import numpy as np
def non_max_suppression_fast(boxes, probabilities=None, overlap_threshold=0.3):
"""
Algorithm to filter bounding box proposals by removing the ones with a too low confidence score
and with too much overlap.
Source: https://www.pyimagesearch.com/2015/02/16/faster-non-maximum-suppression-python/
:param boxes: List of proposed bounding boxes
:param overlap_threshold: the maximum overlap that is allowed
:return: filtered boxes
"""
# if there are no boxes, return an empty list
if boxes.shape[1] == 0:
return []
# if the bounding boxes integers, convert them to floats --
# this is important since we'll be doing a bunch of divisions
if boxes.dtype.kind == "i":
boxes = boxes.astype("float")
# initialize the list of picked indexes
pick = []
# grab the coordinates of the bounding boxes
x1 = boxes[:, 0] - (boxes[:, 2] / [2]) # center x - width/2
y1 = boxes[:, 1] - (boxes[:, 3] / [2]) # center y - height/2
x2 = boxes[:, 0] + (boxes[:, 2] / [2]) # center x + width/2
y2 = boxes[:, 1] + (boxes[:, 3] / [2]) # center y + height/2
# compute the area of the bounding boxes and grab the indexes to sort
# (in the case that no probabilities are provided, simply sort on the
# bottom-left y-coordinate)
area = boxes[:, 2] * boxes[:, 3] # width * height
idxs = y2
# if probabilities are provided, sort on them instead
if probabilities is not None:
idxs = probabilities
# sort the indexes
idxs = np.argsort(idxs)
# keep looping while some indexes still remain in the indexes
# list
while len(idxs) > 0:
# grab the last index in the indexes list and add the
# index value to the list of picked indexes
last = len(idxs) - 1
i = idxs[last]
pick.append(i)
# find the largest (x, y) coordinates for the start of
# the bounding box and the smallest (x, y) coordinates
# for the end of the bounding box
xx1 = np.maximum(x1[i], x1[idxs[:last]])
yy1 = np.maximum(y1[i], y1[idxs[:last]])
xx2 = np.minimum(x2[i], x2[idxs[:last]])
yy2 = np.minimum(y2[i], y2[idxs[:last]])
# compute the width and height of the bounding box
w = np.maximum(0, xx2 - xx1 + 1)
h = np.maximum(0, yy2 - yy1 + 1)
# compute the ratio of overlap
overlap = (w * h) / area[idxs[:last]]
# delete all indexes from the index list that have
idxs = np.delete(idxs, np.concatenate(([last],
np.where(overlap > overlap_threshold)[0])))
# return only the bounding boxes that were picked
return pick
| robocomp/robocomp-robolab-components/detection/test/handGestureClient/src/non_maximum_suppression.py |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* previous = NULL;
ListNode* first = head;
ListNode* second = head->next;
bool first_time = true;
while(first != NULL){
second = first->next;
if(second == NULL) break;
first->next= second->next;
second->next = first;
if(first_time) head = second;
else previous->next = second;
previous = first;
first = first->next;
first_time = false;
}
return head;
}
};
| fash97/LeetCode-24.cpp |
//
// OEXTokenTextStorage.h
// OEXTokenField
//
// Created by Nicolas BACHSCHMIDT on 16/03/2013.
// Copyright (c) 2013 Octiplex. All rights reserved.
//
@class OEXTokenTextStorage;
@protocol OEXTokenTextStorageDelegate <NSTextStorageDelegate>
@optional
- (void)tokenTextStorage:(OEXTokenTextStorage *)textStorage updateTokenAttachment:(NSTextAttachment *)attachment forRange:(NSRange)range;
@end
#pragma mark -
/*- OEXTokenTextStorage is used internally by OEXTokenFieldCell to perform attachment cell replacement as the tokens are inserted in the editor text view.
*/
@interface OEXTokenTextStorage : NSTextStorage
@property (weak) id <OEXTokenTextStorageDelegate> delegate;
- (id)initWithAttributedString:(NSAttributedString *)attrStr;
@end
| alanjrogers/OEXTokenField-OEXTokenTextStorage.h |
/*
* Kendo UI v2015.2.805 (http://www.telerik.com/kendo-ui)
* Copyright 2015 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["fa-IR"] = {
name: "fa-IR",
numberFormat: {
pattern: ["n-"],
decimals: 2,
",": ",",
".": "/",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": "/",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$n-","$n"],
decimals: 2,
",": ",",
".": "/",
groupSize: [3],
symbol: "ريال"
}
},
calendars: {
standard: {
days: {
names: ["يكشنبه","دوشنبه","سه شنبه","چهارشنبه","پنجشنبه","جمعه","شنبه"],
namesAbbr: ["يكشنبه","دوشنبه","سه شنبه","چهارشنبه","پنجشنبه","جمعه","شنبه"],
namesShort: ["ی","د","س","چ","پ","ج","ش"]
},
months: {
names: ["ژانويه","فوريه","مارس","آوريل","مه","ژوئن","ژوئيه","اوت","سپتامبر","اُكتبر","نوامبر","دسامبر"],
namesAbbr: ["ژانويه","فوريه","مارس","آوريل","مه","ژوئن","ژوئيه","اوت","سپتامبر","اُكتبر","نوامبر","دسامبر"]
},
AM: ["ق.ظ","ق.ظ","ق.ظ"],
PM: ["ب.ظ","ب.ظ","ب.ظ"],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, dd MMMM yyyy",
F: "dddd, dd MMMM yyyy hh:mm:ss tt",
g: "dd/MM/yyyy hh:mm tt",
G: "dd/MM/yyyy hh:mm:ss tt",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "hh:mm tt",
T: "hh:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "/",
":": ":",
firstDay: 6
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | cleitonalmeida1/EstagioAZ-assets/vendor/kendoui/src/js/cultures/kendo.culture.fa-IR.js |
# user specific directories
#--------------------------
ROOT = /home/dcode
CODE = $(ROOT)/work_PARA_VER_3_JULY_03
DCODE = $(ROOT)/work_PARA_VER_3_JULY_03
ECODE = $(DCODE)/runable
# general directories
#--------------------------
INCLUDES = $(DCODE)/include/pentium_nopar
EXE = $(ECODE)/piny_md_pentium_test
CMALLOC =
# HP compiler
#--------------------------
FC = f77 -DLINUX -fno-second-underscore
CC = gcc -DLINUX -fno-second-underscore
OPT = -O0
OPT_CARE = -O0
OPT_GRP = -O0
CFLAGS =
FFLAGS = -nofor_main
LIBS = $(LIB_PATH) $(MALLOC) -lm
| yuhangwang/PINY-compile/old-settings/pentium_test/make_head.h |
/*
* Copyright (c) 2010-2016, b3log.org & hacpai.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* about for admin
*
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.4, May 28, 2013
*/
/* about 相关操作 */
admin.about = {
init: function() {
$.ajax({
url: "http://rhythm.b3log.org/version/solo/latest/" + Label.version,
type: "GET",
cache: false,
dataType: "jsonp",
success: function(data, textStatus) {
var version = data.soloVersion;
if (version === Label.version) {
$("#aboutLatest").text(Label.upToDateLabel);
} else {
$("#aboutLatest").html(Label.outOfDateLabel +
"<a href='" + data.soloDownload + "'>" + version + "</a>");
}
},
complete: function(XHR, TS) {
admin.clearTip();
}
});
}
};
/*
* 注册到 admin 进行管理
*/
admin.register["about"] = {
"obj": admin.about,
"init": admin.about.init,
"refresh": function() {
admin.clearTip();
}
}; | 446541492/solo-src/main/webapp/js/admin/about.js |
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2003-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
// Adapted from <boost/config/auto_link.hpp> and from
// http://www.boost.org/more/separate_compilation.html, by John Maddock.
#ifndef BOOST_IOSTREAMS_DETAIL_AUTO_LINK_HPP_INCLUDED
#define BOOST_IOSTREAMS_DETAIL_AUTO_LINK_HPP_INCLUDED
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#if defined(BOOST_EXTERNAL_LIB_NAME)
# if defined(BOOST_MSVC) \
|| defined(__BORLANDC__) \
|| (defined(__MWERKS__) && defined(_WIN32) && (__MWERKS__ >= 0x3000)) \
|| (defined(__ICL) && defined(_MSC_EXTENSIONS) && (_MSC_VER >= 1200)) \
/**/
# pragma comment(lib, BOOST_EXTERNAL_LIB_NAME)
# endif
# undef BOOST_EXTERNAL_LIB_NAME
#endif
//------------------Enable automatic library variant selection----------------//
#if !defined(BOOST_IOSTREAMS_SOURCE) && \
!defined(BOOST_ALL_NO_LIB) && \
!defined(BOOST_IOSTREAMS_NO_LIB) \
/**/
// Set the name of our library, this will get undef'ed by auto_link.hpp
// once it's done with it.
# define BOOST_LIB_NAME boost_iostreams
// If we're importing code from a dll, then tell auto_link.hpp about it.
# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_IOSTREAMS_DYN_LINK)
#error "aaaaa"
# define BOOST_DYN_LINK
# endif
// And include the header that does the work.
# include <boost/config/auto_link.hpp>
#endif // auto-linking disabled
#endif // #ifndef BOOST_IOSTREAMS_DETAIL_AUTO_LINK_HPP_INCLUDED
| titanmonsta/fluorescence-winbuild/include/boost/iostreams/detail/config/auto_link.hpp |
#! /usr/bin/python
__author__ = "gelpi"
__date__ = "$02-nov-2017 8:21:31$"
import math
#Parameters
SIG = 3.4
EPS = 0.09
dmin = 3.8
def calc_energy(sys):
"""Calculates vdw + elec energy for the whole system"""
eint = 0.
evdw = 0.
for p1 in sys['parts']:
for p2 in sys['parts']:
if p1 == p2:
continue
eint = eint + 0.5 * elec_interaction(p1, p2, sys['d'])
evdw = evdw + 0.5 * vdw_interaction(p1, p2, sys['d'])
return [evdw, eint]
def distance(p1,p2):
"""Evaluates Sqrt[(x0-x1)2 +(y0-y1)2 + (z0-z1)2]"""
return math.sqrt((p1[0]-p2[0]) ** 2 + (p1[1]-p2[1]) ** 2 + (p1[2]-p2[2]) ** 2)
def vdw_interaction(p1, p2, dmin):
"""vdwenergy between two particles"""
f = SIG / (distance(p1,p2) * dmin)
return 4. * EPS * (pow(f, 12)-pow(f, 6))
def elec_interaction(p1,p2, dmin):
"""Electrostatic interaction"""
d = distance(p1,p2) * dmin
return 332.16 * p1[3] * p2[3] / d
# MAIN
sys = {'parts': [], 'd' : dmin}
for x in range(-1, 2):
for y in range(-1, 2):
for z in range(-1, 2):
sys['parts'].append([x, y, z, 0.])
[evdw, eint] = calc_energy(sys)
print ("Evdw=", evdw)
#Removing central particle
#p0 is the central particle
p0 = [0, 0, 0, 0]
evdw0 = 0
for pi in sys['parts']:
if pi != p0:
evdw0 = evdw0 + vdw_interaction(p0, pi, sys['d'])
print ("New Evdw=", evdw-evdw0)
#Electrostatics, equal positive charge
#Calculate for a q=1e and adjust later
for pi in sys['parts']:
pi[3] = 1.
(evdw1, eint1) = calc_energy(sys)
print ("Charge to equilibrate: ",math.sqrt(-evdw / eint1))
# Negative in central particle
ecen=0.
p0[3]=1.
for pi in sys['parts']:
if pi != p0:
ecen = ecen + elec_interaction(p0,pi,sys['d'])
neweint = eint1 - 2. * ecen
print ("Centrl neg to compensate: ", math.sqrt(-evdw/neweint))
| jlgelpi/BioPhysics-Exercises/prob217_noclass.py |
Odlo Ceramicool - Basis t-shirt - Blå (475,00 DKK)
Varenr. 160002-20336-X Producent: Odlo
Odlo's Ceramicool basis t-shirt til mænd er skabt med henblik på performance, komfort og kropsafkøling. Ceramicool er et basislag som er opbygget af Odlo's originale CeramiCool-garn, hvilket har en do...
Produkter som vi anbefaler til Odlo Ceramicool - Basis t-shirt - Blå
Odlo's Ceramicool basis t-shirt til mænd er skabt med henblik på performance, komfort og kropsafkøling. Ceramicool er et basislag som er opbygget af Odlo's originale CeramiCool-garn, hvilket har en dokumenteret effekt på, at kunne køle huden aktivt med 1°C ved hjælp af naturlige keramiske køleegenskaber. Dette gør denne bluse uundværlig til sommerens mange cykelture. Ydermere er t-shirten fra Odlo sømløs, åndbar og utrolig blød.
Ceramicool er en svedtrøje til mænd, som både kan anvendes under en trøje som basislag, eller alene om sommeren og i træningscentret. Uanset om du løber, cykler, styrketræner eller går til gymnastik kan du bruge denne t-shirt.
Materiale: 91% polyamid 9% elastan
Når du træner er det vigtigt for din præstation, at du kommer af med overskudsvarmen så kroppen hverken bliver overophedet eller nedkølet. Ceramicool er udviklet i et materiale der danner små luftkanaler, som hurtigt kan overføre kroppens overskudsvarme og derved forbedre din præstation.
Ceramicool basis t-shirten bør vaskes ved max 40 garder i vaskemaskinen, og må ikke kommer i tørretumbleren. Dit sportstøj har altid bedst af at blive vasket i et sportsvaskemiddel. Dette er nemlig med til at forlænge tøjets levetid.
7611366252892 | c4-da |
class InvalidGameModeException(Exception):
pass
_game_modes = {}
def register_game_mode(name):
try:
module = __import__('gamemodes.%s' % name, globals(), locals(), name)
except ImportError:
raise InvalidGameModeException('Could not load game mode: %s' % name)
_game_modes[name] = getattr(module, "%sGameMode" % name.capitalize())
def get_game_mode(name):
return _game_modes[name]()
register_game_mode('standard')
| dbreen/warwords-gamemodes/__init__.py |
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
// define plugins
var plugins = [
new webpack.DefinePlugin({
__DEV__: '1' == process.env.dev ? true : false,
__PDT__: '1' == process.env.pdt ? true : false
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'common',
filename: './js/common.js',
minChunks: Infinity
}),
new ExtractTextPlugin('[name].css'),
new webpack.optimize.MinChunkSizePlugin(800)
];
if('1' == process.env.pdt){
plugins.push( new webpack.optimize.UglifyJsPlugin() );
}
module.exports = {
entry: {
index: './src/js/index.jsx'
},
output: {
path: 'dist',
filename: './js/[name].js',
chunkFilename: './js/[id].[name].js'
},
module: {
loaders: [
{test: /\.jsx$/, loader: 'jsx-loader?harmony!babel-loader'},
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{test: /\.styl$/, loader: ExtractTextPlugin.extract('style-loader', 'stylus-loader')},
{test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader')},
{test: /\.tpl$/, loader: 'html-loader'},
{test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192&name=[path][name].[ext]'},
{test: /\.woff$/, loader: "url?limit=10000&minetype=application/font-woff"},
{test: /\.ttf$/, loader: "file"},
{test: /\.eot$/, loader: "file"},
{test: /\.svg$/, loader: "file"}
]
},
resolve: {
extensions: ['', '.jsx', '.js']
},
plugins: plugins
}
| kreding/flux-webpack.config.js |
# Set all the variables necessary to connect to Twitch IRC
cmdRAFFLE = "!waffles"
| meekus1212/meekbot-commands.py |
/* { dg-do compile } */
/* { dg-options "-fdump-tree-optimized" } */
extern
#ifdef __cplusplus
"C"
#endif
__attribute__((__simd__("notinbranch")))
int simd_attr (void)
{
return 0;
}
/* { dg-final { scan-tree-dump "simd_attr\[ \\t\]simdclone|vector" "optimized" { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-times "_ZGVbN4_simd_attr:" 1 { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-times "_ZGVcN4_simd_attr:" 1 { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-times "_ZGVdN8_simd_attr:" 1 { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-not "_ZGVbM4_simd_attr:" { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-not "_ZGVcM4_simd_attr:" { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-not "_ZGVdM8_simd_attr:" { target { i?86-*-* x86_64-*-* } } } } */
extern
#ifdef __cplusplus
"C"
#endif
__attribute__((simd("inbranch")))
int simd_attr2 (void)
{
return 0;
}
/* { dg-final { scan-tree-dump "simd_attr2\[ \\t\]simdclone|vector" "optimized" { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-not "_ZGVbN4_simd_attr2:" { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-not "_ZGVcN4_simd_attr2:" { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-not "_ZGVdN8_simd_attr2:" { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-times "_ZGVbM4_simd_attr2:" 1 { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-times "_ZGVcM4_simd_attr2:" 1 { target { i?86-*-* x86_64-*-* } } } } */
/* { dg-final { scan-assembler-times "_ZGVdM8_simd_attr2:" 1 { target { i?86-*-* x86_64-*-* } } } } */
| h4ck3rm1k3/gcc-1-gcc/testsuite/c-c++-common/attr-simd-4.c |
// Test that conversion to std::initializer_list takes priority over other
// user-defined conversions.
// { dg-do link }
// { dg-options "-std=c++11" }
#include <initializer_list>
struct string
{
string (const char *) {}
template <class Iter> string (Iter, Iter);
};
template <class T, class U>
struct pair
{
pair (T t, U u) {}
};
template<class T, class U>
struct map
{
void insert (pair<T,U>);
void insert (std::initializer_list<pair<T,U> >) {}
};
int main()
{
map<string,string> m;
m.insert({ {"this","that"}, {"me","you"} });
}
| albertghtoun/gcc-libitm-gcc/testsuite/g++.dg/cpp0x/initlist2.C |
/**********************************************************************
TasksViewController.h
This file is part of TaskGnome IOS.
TaskGnome 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.
Foobar 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 TaskGnome IOS. If not, see <http://www.gnu.org/licenses/>.
Copyright (c) 2013 Hans Oesterholt. All rights reserved.
**********************************************************************/
#import <UIKit/UIKit.h>
#import "ICdTaskInfo.h"
#import "CdTaskMeta.h"
#import "CdDelegate.h"
@interface TasksViewController : UITableViewController
- (IBAction)dlgAddTask:(id)sender;
- (IBAction)checkTask:(id)sender;
- (void)addTask:(NSObject<ICdTaskInfo> *)info;
- (void)updateTask:(NSObject<ICdTaskInfo> *)info;
- (void)prepareForEditTask:(NSObject<ICdTaskInfo> *)task;
- (void)selectActiveTasks;
- (void)selectFinishedTasks;
- (void)refresh;
- (void)setTasksSelector:(id)ts; // id must be of type TaskSelector *
- (CdDelegate *)getCdDelegate;
- (void)checkConnection;
@end
| hdijkema/TaskGnomeIOS-TasksViewController.h |
//*******************************************************************************************//
// //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer //
// //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup //
// //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved. //
// https://www.bytescout.com //
// https://pdf.co //
// //
//*******************************************************************************************//
var request = require('request');
var options = {
'method': 'POST',
'url': 'http://localhost:80/pdf/classifier',
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"url": "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/document-parser/sample-invoice.pdf",
"rulescsv": "Amazon,Amazon Web Services Invoice|Amazon CloudFront\nDigital Ocean,DigitalOcean|DOInvoice\nAcme,ACME Inc.|1540 Long Street, Jacksonville, 32099",
"caseSensitive": "true",
"async": false,
"encrypt": "false",
"inline": "true",
"password": "",
"profiles": ""
})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
| bytescout/ByteScout-SDK-SourceCode-Cloud API Server/PDF Classifier/JavaScript/Classify PDF From URL (nodeJs)/program.js |
package net.kilger.mockins.generator.valueprovider;
/**
* Factory for creating {@link ValueProvider}s.
*/
public interface ValueProviderFactory {
/**
* Returns a {@link ValueProvider} for the given <i>clazz</i>.
* Whether this factory can deal with <i>clazz</i> must
* be checked using {@link #canHandle(Class)} before calling
* this method.
*/
<T> ValueProvider<T> valueProvider(Class<T> clazz);
/**
* True iff this provider factory is specific for clazz.
* general purpose factories should return false here.
* This is because some types should have special
* ValueProviders (e.g. array types) rather than
* generic implementations.
* Note that returning true here already implies
* {@link #canHandle(Class)}.
*/
boolean specificFor(Class<?> clazz);
/**
* Returns true if this factory can create a {@link ValueProvider}
* with {@link #valueProvider(Class)} for <i>clazz</i>
*/
boolean canHandle(Class<?> clazz);
}
| kilgerm/mockins-src/main/java/net/kilger/mockins/generator/valueprovider/ValueProviderFactory.java |
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
namespace StackWarden.Core.Serialization
{
public class PrivateMemberContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var members = properties.Cast<MemberInfo>()
.Union(fields.Cast<MemberInfo>())
.Where(x => !x.Name.Contains("__BackingField"))
.Select(x =>
{
var createdProperty = CreateProperty(x, memberSerialization);
createdProperty.Writable = true;
createdProperty.Readable = true;
return createdProperty;
})
.ToList();
return members;
}
//protected override List<MemberInfo> GetSerializableMembers(Type objectType)
//{
// var inheritedMembers = new List<MemberInfo>(base.GetSerializableMembers(objectType));
// var nonPublicFields = objectType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
// var nonPublicProperties = objectType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetProperty);
// var result = inheritedMembers.Concat(nonPublicFields)
// .Concat(nonPublicProperties)
// .Distinct()
// .Select(x => base.CreateProperty(x, Newtonsoft.Json.MemberSerialization))
// .ToList();
// foreach (var currentItem in result)
// {
// currentItem.
// }
// return result;
//}
}
} | Neurosion/StackWarden-src/StackWarden.Core/Serialization/PrivateMemberContractResolver.cs |
var mongoose = require('mongoose')
var bcrypt = require('bcryptjs')
let Schema = mongoose.Schema
let ObjectId = Schema.ObjectId
let UserSchema = new Schema({
user_id: ObjectId,
username: {
type: String,
unique: true
},
servicebranch: String,
password: String,
first_name: String,
last_name: String,
currentstatus: String,
job_title: {
job_wanted: String,
current_title: String,
date_started: Date,
date_left_last: Date
},
mentors: [{
user_id: String,
username: String,
user_image: String,
unread_message: String,
last_communicated: Date
}],
mentees: [{
user_id: String,
username: String,
user_image: String,
unread_message: String,
last_communicated: Date
}]
})
let User = module.exports = mongoose.model('UserSchema', UserSchema)
// hashed password
module.exports.createUser = (newUser, callback) => {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
// Store hash in your password DB.
newUser.password = hash
newUser.save((err) => {
if (err) {
console.log(err)
} else {
callback(true)
console.log("New User has been created")
}
})
})
})
}
module.exports.getUserByUsername = function (username, callback) {
var query = {
username: username
}
User.findOne(query, callback)
}
| Ankiewicz/veteran-mentor-schemas/users.js |
/*
* Copyright (C) 2009 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#ifndef __BTRFS_FREE_SPACE_CACHE
#define __BTRFS_FREE_SPACE_CACHE
struct btrfs_free_space {
struct rb_node offset_index;
u64 offset;
u64 bytes;
unsigned long *bitmap;
struct list_head list;
};
struct btrfs_free_space_ctl {
spinlock_t tree_lock;
struct rb_root free_space_offset;
u64 free_space;
int extents_thresh;
int free_extents;
int total_bitmaps;
int unit;
u64 start;
struct btrfs_free_space_op *op;
void *private;
};
struct btrfs_free_space_op {
void (*recalc_thresholds)(struct btrfs_free_space_ctl *ctl);
bool (*use_bitmap)(struct btrfs_free_space_ctl *ctl,
struct btrfs_free_space *info);
};
struct inode *lookup_free_space_inode(struct btrfs_root *root,
struct btrfs_block_group_cache
*block_group, struct btrfs_path *path);
int create_free_space_inode(struct btrfs_root *root,
struct btrfs_trans_handle *trans,
struct btrfs_block_group_cache *block_group,
struct btrfs_path *path);
int btrfs_check_trunc_cache_free_space(struct btrfs_root *root,
struct btrfs_block_rsv *rsv);
int btrfs_truncate_free_space_cache(struct btrfs_root *root,
struct btrfs_trans_handle *trans,
struct inode *inode);
int load_free_space_cache(struct btrfs_fs_info *fs_info,
struct btrfs_block_group_cache *block_group);
int btrfs_write_out_cache(struct btrfs_root *root,
struct btrfs_trans_handle *trans,
struct btrfs_block_group_cache *block_group,
struct btrfs_path *path);
struct inode *lookup_free_ino_inode(struct btrfs_root *root,
struct btrfs_path *path);
int create_free_ino_inode(struct btrfs_root *root,
struct btrfs_trans_handle *trans,
struct btrfs_path *path);
int load_free_ino_cache(struct btrfs_fs_info *fs_info,
struct btrfs_root *root);
int btrfs_write_out_ino_cache(struct btrfs_root *root,
struct btrfs_trans_handle *trans,
struct btrfs_path *path,
struct inode *inode);
void btrfs_init_free_space_ctl(struct btrfs_block_group_cache *block_group);
int __btrfs_add_free_space(struct btrfs_free_space_ctl *ctl,
u64 bytenr, u64 size);
static inline int
btrfs_add_free_space(struct btrfs_block_group_cache *block_group,
u64 bytenr, u64 size)
{
return __btrfs_add_free_space(block_group->free_space_ctl,
bytenr, size);
}
int btrfs_remove_free_space(struct btrfs_block_group_cache *block_group,
u64 bytenr, u64 size);
void __btrfs_remove_free_space_cache(struct btrfs_free_space_ctl *ctl);
void btrfs_remove_free_space_cache(struct btrfs_block_group_cache
*block_group);
u64 btrfs_find_space_for_alloc(struct btrfs_block_group_cache *block_group,
u64 offset, u64 bytes, u64 empty_size,
u64 *max_extent_size);
u64 btrfs_find_ino_for_alloc(struct btrfs_root *fs_root);
void btrfs_dump_free_space(struct btrfs_block_group_cache *block_group,
u64 bytes);
int btrfs_find_space_cluster(struct btrfs_root *root,
struct btrfs_block_group_cache *block_group,
struct btrfs_free_cluster *cluster,
u64 offset, u64 bytes, u64 empty_size);
void btrfs_init_free_cluster(struct btrfs_free_cluster *cluster);
u64 btrfs_alloc_from_cluster(struct btrfs_block_group_cache *block_group,
struct btrfs_free_cluster *cluster, u64 bytes,
u64 min_start, u64 *max_extent_size);
int btrfs_return_cluster_to_free_space(
struct btrfs_block_group_cache *block_group,
struct btrfs_free_cluster *cluster);
int btrfs_trim_block_group(struct btrfs_block_group_cache *block_group,
u64 *trimmed, u64 start, u64 end, u64 minlen);
/* Support functions for runnint our sanity tests */
#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
int test_add_free_space_entry(struct btrfs_block_group_cache *cache,
u64 offset, u64 bytes, bool bitmap);
int test_check_exists(struct btrfs_block_group_cache *cache,
u64 offset, u64 bytes);
#endif
#endif
| mericon/Xp_Kernel_LGH850-virt/fs/btrfs/free-space-cache.h |
/**
* @file airhorn command
* @author Sankarsan Kampa (a.k.a k3rn31p4nic)
* @license GPL-3.0
*/
exports.exec = async (Bastion, message) => {
if (message.guild.voiceConnection) {
if (!message.guild.voiceConnection.channel.permissionsFor(message.member).has(this.help.userTextPermission)) {
return Bastion.emit('userMissingPermissions', this.help.userTextPermission);
}
if (message.guild.voiceConnection.speaking) {
return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'isSpeaking'), message.channel);
}
if (!message.guild.voiceConnection.channel.speakable) {
return Bastion.emit('bastionMissingPermissions', 'SPEAK', message);
}
message.guild.voiceConnection.playFile('./assets/airhorn.wav', {
passes: (Bastion.configurations.music && Bastion.configurations.music.passes) || 1,
bitrate: 'auto'
});
}
else if (message.member.voiceChannel) {
if (!message.member.voiceChannel.permissionsFor(message.member).has(this.help.userTextPermission)) {
return Bastion.emit('userMissingPermissions', this.help.userTextPermission);
}
if (!message.member.voiceChannel.joinable) {
return Bastion.emit('bastionMissingPermissions', 'CONNECT', message);
}
if (!message.member.voiceChannel.speakable) {
return Bastion.emit('bastionMissingPermissions', 'SPEAK', message);
}
let connection = await message.member.voiceChannel.join();
connection.on('error', Bastion.log.error);
connection.on('failed', Bastion.log.error);
const dispatcher = connection.playFile('./assets/airhorn.wav', {
passes: (Bastion.configurations.music && Bastion.configurations.music.passes) || 1,
bitrate: 'auto'
});
dispatcher.on('error', error => {
Bastion.log.error(error);
});
dispatcher.on('end', () => {
connection.channel.leave();
});
}
else {
return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'eitherOneInVC'), message.channel);
}
};
exports.config = {
aliases: [ 'horn' ],
enabled: true
};
exports.help = {
name: 'airhorn',
description: 'Plays an airhorn in a voice channel.',
botPermission: '',
userTextPermission: 'MUTE_MEMBERS',
userVoicePermission: '',
usage: 'airhorn',
example: []
};
| snkrsnkampa/Bastion-commands/soundboard/airhorn.js |
/* Signal number definitions. Linux/SPARC version.
Copyright (C) 1996-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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 the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#ifdef _SIGNAL_H
/* Fake signal functions. */
#define SIG_ERR ((__sighandler_t) -1) /* Error return. */
#define SIG_DFL ((__sighandler_t) 0) /* Default action. */
#define SIG_IGN ((__sighandler_t) 1) /* Ignore signal. */
#ifdef __USE_UNIX98
# define SIG_HOLD ((__sighandler_t) 2) /* Add signal to hold mask. */
#endif
/*
* Linux/SPARC has different signal numbers that Linux/i386: I'm trying
* to make it OSF/1 binary compatible, at least for normal binaries.
*/
#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGILL 4
#define SIGTRAP 5
#define SIGABRT 6
#define SIGIOT 6
#define SIGEMT 7
#define SIGFPE 8
#define SIGKILL 9
#define SIGBUS 10
#define SIGSEGV 11
#define SIGSYS 12
#define SIGPIPE 13
#define SIGALRM 14
#define SIGTERM 15
#define SIGURG 16
/* SunOS values which deviate from the Linux/i386 ones */
#define SIGSTOP 17
#define SIGTSTP 18
#define SIGCONT 19
#define SIGCHLD 20
#define SIGCLD SIGCHLD /* Same as SIGCHLD (System V). */
#define SIGTTIN 21
#define SIGTTOU 22
#define SIGIO 23
#define SIGPOLL SIGIO /* SysV name for SIGIO */
#define SIGXCPU 24
#define SIGXFSZ 25
#define SIGVTALRM 26
#define SIGPROF 27
#define SIGWINCH 28
#define SIGLOST 29
#define SIGPWR SIGLOST
#define SIGUSR1 30
#define SIGUSR2 31
#define _NSIG 65 /* Biggest signal number + 1
(including real-time signals). */
#define SIGRTMIN (__libc_current_sigrtmin ())
#define SIGRTMAX (__libc_current_sigrtmax ())
/* These are the hard limits of the kernel. These values should not be
used directly at user level. */
#define __SIGRTMIN 32
#define __SIGRTMAX (_NSIG - 1)
#endif /* <signal.h> included. */
| VincentS/glibc-sysdeps/unix/sysv/linux/sparc/bits/signum.h |
"use strict";
var React = require('react');
var assign = require('react/lib/Object.assign');
var Helpers = require('../mixins/Helpers');
var Link = React.createClass({
mixins: [Helpers.Scroll],
getInitialState : function() {
return { active : false};
},
getDefaultProps: function() {
return {
className: ""
};
},
render: function () {
var activeClass = this.state.active ? (this.props.activeClass || "active") : "";
var props = assign({}, this.props, {
onClick: this.onClick,
className : [this.props.className, activeClass].join(" ").trim()
});
return React.DOM.a(props, this.props.children);
}
});
module.exports = Link;
| ntdb/react-scroll-modules/components/Link.js |
//
// NSPAudioEngine.h
// Canopus
//
// Created by Janos Tolgyesi on 22/05/15.
// Copyright (c) 2015 Neosperience SpA. All rights reserved.
//
#import <Foundation/Foundation.h>
@class AVQueuePlayer, NSPAudioPlaylistItem;
typedef enum : NSUInteger {
NSPAudioEngineStateStopped,
NSPAudioEngineStatePreparingToPlay,
NSPAudioEngineStatePlaying,
NSPAudioEngineStatePaused,
NSPAudioEngineStateError,
} NSPAudioEngineState;
@interface NSPAudioEngine : NSObject
@property (nonatomic, readonly) AVQueuePlayer* player;
@property (nonatomic, strong) NSArray* currentPlaylist;
@property (nonatomic, readonly) NSPAudioPlaylistItem* currentItem;
@property (nonatomic, readonly) NSPAudioEngineState state;
@property (nonatomic, strong) NSError* lastError;
+ (instancetype)sharedInstance;
- (void)play;
- (void)pause;
- (void)stop;
- (void) activateSession;
- (void) deactivateSession;
@end
| Neosperience/NSPCoreUtils-NSPAudioEngine/NSPAudioEngine.h |
// Karma configuration
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '../..',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.min.js',
'bower_components/angular-bootstrap/ui-bootstrap.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/**/*.js'
//'src/**/Tests/Js/**/*Test.js',
//'test/js/**/*Test.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| phillipsnick/nickphillips.co-test/js/karma.config.js |
# -*- coding: utf-8 -*-
# Author: github.com/kholohan
from math import acos, degrees, sqrt, pi
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def __add__(self, v):
return Vector([x+y for x, y in zip(self.coordinates, v.coordinates)])
def __eq__(self, v):
return self.coordinates == v.coordinates
def __getitem__(self,index):
return self.coordinates[index]
def __iter__(self):
return iter(self.coordinates)
def __mul__(self, v):
if isinstance(v, Vector):
return Vector([x*y for x, y in zip(self.coordinates, v.coordinates)])
else:
return Vector([x*v for x in self.coordinates])
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __sub__(self, v):
return Vector([x-y for x, y in zip(self.coordinates, v.coordinates)])
def angle_degree(self, v):
return degrees(self.angle_radian(v))
def angle_radian(self, v):
return acos(round(self.dot_product(v) / (self.magnitude() * v.magnitude()), 3))
def area_parallelogram(self, v):
return self.cross_product(v).magnitude()
def area_triangle(self, v):
return self.area_parallelogram(v) / 2
def cross_product(self, v):
[x1, y1, z1] = self.coordinates
[x2, y2, z2] = v.coordinates
x = (y1 * z2) - (y2 * z1)
y = -((x1 * z2) - (x2 * z1))
z = (x1 * y2) - (x2 * y1)
return Vector([x, y, z])
def dot_product(self, v):
if isinstance(v, Vector):
return sum([x*y for x, y in zip(self.coordinates, v.coordinates)])
def is_orthogonal(self, v, tolerance=1e-10):
return abs(self.dot_product(v)) < tolerance
def is_parallel(self, v, tolerance=1e-10):
if self.is_zero() or v.is_zero(): return True
else:
items = [x / y for x, y in zip(self.coordinates, v.coordinates)]
return all([abs(items[0] - item) < tolerance for item in items])
def is_zero(self, tolerance=1e-10):
return self.magnitude() < tolerance
def magnitude(self):
return sqrt(sum([x**2 for x in self.coordinates]))
def normalize(self):
try:
return Vector([(1 / self.magnitude()) * x for x in self.coordinates])
except ZeroDivisionError:
raise Exception('Cannot normalize the zero vector')
# perpendicular, where v is base vector
def orthogonal(self, base_vector):
return self - self.projection(base_vector)
#project self onto base vector v, parallel
def projection(self, base_vector):
return self.dot_product(base_vector.normalize()) * base_vector.normalize()
def scalar_multiplication(self, v):
return self.__mul__(v)
__rmul__ = __mul__
| kholohan/ud953-linear-algebra-vector.py |
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
generateParenthesisRe(n, n, "", result);
return result;
}
void generateParenthesisRe(int left, int right, string current, vector<string> &result) {
if (left == 0 && right == 0) {
result.push_back(current);
return;
}
if (left > 0) {
generateParenthesisRe(left - 1, right, current + "(", result);
}
if (right > left) {
generateParenthesisRe(left, right - 1, current + ")", result);
}
}
};
| Jiacai/LeetCode-Generate Parentheses.cpp |
Consider the following diagram and determine whether theexpressions are correct or incorrect.
i1+i2 = -i3
E3 - E1 = i3 R3 -i1 R1
E2 - E1 = i1R1-i2 R2
E2 - E3 = -i3R3-i2 R2
E1 - E3 = i1R1+i3 R3
E1 - E2 = i1R1+i2 R2
i1 = i2-i3
### Get this answer with Chegg Study
Practice with similar questions
College Physics for AP® Courses (th Edition)
Q:
For this question, consider the circuit shown in the following figure. a. Assuming that none of the three currents (I1, I2, and I3) are equal to zero, which of the following statements is false? a. I3 = I1 + I2 at point a. b. I2 = I3 - I1 at point e. c. The current through R3 is equal to the current through R5. d. The current through R1 is equal to the current through R5. b. Which of the following statements is true? a. E1 + E2 + I1R1 - I2R2 + I1r1 - I2r2 + I1R5 = 0 b. - E1 + E2 + I1R1 - I2R2 + I1r1 - I2r2 - I1R5 = 0 c. E1 - E2 - I1R1 + I2R2 - I1r1 + I2r2 - I1R5 = 0 d. E1 + E2 - I1R1 + I2R2 - I1r1 + I2r2 + I1R5 = 0 c. If I1 = 5 A and I3 = -2 A, which of the following statements is false? a. The current through R1 will flow from a to b and will be equal to 5 A. b. The current through R3 will flow from a to j and will be equal to 2 A. c. The current through R5 will flow from d to e and will be equal to 5 A. d. None of the above d. If I1 = 5 A and I3 = -2 A, I2 will be equal to a. 3 A b. -3 A c. 7 A d. -7 A | finemath-3plus |
(function() {
'use strict';
var battery;
function toTime(sec) {
sec = parseInt(sec, 10);
var hours = Math.floor(sec / 3600),
minutes = Math.floor((sec - (hours * 3600)) / 60),
seconds = sec - (hours * 3600) - (minutes * 60);
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { minutes = '0' + minutes; }
if (seconds < 10) { seconds = '0' + seconds; }
return hours + ':' + minutes;
}
function readBattery(b) {
battery = b || battery;
var percentage = parseFloat((battery.level * 100).toFixed(2)) + '%',
fully,
remaining;
if (battery.charging && battery.chargingTime === Infinity) {
fully = 'Calculating...';
} else if (battery.chargingTime !== Infinity) {
fully = toTime(battery.chargingTime);
} else {
fully = '---';
}
if (!battery.charging && battery.dischargingTime === Infinity) {
remaining = 'Calculating...';
} else if (battery.dischargingTime !== Infinity) {
remaining = toTime(battery.dischargingTime);
} else {
remaining = '---';
}
document.styleSheets[0].insertRule('.battery:before{width:' + percentage + '}', 0);
document.querySelector('.battery-percentage').innerHTML = percentage;
document.querySelector('.battery-status').innerHTML = battery.charging ? 'Adapter' : 'Battery';
document.querySelector('.battery-level').innerHTML = percentage;
document.querySelector('.battery-fully').innerHTML = fully;
document.querySelector('.battery-remaining').innerHTML = remaining;
}
if (navigator.battery) {
readBattery(navigator.battery);
} else if (navigator.getBattery) {
navigator.getBattery().then(readBattery);
} else {
document.querySelector('.not-support').removeAttribute('hidden');
}
window.onload = function () {
battery.addEventListener('chargingchange', function() {
readBattery();
});
battery.addEventListener("levelchange", function() {
readBattery();
});
};
}());
| aleksandar-todorovic/battery-src/index.js |
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
/*!
* Sitemap
* Copyright(c) 2011 Eugene Kalinin
* MIT Licensed
*/
const sitemap_1 = require("./lib/sitemap");
__export(require("./lib/sitemap"));
__export(require("./lib/sitemap-item"));
__export(require("./lib/sitemap-index"));
__export(require("./lib/errors"));
__export(require("./lib/types"));
var xmllint_1 = require("./lib/xmllint");
exports.xmlLint = xmllint_1.xmlLint;
var sitemap_parser_1 = require("./lib/sitemap-parser");
exports.parseSitemap = sitemap_parser_1.parseSitemap;
exports.default = sitemap_1.createSitemap;
//# sourceMappingURL=index.js.map | BigBoss424/portfolio-v6/node_modules/sitemap/dist/index.js |
var searchData=
[
['w',['w',['../structdisplay__update.html#a07c3d7c96962189ca7d8cdef614a252e',1,'display_update::w()'],['../structdisplay__switch.html#ac4da3bd897eb55df047cf88c23e8bf77',1,'display_switch::w()']]]
];
| datto/librdpmux-doc/html/search/variables_a.js |
[MISSING_PAGE_EMPTY:1]
This paper is structured as follows. In Section 2 we review related research. In Section 3, we describe data sources which have been used to calculate sentiment scores: Thomson Reuters, RavenPack and Twitter. In Section 4 we conduct a correlation analysis and Granger's causality test. In Section 5, we carry out additional experiments to access if topic modelling (or Latent Dirichlet Allocation) can be used to enhance the prediction accuracy of next days stock market directional volatility. In Section 6 and 7 we present the results of the analysis and discuss future work.
## 2. Related Works
A growing number of research papers use NLP methods to access how sentiment of firm-specific news, financial reports, or social media impact stock market returns. An important early work (2007) by Tetlock (2007) explores possible correlations between the media and the stock market using information from the Wall Street Journal and finds that high pessimism causes downward pressure on market prices. Afterwards, Tetlock et al. (2007) uses a bag-of-words model to assess whether company financial news can predict a company's accounting earnings and stock returns. The results indicate that negative words in company-specific news predict low firm earnings, although market prices tend under-react to the information entrenched in negative words.
Bollen et al. (2007) examined whether sentiment captured from Twitter feeds is correlated to the value of the Dow Jones Industrial Average Index (DJIA). They deployed OpinionFinder and Google-Profile of Mode States (GPOMS), opinion-tracking tools that measure mood in six dimensions (Calm, Alert, Sure, Vital, Kind, and Happy). The results let them to conclude that
the accuracy of DJIA predictions can be significantly improved by the inclusion of specific public mood dimensions but not others.
Loughran et al. (2007) apply sentiment analysis to 10-K filings. Authors find that almost three-quarters of negative word counts in 10-K filings based on the Harvard dictionary are typically not negative in a financial context. To do so, they developed an alternative dictionary that better reflects sentiment in financial text.
A majority of the work in sentiment analysis seem to focus on predicting market prices or directional change. There are many examples of applying text mining to news data relating to the stock market with a particular emphasis on the prediction of market prices. However, only a limited number of research papers look into how financial news impacts stock market volatility.
Kogan et al. (2007) use Support Vector Machine (SVM) to predict the volatility of stock market returns. The results indicate that "text regression model predictions to correlate with true volatility nearly as well as historical volatility, and a combined model to perform even better".
Mao et al. (2007) use a wide range of news data and sentiment tracking measures to predict financial market values. The authors find that Twitter sentiment is a significant predictor of daily market returns, but after controlling for all other mood indicators including VIX, sentiment indicators are no longer statistically insignificant.
Similarly, Gross-Kluffmann et al. (2007) find that the release of highly relevant news induces an increase in return volatility, with negative news having a greater impact than positive news.
Glasserman et al. (2007) use an n-gram model to develop a methodology showing that unusual negative and positive news forecasts volatility at both the company-specific and aggregate levels. The authors find that an increase in the "unusualness" of news with negative sentiment predicts an increase in stock market volatility. Similarly, unusual positive news forecasts lower volatility. According to research findings, news is reflected in volatility more slowly at the aggregate than at the company-specific level, in agreement with the effect of diversification.
Calomiris et al. (Calomiris et al., 2019) use news articles to develop a methodology to predict risk and return in stock markets in developed and emerging countries. Their results indicate that the topic-specific sentiment, frequency and unusualness of news text can predict future returns, volatility, and drawdowns.
Similarly, Caporin et al. (Caporin et al., 2019) find that news-related variables can improve volatility prediction. Certain news topics such earning announcements and upgrades/downgrades are more relevant than other news variables in predicting market volatility.
In a more recent study, Atkins et al. (Atkins et al., 2019) use LDA and a simple Naive Bayes classifier to predict stock market volatility movements. The authors find that the information captured from news articles can predict market volatility more accurately than the direction the price movements. They obtained a 56% accuracy in predicting directional stock market volatility on the arrival of new information.
Also Mahajan et al. (Mahajan et al., 2019) used LDA to identify topics of financial news and then to predict a rise or fall in the stock markets based on topics extracted from financial news. Their developed classifier achieved 60% accuracy in predicting market direction.
Jiao et al. (Jiao et al., 2019) show that a high social media activity around a specific company predicts a significant increase in return volatility whereas attention from influential press outlets, e.g. the Wall Street Journal in fact is a predictor of the opposite: a decrease in return volatility.
## 3. Data
For our research we decided to use three different data sets (tweets, news headlines, and full news stories) to analyse sentiment and compare the results. News headlines about FTSE100 companies were obtained from RavenPack. The dataset includes headlines as well as other metadata collected from 1 January 2019 to August 2019. News arrival is recorded with GMT time stamps up to a millisecond precision. In total we have 969,753 headlines for our analysis. The number of headlines during the weekends ranged from around 700 to 1,300 daily, while during normal working days the number of headlines often exceeded 5,000 per day. We used the Eikon API1 to gather news stories about FTSE100 companies starting from April 2019 to the end of August 2019. Around 12,000 articles have been collected between April and August 2019.
Footnote 1: Please see [https://developers.refinitiv.com/eikon-apis/eikon-data-api](https://developers.refinitiv.com/eikon-apis/eikon-data-api)
By using Twitter Streaming API, in total we collected 545,979 tweets during July-August 2019. For the purpose of this study and in order to avoid too generic tweets, we retained and mined only the so-called "$cashtags" that mentioned companies included in the FTSE100 index. The rationale for selecting certain hashtags relates back to the original aim of measuring sentiment of news related to FTSE100 companies rather than overall financial industry.
For this project we decided to use FTSE100 index data. The FTSE100 index represents the performance of the largest 100 companies listed on the London Stock Exchange (LSE) with the highest market capitalization and is considered the best indicator of the health of the UK stock market. The daily closing prices of FTSE100 index were obtained from the Reuters Eikon Platform, using their API.
_In addition, to assess the relationship between stock market movements and sentiment we computed daily market returns and defined the return on day \(t\) as the change in log Close from day \(t-1\) expressed as_
\[r_{t}=\log\frac{CLOSE_{t}}{CLOSE_{t-1}} \tag{1}\]
The volatility of FTSE 100 is classically defined as:\[Vol=\sqrt{\frac{1}{N}\sum_{t+1}^{N}(r_{t}-\bar{r})^{2}}\cdot\sqrt{252} \tag{2}\] | 2012.05906v1.mmd |
import Component from '@ember/component';
import layout from '../../../templates/components/freestyle/bootstrap/tables/body/-row';
import { BuilderForPropDefaults } from 'ember-bootstrap-controls/utils/prop-definition-tools';
import { propDefinitions } from '../../bootstrap/tables/body/-row';
export default Component.extend({
layout,
propDefinitions,
data: Object.assign(BuilderForPropDefaults(propDefinitions), {
value: '',
}),
basicValue: '',
});
| wildland/ember-bootstrap-controls-addon/components/freestyle/bootstrap/tables/body/-row.js |
from distutils.core import setup, Extension
setup(name="java_random", version="1.0.1",
description="Provides a fast implementation of the Java random number generator",
author="Matthew Bradbury",
license="MIT",
url="https://github.com/MBradbury/python_java_random",
ext_modules=[Extension("java_random", ["src/java_random_module.c", "src/java_random.c"])],
classifiers=["Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: Implementation :: CPython"]
)
| MBradbury/python_java_random-setup.py |
'use strict';
import filter from './internal/filter';
import doParallelLimit from './internal/doParallelLimit';
/**
* The same as `filter` but runs a maximum of `limit` async operations at a
* time.
*
* @name filterLimit
* @static
* @memberOf async
* @see async.filter
* @alias selectLimit
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
*/
export default doParallelLimit(filter);
| ezubarev/async-lib/filterLimit.js |
class Repo < ActiveRecord::Base
include GithubApiFactory
include OrderedCommits
has_many :pushes, dependent: :restrict_with_exception
has_many :refs, dependent: :restrict_with_exception
has_many :unordered_commits, class_name: 'Commit', dependent: :restrict_with_exception
has_many :external_link_repos
has_many :external_links, through: :external_link_repos
has_many :deploys, through: :deploy_repos
has_many :deploy_repos
belongs_to :user
validates_presence_of :github_identifier
validates_presence_of :user_id
before_validation :set_github_identifier
def create_hook(request_original_url)
github = create_github_api_from_oauth_token(self)
github_user, github_repo = user_and_repo
begin
github.repos.hooks.list(github_user, github_repo)
rescue Github::Error::NotFound => e
raise CannotAccessWebhooksError.new(
"[gci] #{DateTime.now.utc.iso8601} Cannot access github webhooks for repo " \
"#{github_user}/#{github_repo}. Ensure user is an owner of the github repo."
)
end
req_uri = URI.parse(request_original_url)
if Rails.env.development?
host_port = ENV.fetch('NGROK_HOST')
else
host_port = "#{req_uri.host}:#{req_uri.port}"
end
webhook_url = "#{req_uri.scheme}://#{host_port}/repos/#{self.id}/pushes/receive"
hook_config = {
content_type: 'json',
insecure_ssl: 1,
url: webhook_url
}
response = nil
begin
response = do_create_hook(github, hook_config)
rescue Github::Error::UnprocessableEntity => e
puts "[gci] #{DateTime.now.utc.iso8601} Error creating hook: #{e.inspect}. " \
"Attempting to delete and recreate web hook for #{webhook_url}"
existing_hook_id = github.repos.hooks.list(github_user, github_repo).detect { |h| h.config.url == webhook_url }.id
github.repos.hooks.delete(github_user, github_repo, existing_hook_id)
response = do_create_hook(github, hook_config)
end
update_attributes!(hook: response.to_hash.to_json)
end
def github_api_object
github = create_github_api_from_oauth_token(self)
github_user, github_repo = user_and_repo
github.repos.get(github_user, github_repo)
end
def user_and_repo
matches = /github.com(\/|:)(.+)\/(.+).git/.match(url)
github_user = matches[2]
github_repo = matches[3]
return github_user, github_repo
end
def commit_link(sha)
user, repo = user_and_repo
"https://github.com/#{user}/#{repo}/commit/#{sha}"
end
private
def do_create_hook(github, hook_config)
github_user, github_repo = user_and_repo
github.repos.hooks.create(github_user, github_repo, {name: 'web', active: true, events: ['push'], config: hook_config})
end
def set_github_identifier
return true if github_identifier.present?
self.github_identifier = github_api_object.id
end
end
| pivotaltracker/git-commit-integration-app/models/repo.rb |
var {vowelsCount} = require('../questions/vowelsCount.js');
describe('统计给定的字符串中的元音被字母(a, e, i, o, u)的数量', function(){
it('null值返回', function(){
var count = vowelsCount(null);
expect(count).toBe(0);
});
it('不含元音字母的情况', function(){
var count = vowelsCount('b');
expect(count).toBe(0);
});
it('含有元音字母a的情况', function(){
var count = vowelsCount('a');
expect(count).toBe(1);
});
it('含有元音字母e的情况', function(){
var count = vowelsCount('e');
expect(count).toBe(1);
});
it('含有元音字母i的情况', function(){
var count = vowelsCount('i');
expect(count).toBe(1);
});
it('含有元音字母o的情况', function(){
var count = vowelsCount('o');
expect(count).toBe(1);
});
it('含有元音字母u的情况', function(){
var count = vowelsCount('u');
expect(count).toBe(1);
});
it('长字符串测试abcdefg', function(){
var count = vowelsCount('abcdefg');
expect(count).toBe(2);
});
it('长字符串测试aceioudefzwkjr', function(){
var count = vowelsCount('aceioudefzwkjr');
expect(count).toBe(6);
});
}); | sinhbv/learnJS-spec/vowelsCount-spec.js |
package assignment;
//Importing various libraries
import processing.core.*;
//H_Space class for the homescreen which extends the abstract class
public class H_Space extends Obj
{
//Fields
float a = 833;
float b = 650;
float speedx = 7.0f;
PApplet papplet;
//Constructor to declare the starting point of the object
public H_Space(PApplet papplet, float startx, float starty)
{
super(papplet, startx, starty);
this.papplet = papplet;
}
@Override
//Method to set position and movement of the object
void position()
{
//Error Check
if(pos.x > 980)
{
speedx = -speedx;
}
//Error Check
if(pos.x < 686)
{
speedx = - speedx;
}
pos.x = pos.x + speedx;
}
@Override
//Abstract method to draw the object itself
void thing()
{
//Draw the enemy object
papplet.pushMatrix();
papplet.translate(pos.x, pos.y);
papplet.stroke(245, 250, 20);
papplet.line(enemyx, enemyy, enemyx - 15, enemyy - 15);
papplet.line(enemyx - 15, enemyy - 15, enemyx - 15, enemyy + 30);
papplet.line(enemyx - 15, enemyy + 30, enemyx, enemyy);
papplet.line(enemyx, enemyy, enemyx + 15, enemyy - 15);
papplet.line(enemyx + 15, enemyy - 15, enemyx + 15, enemyy + 30);
papplet.line(enemyx + 15, enemyy + 30, enemyx, enemyy);
papplet.popMatrix();
//Draw the shooter object
papplet.stroke(40, 232, 23);
papplet.line(a, b, a - 20, b + 30);
papplet.line(a - 20, b + 30, a, b + 15);
papplet.line(a, b + 15, a + 20, b + 30);
papplet.line(a + 20, b + 30, a, b);
}
//Abstract method to reset the variables
void newgame()
{
}
}
| Kellier/Assignment-3-Arcade/src/assignment/H_Space.java |
import sys
import argparse
import sqlite3
import gzip
from progressbar import ProgressBar, Counter, Timer
from lxml import etree
parser = argparse.ArgumentParser(prog='apntool', description="""Process Android's apn xml files and drop them into an easily
queryable SQLite db. Tested up to version 9 of their APN file.""")
parser.add_argument('-v', '--version', action='version', version='%(prog)s v1.0')
parser.add_argument('-i', '--input', help='the xml file to parse', default='apns.xml', required=False)
parser.add_argument('-o', '--output', help='the sqlite db output file', default='apns.db', required=False)
parser.add_argument('--quiet', help='do not show progress or verbose instructions', action='store_true', required=False)
parser.add_argument('--no-gzip', help="do not gzip after creation", action='store_true', required=False)
args = parser.parse_args()
try:
connection = sqlite3.connect(args.output)
cursor = connection.cursor()
cursor.execute('SELECT SQLITE_VERSION()')
version = cursor.fetchone()
if not args.quiet:
print("SQLite version: %s" % version)
print("Opening %s" % args.input)
cursor.execute("PRAGMA legacy_file_format=ON")
cursor.execute("PRAGMA journal_mode=DELETE")
cursor.execute("PRAGMA page_size=32768")
cursor.execute("VACUUM")
cursor.execute("DROP TABLE IF EXISTS apns")
cursor.execute("""CREATE TABLE apns(_id INTEGER PRIMARY KEY, mccmnc TEXT, mcc TEXT, mnc TEXT, carrier TEXT, apn TEXT,
mmsc TEXT, port INTEGER, type TEXT, protocol TEXT, bearer TEXT, roaming_protocol TEXT,
carrier_enabled INTEGER, mmsproxy TEXT, mmsport INTEGER, proxy TEXT, mvno_match_data TEXT,
mvno_type TEXT, authtype INTEGER, user TEXT, password TEXT, server TEXT)""")
apns = etree.parse(args.input)
root = apns.getroot()
pbar = ProgressBar(widgets=['Processed: ', Counter(), ' apns (', Timer(), ')'], maxval=len(list(root))).start() if not args.quiet else None
count = 0
for apn in root.iter("apn"):
if apn.get("mmsc") == None:
continue
sqlvars = ["?" for x in apn.attrib.keys()] + ["?"]
mccmnc = "%s%s" % (apn.get("mcc"), apn.get("mnc"))
values = [apn.get(attrib) for attrib in apn.attrib.keys()] + [mccmnc]
keys = apn.attrib.keys() + ["mccmnc"]
cursor.execute("SELECT 1 FROM apns WHERE mccmnc = ? AND apn = ?", [mccmnc, apn.get("apn")])
if cursor.fetchone() == None:
statement = "INSERT INTO apns (%s) VALUES (%s)" % (", ".join(keys), ", ".join(sqlvars))
cursor.execute(statement, values)
count += 1
if not args.quiet:
pbar.update(count)
if not args.quiet:
pbar.finish()
connection.commit()
print("Successfully written to %s" % args.output)
if not args.no_gzip:
gzipped_file = "%s.gz" % (args.output,)
with open(args.output, 'rb') as orig:
with gzip.open(gzipped_file, 'wb') as gzipped:
gzipped.writelines(orig)
print("Successfully gzipped to %s" % gzipped_file)
if not args.quiet:
print("\nTo include this in the distribution, copy it to the project's assets/databases/ directory.")
print("If you support API 10 or lower, you must use the gzipped version to avoid corruption.")
except sqlite3.Error, e:
if connection:
connection.rollback()
print("Error: %s" % e.args[0])
sys.exit(1)
finally:
if connection:
connection.close()
| Securecom/Securecom-Messaging-apntool/apntool.py |
Package.describe({
name: "jquery-history",
summary: "Deprecated package for HTML5 pushState",
version: "1.0.2"
});
Package.onUse(function (api) {
api.versionsFrom('1.0');
api.use('json', 'client');
api.use('jquery', 'client');
api.addFiles(['history.adapter.jquery.js',
'history.html4.js',
'history.js'],
'client');
});
| TribeMedia/meteor-packages/non-core/jquery-history/package.js |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_INSTALLER_SETUP_MODIFY_PARAMS_H_
#define CHROME_INSTALLER_SETUP_MODIFY_PARAMS_H_
namespace base {
class FilePath;
class Version;
} // namespace base
namespace installer {
class InstallationState;
class InstallerState;
// ModifyParams represents the collection of parameters needed
// for modify operations (uninstall, repair, os upgrade, etc.)
// as well as for install operations.
//
// ModifyParams are expected to be constructed on the stack,
// with the lifetime of the contained references and pointers to
// be a strict subset of the calling stack frame.
struct ModifyParams {
InstallerState& installer_state;
InstallationState& installation_state;
// Path to the executable (setup.exe)
const base::FilePath& setup_path;
// Current installed version if valid; otherwise, no version is installed.
const base::Version& current_version;
ModifyParams(InstallerState& installer_state,
InstallationState& installation_state,
const base::FilePath& setup_path,
const base::Version& current_version)
: installer_state(installer_state),
installation_state(installation_state),
setup_path(setup_path),
current_version(current_version) {}
};
} // namespace installer
#endif // CHROME_INSTALLER_SETUP_MODIFY_PARAMS_H_
| ric2b/Vivaldi-browser-chromium/chrome/installer/setup/modify_params.h |
KORRES BLACK GIFT for Him, Black Pepper Cashmere Lemonwood with Eau de Toilette spray 50ml & Showergel 250ml - ilovepharmacy.gr
> Δώρα & Προσφορές>KORRES BLACK GIFT for Him, Black Pepper Cashmere Lemonwood with Eau de Toilette spray 50ml & Showergel 250ml
KORRES BLACK GIFT for Him, Black Pepper Cashmere Lemonwood with Eau de Toilette spray 50ml & Showergel 250ml
Συσκευασία δώρου για άνδρες με ένα χαρακτηριστικό άρωμα σε σπρέυ και ένα αφρόλουτρο της ίδιας σειράς.
Συσκευασία δώρου για άνδρες KORRES BLACK GIFT for Him, περιέχει το άρωμα Black Pepper Cashmere Lemonwood Eau de Toilette 50ml & το αφρόλουτρο Black Pepper Cashmere Lemonwood Showergel 250ml.
Χαρακτηριστικά του αρώματος:
Μετά την κορυφή γεμάτη από φρουτώδεις νότες, Λεμόνι, Μανταρίνι, Ανανάς, Γκρέϊπφρουτ έρχονται οι πολύτιμες νότες από μαύρο πιπέρι που μαζί με το κάρδαμο, τη λεβάντα και το ινδικό Gurjum διαμορφώνουν τον αρρενωπό πυρήνα του αρώματος. Ο πληθωρικός του χαρακτήρας καταλήγει στο Cashmere που δένει αρμονικά με Patchouly, Guaiacwood και Cedarwood. | c4-cy |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) cgstudiomap <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Res Partner phone: missing details',
'version': '0.2',
'author': 'cgstudiomap',
'maintainer': 'cgstudiomap',
'license': 'AGPL-3',
'category': 'Sales',
'summary': 'Set up for phone for missing details bot',
'depends': [
'res_partner_missing_details',
'base_phone_validation',
],
'external_dependencies': {},
'data': [
'missing_details.xml',
],
'installable': True,
}
| cgstudiomap/cgstudiomap-main/local_modules/res_partner_phone_missing_details/__openerp__.py |
var zip = require('./zip');
module.exports = function(gj, options) {
var content = zip(gj, options);
location.href = 'data:application/zip;base64,' + content;
};
| JasonSanford/shp-write-src/download.js |
/* global localStorage */
define([
'jquery',
'mockup-patterns-base',
'pat-registry',
'mockup-utils',
'castle-url/components/utils',
'castle-url/libs/react/react.min',
'mockup-patterns-modal',
'castle-url/patterns/toolbar/menu-item'
], function ($, Base, Registry, utils, cutils, R, ModalPattern, MenuItemBase) {
'use strict';
var D = R.DOM;
var ModalMenuItemBase = cutils.extend(MenuItemBase, {
onClick: function(e){
e.preventDefault();
cutils.createModalComponent(this.props.ModalComponent, this.props.id, this.getSettings());
},
getSettings: function(){
return {
parent: this.props.parent
};
}
});
return ModalMenuItemBase;
});
| castlecms/castle.cms-castle/cms/static/patterns/toolbar/modal-item.js |
package org.innovateuk.ifs.interview.resource;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.time.ZonedDateTime;
public class InterviewApplicationSentInviteResource {
private String subject;
private String content;
private ZonedDateTime assigned;
public InterviewApplicationSentInviteResource() {}
public InterviewApplicationSentInviteResource(String subject, String content, ZonedDateTime assigned) {
this.subject = subject;
this.content = content;
this.assigned = assigned;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public ZonedDateTime getAssigned() {
return assigned;
}
public void setAssigned(ZonedDateTime assigned) {
this.assigned = assigned;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InterviewApplicationSentInviteResource that = (InterviewApplicationSentInviteResource) o;
return new EqualsBuilder()
.append(subject, that.subject)
.append(content, that.content)
.append(assigned, that.assigned)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(subject)
.append(content)
.append(assigned)
.toHashCode();
}
}
| InnovateUKGitHub/innovation-funding-service-common/ifs-resources/src/main/java/org/innovateuk/ifs/interview/resource/InterviewApplicationSentInviteResource.java |
/*
* Copyright 2017 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
"use strict";
var WebSocketWrapper = function (options) {
var self = this;
Emitter(this);
var indefiniteRetry = options.indefiniteRetry || false;
var failIfInitialConnectionFails = options.failIfInitialConnectionFails || true;
var timeoutInterval = options.timeoutInterval || WebSocketWrapper.TIMEOUT_DEFAULT;
var timeoutStart = options.timeoutStart || WebSocketWrapper.TIMEOUT_START;
var everConnectedUsingWebsocket = false;
var ws;
var lastPingTime;
var initTimer;
var stopped;
var pingDetectionTimeoutTimer;
if (indefiniteRetry) {
pingDetectionTimeoutTimer = often(function () {
var diff = new Date() - lastPingTime;
if (diff > timeoutInterval) {
self.close(WebSocketWrapper.CLOSE_WILL_RETRY, "Will retry in some time!");
retryIfNeeded.call(self);
}
}).start(timeoutStart).wait(timeoutInterval);
}
var init = function () {
self.emit('beforeInitialize', options);
ws = new WebSocket(options.url, options.protocols);
lastPingTime = new Date();
stopped = false;
ws.addEventListener('open', function (e) {
everConnectedUsingWebsocket = true;
self.emit('open', e);
});
ws.addEventListener('message', function (e) {
if (isPingFrame(e.data)) {
lastPingTime = new Date();
// don't bubble the ping event, since it's only meant for the websocket
return;
}
self.emit('message', e);
});
ws.addEventListener('error', function (e) {
if (indefiniteRetry) {
pingDetectionTimeoutTimer.done();
}
if (!everConnectedUsingWebsocket) {
self.emit('initialConnectFailed', e)
} else {
self.emit('error', e);
}
retryIfNeeded();
});
ws.addEventListener('close', function (e) {
if (indefiniteRetry) {
pingDetectionTimeoutTimer.done();
}
if (e.code === WebSocketWrapper.CLOSE_ABNORMAL) {
return;
}
self.emit('close', e);
});
};
var retryIfNeeded = function () {
if (!indefiniteRetry) {
return;
}
if (failIfInitialConnectionFails && !everConnectedUsingWebsocket) {
return;
}
if (stopped) {
return;
}
if (initTimer) {
window.clearTimeout(initTimer);
}
initTimer = setTimeout(init, 5000);
};
var isPingFrame = function (data) {
if (_.isString(data)) {
try {
return JSON.parse(e.data)['type'] === 'ping'
} catch (e) {
// ignore, maybe it's not json
}
}
return false;
};
this.close = function (code, reason) {
ws.close(code, reason)
};
this.stop = function (code, reason) {
stopped = true;
pingDetectionTimeoutTimer.done();
this.close(code, reason);
};
init();
};
// the timeout on the server is 10s,
// we add another 5 seconds as a buffer, to account for network latency
WebSocketWrapper.TIMEOUT_DEFAULT = 15000;
WebSocketWrapper.TIMEOUT_START = 5000;
WebSocketWrapper.CLOSE_NORMAL = 1000;
WebSocketWrapper.CLOSE_ABNORMAL = 1006;
WebSocketWrapper.CLOSE_WILL_RETRY = 4100;
window.WebSocketWrapper = WebSocketWrapper;
})(); | sghill/gocd-server/webapp/WEB-INF/rails.new/app/assets/javascripts/websocket_wrapper.js |
/* Copyright Ben Trask and other contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. */
var fs = require("fs");
var has = require("../../utilities/has");
var TYPES = {
"image/png": "png",
"image/jpg": "jpg",
"image/jpeg": "jpg",
"image/gif": "gif",
};
exports.acceptsType = function(type) {
return has(TYPES, type);
};
exports.format = function(stream, type, dir, prefix, callback/* (err) */) {
// stream.pipe(fs.createWriteStream(dir+"/image."+TYPES[type], {}));
var bufs = [];
stream.on("error", function(err) {
callback(err);
});
stream.on("readable", function() {
bufs.push(stream.read());
});
stream.on("end", function() {
var buf = Buffer.concat(bufs).toString("base64")
fs.writeFile(dir+"/index.html", imageHTML(type, buf), {encoding: "utf8"}, function(err) {
callback(err);
});
});
};
// TODO: HACK. Gotta get sub-requests working instead of using data: URIs.
function imageHTML(type, buffer) {
return "<!doctype html>\n<img src=\"data:"+type+";base64,"+buffer+"\">";
}
| btrask/earthfs-js-old-plugins/formatters/image-basic.js |
exports.definition = {
config: {
"columns": {
"id": "String",
"count": "Int"
},
"defaults": {
"id": "instance",
"count": 0
},
"adapter": {
"type": "properties",
"collection_name": "singleModel"
}
},
extendCollection : function(Collection) {
_.extend(Collection.prototype, {
// For Backbone v1.1.2, uncomment this to override the fetch method
/*
fetch: function(options) {
options = options ? _.clone(options) : {};
options.reset = true;
return Backbone.Collection.prototype.fetch.call(this, options);
},
*/
});
return Collection;
}
};
| indera/alloy-test/apps/models/properties/models/modelTab.js |
"""
Django settings for msba project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!ten1ru5t232sshqc1yqhie1@rq&185%r$8ukkl0@g_z6emw3x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'msba.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'msba.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'msba',
'USER': 'wenduowang',
'PASSWORD': 'nicai',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| wenduowang/git_home-python/django/msba/msba/settings.py |
define(["require", "exports", 'eight/core/geometry', 'eight/math/e3ga/vectorE3'], function(require, exports, geometry, vectorE3) {
var vertexList = [
vectorE3(-0.5, -0.5, +0.5),
vectorE3(+0.5, -0.5, +0.5),
vectorE3(+0.5, +0.5, +0.5),
vectorE3(-0.5, +0.5, +0.5),
vectorE3(-0.5, -0.5, -0.5),
vectorE3(+0.5, -0.5, -0.5),
vectorE3(+0.5, +0.5, -0.5),
vectorE3(-0.5, +0.5, -0.5)
];
var triangles = [
[0, 1, 2],
[0, 2, 3],
[4, 7, 5],
[5, 7, 6],
[0, 7, 4],
[0, 3, 7],
[1, 5, 2],
[2, 5, 6],
[2, 7, 3],
[2, 6, 7],
[0, 5, 1],
[0, 4, 5]
];
var boxGeometry = function (spec) {
var base = geometry(spec);
var api = {
primitives: triangles,
vertices: [],
normals: [],
colors: [],
primitiveMode: base.primitiveMode
};
for (var t = 0; t < triangles.length; t++) {
var triangle = triangles[t];
// Normals will be the same for each vertex of a triangle.
var v0 = vertexList[triangle[0]];
var v1 = vertexList[triangle[1]];
var v2 = vertexList[triangle[2]];
var perp = v1.sub(v0).cross(v2.sub(v0));
var normal = perp.div(perp.norm());
for (var j = 0; j < 3; j++) {
api.vertices.push(vertexList[triangle[j]].x);
api.vertices.push(vertexList[triangle[j]].y);
api.vertices.push(vertexList[triangle[j]].z);
api.normals.push(normal.x);
api.normals.push(normal.y);
api.normals.push(normal.z);
api.colors.push(0.0);
api.colors.push(0.0);
api.colors.push(1.0);
}
}
return api;
};
return boxGeometry;
});
| mapleyustat/davinci-eight-src/eight/geometries/boxGeometry.js |
'use strict';
/**
* @ngdoc function
* @name projectsApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the projectsApp
*/
angular.module('projectsApp')
.controller('MainCtrl', ['util',
function(util) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
util.s()
];
}
]);
| pvamshi/data-visualizer-app/scripts/controllers/main.js |
/**
* @license
* Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import parseChangelog = require('changelog-parser');
import commandLineArgs = require('command-line-args');
import marked = require('marked');
import puppeteer = require('puppeteer');
import fs = require('fs');
import util = require('util');
import path = require('path');
const readFile = util.promisify(fs.readFile);
const optionDefinitions = [
{name: 'file', type: String, defaultOption: true},
{name: 'version', type: String},
];
export const run = async () => {
const options = commandLineArgs(optionDefinitions);
const filename = (options as any).file || 'CHANGELOG.md';
const version = (options as any).version;
const packageJson = JSON.parse(
await readFile(path.join(path.dirname(filename), 'package.json'), {encoding:
'utf-8'})
);
const packageName = packageJson.name;
console.log(`Reading ${packageName} release ${version} from ${filename}`);
const changelog = (await parseChangelog({
filePath: filename,
removeMarkdown: false,
})) as Changelog;
const release = await getRelease(changelog, version);
if (release === undefined) {
throw new Error('no release found');
}
const body = marked(release.body);
// colors taken from https://github.com/dracula/dracula-theme
const html = `
<!doctype html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400|Roboto+Mono:300|Roboto+Slab:400,700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Open Sans', sans-serif;
font-weight: 300;
background: #282a36;
color: #f8f8f2;
margin: 1.5em;
}
h1, h2, h3 {
font-family: 'Roboto Slab', serif;
color: #ff79c6;
font-weight: 400;
}
span.name {
color: #8be9fd;
}
code {
font-family: 'Roboto Mono', monospace;
font-size: 14px;
background: #44475a;
border-radius: 3px;
padding: 0 4px;
}
a {
color: inherit;
text-decoration: none;
}
</style>
</head>
<body>
<h2><span class="name">${packageName}</span> ${release.title}</h2>
${body}
</body>
</html>
`;
const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
await page.setViewport({width: 800, height: 800, deviceScaleFactor: 2});
await page.setContent(html);
await page.evaluate(`document.fonts.ready`);
const bounds = await page.evaluate(`
document.documentElement.getBoundingClientRect().toJSON()
`);
await page.screenshot({
path: 'release.png',
encoding: 'binary',
type: 'png',
clip: {
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
},
});
console.log('Wrote screenshot to release.png');
await browser.close();
process.exit();
};
const latestVersion = {};
const getRelease = async (
changelog: Changelog,
version: string | undefined | typeof latestVersion = latestVersion
): Promise<Release | undefined> => {
return changelog.versions.find(
(r) =>
(r.version !== null && version === latestVersion) ||
r.version === version ||
(r.version === null && version === undefined)
);
};
interface Release {
version: string | null;
title: string;
date: string | null;
body: string;
parsed: {
_: string[];
[heading: string]: string[];
};
}
interface Changelog {
title: string;
description: string;
versions: Array<Release>;
}
| PolymerLabs/release-image-src/index.ts |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "NSObject-Protocol.h"
@protocol NSFileManagerDelegate <NSObject>
@optional
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 removingItemAtURL:(id)arg3;
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 removingItemAtPath:(id)arg3;
- (BOOL)fileManager:(id)arg1 shouldRemoveItemAtURL:(id)arg2;
- (BOOL)fileManager:(id)arg1 shouldRemoveItemAtPath:(id)arg2;
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 linkingItemAtURL:(id)arg3 toURL:(id)arg4;
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 linkingItemAtPath:(id)arg3 toPath:(id)arg4;
- (BOOL)fileManager:(id)arg1 shouldLinkItemAtURL:(id)arg2 toURL:(id)arg3;
- (BOOL)fileManager:(id)arg1 shouldLinkItemAtPath:(id)arg2 toPath:(id)arg3;
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 movingItemAtURL:(id)arg3 toURL:(id)arg4;
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 movingItemAtPath:(id)arg3 toPath:(id)arg4;
- (BOOL)fileManager:(id)arg1 shouldMoveItemAtURL:(id)arg2 toURL:(id)arg3;
- (BOOL)fileManager:(id)arg1 shouldMoveItemAtPath:(id)arg2 toPath:(id)arg3;
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 copyingItemAtURL:(id)arg3 toURL:(id)arg4;
- (BOOL)fileManager:(id)arg1 shouldProceedAfterError:(id)arg2 copyingItemAtPath:(id)arg3 toPath:(id)arg4;
- (BOOL)fileManager:(id)arg1 shouldCopyItemAtURL:(id)arg2 toURL:(id)arg3;
- (BOOL)fileManager:(id)arg1 shouldCopyItemAtPath:(id)arg2 toPath:(id)arg3;
@end
| liyong03/YLCleaner-YLCleaner/Xcode-RuntimeHeaders/IDEModelEditor/NSFileManagerDelegate-Protocol.h |
package state
// Represents the state of a document. It can be modified by applying
// Primitives to it, which make simple replacements or deletions to
// the contents at specified locations.
//
// These transformations not only alter the DocumentState's .Value
// field, they also call the OnPrimitive callback, if it is set for
// this DocumentState.
type DocumentState struct {
Value Container
onPrimitive OnPrimitiveCallback
}
func NewDocumentState() *DocumentState {
// We know this won't fail, so we can ignore err
container, _ := makeContainer(map[string]interface{}{})
return &DocumentState{container, nil}
}
// Construct and apply a Primitive that completely resets the Value
// of the DocumentState to an empty JSON {}.
func (ds *DocumentState) Reset() {
// We know this won't fail, so we can ignore err
p := &SetPrimitive{
[]interface{}{},
map[string]interface{}{},
}
ds.Apply(p)
}
// An optional callback to be called for every primitive applied to
// a DocumentState object. Will always be called in the same order,
// in the same goroutine, as the Primitive application itself.
type OnPrimitiveCallback func(primitive Primitive)
// Set the OnPrimitiveCallback for this DocumentState.
func (ds *DocumentState) SetPrimitiveCallback(c OnPrimitiveCallback) {
ds.onPrimitive = c
}
// Apply a Primitive such that the callback (if set) is run.
//
// Always preferable to p.Apply(ds), which does not run the callback.
func (ds *DocumentState) Apply(p Primitive) error {
err := p.Apply(ds)
if err != nil {
return err
}
if ds.onPrimitive != nil {
ds.onPrimitive(p)
}
return nil
}
// Return the raw, JSON-ic value of the DocumentState.
func (ds *DocumentState) Export() interface{} {
return ds.Value.Export()
}
| DJDNS/go-deje-state/state.go |
//
// SSBaseDataSource+WMFLayoutDirectionUtilities.h
// Wikipedia
//
// Created by Brian Gerstle on 11/30/15.
// Copyright © 2015 Wikimedia Foundation. All rights reserved.
//
#import <SSDataSources/SSDataSources.h>
@interface SSBaseDataSource (WMFLayoutDirectionUtilities)
- (NSUInteger)wmf_startingIndexForApplicationLayoutDirection;
- (NSUInteger)wmf_startingIndexForLayoutDirection:(UIUserInterfaceLayoutDirection)layoutDirection;
@end
| jindulys/Wikipedia-Wikipedia/Code/SSBaseDataSource+WMFLayoutDirectionUtilities.h |
(function ($, context) {
"use strict";
var elementUniqueId = 'progress_circle';
var pbBlock = {
level: 3,
withControls: true,
cssBlockClass: 'progress-circle',
cssElementClass: 'progress-circle',
toolbarSection: 'content_elements',
label: 'Progress Circle',
description: 'A progress (or a skill) visualization in a form of an animated circle.'
};
context.registerBlock(elementUniqueId, pbBlock);
var pbElement = function (fieldsValues, contentValue) {
var that = context.classes.elements.baseElement(); // inherit from base element
/**
* VARS
*/
var contentConfig = {
'type': 'input',
'default': ''
};
var fieldsConfig = {
'value': {
'type': 'input',
'hint': '0-100 range'
},
'style': {
type: 'select',
'options': {
'simple': 'simple',
'solid': 'solid'
},
'default': 'simple'
},
'icon': {
type: 'select',
'optionsCallback': g1PageBuilder.helpers.getIconsChoices,
'default': ''
},
'text_color': {
type: 'colorpicker'
},
'bg_color': {
type: 'colorpicker'
}
};
// pseudo constructor
function init () {
that.init(fieldsValues, fieldsConfig, contentValue, contentConfig);
}
init();
// public scope
return that; // gives access to public methods
};
context.registerElement(elementUniqueId, pbElement);
})(jQuery, g1PageBuilder); | googaloo/Sunshine-Pest-Control-wp-content/plugins/g1-page-builder/js/elements/progress_circle/progress_circle.js |
var files =
[
[ "src", "dir_68267d1309a1af8e8297ef4c3efbcdba.html", "dir_68267d1309a1af8e8297ef4c3efbcdba" ],
[ "tests", "dir_59425e443f801f1f2fd8bbe4959a3ccf.html", "dir_59425e443f801f1f2fd8bbe4959a3ccf" ]
]; | CCTLib/cctlib-docs/html/files.js |
Subsets and Splits