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 |
|---|---|---|---|---|---|---|---|
Markdown | UTF-8 | 8,937 | 2.90625 | 3 | [
"MIT"
] | permissive | Audiogram was developed for our particular needs but hopefully it should be reasonably hackable besides the options provided. Here are some examples of possible customization that involve writing/editing the code and notes on how you could get started.
## Use different animations besides the wave/bars/bricks
The code that handles drawing a waveform involves three pieces:
1. The `audiogram/waveform.js` module, which uses the `waveform` utility to scan the file for its waveform data and then slices it up and scales it appropriately. This function is called from the `Audiogram.getWaveform()` method in `audiogram/index.js`.
2. The code in `renderer/patterns.js`, which defines functions for how to draw a few common patterns based on data and options.
3. The code in `renderer/index.js`, which takes the waveform data and calls the pattern-drawing function.
To use a different style using the same data, you could add a new pattern in `renderer/patterns.js` using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) and then use that pattern name in `settings/themes.json`. The built-in patterns make use of [D3](https://d3js.org/) for scaling and other helper functions, but you could use whatever you want.
If you want to modify things more drastically, you could edit the code in `renderer/index.js` to draw anything you want.
Note that if you modify any of the code in `renderer/`, you'll want to run `npm run rebuild` so it rebundles it for the editor.
## Change how captions are rendered/aligned/wrapped
The logic that wraps and aligns caption text is located in `renderer/text-wrapper.js`. It takes in a raw string, slices it into words, and then fits those words onto the current line until it runs out of room and then starts a new line. Once it knows the words going on each line, it aligns that entire box based on the `caption(Left|Right|Top|Bottom)` options. If you want to tinker with this, `renderer/text-wrapper.js` is the place to tinker.
Note that if you modify any of the code in `renderer/`, you'll want to run `npm run rebuild` so it rebundles it for the editor.
## Require users to log in
Audiogram doesn't include any sort of authentication system. If you want to host a version of it for internal use and protect it from the outside world, you could limit access by IP, or you could add some other login system. The web server uses the [Express.js](http://expressjs.com/) framework. If you add authentication middleware at the top of `server/index.js`, it will redirect unauthenticated requests. [Passport.js](http://passportjs.org/) is one resource that offers Express-friendly authentication using OAuth for popular services (e.g. Google or Facebook), but no matter what you'll at least need to administer a list of allowed users somewhere.
## Fiddle with FFmpeg options (e.g. use different encoders)
The FFmpeg command that does the final video rendering is in `audiogram/combine-frames.js`. You can add or edit flags there.
## Use something else besides Redis or a file to track jobs
If `redisHost` is defined in your settings, Redis will be used to track the status of audiogram jobs. If it's not enabled, there will instead be a JSON file called `.jobs` in the root Audiogram directory which works OK if you're just using it locally. If you want to use something else, like some sort of database or SQS, you'll want to edit the files in `lib/transports/redis/`, which define the API for how to interact with Redis or its equivalent. `lib/transports/redis/index.js` will expose the API for Redis or the file equivalent depending on the server settings. The easiest way to get started would probably be to copy the file `lib/transports/redis/fake.js` and update it to work with the system you want to use instead.
## Store files somewhere else besides S3 or a folder
If your settings include an `s3Bucket` setting, your files will be stored on S3. Otherwise, they will be stored in the local folder defined by `storagePath` (this can be an absolute path, or a path relative to the Audiogram root directory). If you want to store files somewhere besides S3 or the local machine, you'll want to edit the files in `lib/transports/s3/`, which define the API for how to interact with S3 or its filesystem equivalent. `lib/transports/s3/index.js` will expose the API for S3 or the filesystem depending on the server settings. The easiest way to get started would probably be to copy the file `lib/transports/s3/fake.js` and update it to work with the system you want to use instead.
## Make S3 files private
By default, files are uploaded to S3 as publicly readable files, and can be viewed at the corresponding url, like `https://s3.amazonaws.com/mybucket/video/[long random id].mp4`. The short reason for this is that it avoids the extra load and complexity caused by serving videos through the webserver. Streaming them directly through the webserver from S3 has some quirks, and downloading them to the webserver in their entirety and then serving them as local files needlessly slows things down. All audio and video files uploaded to S3 have 30+ character random UUID filenames, so the odds of someone stumbling on one are... low. But if you want to keep them totally private, and you still want to use S3, you can either:
1. Edit `lib/transports/s3/remote.js` to set a short expiration date on a video upload.
or
1. Edit `lib/transports/s3/remote.js` to remove the `public-read` setting from the upload and edit the `getURL()` function to return a local URL (`/videos/[id].mp4`).
3. Edit `server/index.js` so that it serves videos even when you're using S3. Modify it with a route handler that streams files from S3 to the end user as appropriate.
## Make this faster
As of now the rule of thumb is that the rendering process will take about a second for every 10-12 frames involved. So if you have a 30 second audio clip and a framerate of 20 frames per second, it will take about 45 seconds in all. The easiest way to make rendering faster is to reduce the framerate in `settings/themes.json` (e.g. a framerate of 10 instead of 20 will involve half as many frames). But there's probably lots of room for other performance improvements.
The `node-canvas` step that draws an individual image for each frame accounts for roughly 80% of the rendering time, and is defined in `audiogram/draw-frames.js` and `renderer/index.js`. We've experimented with other approaches (for example, only rendering the foreground of each image and then combining each frame with the background image using ImageMagick), but none made a dent in the overall speed or resource usage.
The FFmpeg step accounts for most of the remaining rendering time, and is defined in `audiogram/combine-frames.js`. If you're an FFmpeg expert and have thoughts on how to more intelligently render the final video, please let us know! You may at least be able to see some improvements by forcing FFmpeg to use several threads with the `-threads` flag on a multicore machine.
## Extend themes
The current renderer (in `renderer/`) looks for certain theme settings defined in `settings/themes.json` when it's drawing the frames for a video. You could extend a theme with your own option names, and then reference them in the renderer.
As an example, if you wanted to fill the wave with a gradient instead of a solid color, you could add the new option `waveColor2` to a theme and add this bit of extra logic into `renderer/patterns.js`:
```js
// If there's a second wave color, use a gradient instead
if (options.waveColor2) {
var gradient = context.createLinearGradient(0, 0, options.width, 0);
gradient.addColorStop(0, options.waveColor);
gradient.addColorStop(1, options.waveColor2);
context.fillStyle = gradient;
context.strokeStyle = gradient;
}
```
## Use different dimensions besides 1280x720
The width and height for a video are defined in `settings/themes.json`. If you change them there, you will get a video of the appropriate size. The simplest way to handle multiple sizes would be to define multiple themes:
```js
"my-theme-fb": {
"width": 1280,
"height": 720,
"backgroundImage": "my-theme-fb.png"
},
"my-theme-instagram": {
"width": 480,
"height": 480,
"backgroundImage": "my-theme-instagram.png"
}
```
The current specs for different services are as follows:
**Dimensions**
Twitter: 1280x720
Facebook: 1280x720
Instagram: 640x640 (or any square up to 1280 on a side)
Tumblr: displayed at 500px width, height is variable
**Max File Size**
Twitter: 15MB
Facebook: 2.3GB
Instagram: unclear, but large
Tumblr: cumulative max upload of 100MB per day
**Max Length**
Twitter: 30 seconds
Facebook: 60 minutes
Instagram: 15 seconds
Tumblr: cumulative max length of 5 minutes uploaded per day
**Encoding**
Twitter: H.264-MP4-AAC
Facebook: H.264-MP4-AAC
Instagram: H.264-MP4-AAC
Tumblr: H.264-MP4-AAC
|
C | UTF-8 | 2,351 | 2.546875 | 3 | [] | no_license | #ifndef _KETAMA_H_
#define _KETAMA_H_
/**
* XXX.XXX.XXX.XXX:YYYYY ==
* (4 * 3 + 3)[ip] + 1[delimiter] + 5[port] == 21 bytes max
*/
#define MAX_HOST_LEN 22
/* previously 'mcs' */
struct ketama_point {
uint32_t value;
uint32_t srv_id;
};
/* previously 'serverinfo' */
struct ketama_srv_info {
char addr[MAX_HOST_LEN];
uint64_t memory;
};
struct ketama_srv_list {
struct ketama_srv_info *servers;
uint32_t count;
uint32_t allocated;
};
/* previously 'continuum' */
struct ketama_continuum {
struct ketama_srv_list srv_list;
struct ketama_point *points;
uint64_t points_len;
};
struct ketama_continuum *
ketama_continuum_new(struct ketama_srv_list *srv_list);
/**
* \brief Frees any allocated memory.
* \param contptr The continuum that you want to be destroy. */
void ketama_continuum_free(struct ketama_continuum *cont);
/**
* \brief Maps a key onto a server in the continuum.
* \param key The key that you want to map to a specific server.
* \param cont Pointer to the continuum in which we will search.
* \return The mcs struct that the given key maps to. */
const struct ketama_srv_info *ketama_get_server(struct ketama_continuum *cont, char *key);
/**
* \brief Print the server list of a continuum to stdout.
* \param cont The continuum to print. */
void ketama_continuum_print(struct ketama_continuum *cont);
struct ketama_srv_list *
ketama_servers_read_file(const char *filename, uint32_t *count);
struct ketama_srv_list *
ketama_servers_read_string(const char *input, uint32_t *count);
/*vvvvv For debugging purposes */
int
ketama_hash(const char *input, size_t input_len);
const struct ketama_point *
ketama_get_point(struct ketama_continuum *cont, char *key);
/*^^^^^ For debugging purposes */
void
ketama_srv_list_print(struct ketama_srv_list *srv_list);
void
ketama_srv_list_free(struct ketama_srv_list *srv_list);
struct ketama_srv_list *
ketama_srv_list_new(uint32_t count);
int
ketama_srv_list_append(struct ketama_srv_list *srv_list,
struct ketama_srv_info *srv);
ssize_t
ketama_srv_list_find(struct ketama_srv_list *srv_list, const char *ip);
uint64_t
ketama_srv_list_memcount(struct ketama_srv_list *srv_list);
void
ketama_srv_list_delete(struct ketama_srv_list *srv_list,
uint32_t position);
#endif /* _KETAMA_H_ */
|
Python | UTF-8 | 920 | 3.75 | 4 | [] | no_license | #num = int(input("Input an int: "))
#counter = 0
#while counter < num:
# print(num)
# num -= 1
#num = int(input("Input an int: "))
#counter = 0
#while counter < num:
# counter += 1
# print(counter*2)
#num = int(input("Input an int: "))
#counter = num
#sum = 0
#while num != 10:
# sum += num # sum = sum + num
# num = int(input("Input an int: "))
#print(sum)
#n = int(input("Input an int: "))
#counter = 1
#while counter <= n:
# if n % counter == 0:
# print(counter)
# counter += 1
rating = int(input("Input elo rating: "))
while rating > 1:
if rating >= 2700:
print("Super grandmaster")
elif 2700 > rating >= 2500:
print("Grandmaster")
elif 2500 > rating >= 2400:
print("International")
elif 2400 > rating >= 1000:
print("Amateur")
elif 1000 > rating > 1:
print("Invalid")
rating = int(input("Input elo rating: ")) |
C++ | UTF-8 | 6,894 | 2.546875 | 3 | [] | no_license | /*
D E L I Q U E S Z E N Z
Ermittlung des Deliqueszenzpunktes eines Salzes
Es wird die Luftfeuchtigkeit gesucht, bei der ein Salz
so viel Feuchtigkeit aus der Luft aufnimmt, dass es Leit-
fähig wird.
Zunächst werden die aktuellen Werte ermittelt und die
Startparameter gesetzt. Dann wird die gewünschte erste
Sollumgeung hergestellt und die Leitfähigkeit gemessen.
Die Luftfeuchtigkeit wird durch Zuschalten eines Befeuchters
so lange erhöht bis die Leitfähigkeit eintritt. Dann ist das
Programm beendet.
*/
#include "DHT.h" //Bibliothek mit allem was man zum DHT22-Betrieb braucht
#define DHTPIN1 3 //Digitaleingang für Temperatur und Feuchte
#define DHTPIN2 2
#define DHTTYPE DHT22 //Typ des Sensors
// P a r a m e t e r
//Zeitintervall für die Istzustaandsmeldungen
unsigned long IntervProto;
//Zeitintervall für die Erhöhung der Luftfeuchtigkeit
unsigned long IntervHygro;
//Spannungswert auf den der Referenzwert fallen muss
// um eine Leitfähigkeit des Salzes zu vermuten
float LeitSpann;
//Inkrement in Prozenpunkten um die Luftfeuchtigkeit
// erhöht wird.
int IncrHygro;
//Maximaler Differenzwert der beiden Feuchtemsser um eine
// gleichmäßige Verteilung zu postulieren
float SensorDiff;
//Arduino Pins für die verschiedenen Aufgaben
//
int spannungsPin;
int BefeuchterPin;
DHT dht1(DHTPIN1, DHTTYPE); //DHT-Objektreferenz Primär
DHT dht2(DHTPIN2, DHTTYPE); //DHT-Objektreferenz Sekkundär
// V a r i a b l e n
//Zeitpunkt der letzten Protokollierung
unsigned long ZeitProt;
//Zeitpunkt der letzten Sollwerterhöhung
unsigned long ZeitSoll;
//Aktueller Feuchtewert Primär
float AktHygr01;
//Aktueller Feuchtewert Sekundär
float AktHygr02;
//Aktuelle Temperatur Primär
float AktTemp;
//gemessener Spannungswert
int SensorValue;
//errechnete Spannung
float Spannung;
//Schalterstellung des Befeuchters
boolean befeuchter;
//Feuchtigkeitssollwert
unsigned long HygroSoll;
/*
-------------------------------------------------------
*/
void setup() {
IntervProto = 60000; // 1 Minute
IntervHygro = 1200000; // 20 Minuten
LeitSpann = 2.3;
IncrHygro = 5;
HygroSoll = 70; // Bei 5 Prozent geht es los
SensorDiff = 3;
spannungsPin = 0;
BefeuchterPin = 7;
ZeitProt = millis();
ZeitSoll = millis();
Serial.begin(9600);
AktHygr01 = dht1.readHumidity();
Serial.println(AktHygr01);
AktHygr02 = dht2.readHumidity();
Serial.println(AktHygr02);
AktTemp = dht1.readTemperature();
SensorValue = 0;
befeuchter = false;
// Hat das alles geklappt? Wenn nein kann man eigentlich aussteigen
// Ich leg' mich erst mal 10 Minuten auf's Ohr
if (isnan(AktHygr01) ||
isnan(AktHygr02)) {
Serial.println("Die Feuchtigkeit konnte nicht gelesen werden");
delay(600000);
}
// Und den ersten Spannungswert ermitteln
// Wenn das nicht klappt, dann ist hier auch Feierabend
Spannung = spannung_messen();
if (Spannung == 0) {
Serial.println("Es kann keine Spannung ermittelt werden");
delay(600000);
}
// Entweder hat alles geklappt oder die Zeit ist um
// dann kann man mal zunächst das Protokoll eröffnen
protokoll_schreiben(1);
}
/*
-------------------------------------------------------
*/
void loop() {
/* Aus dieser Funktion kommt das Programm erst zurück, wenn
der Sollwert erreicht und der Befeuchter wieder abge-
schaltet ist. */
Feuchte_Regeln(HygroSoll);
AktHygr02 = dht2.readHumidity();
Sensor_Differenzen(AktHygr01, AktHygr02);
Spannung = spannung_messen();
if (Spannung < LeitSpann) {
Serial.println("-----------------------------------------------");
Serial.println("D E L I Q U E S Z E N Z erreicht");
Serial.println("-----------------------------------------------");
Serial.println("Feuchte 1");
Serial.println(AktHygr01);
Serial.println("Feuchte 2");
Serial.println(AktHygr02);
Serial.println("Dauer");
Serial.println(millis());
Serial.println("Temperatur");
Serial.println(AktTemp);
} else {
protokoll_schreiben(2);
}
// Ggf. Erhöhen des Sollwertes
if ((millis() - ZeitSoll) > IntervHygro){
ZeitSoll = millis();
HygroSoll = HygroSoll + IncrHygro;
Serial.println(" ");
Serial.println("Sollwert wurde erhöht auf ");
Serial.print(HygroSoll);
Serial.println(" ");
}
}
/*---------------------------------------------------
EIGENE FUNNKTIONEN
---------------------------------------------------*/
void protokoll_schreiben(int art) {
float laufzeit;
laufzeit = millis() / 1000;
if ((millis() - ZeitProt) > IntervProto ||
art == 1) {
Serial.println("Protokoll - aktuelle Werte");
Serial.println("Feuchte 1");
Serial.println(AktHygr01);
Serial.println("Feuchte 2");
Serial.println(AktHygr02);
Serial.println("Temperatur");
Serial.println(AktTemp);
Serial.println("Spannung");
Serial.println(Spannung);
Serial.println("Zeit in Sekunden");
Serial.println(laufzeit);
ZeitProt = millis();
} else {
// Serial.println(art);
}
}
float spannung_messen() {
float sensorValue;
float spannung;
sensorValue = analogRead(spannungsPin); // Auslesen des Pins für die Spannungsmessung
spannung = sensorValue * 0.0048; // Der Arduino bekommt einen 10-Bit aufgelösten Wert, er kann also bis zu 1024 diskrete Werte liefern. Da der Arduino nur Werte zwischen 0 und 5 Volt liefern kann ist ein Teilwert gleich 5 / 1024 = 0,0048
return spannung;
}
/*
Hier wird so lange gemessen, bis der Sollwert erreich ist
Erst dann wird die Schleife wieder verlassen. Erst dann
macht das Messen der Spannung Sinn.
*/
void Feuchte_Regeln(unsigned long Sollwert){
boolean weiter_regeln;
weiter_regeln = true;
while (weiter_regeln){
if (Sollwert < AktHygr01) {
if (!befeuchter){
Schalten();
}
//
AktHygr01 = dht1.readHumidity();
AktHygr02 = dht2.readHumidity();
AktTemp = dht1.readTemperature();
//
} else {
weiter_regeln = false;
}
}
}
void Sensor_Differenzen(float wert_prim, float wert_sek){
float diffh;
diffh = wert_prim - wert_sek; // Wenn der Wert des 2. Sensors von dem des 1. um den Wert "DifferenzSensoren" abweicht, wird eine Warnmeldung herausgegeben
if (diffh < 0){
diffh = diffh * -1;
}
if (diffh > SensorDiff) {
if ((millis() - ZeitProt) > IntervProto){
Serial.println("-----------------------------------------------");
Serial.println("ACHTUNG ungleichmaessige Feuchtigkeitverteilung");
Serial.println("-----------------------------------------------");
ZeitProt = millis();
}
}
}
void Schalten(){
digitalWrite (BefeuchterPin, HIGH);
delay (50);
digitalWrite (BefeuchterPin, LOW);
befeuchter = !befeuchter;
}
|
Python | UTF-8 | 222 | 3.28125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
n=int(input('Digite a quantidade:'))
v=[]
somaimpares=0
somapares=0
contimpares=0
contpares=0
for i in range(0,n+1,1):
a=float(input('Digite um valor:'))
v=v.append(a)
print(v)
|
C++ | UTF-8 | 642 | 3.453125 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
string countAndSay(int n) {
if (n == 1) return "1";
if (n == 2) return "11";
string str = "11";
for (int i = 3; i <= n; i++) {
str += "$"; // previous char processed in current loop so dummy character required.length()
int len = str.length();
int cnt = 1;
string temp = "";
for(int j = 1; j < len; j++) {
if (str[j] != str[j-1]) {
temp += cnt + '0';
temp += str[j-1];
cnt = 1;
} else {
cnt++;
}
}
str = temp;
}
return str;
}
int main() {
int N = 3;
cout << countAndSay(N) << endl;
return 0;
} |
Markdown | UTF-8 | 4,344 | 3.46875 | 3 | [] | no_license | # LeetCode 专题 -- 动态规划习题
## AcWing 285. 没有上司的舞会
`难度:简单`
### 题目描述
Ural大学有N名职员,编号为1~N。
他们的关系就像一棵以校长为根的树,父节点就是子节点的直接上司。
每个职员有一个快乐指数,用整数 Hi 给出,其中 1≤i≤N。
现在要召开一场周年庆宴会,不过,没有职员愿意和直接上司一起参会。
在满足这个条件的前提下,主办方希望邀请一部分职员参会,使得所有参会职员的快乐指数总和最大,求这个最大值。
**输入格式**:
第一行一个整数N。
接下来N行,第 i 行表示 i 号职员的快乐指数Hi。
接下来N-1行,每行输入一对整数L, K,表示K是L的直接上司。
**输出格式**:
输出最大的快乐指数。
**数据范围**:
- 1≤N≤6000,
- −128≤Hi≤127
```matlab
输入样例:
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
输出样例:
5
```
**链接**:https://www.acwing.com/problem/content/287/
### Solution
1. 动态规划
- **状态表示**:
- dp[i][0] 表示不选第i个节点的收益
- dp[i][1] 表示选择第i个节点的收益
- 属性值:Max
- **状态计算**: (j为i的子节点)
- 选择第i个节点:dp[i][1] += dp[j][0]
- 不选第i个节点:dp[i][0] += Math.max(dp[j][0], dp[j][1])
- **初始化**:
- dp[i][0] = 0;
- dp[i][1] = w[i];
这道题和[LeetCode 337 打家劫舍 III](./337打家劫舍III.md)的思路是一样的。
这道题在Acwing上面,难点是自己利用**用数组模拟邻接表重建出一棵树**。我尝试在注释中备注了一下思路。
```java
import java.util.*;
class Main{
final int N = 6010;
final int INF = 0x3f3f3f3f;
int[] w = new int[N]; // 存储快乐指数,每条边的收益
// 建立邻接表存储树
int[] head = new int[N]; // 存储邻接表的表头
int[] edge = new int[N]; // 按输入顺序存储每条边指向的节点
int[] next = new int[N]; // 记录邻接表中当前节点的下一个节点
int idx = 1; // 记录边的序号,边的序号从1开始吧
boolean[] flag = new boolean[N]; // 记录第i个节点是否有父亲
int[][] dp= new int [N][2]; // dp数组
// 状态表示
// dp[i][0] 表示不选第i个节点的收益
// dp[i][1] 表示选择第i个节点的收益
// 属性值:Max
// 状态计算: (j为i的子节点)
// 选择第i个节点:dp[i][1] += dp[j][0]
// 不选第i个节点:dp[i][0] += Math.max(dp[j][0], dp[j][1])
// 初始化
// dp[i][0] = 0;
// dp[i][1] = w[i];
public void add(int a, int b){
// 第idx边指向b
edge[idx] = b;
// 采用头插法
// 第idx边的下一个节点是上一个时刻的头节点
next[idx] = head[a];
// 当前链表头节点更新,指向第idx边
head[a] = idx;
// idx++ 更新边序号
idx++;
}
public void dfs(int r){
// 遍历当前节点的每一个子树
// 深度优先
dp[r][1] = w[r];
for(int i = head[r]; i != 0; i = next[i]){
int j = edge[i];
dfs(j);
dp[r][0] += Math.max(dp[j][0], dp[j][1]);
dp[r][1] += dp[j][0];
}
}
public void init(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 1; i <= n; i++ ){
w[i] = sc.nextInt();
}
for(int i = 1; i < n; i++){
int son, fa;
son = sc.nextInt();
fa = sc.nextInt();
add(fa, son);
flag[son] = true;
}
}
public int solve(){
// 找根节点是第几条边
// 数据范围从1开始
int root = 1;
// 因为是连续的,所以从小到大遍历,只要找到没有父亲的节点,那它就是根节点
while(flag[root]) root++;
// 深度优先搜索
dfs(root);
return Math.max(dp[root][0], dp[root][1]);
}
public static void main(String[] args) {
Main s = new Main();
s.init();
int res = s.solve();
// 返回选或者不选的根节点情况下的收益较大的一个。
System.out.println(res);
}
}
```
|
Java | UTF-8 | 2,727 | 2.203125 | 2 | [] | no_license | package com.huadingcloudpackage.www.bean;
import java.io.Serializable;
import java.util.List;
/**
* @version V1.0
* @类描述: 提交差异单 传参
* @创建人:李歌
* @修改人:
* @修改备注:
*/
public class SubmitChaYiDanBean implements Serializable {
/**
* differencesReason : 1
* refund : 60
* differencesExplain : 破损了
* orderSonSn : 2020082413424622701251
* goodsSnNum : [{"goodsSn":"HDG00000206","receivedNum":"10"},{"goodsSn":"HDG00000205","receivedNum":"15"}]
* orderSn : 20200824110256874312
*/
private String differencesReason;
private int refund;
private String differencesExplain;
private String orderSonSn;
private String orderSn;
private List<GoodsSnNumBean> goodsSnNum;
public String getDifferencesReason() {
return differencesReason;
}
public void setDifferencesReason(String differencesReason) {
this.differencesReason = differencesReason;
}
public int getRefund() {
return refund;
}
public void setRefund(int refund) {
this.refund = refund;
}
public String getDifferencesExplain() {
return differencesExplain;
}
public void setDifferencesExplain(String differencesExplain) {
this.differencesExplain = differencesExplain;
}
public String getOrderSonSn() {
return orderSonSn;
}
public void setOrderSonSn(String orderSonSn) {
this.orderSonSn = orderSonSn;
}
public String getOrderSn() {
return orderSn;
}
public void setOrderSn(String orderSn) {
this.orderSn = orderSn;
}
public List<GoodsSnNumBean> getGoodsSnNum() {
return goodsSnNum;
}
public void setGoodsSnNum(List<GoodsSnNumBean> goodsSnNum) {
this.goodsSnNum = goodsSnNum;
}
public static class GoodsSnNumBean implements Serializable{
/**
* goodsSn : HDG00000206
* receivedNum : 10
* receivedBigNum : 10
*/
private String goodsSn;
private String receivedNum;
private String receivedBigNum;
public String getGoodsSn() {
return goodsSn;
}
public void setGoodsSn(String goodsSn) {
this.goodsSn = goodsSn;
}
public String getReceivedNum() {
return receivedNum;
}
public void setReceivedNum(String receivedNum) {
this.receivedNum = receivedNum;
}
public String getReceivedBigNum() {
return receivedBigNum;
}
public void setReceivedBigNum(String receivedBigNum) {
this.receivedBigNum = receivedBigNum;
}
}
}
|
Ruby | UTF-8 | 4,391 | 2.671875 | 3 | [
"MIT"
] | permissive | module Flutterby
module Reading
# Reloads the node from the filesystem, if it's a filesystem based
# node.
#
def reload!
logger.info "Reloading #{url.colorize(:blue)}"
time = Benchmark.realtime do
load!
stage!
emit(:reloaded)
end
logger.info "Reloaded #{url.colorize(:blue)} in #{sprintf("%.1fms", time * 1000).colorize(:light_white)}"
end
def data
@data_proxy ||= Dotaccess[@data]
end
# Will return the node's current source. If no source is stored with the
# node instance, this method will load (but not memoize) the contents of
# the file backing this node.
#
def source
@source || load_file_contents
end
private
# Pre-load the contents of the file backing this node and store it with
# this node instance.
#
def load_source!
@source = load_file_contents
end
def load_file_contents
if fs_path && File.file?(fs_path)
logger.debug "Pre-loading source for #{url.colorize(:blue)}"
File.read(fs_path)
end
end
def load!
clear!
@timestamp = Time.now
# Extract name, extension, and filters from given name
@name, @ext, @filters = split_filename(@original_name)
load_from_filesystem! if @fs_path
extract_data!
end
def split_filename(name)
parts = name.split(".")
name = []
filters = []
# The first part is always part of the name
name << parts.shift
# Extract filters
while parts.any? && Filters.supported?(parts.last)
filters << parts.pop
end
# Assign extension
ext = parts.any? ? parts.pop : filters.pop
# Make the remainder part of the name
name += parts
[name.join("."), ext, filters]
end
def load_from_filesystem!
if @fs_path
@timestamp = File.mtime(fs_path)
if ::File.directory?(fs_path)
Dir[::File.join(fs_path, "*")].each do |entry|
name = ::File.basename(entry)
Flutterby::Node.new(name, parent: self, fs_path: entry)
end
# If the file starts with frontmatter, load its entire source
# and keep it
elsif preload_source?
load_source!
end
end
end
# Returns true if the source for this node should be preloaded.
#
def preload_source?
mime_type.ascii? || File.size(fs_path) < 5.kilobytes
end
def extract_data!
@data ||= {}.with_indifferent_access
# Extract prefix and slug
if name =~ %r{\A([\d-]+)-(.+)\Z}
@prefix = $1
@slug = $2
else
@slug = name
end
# Change this node's name to the slug. This may be made optional
# in the future.
@name = @slug
# Extract date from prefix if possible
if prefix =~ %r{\A(\d\d\d\d\-\d\d?\-\d\d?)\Z}
@data['date'] = Date.parse($1)
end
# Read remaining data from frontmatter. Data in frontmatter
# will always have precedence!
extract_frontmatter!
# Do some extra processing depending on extension. This essentially
# means that your .json etc. files will be rendered at least once at
# bootup.
meth = "read_#{ext}!"
send(meth) if respond_to?(meth, true)
end
def extract_frontmatter!
# If the file backing this node has frontmatter, preload the source.
load_source! if file_has_frontmatter?
# If any source is available at all, let's try and parse it for
# frontmatter.
if @source
# YAML Front Matter
if @source.sub!(/\A\-\-\-\n(.+?)\n\-\-\-\n/m, "")
@data.merge! YAML.load($1)
end
# TOML Front Matter
if @source.sub!(/\A\+\+\+\n(.+?)\n\+\+\+\n/m, "")
@data.merge! TOML.parse($1)
end
end
rescue ArgumentError => e
end
def file_has_frontmatter?
if fs_path && File.file?(fs_path)
first_line = File.open(fs_path, &:readline)
["---\n", "+++\n"].include? first_line
end
rescue EOFError
false
end
def read_json!
@data.merge!(JSON.parse(render))
end
def read_yaml!
@data.merge!(YAML.load(render))
end
def read_yml!
read_yaml!
end
def read_toml!
@data.merge!(TOML.parse(render))
end
end
end
|
Java | UTF-8 | 2,107 | 2.0625 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package xxxt.orgchart.dao;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import oracle.jdbc.OracleTypes;
import org.hibernate.Session;
import org.json.JSONArray;
import org.json.JSONObject;
import xxxt.bilogin.db.SessionFactoryUtil;
/**
*
* @author admin
*/
public class OrgName {
/**
*
* @param orgName
* @return
*/
public JSONArray getOrgName(Integer p_org_type_id) {
SessionFactoryUtil.buildSessionFactory();
Session s = null;
//Transaction tx = null;
s = SessionFactoryUtil.getInstance().openSession();
CallableStatement callableStatement = null;
ResultSet rs = null;
String getDBUSERByUserIdSql = "{call apps.xxxt_bi_ws_pkg.get_org_list(?,?)}";
//String jsonInString = null;
JSONArray arr = new JSONArray();
try {
callableStatement = s.connection().prepareCall(getDBUSERByUserIdSql);
//Integer p_org_type_id= 1;
callableStatement.setInt(1, p_org_type_id);
callableStatement.registerOutParameter(2, OracleTypes.CURSOR);
callableStatement.executeUpdate();
rs = (java.sql.ResultSet) callableStatement.getObject(2);
//ObjectMapper mapper = new ObjectMapper();
while (rs.next()) {
JSONObject obj = new JSONObject();
String ORG_ID = rs.getString(1);
String ORG_NAME = rs.getString(2);
// Extract data to JSONArray
obj.put("ORG_ID", ORG_ID).toString();
obj.put("ORG_NAME", ORG_NAME).toString();
arr.put(obj);
}
//jsonInString = mapper.writeValueAsString(arr);
return arr;
} catch (Exception e) {
e.printStackTrace();
arr = null;
return arr;
} finally {
s.close();
SessionFactoryUtil.close();
}
}
}
|
C | UTF-8 | 14,027 | 3.203125 | 3 | [] | no_license | /* FILE: A2_bmp_helpers.c is where you will code your answers for Assignment 2.
*
* Each of the functions below can be considered a start for you.
*
* You should leave all of the code as is, except for what's surrounded
* in comments like "REPLACE EVERTHING FROM HERE... TO HERE.
*
* The assignment document and the header A2_bmp_headers.h should help
* to find out how to complete and test the functions. Good luck!
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
int bmp_open( char* bmp_filename, unsigned int *width,
unsigned int *height, unsigned int *bits_per_pixel,
unsigned int *padding, unsigned int *data_size,
unsigned int *data_offset, unsigned char** img_data ){
// YOUR CODE FOR Q1 SHOULD REPLACE EVERYTHING FROM HERE
FILE* filePtr = fopen(bmp_filename,"rb");
if(filePtr == NULL){
printf("Error: fopen failed\n");
return(-1);
}
unsigned char *header = malloc(32);
fread(header,sizeof(unsigned char),32,filePtr);
//printf("Print : %d - %d - %d\n", (unsigned int)header[2], (unsigned int)header[10],
//(unsigned int)header[18]);
unsigned int *data_size_pointer = (unsigned int*)(header+2);
*data_size = *data_size_pointer;
unsigned int *data_offset_pointer = (unsigned int*)(header+10);
*data_offset = *data_offset_pointer;
unsigned int *width_pointer = (unsigned int*)(header+18);
*width = *width_pointer;
int *h = (int *)&header[22];
*height = *h;
unsigned int *bits_per_pixel_pointer = (unsigned int*)(header+28);
*bits_per_pixel = *bits_per_pixel_pointer;
//calculate padding
int pad = 0;
while(((*width)*3+pad)%4 != 0){
pad++;
}
*padding = pad;
unsigned char* voidPtr = (unsigned char *)malloc(*data_size);
rewind(filePtr);
fread(voidPtr, *data_size, 1,filePtr);
*img_data = voidPtr;
// TO HERE
return 0;
}
// We've implemented bmp_close for you. No need to modify this function
void bmp_close( unsigned char **img_data ){
if( *img_data != NULL ){
free( *img_data );
*img_data = NULL;
}
}
int bmp_mask( char* input_bmp_filename, char* output_bmp_filename,
unsigned int x_min, unsigned int y_min, unsigned int x_max, unsigned int y_max,
unsigned char red, unsigned char green, unsigned char blue )
{
unsigned int img_width;
unsigned int img_height;
unsigned int bits_per_pixel;
unsigned int data_size;
unsigned int padding;
unsigned int data_offset;
unsigned char* img_data = NULL;
int open_return_code = bmp_open( input_bmp_filename, &img_width, &img_height, &bits_per_pixel, &padding, &data_size, &data_offset, &img_data );
if( open_return_code ){ printf( "bmp_open failed. Returning from bmp_mask without attempting changes.\n" ); return -1; }
// YOUR CODE FOR Q2 SHOULD REPLACE EVERYTHING FROM HERE
unsigned char* new_image = (unsigned char*)malloc(data_size);//allocate space for the new image
// unsigned char* temp = img_data;
unsigned char* temp = (unsigned char*)memcpy(new_image,img_data,data_size);
if(temp==NULL){ //check memcpy
printf("Bad input");
return(-1);
}
unsigned int num_colors = bits_per_pixel/8;
unsigned char *pixel_data = temp + data_offset;
int i = 0;
int j = 0;
for(i=y_min;i<=y_max;i++){
for(j=x_min;j<=x_max;j++){
//red, Green, Blue
pixel_data[ i*(img_width*num_colors+padding) + j*num_colors + 2 ] = red;
pixel_data[ i*(img_width*num_colors+padding) + j*num_colors + 1 ] = green;
pixel_data[ i*(img_width*num_colors+padding) + j*num_colors + 0 ] = blue;
}
}
//write into the new file
FILE *newfile = fopen(output_bmp_filename, "wb");
if(newfile==NULL){
printf("Bad file\n");
return(-1);
}
fwrite(temp,data_size,1,newfile);
fclose(newfile);
// TO HERE!
bmp_close( &img_data );
return 0;
}
int bmp_collage( char* bmp_input1, char* bmp_input2, char* bmp_result, int x_offset, int y_offset ){
unsigned int img_width1;
unsigned int img_height1;
unsigned int bits_per_pixel1;
unsigned int data_size1;
unsigned int padding1;
unsigned int data_offset1;
unsigned char* img_data1 = NULL;
int open_return_code = bmp_open( bmp_input1, &img_width1, &img_height1, &bits_per_pixel1, &padding1, &data_size1, &data_offset1, &img_data1 );
if( open_return_code ){ printf( "bmp_open failed for %s. Returning from bmp_collage without attempting changes.\n", bmp_input1 ); return -1; }
unsigned int img_width2;
unsigned int img_height2;
unsigned int bits_per_pixel2;
unsigned int data_size2;
unsigned int padding2;
unsigned int data_offset2;
unsigned char* img_data2 = NULL;
open_return_code = bmp_open( bmp_input2, &img_width2, &img_height2, &bits_per_pixel2, &padding2, &data_size2, &data_offset2, &img_data2 );
if( open_return_code ){ printf( "bmp_open failed for %s. Returning from bmp_collage without attempting changes.\n", bmp_input2 ); return -1; }
// YOUR CODE FOR Q3 SHOULD REPLACE EVERYTHING FROM HERE
//incompatible images
if(bits_per_pixel1!=bits_per_pixel2){
printf("incompatible images\n");
return(-1);
}
//number of colors
unsigned int num_colors = bits_per_pixel1/8;
//determine the width and the height of the new image
int new_width = 0;
int new_height = 0;
if((img_width1>=img_width2)&&(img_height1>=img_height2)){
//determine width
if(x_offset<=0){new_width = -x_offset+img_width1;}
else if(x_offset>0 && x_offset<=(img_width1-img_width2)){new_width = img_width1;}
else if(x_offset>0 && x_offset>(img_width1-img_width2)){new_width = x_offset+img_width2;}
//determine height
if(y_offset<0){new_height = -y_offset+img_height1;}
else if(y_offset>=0 && y_offset<=(img_height1-img_height2)){new_height = img_height1;}
else if(y_offset>(img_height1-img_height2)){new_height=y_offset+img_height2;}
}else if((img_width1<img_width2)&&(img_height1<img_height2)){
//determine width
if(x_offset>=0){new_width = x_offset+img_width2;}
else if(x_offset<0 && (img_width2-img_width1)>=(-x_offset)){new_width = img_width2;}
else if(x_offset<0 && (img_width2-img_width1)<(-x_offset)){new_width = -x_offset+img_width1;}
//determine height
if(y_offset>=0){new_height = y_offset+img_height2;}
else if(y_offset<0 && (-y_offset)<=(img_height2-img_height1)){new_height = img_height2;}
else if(y_offset<0 && (-y_offset)>(img_height2-img_height1)){new_height=-y_offset+img_height1;}
}else if((img_width1>=img_width2)&&(img_height1<img_height2)){
//determine width
if(x_offset<=0){new_width = -x_offset+img_width1;}
else if(x_offset>0 && (img_width1-img_width2)>=(x_offset)){new_width = img_width1;}
else if(x_offset>0 && (img_width1-img_width2)<(x_offset)){new_width = x_offset+img_width2;}
//determine height
if(y_offset>=0){new_height = y_offset+img_height2;}
else if(y_offset<0 && (-y_offset)<=(img_height2-img_height1)){new_height = img_height2;}
else if(y_offset<0 && (-y_offset)>(img_height2-img_height1)){new_height=-y_offset+img_height1;}
}else if((img_width1<img_width2)&&(img_height1>=img_height2)){
//determine width
if(x_offset>=0){new_width = x_offset+img_width2;}
else if(x_offset<0 && (img_width2-img_width1)>=(-x_offset)){new_width = img_width2;}
else if(x_offset<0 && (img_width2-img_width1)<(-x_offset)){new_width = -x_offset+img_width1;}
//determine height
if(y_offset<=0){new_height = -y_offset+img_height1;}
else if(y_offset>0 && (y_offset)<=(img_height1-img_height2)){new_height = img_height1;}
else if(y_offset>0 && (y_offset)>(img_height1-img_height2)){new_height=y_offset+img_height2;}
}
//calculate new padding
int pad = 0;
while(((new_width)*3+pad)%4 != 0){
pad++;
}
//allocate space for the new image
// FILE* filePtr = fopen(bmp_input1,"rb");
// if(filePtr == NULL){
// printf("Error: allocation fopen failed\n");
//return(-1);
// }
// unsigned char *head = malloc(1000);
// fread(head,sizeof(unsigned char),1000,filePtr); //read one bmp
// unsigned int *data_offset_pointer = (unsigned int*)(head+10); //get its header size
// unsigned int header_size = *data_offset_pointer;
unsigned char* new_image = (unsigned char*)malloc((new_width*num_colors+pad)*new_height+data_offset1);
//copy one header to the new image
unsigned char* temp = (unsigned char*)memcpy(new_image,img_data1,data_offset1);
if(temp==NULL){
printf("Memcpy Error\n");
return(-1);
}
//change the fields I need
int total_file_size = ((new_width*num_colors+pad)*new_height+data_offset1);
memcpy((new_image+18),&new_width,4);
memcpy((new_image+22),&new_height,4);
memcpy((new_image+2),&total_file_size,4);
//loop to change the pixels
unsigned char *pixel_data = new_image + data_offset1;
unsigned char *pixel_data1 = img_data1 + data_offset1;
unsigned char *pixel_data2 = img_data2 + data_offset2;
int i =0; int j = 0;
//firstly, set all to black
for(i=0;i<new_height;i++){
for(j=0;j<new_width;j++){
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 2 ] = 0;
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 1 ] = 0;
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 0 ] = 0;
}
}
//secondly, draw the first background image
if(x_offset>=0 && y_offset>=0){
for(i=0;i<img_height1;i++){
for(j=0;j<img_width1;j++){
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 2 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+2];
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 1 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+1];
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 0 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+0];
}
}
}else if(x_offset>=0 && y_offset<0){
for(i=0;i<img_height1;i++){
for(j=0;j<img_width1;j++){
pixel_data[ (i-y_offset)*(new_width*num_colors+pad) + j*num_colors + 2 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+2];
pixel_data[ (i-y_offset)*(new_width*num_colors+pad) + j*num_colors + 1 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+1];
pixel_data[ (i-y_offset)*(new_width*num_colors+pad) + j*num_colors + 0 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+0];
}
}
}else if(x_offset<0 && y_offset>=0){
for(i=0;i<img_height1;i++){
for(j=0;j<img_width1;j++){
pixel_data[ i*(new_width*num_colors+pad) + (j-x_offset)*num_colors + 2 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+2];
pixel_data[ i*(new_width*num_colors+pad) + (j-x_offset)*num_colors + 1 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+1];
pixel_data[ i*(new_width*num_colors+pad) + (j-x_offset)*num_colors + 0 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+0];
}
}
}else if(x_offset<0 && y_offset<0){
for(i=0;i<img_height1;i++){
for(j=0;j<img_width1;j++){
pixel_data[ (i-y_offset)*(new_width*num_colors+pad) + (j-x_offset)*num_colors + 2 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+2];
pixel_data[ (i-y_offset)*(new_width*num_colors+pad) + (j-x_offset)*num_colors + 1 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+1];
pixel_data[ (i-y_offset)*(new_width*num_colors+pad) + (j-x_offset)*num_colors + 0 ] = pixel_data1[i*(img_width1*num_colors+padding1)+j*num_colors+0];
}
}
}
//lastly, draw the second image at the top
if(x_offset<0 && y_offset<0){
for(i=0;i<img_height2;i++){
for(j=0;j<img_width2;j++){
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 2 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+2];
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 1 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+1];
pixel_data[ i*(new_width*num_colors+pad) + j*num_colors + 0 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+0];
}
}
}else if(x_offset<0 && y_offset>=0){
for(i=0;i<img_height2;i++){
for(j=0;j<img_width2;j++){
pixel_data[ (i+y_offset)*(new_width*num_colors+pad) + j*num_colors + 2 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+2];
pixel_data[ (i+y_offset)*(new_width*num_colors+pad) + j*num_colors + 1 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+1];
pixel_data[ (i+y_offset)*(new_width*num_colors+pad) + j*num_colors + 0 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+0];
}
}
}else if(x_offset>=0 && y_offset<0){
for(i=0;i<img_height2;i++){
for(j=0;j<img_width2;j++){
pixel_data[ i*(new_width*num_colors+pad) + (j+x_offset)*num_colors + 2 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+2];
pixel_data[ i*(new_width*num_colors+pad) + (j+x_offset)*num_colors + 1 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+1];
pixel_data[ i*(new_width*num_colors+pad) + (j+x_offset)*num_colors + 0 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+0];
}
}
}else if(x_offset>=0 && y_offset>=0){
for(i=0;i<img_height2;i++){
for(j=0;j<img_width2;j++){
pixel_data[(i+y_offset)*(new_width*num_colors+pad) + (j+x_offset)*num_colors + 2 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+2];
pixel_data[(i+y_offset)*(new_width*num_colors+pad) + (j+x_offset)*num_colors + 1 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+1];
pixel_data[(i+y_offset)*(new_width*num_colors+pad) + (j+x_offset)*num_colors + 0 ] = pixel_data2[i*(img_width2*num_colors+padding2)+j*num_colors+0];
}
}
}
//Save the result in a new BMP file
//write into the new file
FILE *newfile = fopen(bmp_result, "wb");
if(newfile==NULL){
printf("Bad file\n");
return(-1);
}
fwrite(new_image,((new_width*num_colors+pad)*new_height+data_offset1),1,newfile);
fclose(newfile);
// TO HERE!
bmp_close( &img_data1 );
bmp_close( &img_data2 );
return 0;
}
|
Java | UTF-8 | 346 | 2.078125 | 2 | [] | no_license | package com.dariapro.trainyourcountingskills.exception;
/**
* @author Pleshchankova Daria
*
*/
public class ExtraIsNullException extends Exception {
public ExtraIsNullException (String errorMessage) {
super(errorMessage);
}
public ExtraIsNullException (String errorMessage, Throwable err) {
super(errorMessage, err);
}
}
|
Python | UTF-8 | 522 | 2.6875 | 3 | [] | no_license | #! /usr/bin/env python
#Libraries and message types used
import rospy
import time
from std_msgs.msg import String
import os
#called when the send button is clicked
def callback_speak_string(msg):
os.system('espeak ' + '"' + msg.data + '"')
#print(msg.data)
#ROS setup
#Initialize this ROS node
rospy.init_node('speak_string_node')
#setup the subscriber and its callback
rospy.Subscriber("speak_string", String, callback_speak_string)
rate = rospy.Rate(20)
while not rospy.is_shutdown():
rate.sleep()
|
Java | UTF-8 | 1,101 | 4.0625 | 4 | [] | no_license | package cn.edu.bjut.nlp.basic._2object;
/*
instanceof 关键字
instanceof关键字的作用:判断一个对象是否属于指定的类别。
instanceof关键字的使用前提:判断的对象与指定的类别必须要存在继承或者实现的关系。
instanceof关键字的使用格式:
对象 instanceof 类别
instanceof关键字的作用: 目前没用。但是后天我们学习 到了多态之后就非常有用。
一般我们做强制类型转换之前都会使用该关键字先判断一把,然后在进行转换的。
*/
public class _0816_Object_Instanceof {
public static void main(String[] args){
Dog dog = new Dog("nam", "color");
System.out.println(dog instanceof Dog);
Ani ani = new Ani("", "");
System.out.println(ani instanceof Dog);
System.out.println(dog instanceof Ani);
}
}
class Ani{
String name;
String color;
public Ani(String name,String color){
this.name = name;
this.color = color;
}
}
class Dog extends Ani{
public Dog(String name,String color){
super(name, color);
}
public void bite(){
System.out.println("bite");
}
} |
Java | UTF-8 | 459 | 1.898438 | 2 | [] | no_license | package com.spring.actor.lib.web.pagination;
import com.spring.actor.lib.web.ResolveArgumentsException;
public class ResolvePaginationException extends ResolveArgumentsException {
public ResolvePaginationException(String s) {
super(s);
}
public ResolvePaginationException(String s, Throwable throwable) {
super(s, throwable);
}
public ResolvePaginationException(Throwable throwable) {
super(throwable);
}
}
|
C++ | UTF-8 | 2,079 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<string>
#include<time.h>
#include<conio.h>
using namespace std;
void showFile();
void menu();
void show_currentDateTime();
void show_doctors();
void show_nurses();
string doctors[100];
string nurses[100];
int doc = 0;
int nur = 0;
int main()
{
showFile();
menu();
int option;
cout << '\n';
cout << "Your option : ";
cin >> option;
switch(option)
{
case 1: show_doctors(); break;
case 2: show_nurses(); break;
case 3: show_currentDateTime(); break;
default: exit(0);
}
cout << "\nEnter any key to exit !! ";
getch();
}
void menu()
{
cout << "\n\n";
cout << "Enter one of options below :\n";
cout << "1.Show doctors list\n";
cout << "2.Show nurses list\n";
cout << "3.Show cuurent time\n";
cout << "4.exit\n";
}
void showFile()
{
ifstream read;
read.open("myfile.csv");
if(!read)
{
cout << "No such file directory !!\n";
exit(0);
}
cout << '\n';
cout << "My excel file doctors and nurses list [name, last name, id, salary, job]\n\n";
string line , tmp;
char x;
read >> x >> x >> x ;
char comma = ',';
while(read >> line)
{
cout << "\t" << line << "\n";
if(line[line.size() - 1] == 'r')
doctors[doc++] = line.substr(0, line.size() - 7);
else
nurses[nur++] = line.substr(0, line.size() - 6);
}
read.close();
}
void show_currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
cout << "\nCurrent date and time :\t" << buf << "\n";
}
void show_doctors()
{
cout << "\n";
cout << "Doctors list [name, last name, id, salary] :\n\n";
for(int i = 0 ; i < doc; i++)
cout << "\t" << doctors[i] << "\n";
cout << "\n";
}
void show_nurses()
{
cout << "\n";
cout << "Nurses list [name, last name, id, salary] :\n\n";
for(int i = 0; i < nur; i++)
cout << "\t" << nurses[i] << "\n";
cout << "\n";
}
|
C# | UTF-8 | 284 | 2.796875 | 3 | [] | no_license | public interface IEntity
{
int Id { get; set; }
}
public class UserEntity : IEntity
{
int IEntity.Id { get; set; }
public string Name { get; set; }
}
var user = new UserEntity();
((IEntity)user).Id = -1;
user.Name = "John";
|
C++ | UTF-8 | 3,457 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <algorithm>
#define mid lt + (rt-lt)/2
#define vx Element *
using namespace std;
struct Window {
int y, r, l;
char ble;
};
Window make_window(int y, int l, int r, char ble) {
Window *node = new Window;
node->y = y;
node->r = r;
node->l = l;
node->ble = ble;
return *node;
}
struct Element {
int maxi = INT_MIN;
long long add = 0;
vx right = nullptr;
vx left = nullptr;
int x = 0;
};
void setMax(vx v) {
if (!v)
return;
if (v->left && v->right) {
if (v->left->maxi > v->right->maxi) {
v->maxi = v->left->maxi;
v->x = v->left->x;
} else {
v->maxi = v->right->maxi;
v->x = v->right->x;
}
} else if (v->left) {
v->maxi = v->left->maxi;
v->x = v->left->x;
} else if (v->right) {
v->maxi = v->right->maxi;
v->x = v->right->x;
}
}
vx make_vertex(vx left, vx right) {
vx node = new Element();
node->right = right;
node->left = left;
setMax(node);
return node;
}
vx make_list(int value, int x) {
vx node = new Element();
node->maxi = value;
node->left = nullptr;
node->right = nullptr;
node->x = x;
return node;
}
class SegTree {
public:
SegTree(int n) : size(n) {
root = build(0, size - 1);
}
pair<int, int> get(int l, int r) {
return get(root, l, r, 0, size - 1);
}
void Add(int l, int r, int value) {
Add(root, value, 0, size - 1, l, r);
}
private:
int size;
vx root;
void Add(vx v, int value, int lt, int rt, int l, int r) {
if (lt > r || rt < l)
return;
if (v->add) {
if (v->left) {
v->left->add += v->add;
v->left->maxi += v->add;
}
if (v->right) {
v->right->add += v->add;
v->right->maxi += v->add;
}
v->add = 0;
}
if (l <= lt && rt <= r) {
v->add += value;
v->maxi += value;
} else {
Add(v->left, value, lt, mid, l, r);
Add(v->right, value, mid + 1, rt, l, r);
setMax(v);
}
}
vx build(int lt, int rt) {
if (lt == rt)
return make_list(0, lt);
return make_vertex(build(lt, mid), build(mid + 1, rt));
}
pair<int, int> get(vx v, int l, int r, int lt, int rt) {
return {v->maxi, v->x};
}
};
bool comp(Window a, Window b) {
return (a.y == b.y) ? a.ble < b.ble : a.y < b.y;
}
const int off = 1000000;
int main() {
int n, x1, y1, x2, y2;
cin >> n;
vector<Window> W;
for (int i = 0; i < n; i++) {
cin >> x1 >> y1 >> x2 >> y2;
W.push_back(make_window(y1, x1, x2, 'b'));
W.push_back(make_window(y2, x1, x2, 'e'));
}
sort(W.begin(), W.end(), comp);
SegTree tree(2 * off);
int bla;
int ans = INT_MIN;
int x, y;
pair<int, int> q;
for (int i = 0; i < 2 * n; i++) {
if (W[i].ble == 'b') bla = 1;
else bla = -1;
tree.Add(W[i].l + off, W[i].r + off, bla);
q = tree.get(0, 2 * n - 1);
if (q.first > ans) {
ans = q.first;
x = q.second - off;
y = W[i].y;
}
}
cout << ans << endl << x << ' ' << y << endl;
return 0;
} |
Java | UTF-8 | 19,510 | 2.203125 | 2 | [] | no_license | package com.rz.bean;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
* Bean类 - 系统配置
*/
public class Setting {
// 货币种类(人民币、美元、欧元、英磅、加拿大元、澳元、卢布、港币、新台币、韩元、新加坡元、新西兰元、日元、马元、瑞士法郎、瑞典克朗、丹麦克朗、兹罗提、挪威克朗、福林、捷克克朗、葡币)
public enum CurrencyType {
CNY, USD, EUR, GBP, CAD, AUD, RUB, HKD, TWD, KRW, SGD, NZD, JPY, MYR, CHF, SEK, DKK, PLZ, NOK, HUF, CSK, MOP
};
// 小数位精确方式(四舍五入、向上取整、向下取整)
public enum RoundType {
roundHalfUp, roundUp, roundDown
}
// 库存预占时间点(下订单、订单付款、订单发货)
public enum StoreFreezeTime {
order, payment, ship
}
// 水印位置(无、左上、右上、居中、左下、右下)
public enum WatermarkPosition {
no, topLeft, topRight, center, bottomLeft, bottomRight
}
// 积分获取方式(禁用积分获取、按订单总额计算、为商品单独设置)
public enum ScoreType {
disable, orderAmount, goodsSet
}
// 在线客服位置(左、右)
public enum InstantMessagingPosition {
left, right
}
// 在线留言显示方式(立即显示、回复后显示)
public enum LeaveMessageDisplayType {
direct, reply
}
// 评论发表权限(任何访问者、注册会员、已购买会员)
public enum CommentAuthority {
anyone, member, purchased
}
// 评论显示方式(立即显示、回复后显示)
public enum CommentDisplayType {
direct, reply
}
public static final String HOT_SEARCH_SEPARATOR = ",";// 热门搜索分隔符
public static final String ALLOWED_UPLOAD_EXTENSION_SEPARATOR = ",";// 允许上传的文件扩展名分隔符
public static final String LOGO_UPLOAD_NAME = "logo";// Logo图片文件名称(不包含扩张名)
public static final String DEFAULT_BIG_GOODS_IMAGE_FILE_NAME = "default_big_goods_image";// 默认商品图片(大)文件名称(不包含扩展名)
public static final String DEFAULT_SMALL_GOODS_IMAGE_FILE_NAME = "default_small_goods_image";// 默认商品图片(小)文件名称(不包含扩展名)
public static final String DEFAULT_THUMBNAIL_GOODS_IMAGE_FILE_NAME = "default_thumbnail_goods_image";// 商品缩略图文件名称(不包含扩展名)
public static final String WATERMARK_IMAGE_FILE_NAME = "watermark";// 水印图片文件名称(不包含扩展名)
public static final String UPLOAD_DIR = "/upload/";// 上传目录
public static final String CAR_UPLOAD_DIR = "/upload/car/";
public static final String CHART_ORDER_UPLOAD_DIR = "/upload/chart_order/";
public static final String SPOT_UPLOAD_DIR = "/upload/spot/";
public static final String HOTAL_UPLOAD_DIR = "/upload/hotal/";
public static final String AVATAR_UPLOAD_DIR = "/upload/avatar/";
public static final String DEFAULT_MEMBER_AVATAR = "/template/shop/images/avatar.png";// 会员默认头像
private String systemName;// 系统名称
private String systemVersion;// 系统版本
private String systemDescription;// 系统描述
private String environment;
private String shopName;// 网店名称
private String shopUrl;// 网店网址
private String shopLogo;// 网店Logo
private String hotSearch;// 热门搜索关键词
private String metaKeywords;// 首页页面关键词
private String metaDescription;// 首页页面描述
private String address;// 联系地址
private String phone;// 联系电话
private String zipCode;// 邮编
private String email;// 联系email
private CurrencyType currencyType;// 货币种类
private String currencySign;// 货币符号
private String currencyUnit;// 货币单位
private Integer priceScale;// 商品价格精确位数
private RoundType priceRoundType;// 商品价格精确方式
private Integer orderScale;// 订单金额精确位数
private RoundType orderRoundType;// 订单金额精确方式
private String circulateLicence;// 食品流通许可证号
private String foodLicence;// 食品许可证
private String certtext;// 备案号
private Integer storeAlertCount;// 库存报警数量
private StoreFreezeTime storeFreezeTime;// 库存预占时间点
private Integer uploadLimit;// 文件上传最大值,0表示无限制,单位KB
private Boolean isLoginFailureLock; // 是否开启登录失败锁定账号功能
private Integer loginFailureLockCount;// 同一账号允许连续登录失败的最大次数,超出次数后将锁定其账号
private Integer loginFailureLockTime;// 账号锁定时间(单位:分钟,0表示永久锁定)
private Boolean isRegisterEnabled;// 是否开放注册
private String watermarkImagePath; // 水印图片路径
private WatermarkPosition watermarkPosition; // 水印位置
private Integer watermarkAlpha;// 水印透明度
private Integer CarImageStartSn;//图片保存起始目录ID
private Integer bigCarImageWidth;// 商品图片(大)宽度
private Integer bigCarImageHeight;// 商品图片(大)高度
private Integer smallCarImageWidth;// 商品图片(小)宽度
private Integer smallCarImageHeight;// 商品图片(小)高度
private Integer thumbnailCarImageWidth;// 商品缩略图宽度
private Integer thumbnailCarImageHeight;// 商品缩略图高度
private Integer smallCarImageWidth2;// 商品图片(小)2宽度
private Integer smallCarImageHeight2;// 商品图片(小)2高度
private Integer thumbnailCarImageWidth2;// 商品缩略图2宽度
private Integer thumbnailCarImageHeight2;// 商品缩略图2高度
public Integer getCarImageStartSn() {
return CarImageStartSn;
}
public void setCarImageStartSn(Integer CarImageStartSn) {
this.CarImageStartSn = CarImageStartSn;
}
public Integer getSmallCarImageWidth2() {
return smallCarImageWidth2;
}
public void setSmallCarImageWidth2(Integer smallCarImageWidth2) {
this.smallCarImageWidth2 = smallCarImageWidth2;
}
public Integer getSmallCarImageHeight2() {
return smallCarImageHeight2;
}
public void setSmallCarImageHeight2(Integer smallCarImageHeight2) {
this.smallCarImageHeight2 = smallCarImageHeight2;
}
public Integer getThumbnailCarImageWidth2() {
return thumbnailCarImageWidth2;
}
public void setThumbnailCarImageWidth2(Integer thumbnailCarImageWidth2) {
this.thumbnailCarImageWidth2 = thumbnailCarImageWidth2;
}
public Integer getThumbnailCarImageHeight2() {
return thumbnailCarImageHeight2;
}
public void setThumbnailCarImageHeight2(Integer thumbnailCarImageHeight2) {
this.thumbnailCarImageHeight2 = thumbnailCarImageHeight2;
}
private String defaultBigCarImagePath;// 默认商品图片(大)
private String defaultSmallCarImagePath;// 默认商品图片(小)
private String defaultThumbnailCarImagePath;// 默认缩略图
private String allowedUploadExtension;// 允许上传的文件扩展名(为空表示不允许上传文件)
private String smtpFromMail;// 发件人邮箱
private String smtpHost;// SMTP服务器地址
private Integer smtpPort;// SMTP服务器端口
private String smtpUsername;// SMTP用户名
private String smtpPassword;// SMTP密码
private ScoreType scoreType;// 积分获取方式
private Double scoreScale;// 积分换算比率
private Boolean isGzipEnabled;// 是否开启GZIP功能
private Boolean isInstantMessagingEnabled;// 是否开启在线客服功能
private InstantMessagingPosition instantMessagingPosition;// 在线客服位置
private String instantMessagingTitle;// 在线客服标题
private Boolean isLeaveMessageEnabled;// 是否开启在线留言功能
private Boolean isLeaveMessageCaptchaEnabled;// 是否开启在线留言验证码功能
private LeaveMessageDisplayType leaveMessageDisplayType;// 在线留言显示方式
private Boolean isCommentEnabled;// 是否开启评论功能
private Boolean isCommentCaptchaEnabled;// 是否开启评论验证码功能
private CommentAuthority commentAuthority;// 评论发表权限
private CommentDisplayType commentDisplayType;// 评论显示方式
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public String getSystemVersion() {
return systemVersion;
}
public void setSystemVersion(String systemVersion) {
this.systemVersion = systemVersion;
}
public String getSystemDescription() {
return systemDescription;
}
public void setSystemDescription(String systemDescription) {
this.systemDescription = systemDescription;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String getShopUrl() {
return shopUrl;
}
public void setShopUrl(String shopUrl) {
this.shopUrl = shopUrl;
}
public String getShopLogo() {
return shopLogo;
}
public void setShopLogo(String shopLogo) {
this.shopLogo = shopLogo;
}
public String getHotSearch() {
return hotSearch;
}
public void setHotSearch(String hotSearch) {
this.hotSearch = hotSearch;
}
public String getMetaKeywords() {
return metaKeywords;
}
public void setMetaKeywords(String metaKeywords) {
this.metaKeywords = metaKeywords;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public CurrencyType getCurrencyType() {
return currencyType;
}
public void setCurrencyType(CurrencyType currencyType) {
this.currencyType = currencyType;
}
public String getCurrencySign() {
return currencySign;
}
public void setCurrencySign(String currencySign) {
this.currencySign = currencySign;
}
public String getCurrencyUnit() {
return currencyUnit;
}
public void setCurrencyUnit(String currencyUnit) {
this.currencyUnit = currencyUnit;
}
public Integer getPriceScale() {
return priceScale;
}
public void setPriceScale(Integer priceScale) {
this.priceScale = priceScale;
}
public RoundType getPriceRoundType() {
return priceRoundType;
}
public void setPriceRoundType(RoundType priceRoundType) {
this.priceRoundType = priceRoundType;
}
public Integer getOrderScale() {
return orderScale;
}
public void setOrderScale(Integer orderScale) {
this.orderScale = orderScale;
}
public RoundType getOrderRoundType() {
return orderRoundType;
}
public void setOrderRoundType(RoundType orderRoundType) {
this.orderRoundType = orderRoundType;
}
public String getCerttext() {
return certtext;
}
public void setCerttext(String certtext) {
this.certtext = certtext;
}
public Integer getStoreAlertCount() {
return storeAlertCount;
}
public void setStoreAlertCount(Integer storeAlertCount) {
this.storeAlertCount = storeAlertCount;
}
public StoreFreezeTime getStoreFreezeTime() {
return storeFreezeTime;
}
public void setStoreFreezeTime(StoreFreezeTime storeFreezeTime) {
this.storeFreezeTime = storeFreezeTime;
}
public Integer getUploadLimit() {
return uploadLimit;
}
public void setUploadLimit(Integer uploadLimit) {
this.uploadLimit = uploadLimit;
}
public Boolean getIsLoginFailureLock() {
return isLoginFailureLock;
}
public void setIsLoginFailureLock(Boolean isLoginFailureLock) {
this.isLoginFailureLock = isLoginFailureLock;
}
public Integer getLoginFailureLockCount() {
return loginFailureLockCount;
}
public void setLoginFailureLockCount(Integer loginFailureLockCount) {
this.loginFailureLockCount = loginFailureLockCount;
}
public Integer getLoginFailureLockTime() {
return loginFailureLockTime;
}
public void setLoginFailureLockTime(Integer loginFailureLockTime) {
this.loginFailureLockTime = loginFailureLockTime;
}
public Boolean getIsRegisterEnabled() {
return isRegisterEnabled;
}
public void setIsRegisterEnabled(Boolean isRegisterEnabled) {
this.isRegisterEnabled = isRegisterEnabled;
}
public String getWatermarkImagePath() {
return watermarkImagePath;
}
public void setWatermarkImagePath(String watermarkImagePath) {
this.watermarkImagePath = watermarkImagePath;
}
public WatermarkPosition getWatermarkPosition() {
return watermarkPosition;
}
public void setWatermarkPosition(WatermarkPosition watermarkPosition) {
this.watermarkPosition = watermarkPosition;
}
public Integer getWatermarkAlpha() {
return watermarkAlpha;
}
public void setWatermarkAlpha(Integer watermarkAlpha) {
this.watermarkAlpha = watermarkAlpha;
}
public Integer getBigCarImageWidth() {
return bigCarImageWidth;
}
public void setBigCarImageWidth(Integer bigCarImageWidth) {
this.bigCarImageWidth = bigCarImageWidth;
}
public Integer getBigCarImageHeight() {
return bigCarImageHeight;
}
public void setBigCarImageHeight(Integer bigCarImageHeight) {
this.bigCarImageHeight = bigCarImageHeight;
}
public Integer getSmallCarImageWidth() {
return smallCarImageWidth;
}
public void setSmallCarImageWidth(Integer smallCarImageWidth) {
this.smallCarImageWidth = smallCarImageWidth;
}
public Integer getSmallCarImageHeight() {
return smallCarImageHeight;
}
public void setSmallCarImageHeight(Integer smallCarImageHeight) {
this.smallCarImageHeight = smallCarImageHeight;
}
public Integer getThumbnailCarImageWidth() {
return thumbnailCarImageWidth;
}
public void setThumbnailCarImageWidth(Integer thumbnailCarImageWidth) {
this.thumbnailCarImageWidth = thumbnailCarImageWidth;
}
public Integer getThumbnailCarImageHeight() {
return thumbnailCarImageHeight;
}
public void setThumbnailCarImageHeight(Integer thumbnailCarImageHeight) {
this.thumbnailCarImageHeight = thumbnailCarImageHeight;
}
public String getDefaultBigCarImagePath() {
return defaultBigCarImagePath;
}
public void setDefaultBigCarImagePath(String defaultBigCarImagePath) {
this.defaultBigCarImagePath = defaultBigCarImagePath;
}
public String getDefaultSmallCarImagePath() {
return defaultSmallCarImagePath;
}
public void setDefaultSmallCarImagePath(String defaultSmallCarImagePath) {
this.defaultSmallCarImagePath = defaultSmallCarImagePath;
}
public String getDefaultThumbnailCarImagePath() {
return defaultThumbnailCarImagePath;
}
public void setDefaultThumbnailCarImagePath(String defaultThumbnailCarImagePath) {
this.defaultThumbnailCarImagePath = defaultThumbnailCarImagePath;
}
public String getAllowedUploadExtension() {
return allowedUploadExtension;
}
public void setAllowedUploadExtension(String allowedUploadExtension) {
this.allowedUploadExtension = allowedUploadExtension;
}
public String getSmtpFromMail() {
return smtpFromMail;
}
public void setSmtpFromMail(String smtpFromMail) {
this.smtpFromMail = smtpFromMail;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getCirculateLicence() {
return circulateLicence;
}
public void setCirculateLicence(String circulateLicence) {
this.circulateLicence = circulateLicence;
}
public String getFoodLicence() {
return foodLicence;
}
public void setFoodLicence(String foodLicence) {
this.foodLicence = foodLicence;
}
public Integer getSmtpPort() {
return smtpPort;
}
public void setSmtpPort(Integer smtpPort) {
this.smtpPort = smtpPort;
}
public String getSmtpUsername() {
return smtpUsername;
}
public void setSmtpUsername(String smtpUsername) {
this.smtpUsername = smtpUsername;
}
public String getSmtpPassword() {
return smtpPassword;
}
public void setSmtpPassword(String smtpPassword) {
this.smtpPassword = smtpPassword;
}
public ScoreType getScoreType() {
return scoreType;
}
public void setScoreType(ScoreType scoreType) {
this.scoreType = scoreType;
}
public Double getScoreScale() {
return scoreScale;
}
public void setScoreScale(Double scoreScale) {
this.scoreScale = scoreScale;
}
public Boolean getIsGzipEnabled() {
return isGzipEnabled;
}
public void setIsGzipEnabled(Boolean isGzipEnabled) {
this.isGzipEnabled = isGzipEnabled;
}
public Boolean getIsInstantMessagingEnabled() {
return isInstantMessagingEnabled;
}
public void setIsInstantMessagingEnabled(Boolean isInstantMessagingEnabled) {
this.isInstantMessagingEnabled = isInstantMessagingEnabled;
}
public InstantMessagingPosition getInstantMessagingPosition() {
return instantMessagingPosition;
}
public void setInstantMessagingPosition(InstantMessagingPosition instantMessagingPosition) {
this.instantMessagingPosition = instantMessagingPosition;
}
public String getInstantMessagingTitle() {
return instantMessagingTitle;
}
public void setInstantMessagingTitle(String instantMessagingTitle) {
this.instantMessagingTitle = instantMessagingTitle;
}
public Boolean getIsLeaveMessageEnabled() {
return isLeaveMessageEnabled;
}
public void setIsLeaveMessageEnabled(Boolean isLeaveMessageEnabled) {
this.isLeaveMessageEnabled = isLeaveMessageEnabled;
}
public Boolean getIsLeaveMessageCaptchaEnabled() {
return isLeaveMessageCaptchaEnabled;
}
public void setIsLeaveMessageCaptchaEnabled(Boolean isLeaveMessageCaptchaEnabled) {
this.isLeaveMessageCaptchaEnabled = isLeaveMessageCaptchaEnabled;
}
public LeaveMessageDisplayType getLeaveMessageDisplayType() {
return leaveMessageDisplayType;
}
public void setLeaveMessageDisplayType(LeaveMessageDisplayType leaveMessageDisplayType) {
this.leaveMessageDisplayType = leaveMessageDisplayType;
}
public Boolean getIsCommentEnabled() {
return isCommentEnabled;
}
public void setIsCommentEnabled(Boolean isCommentEnabled) {
this.isCommentEnabled = isCommentEnabled;
}
public Boolean getIsCommentCaptchaEnabled() {
return isCommentCaptchaEnabled;
}
public void setIsCommentCaptchaEnabled(Boolean isCommentCaptchaEnabled) {
this.isCommentCaptchaEnabled = isCommentCaptchaEnabled;
}
public CommentAuthority getCommentAuthority() {
return commentAuthority;
}
public void setCommentAuthority(CommentAuthority commentAuthority) {
this.commentAuthority = commentAuthority;
}
public CommentDisplayType getCommentDisplayType() {
return commentDisplayType;
}
public void setCommentDisplayType(CommentDisplayType commentDisplayType) {
this.commentDisplayType = commentDisplayType;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
// 获取热门搜索关键词集合
public List<String> getHotSearchList() {
return StringUtils.isNotEmpty(hotSearch) ? Arrays.asList(hotSearch.split(HOT_SEARCH_SEPARATOR)) : new ArrayList<String>();
}
// 获取允许上传文件类型集合
public List<String> getAllowedUploadExtensionList() {
return StringUtils.isNotEmpty(allowedUploadExtension) ? Arrays.asList(allowedUploadExtension.split(ALLOWED_UPLOAD_EXTENSION_SEPARATOR)) : new ArrayList<String>();
}
} |
PHP | UTF-8 | 9,705 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by Generator.
* Package: org\majkel\tcpdfwarper
* User: Michał (majkel) Kowalik <maf.michal@gmail.com>
* Date: 2016-01-26
* Time: 23:13:35
*/
namespace org\majkel\tcpdfwarper;
/**
* Class TextOp
* @package org\majkel\tcpdfwarper
*
* Prints a text cell at the specified position.
* This method allows to place a string precisely on the page.
*
* @property float $x Abscissa of the cell origin
* @property float $y Ordinate of the cell origin
* @property string $txt String to print
* @property int $fstroke outline size in user units (false = disable)
* @property boolean $fclip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
* @property boolean $ffill if true fills the text
* @property mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
* @property int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
* @property string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
* @property boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
* @property mixed $link URL or identifier returned by AddLink().
* @property int $stretch font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
* @property boolean $ignoreMinHeight if true ignore automatic minimum height value.
* @property string $calign cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul>
* @property string $valign text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
* @property boolean $rtloff if true uses the page top-left corner as origin of axis for $x and $y initial position.
*
* @method TextOp setX(float $x) Abscissa of the cell origin
* @method TextOp setY(float $y) Ordinate of the cell origin
* @method TextOp setTxt(string $txt) String to print
* @method TextOp setFstroke(int $fstroke) outline size in user units (false = disable)
* @method TextOp setFclip(boolean $fclip) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
* @method TextOp setFfill(boolean $ffill) if true fills the text
* @method TextOp setBorder(mixed $border) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
* @method TextOp setLn(int $ln) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
* @method TextOp setAlign(string $align) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
* @method TextOp setFill(boolean $fill) Indicates if the cell background must be painted (true) or transparent (false).
* @method TextOp setLink(mixed $link) URL or identifier returned by AddLink().
* @method TextOp setStretch(int $stretch) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
* @method TextOp setIgnoreMinHeight(boolean $ignoreMinHeight) if true ignore automatic minimum height value.
* @method TextOp setCalign(string $calign) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul>
* @method TextOp setValign(string $valign) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
* @method TextOp setRtloff(boolean $rtloff) if true uses the page top-left corner as origin of axis for $x and $y initial position.
*
* @method float getX() Abscissa of the cell origin
* @method float getY() Ordinate of the cell origin
* @method string getTxt() String to print
* @method int getFstroke() outline size in user units (false = disable)
* @method boolean getFclip() if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
* @method boolean getFfill() if true fills the text
* @method mixed getBorder() Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
* @method int getLn() Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
* @method string getAlign() Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
* @method boolean getFill() Indicates if the cell background must be painted (true) or transparent (false).
* @method mixed getLink() URL or identifier returned by AddLink().
* @method int getStretch() font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
* @method boolean getIgnoreMinHeight() if true ignore automatic minimum height value.
* @method string getCalign() cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul>
* @method string getValign() text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
* @method boolean getRtloff() if true uses the page top-left corner as origin of axis for $x and $y initial position.
*
* @method void write()
* @method void render()
*/
class TextOp extends AbstractOp {
/**
* @codeCoverageIgnore
* @return array
*/
protected function getDefaultArguments() {
return array(
'x' => null,
'y' => null,
'txt' => null,
'fstroke' => false,
'fclip' => false,
'ffill' => true,
'border' => 0,
'ln' => 0,
'align' => '',
'fill' => false,
'link' => '',
'stretch' => 0,
'ignoreMinHeight' => false,
'calign' => 'T',
'valign' => 'M',
'rtloff' => false,
);
}
/**
* @codeCoverageIgnore
* @return string
*/
protected function getMethod() {
return 'Text';
}
/**
* @return void
*/
public function put() {
$this->assertArgExists('x');
$this->assertArgExists('y');
$this->assertArgExists('txt');
parent::put();
}
/**
* Sets position.
* @param float $x Abscissa of the cell origin
* @param float $y Ordinate of the cell origin
* @return TextOp
*/
public function setXY($x, $y) {
return $this->setX($x)->setY($y);
}
/**
* Sets position.
* @param float $x Abscissa of the cell origin
* @param float $y Ordinate of the cell origin
* @return TextOp
*/
public function setPos($x, $y) {
return $this->setX($x)->setY($y);
}
}
|
Java | UTF-8 | 654 | 1.960938 | 2 | [] | no_license | package com.spring.example.myfirstdemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.ArrayList;
@RestController
public class MyuserController {
@GetMapping("/hellodevops")
public String getNames() {
return ( "Welcome to Dockers and K8S, Jenkins ");
}
@GetMapping("/hellopgdevopsfolks")
public String getKanha() {
return ( "Welcome to pg devops folks and team");
}
@GetMapping("/helloteam")
public String getTeam() {
return ( "Welcome to my team");
}
}
|
Python | UTF-8 | 1,466 | 3.296875 | 3 | [] | no_license | __author__ = 'smy'
class Solution(object):
def maxProfit(self,prices):
if len(prices)==0:
return 0
result = 0
lastMax = prices[-1]
for val in reversed(prices[0:len(prices)-1]):
result = max(lastMax-val,result)
lastMax = max(lastMax,val)
return result
def generateParenthesis(self, n):
result = [""]
for i in range(n):
result[0] += "("
for i in range(n):
result[0] += ")"
for i in range(1,n):
for j in range(n,2*n-1):
result.append(result[0][0:i]+")"+result[0][i+1:j]+"("+result[0][j+1:])
for val in result:
print val
def helper(self,grid,endX,endY):
print endX,",",endY
if endX == endY and endX == 0:
return grid[0][0]
if endX < 0 or endY < 0:
return 0
print "no:",endX,",",endY
return min(self.helper(grid, endX-1, endY)+grid[endX][endY],self.helper(grid,endX,endY-1)+grid[endX][endY])
def minPathSum(self,grid):
print len(grid[0])-1,len(grid)-1
return self.helper(grid,len(grid[0])-1,len(grid)-1)
def test(self):
ll = [1,2]
for i in range(len(ll)):
print "size:",len(ll),i
ll.append(3)
solution = Solution()
# solution.generateParenthesis(3)
# print solution.maxProfit([2,1,3])
test = [[1,2,5],[3,2,1]]
# print solution.minPathSum(test)
|
Java | UTF-8 | 3,190 | 2.625 | 3 | [] | no_license | package de.amr.easy.grid.ui.swing.rendering;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.util.Optional;
import javax.swing.JComponent;
import de.amr.easy.data.Stack;
import de.amr.easy.grid.api.GridGraph2D;
import de.amr.easy.grid.impl.GridGraph;
/**
* A Swing component for displaying a grid.
*
* @author Armin Reichert
*/
public class GridCanvas extends JComponent {
protected final Stack<GridRenderer> rendererStack = new Stack<>();
protected GridGraph2D<?, ?> grid;
protected BufferedImage buffer;
protected Graphics2D g2;
public GridCanvas(GridGraph2D<?, ?> grid, int cellSize) {
if (grid == null) {
throw new IllegalArgumentException("No grid specified");
}
this.grid = grid;
setDoubleBuffered(false);
resizeTo(cellSize);
}
public GridGraph2D<?, ?> getGrid() {
return grid;
}
public void setGrid(GridGraph<?, ?> grid) {
if (grid == null) {
throw new IllegalArgumentException("No grid specified");
}
this.grid = grid;
}
public BufferedImage getDrawingBuffer() {
return buffer;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(buffer, 0, 0, null);
}
public void clear() {
getRenderer().ifPresent(r -> fill(r.getModel().getGridBgColor()));
repaint();
}
public void fill(Color bgColor) {
g2.setColor(bgColor);
g2.fillRect(0, 0, getWidth(), getHeight());
repaint();
}
public void drawGridCell(int cell) {
getRenderer().ifPresent(r -> r.drawCell(g2, grid, cell));
repaint();
}
public void drawGridPassage(int either, int other, boolean visible) {
getRenderer().ifPresent(r -> r.drawPassage(g2, grid, either, other, visible));
repaint();
}
public void drawGrid() {
getRenderer().ifPresent(r -> r.drawGrid(g2, grid));
repaint();
}
protected void resizeTo(int cellSize) {
int width = grid.numCols() * cellSize, height = grid.numRows() * cellSize;
setSize(new Dimension(width, height));
setPreferredSize(new Dimension(width, height));
buffer = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration().createCompatibleImage(width, height);
g2 = buffer.createGraphics();
}
public void setCellSize(int cellSize) {
resizeTo(cellSize);
repaint();
}
public Optional<GridRenderer> getRenderer() {
return rendererStack.peek();
}
public void pushRenderer(GridRenderer newRenderer) {
getRenderer().ifPresent(oldRenderer -> {
if (oldRenderer.getModel().getCellSize() != newRenderer.getModel().getCellSize()) {
resizeTo(newRenderer.getModel().getCellSize());
}
});
rendererStack.push(newRenderer);
repaint();
}
public GridRenderer popRenderer() {
if (rendererStack.isEmpty()) {
throw new IllegalStateException("Cannot remove last renderer");
}
GridRenderer oldRenderer = rendererStack.pop();
getRenderer().ifPresent(newRenderer -> {
if (oldRenderer.getModel().getCellSize() != newRenderer.getModel().getCellSize()) {
resizeTo(newRenderer.getModel().getCellSize());
}
});
repaint();
return oldRenderer;
}
} |
C# | UTF-8 | 808 | 2.546875 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneNavigator : MonoBehaviour {
public static SceneNavigator Instance;
public static List<int> sceneNums = new List<int> ();
public static void NewSceneRoute(string scene)
{
sceneNums.Clear ();
GoToScene (scene);
}
static void AddScene(Scene scene)
{
sceneNums.Add (scene.buildIndex);
}
static void AddCurrentScene()
{
AddScene (SceneManager.GetActiveScene ());
}
public static void GoToScene(string scene)
{
AddScene (SceneManager.GetSceneByName (scene));
SceneManager.LoadScene (scene);
}
public static void ReturnToPrevScene()
{
sceneNums.RemoveAt (sceneNums.Count - 1);
SceneManager.LoadScene (sceneNums [sceneNums.Count - 1]);
}
}
|
Java | UTF-8 | 1,795 | 2.046875 | 2 | [] | no_license | package usercenter.saleManage.model;
import java.util.Date;
public class AccessRecord {
private int record_id;
private int submit_id;
private String receive_name;
private int receive_id;
private Date create_dt;
private int access_status;
private int h_id;
private int accepter_reg_id;
private Date update_dt;
private Integer receive_invite_id;
public int getRecord_id() {
return record_id;
}
public void setRecord_id(int record_id) {
this.record_id = record_id;
}
public Date getCreate_dt() {
return create_dt;
}
public void setCreate_dt(Date create_dt) {
this.create_dt = create_dt;
}
public int getSubmit_id() {
return submit_id;
}
public void setSubmit_id(int submit_id) {
this.submit_id = submit_id;
}
public int getReceive_id() {
return receive_id;
}
public void setReceive_id(int receive_id) {
this.receive_id = receive_id;
}
public String getReceive_name() {
return receive_name;
}
public void setReceive_name(String receive_name) {
this.receive_name = receive_name;
}
public int getAccess_status() {
return access_status;
}
public void setAccess_status(int access_status) {
this.access_status = access_status;
}
public int getH_id() {
return h_id;
}
public void setH_id(int h_id) {
this.h_id = h_id;
}
public int getAccepter_reg_id() {
return accepter_reg_id;
}
public void setAccepter_reg_id(int accepter_reg_id) {
this.accepter_reg_id = accepter_reg_id;
}
public Date getUpdate_dt() {
return update_dt;
}
public void setUpdate_dt(Date update_dt) {
this.update_dt = update_dt;
}
public Integer getReceive_invite_id() {
return receive_invite_id;
}
public void setReceive_invite_id(Integer receive_invite_id) {
this.receive_invite_id = receive_invite_id;
}
}
|
Markdown | UTF-8 | 5,269 | 2.78125 | 3 | [
"MIT"
] | permissive | # ras-frontstage routes
This page documents the ras frontstage routes that can be hit.
## Passwords endpoints
To reset a password
`passwords/reset-password/<token>`
* POST request to this endpoint allows you to reset your password
* GET request to this endpoint allows you to get the password reset form
* `token` is used to be able to access the reset page
`passwords/reset-password/check-email`
* GET request to this endpoint is used to render a check e-mail template.
* Used primarily in the `resend-passowrd-email-expired-token` process
`passwords/reset-password/confirmation`
* GET request to this endpoint renders confirmation page that password's been changed.
`passwords/resend-password-email-expired-token/<token>`
* GET request to this endpoint is used to resend an e-mail to a user if their token has expired.
`passwords/forgot-password`
* GET request to this endpoint will return the forgot password page.
* POST request to this endpoint will send a reset password request to the party service.
`passwords/forgot-password/check-email`
* GET request to this endpoint is used to render the check e-mail template for forgot-password.
---
## Register endpoints
`register/activate-account/<token>`
* GET request to this endpoint is used to verify the e-mail address for the respondent.
`register/create-account/confirm-organisation-survey`
* GET request to this endpoint is used to confirm the organisation and survey details that the respondent is enrolling for.
`register/create-account`
* GET request to this endpoint will render a page to enter an enrolment code.
* POST request to this endpoint will validate the enrolment code used and display organisation and survey details.
`register/create-account/enter-account-details`
* GET request to this endpoint will display a form to enter in account details.
* POST request to this endpoint will attempt to create an account for this respondent.
---
## Secure messaging endpoints
`secure-message/create-message`
* GET request to this endpoint will display a form for the user to send a message.
* POST request to this endpoint will send a message.
`secure-message/thread/<thread-id>`
* GET request to this endpoint will display a conversation to the user using the `thread-id`.
* POST request to this endpoint will send a message from the conversation view.
* The `thread-id` is the ID of the conversation between the respondent and the internal user.
`secure-message/threads`
* GET request to this endpoint will display the list of conversations that the user currently has.
---
## Sign-in endpoints
`sign-in`
* GET request to this endpoint will return the log-in page for ras-frontstage.
* POST request to this endpoint will log-in the user to be to see their survey list.
`sign-in/resend_verification/<party_id>` - DEPRECATED. will be removed in a future release
* GET request to this endpoint will resend a verification e-mail to the respondent.
* `party_id` is the ID of the respondent.
`sign-in/resend-verification/<party_id>` - Replaces resend_verification
* GET request to this endpoint will resend a verification e-mail to the respondent.
* `party_id` is the ID of the respondent.
`sign-in/resend-verification-expired-token/<token>`
* GET request to this endpoint will resend a verification e-mail if the verification token has expired.
`sign-in/logout`
* GET request to this endpoint will sign-out the user from their session.
---
## Surveys endpoints
`surveys/access-survey` - Replaces access_survey
* GET request to this endpoint will allow the respondent to upload and download a survey if the ci_type is a SEFT.
If the ci_type is EQ then it'll redirect the user to EQ to complete a questionnaire.
`surveys/add-survey`
* POST request to this endpoint will allow the respondent to add another survey to their account.
`surveys/add-survey/confirm-organisation-survey`
* GET request to this endpoint will display to the user the survey they are adding to their account.
`surveys/add-survey/add-survey-submit`
* GET request to this endpoint will assign the new survey to the respondent.
Called by the `surveys/add-survey/confirm-organisation-survey` page.
`surveys/download-survey`
* GET request to this endpoint will download a survey that the respondent will need to complete.
Only used for SEFT surveys
`surveys/upload-survey`
* POST request to this endpoint will upload a collection instrument to the collection instrument service.
`surveys/upload-failed`
* GET request to this endpoint will render an error page if it fails to upload the collection instrument.
`surveys/<tag>`
* GET request to this endpoint will display to the respondent the surveys that they need to complete.
* `tag` can be either to-do or history.
---
## Contact us endpoints
`/contact-us`
* GET request to this endpoint will display contact details for the ONS.
---
## Cookies endpoints
`/cookies`
* GET request to this endpoint will display cookies that ONS collects on frontstage.
---
## Privacy endpoints
`/privacy-and-data-protection`
* GET request to this endpoint will display privacy and data protection information on frontstage.
---
## Info endpoint
`/info`
* GET request to this endpoint displays the current version of ras-frontstage.
|
C++ | UTF-8 | 5,132 | 2.5625 | 3 | [] | no_license | #include "ConvertProperty.h"
CORBA::Boolean
Property::extract_boolean_from_any(const CORBA::Any& a) {
CORBA::Boolean ret;
if(!(a >>= CORBA::Any::to_boolean(ret)))
throw type_exception();
return ret;
};
CORBA::Short
Property::extract_short_from_any(const CORBA::Any& a) {
CORBA::Short ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::UShort
Property::extract_ushort_from_any(const CORBA::Any& a) {
CORBA::UShort ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::Long
Property::extract_long_from_any(const CORBA::Any& a) {
CORBA::Long ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::LongLong
Property::extract_longlong_from_any(const CORBA::Any& a) {
CORBA::LongLong ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::ULong
Property::extract_ulong_from_any(const CORBA::Any& a) {
CORBA::ULong ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::ULongLong
Property::extract_ulonglong_from_any(const CORBA::Any& a) {
CORBA::ULongLong ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::Double
Property::extract_double_from_any(const CORBA::Any& a) {
CORBA::Double ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::Float
Property::extract_float_from_any(const CORBA::Any& a) {
CORBA::Float ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::Char
Property::extract_char_from_any(const CORBA::Any& a) {
CORBA::Char ret;
if(!(a >>= ret))
throw type_exception();
return ret;
};
CORBA::WChar
Property::extract_wchar_from_any(const CORBA::Any& a) {
CORBA::WChar ret;
if(!(a >>= CORBA::Any::to_wchar(ret)))
throw type_exception();
return ret;
};
CORBA::Octet
Property::extract_octet_from_any(const CORBA::Any& a) {
CORBA::Octet ret;
if(!(a >>= CORBA::Any::to_octet(ret)))
throw type_exception();
return ret;
};
CORBA::Char*
Property::extract_string_from_any(const CORBA::Any& a) {
CORBA::Char* ret = 0;
if(!(a >>= ret))
throw type_exception();
//CORBA::String_var tmp = ret;
return ret;
};
CORBA::WChar*
Property::extract_wstring_from_any(const CORBA::Any& a) {
CORBA::WChar* ret = 0;
if(!(a >>= CORBA::Any::to_wstring(ret, 0)))
throw type_exception();
return ret;
};
//###########################################
void
Property::string2any(CORBA::Any& any, const string type, const string val)
{
if( type == "boolean" )
{
CORBA::Boolean v;
if( val == "true" )
{
v = true;
}
else
{
v = false;
}
any <<= CORBA::Any::from_boolean( v );
}
if( type == "char" )
{
CORBA::Char v = val[0];
any <<= CORBA::Any::from_char( v );
}
if( type == "double" )
{
CORBA::Double v = atof( val.c_str() );
any <<= v;
}
if( type == "float" )
{
CORBA::Float v = atof( val.c_str() );
any <<= v;
}
if( type == "short" )
{
CORBA::Short v = atoi( val.c_str() );
any <<= v;
}
if( type == "long" )
{
CORBA::Long v = atol( val.c_str() );
any <<= v;
}
if( type == "objref" )
{
// TODO
}
if( type == "octet" )
{
CORBA::Octet v = val[0];
any <<= CORBA::Any::from_octet( v );
}
if( type == "string" )
{
any <<= val.c_str();
}
if( type == "ulong" )
{
CORBA::ULong v = atol( val.c_str() );
any <<= v;
}
if( type == "ushort" )
{
CORBA::UShort v = atoi( val.c_str() );
any <<= v;
}
}
//###################
void
Property::any2string(const CORBA::Any& a, string& type, string& value) {
char buf[50];
// get typecode
CORBA::TypeCode_var code =
a.type();
// scan aliases
while(code->kind() == CORBA::tk_alias)
code = code->content_type();
switch(code->kind()) {
case CORBA::tk_boolean: {
type = "boolean";
CORBA::Boolean b = extract_boolean_from_any(a);
if(b)
value = "true";
else
value = "false";
break;
}
case CORBA::tk_short: {
type = "short";
CORBA::Short s = extract_short_from_any(a);
_itoa(s, buf, 10);
value = buf;
break;
}
case CORBA::tk_ushort: {
type = "ushort";
CORBA::UShort s = extract_ushort_from_any(a);
_itoa(s, buf, 10);
value = buf;
break;
}
case CORBA::tk_long: {
type = "long";
CORBA::Long s = extract_long_from_any(a);
_ltoa(s, buf, 10);
value = buf;
break;
}
case CORBA::tk_ulong: {
type = "ulong";
CORBA::ULong s = extract_ulong_from_any(a);
_ltoa(s, buf, 10);
value = buf;
break;
}
case CORBA::tk_float: {
type = "float";
CORBA::Float s = extract_float_from_any(a);
_gcvt(s,20,buf);
value = buf;
break;
}
case CORBA::tk_double: {
type = "double";
CORBA::Double s = extract_double_from_any(a);
_gcvt(s,20,buf);
value = buf;
break;
}
case CORBA::tk_char: {
type = "char";
CORBA::Char c = extract_char_from_any(a);
value = c;
break;
}
case CORBA::tk_string: {
type = "string";
CORBA::Char* s = extract_string_from_any(a);
value = s;
break;
}
case CORBA::tk_wstring: {
type = "wstring";
wstring ws = extract_wstring_from_any(a);
// value = (const string) string(ws);
}
case CORBA::tk_sequence: {
type = "sequence of";
value = "";
break;
}
} //switch
} |
Ruby | UTF-8 | 1,039 | 3.5 | 4 | [] | no_license | #
# @lc app=leetcode id=222 lang=ruby
#
# [222] Count Complete Tree Nodes
#
# https://leetcode.com/problems/count-complete-tree-nodes/description/
#
# algorithms
# Medium (47.06%)
# Total Accepted: 248.8K
# Total Submissions: 528.7K
# Testcase Example: '[1,2,3,4,5,6]'
#
# Given a complete binary tree, count the number of nodes.
#
# Note:
#
# Definition of a complete binary tree from Wikipedia:
# In a complete binary tree every level, except possibly the last, is
# completely filled, and all nodes in the last level are as far left as
# possible. It can have between 1 and 2^h nodes inclusive at the last level h.
#
# Example:
#
#
# Input:
# 1
# / \
# 2 3
# / \ /
# 4 5 6
#
# Output: 6
#
#
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val = 0, left = nil, right = nil)
# @val = val
# @left = left
# @right = right
# end
# end
# @param {TreeNode} root
# @return {Integer}
def count_nodes(root)
end
|
Python | UTF-8 | 1,695 | 2.921875 | 3 | [
"MIT"
] | permissive | import enum
from typing import List
from rest_framework import status
from rest_framework.response import Response
class DataType(enum.Enum):
"""
Constants, used on generating error strings.
"""
QUERY = 'query'
PARAM = 'param'
BODY = 'body'
def extract_data(data: dict, keys: List[str]) -> (List[str], dict):
"""
Extract data based on keys.
:param data: dict-similar-typed source
:param keys: keys to extract value from source
:return: (keys that is not available on data, extracted data)
"""
missing = []
marshaled = {}
for key in keys:
if key in data:
marshaled[key] = data[key]
else:
missing.append(key)
return missing, marshaled
def missing_keys(data_type: DataType, keys: List[str]) -> Response:
"""
Create BAD REQUEST Response.
Indicate the request is missing query or param or body items.
:param data_type: missing data type
:param keys: missing item names
:return: Response
"""
errors = [
'missing {} {}'.format(data_type.value, key) for key in keys
]
return Response(
data={'errors': errors},
status=status.HTTP_400_BAD_REQUEST
)
def wrong_keys(data_type: DataType, keys: List[str]) -> Response:
"""
Create BAD REQUEST Response.
Indicate the request has invalid query or param or body items.
:param data_type: invalid data type
:param keys: invalid item names
:return: Response
"""
errors = [
'wrong {} {}'.format(data_type.value, key) for key in keys
]
return Response(
data={'errors': errors},
status=status.HTTP_400_BAD_REQUEST
)
|
Python | UTF-8 | 1,586 | 2.625 | 3 | [] | no_license | #!/usr/bin/env python
import requests
from bs4 import BeautifulSoup as soup
# In[100]:
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}
# In[101]:
html = requests.get(
'https://www.glassdoor.co.in/Job/los-angeles-data-scientist-jobs-SRCH_IL.0,11_IC1146821_KE12,26.htm',
headers=headers)
print(html.status_code)
# In[102]:
bsobj = soup(html.content, 'lxml')
# print(bsobj)
# In[ ]:
url_list = []
for i in range(1, 6):
url = 'https://www.glassdoor.co.in/Job/los-angeles-data-scientist-jobs-SRCH_IL.0,11_IC1146821_KE12,26.htm?p=' + str(
i)
# In[103]:
company_name = []
for company in bsobj.findAll('div', {'class': 'jobLink'}):
company_name.append(company.a.text.strip())
print(company_name)
# In[104]:
job_title = []
for title in bsobj.findAll('div', {'class': 'jobContainer'}):
job_title.append(title.findAll('a')[1].text.strip())
job_title
# In[105]:
location = []
for i in bsobj.findAll('div', {'class': 'jobInfoItem empLoc'}):
location.append(i.span.text.strip())
location
# In[106]:
links = []
for i in bsobj.findAll('div', {'class': 'jobContainer'}):
link = 'https://www.glassdoor.co.in' + i.a['href']
links.append(link)
links
# In[107]:
description = []
for link in links:
page = requests.get(link, headers=headers)
bs = soup(page.content, 'lxml')
for job in bs.findAll('div', {'id': 'JobDescriptionContainer'})[0]:
description.append(job.text.strip())
# In[108]:
description
# In[ ]:
|
C++ | UTF-8 | 2,146 | 2.96875 | 3 | [
"Apache-2.0",
"ISC",
"MIT"
] | permissive | #ifndef __IDX__UTILS__DATA_SET_GENERATORS__
#define __IDX__UTILS__DATA_SET_GENERATORS__
#include <algorithm>
#include <cstdint>
#include <fstream>
#include <string>
#include <set>
#include <vector>
#include "idx/utils/RandomRangeGenerator.hpp"
#include "idx/utils/CommandParser.hpp"
#include "idx/utils/8ByteDatFileIO.hpp"
namespace idx { namespace utils {
std::vector<uint64_t> createDenseDataSet(size_t size) {
std::vector<uint64_t> values(size);
for(size_t i = 0; i < size; ++i) {
values[i] = i;
}
return std::move(values);
}
std::vector<uint64_t> createPseudoRandomDataSet(size_t size) {
std::vector<uint64_t> values(size);
/*for(size_t i = 0; i < size/10; ++i) {
int(j = 0; j < 10; ++j) {
values[i] = (static_cast<uint64_t>(std::rand()) << 32) | i;;
}
}*/
for(size_t i = 0; i < size; ++i) {
values[i] = (static_cast<uint64_t>(std::rand()) << 32) | i;;
}
return std::move(values);
}
std::vector<uint64_t> createRandomDataSet(size_t size, bool isVerbose=false) {
RandomRangeGenerator<uint64_t> rnd { 0, INT64_MAX };
std::set<uint64_t> uniqueRandomValues;
std::vector<uint64_t> results(size);
if(isVerbose) {
std::cout << "Using seed:" << rnd.getSeed() << std::endl;
}
while(uniqueRandomValues.size() < size) {
uniqueRandomValues.insert(rnd());
}
return std::vector<uint64_t>(uniqueRandomValues.begin(), uniqueRandomValues.end());
};
std::vector<uint64_t> creatDataSet(CommandParser const & params, std::string const & typeParamName) {
std::string dataSetType = params.expect<std::string>(typeParamName);
std::vector<uint64_t> values;
if(dataSetType == "file") {
std::string inputFile = params.expectExistingFile("input");
values = idx::utils::readDatFile(inputFile, params.get("size", 0));
} else {
size_t size = params.expect<size_t>("size");
if(dataSetType == "dense") {
values = idx::utils::createDenseDataSet(size);
} else if(dataSetType == "pseudorandom") {
values = idx::utils::createPseudoRandomDataSet(size);
} else if(dataSetType == "random") {
values = idx::utils::createRandomDataSet(size, params.isVerbose());
}
}
return std::move(values);
}
} }
#endif |
Python | UTF-8 | 1,071 | 2.5625 | 3 | [] | no_license | from actions.login_actions import LoginActions
from facades import login_facade as login
from core.utils import datafile_handler as data_file
from facades import menu_facade as menu
import datetime
import pytest
#Prueba 1.- Registro con correo electrónico no válido
@pytest.mark.parametrize('label_email,label_password,data_email,data_password,message',data_file.get_data('./input_data/login.csv'))
def test_login_success(label_email, label_password, data_email, data_password, message):
global test_case_name
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') #20210511_211246
test_case_name = 'test_login_success {}'.format(timestamp)
menu.view_menu_option('My Account')
menu.click_menu_option('My Account')
login.login_facade(label_email, label_password, data_email, data_password, message)
#Metodo que se ejecuta siempre, despues de cada caso de prueba.
#Cierra la instancia del navegador
def teardown():
login_actions = LoginActions()
login_actions.save_screenshot(test_case_name)
login_actions.close_browser() |
Markdown | UTF-8 | 677 | 2.625 | 3 | [] | no_license | # 将查询条件保存为书签
*概述*.
书签能够用以保存查询条件,并与其它用户共享。
在搜索栏中输入查询条件并执行搜索。
点击位于搜索栏右侧的星型*书签*按钮,打开*新建书签*窗口。

输入书签的*名称*。
根据需要编辑*搜索字符串*一栏中的内容(如果可用)。
点击*确定*保存该查询条件为书签并关闭该窗口。
该搜索查询条件被保存并在*书签*栏中出现。
*结果*.
您将查询条件保存为书签以便之后使用。使用*书签*栏来查看并选择该书签。
|
Java | UTF-8 | 2,396 | 3.9375 | 4 | [] | no_license | public class ComputerPlayer
{
private CardStack2 myCards;
public ComputerPlayer()
{
myCards = new CardStack2();
}
public int getNumCards()
{
return myCards.size();
}
/**
* adds the given card to myCards.
* @param c - a card to add
*/
public void acceptCard(Card c)
{
// ---------------------------------
myCards.add(c);
// ---------------------------------
}
/**
* selects a card from the computer player to play on the given card, removing it from the computer player's stack of cards;
* returns null if a move is not available.
* @param otherCard - the card on which to play
* @return a card to play on this, or null, if we can't!
*/
public Card getPlayForCard(Card otherCard)
{
CardStack2 tempList = new CardStack2();
Card cardToPlay = null;
// ---------------------------------
// initial suggestion, make a temporary list of cards, initially empty. Loop through copies of all the cards in the
// computerplayer's stack and put the copy into our temporary list if the card could be played on otherCard.
for (int i = 0; i<= myCards.size(); i++)
{
Card t = myCards.getCopyOfCardAtIndex(i);
boolean match = t.isAMatch(otherCard);
if (match)
{
tempList.add(t);
}
}
// if there are any cards in this list, pick one at random. Remove it from the computerplayer's stack, and return it.
// if not, return null.
if (tempList.size() >= 1)
{
int random = (int)(Math.random()*tempList.size());
cardToPlay = tempList.getCopyOfCardAtIndex(random);
for (int i = 0; i<= myCards.size(); i++)
{
boolean same = cardToPlay.isTheSame(myCards.getCopyOfCardAtIndex(i));
if (same)
{
myCards.removeCardAtIndex(i);
}
}
}
else
{
cardToPlay = null;
}
// ---------------------------------
return cardToPlay;
}
public int size()
{
// ---------------------------------
int size = myCards.size();
// ---------------------------------
return size;
}
}
|
Shell | UTF-8 | 170 | 2.609375 | 3 | [] | no_license | #!/bin/bash
[[ -f ${HOME}/.dotrc ]] && source ${HOME}/.dotrc
pushd ${DOTFILES:-${HOME}/.dotfiles} &>/dev/null
git submodule update --init --recursive
popd &>/dev/null
|
PHP | UTF-8 | 708 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
use App\News;
use Faker\Factory as Faker;
class NewsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
for ($i = 0; $i < 12; $i++) {
$content = '';
for ($j = 0; $j < 8; $j++){
$content .= '<p>'. $faker->paragraph . '</p>';
}
$news = new News([
'title' => $faker->sentence,
'content' => $content,
'visible' => true,
'created_by' => 1,
]);
$news->save();
}
}
}
|
Java | UTF-8 | 335 | 1.867188 | 2 | [] | no_license | package hieuboy.developer.models;
import lombok.Data;
import java.io.Serializable;
@Data
public class PermissionModel implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String link;
private Boolean islock;
private Integer groupID;
}
|
PHP | UTF-8 | 1,104 | 2.640625 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | <?php
namespace Admin\Bundle\Authentication;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
class SuccessHandler implements AuthenticationSuccessHandlerInterface
{
protected $router;
protected $security;
public function __construct(Router $router , SecurityContext $security)
{
$this->router = $router;
$this->security = $security;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
if ($this->security->isGranted('ROLE_SUPER_ADMIN'))
return new RedirectResponse($this->router->generate('admin'));
elseif ($this->security->isGranted('ROLE_USER'))
return new RedirectResponse($this->router->generate('welcome'));
}
}
|
Markdown | UTF-8 | 3,577 | 3.296875 | 3 | [] | no_license | ---
layout: docs
title: External plugins
permalink: /docs/extending/external/
---
Albert can be extended using regular executables. They are used like plugins, however the executables are separate processes which have separate address spaces. Therefore these executables are called *external extensions*.
An external plugin basically acts as a listener. The plugin listens on the `stdin` data stream for requests and responds using the `stdout` channel. Generally such requests consist of a mandatory command and optional parameters. The set of commands, the expected responses and their format are defined in the section *Communication protocol*.
The great flexibility of the external plugins comes at a price: Since an external plugin is a separate process it has no access to the core components and helper classes. This holds the other way around as well,which means actions of the results passed to the core application are restricted to the execution of programs with parameters. Further the time to respond to the requests is limited.
#### Communication protocol
`INITIALIZE` is sent when the plugin has been loaded. Upon receiving this message the plugin shall initialize itself and check for dependencies. If no errors occurred in the initialization the plugin has to send `ACK`. If the response does not contain `ACK` the return message will be interpreted as an error string and the plugin will be unloaded. The process has 10 seconds to initialize itself. If the timeout is exceeded the plugin will be killed/unloaded forcefully.
`FINALIZE` is sent when the plugin is about to be unloaded. The plugin is assumed to finalize itself and quit the process. The process has 10 seconds to finalize itself. If the timeout is exceeded the plugin will be killed/unloaded forcefully.
`SETUPSESSION`/`TEARDOWNSESSION` are sent when the user started/ended a session. This is intended to trigger preparation/cleanup of a incoming/past queries. This operation has no timeout and no response is expected. However be aware that since this operation is not synchronized another message, which has a timeout, could have been sent while processing this message.
`QUERY` is the request to handle a query. The rest of the line after the command is the query as the user typed it, i.e. it contains the complete query including spaces and potential triggers. The results of the query have to be returned as a JSON array containing JSON objects representing the results. The plugin has 10 ms to respond to the query. If the timeout is exceeded the plugin will be killed/unloaded forcefully.
A result object has to contain the following values: `id`, `name`, `description`, `icon` and `actions`.
- `id` is the plugin wide unique id of the result
- `name` is the name of the result
- `description` is the description of the result
- `icon` is the icon of the result
- `actions` is a JSON array of JSON objects representing the actions for the item.
A JSON object representing an action has to contain the following values: `name`, `command` and `arguments`.
- `name` is the actions name
- `command` is the program to be execute
- `arguments` is an array of parameters for `command`
An example query response could look like this:
```json
[{
"id":"plugin.wide.unique.id",
"name":"An Item",
"description":"Nice description.",
"icon":"/path/to/icon",
"actions":[{
"name":"Action name",
"command":"program",
"arguments":["-a"]
},{
"name":"Another action name",
"command":"another_program",
"arguments":["--name", "value"]
}]
}]
```
|
PHP | UTF-8 | 10,910 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Utility;
use Illuminate\Http\Request;
use App\Utility;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;
class UtiliyController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
private $types;
private $names;
private $form ;
private $is_addable;
function __construct()
{
$this->types= config('utility.types');
$this->names= config('utility.names');
$this->form= config('utility.forms');
$this->is_addable= config('utility.addable');
}
public function get_utilities()
{
return $this->names;
}
public function index($type)
{
if(in_array($type,$this->types))
{
$content=Utility::where('type',$type)->paginate(500);
return View('admin.utility.utilities', ['content' => $content,'type' => $type,'names' => $this->names,'form' => $this->form[$type],'addable' => $this->is_addable[$type]]);
}
return abort(404);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request,$name)
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request,$type)
{
if(in_array($type,$this->types) && $this->is_addable[$type]) {
// $this->validate($request, array(
// 'title_a' => 'required'
// ));
$about = new Utility();
if ($request->input('active') == "true")
$about->active = true;
else
$about->active = false;
$about->type = $type;
$about->title = $request->input('title_a');
$data = array();
foreach ($this->form[$type] as $key => $value)
{
$data[$key]=$request->input($key);
if($value['type']=='file'){
if ($request->hasFile($key)) {
$image = $request->file($key);
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('images/');
$image->move($path, $filename);
$data[$key] = 'images/' . $filename;
}
}
}
$about->data = $data;
$about->save();
Artisan::call('view:clear');
return redirect()->route('utility.index',['name' => $type])
->with('success', 'Setting Added');
}
return abort(404);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request,$type, $id)
{
if(in_array($type,$this->types)) {
// $this->validate($request, array(
// 'title_a' => 'required'
//
// ));
$about = Utility::find($id);
$about->title = $request->input('title_a');
if ($request->input('active') == "true")
$about->active = true;
else
$about->active = false;
$data = array();
foreach ($this->form[$type] as $key => $value)
{
$data[$key]=$request->input($key);
if($value['type']=='file'){
if ($request->hasFile($key)) {
$image = $request->file($key);
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('images/');
$image->move($path, $filename);
$data[$key] = 'images/' . $filename;
}
elseif (isset($about->data[$key]))
$data[$key] = $about->data[$key];
}
}
$about->data = $data;
$about->save();
Artisan::call('view:clear');
return redirect()->route('utility.index',['name' => $type])
->with('success', 'Setting Updated');
}
return abort(404);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($type,$id)
{
if(in_array($type,$this->types) && $this->is_addable[$type]) {
Utility::destroy($id);
return redirect()->route('utility.index',['name' => $type])
->with('success', 'Setting Deleted');
}
return abort(404);
}
}
//
//class UtiliyController extends Controller
//{
//
//
// /**
// * Display a listing of the resource.
// *
// * @return \Illuminate\Http\Response
// */
// private $types;
// private $names;
//
// private $form ;
//
// private $is_addable;
//
//
// function __construct()
// {
// $this->types= config('utility.types');
// $this->names= config('utility.names');
// $this->form= config('utility.forms');
// $this->is_addable= config('utility.addable');
//
// }
//
// public function get_utilities()
// {
// return $this->names;
// }
//
// public function index($type)
// {
//
//
// if(in_array($type,$this->types))
// {
// $content=Utility::where('type',$type)->paginate(500);
// return View('admin.utility.utilities', ['content' => $content,'type' => $type,'names' => $this->names,'form' => $this->form[$type],'addable' => $this->is_addable[$type]]);
// }
// return abort(404);
//
// }
//
// /**
// * Show the form for creating a new resource.
// *
// * @return \Illuminate\Http\Response
// */
// public function create(Request $request,$name)
// {
//
// }
//
// /**
// * Store a newly created resource in storage.
// *
// * @param \Illuminate\Http\Request $request
// * @return \Illuminate\Http\Response
// */
// public function store(Request $request,$type)
// {
// if(in_array($type,$this->types)) {
// $this->validate($request, array(
// 'title_a' => 'required'
// ));
// $about = new Utility();
// if ($request->input('active') == "true")
// $about->active = true;
// else
// $about->active = false;
// $about->type = $type;
// $about->title = $request->input('title_a');
//
//
// $data = array();
// foreach ($this->form[$type] as $key => $value)
// {
// $data[$key]=$request->input($key);
// if($value['type']=='file'){
// if ($request->hasFile($key)) {
// $image = $request->file($key);
// $filename = time() . '.' . $image->getClientOriginalExtension();
// $path = public_path('images/');
// $image->move($path, $filename);
// $data[$key] = 'images/' . $filename;
//
//
// }
// }
// }
//
//
//
// $about->data = $data;
// $about->save();
//
// return redirect()->route('utility.index',['name' => $type])
// ->with('success', 'ساخته شد');
// }
// return abort(404);
// }
//
// /**
// * Display the specified resource.
// *
// * @param int $id
// * @return \Illuminate\Http\Response
// */
// public function show($id)
// {
// //
// }
//
// /**
// * Show the form for editing the specified resource.
// *
// * @param int $id
// * @return \Illuminate\Http\Response
// */
// public function edit($id)
// {
// //
// }
//
// /**
// * Update the specified resource in storage.
// *
// * @param \Illuminate\Http\Request $request
// * @param int $id
// * @return \Illuminate\Http\Response
// */
// public function update(Request $request,$type, $id)
// {
// if(in_array($type,$this->types)) {
// $this->validate($request, array(
// 'title_a' => 'required'
//
// ));
// $about = Utility::find($id);
// $about->title = $request->input('title_a');
// if ($request->input('active') == "true")
// $about->active = true;
// else
// $about->active = false;
//
// $data = array();
//
// foreach ($this->form[$type] as $key => $value)
// {
// $data[$key]=$request->input($key);
// if($value['type']=='file'){
// if ($request->hasFile($key)) {
// $image = $request->file($key);
// $filename = time() . '.' . $image->getClientOriginalExtension();
// $path = public_path('images/');
// $image->move($path, $filename);
// $data[$key] = 'images/' . $filename;
//
//
// }
// elseif (isset($about->data[$key]))
// $data[$key] = $about->data[$key];
// }
// }
// $about->data = $data;
// $about->save();
//
// return redirect()->route('utility.index',['name' => $type])
// ->with('success', 'به روز رسانی انجام شد');
// }
// return abort(404);
// }
//
// /**
// * Remove the specified resource from storage.
// *
// * @param int $id
// * @return \Illuminate\Http\Response
// */
// public function destroy($type,$id)
// {
//
// if(in_array($type,$this->types)) {
// Utility::destroy($id);
// return redirect()->route('utility.index',['name' => $type])
// ->with('success', 'با موفقیت حذف شد');
// }
// return abort(404);
// }
//}
|
Java | UTF-8 | 1,282 | 2 | 2 | [
"MIT"
] | permissive | package com.workflow.controller;
import com.workflow.entity.UserRole;
import com.workflow.entity.activiti.ResultListDataRepresentation;
import com.workflow.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EditorGroupsController {
@Autowired
private UserService userService;
@RequestMapping(value = "/**/rest/editor-groups", method = RequestMethod.GET)
public ResultListDataRepresentation getGroups(@RequestParam(required = false, value = "filter") String filter) {
String groupNameFilter = filter;
if (StringUtils.isEmpty(groupNameFilter)) {
groupNameFilter = "%";
} else {
groupNameFilter = "%" + groupNameFilter + "%";
}
List<UserRole> roleList = userService.getMatchingRoles(groupNameFilter);
ResultListDataRepresentation result = new ResultListDataRepresentation(roleList);
return result;
}
}
|
PHP | UTF-8 | 628 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Domain\Post\Http\Requests\Review;
use App\Infrastructure\Http\AbstractRequests\BaseRequest as FormRequest;
class PostReviewStoreFormRequest extends FormRequest
{
/**
* Determine if the post is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'body' => 'nullable|min:8',
'score' => 'required|integer|min:1|max:5',
];
}
}
|
Java | UTF-8 | 701 | 2.296875 | 2 | [] | no_license | package com.luyunfeng.selectionpanel;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by luyunfeng on 2016/12/18.
*/
public class ItemMarginDecoration extends RecyclerView.ItemDecoration {
private int[] itemMargin = new int[4];
public ItemMarginDecoration(int[] itemMargin) {
this.itemMargin = itemMargin;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = itemMargin[0] / 2;
outRect.top = itemMargin[1] / 2;
outRect.right = itemMargin[2] / 2;
outRect.bottom = itemMargin[3] /2;
}
}
|
PHP | UTF-8 | 1,885 | 3.3125 | 3 | [] | no_license | <?php
// connecting to the database
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "manishadb_testing";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// die if connection was unsuccessfull
if (!$conn){
die("sorry we failed to connect ". mysqli_connect_error());
}
else{
echo "Great!! connection was successfull";
}
$sql = " SELECT * FROM table_php_trip ";
$result = mysqli_query($conn,$sql);
// find the number of records returned
echo "<br>";
// mysqli_num_rows($result) is a function to count the number of rows in table
$numRows = mysqli_num_rows($result);
echo "Total number of records found in the database are: " . $numRows;
echo "</br>";
// Display the Rows returned by the sql query
// if ($numRows > 0){
// $row = mysqli_fetch_assoc($result);
// echo "<br>";
// echo var_dump($row);
// mysqli_fetch_assoc() function fetches the records one by one until it reaches at the end of the records i.e at NULL. It will be always a next array ,assoc means it always returns an associative array
// $row = mysqli_fetch_assoc($result);
// echo "<br>";
// echo var_dump($row);
// $row = mysqli_fetch_assoc($result);
// echo "<br>";
// echo var_dump($row);
// $row = mysqli_fetch_assoc($result);
// echo "<br>";
// echo var_dump($row);
// $row = mysqli_fetch_assoc($result);
// echo "<br>";
// echo var_dump($row);
// $row = mysqli_fetch_assoc($result);
// echo "<br>";
// echo var_dump($row);
// we can fetch in a better way using while loop
while ($row = mysqli_fetch_assoc($result)){
echo "</br>";
// echo var_dump($row);
echo $row['id']. ". Hello ". $row['name']." welcome to " . $row['destination'];
echo "</br>";
}
mysqli_close($conn);
?> |
Java | UTF-8 | 16,896 | 2.984375 | 3 | [] | no_license | package com.appliedminds.martini;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* The GraphPanel analog of a standard Graph datastructure. This
* graph is drawable so it has a method on it that can cuase it to
* draw itself. In fact, it doesn't really draw itself, it delegates
* to some concrete GraphUI object to do that.
*
* <p>The main responsibilities of the DrawableGraph are:
*
* <ul>
*
* <li>To keep track of its nodes and edges.
*
* <li>To hold on to a reference of a GraphUI implementor.
*
* <li>To perform coarse-grained hit testing, and to delegate
* fine-grained hit testing to nodes and edges.
*
* <li>To hold graph properties.
*
* </ul>
*
* <p>Objects that are interested in hit test results on this graph
* can register as HitTestListeners. The hit-test interface is
* provided so that this object can work properly inside of some
* higher-level component, like a GraphPanel. Client code that is
* using a GraphPanel to display the graph will not normally use this
* interface-- instead the client code will register for specific
* DrawableGraphEvents in the (for example) GraphPanel.
*
*
* @author will@apmindsf.com
* @author daepark@apmindsf.com
* @author mathias@apmindsf.com
*/
public class DrawableGraph {
private GraphUI _graphUI;
private ArrayList _hitTestListeners;
private Properties _props;
private NodeList _nodeList;
private EdgeList _edgeList;
/**
* (Not sure how we're creating graph yet. This will be rewritten later.)
*/
public DrawableGraph() {
_hitTestListeners = new ArrayList();
_props = new Properties();
_nodeList = new NodeList();
_edgeList = new EdgeList();
}
/**
* Create a new node in this graph.
*
* @return the newly created DrawableNode.
*/
public DrawableNode createNode() {
DrawableNode node = new DrawableNode(this);
_nodeList.add(node);
return node;
}
/**
* Create an edge in this graph.
*
* @param head a DrawableNode we want to connect the new edge to. This
* will be the head node if the graph is directed.
* @param tail a DrawableNode we want to connect the new edge to. This
* will be the tail node if the graph is directed.
* @return the newly created DrawableEdge.
*/
public DrawableEdge createEdge(DrawableNode head, DrawableNode tail)
{
if (!_nodeList.contains(head))
throw (new RuntimeException("head node does not exist in the graph"));
if (!_nodeList.contains(tail))
throw (new RuntimeException("tail node does not exist in the graph"));
DrawableEdge edge = new DrawableEdge(this, head, tail);
_edgeList.add(edge);
// update head and tail edge lists
head.addIncomingEdge(edge);
tail.addOutgoingEdge(edge);
// update node lists
head.addTailNode(tail);
tail.addHeadNode(head);
return edge;
}
/**
* Remove a node from the graph. All connecting edges will also be
* removed.
*
* @param node the DrawableNode to remove from this graph.
*/
public void remove(DrawableNode node) {
// Remove outgoing edges.
EdgeIterator edges = node.getOutgoingEdges();
while (edges.hasNext()) {
remove(edges.next());
}
// Remove incoming edges.
edges = node.getIncomingEdges();
while (edges.hasNext()) {
remove(edges.next());
}
// finally remove node
_nodeList.remove(node);
}
/**
* Remove an edge from the graph.
*
* @param edge the edge we want to remove from the graph.
*/
public void remove(DrawableEdge edge) {
// the connected nodes
DrawableNode head = edge.getHead();
DrawableNode tail = edge.getTail();
// remove tail from tail node list of head node
head.removeTailNode(tail);
head.removeIncomingEdge(edge);
// remove head from head node list of tail node
tail.removeHeadNode(head);
tail.removeOutgoingEdge(edge);
// finally remove edge
_edgeList.remove(edge);
}
/**
* Set the GraphUI. This should invalidate (as far as drawing goes)
* the current graph.
*
* @param graphUI the GraphUI implementation to use with this graph.
*/
void setGraphUI(GraphUI graphUI) {
_graphUI = graphUI;
}
/**
* Get the current GraphUI that this graph is using.
*
* @return the GraphUI implementation this graph uses.
*/
GraphUI getGraphUI() {
return _graphUI;
}
/**
* Get the collection of nodes.
*
* @return an Iterator over the nodes in this graph.
*/
public NodeIterator nodesIterator() {
return (_nodeList.iterator());
}
/**
* Get the collection of edges.
*
* @return an Iterator over the edges in this graph.
*/
public EdgeIterator edgesIterator() {
return (_edgeList.iterator());
}
/**
* Draw this graph in the given Graphics Context.
*
* @param g the Graphics Context to use for drawing this graph.
* @param vp the viewport for translating into viewport coords.
* @param hit the hit tester map (modified).
* @param ctx the context info for the current graph.
* @param newBuffer a rendering hint passed on to the UI indicating
* that the graphics context is from a freshly created image buffer.
* @param erase a rendering hint passed on to the UI indicating that
* the UI should first try erasing the previously drawn self first
* before drawing.
*/
public void draw(Graphics2D g,
Viewport vp,
HitTesterMap hit,
DrawableGraphContext ctx,
boolean newBuffer,
boolean erase)
{
drawEdges(g, vp, hit, ctx, newBuffer, erase);
drawNodes(g, vp, hit, ctx, newBuffer, erase);
}
/**
* Add a HitTestListener to this object. Registered listeners will
* be notified when a hit test is successful.
*
* @param l a listener.
*/
public void addHitTestListener(HitTestListener l) {
_hitTestListeners.add(l);
}
public void removeHitTestListener(HitTestListener l) {
_hitTestListeners.remove(l);
}
/**
* Notify all registered listeners that a hit test has succeeded.
*
* @param decorationId the UI decoration identifier.
* @param obj the object that was hit.
* @param evt the raw awt event.
* @param context some context object passed up from the UI.
*/
public boolean notifyHitTestSuccess(String decorationId,
DrawableGraphElement obj,
MouseEvent evt,
Object context)
{
boolean consumed = false;
for(Iterator i = _hitTestListeners.iterator(); i.hasNext(); ) {
consumed = consumed ||
((HitTestListener) i.next()).hitTestSuccess(decorationId, obj, context, evt);
}
return(consumed);
}
/**
* Notify all registered listeners that the mouse has entered a
* graph objects space.
*
* @param decorationId the UI decoration identifier.
* @param obj the object that was hit.
* @param evt the raw awt event.
* @param context some context object passed up from the UI.
*/
public boolean notifyMouseEntered(String decorationId,
DrawableGraphElement obj,
MouseEvent evt,
Object context)
{
MouseEvent mevt = createMouseEvent(evt, MouseEvent.MOUSE_ENTERED);
boolean consumed = false;
for(Iterator i = _hitTestListeners.iterator(); i.hasNext(); ) {
HitTestListener htl = (HitTestListener) i.next();
consumed = consumed ||
htl.hitTestSuccess(decorationId, obj, context, mevt);
}
return(consumed);
}
/**
* Notify all registered listeners that the mouse has exited a
* graph objects space.
*
* @param decorationId the UI decoration identifier.
* @param obj the object that was hit.
* @param evt the raw awt event.
* @param context some context object passed up from the UI.
*/
public boolean notifyMouseExited(String decorationId,
DrawableGraphElement obj,
MouseEvent evt,
Object context)
{
MouseEvent mevt = createMouseEvent(evt, MouseEvent.MOUSE_EXITED);
boolean consumed = false;
for(Iterator i = _hitTestListeners.iterator(); i.hasNext(); ) {
consumed = consumed ||
((HitTestListener) i.next()).hitTestSuccess(decorationId, obj, context, mevt);
}
return(consumed);
}
/**
* Notify all registered listeners that a hit test has missed the
* graph.
*
* @param evt the raw awt event.
*/
public void notifyHitMissedGraph(MouseEvent evt) {
for(Iterator i = _hitTestListeners.iterator(); i.hasNext(); ) {
((HitTestListener) i.next()).hitTestMissedGraph(evt);
}
}
/**
* Notify all registered listeners that multiple elements in the
* graph objects space have been "hit"
*
* @param hitElements the list of graph objects that
*/
public void notifyMultipleHitTestSuccess(Object[] hitElements,
Rectangle2D rect)
{
Iterator itr = _hitTestListeners.iterator();
while (itr.hasNext()) {
((HitTestListener)itr.next()).multipleHitTestSuccess(hitElements, rect);
}
}
public void notifyMultipleHitTestMissedGraph(Rectangle2D rect) {
Iterator itr = _hitTestListeners.iterator();
while (itr.hasNext()) {
((HitTestListener)itr.next()).multipleHitTestMissedGraph(rect);
}
}
/**
* Get the list of graph elements that intersect the specified rectangle.
*
* @param map a HitTesterMap object
* @param rect the rectangle in VIEWPORT coordinates
* @return a list of DrawableGraphElements that intersect the
* specified rectangle.
*/
public Set getIntersectingElements(HitTesterMap map,
Rectangle2D rect)
{
Set hitElements = new HashSet();
//
// hit test nodes
//
NodeIterator itr = nodesIterator();
while (itr.hasNext()) {
DrawableNode node = itr.next();
HitTestResult[] nodeHitTestResults= node.hitTest(map, rect);
for (int i = 0; i < nodeHitTestResults.length; i++) {
hitElements.add(nodeHitTestResults[i].getHitTester().getContext());
}
}
//
// hit test edges
//
EdgeIterator itr2 = edgesIterator();
while (itr2.hasNext()) {
DrawableEdge edge = itr2.next();
HitTestResult[] edgeHitTestResults = edge.hitTest(map, rect);
for (int i = 0; i < edgeHitTestResults.length; i++) {
hitElements.add(edgeHitTestResults[i].getHitTester().getContext());
}
}
return (hitElements);
}
/**
* Perform multiple hit testing on the graph. Hit test all graph
* elements within the specified rectangle. Objects registered with
* the HitTestListeners will be notified of success or miss.
*
* @param vp the current viewport.
* @param rect the bounds considered to be a "hit" by the * user in
* WORLD coordinates.
*/
public void performHitTesting(HitTesterMap map,
Viewport vp,
Rectangle2D rect)
{
//
// Do fine grained hit testing on nodes, then edges using VIEWPORT
// coordinates.
//
Rectangle2D vpRect = vp.mapWorldToViewport(rect);
Set hitElements = getIntersectingElements(map, vpRect);
//
// notify multiple hit listeners
//
if (hitElements.size() > 0) {
notifyMultipleHitTestSuccess(hitElements.toArray(), vpRect);
}
else {
notifyMultipleHitTestMissedGraph(vpRect);
}
}
/**
* Perform hit testing on the graph. Objects registered with the as
* HitTestListeners will be notified of success.
*
* @param vp the current viewport.
* @param rect the area "hit" by the user in WORLD coordinates.
* @param event the original awt input event.
*/
public void performHitTesting(HitTesterMap map,
Viewport vp,
Rectangle2D rect,
MouseEvent event)
{
// FIX: Should do corse hit testing first using world coordinates.
boolean graphObjectHit = false;
//
// Do fine grained hit testing on nodes, then edges using VIEWPORT
// coordinates.
//
Point2D wpt = new Point2D.Double(rect.getX(), rect.getY());
Point2D vpt = vp.mapWorldToViewport(wpt);
Rectangle2D vpRect = new Rectangle2D.Double(vpt.getX(),
vpt.getY(),
rect.getWidth(),
rect.getHeight());
boolean consumed = false;
for(NodeIterator i = nodesIterator(); i.hasNext();) {
DrawableNode n = i.next();
HitTestResult res = n.hitTest(map, vpRect, event);
if (res.wasHit()) {
if (!graphObjectHit) {
graphObjectHit = true;
}
if (res.wasConsumed()) {
consumed = true;
break;
}
}
}
// Contiue with the edges only if one of the nodes didn't take it.
if (!consumed) {
for(EdgeIterator i = edgesIterator(); i.hasNext(); ) {
DrawableEdge e = i.next();
HitTestResult res = e.hitTest(map, vpRect, event);
if (res.wasHit()) {
if (!graphObjectHit) {
graphObjectHit = true;
}
if (res.wasConsumed()) {
break;
}
}
}
}
//
// If user clicked outside the graph, that is interesting. Note
// that this could be done during/right after the coarse testing
// (which is not implemented).
//
if (!graphObjectHit) {
int id = event.getID();
if ((id == MouseEvent.MOUSE_CLICKED) ||
(id == MouseEvent.MOUSE_RELEASED) ||
(id == MouseEvent.MOUSE_PRESSED))
{
notifyHitMissedGraph(event);
}
}
}
/**
* Get an arbitrary string property from the graph.
*
* @param key to a property we want.
* @return the value for the given key.
*/
public String getProperty(String key) {
return (_props.getProperty(key));
}
/**
* Set an arbitrary string property on the graph.
*
* @param key the key to a property value we want to set on this graph.
* @param val the value for the key we want to set on this graph.
*/
public void setProperty(String key, String val) {
_props.setProperty(key, val);
}
/**
* @return an Iterator for all the property keys this graph knows about.
*/
public Iterator getPropertyKeys() {
return (_props.keySet().iterator());
}
/**
* Remove a property (key and value) from the graph.
*
* @param key the key of the property to remove.
*/
public void removeProperty(String key) {
if (key != null) {
_props.remove(key);
}
}
/*
* Create a mouse event based on the given mouse event and type.
*/
private MouseEvent createMouseEvent(MouseEvent orig, int type)
{
return(new MouseEvent(orig.getComponent(),
type,
orig.getWhen(),
orig.getModifiers(),
orig.getX(),
orig.getY(),
orig.getClickCount(),
orig.isPopupTrigger()));
}
/**
* Draw an edge in the given Graphics Context.
*
* @param g the Graphics Context to use for drawing the edge.
*/
private void drawEdges(Graphics2D g,
Viewport vp,
HitTesterMap hit,
DrawableGraphContext ctx,
boolean newBuffer,
boolean erase)
{
for (EdgeIterator it=edgesIterator(); it.hasNext();) {
DrawableEdge edge = it.next();
edge.draw(g, vp, hit, ctx, newBuffer, erase);
}
}
/**
* Draw a node in the given Graphics Context.
*
* @param g the Graphics Context to use for drawing the node.
*/
private void drawNodes(Graphics2D g,
Viewport vp,
HitTesterMap hit,
DrawableGraphContext ctx,
boolean newBuffer,
boolean erase)
{
for (NodeIterator it=nodesIterator(); it.hasNext();) {
DrawableNode node = it.next();
node.draw(g, vp, hit, ctx, newBuffer, erase);
}
}
} // end class DrawableGraph
|
Java | UTF-8 | 8,753 | 1.859375 | 2 | [] | no_license | package com.mrbt.lingmoney.admin.service.bank.impl;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.mrbt.lingmoney.admin.service.bank.HxEnterpriseBindCardService;
import com.mrbt.lingmoney.bank.enterprise.HxEnterpriseBindCard;
import com.mrbt.lingmoney.mapper.EnterpriseBindcardMapper;
import com.mrbt.lingmoney.mapper.EnterpriseRechargeMapper;
import com.mrbt.lingmoney.model.EnterpriseBindcard;
import com.mrbt.lingmoney.model.EnterpriseBindcardExample;
import com.mrbt.lingmoney.model.EnterpriseRecharge;
import com.mrbt.lingmoney.model.EnterpriseRechargeExample;
import com.mrbt.lingmoney.utils.PageInfo;
import com.mrbt.lingmoney.utils.PropertiesUtil;
import com.mrbt.lingmoney.utils.ResultParame.ResultInfo;
import com.mrbt.lingmoney.utils.ResultParame.ResultNumber;
/**
*
*@author syb
*@date 2017年9月29日 下午1:59:18
*@version 1.0
**/
@Service
public class HxEnterpriseBindCardServiceImpl implements HxEnterpriseBindCardService {
private static final String BANK_URL = PropertiesUtil.getPropertiesByKey("BANK_POST_URL");
@Autowired
private HxEnterpriseBindCard hxEnterpriseBindCard;
@Autowired
private EnterpriseRechargeMapper enterpriseRechargeMapper;
@Autowired
private EnterpriseBindcardMapper enterpriseBindcardMapper;
@Override
public Map<String, String> requestUnBindCard(String appId, Integer clientType, String bankNo, String logGroup) {
if (StringUtils.isEmpty(bankNo)) {
return null;
}
Map<String, String> resultMap = hxEnterpriseBindCard.requestEnterpriseUnbindCard(clientType, appId, bankNo, "",
logGroup);
resultMap.put("bankUrl", BANK_URL);
return resultMap;
}
@Override
public PageInfo listEnterpriseRechargeRecord(String date, String bankNo, String transType, Integer page,
Integer rows) {
PageInfo pi = new PageInfo(page, rows);
EnterpriseRechargeExample example = new EnterpriseRechargeExample();
EnterpriseRechargeExample.Criteria criteria = example.createCriteria();
if (!StringUtils.isEmpty(date)) {
criteria.andTransDateLike(date.replaceAll("-", "") + "%");
}
if (!StringUtils.isEmpty(bankNo)) {
criteria.andBankAccountNoEqualTo(bankNo);
}
if (!StringUtils.isEmpty(transType)) {
criteria.andTransTypeEqualTo(transType);
}
example.setLimitStart(pi.getFrom());
example.setLimitEnd(pi.getSize());
List<EnterpriseRecharge> list = enterpriseRechargeMapper.selectByExample(example);
pi.setRows(list);
if (list != null && list.size() > 0) {
pi.setCode(ResultInfo.SUCCESS.getCode());
pi.setMsg(ResultInfo.SUCCESS.getMsg());
pi.setTotal(enterpriseRechargeMapper.countByExample(example));
} else {
pi.setTotal(0);
}
return pi;
}
@Override
public PageInfo listEnterpriseBindCard(String acNo, Integer page, Integer rows) {
if (StringUtils.isEmpty(acNo)) {
return null;
}
String logGroup = "\nhxEnterpriseBindCardQueryInfo_" + System.currentTimeMillis() + "_";
// 分页条件写死为 第一页 每页40条
queryBindCardResult(acNo, "1", "40", logGroup);
PageInfo pi = new PageInfo(page, rows);
EnterpriseBindcardExample example = new EnterpriseBindcardExample();
example.createCriteria().andEAccBanknoEqualTo(acNo);
example.setLimitStart(pi.getFrom());
example.setLimitEnd(pi.getSize());
List<EnterpriseBindcard> list = enterpriseBindcardMapper.selectByExample(example);
pi.setRows(list);
if (list != null && list.size() > 0) {
pi.setTotal(enterpriseBindcardMapper.countByExample(example));
} else {
pi.setTotal(0);
}
return pi;
}
/**
* 处理企业绑卡信息查询
* @author yiban
* @date 2017年10月20日 下午6:46:12
* @version 1.0
* @param acNo E账户
* @param currentPage currentPage
* @param pageNumber pageNumber
* @param logGroup logGroup
* @param doc XML文档
*/
private void handleEnterpriseBindCardRecord(String acNo, String currentPage, String pageNumber, String logGroup,
Document doc) {
// doc为空表示有多页,所以需要再次查询
if (doc == null) {
doc = hxEnterpriseBindCard.queryEnterpriseBindCardInfo(acNo, currentPage, pageNumber, logGroup);
}
if (doc != null && doc.selectNodes("//CARDS") != null) {
@SuppressWarnings("unchecked")
List<Element> rsList = doc.selectNodes("//CARDS");
if (rsList != null && rsList.size() > 0) {
for (Element rsElem : rsList) {
EnterpriseBindcard enterpriseBindCard = new EnterpriseBindcard();
String acno = rsElem.selectSingleNode("//ACNO").getText(); // 企业银行账户
String cardno = rsElem.selectSingleNode("//CARDNO").getText(); // 绑定卡
// 加密处理;
String statusid = rsElem.selectSingleNode("//STATUSID").getText(); // 0绑定
// 2预绑定
EnterpriseBindcardExample example = new EnterpriseBindcardExample();
example.createCriteria().andEAccBanknoEqualTo(acno).andCardNoEqualTo(cardno);
List<EnterpriseBindcard> cardList = enterpriseBindcardMapper.selectByExample(example);
if (cardList != null && cardList.size() > 0) {
enterpriseBindCard = cardList.get(0);
if (!enterpriseBindCard.getState().equals(Integer.parseInt(statusid))) {
enterpriseBindCard.setState(Integer.parseInt(statusid));
enterpriseBindcardMapper.updateByPrimaryKeySelective(enterpriseBindCard);
}
} else {
String cardtype = rsElem.selectSingleNode("//CARDTYPE").getText();
String binddate = rsElem.selectSingleNode("//BINDDATE").getText();
String bindtime = rsElem.selectSingleNode("//BINDTIME").getText();
String otherbankflag = rsElem.selectSingleNode("//OTHERBANKFLAG").getText();
String banknumber = rsElem.selectSingleNode("//BANKNUMBER").getText();
String bankname = rsElem.selectSingleNode("//BANKNAME").getText();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
enterpriseBindCard.setId(uuid);
enterpriseBindCard.seteAccBankno(acno);
enterpriseBindCard.setCardNo(cardno);
enterpriseBindCard.setState(Integer.parseInt(statusid));
enterpriseBindCard.setCardType(cardtype);
enterpriseBindCard.setBindDate(formatBankDate(binddate, bindtime));
enterpriseBindCard.setOtherBankFlag(Integer.parseInt(otherbankflag));
enterpriseBindCard.setBankNumber(banknumber);
enterpriseBindCard.setBankName(bankname);
enterpriseBindcardMapper.insertSelective(enterpriseBindCard);
}
}
}
}
}
/**
* 查询企业绑卡记录
*
* @author syb
* @date 2017年9月29日 下午1:57:13
* @version 1.0
* @param acNo
* 银行存管账号
* @param currentPage
* 当前页
* @param pageNumber
* 每页条数
* @param logGroup
* 日志头
* @return
*
*/
private void queryBindCardResult(String acNo, String currentPage, String pageNumber, String logGroup) {
Document doc = hxEnterpriseBindCard.queryEnterpriseBindCardInfo(acNo, currentPage, pageNumber, logGroup);
if (doc != null && doc.selectNodes("//CARDS") != null) {
String errorcode = doc.selectSingleNode("//errorCode").getText();
if (errorcode.equals("0")) {
// 页码总数
String pagecount = doc.selectSingleNode("//PAGECOUNT").getText();
// 如果页数大于1,从第二页开始循环查询
if (Integer.parseInt(pagecount) > 1) {
for (int i = ResultNumber.TWO.getNumber(); i <= Integer.parseInt(pagecount); i++) {
handleEnterpriseBindCardRecord(acNo, i + "", pageNumber, logGroup, null);
}
} else {
handleEnterpriseBindCardRecord(acNo, currentPage, pageNumber, logGroup, doc);
}
}
}
}
/**
* 格式化银行返回时间
*
* @author yiban
* @date 2017年10月23日 上午9:17:16
* @version 1.0
* @param date
* yyyymmdd
* @param time
* hhssmmSSS
* @return 返回时间
*
*/
public String formatBankDate(String date, String time) {
try {
if (!StringUtils.isEmpty(date)) {
return date.substring(0, ResultNumber.FOUR.getNumber()) + "-" + date.substring(ResultNumber.FOUR.getNumber(), ResultNumber.SIX.getNumber()) + "-" + date.substring(ResultNumber.SIX.getNumber(), ResultNumber.EIGHT.getNumber()) + " "
+ time.substring(0, ResultNumber.TWO.getNumber()) + ":" + time.substring(ResultNumber.TWO.getNumber(), ResultNumber.FOUR.getNumber()) + ":" + time.substring(ResultNumber.FOUR.getNumber(), ResultNumber.SIX.getNumber());
} else {
return "";
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
|
Markdown | UTF-8 | 6,523 | 2.609375 | 3 | [] | no_license | ## JINY (Jana's tINY kernel)
[JINY](https://github.com/naredula-jana/Jiny-Kernel) is a cloud OS designed from ground up for superior performance on virtual machine.
1. **What is JINY?**.
- Unlike traditional kernel Jiny is thin kernel designed for cloud. Jiny provides posix interface similar to linux, so linux application can directly run on it without recompiling.
- Designed from ground up: It is cloud OS designed from the ground up to give superior performance on virtual machine(VM). The performance gain comes from reducing isolation, reducing protection, increasing memory and cpu efficiency.
- High Priority(HP) and normal priority mode: Jiny OS runs in two modes.
- **High priority mode or Single App mode**: In this mode, kernel functions like library OS and does the supporting role for the app, designed with low overhead. Only one application can be launched in the OS, and application runs in the same ring as that of OS(i.e ring-0). The functions which are considered “system calls” on Linux( e.g., futex,read ,..etc) are ordinary function calls in Jiny and do not incur syscall call overheads, nor do they incur the cost of user to kernel parameter copying which is unnecessary in single-application OS. fork and exec posix calls are not supported in this mode. App is launched in a different way. Apart from posix calls, Non posix API’s between application and Guest OS will further decreases latency and improves throughput. Currently golang and C application are supported in this mode.
- **Normal priority mode**: Jiny kernel emulates most of the posix calls(system calls) compatible to linux, so that linux binaries can run as it is. Multiple applications can run in this mode at the same time similar to traditional OS.
2. **How different is Jiny from OS like Linux?**
- **Thin kernel** : Jiny is thin kernel, it is having very small set of drivers based on virtio, since it runs on hypervisor. Currently it supports only x86_64 architecture, this makes the size of code small when compare to linux.
- **OS for Cloud**: Designed from ground-up to run on hypervisor, So it runs faster when compare to linux.
- **Object oriented**: Most of subsystems are in object oriented language c++11.
- **Non-posix api's for jvm and golang runtime system**: Supports special api's for jvm and golang runtime system for running app in HP mode. Here java and golang app does not need any change.
- **Single app inside the vm**: Designed to run single application efficiently when compare to traditional os.
- **Network packet processing**: Most of cycles in packet processing is spent in the app context(i.e at the edge) as against in the bottom half in linux, this will minimizing the locks in the SMP. Detailed description is present in the [VanJacbson paper](http://www.lemis.com/grog/Documentation/vj/lca06vj.pdf)
3. **For What purpose Jiny can be used?**
- Running single apps like JVM( any java server), golang apps, memcached etc inside the Jiny vm in high priority mode. Here the app will run much faster when compare to the same app in other vm's like freebsd or linux. Thin OS like Jiny along with virtulization hardware can act like a performance enhancer for the apps on the metal.
- Running multiple normal priority application like any traditional unix like systems with optimizations for vm.
## Procedure to compile and run:
More details of [compiling and running Jiny Kernel is available here.](../master/bin/README.md).
## Performance Test results of Golang-14.2 on Jiny:
[Golang application runs almost 2X to 10X faster on Jiny-Kernel.](../master/doc/benchmarks.md).
## Demo
Watch a demo here:<br>
[Golang in Ring-0](https://www.youtube.com/watch?v=ygGAUJeTv0w)<br>
## Features currently Available:
- Page Cache: LRU and MRU based (based on the published paper in opencirrus for Hadoop)
- File Systems:
- TarFs : Tar file can be mounted as a root/non-root file system.
- 9p
- Host based file system based on IVSHM(Inter Vm Shared Memory)
- Virtualization Features:
- HighPriority Apps: very basic features is available(app to load as module).
- Zero page optimization works along with KSM.
- Elastic Cpu's: depending on the load, some of the cpu's will be rested.
- Elastic Memory: depending on the load, some amount of physical memory can be disabled, so as host/other vm's can use.
- Virtualization drivers:
- Xen : xenbus, network driver using xen paravirtualised.
- KVM : virtio + P9 filesystem
- KVM : virtio + Network (vhost-net,vhost-user), with multi-queue
- KVM : virtio + block (vitio-disk) with multi-queue
- KVM : virtio + Memory ballooning
- KVM : clock
- Vmware : vmxnet3,pvscsi
- SMP: APIC,MSIX
- Networking: Third party tcp/ip stacks as kernel module.
- TCP/ip stack from UIP ( from [AdamDunkels](https://github.com/adamdunkels/uip) as kernel module. The above Benchamark-2 is with uip : currently only udp is supported, need to add tcp.
- LWIP4.0 as a kernel module:
- Debugging features:
- memoryleak detection.
- function tracing or call graph.
- syscall debugging.
- stack capture at any point.
- code profiling.
- Loadable Modules: Supports loadable kernel module. Lwip tcp/ip stack compiled as kernel module.
- User level:
- Statically and dynamically compiled user app can be launched from kernel shell or busy box.
- busybox shell can successfully run on top of Jiny kernel, network apps can able to use socket layer.
- Hardware: It was fully tested for x86/64. partially done for x86_32.
- High Priorty mode: support c apps and golang applications. golang appliction does not need any change. [changes are needed to golang runtime system](../master/modules/HP_golang_changes).
## Papers:
- [Page cache optimizations for Hadoop/HDFS, published and presented in open cirrus-2011 summit](../master/doc/PageCache-Open-Cirrus.pdf) .
- [User space Memory optimization techniques](../master/doc/malloc_paper_techpulse_submit_final.pdf).
- [Jiny pagecache implementation](../master/doc/pagecache.txt).
- [Tar Fs - Jiny root file system](../master/doc/tar_fs.md).
- [Jiny Kernel Memory optimizations](../master/doc/Jiny_memory_management.md).
- [Golang apps in ring-0](../master/doc/GolangAppInRing0.pdf).
- [Perf tool to measure the speed of vm/app](../master/doc/Perf_IPC.pdf).
## Related Projects:
-[Vmstate](https://github.com/naredula-jana/vmstate): Virtualmachine state capture and analysis.
|
Java | UTF-8 | 27,001 | 2.234375 | 2 | [] | no_license | package Student;
import DBConnection.DBConnect;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.ComboBox;
import javax.swing.JOptionPane;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Joe
*/
public class Add_student extends javax.swing.JFrame {
PreparedStatement ps;
ResultSet rs;
Connection con = null;
public Add_student() {
initComponents();
this.setLocationRelativeTo(null);
addStd.setVisible(false);
addStd.setEnabled(false);
studentID.setText(String.valueOf(loadStdID()));
Ac_Year.requestFocus();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
Academic_semester = new javax.swing.JLabel();
groupID = new javax.swing.JTextField();
subGroupID = new javax.swing.JTextField();
studentID = new javax.swing.JTextField();
SgroupNo = new javax.swing.JComboBox();
groupNo = new javax.swing.JComboBox();
clear = new javax.swing.JButton();
addStd = new javax.swing.JButton();
generateID = new javax.swing.JButton();
Semester = new javax.swing.JComboBox();
Ac_Year = new javax.swing.JComboBox();
Programme = new javax.swing.JComboBox();
Academic_year = new javax.swing.JLabel();
clear1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
setResizable(false);
jPanel1.setBackground(new java.awt.Color(0, 0, 204));
jLabel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Add Student Groups");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 782, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel2.setText("Student ID :");
jLabel3.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel3.setText("Programme :");
jLabel4.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel4.setText("Sub-Group ID :");
jLabel5.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel5.setText("Group Number :");
jLabel6.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel6.setText("Sub-Group Number :");
jLabel7.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
jLabel7.setText("Group ID :");
Academic_semester.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
Academic_semester.setText("Academic Semester :");
groupID.setEditable(false);
groupID.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
subGroupID.setEditable(false);
subGroupID.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
studentID.setEditable(false);
studentID.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
studentID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
studentIDActionPerformed(evt);
}
});
SgroupNo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
SgroupNo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Sub Group", "1", "2" }));
groupNo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
groupNo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Group Number", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15" }));
groupNo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
groupNoActionPerformed(evt);
}
});
clear.setBackground(new java.awt.Color(255, 255, 0));
clear.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
clear.setForeground(new java.awt.Color(51, 102, 255));
clear.setText("Clear");
clear.setPreferredSize(new java.awt.Dimension(79, 30));
clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearActionPerformed(evt);
}
});
addStd.setBackground(new java.awt.Color(255, 255, 0));
addStd.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
addStd.setForeground(new java.awt.Color(51, 102, 255));
addStd.setText("Add New Student");
addStd.setEnabled(false);
addStd.setPreferredSize(new java.awt.Dimension(185, 30));
addStd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStdActionPerformed(evt);
}
});
generateID.setBackground(new java.awt.Color(255, 255, 0));
generateID.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
generateID.setForeground(new java.awt.Color(51, 102, 255));
generateID.setText("Generate ID's");
generateID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
generateIDActionPerformed(evt);
}
});
Semester.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
Semester.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Semester", "1st Semester", "2nd Semester" }));
Ac_Year.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
Ac_Year.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Year", "1st Year", "2nd Year", "3rd Year", "4th Year" }));
Programme.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
Programme.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Programme", "IT", "SE", "ISE", "CSNE", "CS", "IN", "DS" }));
Academic_year.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N
Academic_year.setText("Academic Year :");
clear1.setBackground(new java.awt.Color(255, 255, 0));
clear1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
clear1.setForeground(new java.awt.Color(51, 102, 255));
clear1.setText("Close");
clear1.setPreferredSize(new java.awt.Dimension(79, 30));
clear1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clear1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Academic_semester, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Academic_year, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(clear, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clear1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(103, 103, 103)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Programme, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(SgroupNo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(groupNo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Ac_Year, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Semester, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(studentID, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(5, 5, 5))
.addComponent(addStd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(subGroupID, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(groupID, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(generateID, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(269, 269, 269))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(Academic_year, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(Academic_semester, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(studentID, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(Ac_Year, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(Semester, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(groupNo, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23)
.addComponent(SgroupNo, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(Programme, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(groupID, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(subGroupID, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(clear, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(generateID, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addStd, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clear1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(47, 47, 47))))))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void studentIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_studentIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_studentIDActionPerformed
private void clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearActionPerformed
Ac_Year.setSelectedIndex(0);
Semester.setSelectedIndex(0);
groupID.setText("");
subGroupID.setText("");
groupNo.setSelectedIndex(0);
SgroupNo.setSelectedIndex(0);
Programme.setSelectedIndex(0);
}//GEN-LAST:event_clearActionPerformed
private void addStdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addStdActionPerformed
String student_id = studentID.getText();
int academic_Year = Ac_Year.getSelectedIndex();
int academic_semester = Semester.getSelectedIndex();
String group_id = groupID.getText();
String sub_id = subGroupID.getText();
int g_number = groupNo.getSelectedIndex();
int sgroup_number = SgroupNo.getSelectedIndex();
String program = (String)Programme.getSelectedItem();
program = Programme.getSelectedItem().toString();
//SQL query
String quary = "INSERT INTO student(id, academic_year, academic_semester, groupID, subGroup_ID, groupNB, subGroupNB, programme)VALUES(?,?,?,?,?,?,?,?)";
try {
ps = DBConnect.getConnection().prepareStatement(quary);
ps.setString(1, student_id);
ps.setInt(2, academic_Year);
ps.setInt(3, academic_semester);
ps.setString(4, group_id);
ps.setString(5, sub_id);
ps.setInt(6, g_number);
ps.setInt(7, sgroup_number);
ps.setString(8, program);
if(ps.executeUpdate() == 1){
JOptionPane.showMessageDialog(null, "Data Added Successfully");
clearActionPerformed(evt);
studentID.setText(String.valueOf(loadStdID()));
}else{
JOptionPane.showMessageDialog(null, "Error!");
}
} catch (SQLException ex) {
Logger.getLogger(Add_student.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_addStdActionPerformed
private void generateIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateIDActionPerformed
Boolean Error = false;
String ProgrammeV = (String)Programme.getSelectedItem();
String Programme1 = Programme.getSelectedItem().toString();
String Year = String.valueOf(Ac_Year.getSelectedIndex());
String semester = String.valueOf(Semester.getSelectedIndex());
String groupNb = String.valueOf(groupNo.getSelectedIndex());
String SubgroupNb = String.valueOf(SgroupNo.getSelectedIndex());
if(Year.equals("0")){
JOptionPane.showMessageDialog(null, "Please select Year","Error", JOptionPane.ERROR_MESSAGE);
Error = true;
}
if(Error == false && semester.equals("0")){
JOptionPane.showMessageDialog(null, "Please select Semester","Error", JOptionPane.ERROR_MESSAGE);
Error = true;
}
if(Error == false && groupNb.equals("0")){
JOptionPane.showMessageDialog(null, "Please select Group","Error", JOptionPane.ERROR_MESSAGE);
Error = true;
}
if(Error == false && SubgroupNb.equals("0")){
JOptionPane.showMessageDialog(null, "Please select Sub Group","Error", JOptionPane.ERROR_MESSAGE);
Error = true;
}
if(Error == false && Programme1.equals("0")){
JOptionPane.showMessageDialog(null, "Please select Programme","Error", JOptionPane.ERROR_MESSAGE);
Error = true;
}
if(Error){
JOptionPane.showMessageDialog(null, "Please check all fields ","Error", JOptionPane.ERROR_MESSAGE);
}else{
String gID = "Y"+Year+".S"+semester+"."+Programme1+"."+groupNb;
String subgID = "Y"+Year+".S"+semester+"."+Programme1+"."+groupNb+"."+SubgroupNb;
groupID.setText(gID);
subGroupID.setText(subgID);
addStd.setVisible(true);
addStd.setEnabled(true);
}
}//GEN-LAST:event_generateIDActionPerformed
private void groupNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_groupNoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_groupNoActionPerformed
private void clear1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clear1ActionPerformed
this.dispose();
}//GEN-LAST:event_clear1ActionPerformed
public int loadStdID(){
String quary = "SELECT * FROM student ORDER BY id DESC LIMIT 1";
try {
ps = DBConnect.getConnection().prepareStatement(quary);
rs = ps.executeQuery();
while(rs.next()){
int StdID = rs.getInt("id") + 1;
return StdID;
}
} catch (SQLException ex) {
Logger.getLogger(Add_student.class.getName()).log(Level.SEVERE, null, ex);
}
return 0;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Add_student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Add_student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Add_student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Add_student.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Add_student().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox Ac_Year;
private javax.swing.JLabel Academic_semester;
private javax.swing.JLabel Academic_year;
private javax.swing.JComboBox Programme;
private javax.swing.JComboBox Semester;
private javax.swing.JComboBox SgroupNo;
private javax.swing.JButton addStd;
private javax.swing.JButton clear;
private javax.swing.JButton clear1;
private javax.swing.JButton generateID;
private javax.swing.JTextField groupID;
private javax.swing.JComboBox groupNo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JTextField studentID;
private javax.swing.JTextField subGroupID;
// End of variables declaration//GEN-END:variables
}
|
Python | UTF-8 | 319 | 3.15625 | 3 | [] | no_license | class Solution:
"""
@param n: An integer
@return: The number of zero in factorial
"""
def trailingZero(self, n):
if n <5:
return 0
elif n < 10:
return 1
else:
return n//5 + self.trailingZero(n//5)
a = Solution()
print(a.trailingZero(25))
|
Markdown | UTF-8 | 1,293 | 2.6875 | 3 | [] | no_license | # 视差滚动
+ 插件
+ **`Stellar 插件`**
+ 描述
+ **视差滚动** 指网页滚动过程中,多层次的元素进行不同程度的移动,视觉上形成立体运动效果的网页展示技术 主要**核心**就是 前景 和 背景 以不同的速度移动,从而创造出 3D 效果。
+ 特性
+ 视差滚动效果酷炫,适合于个性展示的场合
+ 视差滚动徐徐栈开,适合于娓娓道来,讲故事的场合
+ 视差滚动容易迷航,需要具备较强的导航功能
+ 原理
+ 传统的网页的文字、图片、背景都是一起按照相同方向相同速度滚动的,而视差滚动则是在滚动的时候,内容和多层次的背景实现或不同速度,或不同方向的运动。有的时候也可以加上一些透明度、大小的动画来优化显示。利用 `background-attachment` 属性来实现
# 语义化标签
+ 兼容
+ `document.createElement('')` 并且设置块级元素
+ 插件
+ html5shiv.js
+ 必须在头部引入,这样可以做到在加载页面之前解析
+ 使用条件注释
+ 固定语法 `lt(小于)` `gt(大于)` `lte(小于等于)` `gte(大于等于)`
```html
<!--[if lt IE 9]>
<script src="bower_components/html5shiv/dist/html5shiv.js"></script>
<![endif]-->
``` |
PHP | UTF-8 | 1,411 | 2.9375 | 3 | [] | no_license | <?php
namespace App\Repositories\Corporation;
// 統合API用
use App\Libraries\IntegratedAPI\IntegratedAPIClient;
class CorporationRepository implements CorporationRepositoryInterface {
protected $IntegratedApiClient;
public function __construct(
IntegratedApiClient $IntegratedApiClient
) {
$this->IntegratedApiClient = $IntegratedApiClient;
}
/*
主キー指定で検索
@params int $id
@return Array
*/
public function findById($id) {
$conditions = ['corporation_id' => $id];
$response = $this->IntegratedApiClient->requestByKey('FIND_CORPORATION', $conditions);
$ArrResponse = $response->json();
return $ArrResponse['data'];
}
public function findByIdWithRelated($id) {
$conditions = ['corporation_id' => $id];
$response = $this->IntegratedApiClient->requestByKey('FIND_CORPORATION_WITH_RELATED', $conditions);
$ArrResponse = $response->json();
return $ArrResponse['data'];
}
/*
検索条件を指定して検索
@params Array $conditions
@return Array
*/
public function search(Array $conditions = []) {
$response = $this->IntegratedApiClient->requestByKey('CORPORATION_LIST', $conditions);
$ArrResponse = $response->json();
return $ArrResponse;
}
public function save(Array $data) {
$response = $this->IntegratedApiClient->requestByKey('SAVE_CORPORATION', $data);
$response->throwIfInvalidStatus();
return $response->getData();
}
} |
Markdown | UTF-8 | 1,369 | 2.53125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: 헤더 컨트롤에 항목 추가
ms.date: 11/04/2016
helpviewer_keywords:
- controls [MFC], header
- CHeaderCtrl class [MFC], adding items
- header controls [MFC], adding items to
ms.assetid: 2e9a28b1-7302-4a93-8037-c5a4183e589a
ms.openlocfilehash: 5749a0cae2dfe7e6c9f4c166eca487e36c2d21d2
ms.sourcegitcommit: c21b05042debc97d14875e019ee9d698691ffc0b
ms.translationtype: MT
ms.contentlocale: ko-KR
ms.lasthandoff: 06/09/2020
ms.locfileid: "84616462"
---
# <a name="adding-items-to-the-header-control"></a>헤더 컨트롤에 항목 추가
부모 창에서 헤더 컨트롤 ([CHeaderCtrl](reference/cheaderctrl-class.md))을 만든 후 필요한 만큼 "헤더 항목"을 추가 합니다. 일반적으로 열 마다 하나씩 추가 합니다.
### <a name="to-add-a-header-item"></a>헤더 항목을 추가 하려면
1. [HD_ITEM](/windows/win32/api/commctrl/ns-commctrl-hditemw) 구조를 준비 합니다.
1. [CHeaderCtrl:: InsertItem](reference/cheaderctrl-class.md#insertitem)를 호출 하 고 구조체를 전달 합니다.
1. 추가 항목에 대해 1 단계와 2 단계를 반복 합니다.
자세한 내용은 Windows SDK에서 [헤더 컨트롤에 항목 추가](/windows/win32/Controls/header-controls) 를 참조 하세요.
## <a name="see-also"></a>참고 항목
[CHeaderCtrl 사용](using-cheaderctrl.md)<br/>
[컨트롤](controls-mfc.md)
|
C++ | UTF-8 | 1,638 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "detector.hpp"
namespace giraffic::primes
{
detector::detector(std::uint64_t max_number, std::uint64_t portion, std::size_t workers, std::shared_ptr<giraffic::core::logger> logger)
:m_max_number(max_number), m_portion(portion), m_workers(workers), m_logger(logger), m_numbers(max_number + 1, true), m_async_count(0)
{
}
detector::~detector()
{
}
void detector::build()
{
std::vector<std::future<void>> _asyncs;
for (std::uint64_t i = 2; i * i <= m_max_number; i++)
{
if (m_numbers[i] == true)
{
//build_for(i);
_asyncs.emplace_back(std::async(std::launch::async, &detector::build_for, this, i));
}
}
}
void detector::build_for(std::uint64_t number)
{
++m_async_count;
for (std::uint64_t j = number * 2; j <= m_max_number; j += number)
{
m_numbers[j] = false;
}
--m_async_count;
}
bool detector::is_prime(std::uint64_t number)
{
return is_prime_for(number, 2, m_max_number);
}
bool detector::is_prime_for(std::uint64_t number, std::uint64_t start, std::uint64_t end)
{
std::uint64_t _len = end - start;
if(_len < m_portion || m_async_count >= m_workers*std::thread::hardware_concurrency())
{
for (int i = start; i <= end; i++)
{
if (m_numbers[i])
{
if (i == number)
{
return true;
}
}
}
return false;
}
std::uint64_t _mid = start + _len/2;
++m_async_count;
auto _handle = std::async(std::launch::async, &detector::is_prime_for, this, number, _mid, end);
auto _isprime = is_prime_for(number, start, _mid);
_isprime = _isprime + _handle.get();
--m_async_count;
return _isprime;
}
} |
Python | UTF-8 | 2,515 | 2.53125 | 3 | [] | no_license | __author__ = 'xyang'
import os
import shutil
import fileinput
import re
class manageFile():
def __init__(self):
pass
def remove_character(self, filepath, count, testcase,mode):
lines = open(filepath).readlines()
fp = open('test_suite_debug.cfg','w')
for s in lines:
if testcase in s:
fp.write(s.lstrip('#'))
count += 1
elif mode == 1:
fp.write(s)
count += 1
elif mode == 2:
count +=1
else:
fp.write(s)
print "case number is " + str(count)
fp.close()
shutil.move('test_suite_debug.cfg', filepath)
def add_character(self,filepath, count, testcase,comment):
lines = open(filepath).readlines()
fp = open('test_suite_debug.cfg','w')
for s in lines:
if testcase in s:
fp.write(s.replace(testcase,comment))
count += 1
else:
fp.write(s)
count += 1
print "case number is " + str(count)
fp.close()
shutil.move('test_suite_debug.cfg', filepath)
def append_file(self,source,des,last):
file = open(des,"r")
fileadd = open(source,"r")
conten = file.read()
contenadd = fileadd.read()
pos = conten.find(last)
print pos
if pos != -1:
conten = conten[:pos] + contenadd
file = open(des,"w")
file.write(conten)
print "OK"
def append_file_mem(self,copyfifle,sourcefile,newfile):
with open(copyfifle,'rb') as fin1, \
open(sourcefile,'rb') as fin2, \
open(newfile,'wb') as fout:
shutil.copyfileobj(fin1, fout)
fin1.seek(-len(os.linesep), 2)
if fin1.read() != os.linesep:
fout.write(os.linesep)
shutil.copyfileobj(fin2, fout)
if __name__ == '__main__':
fp = manageFile()
files = os.listdir('D:\\NGTTProject\\aPage\Multi_ASR\\800-002-1020')
path= "D:\\NGTTProject\\aPage\Multi_ASR\\800-002-1020\\test_suite_debug.cfg"
despath= "D:\\NGTTProject\\aPage\Multi_ASR\\800-002-1020\\test_suite.cfg"
testcase = "test_case"
comment = "#test_case"
count = 0
#fp.remove_character(path,count,testcase,2)
#fp.add_character(path,count,testcase,comment)
fp.append_file(path,despath,"digit_fr_8")
#fp.append_file_mem() |
Python | UTF-8 | 366 | 3.046875 | 3 | [] | no_license | myDict = {}
print myDict
myDict['ABC'] = "Company ABC"
myDict['XYZ'] = "Corporation XYZ"
myDict['ZZZ'] = "ZZZ Inc"
print myDict
print myDict['ABC']
for x in myDict.keys():
print x, myDict[x]
for x in myDict:
print x
myDict['ZZZ'] = "Updated Company"
print myDict['ZZZ']
if 'ZZZ' in myDict:
print "True"
print
print "Corporation XYZ" in myDict.values()
|
C# | UTF-8 | 8,441 | 2.921875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace FractalViewer
{
class FractalGen
{
private int NO_OF_THREADS;
public PictureBox PB;
public Bitmap DrawArea;
private WPart[] WpArray;
public fractalConfig FC;
public bool Calculating;
// Constructor
public FractalGen(byte threads, PictureBox PB, fractalConfig FC)
{
NO_OF_THREADS = threads;
this.PB = PB;
DrawArea = new Bitmap(FC.width, FC.height);
PB.Image = DrawArea;
this.FC = FC;
}
// Create the threads
public void Generate()
{
// Create array of WParts
WpArray = new WPart[NO_OF_THREADS];
// Create array of ManualResetEvents
ManualResetEvent[] doneEvents = new ManualResetEvent[NO_OF_THREADS];
double x_step = (FC.fractalArea.x2 - FC.fractalArea.x1) / NO_OF_THREADS;
for (int i = 0; i < NO_OF_THREADS; i++)
{
doneEvents[i] = new ManualResetEvent(false);
FractalArea fa_temp = new FractalArea
{
x1 = FC.fractalArea.x1 + x_step * i,
x2 = FC.fractalArea.x1 + x_step * i + x_step,
y1 = FC.fractalArea.y1,
y2 = FC.fractalArea.y2
};
WPart WP = new WPart(FC.width /NO_OF_THREADS, FC.height, FC.fractalType, FC.w_max, fa_temp, FC.dx, FC.dy, doneEvents[i]);
WpArray[i] = WP;
ThreadPool.QueueUserWorkItem(WP.ThreadPoolCallback,i);
}
Calculating = true;
// Wait for all threads in pool to complete
foreach (var e in doneEvents)
e.WaitOne();
Calculating = false;
Application.DoEvents();
Draw();
PB.Image = DrawArea;
}
//Colorise and display the fractal
public void Draw()
{
int wi;
for (int i = 0; i < NO_OF_THREADS; i++)
{
WPart WP = WpArray[i];
for (int Xcount = 0; Xcount < WP.width; Xcount++)
{
for (int Ycount = 0; Ycount < WP.height; Ycount++)
{
// Draw pixel
wi = WP.w_data[Xcount, Ycount];
if (wi < FC.w_max)
{
const byte alpha = 255;
byte red = Convert.ToByte(FC.R * wi / FC.w_max);
byte green = Convert.ToByte(FC.G * wi / FC.w_max);
byte blue = Convert.ToByte(FC.B * wi / FC.w_max);
byte[] color = { alpha, red, green, blue };
if (BitConverter.IsLittleEndian)
Array.Reverse(color);
DrawArea.SetPixel(Xcount + WP.width*i, Ycount, Color.FromArgb(BitConverter.ToInt32(color, 0)));
}
else
{
DrawArea.SetPixel(Xcount + WP.width*i, Ycount, Color.Black);
}
}
}
}
}
public void Clear()
{
// Clear image area and set to black
Graphics g;
g = Graphics.FromImage(DrawArea);
g.Clear(Color.Black);
g.Dispose();
// Draw image to picturebox
PB.Image = DrawArea;
}
}
// W Part Class
public class WPart
{
public int[,] w_data;
public int type;
public int width;
public int height;
public int w_max;
private FractalArea fa;
public double dx, dy;
public ManualResetEvent doneEvent;
public WPart(int width, int height, int type, int w_max, FractalArea fa, double dx, double dy, ManualResetEvent de)
{
this.width = width;
this.height = height;
this.type = type;
this.w_max = w_max;
this.fa = fa;
this.dx = dx;
this.dy = dy;
w_data = new int[width, height];
doneEvent = de;
}
// Assign work to the threads
public void ThreadPoolCallback(Object threadContext)
{
Calculate();
doneEvent.Set();
}
// Calculate a portion of the w_map and store in array
public void Calculate()
{
int w;
double cr, ci, zr, zi, zr2, zi2, zrt;
if (type == 0 || type == 1)
{
// Loop through each pixel
for (int Xcount = 0; Xcount < width; Xcount++)
{
for (int Ycount = 0; Ycount < height; Ycount++)
{
cr = fa.x1 + dx * Xcount;
ci = fa.y1 + dy * Ycount;
w = 0;
zr = 0;
zi = 0;
zr2 = 0;
zi2 = 0;
// Fractal calculation loop
while (((zr2 + zi2) < 4) && (w < w_max))
{
zrt = zr2 - zi2 + cr;
zi = (type == 0)? 2 * zr * zi + ci : 2 * Math.Abs(zr * zi) + ci;
zr = zrt;
zr2 = Math.Pow(zr, 2);
zi2 = Math.Pow(zi, 2);
w++;
}
// Store w
if (w < w_max)
{
w_data[Xcount, Ycount] = (w < w_max)? w:w_max;
}
}
}
}
}
}
// A fractal area
public class FractalArea
{
public double x1, x2, y1, y2;
public FractalArea() { }
public FractalArea(double x1, double x2, double y1, double y2)
{
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
}
// Stores fractal config
// Type
// W_Max
// Location (current FractalArea)
// Colours
public class fractalConfig
{
public int width = 1350, height = 960;
public int fractalType;
public int w_max = 500;
public FractalArea fractalArea;
public double dx, dy;
public byte R = 0, G = 255, B = 0;
public fractalConfig()
{
}
public void changeFractal(int fractalType)
{
this.fractalType = fractalType;
setDefaultArea();
setDxDy();
}
public void setDxDy()
{
dx = (fractalArea.x2 - fractalArea.x1) / width;
dy = (fractalArea.y2 - fractalArea.y1) / height;
}
public void setDefaultArea()
{
fractalArea = Fractals.getDefaultArea(fractalType);
}
}
// Store fractal details
// Names
// Default X an Y view range
public static class Fractals
{
// Fractal names and default values
public static IDictionary<int, string> fractal_types = new Dictionary<int, string>()
{
{ 0,"Mandelbrot Fractal" },
{ 1,"Burning Ship Fractal" },
};
// Return the fractal name
public static string getFractalNamebyID(int fracID)
{
return fractal_types[fracID];
}
// Return the default fractal area
public static FractalArea getDefaultArea(int fracId)
{
switch (fracId)
{
case 0:
return new FractalArea(-2.0, 1.0, 1.0, -1.0);
case 1:
return new FractalArea(1.0, -2.0, -2.0, 1.0);
default:
return new FractalArea(0.0, 0.0, 0.0, 0.0);
}
}
}
}
// Backlog
//
// Implement Burning ship fractal
// Make the colour change function work
// Change from Double to Decimal
|
JavaScript | UTF-8 | 1,676 | 4.0625 | 4 | [] | no_license | const message = document.querySelector('.message');
const guess = document.querySelector('input');
const btn = document.querySelector('.btn');
let play = false;
let newWord = "";
let randWord = "";
let words = ['empowerment', 'feminism', 'science', 'math',
'women', 'awareness', 'confidence', 'creative', 'development',
'logical', 'success', 'empower', 'passion', 'imaginative',
'respect', 'brave', 'determined']
const generateWords = () => {
let random = Math.floor(Math.random() * words.length);
let newWord = words[random];
return newWord;
}
const scrambleWords = (arr) => {
for(let i = arr.length-1; i > 0; i--){
let temp = arr[i];
let j = Math.floor(Math.random()*(i+1));
arr[i] = arr[j]
arr[j] = temp;
}
return arr;
}
btn.addEventListener('click', function(){
if(!play){
play = true;
btn.innerHTML = 'Guess';
guess.classList.toggle('hidden');
newWord = generateWords();
randWord = scrambleWords(newWord.split("")).join("");
message.innerHTML = randWord;
}
else{
let tempWord = guess.value;
if(tempWord === newWord){
play = false;
message.innerHTML = `You got that right! It is ${tempWord}.`;
btn.innerHTML = "Play again";
guess.classList.toggle('hidden');
guess.value = "";
}
else{
message.innerHTML = `Oops! That's not right. It is ${newWord}`;
btn.innerHTML = "Try again";
play = false;
guess.classList.toggle('hidden');
guess.value = "";
}
}
}) |
Java | UTF-8 | 2,021 | 2.59375 | 3 | [] | no_license | package servlets;
import models.UserModel;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "RedirectServlet", urlPatterns = {"/RedirectServlet"})
public class RedirectServlet extends HttpServlet {
private void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
RequestDispatcher rd = request.getRequestDispatcher("/jsp/RedirectTest.jsp");
HttpSession session = request.getSession();
session.setAttribute("name", "Thiss");
UserModel user = new UserModel(
"Thiss",
25,
123
);
request.setAttribute("user", user);
rd.forward(request, response);
// response.sendRedirect("jsp/RedirectTest.jsp");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>RedirectServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>This is the Redirect Servlet</h1>");
out.println("</body>");
out.println("</html>");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
|
SQL | UTF-8 | 1,371 | 4 | 4 | [] | no_license | /***********************
Author: Deepak Luitel
Assignment: SQL Queries on Mondial Dataset
CMSC424 Database Design
Spring 2015
***********************/
/*Question no:1*/
SELECT name "Name", area "Sq kms", area*0.386102 "Sq miles"
FROM continent;
/*Question no:2*/
SELECT DISTINCT c.name Name, c.population Population,
co.name country, co.population "COUNTRY POP"
FROM city c, country co
WHERE c.country = co.code ORDER by c.population;
/*Question no:3*/
SELECT DISTINCT co.NAME "Countries in Europe"
FROM country co JOIN encompasses en
ON co.CODE = en.COUNTRY
WHERE en.CONTINENT = 'Europe';
/*Question no:4*/
WITH tmp as (SELECT DISTINCT Country.NAME COUNTRY, org.NAME ORGANIZATION,
Country.CAPITAL, org.CITY "HQ City", country.CODE CODE
FROM Organization org LEFT JOIN country ON org.country = country.code)
SELECT DISTINCT tmp.COUNTRY, tmp.Organization, tmp.CAPITAL,
city.population "CAPITAL POPULATION", tmp."HQ City"
FROM tmp LEFT JOIN City
ON tmp.CAPITAL = city.NAME AND tmp.CODE = city.COUNTRY;
/*Question no:5*/
WITH tmp as (SELECT Country.NAME Country, Encompasses.CONTINENT,
Encompasses.PERCENTAGE*Country.AREA "INCLUDED AREA"
FROM Country LEFT JOIN Encompasses ON Country.CODE = Encompasses.COUNTRY)
SELECT DISTINCT tmp.COUNTRY, tmp.CONTINENT,tmp."INCLUDED AREA"
FROM tmp
ORDER BY tmp."INCLUDED AREA" DESC;
|
Java | UTF-8 | 1,401 | 2.515625 | 3 | [] | no_license | package OficeHourse._day02;
import com.cybertek.utilities.WebDriverFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeClass;
import java.util.concurrent.TimeUnit;
public class ZeroBankAccountActivity1 {
/*1. The user navigates to the login page: http://zero.webappsecurity.com/login.html
2. The user logs in with the user "username" and the password "password"
3. The user navigates to Account Activity page
4. Then The page should have the title "Zero - Account Activity"
5. Then Account drop down should have the following options :
(Savings, Checking, Savings, Loan, Credit Card, Brokerage)
6. Brokerage option should have "No results."
*/
//Declare our driver object
WebDriver driver;
@BeforeClass
public void setupClass(){
driver = WebDriverFactory.getDriver("chrome");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://zero.webappsecurity.com/login.html");
//login
driver.findElement(By.cssSelector("[id*='user_log']")).sendKeys("username");
driver.findElement(By.cssSelector("[id*='user_pass']")).sendKeys("password");
driver.findElement(By.cssSelector("[type*='sub']")).click();
driver.findElement(By.cssSelector("[id*='primary-']")).click();
}
}
|
Java | UTF-8 | 5,052 | 2.875 | 3 | [] | no_license | package models;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class ProfileModel implements Serializable {
private static final long serialVersionUID = 1L;
private static int idCounter = 0;
private int id;
private String firstName;
private String lastName;
private final String securityQuestion;
private final String securityAnswer;
private String password;
private String color;
private HashMap<Integer, GoalModel> goalList;
/*ProfileModel constructor WITH Password*/
public ProfileModel(String firstName, String lastName, String securityQuestion, String securityAnswer, String password, String color) {
this.firstName = firstName;
this.lastName = lastName;
this.securityQuestion = securityQuestion;
this.securityAnswer = securityAnswer;
this.password = password;
this.color = color;
this.goalList = new HashMap<>();
id = idCounter++;
}
/*ProfileModel constructor WITHOUT Password*/
public ProfileModel(String firstName, String lastName, String securityQuestion, String securityAnswer, String color) {
this.firstName = firstName;
this.lastName = lastName;
this.securityQuestion = securityQuestion;
this.securityAnswer = securityAnswer;
this.color = color;
this.goalList = new HashMap<>();
id = idCounter++;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSecurityQuestion() {
return securityQuestion;
}
public String getSecurityAnswer() {
return securityAnswer;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public HashMap<Integer, GoalModel> getGoals() {
return goalList;
}
public void setGoals(HashMap<Integer, GoalModel> goals) {
this.goalList = goals;
}
public boolean hasGoals() {
if (goalList != null) {
if (goalList.size() > 0) {
return true;
}
}
return false;
}
public boolean hasCompletedGoals() {
try {
for (GoalModel goal : this.goalList.values()) {
if (goal.isCompleted()) {
return true;
}
}
} catch (Exception ex) {
return false;
}
return false;
}
public boolean hasIncompleteGoals() {
try {
for (GoalModel goal : this.goalList.values()) {
if (!goal.isCompleted()) {
return true;
}
}
} catch (Exception ex) {
return false;
}
return false;
}
public boolean hasPassword() {
return !(password == null || password.isEmpty());
}
@Override
public String toString() {
return "ProfileModel{" + "id=" + id
+ ", firstName=" + firstName
+ ", lastName=" + lastName
+ ", securityQuestion=" + securityQuestion
+ ", securityAnswer=" + securityAnswer
+ ", password=" + password
+ ", color=" + color
+ ", goals=" + goalList + '}';
}
public List<GoalModel> getTopGoals(int quant) {
if (quant <= 0) {
return null;
}
List<GoalModel> topGoals = new ArrayList();
for (GoalModel newGoal : goalList.values()) {
/*Doesn't show complete goals*/
if (newGoal.isCompleted()) {
continue; //Goes to the next iteration
}
/*While list has less items than desired quantity (quant)*/
if (topGoals.size() < quant) {
topGoals.add(newGoal);
continue; //Goes to the next iteration
}
GoalModel smallestIn = topGoals.get(0);
for(GoalModel insertedGoal : topGoals){
if(insertedGoal.getProgress() < smallestIn.getProgress()){
smallestIn = insertedGoal;
}
}
if(newGoal.getProgress() > smallestIn.getProgress()){
topGoals.remove(smallestIn);
topGoals.add(newGoal);
}
}
GoalModel.orderListByProgress(topGoals);
return topGoals;
}
}
|
C# | UTF-8 | 1,632 | 3.71875 | 4 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq;
namespace _05.BombNumbers
{
class BombNumbers
{
static void Main()
{
List<int> sequence = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
int[] bomb = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
while (sequence.Contains(bomb[0]))
{
for (int i = 0; i < sequence.Count; i++)
{
if (sequence[i] == bomb[0])
{
for (int j = 0; j < bomb[1]; j++)
{
if (i + 1 < sequence.Count && i + 1 >= 0)
{
sequence.RemoveAt(i + 1);
}
}
sequence.Remove(bomb[0]);
for (int j = i - bomb[1]; j < i; j++)
{
if (i - bomb[1] >= 0)
{
sequence.RemoveAt(i - bomb[1]);
}
if (i - bomb[1] < 0 && i != 0 && j >= 0)
{
sequence.RemoveAt(0);
}
}
break;
}
}
}
int sum = 0;
foreach (var num in sequence)
{
sum += num;
}
Console.WriteLine(sum);
}
}
}
|
Python | UTF-8 | 1,725 | 3.34375 | 3 | [
"MIT"
] | permissive | import numpy as np
class Perceptron(object):
def __init__(self, eta=0.01, n_iter=50, random_state=1):
'''
:param eta: (float) learning rate, between 0 and 1
:param n_iter: (int) ~ epoch
:param random_state: (int) Random number generator seed
Atttribute:
w_: (1d-array) Weight after fitting
errors_: (list) Number of missclassifications each epoch
'''
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X, y):
'''
Fit the training data
:param X: {array-like}, shape = [n_examples, n_features]: Vecto huan luyen, voi n_examples là số mẫu, còn cái
n_feature đó là số lượng thuôcj tính của nó.
:param y: array- like, shape = [n_example] là biến target value
:return: self: object
'''
rgen = np.random.RandomState(self.random_state)
self.w_ = rgen.normal(loc=0.0, scale=0.01, size=1 + X.shape[1]) # Cộng thêm cái w0
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
def net_input(self, X):
'''Calculate the net_input
It simple is: wT*x
X here is x
'''
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
'''Return class label after unit step'''
return np.where(self.net_input(X) >= 0.0, 1, -1)
|
PHP | UTF-8 | 604 | 2.84375 | 3 | [] | no_license | <?php
if ($argc == 3)
{
require_once('includes/movies.utils.php');
require_once('includes/student.utils.php');
if (!student_validate_login($argv[1]))
puts('Error: is not a valid login.');
elseif (!student_exists($argv[1]))
puts('Error: student does not exist.');
else
{
if (!movies_exists($argv[2]))
puts('Error: movies does not exists.')
elseif (!student_movie_rented($argv[1], $argv[2]))
puts('Error: you did not rent this movie.');
else
{
movies_return($argv[1], $argv[2]);
puts('Returned');
}
}
}
else
puts('Usage: ./etna_movies.php return_movie login_n imdb_code'); |
Ruby | UTF-8 | 1,530 | 3.109375 | 3 | [
"MIT"
] | permissive | class CLI
def call
puts "Please enter your name"
@name = gets.strip
puts "\n\nWelcome #{@name}, to FITTech Job Qual Finder!\n"
JobScrape.scrape_all
welcome_user
menu
end
def welcome_user
puts "Are you ready to look over job postings? y/n\n\n"
response = gets.strip
if response == "y"
puts "Great! I hope viewing these posts, really help with your resume update, #{@name}!\n\n"
list_postings
elsif response == "n"
puts "Hopefully you'll try another time #{@name}!"
goodbye
else
puts "Please answer y or n"
welcome_user
end
end
def list_postings
Job.all.each.with_index(1) do |job, i|
puts "#{i}. #{job.title} "
end
end
def menu
input = nil
while input != "exit"
puts "Number of the job posting you'd like to view the qualifications for, or type list to see all postings again, or type exit"
input = gets.strip.downcase
if input.to_i > 0
new_jobs = Job.all[input.to_i-1]
puts "#{new_jobs.title}\n\n RESPONSIBILITIES\n\n #{new_jobs.responsibilities}\n\n QUALIFICATIONS\n\n #{new_jobs.qualifications} "
elsif input == "list"
list_postings
elsif input == "exit"
exit!
else
puts "Type list or exit"
end
end
end
def goodbye
puts "Thanks check tomorrow for more job posts"
exit!
end
end |
JavaScript | UTF-8 | 4,643 | 2.90625 | 3 | [] | no_license | const canvasWidth = window.innerWidth
const canvasHeight = window.innerHeight
let started = false
let numPendulums = 4
let pendulums
let reverb, filter
function setup(){
createCanvas(canvasWidth, canvasHeight)
reverb = new p5.Reverb()
filter = new p5.LowPass();
reverb.drywet(0.9)
pendulums = Array.from({ length: numPendulums}, (el, i) => createPendulum(i))
// updatePendulumAngle(pendulum)
pendulums.forEach((pendulum, i) => {
pendulum.synth = createSynth(i)
updatePendulumAngle(pendulum)
updatePendulumPosition(pendulum)
drawPendulum(pendulum)
})
}
function draw(){
background(30)
if(started){
pendulums.forEach(pendulum => {
if(!pendulum.ended){
updatePendulumAngle(pendulum)
updatePendulumPosition(pendulum)
updateSynth(pendulum.angle, pendulum.synth)
drawPendulum(pendulum)
}else{
pendulum.synth.osc.amp(0)
pendulum.synth.mod.amp(0)
}
})
} else {
drawText()
}
pendulums.forEach(pendulum => {
// updatePendulumAngle(pendulum)
// updatePendulumPosition(pendulum)
drawPendulum(pendulum)
})
}
function mousePressed(){
if(!started){
started = true
}
pendulums.forEach(pendulum => {
pendulum.synth.osc.start()
pendulum.synth.osc.disconnect()
pendulum.synth.mod.start()
pendulum.synth.mod.disconnect()
reverb.process(pendulum.synth.osc, 1.5, 60)
})
}
const drawText = () => {
textSize(30)
fill(255)
noStroke()
text('click anywhere to start', 100, canvasHeight - 100)
}
const drawBall = (pendulum) => {
fill(pendulum.color)
ellipse(pendulum.center.x, pendulum.center.y, pendulum.size)
}
const drawLine = (pendulum) => {
stroke(255)
strokeWeight(3)
line(pendulum.lineStart.x, pendulum.lineStart.y, pendulum.center.x, pendulum.center.y)
}
const drawPendulum = (pendulum) => {
if(!pendulum.ended){
drawLine(pendulum)
drawBall(pendulum)
}
}
const updatePendulumAngle = (pendulum) => {
// a formula that I didn't make up
// (see: http://www.myphysicslab.com/pendulum1.html)
pendulum.acceleration = (-1 * pendulum.gravity/pendulum.size) * sin(pendulum.angle)
pendulum.velocity += pendulum.acceleration
pendulum.damping -= 0.000001
pendulum.velocity *= pendulum.damping
pendulum.prevAngle = pendulum.angle
pendulum.angle += pendulum.velocity
// if(Math.abs(pendulum.prevAngle - pendulum.angle < 0.0001)){
// pendulum.ended = true
// }
}
const updatePendulumPosition = (pendulum) => {
// polar to cartesian conversion
// (in other words, mapping a slice of a circle onto x y coordinates)
pendulum.center.x = pendulum.swingRadius * sin(pendulum.angle) + pendulum.origin.x
pendulum.center.y = pendulum.swingRadius * cos(pendulum.angle) + pendulum.origin.y
// console.log(pendulum.swingRadius, pendulum.angle, pendulum.origin.y)
// console.log(y)
// return {
// x, y
// }
}
const createSynth = (i) => {
const osc = new p5.Oscillator('sine')
const mod = new p5.Oscillator('sine')
const modBaseFreq = random(100, 200)
const modAmp = random(150,350)
return {
id: i,
osc,
mod,
modBaseFreq,
modAmp,
}
}
const updateSynth = (angle, synth) => {
const newFreq = Math.abs(sin(angle) * synth.modBaseFreq)
if(random(0.0,1.0) > 0.2){
synth.mod.amp(random(-synth.modAmp, synth.modAmp), 0.01)
}
synth.mod.freq(newFreq)
// synth.mod.amp(synth.amp, 0.01)
synth.osc.freq(synth.mod)
// console.log(angle)
let amplt = map(Math.abs(angle), PI/2, 0, 0, 1.0)
if(amplt > 0.8 ){
synth.osc.amp(amplt , 0.001)
}else{
synth.osc.amp(0,0.001)
}
synth.mod.amp(0)
}
const createPendulum = (idx) => {
const randomY = random(50, 100)
return {
// geometries
id: idx,
origin: {x: canvasWidth/2, y: (idx + 1) * randomY},
center: {x: canvasWidth/2, y: 200},
lineStart: {x: canvasWidth/2, y: (idx + 1) * randomY},
size: (idx + 1) * 100,
swingRadius: (idx + 1) * 150,
color: [(idx + 1) * 50, 0, (idx + 1) * 50, 60],
// physics
gravity: 0.9,
damping: 0.99995,
angle: Math.PI/(idx + 1) ,
acceleration: 0,
velocity: 0,
// synth
synth: null,
ended: false,
}
} |
Python | UTF-8 | 10,028 | 2.65625 | 3 | [
"MIT"
] | permissive | """MA243x0A series USB power sensor"""
import functools
from datetime import datetime
import sys
import asyncio
import itertools
import pyvisa
from anritsu_pwrmtr.common import (
InstrumentBase,
get_idn,
Subsystem,
State,
)
ERRORSTATUS = [
"Temperature change of more than 10 °C after zeroing",
"Operating temperature over range < 0 °C or > 60 °C",
"High Power Detector zeroing error",
"Mid Power Detector zeroing error",
"Low Power Detector zeroing error",
]
MODE = [
"Continuous Average",
"Time Slot",
"Scope",
"Idle",
"List",
]
AVGTYP = {"0": "Moving", "1": "Repeat"}
AVGMODE = {"0": "Off", "1": "On", "2": "Once"}
AVGRES = {"0": "1.0", "1": "0.1", "2": "0.01", "3": "0.001"}
def write(func):
"""Write <value> and return result message such as 'OK', 'BAD CMD', 'ERR'"""
@functools.wraps(func)
def inner(*args, **kwargs):
_self = args[0]
func(*args, **kwargs)
return _self._visa.read()
return inner
class MA243x0A(InstrumentBase):
"""MA243x0A class
Attributes:
visa (pyvisa.resources.Resource): pyvisa resource
"""
def __init__(self, visa):
super().__init__(visa)
self._idn = get_idn(visa)
self._state = State()
self.trigger = Trigger(self)
@property
def model(self):
"""(str): the model number"""
return self._idn.model
@property
def serial_number(self):
"""(str): the serial number"""
return self._idn.serial_number
@property
def firmware_version(self):
"""(str): the firmware version"""
return self._idn.firmware_version
def __repr__(self):
return f"<Anritsu {self.model} at {self._visa.resource_name}>"
@property
def status(self):
"""Get the status (errors)"""
result = int(self._visa.query("STATUS?"))
errors = [err for i, err in enumerate(ERRORSTATUS) if result & 2 ** i]
return errors if errors else "no errors"
@property
def mode(self):
"""value : str {Continuous Average, Time Slot, Scope, Idle, List}"""
i = int(self._visa.query("CHMOD?"))
return MODE[i]
@mode.setter
@write
def mode(self, value):
try:
i = MODE.index(value.title())
except ValueError:
raise ValueError(f"'{value}' not in {MODE}") from None
self._visa.write(f"CHMOD {i}")
@property
def aperture_time(self):
"""value : float aperture time in milliseconds 0.01 ms to 1000 ms"""
return float(self._visa.query("CHAPERT?"))
@aperture_time.setter
@write
def aperture_time(self, value):
if 0.01 <= value <= 1000:
self._visa.write(f"CHAPERT {value}")
else:
raise ValueError(f"'{value}' not in 0.01 ms to 1000 ms")
@property
def frequency(self):
"""frequency : float frequency in gigahertz 0.000001 GHz to 50 GHz"""
return float(self._visa.query("FREQ?"))
@frequency.setter
@write
def frequency(self, value):
if 0.000001 <= value <= 50:
self._visa.write(f"FREQ {value}")
else:
raise ValueError(f"'{value}' not in 0.000001 GHz to 50 GHz")
@property
def temperature(self):
"""float current temperature of the sensor in celcius"""
return float(self._visa.query("TMP?"))
@property
def cal_date(self):
"""datetime date of last calibration"""
return datetime.strptime(self._visa.query("CALDATE"), "%m/%d/%Y %H:%M:%S")
@write
def reset(self):
"""Reset the sensor to factory default configuration"""
self._visa.write("RST")
async def _show_spinner(self):
"""Show an in-progress spinner during acquisition"""
glyph = itertools.cycle(["-", "\\", "|", "/"])
try:
while self._state.running:
sys.stdout.write(next(glyph))
sys.stdout.flush()
sys.stdout.write("\b")
await asyncio.sleep(0.5)
return 0
except asyncio.CancelledError:
pass
finally:
sys.stdout.write("\b \b")
async def _zero(self):
# zeroing takes ~25 s
originaltimeout = self._visa.timeout
self._visa.timeout = 100 # ms
self._visa.write("ZERO")
try:
while True:
await asyncio.sleep(10)
try:
result = self._visa.read()
except pyvisa.VisaIOError:
pass
else:
break
return 0 if result == "OK" else 1
except asyncio.CancelledError:
pass
finally:
self._state.running = False
self._visa.timeout = originaltimeout
async def _start_task(self, coroutine, timeout):
"""timeout : int timeout in seconds
coroutine : awaitable
"""
self._state.running = True
task = asyncio.gather(self._show_spinner(), coroutine)
try:
ret_value = await asyncio.wait_for(task, timeout)
except asyncio.TimeoutError:
task.exception() # retrieve the _GatheringFuture exception
raise TimeoutError(
"Operation didn't complete before specified timeout value"
) from None
else:
return ret_value
def zero(self):
"""Zero the power sensor which takes 25 s"""
error = asyncio.run(self._start_task(self._zero(), 30))[1]
if error:
raise RuntimeError(", ".join(self.status))
@property
def averaging_type(self):
"""value : str {Moving, Repeat}"""
return AVGTYP[self._visa.query("AVGTYP?")]
@averaging_type.setter
@write
def averaging_type(self, value):
avgtyp = {v: k for k, v in AVGTYP.items()}
self._visa.write(f"AVGTYP {avgtyp[value]}")
@property
def averaging_count(self):
"""value : int number of samples to average up to 65536"""
return int(self._visa.query("AVGCNT?"))
@averaging_count.setter
@write
def averaging_count(self, value):
self._visa.write(f"AVGCNT {value}")
@property
def averaging_mode(self):
"""value : str auto-averaging mode {Off, On, Once}"""
return AVGMODE[self._visa.query("AUTOAVG?")]
@averaging_mode.setter
@write
def averaging_mode(self, value):
avgmode = {v: k for k, v in AVGMODE.items()}
self._visa.write(f"AUTOAVG {avgmode[value]}")
@property
def averging_resolution(self):
"""value : str resolution {1.0, 0.1, 0.01, 0.001} dB"""
return AVGRES[self._visa.query("AUTOAVGRES?")]
@averging_resolution.setter
@write
def averging_resolution(self, value):
avgres = {v: k for k, v in AVGRES.items()}
self._visa.write(f"AUTOAVGRES {avgres[value]}")
@property
def averaging_source(self):
"""value : int"""
return int(self._visa.query("AUTOAVGSRC?"))
@write
def reset_averaging(self):
"""Clear the averaging buffer and restart"""
self._visa.write("AVGRST")
def read(self):
"""Read power in dBm"""
cmd = "PWR?"
result = self._visa.query(f"{cmd}")
if result.startswith("e"):
raise RuntimeError(", ".join(self.status))
return float(result)
def __dir__(self):
attrs = super().__dir__()
if self.mode != "Continuous Average":
attrs.remove("aperture_time")
return attrs
TRGSRC = {"0": "Continuous", "1": "Internal", "2": "External"}
TRGEDG = {"0": "Positive", "1": "Negative"}
TRGARM = {"0": "Auto", "1": "Single", "2": "Multi", "3": "Standby"}
class Trigger(Subsystem, kind="Trigger"):
"""Trigger subsystem
Attributes
----------
instr : MA243x0A
"""
@property
def source(self):
"""value : str {Continuous, Internal, External}"""
return TRGSRC[self._visa.query("TRGSRC?")]
@source.setter
@write
def source(self, value):
trgsrc = {v: k for k, v in TRGSRC.items()}
self._visa.write(f"TRGSRC {trgsrc[value]}")
@property
def level(self):
"""value : float -35 dBm to +20 dBm in 0.01 dB steps"""
return float(self._visa.query("TRGLVL?"))
@level.setter
@write
def level(self, value):
self._visa.write(f"TRGLVL {value}")
@property
def edge(self):
"""value : str {Positive, Negative}"""
return TRGEDG[self._visa.query("TRGEDG?")]
@edge.setter
@write
def edge(self, value):
trgedg = {v: k for k, v in TRGEDG.items()}
self._visa.write(f"TRGEDG {trgedg[value]}")
@property
def delay(self):
"""value : float
start of acquisition in milliseconds relative to trigger event
-5 ms to +10000 ms in 0.01 ms steps
"""
return float(self._visa.query("TRGDLY?"))
@delay.setter
@write
def delay(self, value):
self._visa.write(f"TRGDLY {value}")
@property
def holdoff(self):
"""value : float
trigger supression in milliseconds after first detected event
0 ms to 10000 ms in 0.01 ms steps
"""
return float(self._visa.query("TRGHOLDDLY?"))
@holdoff.setter
@write
def holdoff(self, value):
self._visa.write(f"TRGHOLDDLY {value}")
@property
def hysteresis(self):
"""value : float hysteresis 0 dB to 10 dB in 0.1 dB steps"""
return float(self._visa.query("TRGHYST?"))
@hysteresis.setter
@write
def hysteresis(self, value):
self._visa.write(f"TRGHYST {value}")
def arm(self, mode="Auto"):
"""Arm the trigger
Parameters
----------
mode : str {"Auto", "Single", "Multi", "Standby"}
"""
trgarm = {v: k for k, v in TRGARM.items()}
self._visa.write(f"TRGARMTYP {trgarm[mode]}")
|
Markdown | UTF-8 | 4,515 | 2.6875 | 3 | [
"MIT"
] | permissive | ---
title: 信息获取与验证·2022扩展包
date: 2022-03-23 01:04
categories:
- 事实核查
tags:
- 事实核查
description: 不吐不快升级包。
is_series: true
series_title: 事实核查
---
这篇东西是去年东奥期间那篇[《后信息时代的信息获取和验证指南》](/blog/2021/09/11/a-guide-for-information-get-and-check-on-this-post-information-age/)的后续,当时,我们讨论了对于信息源的分级和筛选。而正在发生的俄国全面入侵事件,是一次对前述原则的有效演练,也是一次更严峻的挑战。
之所以这么说,主要是因为东奥发生的那些事情,真的仅仅是“新闻”(或“假新闻”)而已,而现在发生的事情,已经涉及到战时的**认知战**,我们所面对的也不仅仅是想吃流量的账号,而是马力全开的政府宣传机器(当然,那些账号也不可能放过这么一波涨粉的机会)。更麻烦的是,对于所涉及的事件本身,我们也没法再靠自身能力来初步鉴别其真伪,必须依赖**专家**——通常,还要靠不止一个领域的专家,因为**没有人可以既懂军事又懂地缘政治、冲突历史,还能读第一手的俄语/乌克兰语材料**(后面甚至还涉及到了生物学、病毒学等等)。
对于整个新闻走向的“认知战”成分,相信在最初的24到48小时后,审慎的观察家们都会有所认识。我也是在第一天转发了一些新闻,之后就再也不转了,因为谁也不想成为任一方的免费宣传工具。
随之而来的自然就是“相信谁”和辟谣的问题。其中的一部分可以简单地采取**“先不信,交给时间”**策略;而另外的部分我找到了一种**“对冲”**策略,即同时关注不同倾向的博主。事实上我一直都在这么做,这次只是把之前关注的那些完全对立倾向的人所转发的信息源都拿来而已。当这一套机制建立起来之后,你会发现他们会轮流对之前对方的信息进行辟谣,或者提供不同的看问题角度。
同时不能不提的是在上一篇文章过后发现的一个公众号“有据核查”,他们会每天针对中文互联网上的热点进行事实核查,非常赞。
从2月24号这天开始,他们开始全力转向针对这场战争的核查:[核查\|俄罗斯伞兵大规模空降乌克兰东部?](http://mp.weixin.qq.com/s?__biz=MzU3OTgzNzg3MA==&mid=2247499933&idx=1&sn=131e91ded753beb03217245353efb0df&chksm=fd628a5cca15034a8ed75dae182515038d3f0666fef83b203853fa7eb9d40d29dd6ad281e0f3)
另外还有早前看到的另一篇与我同样主题的文章[《哪里看乌克兰的“真”新闻?一份不完整清单》](http://mp.weixin.qq.com/s?__biz=MzA4MTc2NDkzOQ==&mid=2651314530&idx=1&sn=a83024ed180db43bf1b7f64f9c6c5101&chksm=847c8e46b30b0750e32ce9f33ffbe8074027c5fcb11d16ecd5471df28e3b549575579b24e2a1),也提出了特别好的一段表述:
> 在点下转发前,先核查几个问题:我要转发的是不是可靠信源?发布信息的是不是没什么粉丝的全新账号?在这个消息之前,这个账号都发过什么?对不熟悉的机构账号发布的信息首先要有质疑态度,看资料和背景,过往报道和立场;看到个人账号,尽量确保他们并不是冒充的账户。
> *Chu and Friends,公众号:胡同阿伦特*
> *哪里看乌克兰的“真”新闻?一份不完整清单*
最后还是要说,整个网络最让人省心的信息源还是[竹新社](https://t.me/tnews365)(电报频道id: tnews365),他们会对最重要的事情做好核查工作后整理发稿。与之连带的是他们的读者讨论群也是我见过氛围最好的,因为只要有人用偏激的观点或者哪一边的认知战话术来群里冒头,几位管理员就会用强大的知识储备让他知道这种行为是自取其辱。
在理想的世界中,会有这么一个工具:我们可以把任意一条消息扔给它,它自动返回给我们与之相关的核查结果和扩展阅读内容。坏消息是我们没有这种工具,好消息是凭借现有的工具,我们已经可以在结果上尽量接近它。
以上就是这次想说的所有内容,其实也没什么东西,大概更多的是一种**怀疑主义**的方法论。结语还是与上一篇一致,只被来自一方的信息投喂就会越来越偏激;在世道诡谲,真相难辨之际,靠谱而多样化的信息源是你最好的朋友。 |
Java | UTF-8 | 3,741 | 2.140625 | 2 | [] | no_license | package com.mcindoe.dashstreamer.views;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.mcindoe.dashstreamer.R;
import com.mcindoe.dashstreamer.controllers.DASHStreamerApplication;
import com.mcindoe.dashstreamer.controllers.MPDParser;
import com.mcindoe.dashstreamer.controllers.Utils;
import com.mcindoe.dashstreamer.controllers.MPDParser.MPDLoadedListener;
import com.mcindoe.dashstreamer.controllers.MPIArrayAdapter;
import com.mcindoe.dashstreamer.controllers.MPIParser;
import com.mcindoe.dashstreamer.controllers.MPIParser.MPILoadedListener;
import com.mcindoe.dashstreamer.models.MediaPresentation;
import com.mcindoe.dashstreamer.models.MediaPresentationIndex;
public class MainActivityControlFragment extends Fragment {
private Fragment mFragment;
private ListView mVideoListView;
private MPIArrayAdapter mMPIArrayAdapter;
private ArrayList<MediaPresentationIndex> mMPIs;
public MainActivityControlFragment() {
mFragment = this;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mVideoListView = (ListView)rootView.findViewById(R.id.video_list_view);
String ip_addr = getResources().getString(R.string.ip_addr);
//Starts a request for the MPIs from the server.
new MPIParser(mFragment.getActivity(), ip_addr + ":4573/mpi.xml", new MPILoadedListener() {
/**
* Called when the download from the server fails.
*/
@Override
public void onFailedDownload() {
Log.d(Utils.LOG_TAG, "MPI download failed.");
Toast.makeText(mFragment.getActivity(), "Load from server failed.\nTry again later.", Toast.LENGTH_LONG).show();
}
/**
* Called when the MPIs have been pulled from the server successfully
*/
@Override
public void onIndicesLoaded(ArrayList<MediaPresentationIndex> mpis) {
mMPIs = mpis;
//Sets up our video list view with our custom array adapter.
mMPIArrayAdapter = new MPIArrayAdapter(mFragment.getActivity(), mMPIs, null);
mVideoListView.setAdapter(mMPIArrayAdapter);
//Sets the click listener for the list view.
mVideoListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Grabs the MPD for the selected MPI and starts the play activity.
new MPDParser(mFragment.getActivity(), mMPIs.get(position).getUrl(), new MPDLoadedListener() {
/**
* Called when the download from the server fails.
*/
@Override
public void onFailedDownload() {
Log.d(Utils.LOG_TAG, "MPI download failed.");
Toast.makeText(mFragment.getActivity(), "Load from server failed.\nTry again later.", Toast.LENGTH_LONG).show();
}
@Override
public void onMediaPresentationsLoaded(ArrayList<MediaPresentation> mpds) {
((DASHStreamerApplication)mFragment.getActivity().getApplication()).setCurrentMediaPresentation(mpds.get(0));
Intent intent = new Intent(mFragment.getActivity(), PlayActivity.class);
startActivityForResult(intent, 0);
mFragment.getActivity().overridePendingTransition(R.animator.enter_next_activity, R.animator.exit_current_activity);
}
});
}
});
}
});
return rootView;
}
}
|
Java | UTF-8 | 2,951 | 2.9375 | 3 | [] | no_license | package com.tonux.spring.jdbc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import com.tonux.spring.jdbc.model.Utilisateur;
import com.tonux.spring.jdbc.rowmappers.UtilisateurRow;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class UtilisateurSpringDAOImpl implements UtilisateurDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void save(Utilisateur utilisateur) {
String query = "insert into Utilisateurs (id, name, role) values (?,?,?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
Object[] args = new Object[] {utilisateur.getId(), utilisateur.getName(), utilisateur.getRole()};
int out = jdbcTemplate.update(query, args);
if(out !=0){
System.out.println("Utilisateur créé id="+ utilisateur.getId());
}else System.out.println("Utilisateur création échouée id="+ utilisateur.getId());
}
public Utilisateur getById(int id) {
String query = "select id, name, role from Utilisateurs where id = ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//using RowMapper
RowMapper<Utilisateur> userRowMapper = new UtilisateurRow();
Utilisateur user = jdbcTemplate.queryForObject(query, new Object[]{id}, userRowMapper);
return user;
}
public void update(Utilisateur utilisateur) {
String query = "update Utilisateurs set name=?, role=? where id=?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
Object[] args = new Object[] {utilisateur.getName(), utilisateur.getRole(), utilisateur.getId()};
int out = jdbcTemplate.update(query, args);
if(out !=0){
System.out.println("Utilisateur mise a jour id="+ utilisateur.getId());
}else System.out.println("Pas Utilisateur trouvé id="+ utilisateur.getId());
}
public void deleteById(int id) {
String query = "delete from Utilisateurs where id=?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
int out = jdbcTemplate.update(query, id);
if(out !=0){
System.out.println("Utilisateur supprimé id="+id);
}else System.out.println("Pas Utilisateur trouvé id="+id);
}
public List<Utilisateur> getAll() {
String query = "select id, name, role from Utilisateurs";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Utilisateur> userList = new ArrayList<Utilisateur>();
List<Map<String,Object>> userRows = jdbcTemplate.queryForList(query);
for(Map<String,Object> userRow : userRows){
Utilisateur user = new Utilisateur();
user.setId(Integer.parseInt(String.valueOf(userRow.get("id"))));
user.setName(String.valueOf(userRow.get("name")));
user.setRole(String.valueOf(userRow.get("role")));
userList.add(user);
}
return userList;
}
}
|
Shell | UTF-8 | 1,061 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash
# Update the petalinux makefile to copy the rootfs.tar.gz file to the Vitis platform staging area
sed -i '31i\\tcp -f images\/linux\/rootfs.tar.gz \${OUTPUT}\/src\/\${CPU_ARCH}\/xrt\/image\/rootfs.tar.gz' petalinux/Makefile
# Update the petalinux project for SD card rootfs
cp petalinux/project-spec/configs/config petalinux/project-spec/configs/config.old
cp petalinux/project-spec/configs/rootfs_config petalinux/project-spec/configs/rootfs_config.old
sed -i 's/CONFIG_SUBSYSTEM_ROOTFS_INITRAMFS=y/# CONFIG_SUBSYSTEM_ROOTFS_INITRAMFS is not set/g' petalinux/project-spec/configs/config
sed -i 's/# CONFIG_SUBSYSTEM_ROOTFS_EXT is not set/CONFIG_SUBSYSTEM_ROOTFS_EXT=y/g' petalinux/project-spec/configs/config
echo 'CONFIG_SUBSYSTEM_SDROOT_DEV="/dev/mmcblk0p2"' >> petalinux/project-spec/configs/config
cat <<EOT >> petalinux/project-spec/meta-user/recipes-bsp/device-tree/files/system-user.dtsi
/{
chosen {
bootargs = "earlycon console=ttyPS0,115200 clk_ignore_unused root=/dev/mmcblk0p2 rw rootwait cma=1100M cpuidle.off=1";
};
};
EOT
|
PHP | UTF-8 | 827 | 2.6875 | 3 | [] | no_license | <?php
require __DIR__ . '/vendor/autoload.php';
use Test\CouponDiscountCalculator;
use Test\FixedAbsoluteCoupon;
use Test\FixedSlabCoupon;
$couponDiscountCalculator = new CouponDiscountCalculator();
$fixedAbsoluteCoupon = new FixedAbsoluteCoupon();
$fixedAbsoluteCoupon->maxAmount = 1000;
$fixedAbsoluteCoupon->minAmount = 500;
$fixedAbsoluteCoupon->discountMaxAmount = 300;
$fixedAbsoluteCoupon->discountAmount = 100;
echo $couponDiscountCalculator->calcDiscount($fixedAbsoluteCoupon, 700);
echo PHP_EOL;
$fixedSlabCoupon = new FixedSlabCoupon();
$fixedSlabCoupon->maxAmount = 1000;
$fixedSlabCoupon->minAmount = 500;
$fixedSlabCoupon->discountMaxAmount = 300;
$fixedSlabCoupon->discountAmount = 50;
$fixedSlabCoupon->discountUnit = 10;
echo $couponDiscountCalculator->calcDiscount($fixedSlabCoupon, 700);
echo PHP_EOL; |
Swift | UTF-8 | 26,351 | 3.0625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // UIViewExtensions.swift - Copyright 2022 SwifterSwift
#if canImport(UIKit) && !os(watchOS)
import UIKit
// MARK: - enums
public extension UIView {
/// SwifterSwift: Shake directions of a view.
///
/// - horizontal: Shake left and right.
/// - vertical: Shake up and down.
enum ShakeDirection {
/// SwifterSwift: Shake left and right.
case horizontal
/// SwifterSwift: Shake up and down.
case vertical
}
/// SwifterSwift: Angle units.
///
/// - degrees: degrees.
/// - radians: radians.
enum AngleUnit {
/// SwifterSwift: degrees.
case degrees
/// SwifterSwift: radians.
case radians
}
/// SwifterSwift: Shake animations types.
///
/// - linear: linear animation.
/// - easeIn: easeIn animation.
/// - easeOut: easeOut animation.
/// - easeInOut: easeInOut animation.
enum ShakeAnimationType {
/// SwifterSwift: linear animation.
case linear
/// SwifterSwift: easeIn animation.
case easeIn
/// SwifterSwift: easeOut animation.
case easeOut
/// SwifterSwift: easeInOut animation.
case easeInOut
}
/// SwifterSwift: Add gradient directions
struct GradientDirection {
static let topToBottom = GradientDirection(startPoint: CGPoint(x: 0.5, y: 0.0),
endPoint: CGPoint(x: 0.5, y: 1.0))
static let bottomToTop = GradientDirection(startPoint: CGPoint(x: 0.5, y: 1.0),
endPoint: CGPoint(x: 0.5, y: 0.0))
static let leftToRight = GradientDirection(startPoint: CGPoint(x: 0.0, y: 0.5),
endPoint: CGPoint(x: 1.0, y: 0.5))
static let rightToLeft = GradientDirection(startPoint: CGPoint(x: 1.0, y: 0.5),
endPoint: CGPoint(x: 0.0, y: 0.5))
let startPoint: CGPoint
let endPoint: CGPoint
}
}
// MARK: - Properties
public extension UIView {
/// SwifterSwift: Border color of view; also inspectable from Storyboard.
@IBInspectable var layerBorderColor: UIColor? {
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
set {
guard let color = newValue else {
layer.borderColor = nil
return
}
// Fix React-Native conflict issue
guard String(describing: type(of: color)) != "__NSCFType" else { return }
layer.borderColor = color.cgColor
}
}
/// SwifterSwift: Border width of view; also inspectable from Storyboard.
@IBInspectable var layerBorderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
/// SwifterSwift: Corner radius of view; also inspectable from Storyboard.
@IBInspectable var layerCornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.masksToBounds = true
layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
}
}
/// SwifterSwift: Height of view.
var height: CGFloat {
get {
return frame.size.height
}
set {
frame.size.height = newValue
}
}
/// SwifterSwift: Check if view is in RTL format.
var isRightToLeft: Bool {
if #available(iOS 10.0, macCatalyst 13.0, tvOS 10.0, *) {
return effectiveUserInterfaceLayoutDirection == .rightToLeft
} else {
return false
}
}
/// SwifterSwift: Take screenshot of view (if applicable).
var screenshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
/// SwifterSwift: Shadow color of view; also inspectable from Storyboard.
@IBInspectable var layerShadowColor: UIColor? {
get {
guard let color = layer.shadowColor else { return nil }
return UIColor(cgColor: color)
}
set {
layer.shadowColor = newValue?.cgColor
}
}
/// SwifterSwift: Shadow offset of view; also inspectable from Storyboard.
@IBInspectable var layerShadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
/// SwifterSwift: Shadow opacity of view; also inspectable from Storyboard.
@IBInspectable var layerShadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
/// SwifterSwift: Shadow radius of view; also inspectable from Storyboard.
@IBInspectable var layerShadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
/// SwifterSwift: Masks to bounds of view; also inspectable from Storyboard.
@IBInspectable var masksToBounds: Bool {
get {
return layer.masksToBounds
}
set {
layer.masksToBounds = newValue
}
}
/// SwifterSwift: Size of view.
var size: CGSize {
get {
return frame.size
}
set {
width = newValue.width
height = newValue.height
}
}
/// SwifterSwift: Get view's parent view controller
var parentViewController: UIViewController? {
weak var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
/// SwifterSwift: Width of view.
var width: CGFloat {
get {
return frame.size.width
}
set {
frame.size.width = newValue
}
}
/// SwifterSwift: x origin of view.
var x: CGFloat {
get {
return frame.origin.x
}
set {
frame.origin.x = newValue
}
}
/// SwifterSwift: y origin of view.
var y: CGFloat {
get {
return frame.origin.y
}
set {
frame.origin.y = newValue
}
}
}
// MARK: - Methods
public extension UIView {
/// SwifterSwift: Recursively find the first responder.
func firstResponder() -> UIView? {
var views = [UIView](arrayLiteral: self)
var index = 0
repeat {
let view = views[index]
if view.isFirstResponder {
return view
}
views.append(contentsOf: view.subviews)
index += 1
} while index < views.count
return nil
}
/// SwifterSwift: Set some or all corners radiuses of view.
///
/// - Parameters:
/// - corners: array of corners to change (example: [.bottomLeft, .topRight]).
/// - radius: radius for selected corners.
func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let maskPath = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
layer.mask = shape
}
/// SwifterSwift: Add shadow to view.
///
/// - Note: This method only works with non-clear background color, or if the view has a `shadowPath` set.
/// See parameter `opacity` for detail.
///
/// - Parameters:
/// - color: shadow color (default is #137992).
/// - radius: shadow radius (default is 3).
/// - offset: shadow offset (default is .zero).
/// - opacity: shadow opacity (default is 0.5). It will also be affected by the `alpha` of `backgroundColor`.
func addShadow(
ofColor color: UIColor = UIColor(red: 0.07, green: 0.47, blue: 0.57, alpha: 1.0),
radius: CGFloat = 3,
offset: CGSize = .zero,
opacity: Float = 0.5) {
layer.shadowColor = color.cgColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
layer.masksToBounds = false
}
/// SwifterSwift: Add array of subviews to view.
///
/// - Parameter subviews: array of subviews to add to self.
func addSubviews(_ subviews: [UIView]) {
subviews.forEach { addSubview($0) }
}
/// SwifterSwift: Fade in view.
///
/// - Parameters:
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func fadeIn(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
if isHidden {
isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 1
}, completion: completion)
}
/// SwifterSwift: Fade out view.
///
/// - Parameters:
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func fadeOut(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) {
if isHidden {
isHidden = false
}
UIView.animate(withDuration: duration, animations: {
self.alpha = 0
}, completion: completion)
}
/// SwifterSwift: Load view from nib.
///
/// - Parameters:
/// - name: nib name.
/// - bundle: bundle of nib (default is nil).
/// - Returns: optional UIView (if applicable).
class func loadFromNib(named name: String, bundle: Bundle? = nil) -> UIView? {
return UINib(nibName: name, bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
/// SwifterSwift: Load view of a certain type from nib
///
/// - Parameters:
/// - withClass: UIView type.
/// - bundle: bundle of nib (default is nil).
/// - Returns: UIView
class func loadFromNib<T: UIView>(withClass name: T.Type, bundle: Bundle? = nil) -> T {
let named = String(describing: name)
guard let view = UINib(nibName: named, bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as? T else {
fatalError("First element in xib file \(named) is not of type \(named)")
}
return view
}
/// SwifterSwift: Remove all subviews in view.
func removeSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
/// SwifterSwift: Remove all gesture recognizers from view.
func removeGestureRecognizers() {
gestureRecognizers?.forEach(removeGestureRecognizer)
}
/// SwifterSwift: Attaches gesture recognizers to the view. Attaching gesture recognizers to a view defines the scope of the represented gesture, causing it to receive touches hit-tested to that view and all of its subviews. The view establishes a strong reference to the gesture recognizers.
///
/// - Parameter gestureRecognizers: The array of gesture recognizers to be added to the view.
func addGestureRecognizers(_ gestureRecognizers: [UIGestureRecognizer]) {
for recognizer in gestureRecognizers {
addGestureRecognizer(recognizer)
}
}
/// SwifterSwift: Detaches gesture recognizers from the receiving view. This method releases gestureRecognizers in addition to detaching them from the view.
///
/// - Parameter gestureRecognizers: The array of gesture recognizers to be removed from the view.
func removeGestureRecognizers(_ gestureRecognizers: [UIGestureRecognizer]) {
for recognizer in gestureRecognizers {
removeGestureRecognizer(recognizer)
}
}
/// SwifterSwift: Rotate view by angle on relative axis.
///
/// - Parameters:
/// - angle: angle to rotate view by.
/// - type: type of the rotation angle.
/// - animated: set true to animate rotation (default is true).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func rotate(
byAngle angle: CGFloat,
ofType type: AngleUnit,
animated: Bool = false,
duration: TimeInterval = 1,
completion: ((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? .pi * angle / 180.0 : angle
let aDuration = animated ? duration : 0
UIView.animate(withDuration: aDuration, delay: 0, options: .curveLinear, animations: { () in
self.transform = self.transform.rotated(by: angleWithType)
}, completion: completion)
}
/// SwifterSwift: Rotate view to angle on fixed axis.
///
/// - Parameters:
/// - angle: angle to rotate view to.
/// - type: type of the rotation angle.
/// - animated: set true to animate rotation (default is false).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func rotate(
toAngle angle: CGFloat,
ofType type: AngleUnit,
animated: Bool = false,
duration: TimeInterval = 1,
completion: ((Bool) -> Void)? = nil) {
let angleWithType = (type == .degrees) ? .pi * angle / 180.0 : angle
let currentAngle = atan2(transform.b, transform.a)
let aDuration = animated ? duration : 0
UIView.animate(withDuration: aDuration, animations: {
self.transform = self.transform.rotated(by: angleWithType - currentAngle)
}, completion: completion)
}
/// SwifterSwift: Scale view by offset.
///
/// - Parameters:
/// - offset: scale offset
/// - animated: set true to animate scaling (default is false).
/// - duration: animation duration in seconds (default is 1 second).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func scale(
by offset: CGPoint,
animated: Bool = false,
duration: TimeInterval = 1,
completion: ((Bool) -> Void)? = nil) {
if animated {
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () in
self.transform = self.transform.scaledBy(x: offset.x, y: offset.y)
}, completion: completion)
} else {
transform = transform.scaledBy(x: offset.x, y: offset.y)
completion?(true)
}
}
/// SwifterSwift: Shake view.
///
/// - Parameters:
/// - direction: shake direction (horizontal or vertical), (default is .horizontal).
/// - duration: animation duration in seconds (default is 1 second).
/// - animationType: shake animation type (default is .easeOut).
/// - completion: optional completion handler to run with animation finishes (default is nil).
func shake(
direction: ShakeDirection = .horizontal,
duration: TimeInterval = 1,
animationType: ShakeAnimationType = .easeOut,
completion: (() -> Void)? = nil) {
CATransaction.begin()
let animation: CAKeyframeAnimation
switch direction {
case .horizontal:
animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
case .vertical:
animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
}
switch animationType {
case .linear:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
case .easeIn:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
case .easeOut:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
case .easeInOut:
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
}
CATransaction.setCompletionBlock(completion)
animation.duration = duration
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0]
layer.add(animation, forKey: "shake")
CATransaction.commit()
}
/// SwifterSwift: Add Gradient Colors.
///
/// view.addGradient(
/// colors: [.red, .blue],
/// locations: [0.0, 1.0],
/// direction: .topToBottom
/// )
///
/// - Parameters:
/// - colors: An array of `SFColor` defining the color of each gradient stop.
/// - locations: An array of `CGFloat` defining the location of each
/// gradient stop as a value in the range [0, 1]. The values must be
/// monotonically increasing.
/// - direction: Struct type describing the direction of the gradient.
func addGradient(colors: [SFColor], locations: [CGFloat] = [0.0, 1.0], direction: GradientDirection) {
// <https://github.com/swiftdevcenter/GradientColorExample>
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = colors.map { $0.cgColor }
gradientLayer.locations = locations.map { NSNumber(value: $0) }
gradientLayer.startPoint = direction.startPoint
gradientLayer.endPoint = direction.endPoint
layer.addSublayer(gradientLayer)
}
/// SwifterSwift: Add Visual Format constraints.
///
/// - Parameters:
/// - withFormat: visual Format language.
/// - views: array of views which will be accessed starting with index 0 (example: [v0], [v1], [v2]..).
func addConstraints(withFormat: String, views: UIView...) {
// https://videos.letsbuildthatapp.com/
var viewsDictionary: [String: UIView] = [:]
for (index, view) in views.enumerated() {
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: withFormat,
options: NSLayoutConstraint.FormatOptions(),
metrics: nil,
views: viewsDictionary))
}
/// SwifterSwift: Anchor all sides of the view into it's superview.
func fillToSuperview() {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
let left = leftAnchor.constraint(equalTo: superview.leftAnchor)
let right = rightAnchor.constraint(equalTo: superview.rightAnchor)
let top = topAnchor.constraint(equalTo: superview.topAnchor)
let bottom = bottomAnchor.constraint(equalTo: superview.bottomAnchor)
NSLayoutConstraint.activate([left, right, top, bottom])
}
}
/// SwifterSwift: Add anchors from any side of the current view into the specified anchors and returns the newly added constraints.
///
/// - Parameters:
/// - top: current view's top anchor will be anchored into the specified anchor.
/// - left: current view's left anchor will be anchored into the specified anchor.
/// - bottom: current view's bottom anchor will be anchored into the specified anchor.
/// - right: current view's right anchor will be anchored into the specified anchor.
/// - topConstant: current view's top anchor margin.
/// - leftConstant: current view's left anchor margin.
/// - bottomConstant: current view's bottom anchor margin.
/// - rightConstant: current view's right anchor margin.
/// - widthConstant: current view's width.
/// - heightConstant: current view's height.
/// - Returns: array of newly added constraints (if applicable).
@discardableResult
func anchor(
top: NSLayoutYAxisAnchor? = nil,
left: NSLayoutXAxisAnchor? = nil,
bottom: NSLayoutYAxisAnchor? = nil,
right: NSLayoutXAxisAnchor? = nil,
topConstant: CGFloat = 0,
leftConstant: CGFloat = 0,
bottomConstant: CGFloat = 0,
rightConstant: CGFloat = 0,
widthConstant: CGFloat = 0,
heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
NSLayoutConstraint.activate(anchors)
return anchors
}
/// SwifterSwift: Anchor center X into current view's superview with a constant margin value.
///
/// - Parameter constant: constant of the anchor constraint (default is 0).
func anchorCenterXToSuperview(constant: CGFloat = 0) {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerXAnchor {
centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
/// SwifterSwift: Anchor center Y into current view's superview with a constant margin value.
///
/// - Parameter withConstant: constant of the anchor constraint (default is 0).
func anchorCenterYToSuperview(constant: CGFloat = 0) {
// https://videos.letsbuildthatapp.com/
translatesAutoresizingMaskIntoConstraints = false
if let anchor = superview?.centerYAnchor {
centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
}
}
/// SwifterSwift: Anchor center X and Y into current view's superview.
func anchorCenterSuperview() {
// https://videos.letsbuildthatapp.com/
anchorCenterXToSuperview()
anchorCenterYToSuperview()
}
/// SwifterSwift: Search all superviews until a view with the condition is found.
///
/// - Parameter predicate: predicate to evaluate on superviews.
func ancestorView(where predicate: (UIView?) -> Bool) -> UIView? {
if predicate(superview) {
return superview
}
return superview?.ancestorView(where: predicate)
}
/// SwifterSwift: Search all superviews until a view with this class is found.
///
/// - Parameter name: class of the view to search.
func ancestorView<T: UIView>(withClass _: T.Type) -> T? {
return ancestorView(where: { $0 is T }) as? T
}
/// SwifterSwift: Returns all the subviews of a given type recursively in the
/// view hierarchy rooted on the view it its called.
///
/// - Parameter ofType: Class of the view to search.
/// - Returns: All subviews with a specified type.
func subviews<T>(ofType _: T.Type) -> [T] {
var views = [T]()
for subview in subviews {
if let view = subview as? T {
views.append(view)
} else if !subview.subviews.isEmpty {
views.append(contentsOf: subview.subviews(ofType: T.self))
}
}
return views
}
}
// MARK: - Constraints
public extension UIView {
/// SwifterSwift: Search constraints until we find one for the given view
/// and attribute. This will enumerate ancestors since constraints are
/// always added to the common ancestor.
///
/// - Parameter attribute: the attribute to find.
/// - Parameter at: the view to find.
/// - Returns: matching constraint.
func findConstraint(attribute: NSLayoutConstraint.Attribute, for view: UIView) -> NSLayoutConstraint? {
let constraint = constraints.first {
($0.firstAttribute == attribute && $0.firstItem as? UIView == view) ||
($0.secondAttribute == attribute && $0.secondItem as? UIView == view)
}
return constraint ?? superview?.findConstraint(attribute: attribute, for: view)
}
/// SwifterSwift: First width constraint for this view.
var widthConstraint: NSLayoutConstraint? {
findConstraint(attribute: .width, for: self)
}
/// SwifterSwift: First height constraint for this view.
var heightConstraint: NSLayoutConstraint? {
findConstraint(attribute: .height, for: self)
}
/// SwifterSwift: First leading constraint for this view.
var leadingConstraint: NSLayoutConstraint? {
findConstraint(attribute: .leading, for: self)
}
/// SwifterSwift: First trailing constraint for this view.
var trailingConstraint: NSLayoutConstraint? {
findConstraint(attribute: .trailing, for: self)
}
/// SwifterSwift: First top constraint for this view.
var topConstraint: NSLayoutConstraint? {
findConstraint(attribute: .top, for: self)
}
/// SwifterSwift: First bottom constraint for this view.
var bottomConstraint: NSLayoutConstraint? {
findConstraint(attribute: .bottom, for: self)
}
}
#endif
|
JavaScript | UTF-8 | 1,407 | 4.21875 | 4 | [] | no_license | /*
Given a sorted array, two integers k and x, find the k closest elements to x in the array.
The result should also be sorted in ascending order.
If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
Absolute value of elements in the array and x will not exceed 104
*/
/**
* @param {number[]} arr
* @param {number} k
* @param {number} x
* @return {number[]}
*/
var findClosestElements = function(arr, k, x) {
// use binary search to find the index of x in the arr first.
var indX = binarySearch(arr, x);
var right = indX === -1 ? indX +1 : indX; // indX point to x or the value most close to x
var left = indX === -1 ? -1 : indX-1;
while(k >0) {
if(left === -1 || Math.abs(arr[left] - x) > Math.abs(arr[right] -x)) right++;
else left--;
k--;
}
left ++;
return arr.slice(left, right);
};
var binarySearch = function(arr, x) {
var s = 0, e = arr.length-1;
while(s < e) {
var mid = ~~((s + e) / 2);
if(arr[mid] < x) { // search on right
s = mid +1;
} else {
e = mid;
}
}
return e;
}; |
C# | UTF-8 | 2,536 | 2.546875 | 3 | [] | no_license | using Microsoft.Crm.Sdk.Samples.HelperCode;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CrmHelper
{
public static class CrmAPIHelper
{
public static HttpClient CreateConnection(String[] cmdargs)
{
Configuration config = null;
if (cmdargs.Length > 0)
config = new FileConfiguration("default");
Authentication auth = new Authentication(config);
var httpClient = new HttpClient(auth.ClientHandler, true);
httpClient.BaseAddress = new Uri(config.ServiceUrl + "api/data/v9.1/");
httpClient.Timeout = new TimeSpan(0, 2, 0);
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
return httpClient;
}
public static JObject RetrieveSingleRecord(HttpClient httpClient, string entityPluralName, string[] properties, string filterCriteria)
{
if (properties == null || properties.Length < 1)
{
throw new Exception("Must at least one select property");
}
JObject result;
var queryOptions = "?$select=" + String.Join(",", properties);
if (!String.IsNullOrWhiteSpace(filterCriteria))
{
queryOptions = queryOptions + "&$filter=" + filterCriteria;
}
var queryResponse = httpClient.GetAsync(entityPluralName + queryOptions).Result;
if (queryResponse.StatusCode == HttpStatusCode.OK) //200
{
JObject body = JsonConvert.DeserializeObject<JObject>
(queryResponse.Content.ReadAsStringAsync().Result);
if(!body.ContainsKey("value") || body["value"] == null || !body["value"].Any())
{
result = null;
}
else
{
result = (JObject)body["value"][0];
}
}
else
{
throw new CrmHttpResponseException(queryResponse.Content);
}
return result;
}
}
}
|
Rust | UTF-8 | 471 | 2.515625 | 3 | [] | no_license | use std::env;
use chrono::Duration;
const DEFAULT_REPORT_INTERVAL: u16 = 60; // every minute
pub fn get_metric_report_interval() -> u16 {
env::var("REPORT_INTERVAL").ok()
.and_then(|v| v.parse::<u16>().ok())
.unwrap_or(DEFAULT_REPORT_INTERVAL)
}
pub fn get_max_metrics_age() -> Duration {
env::var("MAX_METRICS_AGE").ok()
.and_then(|v| v.parse::<i64>().ok())
.map(|v| Duration::hours(v))
.unwrap_or(Duration::weeks(2))
} |
C++ | UTF-8 | 9,324 | 2.796875 | 3 | [] | no_license | #include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>
#define PIN 6 //PIN di uscita dei dati.
int ora = 0; //Variabile contenente le ore.
int minuti = 0; //Variabile contenente i minuti.
int secondi = 0; //Variabile contenente i secondi.
boolean m = false; //Variabile booleana che definisce l'attivazione della parola meno.
int minutiDaSottrarre = 0; //Variabile che contiene i minuti da sottrarre per arrivare all'ora piena.
int gestioneMinuti = 0; //Variabile che aiuta a gestire le parole, i pallini e i simboli + e - per i minuti
int stripeLength = 195; //Lunghezza striscia led.
// NEO_RGB Pixels are wired for RGB bitstream
// NEO_GRB Pixels are wired for GRB bitstream, correct for neopixel stick
// NEO_KHZ400 400 KHz bitstream (e.g. FLORA pixels)
// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip), correct for neopixel stick
Adafruit_NeoPixel strip = Adafruit_NeoPixel(stripeLength, PIN, NEO_GRB + NEO_KHZ800); //Variabile che, tramite il suo metodo, gestisce il collegamento alla striscia di led neopixel.
//Array per gestire i "casi speciali":
int colonnaSecondi[13]; //Array contenente il numero dei led corrispondenti alla riga verticale dei pallini che segnano i secodni con multipli di 5.
int rigaPalliniMinuti[4] = {79, 105, 131, 157}; //Array contenente il numero dei led corrispondenti alla riga orizzontale dei pallini che segnano i minuti tra 1 e 4.
int piuMeno[2] = {27, 53}; //Array contenente il numero dei led corrispondenti al + ed al - posti nella riga orizzontale in cima.
int e[1] = {190}; //Array contenente il numero del led corrispondente alla lettera: "E".
int meno[4] = {17, 36, 43, 62}; //Array contenente il contenente il numero dei led corrispondente alla parola: "meno";
int unQuarto[8] = {89, 94, 120, 141, 146, 167, 172, 193}; //Array contenente il numero dei led corrispondenti alla scritta: "Un quarto".
int mezza[5] = {142, 145, 168, 171, 194}; //Array contenente il numero dei led corrispondenti alla parola: "mezza".
//Array delle ore:
int eLUna[6] = {25, 132, 155, 158, 181, 184}; //Array contenente il numero dei led corrispondenti alla scritta: "È l'una".
int sonoLeDue[9] = {28, 51, 54, 77, 103, 106, 159, 180, 185}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le due".
int sonoLeTre[9] = {28, 51, 54, 77, 103, 106, 23, 30, 49}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le tre".
int sonoLeQuattro[13] = {28, 51, 54, 77, 103, 106, 75, 82, 101, 108, 127, 134, 153}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le quattro".
int sonoLeCinque[12] = {28, 51, 54, 77, 103, 106, 22, 31, 48, 57, 74, 83}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le cinque".
int sonoLeSei[9] = {28, 51, 54, 77, 103, 106, 160, 179, 186}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le sei".
int sonoLeSette[11] = {28, 51, 54, 77, 103, 106, 135, 152, 161, 178, 187}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le sette".
int sonoLeOtto[10] = {28, 51, 54, 77, 103, 106, 21, 32, 47, 58}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le otto".
int sonoLeNove[10] = {28, 51, 54, 77, 103, 106, 73, 84, 99, 110}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le nove".
int sonoLeDieci[11] = {28, 51, 54, 77, 103, 106, 136, 151, 162, 177, 188}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le dieci".
int sonoLeUndici[12] = {28, 51, 54, 77, 103, 106, 20, 33, 46, 59, 72, 85}; //Array contenente il numero dei led corrispondenti alla scritta: "Sono le undici".
int eMezzogiorno[12] = {25, 24, 29, 50, 55, 76, 81, 102, 107, 128, 133, 154}; //Array contenente il numero dei led corrispondenti alla scritta: "È mezzogiorno".
int eMezzanotte[11] = {25, 19, 34, 45, 60, 71, 86, 97, 112, 123, 138}; //Array contenente il numero dei led corrispondenti alla scritta: "È mezzanotte".
//Array dei minuti:
int cinque[6] = {121, 140, 147, 166, 173, 192}; //Array contenente il numero dei led corrispondenti alla parola: "Cinque".
int dieci[5] = {16, 37, 42, 63, 58}; //Array contenente il numero dei led corrispondenti alla parola: "Dieci".
int venti[5] = {15, 38, 41, 64, 67}; //Array contenente il numero dei led corrispondenti alla parola: "Venti".
int venticinque[11] = {65, 66, 91, 92, 117, 118, 143, 144, 169, 170, 195}; //Array contenente il numero dei led corrispondenti alla parola: "Venticinque".
int trenta[6] = {18, 35, 44, 61, 70, 87}; //Array contenente il numero dei led corrispondenti alla parola: "Trenta".
int trentacinque[12] = {18, 35, 44, 61, 70, 87, 96, 113, 122, 139, 148, 165}; //Array contenente il numero dei led corrispondenti alla parola: "Trentacinque".
//Variabili RGB:
int r = 255;
int g = 0;
int b = 255;
void setup() {
strip.begin();
strip.setBrightness(50);
strip.show();
Serial.print("ciao");
}
//Metodo che gestisce l'accensione dei led di ogni array.
void ledsOn(int scritta[], int grandezza) {
for (int i = 0; i < grandezza; i++) {
strip.setPixelColor(scritta[i], r, g, b);
strip.show();
Serial.print("ledON:");
Serial.println(scritta[i]);
}
}
//Metodo che spegne tutti i led della striscia.
void spegniStripeLed() {
for (int i = 0; i < stripeLength; i++) {
strip.setPixelColor(stripeLength[i], 0, 0, 0);
strip.show();
Serial.print("ledOff");
}
}
//Metodo che gestisce le ore.
//Se i minuti superano i 40 allora incrementa l'ora di 1 e si attiva la parola meno
//e se i minuti da sottrarre sono dei multipli di 5 allora utilizzo tranquillamente
//le parole dei minuti che ho già senza dovere illuminare altro.
void setOra() {
Serial.println("Gestione ora");
if (minuti >= 40) {
ora = ora + 1;
Serial.print("Ora:");
Serial.println(ora);
m = true;
minutiDaSottrarre = 60 - minuti;
gestioneMinuti = minutiDaSottrarre % 5;
if(gestioneMinuti == 0){
switch(minutiDaSottrarre){
case 5:
Serial.print("Minuti da sottrarre: 5");
ledsOn(cinque, sizeof(cinque));
break;
case 10:
Serial.print("Minuti da sottrarre: 10");
ledsOn(dieci, sizeof(dieci));
break;
case 15:
Serial.print("Minuti da sottrarre: 15");
ledsOn(unQuarto, sizeof(unQuarto));
break;
case 20:
Serial.print("Minuti da sottrarre: 20");
ledsOn(venti, sizeof(venti));
break;
}
}else{
}
}
}
//Metodo che gestisce i simboli + e -.
//Se la scritta meno non é attiva allora accendo il led corrispondente al simbolo +
//Altrimenti accendo il led corrispondente al -.
void setPiuMeno() {
if (m != true) {
strip.setPixelColor(piuMeno[0], r, g, b);
Serial.println("Simbolo: +");
setMinutiPallini();
} else {
strip.setPixelColor(piuMeno[1], r, g, b);
Serial.println("Simbolo: -");
setMinutiPallini();
}
strip.show();
}
//Metodo che gestisce i minuti tra l'1 ed il 4 segnalati con i pallini.
//Ad ogni ciclo accendo un led ed incremento i minuti.
void setMinutiPallini() {
for (int i = 0; i < sizeof(rigaPalliniMinuti); i++) {
strip.setPixelColor(rigaPalliniMinuti[i], r, g, b);
Serial.print("Minuti: ");
Serial.println(minuti);
minuti = minuti + 1;
strip.show();
}
}
//Metodo che gestisce la riga verticale dei secondi rappresentati con dei pallini.
//Se quel determinato secondo é un multiplo di 5 accendo il suo rispettivo led,
//quando arrivo a 60 secondi spengo tutti i led.
void setSecondi() {
for (int i = 0; i < (int)(secondi / 5); i++) {
strip.setPixelColor(colonnaSecondi[i], r, g, b);
Serial.print("Secondi: ");
Serial.println(secondi);
strip.show();
}
}
void loop() {
setOra();
Serial.print("Inizio");
switch (ora) {
case 0:
Serial.print("Ora: 0");
ledsOn(eMezzanotte, sizeof(eMezzanotte));
break;
case 1:
Serial.print("Ora: 1");
ledsOn(eLUna, sizeof(eLUna));
break;
case 2:
Serial.print("Ora: 2");
ledsOn(sonoLeDue, sizeof(sonoLeDue));
break;
case 3:
Serial.print("Ora: 3");
ledsOn(sonoLeTre, sizeof(sonoLeTre));
break;
case 4:
Serial.print("Ora: 4");
ledsOn(sonoLeQuattro, sizeof(sonoLeQuattro));
break;
case 5:
Serial.print("Ora: 5");
ledsOn(sonoLeCinque, sizeof(sonoLeCinque));
break;
case 6:
Serial.print("Ora: 6");
ledsOn(sonoLeSei, sizeof(sonoLeSei));
break;
case 7:
Serial.print("Ora: 7");
ledsOn(sonoLeSette, sizeof(sonoLeSette));
break;
case 8:
Serial.print("Ora: 8");
ledsOn(sonoLeOtto, sizeof(sonoLeOtto));
break;
case 9:
Serial.print("Ora: 9");
ledsOn(sonoLeNove, sizeof(sonoLeNove));
break;
case 10:
Serial.print("Ora: 10");
ledsOn(sonoLeDieci, sizeof(sonoLeDieci));
break;
case 11:
Serial.print("Ora: 11");
ledsOn(sonoLeUndici, sizeof(sonoLeUndici));
break;
case 12:
Serial.print("Ora: 12");
ledsOn(eMezzogiorno, sizeof(eMezzogiorno));
break;
default:
Serial.print("Led spenti:");
spegniStripeLed();
break;
}
delay(10);
}
|
Python | UTF-8 | 1,465 | 2.515625 | 3 | [] | no_license | import pandas as pd
from datetime import datetime
campaignsSettings = pd.ExcelFile('CAMPAIGNS_SETTINGS.xlsx').parse('Sheet 1')
campaignsWithPeIndex = pd.ExcelFile('CAMPAIGNS_WITH_PE_INDEX.xlsx').parse('Sheet1')
campaignNames = campaignsSettings['NAME_CAMPAIGN']
def convertToDate(str):
return datetime(str[0]//10000,
str[0]%10000 // 100,
str[0] % 100,
str[1] // 100,
str[1] % 100)
def convertShifts(shifts):
shifts = [convertToDate(shift) for shift in shifts]
startSpot = min(shifts)
for i, _ in enumerate(shifts):
shifts[i] -= startSpot
shifts[i] = shifts[i].days*48 + shifts[i].seconds // 1800
return shifts
def readSpots():
data, shifts = [], []
for campaignName in campaignNames:
temp = campaignsWithPeIndex[campaignsWithPeIndex['NAME_CAMPAIGN'] == campaignName]
temp = temp.sort_values(['BROADCAST_DATE', 'TIME_SPOT'], ascending=[0, 0])
shifts.append((temp.head(1)['BROADCAST_DATE'].values[0], temp.head(1)['TIME_SPOT'].values[0]))
temp = temp[::-1]
spotsQualities = []
for index, row in temp.iterrows():
spotsQualities.append(row['PE_NORM'])
data.append(spotsQualities)
return data, convertShifts(shifts)
def readConfines():
confines = []
for index, row in campaignsSettings.iterrows():
confines.append(row['MAX_SPOTS'])
return confines
|
Java | UTF-8 | 355 | 1.664063 | 2 | [] | no_license | package com.rckdeveloper.fitenessapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class HandPushUpActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hand_push_up);
}
} |
JavaScript | UTF-8 | 547 | 2.8125 | 3 | [] | no_license |
const initState = {
inputValue: '222',
list: []
}
export default (state = initState, action) => {
switch (action.type) {
case 'change_input':
let newValue = JSON.parse(JSON.stringify(state))
return {
...newValue,
inputValue: action.data
}
case 'add_todo':
let newValueObj = JSON.parse(JSON.stringify(state))
newValueObj.list.push(newValueObj.inputValue)
newValueObj.inputValue =''
console.log(newValueObj)
return newValueObj
default:
return state
}
} |
Java | UTF-8 | 2,294 | 2.359375 | 2 | [] | no_license | package com.dvnchina.advertDelivery.sysconfig.dao.impl;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.dvnchina.advertDelivery.bean.PageBeanDB;
import com.dvnchina.advertDelivery.dao.impl.BaseDaoImpl;
import com.dvnchina.advertDelivery.sysconfig.bean.ChannelInfo;
import com.dvnchina.advertDelivery.sysconfig.dao.ChannelDao;
public class ChannelDaoImpl extends BaseDaoImpl implements ChannelDao {
/**
* 分页查询频道信息
* @param pageNo
* @param pageSize
* @return
*/
public PageBeanDB queryChannelList(ChannelInfo channel,int pageNo, int pageSize){
StringBuffer hql = new StringBuffer("from ChannelInfo where 1=1");
if(channel != null){
if(!StringUtils.isEmpty(channel.getChannelName())){
hql.append(" and channelName like '%").append(channel.getChannelName()).append("%' ");
}
if(!StringUtils.isEmpty(channel.getChannelCode())){
hql.append(" and channelCode like '%").append(channel.getChannelCode()).append("%' ");
}
}
int rowcount = this.getTotalCountHQL(hql.toString(), null);
PageBeanDB page = new PageBeanDB();
if (pageNo==0){
pageNo =1;
}
page.setPageSize(pageSize);
page.setCount(rowcount);
int totalPage = (rowcount - 1) / pageSize + 1;
if (rowcount == 0) {
pageNo = 1;
totalPage = 0;
}
if (pageNo <= 0) {
pageNo = 1;
} else if (pageNo > totalPage) {
pageNo = totalPage;
}
page.setTotalPage(totalPage);
page.setPageNo(pageNo);
hql.append("order by channelType,channelId");
List<ChannelInfo> list = (List<ChannelInfo>)this.getListForPage(hql.toString(), null, pageNo, pageSize);
page.setDataList(list);
return page;
}
/**
* 根据频道ID获取频道信息
* @param channelId
* @return
*/
public ChannelInfo getChannelById(Integer channelId){
return this.getHibernateTemplate().get(ChannelInfo.class, channelId);
}
/**
* 修改频道信息
* @param channel
*/
public void updateChannel(ChannelInfo channel){
String updateSql = "update t_channelinfo set is_playback = ?,summaryshort = ? where channel_id = ?";
this.executeBySQL(updateSql, new Object[]{channel.getIsPlayBack(),channel.getSummaryShort(),channel.getChannelId()});
}
}
|
Java | UTF-8 | 491 | 1.90625 | 2 | [] | no_license | package com.authorization.AuthServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nimbusds.jose.jwk.JWKSet;
@RestController
public class JwtController {
@Autowired
private JWKSet jwkSet;
@GetMapping(value = "/oauth2/keys", produces = "application/json; charset=UTF-8")
public String keys() {
return this.jwkSet.toString();
}
}
|
C++ | ISO-8859-7 | 3,438 | 2.609375 | 3 | [
"BSL-1.0"
] | permissive | /*=============================================================================
Copyright (c) 2011-2015 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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)
=============================================================================*/
#ifndef SPROUT_COMPLEX_ACOS_HPP
#define SPROUT_COMPLEX_ACOS_HPP
#include <sprout/config.hpp>
#include <sprout/limits.hpp>
#include <sprout/math/constants.hpp>
#include <sprout/math/isnan.hpp>
#include <sprout/math/isinf.hpp>
#include <sprout/math/copysign.hpp>
#include <sprout/complex/complex.hpp>
#include <sprout/complex/asin.hpp>
namespace sprout {
//
// acos
//
// G.6.1.1 The cacos functions
// cacos(conj(z)) = conj(cacos(z)).
// cacos(}0 + i0) returns p /2 - i0.
// cacos(}0 + iNaN) returns p /2 + iNaN.
// cacos(x + i) returns p /2 - i, for finite x.
// cacos(x + iNaN) returns NaN + iNaN and optionally raises the eeinvalidff floating-point exception, for nonzero finite x.
// cacos(-+ iy) returns p - i, for positive-signed finite y.
// cacos(++ iy) returns +0 - i, for positive-signed finite y.
// cacos(-+ i) returns 3p /4 - i.
// cacos(++ i) returns p /4 - i.
// cacos(}+ iNaN) returns NaN } i (where the sign of the imaginary part of the result is unspecified).
// cacos(NaN + iy) returns NaN + iNaN and optionally raises the eeinvalidff floating-point exception, for finite y.
// cacos(NaN + i) returns NaN - i.
// cacos(NaN + iNaN) returns NaN + iNaN.
//
namespace detail {
template<typename T>
inline SPROUT_CONSTEXPR sprout::complex<T>
acos_impl(sprout::complex<T> const& t) {
return sprout::complex<T>(sprout::math::half_pi<T>() - t.real(), -t.imag());
}
} // namespace detail
template<typename T>
inline SPROUT_CONSTEXPR sprout::complex<T>
acos(sprout::complex<T> const& x) {
typedef sprout::complex<T> type;
return sprout::math::isnan(x.real())
? sprout::math::isnan(x.imag()) ? x
: sprout::math::isinf(x.imag()) ? type(x.real(), -x.imag())
: type(x.real(), sprout::numeric_limits<T>::quiet_NaN())
: sprout::math::isnan(x.imag())
? sprout::math::isinf(x.real()) ? type(sprout::numeric_limits<T>::quiet_NaN(), x.real())
: x.real() == 0 ? type(sprout::math::half_pi<T>(), x.imag())
: type(sprout::numeric_limits<T>::quiet_NaN(), sprout::numeric_limits<T>::quiet_NaN())
: x.real() == sprout::numeric_limits<T>::infinity()
? sprout::math::isinf(x.imag()) ? type(sprout::math::quarter_pi<T>(), -x.imag())
: type(T(0), sprout::math::copysign(sprout::numeric_limits<T>::infinity(), -x.imag()))
: x.real() == -sprout::numeric_limits<T>::infinity()
? sprout::math::isinf(x.imag()) ? type(sprout::math::three_quarters_pi<T>(), -x.imag())
: type(sprout::math::pi<T>(), sprout::math::copysign(sprout::numeric_limits<T>::infinity(), -x.imag()))
: sprout::math::isinf(x.imag()) ? type(sprout::math::half_pi<T>(), sprout::math::copysign(sprout::numeric_limits<T>::infinity(), -x.imag()))
: x.real() == 0 && x.imag() == 0 ? type(sprout::math::half_pi<T>(), -x.imag())
: sprout::detail::acos_impl(sprout::asin(x))
;
}
} // namespace sprout
#endif // #ifndef SPROUT_COMPLEX_ACOS_HPP
|
C++ | UTF-8 | 466 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main()
{
int cTeste, k, teste;
cin >> cTeste;
while(cTeste--) {
cin >> k;
while(k--) {
cin >> teste;
switch(teste) {
case 1: cout << "Rolien\n"; break;
case 2: cout << "Naej\n"; break;
case 3: cout << "Elehcim\n"; break;
case 4: cout << "Odranoel\n";break;
}
}
}
return 0;
}
|
C# | UTF-8 | 3,900 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | using System.Collections.Generic;
using NUnit.Framework;
namespace CrossCutting.Diagnostics
{
static class LoggingExtensionTestCases
{
public static IEnumerable<ITestCaseData> GetTestCases()
{
yield return new TestCaseData(new LogLevelTester(
LogLevel.Debug,
(logger, message) => logger.Debug(message),
(logger, exception, message) => logger.Debug(exception, message),
(logger, format, args) => logger.DebugFormat(format, args),
(logger, exception, format, args) => logger.DebugFormat(exception, format, args),
(logger, format, args) => logger.DebugFormat(format, args),
(logger, exception, format, args) => logger.DebugFormat(exception, format, args),
(logger, func) => logger.Debug(func),
(logger, exception, func) => logger.Debug(exception, func))).SetName("Debug");
yield return new TestCaseData(new LogLevelTester(
LogLevel.Info,
(logger, message) => logger.Info(message),
(logger, exception, message) => logger.Info(exception, message),
(logger, format, args) => logger.InfoFormat(format, args),
(logger, exception, format, args) => logger.InfoFormat(exception, format, args),
(logger, format, args) => logger.InfoFormat(format, args),
(logger, exception, format, args) => logger.InfoFormat(exception, format, args),
(logger, func) => logger.Info(func),
(logger, exception, func) => logger.Info(exception, func))).SetName("Info");
yield return new TestCaseData(new LogLevelTester(
LogLevel.Warn,
(logger, message) => logger.Warn(message),
(logger, exception, message) => logger.Warn(exception, message),
(logger, format, args) => logger.WarnFormat(format, args),
(logger, exception, format, args) => logger.WarnFormat(exception, format, args),
(logger, format, args) => logger.WarnFormat(format, args),
(logger, exception, format, args) => logger.WarnFormat(exception, format, args),
(logger, func) => logger.Warn(func),
(logger, exception, func) => logger.Warn(exception, func))).SetName("Warn");
yield return new TestCaseData(new LogLevelTester(
LogLevel.Error,
(logger, message) => logger.Error(message),
(logger, exception, message) => logger.Error(exception, message),
(logger, format, args) => logger.ErrorFormat(format, args),
(logger, exception, format, args) => logger.ErrorFormat(exception, format, args),
(logger, format, args) => logger.ErrorFormat(format, args),
(logger, exception, format, args) => logger.ErrorFormat(exception, format, args),
(logger, func) => logger.Error(func),
(logger, exception, func) => logger.Error(exception, func))).SetName("Error");
yield return new TestCaseData(new LogLevelTester(
LogLevel.Fatal,
(logger, message) => logger.Fatal(message),
(logger, exception, message) => logger.Fatal(exception, message),
(logger, format, args) => logger.FatalFormat(format, args),
(logger, exception, format, args) => logger.FatalFormat(exception, format, args),
(logger, format, args) => logger.FatalFormat(format, args),
(logger, exception, format, args) => logger.FatalFormat(exception, format, args),
(logger, func) => logger.Fatal(func),
(logger, exception, func) => logger.Fatal(exception, func))).SetName("Fatal");
}
}
} |
Java | UTF-8 | 1,576 | 2.25 | 2 | [] | no_license | package com.app.health;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by apple on 03/04/18.
*/
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> name;
private ArrayList<String> email;
private static LayoutInflater inflater=null;
public LazyAdapter(Activity a, ArrayList<String> n,ArrayList<String> e) {
activity = a;
name = n;
email = e;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return name.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listrow, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name// thumb image
// Setting all values in listview
title.setText(name.get(position));
artist.setText(email.get(position));
return vi;
}
} |
Python | UTF-8 | 431 | 3.296875 | 3 | [] | no_license | from pylab import pi
# kg/m^3
STEEL_MASS_DENSITY = 7700
def sphere_mass(radius, mass_density):
return (4 / 3) * pi * radius ** 3 * mass_density
def steel_sphere_mass(radius):
return sphere_mass(radius, STEEL_MASS_DENSITY)
print("steel sphere mass for 1mm")
print(steel_sphere_mass(.001))
print("steel sphere mass for 1m")
print(steel_sphere_mass(1))
print("steel sphere mass for 10m")
print(steel_sphere_mass(10))
|
Python | UTF-8 | 8,134 | 2.578125 | 3 | [] | no_license | """
game.py
a good place to start
Here we are again, old friends. Every day is a good day for a christmas adventure.
"""
import pygame
from pygame.locals import *
pygame.init()
from src.controller_handler import ControllerHandler
from src.player import Player
from src.enemy import Enemy
from src.templates import player_templates
from src.game_world import load_levels
from src import state_machines
from src.sprites.sprites import get_sprite
GAME_TITLE = "The Whales Kill Christmas"
VERSION = "0.1"
DEFAULT_KEY_MAP = {
"left": K_LEFT,
"right": K_RIGHT,
"up": K_UP,
"down": K_DOWN,
"btn 0": K_z,
"btn 1": K_x,
"ready": K_RETURN,
}
DEFAULT_JOY_MAP = {
"left": 0,
"right": 0,
"up": 1,
"down": 1,
"btn 0": 0,
"btn 1": 1,
"ready": 9,
}
CHARACTERS = {
"Herfy": {
"template": player_templates.HERFY,
"state machine": state_machines.herfy,
"icon": "herfyicon.png",
},
"Swankers": {
"template": player_templates.SWANKERS,
"state machine": state_machines.swankers,
"icon": "swankersicon.png",
},
"Beefer": {
"template": player_templates.BEEFER,
"state machine": state_machines.beefer,
"icon": "beefericon.png"
},
"Ernie": {
"template": player_templates.ERNIE,
"state machine": state_machines.ernie,
"icon": "ernieicon.png",
},
}
def boot_menu(game_state):
"""
problably the least generic code in the project so far, but I dont mind a scripted menu
"""
PLAYERS = []
CONTROLLERS = []
READY = []
character_names = list(CHARACTERS.keys())
W, H = game_state["screen"].get_size()
if not pygame.joystick.get_init():
pygame.joystick.init()
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
for name in character_names:
CHARACTERS[name]["icon"] = get_sprite(CHARACTERS[name]["icon"], (1, 255, 1))
while True:
game_state["screen"].fill((255, 255, 255))
game_state["screen"].blit(game_state["fonts"]["HEL64"].render(GAME_TITLE, 0, (0, 0, 0)), (32, 32))
game_state["screen"].blit(game_state["fonts"]["HEL16"].render(VERSION, 0, (0, 0, 0)), (32, 96))
for i, player in enumerate(PLAYERS):
if player is None: continue
game_state["screen"].blit(game_state["fonts"]["HEL32"].render(str(player), 0, (0, 0, 0)), (64 + i * ((W-64) // 4), 256))
game_state["screen"].blit(CHARACTERS[player]["icon"], (i * ((W - 64) // 4), 320))
pygame.draw.rect(game_state["screen"], [(0, 0, 0), (50, 200, 50)][READY[i]], pygame.Rect(((64 + i * ((W-64) // 4), 648), (128, 64))))
game_state["screen"].blit(game_state["fonts"]["HEL32"].render("READY", 0, [(255, 255, 255), (0, 0, 0)][READY[i]]), (66 + i * ((W - 64) // 4), 650))
if CONTROLLERS[i] == "key":
if not pygame.event.peek(KEYDOWN): continue
keys = pygame.key.get_pressed()
if keys[DEFAULT_KEY_MAP["ready"]]:
READY[i] = not READY[i]
if keys[DEFAULT_KEY_MAP["right"]]:
idx = (character_names.index(player) + 1) % 4
while character_names[idx] in PLAYERS and idx != i:
idx += 1
idx %= 4
PLAYERS[i] = character_names[idx]
if keys[DEFAULT_KEY_MAP["left"]]:
idx = (character_names.index(player) - 1) % 4
while character_names[idx] in PLAYERS and idx != i:
idx += 1
idx %= 4
PLAYERS[i] = character_names[idx]
else:
if not (pygame.event.peek(JOYHATMOTION) or pygame.event.peek(JOYBUTTONDOWN)): continue
if CONTROLLERS[i].get_button(DEFAULT_JOY_MAP["ready"]):
READY[i] = not READY[i]
if CONTROLLERS[i].get_hat(0)[0] == 1 or CONTROLLERS[i].get_axis(DEFAULT_JOY_MAP["right"]) > .4:
idx = (character_names.index(player) + 1) % 4
while character_names[idx] in PLAYERS and idx != i:
idx += 1
idx %= 4
PLAYERS[i] = character_names[idx]
if CONTROLLERS[i].get_hat(0)[0] == -1 or CONTROLLERS[i].get_axis(DEFAULT_JOY_MAP["left"]) < -.4:
idx = (character_names.index(player) - 1) % 4
while character_names[idx] in PLAYERS and idx != i:
idx += 1
idx %= 4
PLAYERS[i] = character_names[idx]
game_state["controller handler"].update()
pygame.event.clear()
if len(PLAYERS) < 4:
if "key" not in CONTROLLERS:
if any(pygame.key.get_pressed()):
for name in character_names:
if name in PLAYERS: continue
PLAYERS.append(name)
break
CONTROLLERS.append("key")
READY.append(False)
for joy in joysticks:
if joy not in CONTROLLERS:
if not joy.get_init():
joy.init()
for btn in range(joy.get_numbuttons()):
if not joy.get_button(btn): continue
for name in character_names:
if name in PLAYERS: continue
PLAYERS.append(name)
break
CONTROLLERS.append(joy)
READY.append(False)
break
pygame.display.update()
if READY and all(READY): break
for i, player in enumerate(PLAYERS):
player_obj = Player(CHARACTERS[player]["template"])
player_obj.set_state_handler(
CHARACTERS[player]["state machine"].get_state_handler(
player_obj)
)
if CONTROLLERS[i] == "key":
game_state["controller handler"].add_player(
player_obj, DEFAULT_KEY_MAP
)
else:
game_state["controller handler"].add_player(
player_obj, DEFAULT_JOY_MAP, CONTROLLERS[i]
)
game_state["players"].append(player_obj)
def setup(screen=None, fullscreen=False, FPS=30):
"""
added screen as optional argument so this can be called again after game over
"""
game_state = {}
if screen: game_state["screen"] = screen
elif fullscreen: game_state["screen"] = pygame.display.set_mode((920, 720), FULLSCREEN)
else: game_state["screen"] = pygame.display.set_mode((920, 720))
game_state["fonts"] = {
"HEL16" : pygame.font.SysFont("Helvetica", 16),
"HEL32" : pygame.font.SysFont("Helvetica", 32),
"HEL64" : pygame.font.SysFont("Helvetica", 64),
"HEL128": pygame.font.SysFont("Helvetica", 128)
}
game_state["clock"] = pygame.time.Clock()
game_state["FPS"] = FPS
game_state["objects"] = []
game_state["enemies"] = []
game_state["players"] = []
game_state["controller handler"] = ControllerHandler()
boot_menu(game_state)
return game_state
def game_over(game_state, level):
t = 0 - game_state["screen"].get_height()
while level.run(game_state):
if t < 0: t += 6
else: t = 0
pygame.draw.rect(game_state["screen"], (255, 0, 0) ,pygame.Rect((0, t), game_state["screen"].get_size()))
game_state["screen"].blit(game_state["fonts"]["HEL128"].render("Game Over", 0, (0, 0, 0)), (64, t + 128))
pygame.display.update()
def run_game(game_state):
while True:
levels = load_levels()
for level in levels:
#cutscenes?
while level.run(game_state):
level.draw_screen(game_state)
pygame.display.update()
if not game_state["players"]:
game_over(game_state, level)
#cutscenes?
|
Java | UTF-8 | 1,128 | 2.3125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
/**
*
* @author vivi
*/
public class Utilisateur {
private String pseudo;
private boolean estConnecte;
private String nom;
private String prenom;
private String email;
private String valEmail;
public Utilisateur(String pseudo, boolean estConnecte, String nom, String prenom, String email,String valEmail) {
this.pseudo = pseudo;
this.estConnecte = estConnecte;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.valEmail=valEmail;
}
public String getValEmail() {
return valEmail;
}
public String getPseudo() {
return pseudo;
}
public String getNom() {
return nom;
}
public String getPrenom() {
return prenom;
}
public String getEmail() {
return email;
}
public boolean isConnecte() {
return estConnecte;
}
}
|
C++ | UTF-8 | 2,692 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define nmax 1007
using namespace std;
struct data
{
long k,l,r,gt;
};
long n,m,w[nmax],d,c;
data a[nmax];
void duyet(long u, long yon,long last,long canh)
{
if (a[u].k==2)
{
duyet(a[u].l,yon,2,a[u].r);
duyet(a[u].r,yon,2,a[u].l);
}
if (a[u].k==1)
{
long trai=a[u].l, phai=a[u].r;
if (a[trai].k==2 && a[phai].k==2)
{
duyet(trai,yon+1,1,phai);
duyet(phai,yon,1,trai);
}
else
{
duyet(trai,yon+1,1,phai);
duyet(phai,yon+1,1,trai);
}
}
if (last==-1 && canh==-1 && a[u].k==0)
{
a[u].gt=w[c--];
return;
}
if (a[u].k==0)
{
if (last==1)
{
if (a[canh].k==0)
{
if (a[u].gt==-1) a[u].gt=w[d++];
if (a[canh].gt==-1) a[canh].gt=w[c--];
}
else
if (a[canh].k==1)
{
if (a[u].gt==-1) a[u].gt=w[d++];
}
else
{
if (a[u].gt==-1) a[u].gt=w[c--];
}
}
else
if (last==2)
{
if (a[canh].k==0)
{
if (yon>=1)
{
if (a[u].gt==-1) a[u].gt=w[d++];
if (a[canh].gt==-1) a[canh].gt=w[d++];
}
else
{
if (a[u].gt==-1) a[u].gt=w[c--];
if (a[canh].gt==-1) a[canh].gt=w[c--];
}
}
else
if (a[canh].k==1)
{
if (a[u].gt==-1) a[u].gt=w[c--];
}
else
{
if (yon>=1)
{
if (a[u].gt==-1) a[u].gt=w[d++];
}
else
{
if (a[u].gt==-1) a[u].gt=w[c--];
}
}
}
}
}
long calc(long u)
{
if (a[u].k==2)
{
return min(calc(a[u].l),calc(a[u].r));
}
if (a[u].k==1)
{
return max(calc(a[u].l),calc(a[u].r));
}
if (a[u].k==0) return a[u].gt;
}
int main()
{
ios_base::sync_with_stdio(0);
freopen("TREE.inp","r",stdin);
freopen("TREE.out","w",stdout);
cin >> n >> m;
for (long i=1; i<=m; i++) cin >> w[i];
sort(w+1,w+m+1);
d=1;c=m;
for (long i=1; i<=n; i++)
{ cin >> a[i].k >> a[i].l >> a[i].r; a[i].gt=-1;}
duyet(1,0,-1,-1);
cout<< calc(1);
}
|
Python | UTF-8 | 5,966 | 2.765625 | 3 | [] | no_license | import json
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import pandas as pd
import math
# Rota_01_187_DFS resultados
x = []
y = []
x1 = []
y1 = []
x2 = []
y2 = []
x3 = []
y3 = []
a1 = 'pdfFuel.json'
a2 = 'pdfFuelFuzzy.json'
a3 = 'pdfSpeed.json'
a4 = 'pdfSpeedFuzzy.json'
a = ['pdfFuel1F','pdfFuel2F','pdfFuel3F','pdfFuel1S','pdfFuel2S','pffFuel3S']
b = ['pdfSpeed1F','pdfSpeed2F','pdfSpeed3F','pdfSpeed1S','pdfSpeed2S','pffSpeed3S']
c = ['fuel1F','fuel2F','fuel3F','fuel1S','fuel2S','fuel3S']
d = ['speed1F','speed2F','speed3F','speed1S','speed2S','speed3S']
#arquivo = 'Empirical_Probability_Density'
""" Fuel """
with open('PDF/'+ a[4]+'.json', 'r', encoding='utf8') as f:
data = json.load(f)
x = np.array(list(map(int,data.keys())))
y = np.array(list(data.values()))
print(y)
cdf1 = list(data.values())
cumulative = 0
for i in range(len(cdf1)):
cumulative += cdf1[i]
cdf1[i] = cumulative
with open('PDF/'+a[1]+'.json', 'r', encoding='utf8') as f:
data = json.load(f)
x1 = np.array(list(map(int,data.keys())))
y1 = np.array(list(data.values()))
print(y1)
cdf2 = list(data.values())
cumulative = 0
for i in range(len(cdf2)):
cumulative += cdf2[i]
cdf2[i] = cumulative
""" Speed """
with open('PDF/'+b[4]+'.json', 'r', encoding='utf8') as f:
data = json.load(f)
x2 = np.array(list(map(int,data.keys())))
y2 = np.array(list(data.values()))
cdf3 = list(data.values())
cumulative = 0
for i in range(len(cdf3)):
cumulative += cdf3[i]
cdf3[i] = cumulative
with open('PDF/'+b[1]+'.json', 'r', encoding='utf8') as f:
data = json.load(f)
x3 = np.array(list(map(int,data.keys())))
y3 = np.array(list(data.values()))
cdf4 = list(data.values())
cumulative = 0
for i in range(len(cdf4)):
cumulative += cdf4[i]
cdf4[i] = cumulative
def plotPDF(x,x1,y,y1,nameFile):
if nameFile == 'speed':
limInf = 14
limSup = 56
else:
limInf = -1
limSup = max(x)+1
space = 0.4
new = []
for i in range(len(x)):
if i >= limInf and i <= limSup:
new.append(int(x[i]))
maximo = max(max(y),max(y1))
fig = plt.figure(figsize=(15,5))
plt.ylim(0, maximo+4)
plt.xlim(limInf, limSup)
#plt.bar(x - 0.43*space, y2, label='Neural Network', color='tab:blue', width=0.2)
plt.bar(x - 0.37*space, y, label='SUMO', color='tab:orange', width=0.3)
plt.bar(x + 0.37*space, y1, label='Fuzzy', color='tab:green', width=0.3)
#plt.bar(x + 0.5*space, y3, label='SUMO', color='tab:red', width=0.2)
#plt.ylabel('Empirical Probability Density Function (%)', fontweight="bold")
plt.ylabel('Função Densidade de Probabilidade Empírica (%)', fontweight="bold")
#plt.xlabel('Fuel Consumption (ml/s)', fontweight="bold")
if nameFile == 'fuel':
plt.xlabel('Consumo de Combustível (ml/s)', fontweight="bold")
else:
plt.xlabel('Velocidade (km/h)', fontweight="bold")
plt.xticks(new)
plt.legend(numpoints=1, loc="upper right", ncol=2) # ,bbox_to_anchor=(-0.02, 1.15)
plt.grid(True, which="both", ls="-", linewidth=0.1, color='0.10', zorder=0)
fig.savefig(nameFile+'PDF.png', bbox_inches='tight')
plt.close(fig)
def plotCDF(x,cdf1,cdf2,nameFile):
np.array(cdf1)
np.array(cdf2)
limInf = 0
limSup = max(x)-2
space = 0.6
new = []
for i in range(len(x)):
if i >= limInf and i <= limSup:
new.append(int(x[i]))
fig = plt.figure(figsize=(15,5))
plt.ylim(0, max(cdf1)+5 or max(cdf2)+5)
plt.xlim(limInf, limSup)
print(len(x))
print(x)
print(cdf1)
#plt.bar(x - 0.43*space, y2, label='Neural Network', color='tab:blue', width=0.2)
plt.bar(x - 0.1*space, cdf1, label='SUMO', color='tab:orange', width=0.2)
plt.bar(x + 0.2*space, cdf2, label='Fuzzy', color='tab:green', width=0.2)
#plt.bar(x + 0.5*space, y3, label='SUMO', color='tab:red', width=0.2)
#plt.ylabel('Cumulative Distribution Function (%)', fontweight="bold")
plt.ylabel('Função Distribuição Acumulada (%)', fontweight="bold")
# plt.xlabel('Fuel Consumption (ml/s)', fontweight="bold")
if nameFile == 'fuel':
plt.xlabel('Consumo de Combustível (ml/s)', fontweight="bold")
else:
plt.xlabel('Velocidade (km/h)', fontweight="bold")
plt.xticks(new)
plt.legend(numpoints=1, loc="upper left", ncol=2) # ,bbox_to_anchor=(-0.02, 1.15)
plt.grid(True, which="both", ls="-", linewidth=0.1, color='0.10', zorder=0)
name = 'CDF'
fig.savefig(name+'.png', bbox_inches='tight')
plt.close(fig)
def plotCDF1(x,cdf1,cdf2,nameFile):
fig = plt.figure(1)
yMax = max(cdf1) or max(cdf2)
yMim = min(cdf1) and min(cdf2)
xMax = max(x) + 2
xMim = min(x) - 1
plt.xlim(xMim, xMax)
plt.xticks(rotation = "horizontal")
plt.grid(True, which="both", ls="-", linewidth=0.1, color='0.10', zorder=0)
plt.errorbar(x,cdf1, ls='-', label='SUMO',color='tab:orange', zorder=3)
plt.errorbar(x,cdf2, ls='-', label='Fuzzy',color='tab:green', zorder=3)
#ylabel = 'Cumulative Distribution Function (%)'
ylabel = 'Função Distribuição Acumulada (%)'
#xlabel = 'Fuel Consumption (ml/s)'
if nameFile == 'fuel':
xlabel = 'Consumo de Combustível (ml/s)'
else:
xlabel = 'Velocidade (km/h)'
#title = 'Cumulative Distribution Function'
plt.ylabel(ylabel, fontweight="bold")
plt.xlabel(xlabel, fontweight="bold")
#plt.title(title, fontweight="bold")
plt.legend(numpoints=1, loc="lower right", ncol=3) # ,bbox_to_anchor=(-0.02, 1.15)
fig.savefig(nameFile+'CDF.png', bbox_inches='tight')
plt.close(fig)
plotPDF(x,x1,y,y1,'fuel')
plotPDF(x2,x3,y2,y3,'speed')
plotCDF1(x,cdf1,cdf2,'fuel')
plotCDF1(x2,cdf3,cdf4,'speed') |
C++ | GB18030 | 1,086 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Complex
{
public:
Complex(double re = 0, double im = 0):real(re), imag(im) {};
//<<ʵ
friend ostream& operator <<(ostream& output, Complex& c);
//>>ʵ븴
friend istream& operator >>(istream& input, Complex& c);
private:
double real;//ʵ
double imag;//鲿
};
istream& operator >>(istream& input, Complex& c)
{
int a, b;
char sign, i;
do{
cout << "һ,a+biʽ:";
input >> a >> sign >> b >> i;
} while (!((sign == '+'|| sign == '-') && 'i' == i));
c.real = a;
c.imag = ('+' == sign) ? b : -b;
return input;
}
ostream& operator <<(ostream& output, Complex& c)
{
double num = c.imag;
if (num > 0){
output << c.real << "+" << c.imag << "i" << endl;
}
else{
output << c.real << c.imag << "i" << endl;
}
return output;
}
int main(){
Complex c1,c2;
cin >> c1;
cin >> c2;
cout << c1;
cout << c2;
return 0;
}
|
C# | UTF-8 | 8,633 | 2.640625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Lista.Classes
{
class Registro0400 : Registro
{
public string cod_depe;
public string indr_insc_munl;
public string cnpj_proprio;
public string tipo_depe;
public string endr_depe;
public string cnpj_unif;
public string cod_munc;
public string ctbl_propria;
public string dat_inic_para;
public string dat_fim_para;
public new void MostrarTodosRegistros(string caminhoarquivo)
{
string pathfile = caminhoarquivo;
StreamReader sr = new StreamReader(pathfile);
char c;
while (sr.Peek() > -1)
{
c = Convert.ToChar(sr.Read());
Console.Write(c);
}
}
public Registro0400 RetornaRegistro(int numerolinha, string caminhoarquivo)
{
string c;
int numcharnacoluna = 1;
int numcoluna = 1;
int numlinha = 1;
StreamReader sr = new StreamReader(caminhoarquivo);
Registro0400 regi = new Registro0400();
StringBuilder monta_num_linha = new StringBuilder();
StringBuilder monta_reg = new StringBuilder();
StringBuilder monta_cod_depe = new StringBuilder();
StringBuilder monta_indr_insc_munl = new StringBuilder();
StringBuilder monta_cnpj_proprio = new StringBuilder();
StringBuilder monta_tipo_depe = new StringBuilder();
StringBuilder monta_endr_depe = new StringBuilder();
StringBuilder monta_cnpj_unif = new StringBuilder();
StringBuilder monta_cod_munc = new StringBuilder();
StringBuilder monta_ctbl_propria = new StringBuilder();
StringBuilder monta_dat_inic_para = new StringBuilder();
StringBuilder monta_dat_fim_para = new StringBuilder();
while (sr.Peek() > -1)
{
c = Convert.ToString(Convert.ToChar((sr.Read())));
numcharnacoluna += 1;
switch (c)
{
case "|":
{
numcoluna += 1;
numcharnacoluna = 0;
monta_num_linha.Clear();
monta_reg.Clear();
monta_cod_depe.Clear();
monta_indr_insc_munl.Clear();
monta_cnpj_proprio.Clear();
monta_tipo_depe.Clear();
monta_endr_depe.Clear();
monta_cnpj_unif.Clear();
monta_cod_munc.Clear();
monta_ctbl_propria.Clear();
monta_dat_inic_para.Clear();
monta_dat_fim_para.Clear();
break;
}
case "\n":
{
numlinha += 1;
numcharnacoluna = 0;
numcoluna = 1;
break;
}
default:
{
if (numlinha == numerolinha)
{
switch (numcoluna)
{
case 1:
{
monta_num_linha.Append(c);
regi.num_linha = monta_num_linha.ToString();
break;
}
case 2:
{
monta_reg.Append(c);
regi.reg = monta_reg.ToString();
break;
}
case 3:
{
monta_cod_depe.Append(c);
regi.cod_depe = monta_cod_depe.ToString();
break;
}
case 4:
{
monta_indr_insc_munl.Append(c);
regi.indr_insc_munl = monta_indr_insc_munl.ToString();
break;
}
case 5:
{
monta_cnpj_proprio.Append(c);
regi.cnpj_proprio = monta_cnpj_proprio.ToString();
break;
}
case 6:
{
monta_tipo_depe.Append(c);
regi.tipo_depe = monta_tipo_depe.ToString();
break;
}
case 7:
{
monta_endr_depe.Append(c);
regi.endr_depe = monta_endr_depe.ToString();
break;
}
case 8:
{
monta_cnpj_unif.Append(c);
regi.cnpj_unif = monta_cnpj_unif.ToString();
break;
}
case 9:
{
monta_cod_munc.Append(c);
regi.cod_munc = monta_cod_munc.ToString();
break;
}
case 10:
{
monta_ctbl_propria.Append(c);
regi.ctbl_propria = monta_ctbl_propria.ToString();
break;
}
case 11:
{
monta_dat_inic_para.Append(c);
regi.dat_inic_para = monta_dat_inic_para.ToString();
break;
}
case 12:
{
monta_dat_fim_para.Append(c);
regi.dat_fim_para = monta_dat_fim_para.ToString();
break;
}
}
}
break;
}
}
}
return regi;
}
private Registro0400 RetiraZeroDoRegistro(Registro0400 reg)
{
Registro0400 regi = new Registro0400();
regi = reg;
regi.cod_depe = regi.cod_depe.TrimStart('0');
regi.cnpj_proprio = regi.cnpj_proprio.TrimStart('0');
regi.cnpj_unif = regi.cnpj_unif.TrimStart('0');
return regi;
}
public void ListaRegistro(Registro0400 r)
{
Console.WriteLine(r.num_linha + "|" + r.reg + "|" + r.cod_depe + "|" + r.indr_insc_munl + "|" + r.cnpj_proprio + "|" + r.tipo_depe + "|" + r.endr_depe
+ "|" + r.cnpj_unif + "|" + r.cod_munc + "|" + r.ctbl_propria + "|" + r.dat_inic_para + "|" + r.dat_fim_para);
}
}
}
|
C# | UTF-8 | 1,523 | 2.515625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Data.SqlClient;
namespace StopSQLServer
{
public partial class Frm_Main : Form
{
public Frm_Main()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(//创建数据库连接对象
@"server=(local);Pwd=6221131;uid=sa;database=master"))
{
try
{
string strShutdown = "SHUTDOWN WITH NOWAIT";//创建SQL字符串
SqlCommand cmd = new SqlCommand();//创建命令对象
cmd.Connection = con;//设置连接属性
cmd.Connection.Open();//打开数据库连接
cmd.CommandText = strShutdown;//设置将要执行的SQL语句
cmd.ExecuteNonQuery();//执行SQL语句
MessageBox.Show("已成功断开服务");//弹出消息对话框
}
catch(Exception euy)
{
MessageBox.Show(euy.Message);//弹出消息对话框
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();//关闭窗体
}
}
} |
C++ | GB18030 | 575 | 3.1875 | 3 | [] | no_license | //
// Created by һ on 2020/6/23.
// Q14ǰ
//
#include "util.h"
class Solution {
public:
/**
* 1:Ƚ
*/
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) {
return "";
}
string result = strs[0];
for (int i = 1; i < strs.size(); i++) {
int j = 0;
for (;(j < result.size() && j < strs[i].size()) && result[j] == strs[i][j];j++) {
}
result = result.substr(0, j);
}
return result;
}
}; |
Java | UTF-8 | 185 | 1.921875 | 2 | [] | no_license | package miu.edu.ati.ati.controller;
import miu.edu.ati.ati.domain.Country;
import java.util.List;
public interface CountriesController {
public List<Country> getAllCounties();
}
|
Java | UTF-8 | 4,412 | 2.25 | 2 | [] | no_license | package com.example.demo.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.demo.entity.Celebrite;
import com.example.demo.entity.Departement;
import com.example.demo.entity.Lieu;
import com.example.demo.entity.Monument;
import com.example.demo.metier.IMetier;
@Controller
public class ApliController {
@Autowired
private IMetier imetier;
@RequestMapping(value="/")
public String home() {
return "redirect:/acceuil";
}
@RequestMapping("/celebrites")
public String index()
{
return "celebrites"; }
@RequestMapping("/acceuil")
public String index5()
{
return "acceuil"; }
@RequestMapping("/Lieux")
public String index2(Model model)
{
List<Lieu> ListLieux = imetier.getListLieux();
model.addAttribute("ListLieux",ListLieux);
return "Lieux"; }
@RequestMapping("/monuments")
public String index3()
{
return "monuments"; }
@RequestMapping("/departements")
public String index4()
{
return "departements"; }
@RequestMapping("/consultcelebrite")
public String consultercelebrite(Model model,String nomcelebrite)
{
try {
Celebrite c =imetier.getCelebritebyname(nomcelebrite);
Collection<Monument> ListMonuments = c.getMonuments();
model.addAttribute("ListMonuments",ListMonuments);
model.addAttribute("celebrite", c);
}catch(Exception e) {
model.addAttribute("exception", e);
}
return "celebrites"; }
@RequestMapping("/consultmonument")
public String consultermonument(Model model,String nomM)
{
try {
Monument m =imetier.getMonumentbyname(nomM);
model.addAttribute("monument", m);
}catch(Exception e) {
model.addAttribute("exception1", e);
}
return "monuments"; }
@RequestMapping("/consultdepartement")
public String consultercmt(Model model,String codedepartement)
{
try {
Departement d=imetier.getDepartement(codedepartement);
Collection<Lieu> ListLieux = d.getLieux();
Collection<Monument> ListMonuments = imetier.getListMonumentsByDep(codedepartement);
model.addAttribute("ListLieux",ListLieux);
model.addAttribute("ListMonuments",ListMonuments);
model.addAttribute("departement", d);
}catch(Exception e) {
model.addAttribute("exception", e);
}
return "departements"; }
@RequestMapping(value="/ajouterLieu",method=RequestMethod.POST)
public String ajoutlieu(Model model,String codeInsee, String nomCom,double longitude,double latitude, String dep)
{
try {
Departement d=imetier.getDepartement(dep);
if(d != null) {
Lieu l=new Lieu(codeInsee,nomCom,longitude,latitude,d);
imetier.addLieu(l);}
else {
String a = "erreur";
model.addAttribute("erreur", a);
}
}catch(Exception e) {
model.addAttribute("erreur", e);
}
return "redirect:/Lieux"; }
@RequestMapping("/suprimerLieu")
public String suprimerlieu(String codeLieu)
{
imetier.deleteLieu(codeLieu);
return "redirect:/Lieux";}
@RequestMapping("/addCelebritetomonument")
public String addCetoMo(Model model,Integer numCelebrite, String codeM)
{
try {
imetier.addCelebriteToMonument(numCelebrite, codeM);
}catch(Exception e) {
model.addAttribute("exception3", e);
}
return "monuments";}
@RequestMapping("/calculdistance")
public String consulterdistance(Model model,String codeM1,String codeM2)
{
try {
double distance = imetier.getDistanceBetweenMonuments(codeM1, codeM2);
model.addAttribute("distance", distance);
}catch(Exception e) {
model.addAttribute("exception2", e);
}
return "monuments"; }
@RequestMapping(value="/403")
public String accessDenied() {
return "403";
}
@RequestMapping(value="/modifier")
public String modifierlieu(String codeInsee,Model model) {
Lieu Lieu = imetier.getLieu(codeInsee);
model.addAttribute("Lieu", Lieu);
return "modifierlieu"; }
}
|
C++ | UTF-8 | 1,171 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cstdlib>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <string>
#include <cmath>
using namespace std;
/* 矩阵快速幂 */
#define INF 0x3f3f3f3f
#define M 10000
struct Mat {
long long m[2][2];
Mat() {
memset(m, 0, sizeof(m));
}
};
Mat multi (Mat a, Mat b) {
Mat c;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
c.m[i][j] += (a.m[i][k] * b.m[k][j]) % M;
}
}
}
return c;
}
Mat zxc (Mat a, long long b) {
Mat c;
c.m[0][0] = c.m[1][1] = 1;
while (b) {
if (b & 1)
c = multi(c, a);
a = multi(a, a);
b >>= 1;
}
return c;
}
int main () {
long long n;
while (cin >> n && n != -1) {
Mat one;
if (n == 0) {
cout << 0 << endl;
continue;
}
else if (n == 1) {
cout << 1 << endl;
continue;
}
one.m[0][0] = one.m[1][0] = one.m[0][1] = 1;
one = zxc(one, n-1);
cout << one.m[0][0] % M << endl;;
}
} |
C | GB18030 | 698 | 2.890625 | 3 | [] | no_license | /*
* num: 201510050407
* puepose: Ӽ
* Create: 20161231
* Author: Albert
*/
#include<stdio.h>
#include<math.h>
main()
{
double a,s,h1,h2,h3,h4,c,p1,p2,l,f;
double H1,XH,JH,Hp,lp,Hp1,lp1,Js,jg,n,n1,sum;
scanf("%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf",&a,&s,&h1,&h2,&h3,&h4,&c,&p1,&p2,&l,&f);
H1=h3+h4; XH=1/c*l/1000; JH=H1+XH; Hp=p1+(1-p1)*(H1-h2)/3048; lp=p1+(1-p1)*(H1-h1);
Hp1=p2+(1-p2)*(H1-h2); lp1=p2+(1-p2)*(H1-h1); Js=10*f*(1-p1)*1/c/1000; jg=10*f*(1-p2)*1/c/1000;
n=1000*a/jg; n1=(int)(s*1000/Js+1); sum=n1*n;
printf("%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",H1,XH,JH,Hp,lp,Hp1,lp1,Js,jg,n,n1,sum);
}
|
C++ | UTF-8 | 2,755 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | /* -*- coding: utf-8 -*-
*
* OneEuroFilter.cc -
*
* Author: Nicolas Roussel (nicolas.roussel@inria.fr)
*
*/
#include <libgametrak/utils/OneEuroFilter.h>
namespace gametrak {
void LowPassFilter::setAlpha(double alpha) {
if (alpha<=0.0 || alpha>1.0)
throw std::range_error("alpha should be in (0.0., 1.0]") ;
a = alpha ;
}
LowPassFilter::LowPassFilter(double alpha, double initval) {
y = s = initval ;
setAlpha(alpha) ;
initialized = false ;
}
double LowPassFilter::filter(double value) {
double result ;
if (initialized)
result = a*value + (1.0-a)*s ;
else {
result = value ;
initialized = true ;
}
y = value ;
s = result ;
return result ;
}
double LowPassFilter::filterWithAlpha(double value, double alpha) {
setAlpha(alpha) ;
return filter(value) ;
}
bool LowPassFilter::hasLastRawValue(void) {
return initialized ;
}
double LowPassFilter::lastRawValue(void) {
return y ;
}
// -----------------------------------------------------------------
double OneEuroFilter::alpha(double cutoff) {
double te = 1.0 / freq ;
double tau = 1.0 / (2*M_PI*cutoff) ;
return 1.0 / (1.0 + tau/te) ;
}
void OneEuroFilter::setFrequency(double f) {
if (f<=0) throw std::range_error("freq should be >0") ;
freq = f ;
}
void OneEuroFilter::setMinCutoff(double mc) {
if (mc<=0) throw std::range_error("mincutoff should be >0") ;
mincutoff = mc ;
}
void OneEuroFilter::setBeta(double b) {
beta_ = b ;
}
void OneEuroFilter::setDerivateCutoff(double dc) {
if (dc<=0) throw std::range_error("dcutoff should be >0") ;
dcutoff = dc ;
}
OneEuroFilter::OneEuroFilter(double freq,
double mincutoff, double beta_, double dcutoff) {
setFrequency(freq) ;
setMinCutoff(mincutoff) ;
setBeta(beta_) ;
setDerivateCutoff(dcutoff) ;
x = new LowPassFilter(alpha(mincutoff)) ;
dx = new LowPassFilter(alpha(dcutoff)) ;
lasttime = UndefinedTime ;
}
double OneEuroFilter::filter(double value, double timestamp) {
// update the sampling frequency based on timestamps
if (lasttime!=UndefinedTime && timestamp!=UndefinedTime)
freq = 1.0 / (timestamp-lasttime) ;
lasttime = timestamp ;
// estimate the current variation per second
double dvalue = x->hasLastRawValue() ? (value - x->lastRawValue())*freq : 0.0 ; // FIXME: 0.0 or value?
double edvalue = dx->filterWithAlpha(dvalue, alpha(dcutoff)) ;
// use it to update the cutoff frequency
double cutoff = mincutoff + beta_*fabs(edvalue) ;
// filter the given value
return x->filterWithAlpha(value, alpha(cutoff)) ;
}
OneEuroFilter::~OneEuroFilter(void) {
delete x ;
delete dx ;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.