language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Shell
|
UTF-8
| 429 | 2.609375 | 3 |
[] |
no_license
|
#! /bin/bash
echo 'deb-src http://ftp.ch.debian.org/debian/ jessie main' >> /etc/apt/sources.list
apt-get update
apt-get build-dep -y privoxy
mkdir -p /usr/src/privoxy
pushd /usr/src
curl -LO http://http.debian.net/debian/pool/main/p/privoxy/privoxy_3.0.23.orig.tar.gz
cd privoxy
tar xvf ../privoxy_3.0.23.orig.tar.gz --strip-components=1
cp -R /mnt/host/deb/* .
dpkg-buildpackage -rfakeroot -uc -b
cd ..
mv *.deb /tmp/out
popd
|
C++
|
UTF-8
| 488 | 3.65625 | 4 |
[] |
no_license
|
/*
Author: Sanjeev Sharma
Description: Practice functions, return true if even number
*/
#include <iostream>
using namespace std;
// returns true if the argument is even, otherwise false
bool is_even(int n);
int main() {
// test
for (int i = -5; i < 6; i++) {
cout << i << '\t';
if (is_even(i))
cout << "even" << endl;
else
cout << "odd" << endl;
}
return 0;
}
bool is_even(int n) {
if(n % 2 == 0){
return true;
}
return false;
}
|
PHP
|
UTF-8
| 320 | 3.234375 | 3 |
[] |
no_license
|
// function that runs when shortcode is called
function w3villa_shortcode() {
// Things that you want to do.
$message = 'Hello world!';
// Output needs to be return
return $message;
}
// register shortcode
add_shortcode('greeting', 'w3villa_shortcode');
// call the shortcode
echo do_shortcode("[greeting]");
|
Python
|
UTF-8
| 350 | 3.015625 | 3 |
[] |
no_license
|
import planarity
n = 6
m = n * (n - 1) / 2
out = "1"
for x in xrange(1, pow(2, m)):
edgelist = []
u, v = 1, 1
for y in xrange(m):
u += 1
if u >= v:
v += 1
u = 1
if x & (1<<(m-y-1)):
edgelist.append((u, v))
out += "1" if planarity.is_planar(edgelist) else "0"
print(out)
|
C++
|
UTF-8
| 2,172 | 2.5625 | 3 |
[] |
no_license
|
///
/// @file create_kmers_presence_absence_table.cpp
/// @brief This program will create a table of presence absence accross DBs
//
// Taking the sorted general kmers list as well as the sorted kmers from
// each accessions, create a table with kmers as rows and accessions as collumns
// where each cell indicate if the kmers was found in the accessions or not
///
/// @author Yoav Voichek (YV), [email protected]
///
/// @internal
/// Created 10/29/18
/// Compiler gcc/g++
/// Company Max Planck Institute for Developmental Biology Dep 6
/// Copyright Copyright (c) 2018, Yoav Voichek
///
/// This source code is released for free distribution under the terms of the
/// GNU General Public License as published by the Free Software Foundation.
///=====================================================================================
///
#include "kmer_general.h"
#include "kmers_merge_multiple_databaes.h"
using namespace std;
int main(int argc, char *argv[]) {
/* Read user input */
if(argc != 5) {
cerr << "usage: " << argv[0] <<
" <1 list of kmers files> <2 all sorted kmers> <3 output name> <4 kmer len>" << endl;
return -1;
}
// Read accessions to use
vector<AccessionPath> kmers_handles = read_accessions_path_list(argv[1]);
vector<string> kmers_filenames, accessions_names;
ofstream fout_names(string(argv[3]) + ".names", ios::binary);
for(size_t i=0; i<kmers_handles.size(); i++) {
accessions_names.push_back(kmers_handles[i].name);
fout_names << kmers_handles[i].name << endl;
kmers_filenames.push_back(kmers_handles[i].path);
}
fout_names.close();
cerr << "Create merger" << endl;
MultipleKmersDataBasesMerger merger(kmers_filenames, accessions_names, argv[2], atoi(argv[4]));
cerr << "Opens file" << endl;
ofstream fout(string(argv[3]) + ".table", ios::binary);
merger.output_table_header(fout);
uint64_t total_iter = 5000;
for(uint i=1; i<=(total_iter+1); i++) { // +1 is for debugging - should be empty
cerr << i << " / " << total_iter << " : Loading k-mers" << endl;
merger.load_kmers(i, total_iter);
merger.output_to_table(fout);
}
cerr << "close file" << endl;
fout.close();
return 0;
}
|
Java
|
UTF-8
| 7,659 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
package tictactoe.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.concurrent.TimeUnit;
import net.accelbyte.sdk.core.AccelByteSDK;
import net.accelbyte.sdk.core.client.OkhttpWebSocketClient;
import net.accelbyte.sdk.core.repository.DefaultConfigRepository;
import net.accelbyte.sdk.core.repository.DefaultTokenRepository;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.jetbrains.annotations.NotNull;
public class App {
public static void main(String[] args) throws Exception {
OkhttpWebSocketClient ws = null;
try {
final String lambdaUrl = System.getenv("LAMBDA_URL"); // e.g. http://localhost:3000/tictactoe
final int readTimeoutSeconds = 60; // Give enough time to complete API calls
final OkHttpClient lambdaClient =
new OkHttpClient().newBuilder().readTimeout(readTimeoutSeconds, TimeUnit.SECONDS).build();
final ResettableCountDownLatch updateSignal = new ResettableCountDownLatch();
// Create SDK instance
AccelByteSDK sdk =
new AccelByteSDK(
new net.accelbyte.sdk.core.client.OkhttpClient(),
new DefaultTokenRepository(),
new DefaultConfigRepository());
// Login user
System.out.print("Username: ");
final String username = System.console().readLine();
System.out.print("Password: ");
final String password = String.valueOf(System.console().readPassword());
final boolean isLoginOk = sdk.loginUser(username, password);
if (!isLoginOk) {
System.out.println("Login user failed!");
System.exit(1); // Login failed
}
final String userAccessToken = sdk.getSdkConfiguration().getTokenRepository().getToken();
// Connect to lobby websocket to get notification from lambda
ws =
OkhttpWebSocketClient.create(
sdk.getSdkConfiguration().getConfigRepository(),
sdk.getSdkConfiguration().getTokenRepository(),
new WebSocketListener() {
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
if (text != null
&& (text.contains("GAME START") || text.contains("BOARD UPDATE"))) {
updateSignal.countDown();
}
}
});
System.out.println("Press Ctrl+C to exit");
// Start game
int player = 0;
while (true) {
final Request startRequest =
new Request.Builder()
.url(lambdaUrl + "/start")
.addHeader("Authorization", String.format("Bearer %s", userAccessToken))
.post(RequestBody.create("{}", MediaType.parse("application/json")))
.build();
try (Response lambdaResponse = lambdaClient.newCall(startRequest).execute()) {
if (lambdaResponse.isSuccessful()) {
final String body = lambdaResponse.body().string();
player =
body.contains("ok - player 1") ? 1 : 2; // Set whether user is player 1 or player 2
break; // Stop here and proceed to play game
}
}
// Starting game may fail because of existing game, try to clear it first
System.out.print("Existing game found, press ENTER to clear it ... ");
System.console().readPassword();
final Request resetRequest =
new Request.Builder()
.url(lambdaUrl + "/reset")
.addHeader("Authorization", String.format("Bearer %s", userAccessToken))
.post(RequestBody.create("{}", MediaType.parse("application/json")))
.build();
try (Response lambdaResponse = lambdaClient.newCall(resetRequest).execute()) {
if (!lambdaResponse.isSuccessful()) {
System.out.println(lambdaResponse.body().string());
System.exit(1); // Reset failed
}
}
}
if (player == 1) {
System.out.println("Waiting for player 2");
} else {
System.out.println("Player 1 moves first");
}
// Play game
while (true) {
System.out.println();
updateSignal.await();
updateSignal.Reset();
final Request stateRequest =
new Request.Builder()
.url(lambdaUrl + "/state")
.addHeader("Authorization", String.format("Bearer %s", userAccessToken))
.get()
.build();
String gameJson = null;
try (Response lambdaResponse = lambdaClient.newCall(stateRequest).execute()) {
if (lambdaResponse.isSuccessful()) {
gameJson = lambdaResponse.body().string();
} else {
System.out.println(lambdaResponse.body().string());
System.exit(1); // Cannot get state
}
}
final ObjectMapper mapper = new ObjectMapper();
final Game game = mapper.readValue(gameJson, Game.class);
// Print board
printBoard(game.board);
System.out.println();
if (game.state == Game.State.PLAYER1_TURN || game.state == Game.State.PLAYER2_TURN) {
// Make move
if ((game.state == Game.State.PLAYER1_TURN && player == 1)
|| (game.state == Game.State.PLAYER2_TURN && player == 2)) {
while (true) {
System.out.print(String.format("Your move (%s): ", player == 1 ? 'X' : 'O'));
final String moveIndex = System.console().readLine();
final Request moveRequest =
new Request.Builder()
.url(lambdaUrl + "/move")
.addHeader("Authorization", String.format("Bearer %s", userAccessToken))
.post(
RequestBody.create(
String.format("{\"move\" : \"%s\"}", moveIndex),
MediaType.parse("application/json")))
.build();
try (Response lambdaResponse = lambdaClient.newCall(moveRequest).execute()) {
if (!lambdaResponse.isSuccessful()) {
System.out.println("Wrong move?");
continue;
}
}
break;
}
} else {
System.out.println("Waiting for response");
}
} else if (game.state == Game.State.PLAYER1_WINS || game.state == Game.State.PLAYER2_WINS) {
// Win or lose
if ((game.state == Game.State.PLAYER1_WINS && player == 1)
|| (game.state == Game.State.PLAYER2_WINS && player == 2)) {
System.out.println("You win");
} else {
System.out.println("You lose");
}
break;
} else if (game.state == Game.State.DRAW) {
// Draw
System.out.println("Draw");
break;
}
}
System.exit(0);
} finally {
if (ws != null) {
ws.close(1000, "normal close");
}
}
System.exit(1);
}
private static void printBoard(char[][] board) {
final int n = board.length;
for (int r = 0; r < n; r++) {
System.out.println("+―――+―――+―――+");
for (int c = 0; c < n; c++) {
System.out.print(String.format("| %s ", board[r][c]));
}
System.out.println("|");
}
System.out.println("+―――+―――+―――+");
}
}
|
C#
|
UTF-8
| 2,775 | 3.390625 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
namespace NGnono.Doubts.GenericsDoubts
{
internal struct StructDict
{
//public override int GetHashCode()
//{
// return 1;
//}
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Run();
Console.ReadLine();
}
/// <summary>
/// 值类型 字典问题
/// </summary>
public static void Run()
{
var dict = new Dictionary<StructDict, bool>();
var a = new StructDict();
a.Name = "121";
var b = new StructDict();//hashcode 与a一致
b.Name = "121";
var c = new StructDict();
c.Name = "aaaa";
var d = new StructDict();//
var e = new StructDict();//hashcode 与d一致
Console.WriteLine(a.GetHashCode());
Console.WriteLine(b.GetHashCode());
Console.WriteLine(c.GetHashCode());
Console.WriteLine(d.GetHashCode());
Console.WriteLine(e.GetHashCode());
dict.Add(a, true);
dict.Add(b, true);
dict.Add(c, true);
dict.Add(d, true);
dict.Add(e, true);
}
public void Run1()
{
var record = new Record();
var i = record.Get<int>("int");
var s = record.Get<string>("str");
var l = record.Get<long>("long");
var d = record.Get<float>("float");
Console.WriteLine(i);
Console.WriteLine(s);
Console.WriteLine(l);
Console.WriteLine(d);
}
}
public static class RecordExtensions
{
private static class Cache<T>
{
public static Func<IRecord, string, T> Get;
}
static RecordExtensions()
{
Cache<string>.Get = (record, field) => record.GetString(field);
Cache<int>.Get = (record, field) => record.GetInt(field);
Cache<long>.Get = (record, field) => record.GetLong(field);
}
public static T Get<T>(this IRecord record, string field)
{
return Cache<T>.Get(record, field);
}
}
public interface IRecord
{
string GetString(string field);
int GetInt(string field);
long GetLong(string field);
}
public class Record : IRecord
{
public string GetString(string field)
{
return "str";
}
public int GetInt(string field)
{
return 1;
}
public long GetLong(string field)
{
return 11L;
}
}
}
|
Markdown
|
UTF-8
| 2,847 | 3.609375 | 4 |
[] |
no_license
|
Local Storage
INTRODUCING HTML5 STORAGE
“HTML5 Storage” is a specification named Web Storage, which was at one time part of the HTML5 specification proper, but was split out into its own specification for uninteresting political reasons. Certain browser vendors also refer to it as “Local Storage” or “DOM Storage.” The naming situation is made even more complicated by some related, similarly-named
USING HTML5 STORAGE
HTML5 Storage is based on named key/value pairs. You store data based on a named key, then you can retrieve that data with the same key. The named key is a string. The data can be any type supported by JavaScript, including strings, Booleans, integers, or floats. However, the data is actually stored as a string. If you are storing and retrieving anything other than strings.
TRACKING CHANGES TO THE HTML5 STORAGE AREA
The storage event is supported everywhere the localStorage object is supported, which includes Internet Explorer 8. IE 8 does not support the W3C standard addEventListener (although that will finally be added in IE 9). Therefore, to hook the storage event, you’ll need to check which event mechanism the browser supports.
LIMITATIONS IN CURRENT BROWSERS
In talking about the history of local storage hacks using third-party plugins, I made a point of mentioning the limitations of each technique, such as storage limits. I just realized that I haven’t mentioned anything about the limitations of the now-standardized HTML5 Storage. I’ll give you the answers first, then explain them. The answers, in order of importance, are “5 megabytes,” “QUOTA_EXCEEDED_ERR,” and “no.”
HTML5 STORAGE IN ACTION
Let’s see HTML5 Storage in action. Recall the Halma game we constructed in the canvas chapter. There’s a small problem with the game: if you close the browser window mid-game, you’ll lose your progress. But with HTML5 Storage, we can save the progress locally, within the browser itself. Here is a live demonstration. Make a few moves, then close the browser tab, then re-open it. If your browser supports HTML5 Storage, the demonstration page should magically remember your exact position within the game, including the number of moves you’ve made, the position of each of the pieces on the board, and even whether a particular piece is selected.
BEYOND NAMED KEY-VALUE PAIRS: COMPETING VISIONS
While the past is littered with hacks and workarounds, the present condition of HTML5 Storage is surprisingly rosy. A new API has been standardized and implemented across all major browsers, platforms, and devices. As a web developer, that’s just not something you see every day, is it? But there is more to life than “5 megabytes of named key/value pairs,” and the future of persistent local storage is… how shall I put it… well, there are competing visions.
|
Ruby
|
UTF-8
| 4,206 | 3.515625 | 4 |
[] |
no_license
|
require_relative '../connect_four'
describe Game do
before :all do
@game = Game.new
end
describe '#new' do
it 'generates a Board' do
expect(@game.board).to be_an_instance_of Game::Board
end
it 'gives Player 1 the first turn' do
expect(@game.player1.is_turn).to be true
expect(@game.player2.is_turn).to be false
end
end
describe '#gg?' do
let (:gameover) { game = Game.new
game.board.each { |column| column.each { |space| space.mark('Dave') } }
return game
}
let (:davewins) { game = Game.new
4.times do
game.player1.claim(1)
end
return game
}
it 'returns false when there are empty spaces and there is no winner' do
expect(@game.gg?).to be false
end
it 'returns true when all spaces are filled' do
expect(gameover.gg?).to be true
end
before { @newgame = davewins}
it 'returns player object when a player has a winning combination' do
expect(@newgame.gg?).to eq(@newgame.player1)
end
end
describe '#active_player' do
it 'recognizes whose turn it is' do
expect(@game.active_player).to eq(@game.player1)
end
end
describe Game::Player do
describe '#claim' do
before :all do
@game.player1.claim(1)
end
it 'lets player mark a valid space' do
expect(@game.board[0][0].marked).to eq(@game.player1)
end
it "includes that space in an array of the player's spaces" do
expect(@game.player1.spaces).to eq([@game.board[0][0]])
end
before { @game.board[0].each { |space| space.mark(@game.player1) } }
it 'claim a space in a full column' do
expect{ @game.player1.claim(1) }.to raise_exception(RuntimeError)
end
it 'raises an exception if the player chooses a non-existent column' do
expect{ @game.player1.claim(0) }.to raise_exception(RangeError)
end
end
end
describe Game::Board do
it 'inherits from Array' do
expect(Game::Board.superclass).to eq(Array)
end
before :all do
@board = Game::Board.new
end
describe '#new' do
it 'creates a new Board object' do
expect(@board).to be_an_instance_of Game::Board
end
it 'makes an array with 7 arrays of 6 instances of Space' do
expect(@board[0]).to be_an_instance_of Array
expect(@board[6]).to be_an_instance_of Array
expect(@board[0][0]).to be_an_instance_of Game::Space
expect(@board[6][5]).to be_an_instance_of Game::Space
end
end
describe '#display' do
it 'prints the board to the screen' do
end
end
end
describe Game::Space do
before :all do
@space = Game::Space.new
end
before :all do
@board = Game::Board.new
@board[0][0].mark('Dave')
end
describe '#new' do
it 'creates a new Space' do
expect(@space).to be_an_instance_of Game::Space
end
it 'creates unmarked Space objects' do
expect(@space).not_to be_marked
end
end
describe '#mark' do
before :each do
@space.mark('Dave')
end
it 'marks a Space' do
expect(@space).to be_marked
end
it 'claims Space for player' do
expect(@space.marked).to eq('Dave')
end
end
describe '#below' do
it 'returns the Space beneath it on the Board' do
expect(@board[0][1].below).to eq(@board[0][0])
end
it 'returns nil when there is no Space beneath it' do
expect(@board[0][0].below).to be_nil
end
end
describe '#valid?' do
it 'returns true when the space is unmarked and has no unmarked spaces beneath it' do
expect(@board[0][1]).to be_valid
expect(@board[1][0]).to be_valid
end
it 'returns false when the space is marked' do
expect(@board[0][0]).not_to be_valid
end
it 'returns false when there is an unmarked space below it' do
expect(@board[0][5]).not_to be_valid
end
end
end
end
|
Markdown
|
UTF-8
| 10,104 | 3.234375 | 3 |
[] |
no_license
|
# 引言
随着互联网的发展,人们在享受互联网带来的便捷的服务的时候,也面临着个人的隐私泄漏的问题。小到一个拥有用户系统的小型论坛,大到各个大型的银行机构,互联网安全问题都显得格外重要。而这些网站的背后,则是支撑整个服务的核心数据库。可以说数据库就是这些服务的命脉,没有数据库,也就无从谈起这些服务了。
对于数据库系统的安全特性,主要包括数据独立性、数据安全性、数据完整性、并发控制、故障恢复等方面。而这些里面显得比较重要的一个方面是数据的安全性。由于开发人员的设计不周到,以及数据库的某些缺陷,很容易让黑客发现系统的漏洞,从而造成巨大的损失。
接下来本文将会介绍非常常见的一种攻击数据库的方法:SQL注入,以及使用在项目使用Java开发的情况下如何使用SpringMVC的拦截器实现防止SQL注入的功能。
# SQL注入
## SQL注入简介
通俗的讲,SQL注入就是恶意黑客或者竞争对手利用现有的B/S或者C/S架构的系统,将恶意的SQL语句通过表单等传递给后台SQL数据库引擎执行。比如,一个黑客可以利用网站的漏洞,使用SQL注入的方式取得一个公司网站后台的所有数据。试想一下,如果开发人员不对用户传递过来的输入进行过滤处理,那么遇到恶意用户的时候,并且系统被发现有漏洞的时候,后果将是令人难以想象的。最糟糕的是攻击者拿到了数据库服务器最高级的权限,可以对整个数据库服务器的数据做任何操作。
通常情况下,SQL注入攻击一般分为以下几个步骤:
* 判断WEB环境是否可以注入SQL。对于一个传统的WEB网页来说,如果是一个简单的静态页面,比如地址为http://www.news.com/100.html的网页,这是一个简单的静态页面,一般不涉及对数据库的查询。而如果这个网页的网址变成了:http://www.news.com/news.asp?id=100 那么,这就是一个根据主键id来查询数据的动态网页了。攻击者往往能够在 id=100的后面加上一些自己的SQL,用来“欺骗”过应用程序。
* 寻找SQL注入点。当攻击者确定某个页面可以使用SQL注入之后,他一般会寻找可以SQL注入的点。而这些点往往就是网页或者应用程序中的用于向服务器发送用户数据的表单了。一般的流程是,客户端通过这些表单发送一些用户信息的字段,比如用户名和密码,接着服务器就会根据这些字段去查询数据库。而如果用户输入了一些非法的字符,比如’这个符号,那么在SQL解析的时候,解析的结果可能并不是应用开发人员想象中那样。
* 寻找系统的后台。这一点就建立在破坏者对整个系统的了解程度上面了,如果攻击者对整个系统了如指掌,那么实现攻击也就是一件很简单的事情了。
* 入侵和破坏。当攻击者攻破系统之后,整个系统从某种意义上来讲已经失去意义了。
## SQL注入案例
## 一个简单的PHP登录验证SQL注入
比如一个公司有一个用来管理客户的客户管理系统,在进入后台进行管理的时候需要输入用户名和密码。
假设在客户端传给服务器的字段分别为用户名username和密码password,那么如果用来处理登录的服务器端代码对用户的输入做以下处理:
![PHPsql注入][1]
上面的PHP代码就是首先获取客户端POST过来的填写在表单里面的用户名和密码,接着要MySQL去执行下面这条SQL语句:
```
SELECT `id` FROM `users` WHERE `username` = username AND `password` = password;
```
可以看到上面的代码没有对用户的输入做任何的过滤,这是非常容易遭到黑客攻击的。
比如,一个用户在输入用户名的输入框里面输入了
```
user’;SHOW TABLES;--
```
那么就会解析为下面的SQL:
```
SELECT `id` FROM `users` WHERE `username` = ‘user’;SHOW TABLES;-- AND `password` = password;
```
可以看到被解析的SQL被拆分为了2条有用的SQL:
```
(1)SELECT `id` FROM `users` WHERE `username` = ‘user’;
(2)SHOW TABLES;
```
而后面验证密码的部分就被注释掉了。这样攻击者就轻松的获得了这个数据库里面的所有表的名字。同样的道理,如果攻击者在输入框里面输入:
```
’;DROP TABLE [table_name];--
```
那么,这一张表就被删除了,可见后果是非常严重的。
而用户如果在用户名输入框里面输入了:user’or 1=1--
那么会被解析成:
```
SELECT `id` FROM `users` WHERE `username` = ‘user’
or 1=1-- AND `password` = password;
```
这里可以看到1=1永远为真,这样不用输入用户名就直接可以登入系统了。
## 一个ASP新闻动态页面的id查询
比如有一个新闻网站的动态页面是这种格式:
```
http://www.news.com/news.asp?id=100
```
那么当用户在浏览器的地址框里面输入
```
http://www.news.com/news.asp?id=100;and user>0
```
那么如果这个网站的数据库用的是SQL Server的话,那么SQL Server在解析的时候,由于user是SQL Server的一个内置变量,它的值就是当前连接数据库的用户,那么SQL在执行到这里的时候会拿一个类型为nvarchar的和一个int类型的比较。比较过程中就必然涉及类型的转化,然而不幸的是,转化过程并不是一帆风顺,出错的时候SQL Server将会给出类似将nvarchar值”aaa”转为为int的列时发生语法错误。这个时候攻击者就轻松的获得了数据库的用户名。
# SpringMVC拦截器防止SQL注入
为了有效的减少以及防止SQL注入的攻击,开发人员在开发的时候一定不要期待用户的输入都是合理的,当用户输入完毕之后,应该严谨的对用户提交的数据进行格式上的检查以及过滤,尽可能的减少被注入SQL 的风险。
一般来说,不同的服务器端语言都有不同的解决方案。比如拿中小型企业采用得最多的PHP语言来说,PHP的官方就为开发者提供了这样的一些函数,比如mysql_real_escape_string()等。
接下来会详细介绍如何通过SpringMVC的拦截器实现防止SQL注入的功能。
这里以我的大数据人才简历库的拦截器为例。
## 自定义拦截器类实现HandlerInterceptor接口
```
package com.data.job.util.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
/**
* 防止SQL注入的拦截器
*
* @author [email protected]
* @time 2/13/16 8:22 PM.
*/
public class SqlInjectInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String[] values = request.getParameterValues(name);
for (String value : values) {
value = clearXss(value);
}
}
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
}
/**
* 处理字符转义
*
* @param value
* @return
*/
private String clearXss(String value) {
if (value == null || "".equals(value)) {
return value;
}
value = value.replaceAll("<", "<").replaceAll(">", ">");
value = value.replaceAll("\\(", "(").replace("\\)", ")");
value = value.replaceAll("'", "'");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']",
"\"\"");
value = value.replace("script", "");
return value;
}
}
```
## 配置拦截器
```
<!-- 拦截器配置-->
<mvc:interceptors>
<!-- SQL注入拦截-->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.data.job.util.interceptor.SqlInjectInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
```
# SQL注入总结
安全问题从古至今都有着非常高的关注度,如今互联网高速发达,各种网络应用层出不穷。不管是现在炙手可热的云计算和大数据,还是传统的B/S或者C/S架构的网络应用,数据的安全性是至关重要的。从应用层面来讲,网络应用的开发者可以通过完善软件的架构,尽量减少因为BUG而导致的数据泄漏的问题。开发者可以不断的审视与完善自己的系统,站在攻击者的角度上去开发某些关键的安全性要求比较高的环节,如银行支付部分等,这样能够在一定程度上面减少SQL注入等应用层面攻击数据库的风险。
# 项目地址
[完整代码](https://github.com/noprom/bigdatatalentpool)托管在github。
[1]: http://img.mukewang.com/56fdb9a00001a8de08640168.png
[2]: http://img.mukewang.com/56de3e9e0001637614341394.png
[3]: http://img.mukewang.com/56de3eae0001481014321394.png
[4]: http://img.mukewang.com/56de3eb70001e57a14300750.png
[5]: http://img.mukewang.com/56de3ec1000104a514280750.png
[6]: http://img.mukewang.com/56de3ec90001140c14320750.png
[7]: http://img.mukewang.com/56de3ed10001584514320780.png
[8]: http://img.mukewang.com/56de3ee1000163c315540920.png
[9]: http://img.mukewang.com/56de3ee90001b0f508481170.png
[10]: http://img.mukewang.com/56de3ef40001844919321238.png
[11]: http://img.mukewang.com/56de3efe0001f75419321238.png
[12]: http://img.mukewang.com/56de3f170001987825601546.png
|
C++
|
UTF-8
| 311 | 2.59375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <boost/algorithm/cxx11/any_of.hpp>
#include <boost/bind.hpp>
struct g
{
bool a(const int& c)const {return c==5;}
};
std::array<g,100> cucc;
int main()
{
return boost::algorithm::any_of(cucc, boost::bind(&g::a, 5));
}
|
Shell
|
UTF-8
| 800 | 2.6875 | 3 |
[] |
no_license
|
#!/bin/bash
alias vi='vim'
alias g='git'
alias ed='emacs --daemon -nw'
alias e='emacsclient -t'
alias gopen='gnome-open'
alias mkdir='mkdir -p'
alias ...='../..'
alias cnpm='npm --registry=https://registry.npm.taobao.org \
--cache=$HOME/.npm/.cache/cnpm \
--disturl=https://npm.taobao.org/dist \
--userconfig=$HOME/.cnpmrc'
# alias docker-clean='docker rm $(docker ps -qa -f status=exited); docker rmi $(docker images -qa -f dangling=true)'
alias docker-clean='for i in `docker ps -qa -f status=exited`; do \
docker rm $i; \
echo "rm docker container $i"; \
done; \
for j in `docker images -qa -f dangling=true`; do \
docker rmi $j; \
echo "rm docker image $j"; \
done'
alias pidinfo='gdb -ex "set pagination 0" -ex "thread apply all bt" --batch -p'
|
Java
|
UTF-8
| 918 | 1.8125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.demo.common.model.base;
import com.jfinal.plugin.activerecord.IBean;
import com.jfinal.plugin.activerecord.Model;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseRoleResource<M extends BaseRoleResource<M>> extends Model<M> implements IBean {
public java.lang.Integer getRoleResourceId() {
return get("role_resource_id");
}
public void setRoleResourceId(java.lang.Integer roleResourceId) {
set("role_resource_id", roleResourceId);
}
public java.lang.Integer getRoleId() {
return get("role_id");
}
public void setRoleId(java.lang.Integer roleId) {
set("role_id", roleId);
}
public java.lang.Integer getResourceId() {
return get("resource_id");
}
public void setResourceId(java.lang.Integer resourceId) {
set("resource_id", resourceId);
}
}
|
Java
|
UTF-8
| 767 | 2.15625 | 2 |
[] |
no_license
|
package app_kvECS;
import shared.metadata.*;
import java.util.List;
import shared.messages.KVAdminMessage;
public interface INodeConnection {
/**
* Sends a list of nodes to kill to a node.
*/
public void sendKillMessage() throws Exception;
public boolean sendCloseMessage();
/**
* Tell a server tp delete its data
*/
public void sendDeleteData() throws Exception;
/**
* Sends a metadata set to a node.
*/
public void sendMetadata(MetaDataSet mds) throws Exception;
/**
* Sends a transfer request to a node.
*/
public KVAdminMessage sendTransferRequest(TransferRequest tr) throws Exception;
/**
* Returns the name of this node
*/
public String getNodeName();
}
|
Python
|
UTF-8
| 1,720 | 3.375 | 3 |
[] |
no_license
|
#http://suninjuly.github.io/selects1.html
#http://suninjuly.github.io/selects2.html
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
import math
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
link = "http://suninjuly.github.io/selects1.html"
try:
browser = webdriver.Chrome()
browser.get(link)
# browser.find_element_by_tag_name("select").click()
# browser.find_element_by_css_selector("option:nth-child(2)").click()
# time.sleep(1)
# browser.find_element_by_css_selector("option:nth-child(3)").click()
# time.sleep(1)
# browser.find_element_by_css_selector("option:nth-child(4)").click()
# browser.find_element_by_css_selector("[value='1']").click()
select = Select(browser.find_element_by_tag_name("select"))
# select.select_by_index(3) # ищем элемент с индексом 3 (нумирация с нуля)
select.select_by_value("1") # ищем элемент с текстом "1"
#Можно использовать еще два метода: select.select_by_visible_text("text") и select.select_by_index(index). Первый способ ищет элемент по видимому тексту, например, select.select_by_visible_text("Python") найдёт "Python" для нашего примера.
# button = browser.find_element_by_css_selector(".btn")
# button.click()
finally:
# успеваем скопировать код за 30 секунд
time.sleep(15)
# закрываем браузер после всех манипуляций
browser.quit()
# не забываем оставить пустую строку в конце файла
|
C#
|
UTF-8
| 1,002 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AnimationEffects
{
/// <summary>
/// Use this class to attach sound effects data to animations
/// Optional: randomize the pitch for the sounds
/// Domain: Editor, project-specific
/// </summary>
[System.Serializable]
public class SoundEffectData : System.Object
{
public AudioClip audioClip = null;
public float soundTriggerTime = 0f;
[Tooltip("should the sound pitch be randomized?")]
public bool useRandomPitch = false;
public const float volume = 1f;
//internal min and max pitch settings
private const float minPitch = 0f;
private const float maxPitch = 2f;
//set up some reasonable defaults
private const float defaultMinPitch = 0.7f;
private const float defaultMaxPitch = 1.4f;
public Vector2 randomPitch = new Vector2(defaultMinPitch, defaultMaxPitch);
}
}
|
Java
|
UTF-8
| 370 | 1.554688 | 2 |
[
"MIT"
] |
permissive
|
/**
*
*/
package br.com.swconsultoria.efd.icms.registros.bloco0;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author Samuel Oliveira
*
*/
@EqualsAndHashCode
@Getter
@Setter
public class Registro0220 {
private final String reg = "0220";
private String unid_conv;
private String fat_conv;
private String cod_barra;
}
|
Python
|
UTF-8
| 2,632 | 4.03125 | 4 |
[] |
no_license
|
# Leetcode 99. Recover Binary Search Tree
# Solution 1 Sort an almost sorted array where two elements are swapped
# Runtime: O(N)
# Memory Usage: O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
def inorder_traversal(node: TreeNode) -> List[int]:
if not root:
return []
return inorder_traversal(node.left) + [node.val] + inorder_traversal(node.right)
def find_two_swapped(nums: List[int]) -> (int, int):
n = len(nums)
x = y = -1
for i in range(n-1):
if nums[i+1] < nums[i]:
y = nums[i+1]
# first swap occurence
if x == -1:
x = nums[i]
# second swap occurence
else:
break
return x, y
def recover(root: TreeNode, count: int):
if r:
if r.val == x or r.val == y:
if r.val == x:
r.val = y
else:
r.val = x
count -= 1
if count == 0:
return
recover(r.left, count)
recover(r.right, count)
nums = inorder(root)
x, y = find_two_swapped(nums)
recover(root, 2)
# Solution 2: Iterative inorder traversal
# Runtime: O(1) best case, O(N) worst case
# Memory Usage: O(H) to keep the stack where H is the tree height
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
stack = [] # stack helps us keep the record of parent nodes that are larger than current node
x = y = pred = None # pred: previous number in the sorted array
while stack or root: # when traversing the tree either stack or root must not be null
while root:
stack.append(root)
root = root.left # visit left child first
# first swap occurence
if pred and root.val < pred.val
y = root
if x is None:
x = pred
# second swap occurence
else:
break
pred = root
root = root.right
# swap two values
x.val, y.val = y.val, x.val
|
Java
|
UTF-8
| 1,294 | 2.234375 | 2 |
[] |
no_license
|
package com.wissen.justhire.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the process_status database table.
*
*/
@Entity
@Table(name="process_status")
@NamedQuery(name="ProcessStatus.findAll", query="SELECT p FROM ProcessStatus p")
public class ProcessStatus implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="candidate_id")
private int candidateId;
@Column(name="round_id")
private int roundId;
@Enumerated(EnumType.STRING)
private StatusType status;
//bi-directional one-to-one association to Candidate
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="candidate_id")
private Candidate candidate;
public ProcessStatus() {
}
public int getCandidateId() {
return this.candidateId;
}
public void setCandidateId(int candidateId) {
this.candidateId = candidateId;
}
public int getRoundId() {
return this.roundId;
}
public void setRoundId(int roundId) {
this.roundId = roundId;
}
public StatusType getStatus() {
return this.status;
}
public void setStatus(StatusType status) {
this.status = status;
}
public Candidate getCandidate() {
return this.candidate;
}
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
}
}
|
Java
|
UTF-8
| 2,589 | 2.9375 | 3 |
[] |
no_license
|
package demos;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import communication.MyLog;
import models.IzhNeuron;
import startup.Constants;
public class OneNeuronDynamics {
/** log*/
MyLog mlog = new MyLog("neneuron", true);
/** duration of the experiment*/
int experimentTime = 300;
NetworkRunnable netThread;
IzhNeuron neuron;
/** spikes time series */
FileWriter membraneWriter;
int iter = 0;
public void run(){
neuron = new IzhNeuron();
neuron.setNeuronType(Constants.NeurInhibitory);
//get date
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
Date date = new Date();
String strDate = dateFormat.format(date);
String folderName = Constants.DataPath + "/" + strDate + "/";
//create directory
File theDir = new File(folderName);
// if the directory does not exist, create it
if (!theDir.exists()) {
mlog.say("creating directory: " + folderName);
boolean result = false;
try{
theDir.mkdir();
result = true;
}
catch(SecurityException se){
//handle it
}
if(result) {
System.out.println("DIR created");
}
}
try {
membraneWriter = new FileWriter(folderName+"/"+Constants.SpikesFileName);
mlog.say("stream opened "+Constants.SpikesFileName);
String str = "iteration,V\n";
membraneWriter.append(str);
membraneWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
netThread = new NetworkRunnable();
new Thread(netThread).run();
}
private void updateNeuron() {
double in = 4;//.1;
neuron.addToI(in);
neuron.update();
neuron.checkFiring();
double v = neuron.getV();
neuron.setI(0);
try {
String str = iter+","+v+"\n";
membraneWriter.append(str);
membraneWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class NetworkRunnable implements Runnable{
boolean run = true;
MyLog mlog = new MyLog("networkRunnable",true);
public void kill(){
run = false;
}
//@Override
public void run() {
while(run){
updateNeuron();
iter++;
if(iter>=experimentTime){
mlog.say("end of experiment at t="+iter);
kill();
}
}
try {
membraneWriter.flush();
membraneWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
Java
|
UTF-8
| 1,202 | 2.296875 | 2 |
[] |
no_license
|
package br.ufjf.dcc196.trb2.arthur_e_gustavo.adapters;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import br.ufjf.dcc196.trb2.arthur_e_gustavo.R;
import br.ufjf.dcc196.trb2.arthur_e_gustavo.helpers.AppContract;
import br.ufjf.dcc196.trb2.arthur_e_gustavo.helpers.AppDbHelper;
public class ParticipantAdapter extends CursorAdapter {
private AppDbHelper appHelper;
public ParticipantAdapter(Context context, Cursor c) {
super(context, c);
appHelper = new AppDbHelper(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.participant_view, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textTitle = view.findViewById(R.id.participant_view_txtName);
String title = cursor.getString(cursor.getColumnIndexOrThrow(AppContract.Participant.COLUMN_NAME_NAME));
textTitle.setText(title);
}
}
|
Java
|
UTF-8
| 2,005 | 2.4375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.gbif.pipelines.transforms.core;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.gbif.pipelines.io.avro.LocationRecord;
import org.gbif.pipelines.io.avro.json.LocationInheritedRecord;
import org.junit.Test;
/** Tests for LocationInheritedFieldsFn. */
public class LocationInheritedFieldsFnTest {
@Test
public void testAcc() {
// Creates the combine function
LocationInheritedFieldsFn locationInheritedFieldsFn = new LocationInheritedFieldsFn();
// Accumulates 2 records in one accumulator
LocationInheritedFieldsFn.Accum accum1 = locationInheritedFieldsFn.createAccumulator();
locationInheritedFieldsFn.addInput(
accum1,
LocationRecord.newBuilder()
.setId("1")
.setHasCoordinate(true)
.setDecimalLatitude(0.0d)
.setDecimalLongitude(90.0d)
.build());
locationInheritedFieldsFn.addInput(
accum1,
LocationRecord.newBuilder()
.setId("2")
.setParentId("1")
.setHasCoordinate(true)
.setDecimalLatitude(1.0d)
.setDecimalLongitude(91.0d)
.build());
// Accumulates one leaf record in a different accumulator
LocationInheritedFieldsFn.Accum accum2 = locationInheritedFieldsFn.createAccumulator();
locationInheritedFieldsFn.addInput(
accum2, LocationRecord.newBuilder().setId("3").setParentId("2").build());
// Merge accumulators
LocationInheritedFieldsFn.Accum mergedAccum =
locationInheritedFieldsFn.mergeAccumulators(Arrays.asList(accum1, accum2));
// Get the results
LocationInheritedRecord locationInheritedRecord =
locationInheritedFieldsFn.extractOutput(mergedAccum);
// Results are gotten from the immediate parent of the leaf record
assertEquals(new Double(1.0d), locationInheritedRecord.getDecimalLatitude());
assertEquals(new Double(91.0d), locationInheritedRecord.getDecimalLongitude());
}
}
|
Java
|
UTF-8
| 5,240 | 1.828125 | 2 |
[] |
no_license
|
package shopandclient.ssf.com.shopandclient.ui;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.jaeger.library.StatusBarUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import shopandclient.ssf.com.shopandclient.R;
import shopandclient.ssf.com.shopandclient.adapter.MyGroupAdapter;
import shopandclient.ssf.com.shopandclient.base.BaseActivity;
import shopandclient.ssf.com.shopandclient.base.Constants;
import shopandclient.ssf.com.shopandclient.base.MyApplication;
import shopandclient.ssf.com.shopandclient.entity.MyGroupBean;
import shopandclient.ssf.com.shopandclient.im.Constant;
import shopandclient.ssf.com.shopandclient.im.ui.ChatActivity;
import shopandclient.ssf.com.shopandclient.net.RetrofitHandle;
import shopandclient.ssf.com.shopandclient.net.services.ChatCenterService;
import shopandclient.ssf.com.shopandclient.util.Observer;
import shopandclient.ssf.com.shopandclient.util.SpConfig;
import shopandclient.ssf.com.shopandclient.util.Subject;
import shopandclient.ssf.com.shopandclient.util.TokenManager;
import java.util.ArrayList;
import java.util.List;
public class MyGroupActivity extends BaseActivity implements AdapterView.OnItemClickListener, Observer {
@BindView(R.id.rl_btn_back)
RelativeLayout rlBtnBack;
@BindView(R.id.tv_center_title)
TextView tvCenterTitle;
@BindView(R.id.rl_btn_scope)
RelativeLayout rlBtnScope;
@BindView(R.id.rl_action)
RelativeLayout rlAction;
@BindView(R.id.lv_friends_list)
ListView lvFriendsList;
@BindView(R.id.iv_back)
ImageView ivBack;
ArrayList<MyGroupBean.DataBean> arrayList;
private MyGroupAdapter mga;
private List<EMGroup> grouplist;
private TokenManager tokenManager;
@Override
public int getLayoutResourceId() {
return R.layout.activity_my_group;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
tokenManager = TokenManager.newInstance();
tokenManager.registerObserver(this);
ButterKnife.bind(this);
StatusBarUtil.setColor(this, MyApplication.getInstance().mContext.getResources().getColor(R.color.password_tips), 0);
}
@Override
public void update(Subject subject) {
SpConfig.getInstance().putBool(Constants.ISLOGIN, false);
}
@Override
protected void initView() {
super.initView();
rlAction.setBackgroundColor(MyApplication.getInstance().mContext.getResources().getColor(R.color.password_tips));
ivBack.setBackgroundDrawable(MyApplication.getInstance().mContext.getResources().getDrawable(R.drawable.black));
tvCenterTitle.setText(MyApplication.getInstance().mContext.getResources().getString(R.string.my_group));
tvCenterTitle.setTextColor(MyApplication.getInstance().mContext.getResources().getColor(R.color.white));
rlBtnScope.setVisibility(View.INVISIBLE);
lvFriendsList.setOnItemClickListener(this);
getMyGroupData();
grouplist = EMClient.getInstance().groupManager().getAllGroups();
}
private void getMyGroupData() {
ChatCenterService service = RetrofitHandle.getInstance().retrofit.create(ChatCenterService.class);
Call<MyGroupBean> call = service.getMyGroup();
call.enqueue(new Callback<MyGroupBean>() {
@Override
public void onResponse(Call<MyGroupBean> call, Response<MyGroupBean> response) {
if (response.body().getCode() == 200) {
arrayList = response.body().getData();
mga = new MyGroupAdapter(MyGroupActivity.this, arrayList);
lvFriendsList.setAdapter(mga);
}
}
@Override
public void onFailure(Call<MyGroupBean> call, Throwable t) {
}
});
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* Bundle bundle=new Bundle();
bundle.putInt("groupId",arrayList.get(position).getGroupID());
bundle.putInt("groupAdminID",arrayList.get(position).getGroupAdminID());
openActivity(ManagerGroupActivity.class,bundle);*/
// enter group chat
Intent intent = new Intent(MyGroupActivity.this, ChatActivity.class);
// it is group chat
intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
intent.putExtra("groupName",arrayList.get(position).getGroupName());
intent.putExtra("userId",grouplist.get(position).getGroupId());
intent.putExtra("groupId",arrayList.get(position).getGroupID());
intent.putExtra("groupAdminID",arrayList.get(position).getGroupAdminID());
startActivityForResult(intent, 0);
}
@OnClick(R.id.rl_btn_back)
public void onViewClicked() {
finish();
}
@Override
protected void onResume() {
super.onResume();
getMyGroupData();
}
}
|
Java
|
UTF-8
| 549 | 1.953125 | 2 |
[] |
no_license
|
package com.microservicelibrairie.dao;
import com.microservicelibrairie.entities.Librairie;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface LibrairieRepository extends JpaRepository<Librairie,Long> {
List<Librairie>findByGenre_Genre(String genre);
Page<Librairie>findByAuteurContainingIgnoreCaseAndTitreContainingIgnoreCase(String motClefAuteur, String motClefTitre,Pageable pageable);
}
|
Java
|
UTF-8
| 5,597 | 2.265625 | 2 |
[] |
no_license
|
package com.bullshit.endpoint.entity;
public class Hospital {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hospital.hospital_id
*
* @mbggenerated
*/
private String hospitalId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hospital.hospital_tel
*
* @mbggenerated
*/
private String hospitalTel;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hospital.hospital_province
*
* @mbggenerated
*/
private String hospitalProvince;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hospital.hospital_name
*
* @mbggenerated
*/
private String hospitalName;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hospital.hospital_type
*
* @mbggenerated
*/
private String hospitalType;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column hospital.hospital_address
*
* @mbggenerated
*/
private String hospitalAddress;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hospital.hospital_id
*
* @return the value of hospital.hospital_id
*
* @mbggenerated
*/
public String getHospitalId() {
return hospitalId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hospital.hospital_id
*
* @param hospitalId the value for hospital.hospital_id
*
* @mbggenerated
*/
public void setHospitalId(String hospitalId) {
this.hospitalId = hospitalId == null ? null : hospitalId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hospital.hospital_tel
*
* @return the value of hospital.hospital_tel
*
* @mbggenerated
*/
public String getHospitalTel() {
return hospitalTel;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hospital.hospital_tel
*
* @param hospitalTel the value for hospital.hospital_tel
*
* @mbggenerated
*/
public void setHospitalTel(String hospitalTel) {
this.hospitalTel = hospitalTel == null ? null : hospitalTel.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hospital.hospital_province
*
* @return the value of hospital.hospital_province
*
* @mbggenerated
*/
public String getHospitalProvince() {
return hospitalProvince;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hospital.hospital_province
*
* @param hospitalProvince the value for hospital.hospital_province
*
* @mbggenerated
*/
public void setHospitalProvince(String hospitalProvince) {
this.hospitalProvince = hospitalProvince == null ? null : hospitalProvince.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hospital.hospital_name
*
* @return the value of hospital.hospital_name
*
* @mbggenerated
*/
public String getHospitalName() {
return hospitalName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hospital.hospital_name
*
* @param hospitalName the value for hospital.hospital_name
*
* @mbggenerated
*/
public void setHospitalName(String hospitalName) {
this.hospitalName = hospitalName == null ? null : hospitalName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hospital.hospital_type
*
* @return the value of hospital.hospital_type
*
* @mbggenerated
*/
public String getHospitalType() {
return hospitalType;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hospital.hospital_type
*
* @param hospitalType the value for hospital.hospital_type
*
* @mbggenerated
*/
public void setHospitalType(String hospitalType) {
this.hospitalType = hospitalType == null ? null : hospitalType.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column hospital.hospital_address
*
* @return the value of hospital.hospital_address
*
* @mbggenerated
*/
public String getHospitalAddress() {
return hospitalAddress;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column hospital.hospital_address
*
* @param hospitalAddress the value for hospital.hospital_address
*
* @mbggenerated
*/
public void setHospitalAddress(String hospitalAddress) {
this.hospitalAddress = hospitalAddress == null ? null : hospitalAddress.trim();
}
}
|
Ruby
|
UTF-8
| 362 | 3.234375 | 3 |
[] |
no_license
|
class Destination
attr_reader :station_name, :fuel_type, :access_days_time, :address
def initialize(station)
@station_name = station[:station_name]
@fuel_type = station[:fuel_type_code]
@access_days_time = station[:access_days_time]
@address = "#{station[:street_address]}, #{station[:city]}, #{station[:state]} #{station[:zip]}"
end
end
|
Java
|
UTF-8
| 1,570 | 3.125 | 3 |
[] |
no_license
|
package com.CRUD;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.etity.Employee;
import java.util.Scanner;
public class ReadObject {
//Delete the object
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 1- Create a factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Employee.class).
buildSessionFactory();
// 2 - create Session
Session theSession = factory.getCurrentSession();
try {
System.out.print("Enter the Employee ID you want to read: ");
int empID = input.nextInt();
Session theSession2nd = factory.getCurrentSession();
theSession2nd.beginTransaction();
System.out.println(theSession2nd.get(Employee.class, empID));
Employee readEmp = theSession2nd.get(Employee.class, empID);
if (readEmp == null) {
System.out.println("The Employee does not exist");
}
else {
System.out.println(readEmp); // print the object
System.out.println("================================");
System.out.println("ID: "+readEmp.getId());
System.out.println("First Name: "+readEmp.getFirstName());
System.out.println("Last Name: "+readEmp.getLastName());
System.out.println("Course: "+readEmp.getCourse());
System.out.println("Email: "+readEmp.getEmail());
theSession2nd.getTransaction().commit();
}
} catch (Exception e) {
}
finally {
theSession.close();
}
}
}
|
Python
|
UTF-8
| 1,359 | 2.671875 | 3 |
[] |
no_license
|
import casadi as cd
import pandas as pd
import numpy as np
def gen_t(pts1, pts2):
tpts = [0]
for i, pt in enumerate(pts1):
if i != 0:
dist_tmp = (pts1[i] - pts1[i-1]) ** 2 + (pts2[i] - pts2[i-1]) ** 2
tpts += [cd.sqrt(dist_tmp) + tpts[-1]]
maxt = tpts[-1]
tpts = [t/maxt for t in tpts]
return tpts
def get_curve(curve, prev=None):
xpts, ypts = curve['xpts'], curve['ypts']
order = curve['order']
if prev is not None:
init_ts = prev
else:
init_ts = curve['init_ts']
xs, ys = xpts[0], ypts[0]
xf, yf = xpts[-1], ypts[-1]
tpts = gen_t(xpts, ypts)
xpoly = np.polynomial.polynomial.Polynomial.fit(tpts, xpts, order)
ypoly = np.polynomial.polynomial.Polynomial.fit(tpts, ypts, order)
cx = xpoly.convert().coef[::-1]
cy = ypoly.convert().coef[::-1]
return xs, ys, xf, yf, init_ts, xpts, ypts, tpts, xpoly, ypoly, cx, cy, order
def compute_step(init, ts, D): # init = [x, y, phi, delta, vx, theta, aux, alphaux, dt]
x, y, phi, delta, v, theta, a, alpha, dt = init
x_ts = x + v*np.cos(phi)*ts
y_ts = y + v*np.sin(phi)*ts
phi_ts = phi + (v/D)*np.tan(delta)*ts
delta_ts = delta + alpha*ts
v_ts = v + a*ts
theta_ts = theta + v*dt*ts
return np.array([x_ts, y_ts, phi_ts, delta_ts, v_ts, theta_ts])
|
Java
|
UTF-8
| 554 | 1.84375 | 2 |
[] |
no_license
|
package com.nnlightctl.server;
import com.nnlight.common.Tuple;
import com.nnlightctl.request.BaseRequest;
import com.nnlightctl.request.SystemParamRequest;
import com.nnlightctl.po.SystemParam;
import java.util.List;
public interface SystemParamServer {
int addOrUpdateSystemParam( SystemParamRequest request);
SystemParam getDepartment(Long id);
List<SystemParam> getSystemParamByCode(String codeNumber);
Tuple.TwoTuple<List<SystemParam>, Integer> listSystemParam(BaseRequest request);
int deleteSystemParam(List<Long> systemParamIds);
}
|
Python
|
UTF-8
| 579 | 3.125 | 3 |
[] |
no_license
|
class Category:
def __init__(self, amount, label):
self._amount = amount
self._label = label
def __str__(self):
return str(self._amount) + ', ' + self._label
def __repr__(self):
return str(self)
def get_label(self):
return self._label
class Expense(Category):
def __init__(self, amount, label):
super().__init__(amount, label)
self.STR = 'New Expense'
class Income(Category):
def __init__(self, amount, label):
super().__init__(amount, label)
self.STR = 'New Expense'
|
C#
|
UTF-8
| 12,937 | 2.71875 | 3 |
[] |
no_license
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Collections.Generic;
namespace CurrencyJob
{
class Program
{
private static string BaseURL = "https://openexchangerates.org/api/latest.json";
static void Main(string[] args)
{
var CurrencyMapper = GetCurrencyMapper();
var JsonData = GetCurrencies().Result;
var CurrencyPriceData = JsonConvert.DeserializeObject<CurrencyPriceData>(JsonData);
var thing = RunDbQuery(CurrencyPriceData,CurrencyMapper).Result;
}
public static async Task<string> GetCurrencies()
{
HttpClient Client = new HttpClient();
string RawJson = null;
Client.BaseAddress = new Uri(BaseURL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Response = Client.GetAsync(UrlParameter).Result;
if (Response.IsSuccessStatusCode)
{
RawJson = Response.Content.ReadAsStringAsync().Result;
Console.WriteLine("API call successful");
}
else
{
Console.WriteLine("Job failed to call API");
}
return RawJson;
}
public static async Task<string> RunDbQuery(CurrencyPriceData CurrencyPrices,Dictionary<int,string> CurrencyMapper)
{
bool Checked = false;
int CurrencyId;
double OldPrice;
Dictionary<int, double> CurrencyPriceDict = new Dictionary<int, double>();
var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0);
dt = dt.AddSeconds(CurrencyPrices.timestamp);
var Date = dt.ToString("yyyy-MM-dd H:mm:ss");
SqlConnection Conn = new SqlConnection(ConnectionString);
Conn.Open();
var CurrencyDict = new Dictionary<string, string>();
using (var command = Conn.CreateCommand())
{
command.CommandText = "SELECT top 168 * FROM CurrencyPrice ORDER BY Timestamp DESC;";
SqlDataReader Reader = await command.ExecuteReaderAsync();
while (Reader.Read())
{
string LastTimestamp = Reader.GetValue(4).ToString();
Console.WriteLine("Month: " + LastTimestamp.Split('/')[0]);
Console.WriteLine("Day: "+ LastTimestamp.Split('/')[1]);
Console.WriteLine("Year: " + LastTimestamp.Split(' ')[0].Split('/')[2]);
Console.WriteLine("Hour: " + LastTimestamp.Split(' ')[1].Split(':')[0]);
int Month = int.Parse(LastTimestamp.Split('/')[0]);
int Day = int.Parse(LastTimestamp.Split('/')[1]);
int Year = int.Parse(LastTimestamp.Split(' ')[0].Split('/')[2]);
int Hour = int.Parse(LastTimestamp.Split(' ')[1].Split(':')[0]);
DateTime LastTime = new DateTime(Year,Month,Day);
LastTime.AddHours(Hour);
Console.WriteLine(LastTime.ToString());
if (!Checked&&LastTime.AddHours(1)>dt.AddMinutes(10))
{
Console.WriteLine("Already ran job within the last hour, last job was run at: " + LastTime.ToString());
return null;
}
else if (!Checked)
{
Console.WriteLine("Job is good to run, last run at: " + LastTime.ToString());
}
Checked = true;
CurrencyPriceDict.Add(int.Parse(Reader.GetValue(2).ToString()),double.Parse(Reader.GetValue(3).ToString()));
}
Reader.Close();
}
foreach (var entry in CurrencyPriceDict)
{
//need to make sure this doesnt run more than once an hour
CurrencyId = entry.Key;
OldPrice = entry.Value;
CurrencyMapper.TryGetValue(CurrencyId, out string CurrencyCode);
CurrencyPrices.rates.TryGetValue(CurrencyCode, out double NewPrice);
NewPrice = 1 / NewPrice;
var Change = Math.Round((((( NewPrice) - OldPrice) / OldPrice) * 100), 2);
Console.WriteLine("CurrencyID: " + CurrencyId);
Console.WriteLine("OldPrice: " + OldPrice);
Console.WriteLine("NewPrice: " + NewPrice);
Console.WriteLine("Change: " + Change);
Console.WriteLine("INSERT INTO CurrencyPrice VALUES(" + Change + ","
+ 999 + ","
+ (NewPrice) + ","
+ dt + ")");
string CommandText = "INSERT INTO CurrencyPrice VALUES(" + Change + ", "
+ CurrencyId + ","
+ NewPrice + ","
+ "@1)";
var command = Conn.CreateCommand();
command.Parameters.AddWithValue("@1",dt);
command.CommandText = CommandText;
SqlDataReader Reader = await command.ExecuteReaderAsync();
Reader.Close();
}
return null;
}
public static Dictionary<int,string> GetCurrencyMapper()
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "AED");
dictionary.Add(2, "OMR");
dictionary.Add(3, "PAB");
dictionary.Add(4, "PEN");
dictionary.Add(5, "PGK");
dictionary.Add(6, "PHP");
dictionary.Add(7, "PKR");
dictionary.Add(8, "PLN");
dictionary.Add(9, "PYG");
dictionary.Add(10, "RON");
dictionary.Add(11, "NZD");
dictionary.Add(12, "RSD");
dictionary.Add(13, "RUB");
dictionary.Add(14, "RWF");
dictionary.Add(15, "SAR");
dictionary.Add(16, "SBD");
dictionary.Add(17, "SCR");
dictionary.Add(18, "SDG");
dictionary.Add(19, "QAR");
dictionary.Add(20, "NPR");
dictionary.Add(21, "NOK");
dictionary.Add(22, "NIO");
dictionary.Add(23, "LYD");
dictionary.Add(24, "MAD");
dictionary.Add(25, "MDL");
dictionary.Add(26, "MGA");
dictionary.Add(27, "MKD");
dictionary.Add(28, "MMK");
dictionary.Add(29, "MNT");
dictionary.Add(30, "MOP");
dictionary.Add(31, "MRO");
dictionary.Add(32, "MUR");
dictionary.Add(33, "MVR");
dictionary.Add(34, "MWK");
dictionary.Add(35, "MXN");
dictionary.Add(36, "MYR");
dictionary.Add(37, "MZN");
dictionary.Add(38, "NAD");
dictionary.Add(39, "NGN");
dictionary.Add(40, "SEK");
dictionary.Add(41, "SGD");
dictionary.Add(42, "SHP");
dictionary.Add(43, "SLL");
dictionary.Add(44, "VEF");
dictionary.Add(45, "VND");
dictionary.Add(46, "VUV");
dictionary.Add(47, "WST");
dictionary.Add(48, "XAF");
dictionary.Add(49, "XAG");
dictionary.Add(50, "XAU");
dictionary.Add(51, "XCD");
dictionary.Add(52, "XDR");
dictionary.Add(53, "XOF");
dictionary.Add(54, "XPD");
dictionary.Add(55, "XPF");
dictionary.Add(56, "XPT");
dictionary.Add(57, "YER");
dictionary.Add(58, "ZAR");
dictionary.Add(59, "ZMW");
dictionary.Add(60, "ZWL");
dictionary.Add(61, "UZS");
dictionary.Add(62, "LSL");
dictionary.Add(63, "UYU");
dictionary.Add(64, "UGX");
dictionary.Add(65, "SOS");
dictionary.Add(66, "SRD");
dictionary.Add(67, "SSP");
dictionary.Add(68, "STD");
dictionary.Add(69, "SVC");
dictionary.Add(70, "SYP");
dictionary.Add(71, "SZL");
dictionary.Add(72, "THB");
dictionary.Add(73, "TJS");
dictionary.Add(74, "TMT");
dictionary.Add(75, "TND");
dictionary.Add(76, "TOP");
dictionary.Add(77, "TRY");
dictionary.Add(78, "TTD");
dictionary.Add(79, "TWD");
dictionary.Add(80, "TZS");
dictionary.Add(81, "UAH");
dictionary.Add(82, "USD");
dictionary.Add(83, "LRD");
dictionary.Add(84, "LKR");
dictionary.Add(85, "LBP");
dictionary.Add(86, "BWP");
dictionary.Add(87, "BYN");
dictionary.Add(88, "BZD");
dictionary.Add(89, "CAD");
dictionary.Add(90, "CDF");
dictionary.Add(91, "CHF");
dictionary.Add(92, "CLF");
dictionary.Add(93, "CLP");
dictionary.Add(94, "CNH");
dictionary.Add(95, "CNY");
dictionary.Add(96, "COP");
dictionary.Add(97, "CRC");
dictionary.Add(98, "CUC");
dictionary.Add(99, "CUP");
dictionary.Add(100, "CVE");
dictionary.Add(101, "CZK");
dictionary.Add(102, "DJF");
dictionary.Add(103, "BTN");
dictionary.Add(104, "BTC");
dictionary.Add(105, "BSD");
dictionary.Add(106, "BRL");
dictionary.Add(107, "AFN");
dictionary.Add(108, "ALL");
dictionary.Add(109, "AMD");
dictionary.Add(110, "ANG");
dictionary.Add(111, "AOA");
dictionary.Add(112, "ARS");
dictionary.Add(113, "AUD");
dictionary.Add(114, "AWG");
dictionary.Add(115, "DKK");
dictionary.Add(116, "AZN");
dictionary.Add(117, "BBD");
dictionary.Add(118, "BDT");
dictionary.Add(119, "BGN");
dictionary.Add(120, "BHD");
dictionary.Add(121, "BIF");
dictionary.Add(122, "BMD");
dictionary.Add(123, "BND");
dictionary.Add(124, "BOB");
dictionary.Add(125, "BAM");
dictionary.Add(126, "DOP");
dictionary.Add(127, "DZD");
dictionary.Add(128, "EGP");
dictionary.Add(129, "IQD");
dictionary.Add(130, "IRR");
dictionary.Add(131, "ISK");
dictionary.Add(132, "JEP");
dictionary.Add(133, "JMD");
dictionary.Add(134, "JOD");
dictionary.Add(135, "JPY");
dictionary.Add(136, "KES");
dictionary.Add(137, "KGS");
dictionary.Add(138, "KHR");
dictionary.Add(139, "KMF");
dictionary.Add(140, "KPW");
dictionary.Add(141, "KRW");
dictionary.Add(142, "KWD");
dictionary.Add(143, "KYD");
dictionary.Add(144, "KZT");
dictionary.Add(145, "LAK");
dictionary.Add(146, "INR");
dictionary.Add(147, "IMP");
dictionary.Add(148, "ILS");
dictionary.Add(149, "GIP");
dictionary.Add(150, "EUR");
dictionary.Add(151, "FJD");
dictionary.Add(152, "FKP");
dictionary.Add(153, "GBP");
dictionary.Add(154, "GEL");
dictionary.Add(155, "GGP");
dictionary.Add(156, "GHS");
dictionary.Add(157, "IDR");
dictionary.Add(158, "GMD");
dictionary.Add(159, "GNF");
dictionary.Add(160, "GTQ");
dictionary.Add(161, "GYD");
dictionary.Add(162, "HKD");
dictionary.Add(163, "HNL");
dictionary.Add(164, "HRK");
dictionary.Add(165, "HTG");
dictionary.Add(166, "HUF");
dictionary.Add(167, "ETB");
dictionary.Add(168, "ERN");
return dictionary;
}
}
public class CurrencyPrice
{
public int CurrencyPriceId { get; set; }
public int CurrencyId { get; set; }
public double Price { get; set; }
public DateTime TimeStamp { get; set; }
public double ChangePercentage { get; set; }
}
public class CurrencyPriceData
{
public string disclaimer { get; set; }
public string license { get; set; }
public int timestamp { get; set; }
public string Base { get; set; }
public Dictionary<string, double> rates { get; set; }
}
}
|
Java
|
UTF-8
| 426 | 2.140625 | 2 |
[] |
no_license
|
/*
* Creator: Calvin Liu
*/
package me.calvinliu.scoreboard.integration;
/**
* Http Result for testing
*/
public class HttpResult {
private String response;
private int code;
public HttpResult(String response, int code) {
this.response = response;
this.code = code;
}
public String getResponse() {
return response;
}
public int getCode() {
return code;
}
}
|
C#
|
UTF-8
| 1,866 | 3.34375 | 3 |
[] |
no_license
|
using System;
namespace _03._Santas_Holiday
{
class Program
{
static void Main(string[] args)
{
int numOfDays = int.Parse(Console.ReadLine());
string typeOfRoom = Console.ReadLine();
string feedback = Console.ReadLine();
double pricePerNight = 0;
double discount = 0;
switch (typeOfRoom)
{
case "room for one person": pricePerNight = 18; break;
case "apartment":
pricePerNight = 25;
if (numOfDays < 10)
{
discount = 0.30;
}
else if (numOfDays >= 10 && numOfDays <= 15)
{
discount = 0.35;
}
else if (numOfDays > 15)
{
discount = 0.50;
}
break;
case "president apartment":
pricePerNight = 35;
if (numOfDays < 10)
{
discount = 0.10;
}
else if (numOfDays >= 10 && numOfDays <= 15)
{
discount = 0.15;
}
else if (numOfDays > 15)
{
discount = 0.20;
}
break;
}
double total = pricePerNight * (numOfDays - 1);
total -= total * discount;
if (feedback == "positive")
{
total += total * 0.25;
}
else
{
total -= total * 0.10;
}
Console.WriteLine($"{total:F2}");
}
}
}
|
Python
|
UTF-8
| 163 | 2.796875 | 3 |
[] |
no_license
|
def answer(x):
distinct = set()
for s in x:
if s not in distinct and s[::-1] not in distinct:
distinct.add(s)
return len(distinct)
|
C#
|
UTF-8
| 5,879 | 3.640625 | 4 |
[] |
no_license
|
using System;
namespace _03_Types
{
class Program
{
static void Main(string[] args)
{
// tuples
(int, int) t1 = (1, 2);
t1.Item1 = 10;
var t21 = (1, 2);
t21.Item2 = 20;
var t22 = (1, "abc");
t22.Item2 = "xyz";
(int no1, int no2) t3 = (1, 2);
(int no1, int no2) t4 = (no1: 1, no2: 2);
t3.no1 = 10;
t1 = t4;
// arrays
// they are objects of types derived from System.Array abstract class
// size is fixed!
int[] a1 = new int[3]; // 1 dimensional array declared
int[] a11 = new int[] { 1, 2, 3 }; // no need for 3 since it's initialized
int[] a111 = { 1, 2, 3 }; // actually new int[] can also be ommitted
int[,] a21; // 2 dimensinal array declared
a21 = new int[1, 2]; // 1 x 2 array is defined but not initialized
// Array declarations examples without initialization
int[] tab1; // single-dimensional array
// of int type elements
int[,] tab2; // two-dimensional array
// of int type elements
int[][] tab3; // single-dimensional array, whose
// elements are single-dimensional arrays
// of int type elements
int[,][][,,] tab4; // two-dimensional array, whose
// elements are single-dimensional arrays,
// whose elements are 3-dimensional arrays
// of int type elements
// Array declarations examples
// with initialization by new operator
int[] tab11 = new int[5];
int[,] tab21 = new int[4, 2];
int[][] tab31 = new int[5][];
// then each element is initialized seperately:
tab31[1] = new int[5];
tab31[2] = new int[2];
int[,][][,,] tab41 = new int[3, 4][][,,];
// then each element is initialized seperately:
tab41[2, 1] = new int[5][,,];
// then each element is again initialized seperately:
tab41[2, 1][3] = new int[7, 8, 9];
// simpler to use var
var tab411 = new int[3, 4][][,,];
// these give error because they elements cannot be initialized at bulk like this:
// int[][] tab31a = new int[5][4]; // error
// int[,][][,,] tab41a = new int[3, 4][5][6, 7, 8]; // error
// int[][] tab31b = new int[][4]; // error
// int[,][][,,] tab41b = new int[3,][][,,]; // error
// Array declarations examples with array initializator {}
int[] tab12 = { 1, 2, 3, 4, 5 };
// creates 5-element array
int[,] tab22 = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
// create 3-row, 2-column array
int[][] tab32 = { new int[10], new int[20] };
// create 2-element array of arrays
// tab32[0] is 10-element array
// tab32[1] is 20-element array
int[,][][,,] tab42 = { { new int[2][,,], new int[4][,,] } , { new int[3][,,], new int[5][,,] } };
// create 2-element array of arrays
// int[][] tab52 = { { 1, 2 }, { 3, 4 } };
// error - nested array must be created
// using new operator
// (because tab5 is array of arrays)
// array of reference type can contain elements of different types (e.g. those derived from the reference type)
object[] tab = { 1, 2.5, "text", null, 1u, 2L };
// Array declarations examples with implicit elements types
// single-dimensional array
var tab1x = new int[5]; // int[] tab1x = new int[5];
// two-dimensional array
var tab2x = new int[4, 2]; // int[,] tab2x = new int[4,2];
// arrays of arrays
var tab3x = new int[5][]; // int[][] tab3x = new int[5][];
// declarations with initialization
// - elements types can be omitted too!
var tab4x = new[] { 1, 2, 3 }; //int[] tab4x = new int [] { 1, 2, 3 };
// elements must be of the same type
var tab5x = new[] { new[] { 1, 2 }, new[] { 3, 4 } };
//int[][] tab5x = new int[2][] { new int[2] { 1, 2 }, new int[2] { 3, 4 } };
var tab1xx = new[] { 1, 2, 3, 4, 5 };
var tab2xx = new[] { 1, 2, 3, 4, 5 };
var t1xx = new int[5];
var t2xx = new int[5];
t1xx = tab1xx; // references tab1xx and t1xx refer to
// the same array
t2xx = tab2xx[..]; // references tab2xx and t2xx refer to two
// separate arrays with the same elements,
// t2xx is a shallow copy of tab2xx
int[,] a; // it will be one object
a = new int[5, 5];
for (int i = 0; i < a.GetLength(0); ++i) // GetLength() method returns the length of the given dimension
for (int j = 0; j < a.GetLength(1); ++j)
a[i, j] = i + j;
int[][] b; // it will be many objects
b = new int[5][];
for (int i = 0; i < b.Length; ++i) // Length property gives the length of the array
{
b[i] = new int[5];
for (int j = 0; j < b[i].Length; ++j)
b[i][j] = i + j;
}
}
}
}
|
JavaScript
|
UTF-8
| 1,471 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
$(document).ready(function() {
$(".profile").submit(function(event){
event.preventDefault();
var countryInput = $ ("input:radio[name=country]:checked").val();
var spotInput = $("input:radio[name=spot]:checked").val();
var ageInput = $("#age").val();
var daysInput = $("#days").val();
var companyInput = $("#company").val();
var lastPlacesInput = $("#lastPlaces").val();
var bestPlacesInput = $("#bestPlaces").val();
console.log(countryInput);
console.log(spotInput);
console.log(ageInput);
console.log(daysInput);
console.log(companyInput);
console.log(lastPlacesInput);
console.log(bestPlacesInput);
if (countryInput === "overseas" && spotInput === "beach" && ageInput === "under40" && companyInput === "friend") {
$(".rio, .tahiti").show();
} else if (countryInput === "us" && spotInput === "beach" && ageInput === "under40" && companyInput === "family") {
$(".hawaii").show();
} else if (countryInput === "us"){
$(".hawaii, .oregon, .aspen").show();
} else if (countryInput === "overseas"){
$(".rio, .tahiti, .greenland, .machu").show();
} else if (spotInput === "beach"){
$(".rio, .tahiti, .hawaii").show();
} else if (spotInput === "snow"){
$(".greenland, .aspen").show();
} else if (spotInput === "mountain"){
$(".oregon, .machu").show();
} else if (ageInput === "age"){
$(".allResults").show();
}
});
});
|
Python
|
UTF-8
| 2,491 | 3.703125 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
from euler.baseeuler import BaseEuler
from os import path, getcwd
from itertools import cycle, product
class Euler(BaseEuler):
def solve(self):
fp = path.join(getcwd(), 'euler/resources/cipher.txt')
with open(fp, 'r') as f:
data = f.read()
ct = list(map(int, data.split(',')))
return self._decode(ct, 3, range(97, 123), ' the ')
def _decode(self, ct, klen, kset, sample):
for k in product(kset, repeat=klen):
txt = [x ^ y for x, y in zip(ct, cycle(k))]
if sample in ''.join(map(chr, txt)):
return sum(txt)
return 0
@property
def answer(self):
return ('The sum of the ASCII values in the original text is ' +
'%d.' % self.solve())
@property
def problem(self):
return '''
Project Euler Problem 59
Each character on a computer is assigned a unique code and the preferred
standard is ASCII (American Standard Code for Information Interchange). For
example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to
ASCII, then XOR each byte with a given value, taken from a secret key. The
advantage with the XOR function is that using the same encryption key on
the cipher text, restores the plain text; for example, 65 XOR 42 = 107,
then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text
message, and the key is made up of random bytes. The user would keep the
encrypted message and the encryption key in different locations, and
without both "halves", it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified
method is to use a password as a key. If the password is shorter than the
message, which is likely, the key is repeated cyclically throughout the
message. The balance for this method is using a sufficiently long password
key for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower
case characters. Using cipher.txt (right click and 'Save Link/Target
As...'), a file containing the encrypted ASCII codes, and the knowledge
that the plain text must contain common English words, decrypt the message
and find the sum of the ASCII values in the original text.
'''
|
JavaScript
|
UTF-8
| 13,120 | 2.53125 | 3 |
[] |
no_license
|
/**
* PeptideController
*
* @description :: Server-side logic for managing Peptides
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
/**
* `PeptideController.create()`
*/
create: function (req, res) {
var gene = req.body.gene;
var geneCard = req.body.geneCard;
var type = req.body.type;
var tumor = req.body.tumor;
var hla = req.body.hla;
var freq;
//Freq must be an int, so making sure of it
if (isNaN(req.body.freq) || req.body.freq == null) {
freq = 0;
} else {
freq = req.body.freq;
}
var leftSequence = req.body.leftSequence;
var redPart = req.body.redPart;
var rightSequence = req.body.rightSequence;
var pos = req.body.pos;
var stimulation = req.body.stimulation;
var reference = req.body.reference;
var fullReference = req.body.fullReference;
var url = req.body.url;
var newTag = !!req.body.newTag;
var comment = req.body.comment;
var image = "";
//Skipper used to upload the expression image, even if there isn't any image uploaded
req.file('file').upload(function whenDone(err,uploadedFiles){
if (err) {
sails.log.error(new Error("Create: Error when uploading image file"));
}
//In case there is no image
if (uploadedFiles.length === 0) {
Peptide.create({
gene: gene,
geneCard: geneCard,
type: type,
tumor: tumor,
hla: hla,
freq: freq,
leftSequence: leftSequence,
redPart: redPart,
rightSequence: rightSequence,
pos: pos,
stimulation: stimulation,
reference: reference,
fullReference: fullReference,
url: url,
newTag: newTag,
image: image,
comment: comment
}).exec(function (err) {
if (err) {
sails.log.error(new Error("500: Database Error (create)"));
res.send(500, {error: 'Database Error'});
}
res.redirect('Peptide/adminlist');
});
}else {
//Convert the uploaded image into base64 string, then delete the uploaded image from the disk
var fs = require('fs');
var bitmap = fs.readFileSync(uploadedFiles[0].fd);
image = "data:image/jpeg;base64,"+ bitmap.toString('base64');
fs.unlink(uploadedFiles[0].fd, function(err) {
if (err) {
sails.log.error(new Error("Create: Error when deleting image in the server"));
return;
}
Peptide.create({
gene: gene,
geneCard: geneCard,
type: type,
tumor: tumor,
hla: hla,
freq: freq,
leftSequence: leftSequence,
redPart: redPart,
rightSequence: rightSequence,
pos: pos,
stimulation: stimulation,
reference: reference,
fullReference: fullReference,
url: url,
newTag: newTag,
image: image,
comment: comment
}).exec(function (err) {
if (err) {
sails.log.error(new Error("500: Database Error (create)"));
res.send(500, {error: 'Database Error'});
}
res.redirect('Peptide/adminlist');
});
});
}
});
},
/**
* `PeptideController.list()`
*/
//Request to the database. Fetch the peptides based on their types so they are grouped for the page
list: function (req, res) {
Peptide.find().where({type: "mutation"}).exec(function (err, mutations) {
if (err) {
sails.log.error(new Error("500: Database Error (list: fetch mutation)"));
res.send(500, {error: 'Database Error'});
}
Peptide.find().where({type: "tumor"}).exec(function (err, tumors) {
if (err) {
sails.log.error(new Error("500: Database Error (list: fetch tumor)"));
res.send(500, {error: 'Database Error'});
}
Peptide.find().where({type: "differentiation"}).exec(function (err, differentiations) {
if (err) {
sails.log.error(new Error("500: Database Error (list: fetch differentiation)"));
res.send(500, {error: 'Database Error'});
}
Peptide.find().where({type: "overexpressed"}).exec(function (err, overs) {
if (err) {
sails.log.error(new Error("500: Database Error (list: fetch overexpressed)"));
res.send(500, {error: 'Database Error'});
}
Peptide.find().where({type: "potential"}).exec(function (err, potentials) {
if (err) {
sails.log.error(new Error("500: Database Error (list: fetch potential)"));
res.send(500, {error: 'Database Error'});
}
res.view('list', {
mutations: mutations,
tumors: tumors,
differentiations: differentiations,
overs: overs,
potentials: potentials
});
});
});
});
});
});
},
/**
* `PeptideController.search()`
*/
//Request to the database. Separate the peptides and the potential articles
search: function (req, res) {
Peptide.find().where({type: {'!' : ["potential"]}}).exec(function (err, peptides){
if (err) {
sails.log.error(new Error("500: Database Error (search: fetch non-potential)"));
res.send(500, {error: 'Database Error'});
}
Peptide.find().where({type: "potential"}).exec(function (err, potentials) {
if (err) {
sails.log.error(new Error("500: Database Error (search: fetch potential)"));
res.send(500, {error: 'Database Error'});
}
res.view('search', {
peptides: peptides,
potentials: potentials
});
});
});
},
/**
* `PeptideController.adminlist()`
*/
adminlist: function (req, res) {
Peptide.find().where({type: {'!' : ["potential"]}}).exec(function (err, peptides){
if (err) {
sails.log.error(new Error("500: Database Error (adminlist: fetch non-potential)"));
res.send(500, {error: 'Database Error'});
}
Peptide.find().where({type: "potential"}).exec(function (err, potentials) {
if (err) {
sails.log.error(new Error("500: Database Error (adminlist: fetch potential)"));
res.send(500, {error: 'Database Error'});
}
res.view('adminlist', {
peptides: peptides,
potentials: potentials
});
});
});
},
/**
* `PeptideController.submit()`
*/
submit: function(req, res) {
res.view('submit');
},
/**
* `PeptideController.send()`
*/
send: function(req,res) {
//Use the build-in skipper
req.file('pdf').upload(function whenDone(err,uploadedFiles){
if (err) {
sails.log.error(new Error("Send: Error when uploading pdf"));
return res.view('submit', {message:"error"});
}
//Nodemailer module used to send the mail
var nodemailer = require('nodemailer');
var config = require("../../config/secrets");
//Credentials of host
var transporter = nodemailer.createTransport({
host: config.emailsmtp,
port: config.emailport
});
var mailOptions;
//Mail body
mailOptions = {
from: config.emailsender,
to: config.emailreceiver,
subject: 'CAPeD: A new file has been submitted to you',
html: '<html><p>Greetings</p><p>A new article from ' + req.body.email + ' has been submitted.</p><p>Here is their comment: </p><p><i>' + req.body.comment + '</i></p></html>',
attachments: [{
filename: uploadedFiles[0].filename,
path: uploadedFiles[0].fd
}]
};
//Sending the mail
transporter.sendMail(mailOptions, function(error, info){
if (err) {
sails.log.error(new Error("Send: Error when sending mail"));
return res.view('submit', {message:"error"});
}
console.log('Email sent: ' + info.response);
//Deleting the temporary file after the mail has been sent.
var fs = require('fs');
fs.unlink(uploadedFiles[0].fd, function(err) {
if (err) {
sails.log.error(new Error("Send: Error when deleting pdf in the server"));
return;
}
return res.view('submit', {message:"success"});
});
});
});
},
/**
* `PeptideController.add()`
*/
add: function(req, res) {
res.view('add');
},
/**
* `PeptideController.edit()`
*/
edit: function (req, res) {
Peptide.findOne({id: req.params.id}).exec(function (err, peptide) {
if (err) {
sails.log.error(new Error("500: Database Error (edit)"));
res.send(500, {error: 'Database Error'});
}
if(!peptide){
res.redirect('404');
}else {
res.view('edit', {peptide: peptide});
}
})
},
details: function (req, res) {
Peptide.findOne({id: req.params.id}).exec(function (err, peptide) {
if (err) {
sails.log.error(new Error("500: Database Error (details)"));
res.send(500, {error: 'Database Error'});
}
if(!peptide){
res.redirect('404');
}else{
res.view('details', {peptide: peptide});
}
})
},
/**
* `PeptideController.update()`
*/
update: function(req, res){
var gene = req.body.gene;
var geneCard = req.body.geneCard;
var type = req.body.type;
var tumor = req.body.tumor;
var hla = req.body.hla;
var freq;
if (isNaN(req.body.freq) || req.body.freq == null) {
freq = 0;
} else {
freq = req.body.freq;
}
var leftSequence = req.body.leftSequence;
var redPart = req.body.redPart;
var rightSequence = req.body.rightSequence;
var pos = req.body.pos;
var stimulation = req.body.stimulation;
var reference = req.body.reference;
var fullReference = req.body.fullReference;
var url = req.body.url;
var newTag = !!req.body.newTag;
var comment = req.body.comment;
var image;
if (req.body.deleteImage){
image = "";
} else {
image = req.body.image;
}
//Similarly to create, uses skipper to upload the file
req.file('file').upload(function whenDone(err,uploadedFiles) {
if (err) {
sails.log.error(new Error("Update: Error when uploading image file"));
}
//Proceed with update if there is no image
if (uploadedFiles.length === 0) {
Peptide.update({id: req.params.id},{
gene: gene,
geneCard: geneCard,
type: type,
tumor: tumor,
hla: hla,
freq: freq,
leftSequence: leftSequence,
redPart: redPart,
rightSequence: rightSequence,
pos: pos,
stimulation: stimulation,
reference: reference,
fullReference: fullReference,
url: url,
newTag: newTag,
image: image,
comment: comment
}).exec(function (err) {
if (err) {
sails.log.error(new Error("500: Database Error (update)"));
res.send(500, {error: 'Database Error'});
}
res.redirect('Peptide/adminlist');
});
} else {
//Convert the image into base 64 then delete uploaded image from the disk
var fs = require('fs');
var bitmap = fs.readFileSync(uploadedFiles[0].fd);
image = "data:image/jpeg;base64," + bitmap.toString('base64');
fs.unlink(uploadedFiles[0].fd, function (err) {
if (err) {
sails.log.error(new Error("Update: Error when deleting pdf in the server"));
return;
}
Peptide.update({id: req.params.id}, {
gene: gene,
geneCard: geneCard,
type: type,
tumor: tumor,
hla: hla,
freq: freq,
leftSequence: leftSequence,
redPart: redPart,
rightSequence: rightSequence,
pos: pos,
stimulation: stimulation,
reference: reference,
fullReference: fullReference,
url: url,
newTag: newTag,
image: image,
comment: comment
}).exec(function (err) {
if (err) {
sails.log.error(new Error("500: Database Error (update)"));
res.send(500, {error: 'Database Error'});
}
res.redirect('Peptide/adminlist');
});
});
}
});
},
/**
* `PeptideController.delete()`
*/
delete: function (req, res) {
Peptide.destroy({id: req.params.id}).exec(function (err) {
if (err) {
sails.log.error(new Error("500: Database Error (delete)"));
res.send(500, {error: 'Database Error'});
}
res.redirect('Peptide/adminlist');
});
}
};
|
Markdown
|
UTF-8
| 663 | 2.75 | 3 |
[] |
no_license
|
# Programação assíncrona
- Operações que podem ser lentas
- Requisição de daos à APIs
- Processamento intenso de dados
- Comunicação com banco de dados (Node.js)
- É extremamente importante que o JavaScript **não** espere o término de instruções lentas
- A principal técnica é a utilização do **event loop**
## Event loop
- Funções a serem executas em uma pilha lógica de invocações (call stack)
- Quando a função utiliza Web APIs, ela precisa passar pelo evento loop, pois está sujeita à lentidões
- Executa uma função por vez e faz a orquestração que permite execução assíncrona
- Em geral, WEB APIs possuem callbacks
|
C++
|
UTF-8
| 943 | 3.65625 | 4 |
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-3.0-only"
] |
permissive
|
///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2019.
// 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)
//
// appendix0a_12-001_range_based_for.cpp
#include <cstdint>
#include <iostream>
#include <vector>
void do_something()
{
// Set v to (1,2,3).
std::vector<char> v =
{
char(1),
char(2),
char(3)
};
// Add 0x30 to each element in v,
// giving (0x31,0x32,0x33).
// Use range-based-for(:).
for(char& c : v)
{
c += char(0x30);
}
// Print v as characters.
std::cout << "v: ";
for(char c : v) { std::cout << c << ","; }
std::cout << std::endl;
// Print v as integers.
std::cout << "v: ";
for(char c : v) { std::cout << "0x" << std::hex << std::uint32_t(c) << ","; }
std::cout << std::endl;
}
int main()
{
do_something();
}
|
Python
|
UTF-8
| 3,024 | 3.609375 | 4 |
[] |
no_license
|
import csv
from collections import defaultdict
def read_csv(path):
"""Reads a CSV from a given path.
Stores it as a list of lists.
Args:
path (str): path to the CSV file.
Returns:
list: list of lists, each corresponds
to a different line in the given CSV file.
"""
with open(path, newline='') as csv_file:
csv_file = csv.reader(csv_file, delimiter=',')
rows = [row for row in csv_file]
return rows
def create_dict(csv_files, unique):
"""Creates a dict from a list of lists.
Firs element stored should contain the information
about column names. The keys in the dictionary
will be taken from the `unique` column.
Args:
csv_files (list): list of lists. Each contains
one line from a CSV file,
unique (str): name of the column. It's values will
be used as ids (this column should contain only
unique values).
Returns:
tuple: the first element is the dictionary
made from the list of lists which corresponds
to the CSV file. The second element is a list
which containt the names of all columns.
"""
csv_dict = defaultdict(dict)
all_columns = set()
for csv_file in csv_files:
col_names = csv_file[0]
for col_name in col_names:
all_columns.add(col_name)
all_columns = list(all_columns)
all_columns.remove(unique)
for csv_file in csv_files:
col_names = csv_file[0]
unique_id = col_names.index(unique)
for line in csv_file[1:]:
tmp = {}
for i in range(len(col_names)):
if i == unique_id:
continue
tmp[col_names[i]] = line[i]
if tmp.keys() == all_columns:
continue
else:
missing_columns = list(set(all_columns).difference(set(tmp.keys())))
for missing_column in missing_columns:
tmp[missing_column] = ''
csv_dict[line[unique_id]] = tmp
return csv_dict, all_columns
def merge_csv(csv_list, output_path, unique):
"""Merges two CSV files by a unique column.
Args:
csv_list (list): list of paths to CSV files,
output_path (str): path to save the new, merged CSV file,
unique (str): column name, should be unique.
"""
csv_files_list = [read_csv(path) for path in csv_list]
csv_files_dict, col_names = create_dict(csv_files_list, unique)
merged_csv = [[unique, *col_names]]
for unique_key, value in csv_files_dict.items():
tmp = [value.get(col_name, unique_key) for col_name in merged_csv[0]]
merged_csv.append(tmp)
with open(output_path, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerows(merged_csv)
if __name__ == "__main__":
merge_csv(
csv_list=['files/students1.csv', 'files/students2.csv'],
output_path='files/all_students.csv',
unique='Name'
)
|
Python
|
UTF-8
| 5,087 | 2.75 | 3 |
[] |
no_license
|
"""
puts vulnerability info into the db
cve, summary, repo_location, commit_number
"""
import re
from lxml import etree
import urllib2
import psycopg2
# Connect to an existing database
conn = psycopg2.connect(dbname="patch_db", user="patch_user")
# Open a cursor to perform database operations
cur = conn.cursor()
def search_results(filename):
print filename
f = open(filename)
tree = etree.parse(f)
entry_nodes = tree.xpath('//prefix:entry', namespaces={'prefix':'http://scap.nist.gov/schema/feed/vulnerability/2.0'})
for entry_node in entry_nodes:
cve = entry_node.xpath('@id')[0]
summary_node = entry_node.xpath('./prefix:summary', namespaces={'prefix':'http://scap.nist.gov/schema/vulnerability/0.4'})[0]
summary = summary_node.text
cwe_nodes = entry_node.xpath('./prefix:cwe', namespaces={'prefix':'http://scap.nist.gov/schema/vulnerability/0.4'})
if len(cwe_nodes) > 0:
cwe = cwe_nodes[0].xpath('@id')[0]
else:
cwe = '0'
published_datetime_node = entry_node.xpath('./prefix:published-datetime', namespaces={'prefix':'http://scap.nist.gov/schema/vulnerability/0.4'})[0]
published_datetime = published_datetime_node.text
modified_datetime_node = entry_node.xpath('./prefix:last-modified-datetime', namespaces={'prefix':'http://scap.nist.gov/schema/vulnerability/0.4'})[0]
modified_datetime = modified_datetime_node.text
reference_group_nodes = entry_node.xpath('./prefix:references', namespaces={'prefix':'http://scap.nist.gov/schema/vulnerability/0.4'})
for reference_group_node in reference_group_nodes:
reference_nodes = reference_group_node.xpath('./prefix:reference', namespaces={'prefix':'http://scap.nist.gov/schema/vulnerability/0.4'})
for reference_node in reference_nodes:
url = reference_node.xpath('@href')[0]
if len(url)>0 and re.search('.*/commit/.*[0-9A-Fa-f]{40}', url):
git_type_1(url, cve, cwe, summary, published_datetime, modified_datetime)
elif len(url)>0 and re.search('.*git\..*[0-9A-Fa-f]{40}.*', url):
git_type_2(url, cve, cwe, summary, published_datetime, modified_datetime)
def git_type_1(url, cve, cwe, summary, published_datetime, modified_datetime):
repo_location = re.split('commit|;', url)[0]
commit_number = re.search('[0-9A-Fa-f]{40}', url).group(0)
if len(repo_location) > 0 and len(commit_number) > 0:
insert_revision(cve, cwe, summary, published_datetime, modified_datetime, repo_location, commit_number)
def git_type_2(url, cve, cwe, summary, published_datetime, modified_datetime):
try:
summary_url = re.split(';', url)[0]
summary_page = urllib2.urlopen(summary_url)
parser = etree.HTMLParser()
git_tree = etree.parse(summary_page, parser)
url_nodes = git_tree.xpath("//tr[@class='metadata_url']/td")
repo_location = ''
for url_node in url_nodes:
if url_node.text and re.match("git://", url_node.text):
repo_location = url_node.text
if not(repo_location):
location_nodes = git_tree.xpath("//div[@class='page_header']/a")
if len(location_nodes) > 2:
repo_location = location_nodes[1].text + '/' + location_nodes[2].text
commit_number = re.search('[0-9A-Fa-f]{40}', url).group(0)
if len(repo_location) > 0 and len(commit_number) > 0:
insert_revision(cve, cwe, summary, published_datetime, modified_datetime, repo_location, commit_number)
except urllib2.URLError:
#print "bad git url"
pass
def insert_revision(cve, cwe, summary, published_datetime, modified_datetime, repo_location, commit_number):
print cve
cur.execute("SELECT * FROM locations where location = %s;", (repo_location,))
if cur.fetchone() == None:
cur.execute("INSERT INTO locations (location) VALUES (%s)", (repo_location,))
conn.commit()
cur.execute("SELECT location_id FROM locations where location = %s;", (repo_location,))
location_id = cur.fetchone()[0]
cur.execute("SELECT * FROM entries where cve = %s;", (cve,))
if cur.fetchone() == None:
cur.execute("INSERT INTO entries (cve, cwe, summary, published_datetime, modified_datetime, commit_number) VALUES (%s, %s, %s, %s, %s, %s)", (cve, cwe, summary, published_datetime, modified_datetime, commit_number))
conn.commit()
cur.execute("INSERT INTO location_mapping (cve, location_id) VALUES (%s, %s)", (cve, location_id))
conn.commit()
def main():
filenames = ['nvdcve-2.0-2002.xml', 'nvdcve-2.0-2003.xml', 'nvdcve-2.0-2004.xml', 'nvdcve-2.0-2005.xml', 'nvdcve-2.0-2006.xml', 'nvdcve-2.0-2007.xml', 'nvdcve-2.0-2008.xml', 'nvdcve-2.0-2009.xml', 'nvdcve-2.0-2010.xml', 'nvdcve-2.0-2011.xml', 'nvdcve-2.0-2012.xml', 'nvdcve-2.0-modified.xml', 'nvdcve-2.0-recent.xml']
for filename in filenames:
search_results(filename)
if __name__ == "__main__":
main()
|
PHP
|
UTF-8
| 8,126 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* Generated by PHPUnit_SkeletonGenerator on 2015-02-16 at 20:05:00.
*/
class SentenceTest extends PHPUnit_Framework_TestCase {
/**
* @var Sentence
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp() {
$this->object = new Sentence;
}
/**
* @covers Sentence::count
*/
public function testCountEmpty() {
$this->assertSame(0, $this->object->count(''));
$this->assertSame(0, $this->object->count(' '));
$this->assertSame(0, $this->object->count("\n"));
}
/**
* @covers Sentence::count
*/
public function testCountWord() {
$this->assertSame(1, $this->object->count('Hello'));
$this->assertSame(1, $this->object->count('Hello.'));
$this->assertSame(1, $this->object->count('Hello...'));
$this->assertSame(1, $this->object->count('Hello!'));
$this->assertSame(1, $this->object->count('Hello?'));
$this->assertSame(1, $this->object->count('Hello?!'));
}
/**
* @covers Sentence::count
*/
public function testCountTwoWords() {
$this->assertSame(1, $this->object->count('Hello world'));
$this->assertSame(1, $this->object->count('Hello world.'));
$this->assertSame(1, $this->object->count('Hello world...'));
$this->assertSame(1, $this->object->count('Hello world!'));
$this->assertSame(1, $this->object->count('Hello world?'));
$this->assertSame(1, $this->object->count('Hello world?!'));
}
/**
* @covers Sentence::count
*/
public function testCountMultipleWords() {
$this->assertSame(2, $this->object->count('Hello world. Are you there'));
$this->assertSame(2, $this->object->count('Hello world. Are you there?'));
$this->assertSame(1, $this->object->count('Hello world, Are you there?'));
$this->assertSame(1, $this->object->count('Hello world: Are you there?'));
$this->assertSame(1, $this->object->count('Hello world... Are you there?'));
}
/**
* @covers Sentence::count
*/
public function testCountLinebreaks() {
$this->assertSame(2, $this->object->count("Hello world...\rAre you there?"));
$this->assertSame(2, $this->object->count("Hello world...\nAre you there?"));
$this->assertSame(2, $this->object->count("Hello world...\r\nAre you there?"));
$this->assertSame(2, $this->object->count("Hello world...\r\n\rAre you there?"));
$this->assertSame(2, $this->object->count("Hello world...\n\r\nAre you there?"));
$this->assertSame(2, $this->object->count("Hello world...\n\nAre you there?"));
$this->assertSame(2, $this->object->count("Hello world...\r\rAre you there?"));
}
/**
* @covers Sentence::count
*/
public function testCountAbreviations() {
$this->assertSame(1, $this->object->count("Hello mr. Smith."));
$this->assertSame(1, $this->object->count("Hello, OMG Kittens!"));
$this->assertSame(1, $this->object->count("Hello, abbrev. Kittens!"));
$this->assertSame(1, $this->object->count("Hello, O.M.G. Kittens!"));
}
/**
* @covers Sentence::count
*/
public function testCountMultiplePunctuation() {
$this->assertSame(2, $this->object->count("Hello there. Brave new world."));
$this->assertSame(1, $this->object->count("Hello there... Brave new world."));
$this->assertSame(2, $this->object->count("Hello there?... Brave new world."));
$this->assertSame(2, $this->object->count("Hello there!... Brave new world."));
$this->assertSame(2, $this->object->count("Hello there!!! Brave new world."));
$this->assertSame(2, $this->object->count("Hello there??? Brave new world."));
}
/**
* @covers Sentence::count
*/
public function testCountOneWordSentences() {
$this->assertSame(2, $this->object->count("You? Smith?"));
$this->assertSame(2, $this->object->count("You there? Smith?"));
$this->assertSame(1, $this->object->count("You mr. Smith?"));
//$this->assertSame(2, $this->object->count("Are you there. Smith?"); // Confuses "there." for an abbreviation.
$this->assertSame(2, $this->object->count("Are you there. Smith, sir?"));
$this->assertSame(2, $this->object->count("Are you there. Mr. Smith?"));
}
/**
* @covers Sentence::split
*/
public function testSplitEmpty() {
$this->assertSame(array(), $this->object->split(''));
$this->assertSame(array(), $this->object->split(' '));
$this->assertSame(array(), $this->object->split("\n"));
}
/**
* @covers Sentence::split
*/
public function testSplitWord() {
$this->assertSame(array('Hello'), $this->object->split('Hello'));
$this->assertSame(array('Hello.'), $this->object->split('Hello.'));
$this->assertSame(array('Hello...'), $this->object->split('Hello...'));
$this->assertSame(array('Hello!'), $this->object->split('Hello!'));
$this->assertSame(array('Hello?'), $this->object->split('Hello?'));
$this->assertSame(array('Hello?!'), $this->object->split('Hello?!'));
}
/**
* @covers Sentence::split
*/
public function testSplitMultipleWords() {
$this->assertSame(array('Hello world.', ' Are you there'), $this->object->split('Hello world. Are you there'));
$this->assertSame(array('Hello world.', ' Are you there?'), $this->object->split('Hello world. Are you there?'));
$this->assertSame(array('Hello world.', 'Are you there'), $this->object->split('Hello world. Are you there', Sentence::SPLIT_TRIM));
$this->assertSame(array('Hello world.', 'Are you there?'), $this->object->split('Hello world. Are you there?', Sentence::SPLIT_TRIM));
$this->assertSame(array('Hello world, Are you there?'), $this->object->split('Hello world, Are you there?'));
$this->assertSame(array('Hello world: Are you there?'), $this->object->split('Hello world: Are you there?'));
$this->assertSame(array('Hello world... Are you there?'), $this->object->split('Hello world... Are you there?'));
}
/**
* @covers Sentence::split
*/
public function testSplitLinebreaks() {
$this->assertSame(array("Hello world...\r", "Are you there?"), $this->object->split("Hello world...\rAre you there?"));
$this->assertSame(array("Hello world...\n", " Are you there?"), $this->object->split("Hello world...\n Are you there?"));
$this->assertSame(array("Hello world...\n", "Are you there?"), $this->object->split("Hello world...\nAre you there?"));
$this->assertSame(array("Hello world...\r\n", "Are you there?"), $this->object->split("Hello world...\r\nAre you there?"));
$this->assertSame(array("Hello world...\r\n\r", "Are you there?"), $this->object->split("Hello world...\r\n\rAre you there?"));
$this->assertSame(array("Hello world...\n\r\n", "Are you there?"), $this->object->split("Hello world...\n\r\nAre you there?"));
$this->assertSame(array("Hello world...\n\n", "Are you there?"), $this->object->split("Hello world...\n\nAre you there?"));
$this->assertSame(array("Hello world...\r\r", "Are you there?"), $this->object->split("Hello world...\r\rAre you there?"));
}
/**
* @covers Sentence::split
*/
public function testSplitAbreviations() {
$this->markTestIncomplete('This test has not been implemented yet.');
$this->assertSame(array('Hello mr. Smith.'), $this->object->split("Hello mr. Smith."));
$this->assertSame(array('Hello, OMG Kittens!'), $this->object->split("Hello, OMG Kittens!"));
$this->assertSame(array('Hello, abbrev. Kittens!'), $this->object->split("Hello, abbrev. Kittens!"));
$this->assertSame(array('Hello, O.M.G. Kittens!'), $this->object->split("Hello, O.M.G. Kittens!"));
}
/**
* @covers Sentence::split
*/
public function testSplitOneWordSentences() {
$this->assertSame(array("You?", " Smith?"), $this->object->split("You? Smith?"));
$this->assertSame(array("You there?", " Smith?"), $this->object->split("You there? Smith?"));
$this->assertSame(array("You mr. Smith?"), $this->object->split("You mr. Smith?"));
//$this->assertSame(2, $this->object->count("Are you there. Smith?"); // Confuses "there." for an abbreviation.
$this->assertSame(array("Are you there.", " Smith, sir?"), $this->object->split("Are you there. Smith, sir?"));
$this->assertSame(array("Are you there.", " Mr. Smith?"), $this->object->split("Are you there. Mr. Smith?"));
}
}
|
Markdown
|
UTF-8
| 268 | 2.78125 | 3 |
[] |
no_license
|
默认的解释器会自动装载被调用的 Node.js 核心模块到 REPL 环境中。
举个例子,除了声明为全局或有限范围的变量的情况,输入`fs`会被解释为 `global.fs = require('fs')`。
```js
> fs.createReadStream('./some/file');
```
|
Python
|
UTF-8
| 1,635 | 2.53125 | 3 |
[] |
no_license
|
from domain.entity import Entity
class Card_client(Entity):
def __init__(self,nume,prenume,CNP,data_nasterii,data_inregistrarii):
super(Card_client, self).__init__()
self.__nume = nume
self.__prenume = prenume
self.__CNP = CNP
self.__data_nasterii = data_nasterii
self.__data_inregistrarii = data_inregistrarii
@property
def nume(self):
return self.__nume
@property
def prenume(self):
return self.__prenume
@property
def CNP(self):
return self.__CNP
@property
def data_nasterii(self):
return datetime.datetime(
int(self.__data_nasterii[6] + self.__data_nasterii[7] + self.__data_nasterii[8] + self.__data_nasterii[9]),
int(self.__data_nasterii[3] + self.__data_nasterii[4]),
int(self.__data_nasterii[0] + self.__data_nasterii[1]))
@property
def data_inregistrarii(self):
return datetime.datetime(int(
self.__data_inregistrarii[6] + self.__data_inregistrarii[7] + self.__data_inregistrarii[8] +
self.__data_inregistrarii[9]), int(self.__data_inregistrarii[3] + self.__data_inregistrarii[4]),
int(self.__data_inregistrarii[0] + self.__data_inregistrarii[1]))
def __str__(self):
return f'1.{self.nume} {self.prenume}, {self.CNP}, data nasterii: {self.data_nasterii}, data inregistarii: {self.data_inregistrarii}'
def __eq__(self,other):
if type(self)!=type(other):
return False
return self.id_entity==other.id_entity
|
Python
|
UTF-8
| 3,720 | 3.328125 | 3 |
[] |
no_license
|
import re
import sys
from dataclasses import dataclass
import math
import copy
sys.path.append("c:\\Users\\james_pc\\projects\\aoc2020\\")
sys.path.append("./..")
from utils import time_algo
PATH = "day22/"
# Part 1
def get_input(filename):
my_file = open(filename, "r")
content = my_file.readlines()
return [line.rstrip() for line in content]
class Game:
def __init__(self, player1_deck, player2_deck):
self.player1_deck = player1_deck
self.player2_deck = player2_deck
# self.turn = "player_1"
self.previous_rounds = []
self.winner = None
def play(self):
while (self.player1_deck != []) and (self.player2_deck != []):
# If this is a repeat of previous round, player 1 wins
if [self.player1_deck, self.player2_deck] in self.previous_rounds:
self.winner = "player1"
break
self.previous_rounds.append(
[self.player1_deck.copy(), self.player2_deck.copy()]
)
player1_card = self.player1_deck.pop(0)
player2_card = self.player2_deck.pop(0)
# Get winner
if (player1_card <= len(self.player1_deck)) and (
player2_card <= len(self.player2_deck)
):
# Decide winner with sub game
sub_player1_deck = self.player1_deck[:player1_card]
sub_player2_deck = self.player2_deck[:player2_card]
sub_game = Game(
player1_deck=sub_player1_deck, player2_deck=sub_player2_deck
)
sub_game.play()
round_winner = sub_game.winner
assert round_winner != None
else:
# Decide winner with normal rules
if player1_card > player2_card:
round_winner = "player1"
elif player2_card > player1_card:
round_winner = "player2"
# Add cards to the bottom of the deck
if round_winner == "player1":
self.player1_deck.append(player1_card)
self.player1_deck.append(player2_card)
elif round_winner == "player2":
self.player2_deck.append(player2_card)
self.player2_deck.append(player1_card)
else:
raise Exception
if len(self.player1_deck) == 0:
self.winner = "player2"
elif len(self.player2_deck) == 0:
self.winner = "player1"
def get_win_score(self):
if self.winner == "player1":
winner_deck = self.player1_deck
elif self.winner == "player2":
winner_deck = self.player2_deck
else:
raise Exception
score = 0
for i in range(len(winner_deck)):
score += winner_deck[i] * (len(winner_deck) - i)
return score
def parse_input(input):
player1_deck = []
player2_deck = []
current_deck = player1_deck
for line in input:
if line.startswith("Player 1") or (line == ""):
pass
elif line.startswith("Player 2"):
current_deck = player2_deck
else:
current_deck.append(int(line))
return Game(player1_deck=player1_deck, player2_deck=player2_deck)
def part2_solve(game):
game.play()
print("here")
return game.get_win_score()
if __name__ == "__main__":
input = parse_input(get_input(PATH + "test_input"))
print(part2_solve(input))
input = parse_input(get_input(PATH + "test_input_1"))
print(part2_solve(input))
input = parse_input(get_input(PATH + "real_input"))
print(part2_solve(input))
|
Java
|
UTF-8
| 197 | 2.265625 | 2 |
[] |
no_license
|
package com.monopoly.exceptions;
@SuppressWarnings("serial")
public class InvalidDiceValueException extends Exception
{
public InvalidDiceValueException()
{
super("Invalid Dice Value!");
}
}
|
JavaScript
|
UTF-8
| 5,768 | 2.890625 | 3 |
[] |
no_license
|
(function (){
var resSpan = document.getElementsByTagName('span')[0];
var canvas = document.createElement("canvas");
var fire = document.getElementById("fire");
var ctx = canvas.getContext("2d");
var spaceShipHeigth = 40;
var spaceShipWidth = 40;
var monsterHeigth = 60;
var monsterWidth =60;
var score = 0;
var youLose = false;
var ship;
canvas.width = 480;
canvas.height = 600;
var spaceShpiMoveSpeed = 15;
var gameSpeed = 180;
var req;
document.body.appendChild(canvas);
init();
var monsters;
//draw game field
function fieldDraw() {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
//initialize game objects
function init(){
new createSpaceShip();
monsters = new Array();
monsters.push(new addSpriteRow(0 ));
fieldDraw();
canvas.onkeypress = spaceShipMove;
document.addEventListener('keydown', spaceShipMove, false);
}
//add spaceship to scene
var img;
function createSpaceShip(){
this.x = (canvas.width - spaceShipWidth)/2 ;
this.y;
img = new Image();
img.src = 'img/spaceship.jpg';
img.onload = function() {
req = requestAnimationFrame(motion);
}
}
function addSprite(x, y, cp){
this.sprite = new Image();
this.sprite.src = cp ? 'sprites/monster12.png' : 'sprites/monster11.png';
this.x = x;
this.y = y;
this.isKilled = false;
}
//add row of monsters
function addSpriteRow(i){
var delay = 0;
var changePic = (i % 2 == 0) ? false : true;
this.spArr = new Array();
this.monsterY = 0;
for(var i = 0; i < canvas.width/monsterWidth; i++){
this.spArr.push(new addSprite(i * monsterWidth, this.monsterY, changePic));
}
this.draw = function(){
delay++;
if(delay % 30 ==0 ){
changePic = !changePic;
for(var j = 0; j < this.spArr.length; j++) this.spArr[j].sprite.src = changePic ? 'sprites/monster12.png' : 'sprites/monster11.png';
if(delay == gameSpeed){delay = 0; this.monsterY += monsterHeigth;}
}
}
}
//n**2 !!!! draw new monster rows. think about dif.
var addNewRow = 0;
function monsterDraw(aMonsters){
if(aMonsters[0].monsterY !== addNewRow && aMonsters[0].monsterY !=0 ) {
addNewRow = aMonsters[0].monsterY;
monsters.push(new addSpriteRow());
}
for(var mCount = 0; mCount < aMonsters.length; mCount++){
aMonsters[mCount].draw();
for(var spNum = 0; spNum < aMonsters[mCount].spArr.length; spNum++)
ctx.drawImage(aMonsters[mCount].spArr[spNum].sprite, aMonsters[mCount].spArr[spNum].x, aMonsters[mCount].monsterY, monsterWidth, monsterHeigth);
}
}
//n*3 think about perfomans
function checkLose(){
for(var i = 0; i < monsters.length; i++ ){
if(monsters[i].monsterY >= 9 * monsterHeigth){
for(var j = 0; j < monsters[i].spArr.length; j++ ){
if( !monsters[i].spArr[j].isKilled){
window.cancelAnimationFrame(req);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.font = 'bold 30px sans-serif';
ctx.fillText("YOU LOSE ", 180, 200);
ctx.fillText("Press F5 for restart!", 120, 240);
ctx.fillText("Your score:" + score, 130, 280);
youLose = true;
}
}
}
}
}
//n**3 !! think about perfomans
function killCheck(){
for (var i =0; i < patrons.length; i ++){
for(var k = 0; k < monsters.length; k++ ){
for (var j = 0; j < monsters[k].spArr.length; j++) {
if(patrons.length > 0 && monsters[k] && patrons !== undefined
&& patrons[i].x > monsters[k].spArr[j].x
&& patrons[i].x < monsters[k].spArr[j].x + monsterWidth
&& patrons[i].y < monsters[k].monsterY + monsterHeigth
&& !patrons[i].attecked){
patrons[i].attecked = true;
patrons[i].color = '#000';
monsters[k].spArr[j].isKilled = true;
score+=100;
resSpan.innerHTML=score;
}
monsters[k].spArr = massMonstorssClean(monsters[k].spArr);
}
}
}
}
function patronsDraw(){
if(patrons.length!=0) {
for(var i=0; i < patrons.length; i++){
if(patrons[i].y >= -3) patrons[i].y -=3;
else continue;
patrons[i].draw();
}
}
}
//main draw loop
function motion() {
fieldDraw();
monsterDraw(monsters)
ctx.drawImage(img, xPos, canvas.height-spaceShipWidth, spaceShipWidth, spaceShipHeigth)
patronsDraw();
patrons = massPatronsClean(patrons);
req = requestAnimationFrame(motion);
killCheck();
checkLose();
}
var patrons = new Array();
var xPos = (canvas.width - spaceShipWidth)/2;
function spaceShipMove(e){
if(e.keyCode === 37 || e.which ===37) xPos=(xPos > 0) ? xPos - spaceShpiMoveSpeed : xPos;
if(e.keyCode === 39 || e.which === 39)xPos=(xPos < canvas.width - spaceShipWidth ) ? xPos + spaceShpiMoveSpeed : xPos;
if((e.keyCode === 32 || e.which === 32) && !youLose){
fire.play();
patrons.push(new rect(xPos + spaceShipWidth/2, canvas.height - spaceShipHeigth - 5));
}
}
function rect(x, y) {
this.color = '#ddd';
this.x = x;
this.attecked = false;
this.y = y;
this.width = 2;
this.height = 3;
this.draw = function()
{
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function massPatronsClean(mas){
return mas.filter(function(num){
if(num.y <= -3) num.attecked = true;
return (num.y >= -3 || !num.attecked);
});
}
function massMonstorssClean(mas){
return mas.filter(function(number){
return !number.isKilled;
});
}
}());
|
PHP
|
UTF-8
| 976 | 3.046875 | 3 |
[] |
no_license
|
<?php
/**
* definisce un oggetto percorso
*/
class Giro {
public $nomeGiro;
public $autista;
public $mezzo;
public $idGiro;
public $idAppalto;
public $fermate;
//COSTRUTTORE
/**
* costruttore percorso
* @param type string $unNome nome del percorso
* @param type string $unAutista nome dell'autista
* @param type string $unMezzo mezzo
* @param type array $delleFermate fermate nel percorso
* @param type int $unIdGiro id univoco percorso
* @param type int $unIdAppalto id della commessa di appartenenza
*/
public function __construct($unNome, $unAutista, $unMezzo, $delleFermate, $unId, $unIdAppalto) {
$this->nomeGiro = $unNome;
$this->autista = $unAutista;
$this->mezzo = $unMezzo;
$this->idGiro = $unId;
$this->idAppalto = $unIdAppalto;
$this->fermate = $delleFermate; //questo sarà un array di fermate
}
}
|
Python
|
UTF-8
| 379 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
import netomaton as ntm
import numpy as np
from .rule_test import *
class TestUtils(RuleTest):
def test_binarize_for_plotting(self):
activities = [[2], [35], [12]]
np.testing.assert_equal([[0, 0, 0, 0, 1, 0],
[1, 0, 0, 0, 1, 1],
[0, 0, 1, 1, 0, 0]], ntm.binarize_for_plotting(activities))
|
C++
|
UTF-8
| 2,807 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2017 Facebook, 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.
*/
/*
* Drop-in replacement for std::call_once() with a fast path, which the GCC
* implementation lacks. The tradeoff is a slightly larger `once_flag' struct
* (8 bytes vs 4 bytes with GCC on Linux/x64).
*
* $ call_once_test --benchmark --bm_min_iters=100000000 --threads=16
* ============================================================================
* folly/test/CallOnceTest.cpp relative time/iter iters/s
* ============================================================================
* StdCallOnceBench 3.54ns 282.82M
* FollyCallOnceBench 698.48ps 1.43G
* ============================================================================
*/
#pragma once
#include <atomic>
#include <mutex>
#include <utility>
#include <folly/Likely.h>
#include <folly/Portability.h>
#include <folly/SharedMutex.h>
namespace folly {
class once_flag {
public:
constexpr once_flag() noexcept = default;
once_flag(const once_flag&) = delete;
once_flag& operator=(const once_flag&) = delete;
template <typename Callable, class... Args>
friend void call_once(once_flag& flag, Callable&& f, Args&&... args);
template <typename Callable, class... Args>
friend void call_once_impl_no_inline(once_flag& flag,
Callable&& f,
Args&&... args);
private:
std::atomic<bool> called_{false};
folly::SharedMutex mutex_;
};
template <class Callable, class... Args>
void FOLLY_ALWAYS_INLINE
call_once(once_flag& flag, Callable&& f, Args&&... args) {
if (LIKELY(flag.called_.load(std::memory_order_acquire))) {
return;
}
call_once_impl_no_inline(
flag, std::forward<Callable>(f), std::forward<Args>(args)...);
}
// Implementation detail: out-of-line slow path
template <class Callable, class... Args>
void FOLLY_NOINLINE
call_once_impl_no_inline(once_flag& flag, Callable&& f, Args&&... args) {
std::lock_guard<folly::SharedMutex> lg(flag.mutex_);
if (flag.called_) {
return;
}
std::forward<Callable>(f)(std::forward<Args>(args)...);
flag.called_.store(true, std::memory_order_release);
}
}
|
Java
|
UTF-8
| 1,047 | 1.953125 | 2 |
[] |
no_license
|
package net.luis.common.action;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opensymphony.xwork2.ActionSupport;
import net.luis.common.dao.Page;
/**
* @CreateTime:2017年3月28日 下午4:43:04
* @Author sai.liu
* @ProjectPackage:net.luis.base.action.BaseAction.java @Description:
*/
public abstract class BaseAction extends ActionSupport{
private static final long serialVersionUID = -2195179132019926434L;
protected Logger logger = LoggerFactory.getLogger(getClass());
/** 设置page对象* */
public Page page = new Page(50);
public Page getPage() {
if (this.page.getPageSize() < 5) {
this.page.setPageSize(10);
}
return this.page;
}
public void setPage(Page page) {
this.page = page;
}
public String message;
public List<Integer> checks;
public List<Integer> getChecks() {
return checks;
}
public Integer[] checkIds;
public Integer[] getCheckIds() {
return checkIds;
}
}
|
Java
|
UTF-8
| 1,092 | 2.03125 | 2 |
[] |
no_license
|
package com.example.finclaw.bl.attendance;
import com.example.finclaw.vo.ResponseVO;
import com.example.finclaw.vo.account.UserVO;
import com.example.finclaw.vo.attendance.AttendanceVO;
import com.example.finclaw.vo.project.ProjectVO;
import com.example.finclaw.vo.server.ServerInfoForm;
import com.example.finclaw.vo.server.ServerInfoVO;
import java.util.List;
public interface AttendService {
ResponseVO attendProject(Integer projectID, Integer cooperationID);
ResponseVO quitProject(Integer projectID, Integer cooperationID);
ResponseVO updateServerInfo(ServerInfoForm serverInfoForm);
ResponseVO setReadyForProject(Integer projectID, Integer cooperationID, boolean isReady);
ResponseVO setChosen(Integer projectID, Integer cooperationID, boolean isChosen);
List<ProjectVO> getCooperationProjects(Integer cooperationID);
ServerInfoVO getServerInfo(Integer projectID, Integer cooperationID);
List<UserVO> getProjectDataProducers(Integer projectID);
AttendanceVO getAttendanceInfo(Integer projectID, Integer cooperationID) throws Exception;
}
|
C
|
UTF-8
| 1,729 | 3.75 | 4 |
[
"MIT"
] |
permissive
|
#include<alloc.h>
#include<stdio.h>
#include<conio.h>
#define F 0
#define T 1
struct btnode
{
struct btnode *lc;
int data;
struct btnode *rc;
};
int ch,n,i;
void main()
{
struct btnode *bt1,*bt2;
bt1=NULL;
bt2=NULL;
while(1)
{
clrscr();
printf("\n\t\t\t1:Insert a node in Tree-1");
printf("\n\t\t\t2:Insert a node in Tree-2");
printf("\n\t\t\t3:Compare");
printf("\n\t\t\t4:Exit");
printf("\n\t\t\tPlease enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the element: ");
scanf("%d",&n);
insert(&bt1,n);
break;
case 2:
printf("\nEnter the element: ");
scanf("%d",&n);
insert(&bt2,n);
break;
case 3:
compare(bt1,bt2,&i);
if(i==T)
printf("Both the trees are equal");
else
printf("Both the trees ain't equal");
getch();
break;
case 4:
deleteall(bt1);
deleteall(bt2);
exit(0);
break;
default:
printf("Enter a correct choice!");
getch();
}
}
}
insert(struct btnode **p,int num)
{
if(*p==NULL)
{
*p=(struct btnode *) malloc(sizeof(struct btnode));
(*p)->lc=NULL;
(*p)->rc=NULL;
(*p)->data=num;
}
else
{
if(num<(*p)->data)
insert(&((*p)->lc),num);
else
insert(&((*p)->rc),num);
}
}
deleteall(struct btnode *p)
{
if(p!=NULL)
{
deleteall(p->lc);
deleteall(p->rc);
free(p);
}
}
compare(struct btnode *p,struct btnode *q,int *flag)
{
*flag=F;
if(p==NULL && q==NULL)
*flag=T;
if(p!=NULL && q!=NULL)
{
if(p->data!=q->data)
*flag=F;
else
{
compare(p->lc,q->lc,flag);
if(*flag!=F)
compare(p->rc,q->rc,flag);
}
}
}
|
Java
|
UTF-8
| 16,515 | 1.976563 | 2 |
[
"Apache-2.0"
] |
permissive
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.cmmn.test.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.api.runtime.GenericEventListenerInstance;
import org.flowable.cmmn.api.runtime.PlanItemDefinitionType;
import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.engine.test.CmmnDeployment;
import org.flowable.cmmn.engine.test.FlowableCmmnTestCase;
import org.flowable.task.api.Task;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
/**
* @author Tijs Rademakers
*/
public class GenericEventListenerTest extends FlowableCmmnTestCase {
@Rule
public TestName name = new TestName();
@Test
@CmmnDeployment
public void testSimpleEnableTask() {
//Simple use of the UserEventListener as EntryCriteria of a Task
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey(name.getMethodName()).start();
assertNotNull(caseInstance);
assertEquals(1, cmmnRuntimeService.createCaseInstanceQuery().count());
//3 PlanItems reachable
assertEquals(3, cmmnRuntimeService.createPlanItemInstanceQuery().count());
//1 User Event Listener
PlanItemInstance listenerInstance = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.GENERIC_EVENT_LISTENER).singleResult();
assertNotNull(listenerInstance);
assertEquals("eventListener", listenerInstance.getPlanItemDefinitionId());
assertEquals(PlanItemInstanceState.AVAILABLE, listenerInstance.getState());
// Verify same result is returned from query
GenericEventListenerInstance eventListenerInstance = cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
assertNotNull(eventListenerInstance);
assertEquals(eventListenerInstance.getId(), listenerInstance.getId());
assertEquals(eventListenerInstance.getCaseDefinitionId(), listenerInstance.getCaseDefinitionId());
assertEquals(eventListenerInstance.getCaseInstanceId(), listenerInstance.getCaseInstanceId());
assertEquals(eventListenerInstance.getElementId(), listenerInstance.getElementId());
assertEquals(eventListenerInstance.getName(), listenerInstance.getName());
assertEquals(eventListenerInstance.getPlanItemDefinitionId(), listenerInstance.getPlanItemDefinitionId());
assertEquals(eventListenerInstance.getStageInstanceId(), listenerInstance.getStageInstanceId());
assertEquals(eventListenerInstance.getState(), listenerInstance.getState());
assertEquals(1, cmmnRuntimeService.createGenericEventListenerInstanceQuery().count());
assertEquals(1, cmmnRuntimeService.createGenericEventListenerInstanceQuery().list().size());
assertNotNull(cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseDefinitionId(listenerInstance.getCaseDefinitionId()).singleResult());
assertNotNull(cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseDefinitionId(listenerInstance.getCaseDefinitionId()).singleResult());
//2 HumanTasks ... one active and other waiting (available)
assertEquals(2, cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.HUMAN_TASK).count());
PlanItemInstance active = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.HUMAN_TASK).planItemInstanceStateActive().singleResult();
assertNotNull(active);
assertEquals("taskA", active.getPlanItemDefinitionId());
PlanItemInstance available = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.HUMAN_TASK).planItemInstanceStateAvailable().singleResult();
assertNotNull(available);
assertEquals("taskB", available.getPlanItemDefinitionId());
//Trigger the listener
cmmnRuntimeService.completeGenericEventListenerInstance(listenerInstance.getId());
//UserEventListener should be completed
assertEquals(0, cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.GENERIC_EVENT_LISTENER).count());
//Only 2 PlanItems left
assertEquals(2, cmmnRuntimeService.createPlanItemInstanceQuery().list().size());
//Both Human task should be "active" now, as the sentry kicks on the UserEventListener transition
assertEquals(2, cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.HUMAN_TASK).planItemInstanceStateActive().count());
//Finish the caseInstance
assertCaseInstanceNotEnded(caseInstance);
cmmnTaskService.createTaskQuery().list().forEach(t -> cmmnTaskService.complete(t.getId()));
assertCaseInstanceEnded(caseInstance);
}
@Test
@CmmnDeployment
public void testTerminateTask() {
//Test case where the EventListener is used to complete (ExitCriteria) of a task
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey(name.getMethodName()).start();
assertNotNull(caseInstance);
assertEquals(1, cmmnRuntimeService.createCaseInstanceQuery().count());
//4 PlanItems reachable
assertEquals(4, cmmnRuntimeService.createPlanItemInstanceQuery().list().size());
//1 Stage
assertEquals(1, cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.STAGE).count());
//1 Event Listener
PlanItemInstance listenerInstance = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.GENERIC_EVENT_LISTENER).singleResult();
assertNotNull(listenerInstance);
assertEquals("eventListener", listenerInstance.getPlanItemDefinitionId());
assertEquals("eventListenerPlanItem", listenerInstance.getElementId());
assertEquals(PlanItemInstanceState.AVAILABLE, listenerInstance.getState());
//2 Tasks on Active state
List<PlanItemInstance> tasks = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType("task").list();
assertEquals(2, tasks.size());
tasks.forEach(t -> assertEquals(PlanItemInstanceState.ACTIVE, t.getState()));
//Trigger the listener
cmmnRuntimeService.triggerPlanItemInstance(listenerInstance.getId());
//UserEventListener should be completed
assertEquals(0, cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.USER_EVENT_LISTENER).count());
//Only 2 PlanItems left (1 stage & 1 active task)
assertEquals(2, cmmnRuntimeService.createPlanItemInstanceQuery().list().size());
PlanItemInstance activeTask = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType("task").planItemInstanceStateActive().singleResult();
assertNotNull(activeTask);
assertEquals("taskB", activeTask.getPlanItemDefinitionId());
//Finish the caseInstance
assertCaseInstanceNotEnded(caseInstance);
cmmnRuntimeService.triggerPlanItemInstance(activeTask.getId());
assertCaseInstanceEnded(caseInstance);
}
@Test
@CmmnDeployment
public void testTerminateStage() {
//Test case where the GenericEventListener is used to complete (ExitCriteria) of a Stage
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey(name.getMethodName()).start();
assertNotNull(caseInstance);
assertEquals(1, cmmnRuntimeService.createCaseInstanceQuery().count());
//3 PlanItems reachable
assertEquals(3, cmmnRuntimeService.createPlanItemInstanceQuery().list().size());
//1 Stage
PlanItemInstance stage = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.STAGE).singleResult();
assertNotNull(stage);
//1 User Event Listener
PlanItemInstance listenerInstance = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.GENERIC_EVENT_LISTENER).singleResult();
assertNotNull(listenerInstance);
assertEquals("eventListener", listenerInstance.getPlanItemDefinitionId());
assertEquals(PlanItemInstanceState.AVAILABLE, listenerInstance.getState());
//1 Tasks on Active state
PlanItemInstance task = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType("task").singleResult();
assertNotNull(task);
assertEquals(PlanItemInstanceState.ACTIVE, task.getState());
assertEquals(stage.getId(), task.getStageInstanceId());
//Trigger the listener
assertCaseInstanceNotEnded(caseInstance);
cmmnRuntimeService.triggerPlanItemInstance(listenerInstance.getId());
assertCaseInstanceEnded(caseInstance);
}
@Test
@CmmnDeployment
public void testGenericEventListenerInstanceQuery() {
//Test for EventListenerInstanceQuery
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
.caseDefinitionKey(name.getMethodName())
.start();
assertNotNull(caseInstance);
assertEquals(1, cmmnRuntimeService.createCaseInstanceQuery().count());
//All planItemInstances
assertEquals(8, cmmnRuntimeService.createPlanItemInstanceQuery().count());
//UserEventListenerIntances
assertEquals(6, cmmnRuntimeService.createGenericEventListenerInstanceQuery().stateAvailable().count());
List<GenericEventListenerInstance> events = cmmnRuntimeService.createGenericEventListenerInstanceQuery().list();
assertEquals(6, events.size());
//All different Intances id's
assertEquals(6, events.stream().map(GenericEventListenerInstance::getId).distinct().count());
//UserEventListenerIntances inside Stage1
String stage1Id = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.STAGE).planItemDefinitionId("stage1").singleResult().getId();
assertEquals(2, cmmnRuntimeService.createGenericEventListenerInstanceQuery().stageInstanceId(stage1Id).count());
//UserEventListenerIntances inside Stage2
String stage2Id = cmmnRuntimeService.createPlanItemInstanceQuery().planItemDefinitionType(PlanItemDefinitionType.STAGE).planItemDefinitionId("stage2").singleResult().getId();
assertEquals(2, cmmnRuntimeService.createGenericEventListenerInstanceQuery().stageInstanceId(stage2Id).count());
//UserEventListenerIntances not in a Stage
assertEquals(2, events.stream().filter(e -> e.getStageInstanceId() == null).count());
//Test query by elementId
assertNotNull(cmmnRuntimeService.createGenericEventListenerInstanceQuery().elementId("caseEventListenerOne").singleResult());
//Test query by planItemDefinitionId
assertEquals(2, cmmnRuntimeService.createGenericEventListenerInstanceQuery().planItemDefinitionId("caseUEL1").count());
//Test sort Order - using the names because equals is not implemented in UserEventListenerInstance
List<String> names = events.stream().map(GenericEventListenerInstance::getName).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
List<String> namesDesc = cmmnRuntimeService.createGenericEventListenerInstanceQuery()
.stateAvailable().orderByName().desc().list().stream().map(GenericEventListenerInstance::getName).collect(Collectors.toList());
assertThat(names).isEqualTo(namesDesc);
}
@Test
@CmmnDeployment
public void testOrphanEventListenerMultipleSentries() {
// The model here has one event listener that will trigger the exit of two tasks (A and C) and trigger the activation of task B
// Verify the model setup
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testOrphanEventListenerMultipleSentries").start();
assertNotNull(cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult());
List<Task> tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
assertEquals(2, tasks.size());
assertEquals("A", tasks.get(0).getName());
assertEquals("C", tasks.get(1).getName());
// Completing one tasks should not have impact on the event listener
cmmnTaskService.complete(tasks.get(0).getId());
assertNotNull(cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult());
tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).orderByTaskName().asc().list();
assertEquals(1, tasks.size());
assertEquals("C", tasks.get(0).getName());
// Completing the other task with the exit sentry should still keep the event, as it's reference by the entry of B
cmmnTaskService.complete(tasks.get(0).getId());
assertNotNull(cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult());
assertEquals(0, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
// Firing the event listener should start B
cmmnRuntimeService.completeGenericEventListenerInstance(cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult().getId());
assertNull(cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult());
assertEquals(1, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
}
@Test
@CmmnDeployment
public void testMultipleEventListenersAsEntry() {
CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().caseDefinitionKey("testMultipleEventListenersAsEntry").start();
assertEquals(0, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
List<GenericEventListenerInstance> eventListenerInstances = cmmnRuntimeService.createGenericEventListenerInstanceQuery()
.caseInstanceId(caseInstance.getId()).orderByName().asc().list();
assertThat(eventListenerInstances).extracting(GenericEventListenerInstance::getName).containsExactly("A", "B", "C");
// Completing A should change nothing
cmmnRuntimeService.completeGenericEventListenerInstance(eventListenerInstances.get(0).getId());
assertEquals(0, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
eventListenerInstances = cmmnRuntimeService.createGenericEventListenerInstanceQuery()
.caseInstanceId(caseInstance.getId()).orderByName().asc().list();
assertThat(eventListenerInstances).extracting(GenericEventListenerInstance::getName).containsExactly("B", "C");
// Completing B should activate the stage and remove the orphan event listener C
cmmnRuntimeService.completeGenericEventListenerInstance(eventListenerInstances.get(0).getId());
assertEquals(1, cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).count());
assertEquals(0, cmmnRuntimeService.createGenericEventListenerInstanceQuery().caseInstanceId(caseInstance.getId()).count());
}
}
|
Python
|
UTF-8
| 927 | 2.515625 | 3 |
[
"CC0-1.0"
] |
permissive
|
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class RecentFilter(Gtk.RecentChooserDialog):
def __init__(self):
Gtk.RecentChooserDialog.__init__(self)
self.set_title('RecentFilter')
self.set_default_size(300, 200)
recentfilter = Gtk.RecentFilter()
recentfilter.set_name('All Items')
recentfilter.add_pattern('*')
self.add_filter(recentfilter)
recentfilter = Gtk.RecentFilter()
recentfilter.set_name('Within last 3 days')
recentfilter.add_age(3)
self.add_filter(recentfilter)
recentfilter = Gtk.RecentFilter()
recentfilter.set_name('Image Files')
recentfilter.add_pattern('*.png')
recentfilter.add_pattern('*.jpg')
recentfilter.add_pattern('*.svg')
self.add_filter(recentfilter)
dialog = RecentFilter()
dialog.run()
dialog.destroy()
|
Go
|
UTF-8
| 2,423 | 3.9375 | 4 |
[
"MIT"
] |
permissive
|
package async
import (
"context"
"sync"
)
// Task is a function that can be run concurrently.
type Task func() error
// Run will execute the given tasks concurrently and return any errors.
func Run(tasks ...Task) <-chan error {
errc := make(chan error)
// run tasks
var wg sync.WaitGroup
for _, v := range tasks {
wg.Add(1)
go func(task Task) {
defer wg.Done()
err := task()
if err != nil {
errc <- err
}
}(v)
}
// make sure to close error channel
go func() {
wg.Wait()
close(errc)
}()
return errc
}
// RunForever will execute the given task repeatedly on a set number of goroutines and return any errors. Context can be used to cancel execution of additional tasks.
func RunForever(ctx context.Context, concurrent int, task Task) <-chan error {
errc := make(chan error)
// run tasks
var wg sync.WaitGroup
for c := 0; c < concurrent; c++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
err := task()
if err != nil {
errc <- err
}
select {
case <-ctx.Done():
errc <- ctx.Err()
return
default:
}
}
}()
}
// make sure to close error channel
go func() {
wg.Wait()
close(errc)
}()
return errc
}
// RunLimited will execute the given task a set number of times on a set number of goroutines and return any errors. Total times the task will be executed is equal to concurrent multiplied by count. Context can be used to cancel execution of additional tasks.
func RunLimited(ctx context.Context, concurrent int, count int, task Task) <-chan error {
errc := make(chan error)
// run tasks
var wg sync.WaitGroup
for c := 0; c < concurrent; c++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < count; i++ {
err := task()
if err != nil {
errc <- err
}
select {
case <-ctx.Done():
errc <- ctx.Err()
return
default:
}
}
}()
}
// make sure to close error channel
go func() {
wg.Wait()
close(errc)
}()
return errc
}
// Wait until channel is closed or error is received.
func Wait(errc <-chan error) error {
for err := range errc {
if err != nil {
return err
}
}
return nil
}
// HandleError sets a handler function to be called anytime an error is received on the given channel.
func HandleError(errc <-chan error, handler func(error)) {
go func() {
for err := range errc {
if err != nil {
handler(err)
}
}
}()
}
|
Python
|
UTF-8
| 902 | 3.359375 | 3 |
[] |
no_license
|
def solution(begin, target, words):
arr = [begin] + words
lenw = len(words[0])
graph = {e: [] for e in arr}
for x in graph:
for y in arr:
if x != y and check(x, y, lenw):
graph[x].append(y)
minc = bfs(graph, begin, target)
return minc
def check(a, b, size):
cnt = 0
for i in range(size):
if a[i] != b[i]:
if cnt == 1:
return False
else:
cnt += 1
return True
def bfs(g, b, t):
from collections import deque
visited = {b: 0}
deq = deque([b])
while deq:
tmp = deq.popleft()
for next in g[tmp]:
if next not in visited:
visited[next] = visited[tmp] + 1
deq.append(next)
return visited.get(t, 0)
b_ = "hit"
t_ = "cog"
w_ = ["hot", "dot", "dog", "lot", "log"]
print(solution(b_, t_, w_))
|
Java
|
UTF-8
| 442 | 1.671875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package im.heart.cms.repository;
import java.math.BigInteger;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import im.heart.cms.entity.Ad;
import org.springframework.stereotype.Repository;
/**
*
* @author gg
* @desc Ad接口
*/
@Repository
public interface AdRepository extends JpaRepository<Ad, BigInteger> ,JpaSpecificationExecutor<Ad> {
}
|
C++
|
UTF-8
| 1,628 | 3.625 | 4 |
[] |
no_license
|
#include <iostream>
#include "vector_io.h"
std::string intToString(int & input){
std::string output = "";
bool got_minus = input < 0;
if (input == 0)
return std::string("0");
while(input) {
char c = std::abs(input % 10) + 48;
input /= 10;
output.push_back(c);
}
if (got_minus)
output.push_back('-');
return std::string(output.rbegin(), output.rend());
}
int stringToInt(const std::string & input){
int output = 0;
bool got_minus = input.at(0) == '-';
std::string::const_iterator ib = input.begin();
if (got_minus)
ib++;
std::string rest(ib, input.end());
for (auto c : rest){
if(!std::isdigit(c)){
throw std::invalid_argument("Character is not a digit");
}
output = 10 * output + (c - '0');
}
if (got_minus)
output *= -1;
return output;
}
int main() {
std::vector<std::string> input = {
"123",
"-23",
"0001",
"-0",
"a23",
"2a2",
"-a2",
"-2a"
};
for (auto s:input){
int to_int = 0;
try{
to_int = stringToInt(s);
} catch(const std::invalid_argument & e){
std::cout << s << " " << e.what() << std::endl;
continue;
}
std::cout << to_int << std::endl;
}
std::vector<int> ints = {
1,
23,
-0,
-12,
76567,
0
};
for (auto i:ints){
std::cout << intToString(i) << std::endl;
}
return 0;
}
|
Java
|
UTF-8
| 8,155 | 2.046875 | 2 |
[] |
no_license
|
package kirey.com.icap.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.google.firebase.iid.FirebaseInstanceId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import kirey.com.icap.R;
import kirey.com.icap.model.RecievedMessage;
import kirey.com.icap.model.UserData;
import kirey.com.icap.services.LogoutTask;
import kirey.com.icap.services.MessageMarkAsReadTask;
import kirey.com.icap.utils.ICAPApp;
import kirey.com.icap.utils.MessageListAdapter;
public class MainActivity extends AppCompatActivity {
String TAG = "MainActivity";
private Button subscribeGroup1Btn, subscribeGroup2Btn, subscribeGroup3Btn, loginBtn;
private TextView msgTextView, usernameTextView, firstNameTextView, lastNameTextView, emailTextView;
private LinearLayout deleteSelectionLinLay;
private ListView messagesListView;
private List<RecievedMessage> storedMessages;
MessageBroadcastReciver broadCastReciver;
MessageListAdapter listAdapter;
boolean deleteMode = false;
MenuItem deleteAll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.v("TOKEN", FirebaseInstanceId.getInstance().getToken());
final String userToken = ((ICAPApp)this.getApplicationContext()).getUserToken();
firstNameTextView = (TextView) findViewById(R.id.firstNameTextView);
lastNameTextView = (TextView) findViewById(R.id.lastNameTextView);
msgTextView = (TextView) findViewById(R.id.msgTextView);
loginBtn = (Button) findViewById(R.id.loginBtn);
usernameTextView = (TextView) findViewById(R.id.usernameTextView);
messagesListView = (ListView) findViewById(android.R.id.list);
emailTextView = (TextView) findViewById(R.id.emailTextView);
storedMessages = ((ICAPApp)this.getApplicationContext()).getStoredMessages();
//sort desc
Collections.sort(storedMessages, new Comparator<RecievedMessage>() {
@Override
public int compare(RecievedMessage r1, RecievedMessage r2) {
return Long.valueOf(r1.getMessageTimestamp()).compareTo(Long.valueOf(r2.getMessageTimestamp()));
}
});
//load userdata
UserData userData = ((ICAPApp) this.getApplicationContext()).loadUserData();
listAdapter = new MessageListAdapter(this,R.layout.message_list_item, storedMessages);
messagesListView.setAdapter(listAdapter);
emailTextView.setText(UserData.getInstance().getMail());
usernameTextView.setText(UserData.getInstance().getUsername());
firstNameTextView.setText(UserData.getInstance().getFirstName());
lastNameTextView.setText(UserData.getInstance().getLastName());
messagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
TextView c = (TextView) v.findViewById(R.id.titleItemTextView);
//if(!listAdapter.getItem(position).isRead())
//new MessageMarkAsReadTask(MainActivity.this).execute(listAdapter.getItem(position).getMessageId(), userToken);
}
});
messagesListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
//show delete all button in menu
deleteAll.setVisible(true);
//show delete option for each list item
listAdapter.showDeleteSection(true);
deleteMode = true;
refreshMessages();
return true;
}
});
//handle notification message if any
/* if (getIntent().getExtras() != null) {
String data = (String) getIntent().getExtras().get("messageText");
if(data != null)
refreshTextMessage(data);
}*/
//refreshTextMessage(((KgriApp) this.getApplicationContext()).getMessageRecieved());
refreshMessages();
}
private class MessageBroadcastReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshMessages();
}
}
private void refreshMessages() {
storedMessages = ((ICAPApp)this.getApplicationContext()).getStoredMessages();
if(storedMessages.size() == 0)
msgTextView.setVisibility(View.VISIBLE);
//refresh list of messages
else {
msgTextView.setVisibility(View.GONE);
Collections.sort(storedMessages, new Comparator<RecievedMessage>() {
@Override
public int compare(RecievedMessage r1, RecievedMessage r2) {
return Long.valueOf(r2.getMessageTimestamp()).compareTo(Long.valueOf(r1.getMessageTimestamp()));
}
});
}
listAdapter.refresh(storedMessages);
}
@Override
protected void onStop() {
super.onStop();
if(broadCastReciver!=null)
unregisterReceiver(broadCastReciver);
}
protected void onResume() {
super.onResume();
refreshMessages();
broadCastReciver = new MessageBroadcastReciver();
registerReceiver(broadCastReciver, new IntentFilter("sendData"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
new LogoutTask(this).execute();
return true;
case R.id.action_settings:
startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
return true;
case R.id.action_delete:
ArrayList<RecievedMessage> listForDelete= listAdapter.getCheckedItems();
for (RecievedMessage msg:listForDelete) {
((ICAPApp)this.getApplicationContext()).deleteMessageFromStorage(msg.getId());
}
listAdapter.showDeleteSection(false);
deleteMode = false;
deleteAll.setVisible(false);
refreshMessages();
return true;
case R.id.action_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_action_bar, menu);
deleteAll = menu.findItem(R.id.action_delete);
return true;
}
@Override
public void onBackPressed() {
if(deleteMode) {
listAdapter.showDeleteSection(false);
listAdapter.uncheckAll();
deleteMode = false;
deleteAll.setVisible(false);
refreshMessages();
}
else super.onBackPressed();
}
}
|
Markdown
|
UTF-8
| 1,094 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
---
title: Axios and Content-Type
date: 2020-02-11
tag: JS
---
import { MDXTextLink as TextLink } from "../../../src/components/mdx-comps"
During work today, my colleague Mo and I were having issues making `DELETE` requests to a
micro service that he had created. In Postman and the standard XHR function that ships with
Google Chrome, the delete requests were going through with no problem but when we tried to make a call
via `axios.delete(url/id)`, the server kept returning a 400 error.
The truly peculiar thing was that making a call in the following manner worked:
```js
axios({
method: "DELETE",
url: `url/${id}`,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer SOME_TOKEN",
},
})
```
However, this failed:
```js
axios.delete(`url/${id}`, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer SOME_TOKEN",
},
})
```
Long story short, TIL: `axios.delete` will drop the content-type header (which is the right behavior) so
my buddy Mo had to change up his micro service endpoint to not expect a content type 😁!
|
Java
|
UTF-8
| 2,189 | 2.28125 | 2 |
[] |
no_license
|
package com.example.greentea.ViewHolder;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.greentea.R;
import java.util.ArrayList;
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.ViewHolder> {
ArrayList cmt_name, cmt_date, cmt, cmt_rating_bar;
Context context;
public CommentAdapter(Context context, ArrayList cmt_name, ArrayList cmt_date, ArrayList cmt, ArrayList cmt_rating_bar){
this.context = context;
this.cmt_name = cmt_name;
this.cmt_date = cmt_date;
this.cmt = cmt;
this.cmt_rating_bar = cmt_rating_bar;
}
@NonNull
@Override
public CommentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_comment_item, parent, false);
return new CommentAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CommentAdapter.ViewHolder holder, int position) {
holder.comment_name.setText(cmt_name.get(position).toString());
holder.comment_date.setText(cmt_date.get(position).toString());
holder.comment.setText(cmt.get(position).toString());
holder.comment_rating_bar.setRating(Long.parseLong(cmt_rating_bar.get(position).toString()));
}
@Override
public int getItemCount() {
return cmt_name.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView comment_name, comment_date, comment;
RatingBar comment_rating_bar;
public ViewHolder(@NonNull View itemView){
super(itemView);
comment_name = itemView.findViewById(R.id.txt_comment_name);
comment_date = itemView.findViewById(R.id.txt_comment_date);
comment = itemView.findViewById(R.id.txt_comment);
comment_rating_bar = itemView.findViewById(R.id.txt_rating_bar);
}
}
}
|
Java
|
UTF-8
| 8,348 | 2.546875 | 3 |
[] |
no_license
|
package com.haoxueren.demo.rxjava;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.haoxueren.demo.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
public class RxJavaActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rxjava);
Observable<Integer> observable1 = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
Thread.sleep(1);
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(3);
emitter.onComplete();
}
});
// 第二个被观察者
Observable<Integer> observable2 = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
Thread.sleep(3);
emitter.onNext(4);
emitter.onNext(5);
emitter.onNext(6);
emitter.onComplete();
}
});
Observable.zip(observable1, observable2, new BiFunction<Integer, Integer, Object>() {
@Override
public Object apply(@NonNull Integer integer, @NonNull Integer integer2) throws Exception {
return integer + ":" + integer2;
}
}).subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
System.out.println("accept:" + o);
}
});
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(1);
emitter.onComplete();
}
}).doOnNext(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
System.out.println("doOnNextConsumer");
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
System.out.println("subscribeConsumer");
}
});
}
private void startWith(Observable<Integer> observable1, Observable<Integer> observable2) {
observable2.startWith(observable1).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
System.out.println(integer);
}
});
}
private void concat() {
// 第一个被观察者
Observable<Integer> observable1 = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(3);
emitter.onComplete();
}
});
// 第二个被观察者
Observable<Integer> observable2 = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
emitter.onNext(4);
emitter.onNext(5);
emitter.onNext(6);
emitter.onComplete();
}
});
// 连接两个被观察者
Observable.concat(observable1, observable2).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
System.out.println(integer);
}
});
}
private void concatJust() {
Observable<Integer> just1 = Observable.just(1, 2, 3);
Observable<Integer> just2 = Observable.just(4, 5, 6);
Observable.concat(just1, just2).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
System.out.println(integer);
}
});
}
private void toList() {
Observable.just(1, 2, 3).toList().subscribe(new Consumer<List<Integer>>() {
@Override
public void accept(List<Integer> list) throws Exception {
System.out.println(list);
}
});
}
private void map() {
Observable.just(10, 20, 30).map(new Function<Integer, String>() {
@Override
public String apply(@NonNull Integer integer) throws Exception {
return String.format(Locale.CHINA, "%d%%", integer);
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
System.out.println(s);
}
});
}
private void interval() {
int initialDelay = 1;
int intervalPeriod = 3;
TimeUnit timeUnit = TimeUnit.SECONDS;
Scheduler scheduler = Schedulers.computation();
Observable.interval(initialDelay, intervalPeriod, timeUnit, scheduler)
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long l) throws Exception {
System.out.println(l);
}
});
}
private void fromIterable() {
List<String> list = new ArrayList<>();
list.add("RxJava");
list.add("Retrofit");
list.add("GreenDao");
Observable.fromIterable(list).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
System.out.println(s);
}
});
}
private void fromArray() {
Integer[] integers = {1, 2, 3, 4, 5, 6};
Observable.fromArray(integers).subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
System.out.println(integer);
}
});
}
private void just() {
Observable.just("java", "kotlin", "python").subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
System.out.println(s);
}
});
}
// 通过Observable.create()创建一个被观察者
private void create() {
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception {
emitter.onNext("emitter.onNext01");
emitter.onNext("emitter.onNext02");
emitter.onError(new NullPointerException());
emitter.onComplete();
}
}).subscribe(new Observer<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull String s) {
System.out.println(s);
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println("onError");
}
@Override
public void onComplete() {
System.out.println("onComplete");
}
});
}
public void map(View view) {
MapTest.test();
}
}
|
Java
|
UTF-8
| 1,507 | 3.546875 | 4 |
[] |
no_license
|
import java.util.Scanner;
import org.jfugue.player.Player;
public class main{
public static void printmenu() {
System.out.println("Menu:");
System.out.println("1: Interval Training");
System.out.println("2: Pitch Training");
System.out.println("3: Triad Training");
System.out.println("4: Inversion Training");
System.out.println("5: Rhythm Training");
System.out.println("PUT MODES HERE");
System.out.println("Q: Quit");
System.out.print("Select one of the choices above to begin: ");
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Player player = new Player();
Intervals intervalTrainer = new Intervals();
Pitches pitchTrainer = new Pitches();
Triads triadTrainer = new Triads();
Inversions inversionTrainer = new Inversions();
Rhythms rhythmTrainer = new Rhythms();
System.out.println("Welcome to the Music Theory Study Buddy.\n");
printmenu();
String res = scanner.next();
while(!(res.equals("Q"))){
if(res.equals("1")) {
intervalTrainer.act(scanner, player);
} else if(res.equals("2")) {
pitchTrainer.act(scanner, player);
} else if(res.equals("3")) {
triadTrainer.act(scanner, player);
} else if(res.equals("4")) {
inversionTrainer.act(scanner, player);
} else if(res.equals("5")) {
rhythmTrainer.act(scanner, player);
}
System.out.println("\n\nWelcome back to the main menu.\n");
printmenu();
res = scanner.next();
}
System.exit(0);
}
}
|
C++
|
UTF-8
| 2,757 | 2.796875 | 3 |
[] |
no_license
|
#include <cstring>
#include <iostream>
#include "adt/array_size.h"
#include "deliantra/data/glyph.h"
#include "deliantra/data/map.h"
#include "trenderer.h"
void
renderer::draw_map () const
{
for (size_t y = 0; y < array_size (win); y++)
{
wchar_t buf[array_size (win[y]) + 1];
memcpy (buf, win[y], sizeof win[y]);
buf[array_size (win[y])] = L'\0';
printf ("%ls\n", buf);
}
}
void
renderer::drawinfo (int level, std::string const &msg)
{
std::cout << "drawinfo: " << msg << '\n';
}
static u16
select_face (u16 const (&face)[3], int layer)
{
if (layer == -1)
return face[2]
? face[2]
: face[1]
? face[1]
: face[0]
;
return face[layer];
}
void
renderer::map (data::map const &map)
{
static int const layer = -1;
for (size_t y = 0; y < array_size (win); y++)
for (size_t x = 0; x < array_size (win[y]); x++)
win[y][x] = L'_';
static data::glyph const space = { { { 0, 0, L'?' }, { 0, 0, L'?' } } };
static data::glyph const player = { { { 0, 0, L'@' }, { 0, 0, L'@' } } };
int const playerx = (W - !(W % 2)) / 2;
int const playery = (H - !(H % 2)) / 2;
int const offx = (map.w - W) / 2;
int const offy = (map.h - H) / 2;
return_unless (!data::glyphs.empty ());
for (int y = 0; y < H; y++)
{
int const mapy = y + map.y + offy;
if (!map.rows.has (mapy))
continue;
auto const &row = map.rows[mapy];
for (int x = 0; x < W; x++)
{
int const mapx = x + map.x + offx;
if (!row.has (mapx))
continue;
data::map::cell const &cell = row[mapx];
u32 const face = select_face (cell.face, layer);
data::glyph const *glyph;
int const winy = y * 1;
int const winx = x * 2;
if (x == playerx && y == playery)
glyph = &player;
else if (face && face < data::glyphs.size ()) // TODO: warn about face >= size
glyph = &data::glyphs[face];
else
glyph = &space;
return_unless (winy >= 0);
return_unless (winx >= 0);
return_unless (winy < int (array_size ( win)));
return_unless (winx < int (array_size (*win)));
win[winy][winx + 0] = (*glyph)[0].text;
win[winy][winx + 1] = (*glyph)[1].text;
}
}
}
void
renderer::map_scroll (int dx, int dy)
{
std::cout << "map_scroll " << dx << ' ' << dy << '\n';
}
void
renderer::msg (int level, std::string const &channel, std::string const &msg)
{
std::cout << channel << ": " << msg << '\n';
}
void
renderer::newmap ()
{
std::cout << "newmap\n";
}
void
renderer::stats (data::statistics const &stats)
{
}
|
Java
|
UTF-8
| 853 | 2.328125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.beanbox.context.suppport;
import com.beanbox.beans.factory.support.DefaultListableBeanFactory;
import com.beanbox.beans.reader.support.XmlBeanDefinitionReader;
import com.beanbox.context.suppport.AbstractRefreshableApplicationContext;
/**
* @author: @zyz
* 模板模式
*/
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableApplicationContext {
@Override
protected void loadBeanDefinition (DefaultListableBeanFactory beanFactory) {
XmlBeanDefinitionReader beanDefinitionReader=new XmlBeanDefinitionReader (beanFactory,this);
String[] configurations=getConfigLocations();
if (configurations!=null)
{
beanDefinitionReader.loadBeanDefinitions (configurations);
}
}
/**
* 获得所有需要加载的Xml文件路径
* @return
*/
protected abstract String[] getConfigLocations ();
}
|
Python
|
UTF-8
| 9,230 | 3 | 3 |
[] |
no_license
|
'''
Bio 331 HW 3: Random Walks
Author: Sol Taylor-Brill
Date: 10/03/19
'''
import matplotlib.pyplot as plt
import random
import math
from graphspace_python.api.client import GraphSpace
from graphspace_python.graphs.classes.gsgraph import GSGraph
graphspace = GraphSpace("[email protected]", "solTB") #Starting GraphSpace session
def main():
foutput = FileReader("EGFR1-edges.txt")
nodes = foutput[0]
edges = foutput[1]
interactDict = foutput[2]
s="EGF" #the starting node
Tprob = 1000
Tsim = 100000
q = 0.95
#run either add_edges OR add_self_loops to get either out connections to source node or self loops
Gin, Gout = Neighbor_Dicts(nodes,edges)
#G_in, G_out = add_edges(Gin, Gout, nodes,edges,s)
G_in, G_out = add_self_loops(Gin, Gout, nodes,edges)
X, TDict = rw_probs(nodes,G_in,G_out,s,Tprob,q)
TimeDict = rw_simulate(nodes,G_out,s,Tsim,q)
Graph_Maker(nodes,edges,TimeDict,interactDict)
'''
TpList = [10,100,1000,10000]
TsList = [10,100,1000, 10000]
ErrorList = []
for i in range(len(TpList)):
X, TDict = rw_probs(nodes,G_in,G_out,s,TpList[i],q)
TimeDict = rw_simulate(nodes,G_out,s,TsList[i],q)
NormTimeDict = Normalizer(TimeDict)
Error = Error_Calc(nodes,NormTimeDict,TDict,TpList[i])
ErrorList.append(Error)
print(ErrorList)
'''
return
#This function just reads the edgefile. It's based on a function from HW2 but it uses lists instead of sets
#and doesn't include the edge type information
def FileReader(f):
print("reading " + f)
EdgeList = open(f,'r')
nodes = []
edges = []
InteractDict = {}
#The following for loop goes through all the lines in the file and adds nodes and edges to their lists
#It also makes an edge->interaction dictionary
for l in EdgeList:
line = str(l)
nodesinline = line.split()
n1 = nodesinline[0]
n2 = nodesinline[1]
file_edge = [n1,n2] #doesn't include edge type
callstring = str(n1 + n2)
Interaction = nodesinline[2]
InteractDict[callstring] = Interaction
if file_edge not in edges:
edges.append(file_edge)
if n1 not in nodes:
nodes.append(n1)
if n2 not in nodes:
nodes.append(n2)
return nodes, edges, InteractDict
#makes Gin and Gout (in neighbors and out neighbors) dictionaries
#This function was copied from Lab 5
def Neighbor_Dicts(nodes,edges):
Gin = {} #dictionary node->in neighbors [0]
Gout = {} #dictionary node->out neighbors [1]
for n in nodes:
Gin[n] = []
Gout[n] =[]
for e in edges:
NinList = Gin[e[1]] #calling all the in neighbors of the out node (second node)
NoutList = Gout[e[0]] #calling all the out neighbors of the in node (first node)
NinList.append(e[0]) #adding the first node (in node) to the list of in neighbors of the out node
NoutList.append(e[1]) #adding the second node (out node) to the in nodes list of out neighbors
Gin[e[1]] = NinList
Gout[e[0]] = NoutList
return Gin, Gout
#This functions adds extra edges to the graph so that any node that has no outgoing edges will have an edge to s
def add_edges(Gin,Gout,nodes,edges,s):
for v in nodes: #goes through all the nodes in the graph
if len(Gout[v]) == 0: #if the node has no outgoing neighbors
edges.append((v,s))
Gout[v] = [s] #the list of out-neighbors of v = s
inputval = Gin[s] + [v] #adds v to the list of in-neighbors of s
Gin[s] = inputval #updates in-neighbors of s
return Gin, Gout
def add_self_loops(Gin,Gout,nodes,edges):
for v in nodes: #goes through all the nodes in the graph
if len(Gout[v]) == 0: #if the node has no outgoing neighbors
edges.append((v,v))
Gout[v] = [v] #the list of out-neighbors of v = v
inputval = Gin[v] + [v] #adds v to the list of in-neighbors of v
return Gin, Gout
# This function intakes a list of nodes, the Gin/Gout dictionaries, a starting node, s, timesteps, T, and probability value, q.
#This function was copied from Lab 5
def rw_probs(nodes,Gin,Gout,s,T,q):
table_Dict = {} #a dictionary that will contain the dictionary of values for each time step
table_list = [] #a list of lists
#this part just initializes a dictionary of dictionaries so that it will run more easily.
for t in range(0,(T+1)):
nodedict = {}
for n in nodes:
nodedict[n] = []
table_Dict[t]= nodedict
for node in nodes:
if node == s:
table_Dict[0][node]=1
else:
table_Dict[0][node]=0
for t in range(1,(T+1)):
for n in nodes: #goes through all nodes
val = 0
for x in Gin[n]: #goes through all in-neighbors
inputval = table_Dict[(t-1)][x]/len(Gout[x])
val = val + inputval#making a sum of all p(u)^t-1
eq_val = q*val + ((1-q)*table_Dict[0][n]) #probability value for each node in time, t
table_Dict[t][n] = eq_val #adding the value to the table_Dict
for call in table_Dict:
tlist = []
for val in table_Dict[call]:
tlist.append(table_Dict[call][val])
table_list.append(tlist) #making a list of lists
return table_list, table_Dict
#This function simulates a random walker moving through a graph and
#outputs a dictionary of times a node was visited by a random walker
#inputs = nodes, G_out (dictionary node->Nout), s (source node), T (time steps), q (probability [0-1])
def rw_simulate(nodes,G_out,s,T,q):
TimeDict = {} #Dictionary node->times walker visited
for n in nodes: #initializing TimeDict w/ all nodes except s at 0
if n == s:
TimeDict[n] = 1 #because it starts at 1
else:
TimeDict[n] = 0 #all other nodes initialized at 0
#Moving through time steps
CurrentNode = s #where the traveler is at.
for t in range(1,T):
start = CurrentNode
n_out = G_out[start] #a list of all outgoing nodes of the current node
num = random.random() #generates random number between 0 and 1
if num > q:
CurrentNode = s #redefining the current node. Teleport back to source
else:
newnode = random.choice(n_out) #choose random outgoing neighbor as new current node
CurrentNode = newnode
numtimes = TimeDict[CurrentNode] + 1 #adds 1 to the node that was just moved to
TimeDict[CurrentNode] = numtimes #redefines node that just got moved to
return TimeDict
#Normalizes the TimeDict values so that they are between 0 and 1
def Normalizer(TimeDict):
TimeList = [] #a list of the number of time each node has been visited
NormTimeDict = {}
for node in TimeDict:
TimeList.append(TimeDict[node])
for n in TimeDict:
NormTimeDict[n] = TimeDict[n]/max(TimeList)
return NormTimeDict
#calculates the error (sum for all the nodes of the difference between the simulated value and calculated value)
def Error_Calc(nodes, NormTimeDict, TableDict, Tprob):
sumval= 0
for n in nodes:
errorval = (NormTimeDict[n] - TableDict[Tprob][n])**2 #squared difference
sumval = sumval + errorval #sum of squared differences
print(sumval)
return sumval
#Makes the graph.
#Taken from Lab 4
def Graph_Maker(node_list, edge_list, TimeDict,interactDict):
G = GSGraph()
G.set_name('Sol_Self-Loop_Walk_Graph')
G.set_tags(['HW3'])
#This section transforms and normalizes the data
Timelist = [] #I'm just making a list of counts to use to calculate node color
logList = []
NewTimeDict = {}
for noden in TimeDict: #just making a list of values in the dictionary (useful for nodecolor)
newval = TimeDict[noden] + 1 #adds 1 to each countso there are no zeros
NewTimeDict[noden] = newval #adds the value
if NewTimeDict[noden] not in Timelist:
Timelist.append(NewTimeDict[noden]) #adds the value to a list
for val in Timelist: #to figure out the max log transformed value
logv = math.log(val)
logList.append(logv)
for n in NewTimeDict: #log transforms values and then normalizes
logval = math.log(NewTimeDict[n])
NewTimeDict[n] = logval/max(logList) #new value is the log of the count normalized by dividing by the max log value
#This section makes the graph and updates on GraphSpace
seenedges = [] # a list of edges that have gone over so there aren't multiple edges between two nodes
for n in node_list:
poplabel = "Count: " + str(TimeDict[n]) + ";Normalized: " + str(NewTimeDict[n])
G.add_node(n,popup=poplabel, label=n)
blue = NewTimeDict[n] #a value between 0 and 1 (most visited = most blue)
red = 1-blue #opposite of blue
nodecolor = rgb_to_hex(red,0,blue)
G.add_node_style(n, width = 20, height = 20, color=nodecolor,)
for e in edge_list:
namecall = str(e[0] + e[1]) #to call up interaction type for the popup
if namecall in interactDict:
plabel = interactDict[namecall]
else:
plabel = "N/A"
if [e[1],e[0]] in edge_list: #if the inverse exists
if e not in seenedges:
G.add_edge(e[0],e[1], popup = plabel, directed=False)
seenedges.append(e)
seenedges.append([e[1],e[0]])
else: #if the graph isn't bidirectional add an arrow
G.add_edge(e[0],e[1],popup = plabel, directed=True)
G.add_edge_style(e[0],e[1], width = 2,directed=True)
graphspace.post_graph(G)
print("Graph Updated")
'''
This function just outputs a hex color code from inputs of the amount of red and blue calculated from layer in Graph_Maker()
This function was just copied from the lab 4 handout.
'''
def rgb_to_hex(red,green,blue):
maxHexValue = 255
r = int(red*maxHexValue)
g = int(green*maxHexValue)
b = int(blue*maxHexValue)
RR = format(r,'02x')
GG = format(g,'02x')
BB = format(b,'02x')
colorname = '#' + RR + GG + BB
return colorname
main()
|
C#
|
UTF-8
| 5,987 | 2.546875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CarInsurance.Models;
namespace CarInsurance.Controllers
{
public class InsureeController : Controller
{
private InsuranceEntities db = new InsuranceEntities();
// GET: Insuree
public ActionResult Index()
{
return View(db.Insurees.ToList());
}
// GET: Insuree/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Insuree insuree = db.Insurees.Find(id);
if (insuree == null)
{
return HttpNotFound();
}
return View(insuree);
}
// GET: Insuree/Create
public ActionResult Create()
{
return View();
}
// POST: Insuree/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType,Quote")] Insuree insuree)
{
if (ModelState.IsValid)
{
insuree.Quote = calculateQuote(insuree);
db.Insurees.Add(insuree);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(insuree);
}
public static decimal calculateQuote(Insuree insuree)
{
decimal rate = 50.0M;
DateTime now = DateTime.Today;
var age = now.Year - insuree.DateOfBirth.Year;
if (age <= 18)
{
rate += 100.0M;
}
if (age >= 19 && age <= 25)
{
rate += 50.0M;
}
if (age > 25)
{
rate += 25.0M;
}
if (insuree.CarYear < 2000)
{
rate += 25.0M;
}
if (insuree.CarYear > 2015)
{
rate += 25.0M;
}
if (insuree.CarMake.ToLower() == "porche")
{
rate += 25.0M;
}
if (insuree.CarMake.ToLower() == "porche" && insuree.CarModel.ToLower() == "911 carrera")
{
rate += 25.0M;
}
if (insuree.SpeedingTickets > 0)
{
rate += (insuree.SpeedingTickets * 10);
}
if (insuree.DUI)
{
rate += (rate * .25M);
}
if (insuree.CoverageType)
{
rate += (rate * .5M);
}
insuree.Quote = rate;
return insuree.Quote;
//using (InsuranceEntities db = new InsuranceEntities())
//{
// var create = new Insuree();
// create.FirstName = firstName;
// create.LastName = firstName;
// create.EmailAddress = emailAddress;
// create.DateOfBirth = dateOfBirth;
// create.CarYear = carYear;
// create.CarMake = carMake;
// create.CarModel = carModel;
// create.DUI = DUI;
// create.SpeedingTickets = speedingTickets;
// create.CoverageType = coverageType;
// create.Quote = rate;
// db.Insurees.Add(create);
// db.SaveChanges();
//}
}
// GET: Insuree/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Insuree insuree = db.Insurees.Find(id);
if (insuree == null)
{
return HttpNotFound();
}
return View(insuree);
}
// POST: Insuree/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType,Quote")] Insuree insuree)
{
if (ModelState.IsValid)
{
db.Entry(insuree).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(insuree);
}
// GET: Insuree/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Insuree insuree = db.Insurees.Find(id);
if (insuree == null)
{
return HttpNotFound();
}
return View(insuree);
}
// POST: Insuree/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Insuree insuree = db.Insurees.Find(id);
db.Insurees.Remove(insuree);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
Java
|
UTF-8
| 1,338 | 3.046875 | 3 |
[] |
no_license
|
package by.epam_training.java_online.module5.task1_text_file.logic;
import by.epam_training.java_online.module5.task1_text_file.entity.Directory;
public class FileLogic {
private final static FileLogic instance = new FileLogic();
private FileLogic() {
}
public static FileLogic getInstance() {
return instance;
}
public Directory getSuperDirectory(Directory dir) {
int superDirIndex = dir.getPath().size() - 2;
return dir.getPath().get(superDirIndex);
}
public boolean isDirectoryExists(Directory dir) {
if (dir.getPath() == null) {
return false;
} else {
boolean exists = true;
for (Directory d : dir.getPath()) {
if (d.getName() == null)
exists = false;
}
return exists;
}
}
public void deleteDirectory(Directory dir) {
if (dir.getDirectories().size() > 0) {
for (Directory d : dir.getDirectories()) {
deleteDirectory(d);
}
}
dir.setName(null);
dir.setPath(null);
dir.setDirectories(null);
dir.setFiles(null);
}
public boolean checkName(Directory dir, String nameToCheck) {
if (dir.getDirectories() == null) {
return false;
} else {
for (Directory d : dir.getDirectories()) {
if (d.getName().equals(nameToCheck))
return true;
}
}
return false;
}
}
|
JavaScript
|
UTF-8
| 1,537 | 3.453125 | 3 |
[] |
no_license
|
// task 1
// Make a page that has on it an element that is 100px by 100px in size,
// has absolute positioning, and has a solid background color.Add an event
// handler that makes this box center itself directly under the user's mouse
// pointer as it is moved across the screen.
(function () {
var elem = document.querySelector(".sq");
// console.log(elem);
document.addEventListener("mousemove",
function (e) {
var x = e.clientX / 2;
var y = e.clientY / 2;
elem.style.left = x + "px";
elem.style.top = y + "px";
});
})();
// unfortunately not CENTERING itself under the user's mouse:/
// task 2
// Make a page that has a <textarea> element on it. As the user types visible
// characters into this field, the characters should be replaced with the characters
// in the corresponding position in the Gettysburg Address.
// (Note - you can get and set the text in a <textarea> through its value property.)
(function () {
var txt = document.querySelector("#text");
// console.log(txt);
var address = "Address Delivered at the Dedication of the Cemetery at Gettysburg. Abraham Lincoln, November 19, 1863. Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.";
txt.addEventListener("input", function (e) {
var s = address.slice(0, e.target.value.length);
e.target.value = s;
return s;
})
})();
|
JavaScript
|
UTF-8
| 519 | 2.75 | 3 |
[] |
no_license
|
class Monitor {
Promise(source, handler, interval) {
source()
.then(value => {
if (value !== this.value) {
handler(this.value = value)
}
})
.then(() => setTimeout(() =>
this.Promise(...arguments), interval)
)
.catch(err => console.error(err))
}
Callback(process, handler) {
return value => {
value = process(value)
if (value !== this.value) {
handler(this.value = value)
}
}
}
}
module.exports = Monitor
|
Markdown
|
UTF-8
| 1,862 | 2.59375 | 3 |
[
"CC-BY-3.0"
] |
permissive
|
---
name: "article"
path: "/article1"
date: 2019-08-01T17:12:33.962Z
title: "Рекорд по набору текста с помощью нейроинтерфейса"
pre: "В Китае установили рекорд по набору текста с помощью нейроинтерфейса: на одну букву по полсекунды. Аппарат продемонстрировали на Всемирной конференции роботов. Вэй Сывэнь, сотрудник Тяньцзинского университета, создал специальный "
description: "В Китае установили рекорд по набору текста с помощью нейроинтерфейса: на одну букву по полсекунды. Аппарат продемонстрировали на Всемирной конференции роботов.
Вэй Сывэнь, сотрудник Тяньцзинского университета, создал специальный нейроинтерфейс для обмена информацией между мозгом и компьютером. Его программа считывает биотоки мозга со скоростью 691,55 бит в минуту.
Нейроинтерфейс определяет нужную букву английского алфавита со 100% точностью за 0,4 секунды. Для сравнения, точность распознавания подобного аппарата от Facebook составляет только 76%. Это при условии, что круг тем в случае с Facebook был ограничен, а обещанная скорость не превышает 100 слов в минуту."
---
Oooooh-weeee, my first news post!
|
PHP
|
UTF-8
| 1,116 | 2.984375 | 3 |
[] |
no_license
|
<?php
namespace VkApiSDK\ApiTypes\Database;
use VkApiSDK\BaseType;
use VkApiSDK\ApiTypes;
class City extends BaseType {
protected static $requiredParams = [];
protected static $map = [
'id' => true,
'title' => true,
'area' => true,
'region' => true,
'important' => ApiTypes\Base\BoolInt::class,
];
protected $id;
protected $title;
protected $area;
protected $region;
protected $important;
public function setId($id) {
$this->id = (int) $id;
}
public function getId() {
return (int) $this->id;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setArea($area) {
$this->area = $area;
}
public function getArea() {
return $this->area;
}
public function setRegion($region) {
$this->region = $region;
}
public function getRegion() {
return $this->region;
}
public function setImportant($important) {
$this->important = $important;
}
public function getImportant() {
return $this->important;
}
}
?>
|
Java
|
UTF-8
| 572 | 2.90625 | 3 |
[] |
no_license
|
package com.yc.model.Observer;
/**
* @author cfun
* @description 李斯
* @date 2019-11-14
*/
public class LiSi implements IliSi {
@Override
public void update(String str) {
System.out.println("李斯:观察到韩非子活动,开始向老板汇报了...");
this.reportToQinShiHuang(str);
System.out.println("李斯:汇报完毕...\n");
}
//汇报给秦始皇
private void reportToQinShiHuang(String reportContext){
System.out.println("李斯:报告,秦老板!韩非子有活动了--->"+reportContext);
}
}
|
C
|
UTF-8
| 1,138 | 3.671875 | 4 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
/* LEE LAS INSTRUCCIONES COMPLETAS ANTES DE EJECUTAR ESTE PROGRAMA.
1) Observa con detenimiento este código.
2) Escribe en un comentario el output que esperas ver en la consola.
3) Compila y ejecuta el programa.
4) Compara tus predicciones con el resultado
5) Explica con tus palabras por qué sucede esto.
MIS PREDICCIONES:
|-------------------|
| OUTPUT ESPERADO |
|-------------------|
| |
| |
| |
| |
| |
|===================|
*/
void foo(int a)
{
// which value does a have on each execution?
// is the a in the main function modified?
a = a + 10;
printf("inside foo: %d\n", a);
}
void bar(int a)
{
// which value does a have on each execution?
// is the a in the main function modified?
a = 0;
printf("inside bar: %d\n", a);
}
int main()
{
// is this value modified?
int a = 10;
printf("first time: %d\n", a);
foo(a);
printf("after foo: %d\n", a);
bar(a);
printf("after bar: %d\n", a);
}
|
JavaScript
|
UTF-8
| 3,533 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
/**
* BiliOB-Watcher
*
* @author FlyingSky-CN
* @package audioVisual
*/
$('#music').attr('width', audioVisualConfig.width);
$('#music').attr('height', audioVisualConfig.height);
var canvasCtx = document.getElementById("music").getContext("2d");
var AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
var audioContext = new AudioContext();
var audioVisual = (data) => audioContext.decodeAudioData(data, (buffer) => {
/**
* AudioBufferSourceNode
* 用于播放解码出来的 buffer 的节点
*/
audioBufferSourceNode = audioContext.createBufferSource();
/**
* AnalyserNode
* 用于分析音频频谱的节点
*/
var analyser = audioContext.createAnalyser();
/**
* 音频频谱的密集程度
*/
analyser.fftSize = audioVisualConfig.fftSize;
/**
* 连接节点,audioContext.destination 是音频要最终输出的目标。
* 所以所有节点中的最后一个节点应该再连接到 audioContext.destination 才能听到声音。
*/
audioBufferSourceNode.connect(analyser);
analyser.connect(audioContext.destination);
/**
* 播放音频
*/
audioBufferSourceNode.buffer = buffer; //回调函数传入的参数
audioBufferSourceNode.start(); //部分浏览器是 noteOn() 函数,用法相同
/**
* 可视化
*/
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
canvasCtx.clearRect(0, 0, audioVisualConfig.width, audioVisualConfig.height);
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
canvasCtx.fillStyle = audioVisualConfig.background;
canvasCtx.fillRect(0, 0, audioVisualConfig.width, audioVisualConfig.height);
var space = audioVisualConfig.space * audioVisualConfig.multiple;
var barWidth = audioVisualConfig.width / bufferLength - space;
var barHeight;
var x = 0;
/**
* 绘制圆角矩形(纯色填充)
*
* @param {object} context canvasContext
* @param {number} x x
* @param {number} y y
* @param {number} w width
* @param {number} h height
* @param {number} r round
*/
var roundRectColor = (context, x, y, w, h, r) => {
context.save();
context.fillStyle = audioVisualConfig.fill;
context.strokeStyle = audioVisualConfig.fill;
context.lineJoin = 'round';
context.lineWidth = r;
context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);
context.fillRect(x + r, y + r, w - r * 2, h - r * 2);
context.stroke();
context.closePath();
}
for (var i = 0; i < bufferLength - audioVisualConfig.ignore; i++) {
barHeight = dataArray[i] / 255 * (audioVisualConfig.height - barWidth * audioVisualConfig.basic) + barWidth * audioVisualConfig.basic;
roundRectColor(
canvasCtx,
x,
(audioVisualConfig.way === 'top') ? 0 :
(audioVisualConfig.way === 'bottom') ? audioVisualConfig.height - barHeight :
(audioVisualConfig.height - barHeight) / 2,
barWidth,
barHeight,
audioVisualConfig.round ? barWidth : 0
);
x += barWidth + space;
}
};
draw();
});
|
Ruby
|
UTF-8
| 679 | 2.84375 | 3 |
[] |
no_license
|
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'csv'
require 'pry'
zipcodes = []
CSV.foreach("zipcode.csv", headers: true) do |row|{ zipcode: row['zipcode'] }
row.each { |key,value| zipcodes << value }
end
zipcodes.each do |code|
url = "http://www.zillow.com/homes/#{code}_rb"
html = open(url)
scrape = Nokogiri::HTML(html)
scrape.css(".property-info").each do |info|
if info.css(".routable") != nil
size = info.css(".property-data").text
price = info.css(".price-large").text
address = info.css(".routable").text
end
CSV.open("zillow_info.csv", 'a') do |csv|
csv << [address, size, price]
end
end
end
|
Markdown
|
UTF-8
| 654 | 2.546875 | 3 |
[] |
no_license
|
# Jeff’s dotfiles
Mostly just my vim, tmux, and bash configs.
### Install
Warning, this will replace some files in your home directory, and includes my own opinionated configs; read the source and use with care.
1. Clone this repo.
2. Symlink the files in this repo to your home directory. You'll also need to clone the vim and tmux plugin managers.
(The bootstrap script will do step 2 for you.)
```bash
git clone https://github.com/jschomay/.dotfiles.git ~/.dotfiles
cd ~/.dotfiles && source bootstrap.sh && cd -
```
For now, you need to install vim, tmux, brew, and what ever else on your own.
Also, add your name and email to `.gitconfg`.
|
JavaScript
|
UTF-8
| 158 | 2.921875 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Write your code here
let num1 = 31;
let num2 = 2;
let multiply = num1 * num2;
let random = Math.random();
let mod = 4%10;
let max = Math.max(5,20,15);
|
C++
|
UTF-8
| 216 | 3.171875 | 3 |
[] |
no_license
|
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
char a;
cout << "enter a symbol: ";
cin >> a;
if (isalpha(a)){
cout << "alphabet";}
else{
cout << "not alphabet";}
return 0;
}
|
Swift
|
UTF-8
| 677 | 2.59375 | 3 |
[] |
no_license
|
//
// CommentCell.swift
// TessafoldTest
//
// Created by Ali jaber on 26/04/2021.
//
import UIKit
class CommentCell: UITableViewCell {
@IBOutlet weak var commentLabel: UILabel!
var comment: Comment? {
didSet {
setUI()
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setUI() {
if let comment = comment?.body {
commentLabel.text = comment
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
Markdown
|
UTF-8
| 4,381 | 3.078125 | 3 |
[] |
no_license
|
# Executive Summary
## 1.1. Company Description
Embark integrates the latest technology into all projects putting clients ahead of the game. Other companies say they're innovative, when in reality they're using technology that has been around for years. Embark comes up with 'out-of-the-box' solutions, as well as being aesthetically and technically impressive compared to what other companies can offer. Everything we do aims to be award-winning.
Embark only does interesting, thought provoking; campaigns by Embark engages people to buy projects, subscribe to services, make a company stand out and **make** an event.
Embark is all about brand awareness and you can't make something stand out unless it is better than the competition, that why at Embark we build better.
## 1.2. Mission Statement
*“Embark build award winning campaigns and engaging experiences through digital innovation”*
## 1.3. Products and Services
Embark utilises the latest techniques, a good eye for design and the most creative uses of technology, resulting in campaigns that far outweigh current attempts of regional competition.
Embark is not an agency that will just create another email campaign, or to set up pay-per-click advertising and AdWords. Campaigns of this nature rarely make an impact when a company is trying to get a message out there. Embark's selection of services enable businesses to genuinely make a significant difference in raising awareness of brands, products and events, reaching their target audience in new and exciting ways.
Embark's services are split into three main categories; Digital, Experiential, and Production. These categories have been created in order to help the client choose a solution that is right for them. Clients do not have to commit to a specific package, but instead, can choose from the full range of products and services which, when combined, create an integrated marketing campaign.
**Digital** - Encompasses all the services clients may need for creating tailored online campaigns. This includes micro-sites, landing pages, responsive websites for clients looking to promote products, services, brands, or events online.
Embark also offers real-time visualisations for the web, enabling clients to communicate information through graphical means. Embark's data Visualisations bring aesthetic form and functionality together to create a unique experience, stimulating engagement and attention.
Embark also offers native mobile application development, focussing on high quality interface and interaction design on all projects and stands above the crowd online.
**Experiential** - Embark offers bespoke digital solutions, in the form of interactive installations and interaction devices. These focus on engaging client's customers in unique ways by building specific interaction on the Arduino and Raspberry pie prototyping platforms. When prototypes are complete, Embark create custom products which are released separately or integrate into clients product, event, building, stand or whatever is required.
Each installation will be tailored for our clients, enabling Embark to create the perfect solution to effectively engage the target audience of the client. Recent developments of ‘internet-of-things’ technology platforms mean services can be fully integrated with online applications and other Embark digital services, sharing data in real-time.
Clients can either approach the company with an idea, or alternatively an innovative solution that best suits their needs, which can be created.
**Production** - Covers the video production services Embark provides. Professional demonstrations, documentaries, interviews and showcase videos can be produced for clients. Inline with the industry standard, Embark uses Digital SLR cameras along with various lenses that the company has access to in order to film events or products for showcasing, creating quality content. Custom videography and photography can be integrated into any of the services Embark offers.
Within Production we also offer motion graphics, animations and visual effects to combine with other services. Video work will most likely be for the clients to showcase their brand or product online, therefore a Production solution ties in well with services such as web design, which the client may be interested in for an integrated campaign.
|
Markdown
|
UTF-8
| 1,709 | 3.21875 | 3 |
[] |
no_license
|
# Css&Less
- 命名
- 类名及id全部小写,中划线分隔
- 例:
```css
.my-class {
font-size: 20px;
}
#my-id {
background: transparent;
}
```
- less变量
- 变量、函数、混合等采用驼峰式命名
```less
@baseColor: #f938ab;
@successColor: green;
@warnColor: red;
.box {
background: @baseColor;
}
```
- 更多 [Less]()
- 注释
- css注释 统一使用 “ /* .... */ ” ,Less中相同
- 例:
```css
/* 模块导航 */
.module-header {}
/*
* 模块导航
* @xiewenqiang-Jason
*/
.module-header {}
```
- 属性合并
- 相关属性的声明尽量做分组处理,组之间使用空行
- 例:
```css
.my-box {
display: flex;
just-content: space-bewteen;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
font: normal 13px "Helvetica Neue", sans-serif;
line-height: 1.5;
text-align: center;
border: 1px solid #e5e5e5;
border-radius: 3px;
width: 100px;
height: 100px;
}
```
- 分号与引号
- 必须书写分号
- 使用双引号
- 组件css
- 参照Vue组件style规范
- 其他
- 颜色:使用小写字母,能简写就简写
- 媒体查询或者相关规则,尽量将规则放置在最近位置,不要将其放置到独立文件或者文件的底部
- 去掉小数点前面的0
- 属性为0的不要加单位
- 相同规则复用 (less)
- 不要使用 * 选择器
- 不用的类或者规则,删除
- 不需要前缀书写-编译器自动添加
|
JavaScript
|
UTF-8
| 1,733 | 3.109375 | 3 |
[] |
no_license
|
//This is an example of a component that ONLY uses an Action Creator from the Redux Reducer to make a call to get an array of swag objects that render maps to a bunch of <Swag /> objects that get displayed. There are NO STATE subscriptions in this example.
import React, { Component } from "react";
import './Shop.css';
//Import other needed components that get displayed in this component
import Swag from './Swag/Swag';
//Import Redux's connect
import { connect } from "react-redux";
//Import Action Creator Functions from the Reducer. Connect uses this function as an argument and RETURNS IT as a prop that must be extracted below in the render.
import { getSwag } from '../../ducks/zample-reducer';
//Create the Class/Component
class Shop extends Component {
//Use componentDidMount to immediately make a call to the getSwag action in the reducer for items to display
componentDidMount() {
const { getSwag } = this.props; // same as writing const getSwag = this.props.getSwag. This.prop comes from connect
getSwag();
}
render() {
//deconstruct this.props to get any needed state objects
const { swag } = this.props;
//map the state object's swag array to create a bunch of <Swag /> components to show on screen
const swagComponents = swag.map( swag => (
<Swag key={ swag.id } title={ swag.title } price={ swag.price } id={ swag.id } />
));
//In the return jsx, place the array swagComponents that you created from the map process
return (
<div id="Shop__swagParent">
<div id="Shop__swagChild">
{ swagComponents }
</div>
</div>
)
}
}
//
export default connect( state => state, { getSwag } )( NameOfComponent );
|
Markdown
|
UTF-8
| 4,021 | 2.8125 | 3 |
[] |
no_license
|
---
title: "Setting some goals for 2020"
author: John Peart
excerpt: "Another year, another set of goals."
layout: post
image: /assets/images/social/goals/goals.png
category:
- personal
---
2019 has been, on the whole, pretty successful.
I worked on [things that really mattered](https://www.gov.uk/government/publications/lgbt-action-plan-annual-progress-report-2018-to-2019), and I [got a new job](https://twitter.com/johnpeart/status/1152232805159620608). I saw [the Northern Lights](https://www.instagram.com/p/BtE4fqhF56n/) in Iceland and [giant turtles](https://www.instagram.com/p/BxUlsKSl3EY/) in Mauritius. And I nearly spontaneously combust as I [showcased the Civil Service at its best at Pride](https://twitter.com/ClareMoriarty/status/1147623334018015232?s=20).
On top of all that, I achieved [a pretty big chunk of the goals](/2019/12/26/2019-resolutions-review) I set myself this year.
But that's this year, and it is *so* 2019. I'm now all about 2020, and that means setting some new goals (or rolling over ones I want another crack at). Here are my ~~New Year's Resolutions~~ *goals* for 2020.
## Goals for 2020
### 1. Become a charity trustee or college governor
For the last 6 years, I've been heavily involved in leading the Civil Service LGBT+ Network[^csra]. It took up a *lot* of my spare time, but back in July I got a new job and didn't feel like I could do it justice whilst also doing the Network work justice: so [I stepped down](https://www.civilservice.lgbt/2019/09/18/john-peart-stepping-down/).
Now I've got an itch for something new. Time to start giving back (again). So this year I'd like to become a charity trustee or a college governor. I've got a skillset organisations might be able to put to good use; and I feel like these kinds of roles will be something I can learn from too.
(*If you think you've got the role for me, get in touch!*)
[^csra]: Formerly known as the Civil Service Rainbow Alliance.
> **Success measure:** Become a charity trustee or college governor by December 2020.
### 2. Be a better friend
I'm one of those people who always says "we should meet up" and then never actually sorts it out. That's bad. So in 2020, I'm going to catch up with at least 1 friend every month. Even if it's just for a coffee.
> **Success measure:** Catch up with at least 12 friends
### 3. Keep writing blog posts
In both 2018 and 2019, I wrote an average of one blog post a month. But two data points do not make a trend, my friends, so in 2020 the goal is to keep it up, with a minimum of 12 more blog posts on whatever topics take my fancy at the time.
> **Success measure:** 12 blog posts written
### 4. Start a podcast
I set myself the goal of starting a podcast in 2019, and [I have done a lot of preparatory work](/2019/01/27/department-of-bad-ideas) to get it off the ground. This year, I aim to finish what I started.
> **Success measure:** 5 podcast episodes released
### 5. Be healthier
I'm not getting any younger: and I need to start looking after myself better. Last year I set the goal to be active on average for 30 minutes a day: even if 'active' meant a brisk walk. This year, I want to take it a bit more seriously.
I'll be looking to fix up in a few areas: exercising more, eating better, and drinking more water. If it works, I hope to lose a bit of weight. I usually weigh around 75kg to 80kg; I'd like to be around 70kg by year end.
> **Success measure:** Lose 10kg of weight
### 6. Drink less alcohol
This should be an easy one, comparatively: I'm going to do Dry January. *Yes, I'm that boring*.
> **Success measure:** No alcohol until at least 1 February
### 7. Save some money
I struggle to discipline myself into saving money, but I am going to keep trying to do it. Last year I saved around £2,000 out of the £5,000 I aimed for. This year, I want to save more, and the target will stay the same.
> **Success measure:** £5,000 saved
> You can follow my progress with my goals by visiting my [goals dashboard](/goals/).
|
TypeScript
|
UTF-8
| 408 | 3.453125 | 3 |
[] |
no_license
|
let multiply = function (x, y) {
return x * y
}
let multiplyTs = function (x: number, y: number): number {
return x * y
}
console.log(multiply(2, 3))
console.log(multiplyTs(5, 8))
// Arrow Functions
let divide = (x, y) => {
return x / y;
}
let divideTs = (x: number, y: number): number => {
return x / y;
}
// Only Function Definitions
let divideTs3: (x: number, y: number) => number;
|
Rust
|
UTF-8
| 2,792 | 3.359375 | 3 |
[] |
no_license
|
use std::ops::RangeInclusive;
use crate::{
easing::{Easing, Linear},
tweenable::Tweenable,
};
#[derive(Debug)]
pub struct Stage<T: Tweenable> {
pub duration: f32,
pub values: RangeInclusive<T>,
pub easing: Box<dyn Easing>,
}
#[derive(Debug, Clone, Copy)]
enum State {
Running { stage_index: usize, time: f32 },
Finished,
}
pub struct Sequence<T: Tweenable> {
start: T,
stages: Vec<Stage<T>>,
state: State,
current_value: T,
}
impl<T: Tweenable> Sequence<T> {
pub fn new(start: T) -> Self {
Self {
start,
stages: vec![],
state: State::Running {
stage_index: 0,
time: 0.0,
},
current_value: start,
}
}
pub fn single(duration: f32, values: RangeInclusive<T>, easing: impl Easing + 'static) -> Self {
Self::new(*values.start()).tween(duration, *values.end(), easing)
}
pub fn tween(mut self, duration: f32, target: T, easing: impl Easing + 'static) -> Self {
let start = self
.stages
.last()
.map_or(self.start, |stage| *stage.values.end());
self.stages.push(Stage {
duration,
values: start..=target,
easing: Box::new(easing),
});
self
}
pub fn wait(mut self, duration: f32) -> Self {
let start = self
.stages
.last()
.map_or(self.start, |stage| *stage.values.end());
self.stages.push(Stage {
duration,
values: start..=start,
easing: Box::new(Linear),
});
self
}
pub fn update(&mut self, delta_time: f32) {
if let State::Running { stage_index, time } = &mut self.state {
if self.stages.is_empty() {
self.state = State::Finished;
return;
}
let mut current_stage = &self.stages[*stage_index];
// increment the current time
*time += delta_time;
// advance through the stages of the animation.
// this is done in a loop in case we pass through
// multiple stages in one frame.
while *time >= current_stage.duration {
*time -= current_stage.duration;
*stage_index += 1;
// if we reached the last stage, set the state
// to finished and stop updating.
if *stage_index >= self.stages.len() {
self.state = State::Finished;
// set the current value to the end value
// of the last stage; otherwise, the final
// value of the animation will be outdated
self.current_value = *current_stage.values.end();
return;
}
current_stage = &self.stages[*stage_index];
}
self.current_value = current_stage.values.start().lerp(
*current_stage.values.end(),
current_stage.easing.ease(*time / current_stage.duration),
);
}
}
pub fn current(&self) -> T {
self.current_value
}
pub fn finished(&self) -> bool {
matches!(self.state, State::Finished)
}
pub fn reset(&mut self) {
self.state = State::Running {
stage_index: 0,
time: 0.0,
};
self.current_value = self.start;
}
}
|
Java
|
UTF-8
| 305 | 1.757813 | 2 |
[] |
no_license
|
package com.alipay.android.phone.mobilecommon.multimediabiz.biz.persistence.db;
import android.content.Context;
public interface DbHelperCreator {
DbHelper getDbHelper(Context context);
String getDbName();
int getDbVersion();
OnDbCreateUpgradeHandler getOnDbCreateUpgradeHandler();
}
|
Java
|
UTF-8
| 588 | 2.015625 | 2 |
[] |
no_license
|
package com.v2.coaching.di.module;
import android.content.Context;
import com.v2.coaching.Ui.Activity.BaseMain;
import com.v2.coaching.di.ActivityContext;
import dagger.Module;
import dagger.Provides;
/**
* Created by janisharali on 08/12/16.
*/
@Module
public class ActivityModule {
private BaseMain mBaseMain;
public ActivityModule(BaseMain baseMain) {
mBaseMain = baseMain;
}
@Provides
@ActivityContext
Context provideContext() {
return mBaseMain;
}
@Provides
BaseMain provideActivity() {
return mBaseMain;
}
}
|
Swift
|
UTF-8
| 656 | 2.5625 | 3 |
[] |
no_license
|
//
// SpeechRecognizer.swift
// Watson Conversation
//
// Created by Marco Aurélio Bigélli Cardoso on 10/04/17.
// Copyright © 2017 IBM. All rights reserved.
//
import Foundation
@objc protocol SpeechRecognizer: class {
weak var delegate: SpeechRecognizerDelegate? { get set }
func startRecording()
func cancel()
}
@objc protocol SpeechRecognizerDelegate: class {
@objc optional func speechRecognizerDidStart(_ recognizer: SpeechRecognizer)
@objc optional func speechRecognizer(_ recognizer: SpeechRecognizer, didFinishRecognition result: String)
@objc optional func speechRecognizer(_ recognizer: SpeechRecognizer, errorDidOccur error: String)
}
|
Java
|
UTF-8
| 447 | 1.765625 | 2 |
[] |
no_license
|
package com.ml.blog.service;
import com.github.pagehelper.PageInfo;
import com.ml.blog.entity.Message;
/**
* @author Mr.ml
* @date 2021/1/16
*/
public interface MessageService {
int saveMessage(Message message);
int removeMessage(Integer messageId);
int updateMessage(Message message);
Message getMessage(Integer messageId);
PageInfo<Message> listMessages(Integer pageNum, Integer pageSize);
}
|
Python
|
UTF-8
| 307 | 2.703125 | 3 |
[] |
no_license
|
from collections import Counter
def bairro_mais_custoso(dg):
ds = {}
soma = 0
for k, v in dg.items():
v2 = v[6:12]
for i in v2:
soma += i
ds[k] = soma
k = Counter(ds)
m = k.most_common(1)
return m
|
JavaScript
|
UTF-8
| 1,049 | 3.515625 | 4 |
[] |
no_license
|
function sort(arr) {
heapify(arr); // O(N) T
let right = arr.length - 1;
// O(NLog(N)) T
while (right > 0) {
swap(arr, 0, right);
right--;
sink(arr, 0, right);
}
return arr;
}
// O(N) T
function heapify(arr) {
let lastParentIdx = Math.floor((arr.length - 2) / 2);
for (let i = lastParentIdx; i >= 0; i--) {
sink(arr, i, arr.length - 1);
}
}
// O(Log(N)) T
function sink(arr, i, right) {
let smChildIdx = getSmallerChildIdx(arr, i, right);
while (smChildIdx && arr[i] > arr[smChildIdx]) {
swap(arr, i, smChildIdx);
i = smChildIdx;
smChildIdx = getSmallerChildIdx(arr, i, right);
}
}
function getSmallerChildIdx(arr, i, right) {
let smChildIdx = i * 2 + 1;
if (smChildIdx > right) return null;
if (smChildIdx <= right - 1 && arr[smChildIdx] > arr[smChildIdx + 1])
smChildIdx++;
return smChildIdx;
}
function swap(arr, i, j) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
module.exports = sort;
|
Java
|
UTF-8
| 587 | 1.875 | 2 |
[] |
no_license
|
package org.onedatashare.server.service;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onedatashare.server.service.oauth.DbxOauthService;
import org.springframework.beans.factory.annotation.Autowired;
public class DbxOauthServiceTest {
@Autowired
private DbxOauthService dbxOauthService;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void start_givenNothing_throwsRuntimeException() {
thrown.expect(RuntimeException.class);
dbxOauthService.start();
}
}
|
C#
|
UTF-8
| 1,022 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
namespace MvcApi.Query
{
/// <summary>
/// Represents a query option like $filter, $top etc.
/// </summary>
public interface IStructuredQueryPart
{
/// <summary>
/// The query operator that this query parameter is for.
/// </summary>
string QueryOperator { get; }
/// <summary>
/// The value part of the query parameter for this query part.
/// </summary>
string QueryExpression { get; }
/// <summary>
/// Applies this <see cref="IStructuredQueryPart"/> on to an <see cref="IQueryable"/>
/// returning the resultant <see cref="IQueryable"/>
/// </summary>
/// <param name="source">The source <see cref="IQueryable"/></param>
/// <returns>The resultant <see cref="IQueryable"/></returns>
IQueryable ApplyTo(IQueryable source);
}
}
|
Ruby
|
UTF-8
| 426 | 3.890625 | 4 |
[] |
no_license
|
# password.rb
#Write a program that displays a welcome message, but only after the user
#enters the correct password, where the password is a string that is defined as
#a constant in your program. Keep asking for the password until the user enters
#the correct password.
PWD = "bubble"
loop do
puts "Please enter your password:"
pwd_try = gets.chomp
break if pwd_try == PWD
puts "Sorry, incorrect password."
end
|
Java
|
UTF-8
| 546 | 1.851563 | 2 |
[] |
no_license
|
package com.snap.core.db.record;
import com.snap.core.db.record.BestFriendModel.Creator;
/* compiled from: lambda */
public final /* synthetic */ class -$$Lambda$ktw8M_f8IJdmsC-qellLlsv2DwM implements Creator {
public static final /* synthetic */ -$$Lambda$ktw8M_f8IJdmsC-qellLlsv2DwM INSTANCE = new -$$Lambda$ktw8M_f8IJdmsC-qellLlsv2DwM();
private /* synthetic */ -$$Lambda$ktw8M_f8IJdmsC-qellLlsv2DwM() {
}
public final BestFriendModel create(long j, long j2) {
return new AutoValue_BestFriendRecord(j, j2);
}
}
|
C++
|
UTF-8
| 504 | 2.953125 | 3 |
[] |
no_license
|
// Strings.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string.h>
#include <iostream>
using namespace std;
#pragma warning(disable: 4996)
void foo(char *s)
{
cout << s << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
foo("This is const string");
char name2[10];
char *str = "Hello";
/*cout << str << endl;
for (int i = 0; i < 5; i++)
{
name2[i] = str[i];
}
name2[5] = '\0';*/
strcpy(name2, str);
cout << name2 << endl;
return 0;
}
|
Java
|
UTF-8
| 380 | 2.796875 | 3 |
[] |
no_license
|
package com.mnikiforov.testing_sber.t2016.c3_ooconcepts;
/**
* Created by Zigzag on 16.10.2016.
*/
public class Polimorphism_A {
protected int i = 1;
public Polimorphism_A() {
System.out.println("A");
setI();
}
public void setI() {
System.out.println("A.setI");
i = 2;
}
public int getI() {
return i;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.