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 |
|---|---|---|---|---|---|---|---|
Swift | UTF-8 | 552 | 2.703125 | 3 | [] | no_license | import Foundation
extension Smoke {
public struct Craving: Codable {
public let reason: Reason?
public let trigger: Trigger
public let date: Date
public init(_ reason: Reason?, _ trigger: Trigger) {
self.reason = reason
self.trigger = trigger
date = .init()
}
init(_ trigger: Trigger, _ reason: Reason?, _ date: Date = .init()) {
self.trigger = trigger
self.reason = reason
self.date = date
}
}
}
|
C++ | UTF-8 | 9,236 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "WilcoxonTest.h"
WilcoxonTest::WilcoxonTest(float * _data, int _dataXsize, int _dataYsize, string _testIndexes, string _controlIndexes)
{
data = _data;
dataXsize = _dataXsize;
dataYsize = _dataYsize;
testIndexes = parseIntString(_testIndexes);
controlIndexes = parseIntString(_controlIndexes);
if(testIndexes->size() != controlIndexes->size()){
cout << "Control and Test indexes are not the same size!" << endl;
cout << "This program implements paired Wilcoxon test, so please use data groups with the same size." << endl;
throw;
}
readApproximatePtable();
}
WilcoxonTest::WilcoxonTest(float * _data, int _dataXsize, int _dataYsize, vector<int> * _testIndexes, vector<int> * _controlIndexes)
{
data = _data;
dataXsize = _dataXsize;
dataYsize = _dataYsize;
testIndexes = _testIndexes;
controlIndexes = _controlIndexes;
if(testIndexes->size() != controlIndexes->size()){
cout << "Control and Test indexes are not the same size!" << endl;
cout << "This program implements paired Wilcoxon test, so please use data groups with the same size." << endl;
throw;
}
readApproximatePtable();
}
vector<double> * WilcoxonTest::test()
{
pValues = new vector<double>();
int numberOfTests = testIndexes->size();
for(int y = 0; y < numberOfTests; y++)
{
vector<float> * absoluteValues = new vector<float>();
vector<float> * signs = new vector<float>;
float w = calculateWValue(y, absoluteValues, signs);
int numberOfZeroes = getNumberOfZeroes(absoluteValues);
pValues->push_back(calculatePValue(w, numberOfZeroes));
}
return pValues;
}
vector<int> * WilcoxonTest::parseIntString(string input)
{
vector<int> * intVector = new vector<int>();
vector<string> * intStrings = splitLine(input, ',');
for(unsigned int i = 0; i < intStrings->size(); i++){
intVector->push_back(atoi(intStrings->at(i).c_str()));
}
return intVector;
}
void WilcoxonTest::readApproximatePtable()
{
string fileLocation = "/usr/lib/wilcoxonTest/approximateTable500.txt";
ifstream listFile(fileLocation.c_str());
if (!listFile.is_open())
{
cerr << "P values table file does not exist at " << fileLocation << endl;
throw;
}
approximatePTable = new std::vector<std::vector<approximatePosition> * >();
string sLine = "";
while (!listFile.eof())
{
getline(listFile, sLine);
if(sLine.compare("") != 0)
{
approximatePTable->push_back(getPositions(sLine));
}
}
listFile.close();
}
void WilcoxonTest::trim(string& str)
{
string::size_type pos = str.find_last_not_of(' ');
if(pos != string::npos) {
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
}
std::vector<approximatePosition> * WilcoxonTest::getPositions(string positionsLine)
{
std::vector<approximatePosition> * positions = new std::vector<approximatePosition>();
string trimmed_input = positionsLine.substr(1, positionsLine.length() - 1);
std::vector<string> * positionsStrings = splitLine(trimmed_input, ']');
for(unsigned int i = 0; i < positionsStrings->size(); i++){
string rawPosistionString = positionsStrings->at(i);
if(rawPosistionString.compare("") == 0)
{
break;
}
int beginning = rawPosistionString.find('[');
string warPositionStringFromBeginning = rawPosistionString.substr(beginning);
int middle = warPositionStringFromBeginning.find(',');
string x_str = warPositionStringFromBeginning.substr(1, middle - 1);
string y_str = warPositionStringFromBeginning.substr(middle + 1, warPositionStringFromBeginning.length() - 1);
trim(y_str);
trim(x_str);
approximatePosition pos;
pos.x = atoi(x_str.c_str());
pos.y = atof(y_str.c_str());
positions->push_back(pos);
}
return positions;
}
std::vector<string> * WilcoxonTest::splitLine(string inputString, char lineSplit)
{
std::istringstream stringStream ( inputString );
std::vector<string> * datacells = new std::vector<string>();
while (!stringStream.eof())
{
string newString;
getline( stringStream, newString, lineSplit);
datacells->push_back(newString);
}
return datacells;
}
float WilcoxonTest::calculateWValue(int yIndex, vector<float> * absoluteValues, vector<float> * signs)
{
for (int i = 0; i < dataXsize; i++)
{
int testIndex = testIndexes->at(yIndex);
int controlIndex = controlIndexes->at(yIndex);
float x1 = data[(testIndex * dataXsize) + i];
float x2 = data[(controlIndex * dataXsize) + i];
float value = x2-x1;
absoluteValues->push_back(abs(value));
signs->push_back(getSign(value));
}
//Sort the list
quicksort(0, dataXsize-1, absoluteValues, signs);
double * ranks = rankThePairs(yIndex, absoluteValues);
float w = 0;
for (int i = 0; i < dataXsize; i++)
{
if (absoluteValues->at(i) != 0)
{
w += ranks[i] * signs->at(i);
}
}
delete ranks;
return abs(w);
}
double WilcoxonTest::calculatePValue(float w, int numberOfZeroes)
{
int Nr = 0;
for (int x = numberOfZeroes; x < dataXsize; x++)
{
Nr++;
}
float z = calculateZValue(w, Nr);
if(Nr > 500){
if(z < 0)
{
return gsl_cdf_gaussian_P(z, 1);
}
return gsl_cdf_gaussian_Q(z, 1);
}
else
{
return getApproximatePValue(w, z);
}
}
float WilcoxonTest::calculateZValue(float w, int Nr)
{
float sigma = sqrt((Nr * (Nr+1) * (2*Nr + 1)) / 6);
return (w - 0.5) / sigma;
}
double WilcoxonTest::getApproximatePValue(float w, float z)
{
std::vector<approximatePosition> * approximatePositions = approximatePTable->at(dataXsize);
approximatePosition beginningPos = approximatePositions->at(0);
for (unsigned int i = 1; i < approximatePositions->size(); i++)
{
approximatePosition endPos = approximatePositions->at(i);
if (w >= beginningPos.x && w <= endPos.x){
return approximateP(w, z, beginningPos, endPos);
}
beginningPos = endPos;
}
return 0;
}
double WilcoxonTest::approximateP(float w, float z, approximatePosition beginningPos, approximatePosition endPos)
{
double relativeValue;
if(w == beginningPos.x)
{
relativeValue = beginningPos.y;
}
else if (w == endPos.x)
{
relativeValue = endPos.y;
}
else
{
relativeValue = beginningPos.y + (endPos.y - beginningPos.y) * (abs(w) - beginningPos.x) / (endPos.x - beginningPos.x);
}
if (z < 0) {
return relativeValue * gsl_cdf_gaussian_P(z, 1);
}
return relativeValue * gsl_cdf_gaussian_Q(z, 1);
}
double * WilcoxonTest::rankThePairs(int yIndex, vector<float> * absoluteValues)
{
double * ranks = new double[dataXsize];
int i = 0;
while (i < dataXsize)
{
int j = i + 1;
while (j < dataXsize)
{
if(absoluteValues->at(i) != absoluteValues->at(j))
{
break;
}
j++;
}
for(int k = i; k <= j-1; k++)
{
ranks[k] = 1 + (double)(i + j-1)/(double)2;
}
i = j;
}
return ranks;
}
int WilcoxonTest::getSign(float value)
{
if(value > 0)
{
return 1;
}
else if(value < 0)
{
return -1;
}
return 0;
}
int WilcoxonTest::getNumberOfZeroes(vector<float> * absoluteValues)
{
int numberOfZeroes = 0;
for (int i = 0; i < dataXsize; i++)
{
if(absoluteValues->at(i) == 0)
{
numberOfZeroes++;
}
}
return numberOfZeroes;
}
void WilcoxonTest::quicksort(int m, int n, vector<float> * absoluteValues, vector<float> * signs)
{
float key;
int i,j,k;
if( m < n)
{
k = choose_pivot(m,n);
swap(&absoluteValues->at(m), &absoluteValues->at(k));
swap(&signs->at(m), &signs->at(k));
key = absoluteValues->at(m);
i = m + 1;
j = n;
while(i <= j)
{
while((i <= n) && ( absoluteValues->at(i) <= key))
{
i++;
}
while((j >= m) && ( absoluteValues->at(j) > key))
{
j--;
}
if( i < j)
{
swap(&absoluteValues->at(i), &absoluteValues->at(j));
swap(&signs->at(i), &signs->at(j));
}
}
// swap two elements
swap(&absoluteValues->at(m), &absoluteValues->at(j));
swap(&signs->at(m), &signs->at(j));
// recursively sort the lesser list
quicksort(m,j - 1, absoluteValues, signs);
quicksort(j + 1, n, absoluteValues, signs);
}
}
void WilcoxonTest::swap(float *x,float *y)
{
float temp;
temp = *x;
*x = *y;
*y = temp;
}
int WilcoxonTest::choose_pivot(int i,int j )
{
return((i+j) /2);
}
|
JavaScript | UTF-8 | 1,715 | 2.609375 | 3 | [] | no_license | var express = require('express');
const os = require('os');
var app = express();
var path = require('path');
const nunjucks = require('nunjucks');
nunjucks.configure('views', {
autoescape: true,
express: app
});
let host = '192.168.1.69'; // Choose a different loopback address
let port = '9373'; // Last digits of your NetID
let myName = 'Hien Vo';
//
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
//
let networkInterfaces = os.networkInterfaces();
str = JSON.stringify(networkInterfaces);
let ipv4 = Object.entries(networkInterfaces)[0][1][4].address;
let mac = Object.entries(networkInterfaces)[0][1][4].mac;
today = mm + '/' + dd + '/' + yyyy;
dt = "Date and Time";
style1 = "main{background-color: salmon;}body{border-style: solid;}h1 {color: blue;}";
let data = {head1: dt, name: myName, info:today, style: style1}
app.get('/date', (req, res) =>{
res.render('8-1temp.njk', data);
//res.send('It is ' + today + ', Hien Vo');
});
dt = "Server and Mac address";
addresses = "This computers active external interface has IPv4 address: " + ipv4 + ", and Mac address is " + mac;
style2 = "main{background-color: lightblue;}body{border-style: solid;}h1 {color: Crimson;}";
let data2 = {head1: dt, name: myName, info: addresses, style: style2}
app.get('/address', (req,res) =>{
//res.send('This computers active external interface has IPv4 address: ' + ipv4 + ', and Mac address is ' + mac + ', Hien Vo');
res.render('8-1temp.njk', data2);
});
app.listen(9373, function(){
console.log('app listening to port 9373');
});
|
C++ | UTF-8 | 2,368 | 2.53125 | 3 | [
"AFL-2.0"
] | permissive | //
// Created by calabash_boy on 18-10-6.
//
//求树上长度小于等于k的有向路径数
#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAX = 1e4+100;
const int INF = 0x3f3f3f3f;
int first [MAX*2]; int des[MAX*2];
int len[MAX*2]; int nxt[MAX*2];
int n,k,tot; int a[MAX]; int sum[MAX];
int dp[MAX]; int dis[MAX]; int num,ans;
bool vis[MAX]; int Sum,Min,Minid;
void init(){
memset(first,0,sizeof first);
tot =0; ans =0;
memset(vis,0,sizeof vis);
}
inline void add(int x,int y,int z){
tot++;
des[tot]= y; len[tot] =z;
nxt[tot] = first[x]; first[x] = tot;
}
void input(){
for (int i=1;i<n;i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w); add(v,u,w);
}
}
void dfs1(int node,int father){
sum[node] = 1; dp[node] = 0;
for (int t = first[node];t;t = nxt[t]){
int v = des[t];
if (v == father||vis[v]){
continue;
}
dfs1(v,node);
sum[node] += sum[v];
dp[node] = max(dp[node],sum[v]);
}
}
void dfs2(int node,int father){
int temp = max(dp[node],Sum-sum[node]);
if (temp<Min){
Min = temp; Minid = node;
}
for (int t = first[node];t;t = nxt[t]){
int v = des[t];
if (v==father||vis[v]){ continue; }
dfs2(v,node);
}
}
int getRoot(int u){
dfs1(u,0); Sum = sum[u];
Min = INF; Minid = -1;
dfs2(u,0);
return Minid;
}
void getDist(int node,int father,int dist){
dis[num++] = dist;
for (int t = first[node];t;t = nxt[t]){
int v =des[t];
if (v == father||vis[v]){ continue; }
getDist(v,node,dist+len[t]);
}
}
int calc (int u,int val){
num=0; int res =0;
getDist(u,0,0);
sort(dis,dis+num);
int i=0;int j=num-1;
while (i<j){
if (dis[i]+dis[j]+2*val<=k){
res+=j-i;
i++;
}else{ j--; }
}
return res;
}
void solve(int u){
int root = getRoot(u);
ans +=calc(root,0); vis[root] = true;
for (int t = first[root];t;t = nxt[t]){
int v = des[t];
if (vis[v]){
continue;
}
ans-=calc(v,len[t]);
solve(v);
}
}
int main(){
while (scanf("%d%d",&n,&k)!=EOF&&n&&k){
init();
input();
solve(1);
printf("%d\n",ans);
}
return 0;
} |
Python | UTF-8 | 532 | 3.78125 | 4 | [] | no_license | def sort_artists(tp):
result =[]
value =[]
for s in tp:
for item in s:
try:
if item.isnumeric:
result.append(item)
except:
value.append(item)
result.sort()
value.sort(reverse=True)
final = (result,value)
return final
#(['Elvis Presley', 'Michael Jackson', 'The Beatles'], [270.8, 211.5, 183.9])
artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]
print(sort_artists(artists))
|
Java | UTF-8 | 2,040 | 2.578125 | 3 | [] | no_license | package com.examples.com.aspect;
import com.examples.com.EntityNotFoundException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAspect {
@After("execution(* insert(..))")
public void beforeInserting(final JoinPoint joinPoint) {
System.out.println("Entity is being inserted for: " + joinPoint.getSignature());
}
@After("execution(* delete(..))")
public void afterDeleting(final JoinPoint joinPoint) {
final Object[] arguments = joinPoint.getArgs();
System.out.println("Entity is being deleted: " + arguments[0]);
}
@AfterThrowing(
pointcut = "execution(* update(..))",
throwing = "ex")
public void getAnyException(final EntityNotFoundException ex) {
System.out.println("Some problem in the system! Will get back soon!");
}
@Around("execution(* update(..))")
public void handleUpdate(final ProceedingJoinPoint joinPoint) {
try {
joinPoint.proceed();
} catch (final Throwable throwable) {
System.out.println("Suppressing the exception! Update cannot be handled this time!");
}
}
@Around("execution(* *(int))")
public Object handleCalculation(final ProceedingJoinPoint joinPoint) {
try {
final Object[] arguments = joinPoint.getArgs();
final int val = (Integer) arguments[0];
if (val < 0) {
System.out.println("Cannot multiply negative input!");
} else {
return joinPoint.proceed();
}
} catch (final Throwable throwable) {
System.out.println("Suppressing the exception! Update cannot be handled this time!");
}
return Integer.MIN_VALUE;
}
}
|
Java | UTF-8 | 1,920 | 2.375 | 2 | [] | no_license | package com.hyphenate.easeui.domain;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author lishuqi
* @date 2018/3/26
*/
public class AddMedicationTemplate implements Parcelable {
private String name;
private int num;
private String remark;
private int medicine_id;
public String price;
public int getMedicine_id() {
return medicine_id;
}
public void setMedicine_id(int medicine_id) {
this.medicine_id = medicine_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMum() {
return num;
}
public void setMum(int num) {
this.num = num;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeInt(this.num);
dest.writeString(this.remark);
dest.writeInt(this.medicine_id);
dest.writeString(this.price);
}
public AddMedicationTemplate() {
}
protected AddMedicationTemplate(Parcel in) {
this.name = in.readString();
this.num = in.readInt();
this.remark = in.readString();
this.medicine_id = in.readInt();
this.price = in.readString();
}
public static final Creator<AddMedicationTemplate> CREATOR = new Creator<AddMedicationTemplate>() {
@Override
public AddMedicationTemplate createFromParcel(Parcel source) {
return new AddMedicationTemplate(source);
}
@Override
public AddMedicationTemplate[] newArray(int size) {
return new AddMedicationTemplate[size];
}
};
}
|
JavaScript | UTF-8 | 2,311 | 2.53125 | 3 | [] | no_license | import React from 'react';
import PropTypes from 'prop-types';
import Location from './Location';
export default function Locations({ flyerEvents, isFullTourListing, isTourAbbrev }) {
let eventLocations = flyerEvents.map(event => {
let eventLocation = {}
if (isFullTourListing) {
for (const [key, val] of Object.entries(event)) {
if (["event_date", "city_name", "region_name", "country_name", "venue_name", "cancelled"].includes(key) && Boolean(val)) {
eventLocation[key] = val
}
}
} else {
for (const [key, val] of Object.entries(event)) {
if (["city_name", "region_name", "country_name", "venue_name", "cancelled"].includes(key) && Boolean(val)) {
eventLocation[key] = val
}
}
}
return eventLocation
})
switch (true) {
case isFullTourListing:
return (
<div className="Flyer--locations">
{eventLocations.map((location, i) => {
if (location.event_date) {
return <Location
key={i}
eventLocation={location}
hasTourEventDate={true}
isCancelled={location.cancelled ? true : false}/>
}
return <Location key={i} eventLocation={location} />
})}
</div>
);
case isTourAbbrev:
return (
<div className="Flyer--locations">
<Location isTourAbbrev={true} />
</div>
);
case eventLocations.length > 0 && !isTourAbbrev:
return (
<div className="Flyer--locations">
<Location eventLocation={eventLocations[0]}/>
</div>
);
default:
return null;
}
}
Locations.defaultProps = {
flyerEvents: [],
isFullTourListing: false,
isTourAbbrev: false
}
Locations.propTypes = {
flyerEvents: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
flyer_id: PropTypes.string,
event_date: PropTypes.oneOfType([
PropTypes.instanceOf(Date),
PropTypes.string
]),
city_name: PropTypes.string,
region_name: PropTypes.string,
country_name: PropTypes.string,
venue_name: PropTypes.string,
city_id: PropTypes.number,
cancelled: PropTypes.bool
})),
isFullTourListing: PropTypes.bool,
isTourAbbrev: PropTypes.bool
}
|
Swift | UTF-8 | 1,347 | 3.234375 | 3 | [
"MIT"
] | permissive | import Foundation
public final class Votable: NSObject {
public var name = ""
public var meta = ""
public var id: Int64 = 0
}
extension Votable: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
meta = try container.decode(String.self, forKey: .meta)
id = try container.decode(Int64.self, forKey: .id)
}
private enum CodingKeys: String, CodingKey {
case name
case meta
case id
}
}
extension Votable: NSSecureCoding {
public static var supportsSecureCoding: Bool {
return true
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: CodingKeys.name.rawValue)
aCoder.encode(meta, forKey: CodingKeys.meta.rawValue)
aCoder.encode(id, forKey: CodingKeys.id.rawValue)
}
public convenience init?(coder aDecoder: NSCoder) {
self.init()
name = aDecoder.decodeObject(of: NSString.self, forKey: CodingKeys.name.rawValue)! as String
meta = aDecoder.decodeObject(of: NSString.self, forKey: CodingKeys.meta.rawValue)! as String
id = aDecoder.decodeInt64(forKey: CodingKeys.id.rawValue)
}
}
|
C++ | UTF-8 | 1,934 | 2.734375 | 3 | [
"BSD-3-Clause",
"MIT",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | #ifndef DUNJUN_GRAPHICS_SHADERPROGRAM_HPP
#define DUNJUN_GRAPHICS_SHADERPROGRAM_HPP
#include <Dunjun/Math/Types.hpp>
#include <Dunjun/Graphics/Transform.hpp>
#include <Dunjun/Graphics/Color.hpp>
#include <Dunjun/Core/ContainerTypes.hpp>
#include <Dunjun/Core/String.hpp>
namespace Dunjun
{
enum class ShaderType
{
Vertex,
Fragment,
};
class ShaderProgram
{
public:
u32 handle;
b32 isLinked;
String errorLog;
ShaderProgram();
~ShaderProgram();
b32 attachShaderFromFile(ShaderType type, const String& filename);
b32 attachShaderFromMemory(ShaderType type, const String& filename);
void use() const;
b32 isInUse() const;
void stopUsing() const;
void checkInUse() const;
b32 link();
void bindAttribLocation(s32 location, const String& name);
s32 getAttribLocation(const String& name) const;
s32 getUniformLocation(const String& name) const;
void setUniform(const String& name, f32 x) const;
void setUniform(const String& name, f32 x, f32 y) const;
void setUniform(const String& name, f32 x, f32 y, f32 z) const;
void setUniform(const String& name, f32 x, f32 y, f32 z, f32 w) const;
void setUniform(const String& name, u32 x) const;
void setUniform(const String& name, s32 x) const;
void setUniform(const String& name, bool x) const;
void setUniform(const String& name, const Vector2& v) const;
void setUniform(const String& name, const Vector3& v) const;
void setUniform(const String& name, const Vector4& v) const;
void setUniform(const String& name, const Matrix4& m) const;
void setUniform(const String& name, const Quaternion& t) const;
void setUniform(const String& name, const Transform& t) const;
void setUniform(const String& name, const Color& c) const;
private:
mutable HashMap<s32> m_attribLocations;
mutable HashMap<s32> m_uniformLocations;
ShaderProgram(const ShaderProgram&) = delete;
ShaderProgram& operator=(const ShaderProgram&) = delete;
};
} // namespace Dunjun
#endif
|
Markdown | UTF-8 | 1,713 | 2.96875 | 3 | [
"Apache-2.0"
] | permissive | ### Activities
To track admin activities you need to define it on seed.yml on `permissions` key
- `role` should be in a range of existing: `admin`, `superadmin`, `support`, `techical`, `accountant`
- `verb` should be `post`, `get`, `put`, `delete`
- `path` - endpoint which should be checked, should be started with `api/v2/#{component}` as prefix
- `action` should be `audit`
```
For example
permissions:
- { role: 'admin', verb: 'post', path: api/v2/admin, action: audit }
```
Here you can see a list of possible fields for activity:
| Field | Type | Description |
|:-----------|:--------:|:-----------:|
| user_id | bigint | ID of user who creates activity |
| target_uid | string | User UID for whom activity was created (admin remove OTP for user, target_uid will be uid of user for which admin removed OTP|
| category | string | `admin` (admin activities), `user` (user activities)|
| user_ip | string | IP address |
| user_agent | string | User Agent such as `Mozilla/5.0`|
| topic | string | Defined topic (`session`, `adjustments`) or `general` by default|
| action | string | API action: `POST => 'create'`, `PUT => 'update'`, `GET => 'read'`, `DELETE => 'delete'`, `PATCH => 'update'` or `system` if there is no match of HTTP method|
| result | string | Status of API response: `succeed`, `failed`, `denied`|
| data | text | Parameters which was sent to specific API endpoint|
| created_at | datetime | Time of activity creation|
##### Useful commands
If you want to delete old activities you can run next command
Be sure that your parameters has valid date string, such as `YYYY-mm-dd` !
```
bundle exec rake activities:delete[from,to]
```
|
Java | UTF-8 | 2,487 | 2.125 | 2 | [] | no_license | package kj.pos.entity.product;
import kj.pos.entity.BaseEntity;
import org.apache.ibatis.type.Alias;
import java.util.Date;
import java.io.Serializable;
@Alias("ProductSku")
public class ProductSku extends BaseEntity{
//创建字段
private Long id;//skuId
private Long pid;//商品信息表(product id)
private String productCode;//
private String productName;
private String code;//规格代码
private String name;//规格名称
private String gbCode;//国标码
private Double untPrice;//标准售价
private Double costPrice;//成本价
private Double usePrice;//代理价
private Boolean del;//是否删除 0 未删除 1删除
private String memo;//备注
//创建getter和setter方法
public Long getId(){
return this.id;
}
public void setId(Long id){
this.id = id;
}
public Long getPid(){
return this.pid;
}
public void setPid(Long pid){
this.pid = pid;
}
public String getProductCode(){
return this.productCode;
}
public void setProductCode(String productCode){
this.productCode = productCode;
}
public String getCode(){
return this.code;
}
public void setCode(String code){
this.code = code;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getGbCode(){
return this.gbCode;
}
public void setGbCode(String gbCode){
this.gbCode = gbCode;
}
public Double getUntPrice(){
return this.untPrice;
}
public void setUntPrice(Double untPrice){
this.untPrice = untPrice;
}
public Double getCostPrice(){
return this.costPrice;
}
public void setCostPrice(Double costPrice){
this.costPrice = costPrice;
}
public Double getUsePrice(){
return this.usePrice;
}
public void setUsePrice(Double usePrice){
this.usePrice = usePrice;
}
public Boolean getDel(){
return this.del;
}
public void setDel(Boolean del){
this.del = del;
}
public String getMemo(){
return this.memo;
}
public void setMemo(String memo){
this.memo = memo;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
} |
C | UTF-8 | 684 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
int i;
typedef struct s{
char name[20];
char lastName[20];
unsigned int id;
unsigned char cal;
} Student;
int main(){
char *fileName = "studentDb.data";
int fd = open(filename, 0_RDWR);
int id;
Student *pAvanzada = (Student *)mmap(
NULL,
5 * sizeof(Student),
PROT_READ | PROT_WRITE,
MAP_FILE | MAP_PRIVATE,
fd,
0
);
for(i =0; i<4; i++) {
printf("Provide id, new name \n");
scanf("%d %s", &id, name);
strcpy(pAvanzada[1].name, "Pedro");
msync(pAvanzada,5 * sizeof(Student), MS_SYNC);
}
munmap(pAvanzada,5 * sizeof(Student));
close(fd);
return 0;
} |
Java | UTF-8 | 1,134 | 2.609375 | 3 | [] | no_license | package day36_Agustos_09_2021_dersi_inheritance01;
public class Isci extends Muhasebe{
public static void main(String[] args) {
Isci i1=new Isci();
i1.isim="Cumali";
i1.soyisim="Korkmaz";
i1.adres="falan fesmekan";
i1.saatUcreti=10;
i1.statü="chief";
i1.tel="12345";
i1.id=i1.idAta();
i1.maas=i1.maasHesapla();
System.out.println("isim : "+i1.isim + "\n" + "soyadi : "+i1.soyisim+ "\n" +"tel no : "+i1.tel+ "\n" +"adresi : " + i1.adres + "\n" + "saat ucretiniz : "+i1.saatUcreti + " tl"+ "\n" +"id numaraniz : "+i1.id + "\n" + "bu ay ki maasiniz : "+i1.maas+" tl‘dir.");
Isci i2=new Isci();
i2.isim="Aydin";
i2.soyisim="Tokuslu";
i2.adres="falan2 fesmekan2";
i2.saatUcreti=15;
i2.statü="head of department";
i2.tel="23456";
i2.id=i2.idAta();
i2.maas=i2.maasHesapla();
System.out.println("");
System.out.println("isim : "+i2.isim + "\n" + "soyadi : "+i2.soyisim+ "\n" +"tel no : "+i2.tel+ "\n" +"adresi : " + i2.adres + "\n" + "saat ucretiniz : "+i2.saatUcreti + " tl"+ "\n" +"id numaraniz : "+i2.id + "\n" + "bu ay ki maasiniz : "+i2.maas+" tl‘dir.");
}
}
|
TypeScript | UTF-8 | 2,511 | 3.140625 | 3 | [
"MIT"
] | permissive | import { ts } from 'ts-morph'
import { Expression, tabs, generateTempBindingName } from ".";
let operatorsMap = {
'==': 'equal',
'===': 'equal',
'!=': '/=',
'!==': '/=',
'!': 'not',
'&&': 'and',
'||': 'or'
} as { [index: string]: string };
let assignOperators = [
'+=',
'-=',
'*=',
'/='
]
export class BinaryExpression extends Expression {
type: string = 'BinaryExpression'
operator: string;
constructor(
op: string,
readonly left: Expression,
readonly right: Expression
) {
super();
if (op in operatorsMap) {
this.operator = operatorsMap[op];
} else {
this.operator = op;
}
}
emitQuoted(indent: number) {
return this.emit(indent, true)
}
emit(indent: number, quoted = false) {
if (assignOperators.indexOf(this.operator) !== -1) {
return `${tabs(indent)}(setf ${this.left.emit(0)} (${this.operator[0]} ${this.left.emit(0)} ${this.right.emit(0)}))`
} else {
let operatorFunc = this.operator
if (this.operator === "+") {
operatorFunc = "ts/+"
}
const unquote = quoted ? ',' : ''
return `${tabs(indent)}${unquote}(${operatorFunc} ${this.left.emit(0)} ${this.right.emit(0)})`
}
}
}
abstract class UnaryExpression extends Expression {
constructor(readonly operator: string,
readonly operand: Expression) {
super()
}
}
export class UnaryPrefixExpression extends UnaryExpression {
type: string = 'UnaryPrefixExpression'
constructor(readonly op: string, operand: Expression) {
super(operatorsMap[op], operand)
}
emitQuoted(indent: number) {
return this.emit(indent, true)
}
emit(indent: number, quoted = false) {
if (this.op === '-') {
return `${tabs(indent)}-${this.operand.emit(0)}`
}
const unquote = quoted ? ',' : ''
return `${tabs(indent)}${unquote}(${this.operator} ${this.operand.emit(0)})`
}
}
const unaryPostFixOps: any = {
[0]: "1+",
[1]: "1-"
}
export enum UnaryPostfixOp {
PlusPlus = 0,
MinusMinus = 1
}
export class UnaryPostfixExpression extends UnaryExpression {
type: string = "UnaryPostfixExpression"
constructor(op: UnaryPostfixOp, operand: Expression) {
super(unaryPostFixOps[op], operand)
}
emitQuoted(indent: number) {
return this.emit(indent, true)
}
emit(indent: number, quoted = false) {
const unquote = quoted ? ',' : ''
const operandStr = this.operand.emit(0)
const tempBinding = generateTempBindingName()
return `${tabs(indent)}${unquote}(let ((${tempBinding} ${operandStr})) (setf ${operandStr} (${this.operator} ${operandStr})) ${tempBinding})`
}
}
|
Python | UTF-8 | 1,945 | 3.578125 | 4 | [] | no_license | ###############################################
# Author: Rafael Passos Guimarães
# E-mail: rapassos@gmail.com
# Date: 10/Jul/2020
###############################################
conjunto = {1, 2, 3, 4, 4, 2, 4}
print(type(conjunto))
print(conjunto)
conjunto.add(5)
print(conjunto)
conjunto.discard(2)
print(conjunto)
conjunto1 = {1, 2, 3, 4, 5}
conjunto2 = {5, 6, 7, 8}
print('Conjunto 1: {}'.format(conjunto1))
print('Conjunto 2: {}'.format(conjunto2))
conjunto_uniao = conjunto1.union(conjunto2)
print('União: {}'.format(conjunto_uniao))
conjunto_interseccao = conjunto1.intersection(conjunto2)
print('Intersecção: {}'.format(conjunto_interseccao))
conjunto_diferenca1 = conjunto1.difference(conjunto2)
print('Diferença entre o conjunto 1 e 2: {}'.format(conjunto_diferenca1))
conjunto_diferenca2 = conjunto2.difference(conjunto1)
print('Diferença entre o conjunto 2 e 1: {}'.format(conjunto_diferenca2))
conjunto_diferenca_simetrica = conjunto1.symmetric_difference(conjunto2)
print('Diferença simétrica: {}'.format(conjunto_diferenca_simetrica))
conjunto_a = {1, 2, 3}
conjunto_b = {1, 2, 3, 4, 5}
print('Conjunto A: {}'.format(conjunto_a))
print('Conjunto B: {}'.format(conjunto_b))
conjunto_subset = conjunto_a.issubset(conjunto_b)
print('A é subconjunto de B: {}'.format(conjunto_subset))
conjunto_subset = conjunto_b.issubset(conjunto_a)
print('B é subconjunto de A: {}'.format(conjunto_subset))
conjunto_superset = conjunto_a.issuperset(conjunto_b)
print('A é superconjunto de B: {}'.format(conjunto_superset))
conjunto_superset = conjunto_b.issuperset(conjunto_a)
print('B é superconjunto de A: {}'.format(conjunto_superset))
lista_animais = ['cachorro', 'cachorro', 'gato', 'elefante', 'gato']
print('Lista de animais: {}'.format(lista_animais))
conjunto_animais = set(lista_animais)
print('Conjunto de animais: {}'.format(conjunto_animais))
lista_animais = list(conjunto_animais)
print('Lista de animais: {}'.format(lista_animais))
|
Python | UTF-8 | 502 | 2.53125 | 3 | [
"MIT"
] | permissive | import os
import pytest
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from models import LogisticModel
def test_logistic_model():
model = LogisticModel({'solver': 'liblinear'})
X, y = load_iris(return_X_y=True)
xtrain, xtest, ytrain, ytest = train_test_split(X, y, random_state=1011, test_size=0.33)
model.fit(xtrain, ytrain)
assert accuracy_score(ytest, model.predict(xtest)) >= 0.9 |
Java | UTF-8 | 11,844 | 1.914063 | 2 | [] | no_license | package com.maywide.biz.prd.web.action;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.Assert;
import com.maywide.biz.core.pojo.LoginInfo;
import com.maywide.biz.core.service.ParamService;
import com.maywide.biz.core.service.RuleService;
import com.maywide.biz.market.entity.GridManager;
import com.maywide.biz.prd.entity.Catalog;
import com.maywide.biz.prd.entity.CatalogCondtion;
import com.maywide.biz.prd.entity.CatalogItem;
import com.maywide.biz.prd.service.CatalogCondtionService;
import com.maywide.biz.prd.service.CatalogItemService;
import com.maywide.biz.prd.service.CatalogService;
import com.maywide.biz.prd.service.SalespkgKnowService;
import com.maywide.biz.prv.entity.PrvArea;
import com.maywide.biz.system.entity.PrvSysparam;
import com.maywide.common.web.action.BaseController;
import com.maywide.core.annotation.MetaData;
import com.maywide.core.cons.Constant;
import com.maywide.core.exception.WebException;
import com.maywide.core.pagination.GroupPropertyFilter;
import com.maywide.core.pagination.PropertyFilter;
import com.maywide.core.pagination.PropertyFilter.MatchType;
import com.maywide.core.security.AuthContextHolder;
import com.maywide.core.service.BaseService;
import com.maywide.core.service.PersistentService;
import com.maywide.core.util.PinYinUtils;
@MetaData(value = "目录管理")
public class CatalogController extends BaseController<Catalog, Long> {
@Autowired
private CatalogService catalogService;
@Autowired
private CatalogCondtionService catalogCondtionService;
@Autowired
private CatalogItemService catalogItemService;
@Autowired
private PersistentService persistentService;
@Autowired
private SalespkgKnowService salespkgKnowService;
@Autowired
private ParamService paramService;
@Autowired
private RuleService ruleService;
@Override
protected BaseService<Catalog, Long> getEntityService() {
return catalogService;
}
public HttpHeaders condtion() {
return buildDefaultHttpHeaders("condtion");
}
public HttpHeaders item() {
return buildDefaultHttpHeaders("item");
}
@Override
@MetaData(value = "查询")
public HttpHeaders findByPage() {
try {
Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(getRequest());
GroupPropertyFilter groupFilter = GroupPropertyFilter.buildFromHttpRequest(entityClass, getRequest());
LoginInfo logininfo = AuthContextHolder.getLoginInfo();
String city = logininfo.getCity();
if (StringUtils.isNotEmpty(city) && !Constant.ADMINISTRATOR.equals(logininfo.getLoginname())) {
// 超级管理员查询全部地市的记录
groupFilter.append(new PropertyFilter(MatchType.EQ, "city", city));
}
appendFilterProperty(groupFilter);
String foramt = this.getParameter(PARAM_NAME_FOR_EXPORT_FORMAT);
if ("xls".equalsIgnoreCase(foramt)) {
exportXlsForGrid(groupFilter, pageable.getSort());
} else {
// Page l = this.getEntityService().findByPage(groupFilter, pageable);
setModel( this.getEntityService().findByPage(groupFilter, pageable));
}
} catch (Exception e) {
throw new WebException(e.getMessage(), e);
}
return buildDefaultHttpHeaders();
}
/* private Page<Catalog> trainsientContent(Page<Catalog> page, Pageable pageable) throws Exception {
List<Catalog> content = page.getContent();
List<PrvSysparam> params = paramService.getData(BizConstant.SysparamGcode.BIZ_OPCODE);
List<Catalog> newContent =new ArrayList<Catalog>();
for(Catalog catalog:content){
if(catalog.getBizopcodes()!=null){
String[] pcodes =catalog.getBizopcodes().split(",");
String pcodeStr="";
for(String pcode :pcodes){
for(PrvSysparam param:params){
if(pcode.equals(param.getMcode())){
pcodeStr+=param.getMname();
pcodeStr+=" ";
break;
}
}
}
catalog.setOpcodesname(pcodeStr);
}
newContent.add(catalog);
}
return new PageImpl<Catalog>(newContent,pageable, page.getSize());
}*/
@Override
@MetaData(value = "删除")
public HttpHeaders doDelete() {
return super.doDelete();
}
@Override
@MetaData(value = "保存")
public HttpHeaders doSave() {
catalogService.clear();
return super.doSave();
}
@Override
@MetaData("打开编辑表单")
public HttpHeaders edit() {
try {
} catch (Exception e) {
e.printStackTrace();
throw new WebException(e.getMessage());
}
return buildDefaultHttpHeaders("inputBasic");
}
public HttpHeaders findAllKnows() {
setModel(salespkgKnowService.findAllCached());
return buildDefaultHttpHeaders();
}
public HttpHeaders selectAreaOptions() {
List<PrvSysparam> areaList;
try {
areaList = paramService.getData("PRV_CITY");
setModel(areaList);
} catch (Exception e) {
e.printStackTrace();
}
return new DefaultHttpHeaders();
}
public HttpHeaders selectConditionTypeOptions() {
List<PrvSysparam> areaList;
try {
areaList = paramService.getData("CATALOG_CONDITION_TYPE");
setModel(areaList);
} catch (Exception e) {
e.printStackTrace();
}
return new DefaultHttpHeaders();
}
public Map<String, String> getAreaMap() {
String hql = "FROM PrvSysparam WHERE gcode = ? AND scope is null ORDER BY id";
List<PrvSysparam> areaList;
Map<String, String> areaMap = new LinkedHashMap<String, String>();
try {
areaList = persistentService.find(hql, "PRV_CITY");
Collections.sort(areaList, new Comparator() {
public int compare(Object o1, Object o2) {
PrvSysparam param1 = (PrvSysparam) o1;
PrvSysparam param2 = (PrvSysparam) o2;
String pinyin1 = PinYinUtils.converterToFirstSpell(param1.getMname());
String pinyin2 = PinYinUtils.converterToFirstSpell(param2.getMname());
int rtnval = pinyin1.compareTo(pinyin2);
return rtnval;
}
});
for (PrvSysparam param : areaList) {
areaMap.put(param.getMcode(), param.getDisplay());
}
return areaMap;
} catch (Exception e) {
e.printStackTrace();
}
return areaMap;
}
public Map<String, String> getTownMap() {
Map<String, String> townMap = new LinkedHashMap<String, String>();
String hql = "FROM PrvArea WHERE city = ? ORDER BY id";
List<PrvArea> areaList;
try {
areaList = persistentService.find(hql, bindingEntity.getCity());
Collections.sort(areaList, new Comparator() {
public int compare(Object o1, Object o2) {
PrvArea param1 = (PrvArea) o1;
PrvArea param2 = (PrvArea) o2;
String pinyin1 = PinYinUtils.converterToFirstSpell(param1.getName());
String pinyin2 = PinYinUtils.converterToFirstSpell(param2.getName());
int rtnval = pinyin1.compareTo(pinyin2);
return rtnval;
}
});
for (PrvArea param : areaList) {
townMap.put(param.getId().toString(), param.getName());
}
return townMap;
} catch (Exception e) {
e.printStackTrace();
}
return townMap;
}
public HttpHeaders queryAllTown() {
List<PrvSysparam> areaList;
try {
areaList = paramService.getData("PRV_TOWN");
setModel(areaList);
} catch (Exception e) {
e.printStackTrace();
}
return new DefaultHttpHeaders();
}
public HttpHeaders getTown() {
Assert.notNull(getParameter("areaid"));
if (StringUtils.isEmpty(getParameter("areaid"))) {
return new DefaultHttpHeaders();
}
Long areaId = new Long(getParameter("areaid"));
List<PrvSysparam> areaList;
try {
areaList = paramService.getSubData("PRV_TOWN", areaId);
setModel(areaList);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new DefaultHttpHeaders();
}
public Map<Long, String> getConditionMap() {
String hql = "FROM PrvSysparam WHERE gcode = ? ORDER BY id";
List<PrvSysparam> areaList;
try {
areaList = persistentService.find(hql, "CATALOG_CONDITION_TYPE");
Map<Long, String> conditionMap = new HashMap<Long, String>();
for (PrvSysparam param : areaList) {
conditionMap.put(param.getId(), param.getDisplay());
}
return conditionMap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public Map<String,String> getBizopcodesMap(){
Map<String, String> bizOpcodesMap = new LinkedHashMap<String, String>();
try {
bizOpcodesMap = catalogService.findBizopcodesMap();
}catch (Exception e) {
e.printStackTrace();
}
return bizOpcodesMap;
}
public HttpHeaders findBizopcodesMap(){
Map<String, String> bizOpcodesMap = new LinkedHashMap<String, String>();
try {
bizOpcodesMap = catalogService.findBizopcodesMap();
}catch (Exception e) {
e.printStackTrace();
}
setModel(bizOpcodesMap);
return buildDefaultHttpHeaders();
}
public HttpHeaders queryCondtion() {
try {
Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(getRequest());
GroupPropertyFilter groupFilter = GroupPropertyFilter.buildFromHttpRequest(GridManager.class, getRequest());
PropertyFilter propertyFilter = new PropertyFilter(MatchType.EQ, "catalogid", bindingEntity.getId());
groupFilter.append(propertyFilter);
appendFilterProperty(groupFilter);
String foramt = this.getParameter(PARAM_NAME_FOR_EXPORT_FORMAT);
if ("xls".equalsIgnoreCase(foramt)) {
exportXlsForGrid(groupFilter, pageable.getSort());
} else {
Page<CatalogCondtion> page = catalogCondtionService.findByPage(groupFilter, pageable);
catalogService.transCondtionList(page.getContent());
setModel(page);
}
} catch (Exception e) {
throw new WebException(e.getMessage(), e);
}
return buildDefaultHttpHeaders();
}
public HttpHeaders queryItem() {
try {
Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(getRequest());
GroupPropertyFilter groupFilter = GroupPropertyFilter.buildFromHttpRequest(GridManager.class, getRequest());
PropertyFilter propertyFilter = new PropertyFilter(MatchType.EQ, "catalogid", bindingEntity.getId());
groupFilter.append(propertyFilter);
appendFilterProperty(groupFilter);
String foramt = this.getParameter(PARAM_NAME_FOR_EXPORT_FORMAT);
if ("xls".equalsIgnoreCase(foramt)) {
exportXlsForGrid(groupFilter, pageable.getSort());
} else {
Page<CatalogItem> page = catalogItemService.findByPage(groupFilter, pageable);
catalogService.transKnowList(page.getContent());
setModel(page);
}
} catch (Exception e) {
throw new WebException(e.getMessage(), e);
}
return buildDefaultHttpHeaders();
}
}
|
Markdown | UTF-8 | 990 | 3.328125 | 3 | [] | no_license | # Bulk Image Resizer
Python script that utilizes PIL and glob packages in order to resize all the images of given format at the designated path folder as well as in it's subfolders. Images can be both upscaled and downscaled, however since the program uses LANCZOS filter, upscaling can be exceptionally slow for large amount of images.
Supported image formats are: .png, .ico, .jpeg, .jpg, .bmp and .icns.
When calling the script 3 or 4 positional arguments are necessary. First being the path to root folder from which the images are taken, second the image format of the images to be resized and third and fourth parameter represent dimensions for resizal. If 3 positional arguments are given, the height and width of the image would be equal to the last argument. Example call would be:
```
pipenv python run bulkResizer.py Path/To/Folder .png 250 250
```
After the call is executed, resized images are stored in a new folder that is created next to root folder at the given path.
|
Shell | UTF-8 | 954 | 3.75 | 4 | [
"Apache-2.0"
] | permissive | #!/bin/bash
set -e
set -o xtrace
if [[ $# -lt 2 ]];
then
echo "usage: ./kitchen_work.sh p4 template [outdir]"
exit 1
fi
if [[ ! -f $1 ]];
then
echo "no such file $1"
exit 1
fi
if [[ ! -f $2 ]];
then
echo "template doesn't exist"
fi
fname=$1
template=$2
outdir=${3:-.}
if [[ ! -d $outdir ]];
then
echo "directory $outdir not there"
exit 1
fi
trimmed=`basename $fname .p4`
time p4c-analysis --dump-instrumented "${outdir}/${trimmed}-instrumented.p4" ${fname}
echo "instrumented ${outdir}/${trimmed}-instrumented.p4"
time p4c-analysis --expand-to "${outdir}/${trimmed}-instrumented-expanded.p4" "${outdir}/${trimmed}-instrumented.p4"
echo "expanded ${outdir}/${trimmed}-instrumented-expanded.p4"
time p4c-analysis --render-integration "${outdir}/${trimmed}-integrated.p4" \
--integration-template ${template} --render-only "${outdir}/${trimmed}-instrumented-expanded.p4"
echo "integrated ${outdir}/${trimmed}-integrated.p4" |
JavaScript | UTF-8 | 3,191 | 2.78125 | 3 | [] | no_license | // not animated collapse/expand
function togglePannelStatus(content)
{
var expand = (content.style.display=="none");
content.style.display = (expand ? "block" : "none");
}
// current animated collapsible panel content
var currentContent = null;
function togglePannelAnimatedStatus(content, interval, step, panelIndex)
{
// wait for another animated expand/collapse action to end
if (currentContent==null)
{
currentContent = content;
var expand = (content.style.display=="none");
if (expand)
{
content.style.display = "block";
setToggleStateMemory(panelIndex,1);
}
else
{
setToggleStateMemory(panelIndex,0);
}
var max_height = content.offsetHeight;
var step_height = step + (expand ? 0 : -max_height);
// schedule first animated collapse/expand event
content.style.height = Math.abs(step_height) + "px";
setTimeout("togglePannelAnimatingStatusProgress("
+ interval + "," + step
+ "," + max_height + "," + step_height + ")", interval);
}
}
function togglePannelAnimatingStatusProgress(interval,
step, max_height, step_height)
{
var step_height_abs = Math.abs(step_height);
// schedule next animated collapse/expand event
if (step_height_abs>=step && step_height_abs<=(max_height-step))
{
step_height += step;
currentContent.style.height = Math.abs(step_height) + "px";
setTimeout("togglePannelAnimatingStatusProgress("
+ interval + "," + step
+ "," + max_height + "," + step_height + ")", interval);
}
// animated expand/collapse done
else
{
if (step_height_abs<step)
currentContent.style.display = "none";
currentContent.style.height = "";
currentContent = null;
}
}
function setToggleStateMemory(panelIndex,value)
{
if(hdTogglePanel)
{
var reconstructValue = '';
var arrValues = hdTogglePanel.value.split(',');
for(i = 1; i < arrValues.length + 1; i++)
{
if(i == panelIndex)
reconstructValue += value + ',';
else
reconstructValue += arrValues[i - 1] + ',';
}
hdTogglePanel.value = reconstructValue.substring(0, reconstructValue.length - 1);
}
}
function setInitToggleStatePostback(arrValues)
{
var positionIndex = 1;
for(i=1; i < arrValues.length + 1; i++)
{
if(arrValues[i-1] == 0)
{
userTogglePanel(positionIndex);
}
positionIndex += 1;
}
}
function userTogglePanel(panelIndex)
{
switch(panelIndex)
{
case 1:
togglePannelStatus(document.getElementById('contentBookCat'));
break;
case 2:
togglePannelStatus(document.getElementById('contentBookAuthor'));
break;
case 3:
togglePannelStatus(document.getElementById('contentBookPublisher'));
break;
case 4:
togglePannelStatus(document.getElementById('contentBookType'));
break;
}
}
|
Java | UTF-8 | 734 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | package de.ipvs.as.mbp.domain.rules;
import de.ipvs.as.mbp.domain.user_entity.UserEntityRequestDTO;
import java.util.List;
/**
* DTO for rules.
*/
public class RuleDTO extends UserEntityRequestDTO {
private String name;
private String trigger;
private List<String> actions;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTrigger() {
return trigger;
}
public void setTrigger(String trigger) {
this.trigger = trigger;
}
public List<String> getActions() {
return actions;
}
public void setActions(List<String> actions) {
this.actions = actions;
}
}
|
C# | UTF-8 | 951 | 2.859375 | 3 | [
"MIT"
] | permissive | using System;
namespace SnapUi {
public class RequiredAncestorNotFoundException : Exception {
public RequiredAncestorNotFoundException()
: base(CreateMessage()) { }
public RequiredAncestorNotFoundException(string message)
: base(message) { }
public RequiredAncestorNotFoundException(string message, Exception innerException)
: base(message, innerException) { }
public RequiredAncestorNotFoundException(Type typeOfRequired)
: this(CreateMessage(typeOfRequired.FullName)) { }
public RequiredAncestorNotFoundException(Type typeOfRequired, Exception innerException)
: this(CreateMessage(typeOfRequired.FullName), innerException) { }
private static string CreateMessage(string? ancestor = null) =>
"Required ancestor"
+ ((ancestor == null) ? " " : ":'" + ancestor + "' ")
+ "not found.";
}
}
|
Python | UTF-8 | 7,900 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains tools used in our parser for BEL statements.
"""
# Standard Library
import collections
import json
import math
import os
import pprint
import random
import re
import string
from typing import Any, List, Mapping
# Third Party Imports
import yaml
# Local Imports
import bel.lang.exceptions as bel_ex
from bel.lang.ast import Arg, BELAst, Function, NSArg, StrArg
###################
# STATEMENT TOOLS #
###################
class InvalidStatementObject(object):
def __init__(self, s, r, o):
self.subject = s
self.relation = r
self.object = o
self.string_form = self.to_string_form(s, r, o)
def to_string_form(self, s, r, o):
sub = self.stmt_creation_decode(s)
rlt = r
obj = self.stmt_creation_decode(o)
return "{} {} {}".format(sub, rlt, obj)
def stmt_creation_decode(self, ast_dict):
arg_type = ast_dict.get("type", False)
arg_value = ast_dict.get("value", False)
if arg_type == "Function":
f_name = ast_dict.get("name", None)
tmp = self.stmt_creation_decode(arg_value[0])
for arg in arg_value[1:]:
tmp += ", {}".format(self.stmt_creation_decode(arg))
return "{}({})".format(f_name, tmp)
elif arg_type == "String":
return arg_value
elif arg_type == "Entity":
return arg_value
else:
return "UNK"
# TODO: move these functions to appropriate place; create_invalid , make_statement, etc. need not be in tools.
def create_invalid(bel_obj, count, max_args):
list_of_statement_objs = []
for _ in range(count):
stmt_obj = make_statement(bel_obj, max_args)
list_of_statement_objs.append(stmt_obj)
return list_of_statement_objs
def make_statement(bel_obj, max_args):
s = choose_and_make_function(bel_obj, max_args)
r = choose_rand_relation(bel_obj.relations)
o = choose_and_make_function(bel_obj, max_args)
return InvalidStatementObject(s, r, o)
def choose_and_make_function(bel_obj, max_args):
full_func = {
"name": choose_rand_function(bel_obj.function_signatures),
"type": "Function",
"value": [],
}
num_args = random.randint(1, max_args) # how many args to have
for _ in range(num_args):
t = random.choice(["Entity", "String", "Function"])
arg = {"type": t}
if t == "Entity":
arg["value"] = random_namespace_arg()
elif t == "String":
arg["value"] = random_quoted_string()
elif t == "Function":
arg = choose_and_make_function(bel_obj, max_args)
else:
pass
full_func["value"].append(arg)
return full_func
def choose_rand_relation(relations):
return random.choice(relations)
def choose_rand_function(func_sigs):
return random.choice(list(func_sigs.keys()))
def random_namespace_arg():
ascii_letters = string.ascii_uppercase + string.ascii_lowercase
ascii_alphanumeric_upper = string.ascii_uppercase + string.digits
ascii_alphanumeric = ascii_letters + string.digits
i = random.randint(2, 5)
rand_nspace = "NS" + "".join(random.choice(ascii_alphanumeric_upper) for _ in range(i))
j = random.randint(5, 25)
if random.random() < 0.5: # quoted nsvalue
rand_nsvalue = "".join(random.choice(ascii_alphanumeric + " ' - , + /.") for _ in range(j))
rand_nsvalue = '"{}"'.format(rand_nsvalue)
else: # unquoted nsvalue
rand_nsvalue = "".join(random.choice(ascii_alphanumeric) for _ in range(j))
return "{}: {}".format(rand_nspace, rand_nsvalue)
def random_quoted_string():
ascii_letters = string.ascii_uppercase + string.ascii_lowercase
ascii_alphanumeric = ascii_letters + string.digits
j = random.randint(5, 25)
rand_nsvalue = "".join(random.choice(ascii_alphanumeric + " ' - , + /.") for _ in range(j))
return '"{}"'.format(rand_nsvalue)
# def simple_args(args, bel_obj):
#
# new_args = []
#
# for p in args:
#
# if 'function' in p:
# obj_type = 'function'
# f_type = 'primary'
# obj = {
# 'name': p['function'],
# 'type': f_type,
# 'alternate': bel_obj.translate_terms[p['function']],
# 'full_string': decode(p),
# 'args': simple_args(p['function_args'], bel_obj)
# }
# elif 'm_function' in p:
# obj_type = 'function'
# f_type = 'modifier'
# obj = {
# 'name': p['m_function'],
# 'type': f_type,
# 'alternate': bel_obj.translate_terms[p['m_function']],
# 'full_string': decode(p),
# 'args': simple_args(p['m_function_args'], bel_obj)
# }
# elif 'ns_arg' in p:
# obj_type = 'ns_variable'
# obj = {
# 'namespace': p['ns_arg']['nspace'],
# 'value': p['ns_arg']['ns_value'],
# 'full_string': decode(p)
# }
# else:
# obj_type = 'str_variable'
# obj = {
# 'value': p['str_arg'],
# }
#
# new_args.append({obj_type: obj})
#
# return new_args
# def extract_args_from_rule(rule, function_obj):
#
# args = []
#
# print('OLD RULE: {}'.format(rule))
# rule = rule.replace('{{ ', '').replace(' }}', '')
#
# # instead of replacing the keyword with the given variable, we need to actually create an object....
#
# rule = rule.replace('p_full', variables['p_full'])
# rule = rule.replace('p_name', variables['p_name'])
#
# rule = rule.replace('full', variables['full']) # this should be the func object string
# rule = rule.replace('fn_name', variables['fn_name']) # this should be the function object
# print('NEW RULE: {}'.format(rule))
# print()
#
# args_wanted = []
#
# arg_pattern = '(p_)?args(\[[fmns]\])?'
# regex_pattern = re.compile(arg_pattern)
# arg_matched_rule = regex_pattern.search(rule)
#
# if arg_matched_rule: # if args are needed, loop through
# final_to_replace = arg_matched_rule.group()
# use_parent_args = None
#
# try:
# use_parent_args = arg_matched_rule.group(1)
# filter_string = arg_matched_rule.group(2)
# if filter_string is None:
# filter_string = ''
# except IndexError as e:
# filter_string = '' # stands for all
#
# # print('Use parent args: {}'.format(bool(use_parent_args)))
# # print('Filter string: {}'.format(filter_string))
#
# allowed_type = ''
#
# if 'f' in filter_string:
# allowed_type = 'function'
# elif 'm' in filter_string:
# allowed_type = 'm_function'
# elif 'n' in filter_string:
# allowed_type = 'ns_arg'
# elif 's' in filter_string:
# allowed_type = 'str_arg'
#
# if use_parent_args is not None: # use the parent's args
# args_to_loop = variables['p_args']
# else:
# args_to_loop = args
#
# for a in args_to_loop:
# if allowed_type == '' or allowed_type in list(a):
# decoded_arg = decode(a)
# final_rule = rule.replace(final_to_replace, decoded_arg)
# args_wanted.append(final_rule)
# make_simple_ast(a)
#
# else:
# return [rule]
#
# return args_wanted
#################
# PARSING TOOLS #
#################
class Colors:
PINK = "\033[95m"
BLUE = "\033[94m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
END = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
|
PHP | UTF-8 | 2,177 | 3.15625 | 3 | [] | no_license | <?php
namespace Alpadia\Models\Repositories;
use Alpadia\Models\Entities\Game as Game;
use Alpadia\Models\Factories\GameFactory as GameFactory;
use Alpadia\Models\Repositories\Repository as Repository;
use Alpadia\Models\Repositories\RepositoryInterface as RepositoryInterface;
use Illuminate\Database\QueryException as QueryException;
class GameRepository extends Repository implements RepositoryInterface
{
/**
* Add new game
*
* @param array $data Game data
*
* @return array Game added
*/
public function add(array $data) : array
{
$game = GameFactory::createFromArray($data);
try {
if ($game->save()) {
return $game->toArray();
}
} catch (QueryException $e) {
$this->queryErrors[] = $e->errorInfo[2];
}
return [];
}
/**
* Delete a game
*
* @param int $id Game id
*
* @return int 1 if deleted
*/
public function delete(int $id) : int
{
$game = Game::where(["id"=>$id])->first();
if ( isset($game) ) {
return $game->delete();
}
return 0;
}
/**
* Find a game
*
* @param int $id Game id
*
* @return array Game data
*/
public function find(int $id) : array
{
$game = Game::where(["id"=>$id])->first();
if (isset($game)) {
return $game->toArray();
}
return [];
}
/**
* Get all games
*
* @return array Game collection
*/
public function get() : array
{
return Game::get()->toArray();
}
/**
* Update game data
*
* @param int $id Game unique id
* @param array $data Game new data
*
* @return array Game data
*/
public function update(int $id, array $data) : array
{
try {
$updated = Game::where(["id" => $id])->update($data);
if ($updated) {
return $this->find($id);
}
} catch (QueryException $e) {
$this->queryErrors[] = $e->errorInfo[2];
}
return [];
}
}
?>
|
JavaScript | UTF-8 | 832 | 2.765625 | 3 | [
"MIT"
] | permissive | 'use strict';
var Logger = function (loggerConfig) {
var levels = {
debug: 4,
info: 3,
warn: 2,
error: 1,
abort: 0
};
console.log('config:', loggerConfig);
var currentLevel = levels[loggerConfig.level] || 2;
this.debug = function(msg){
if(currentLevel >= levels.debug){
console.log('[debug]: ', msg);
}
};
this.info = function(msg){
if(currentLevel >= levels.info){
console.log('[info]: ', msg);
}
};
this.warn = function(msg){
if(currentLevel >= levels.warn){
console.log('[*warn*]: ', msg);
}
};
this.error = function(msg){
if(currentLevel >= levels.error){
console.log('[**error**]: ', msg);
}
};
};
module.exports = Logger; |
Java | UTF-8 | 3,003 | 1.890625 | 2 | [] | no_license | package nta.med.service.ihis.handler.cpls;
import java.util.List;
import javax.annotation.Resource;
import nta.med.data.dao.medi.cpl.Cpl3020Repository;
import nta.med.data.model.ihis.cpls.CPL0000Q00GetSigeyulDataSelect2ListItemInfo;
import nta.med.core.infrastructure.socket.handler.ScreenHandler;
import nta.med.service.ihis.proto.CplsModelProto;
import nta.med.service.ihis.proto.CplsServiceProto;
import nta.med.service.ihis.proto.CplsServiceProto.CPL0000Q00GetSigeyulDataSelect2Request;
import nta.med.service.ihis.proto.CplsServiceProto.CPL0000Q00GetSigeyulDataSelect2Response;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.vertx.java.core.Vertx;
@Service
@Scope("prototype")
public class CPL0000Q00GetSigeyulDataSelect2Handler extends ScreenHandler<CplsServiceProto.CPL0000Q00GetSigeyulDataSelect2Request, CplsServiceProto.CPL0000Q00GetSigeyulDataSelect2Response> {
private static final Log LOG = LogFactory.getLog(CPL0000Q00GetSigeyulDataSelect2Handler.class);
@Resource
private Cpl3020Repository cpl3020Repository;
@Override
@Transactional(readOnly = true)
public CPL0000Q00GetSigeyulDataSelect2Response handle(Vertx vertx,
String clientId, String sessionId, long contextId,
CPL0000Q00GetSigeyulDataSelect2Request request) throws Exception {
CplsServiceProto.CPL0000Q00GetSigeyulDataSelect2Response.Builder response = CplsServiceProto.CPL0000Q00GetSigeyulDataSelect2Response.newBuilder();
List<CPL0000Q00GetSigeyulDataSelect2ListItemInfo> listItem = cpl3020Repository.getCPL0000Q00GetSigeyulDataSelect2(getHospitalCode(vertx, sessionId), request.getBunho(),
request.getHangmogCode(), request.getJubsuDate(), request.getJubsuTime());
if(!CollectionUtils.isEmpty(listItem)) {
for(CPL0000Q00GetSigeyulDataSelect2ListItemInfo item : listItem) {
CplsModelProto.CPL0000Q00GetSigeyulDataSelect2ListItemInfo.Builder info = CplsModelProto.CPL0000Q00GetSigeyulDataSelect2ListItemInfo.newBuilder();
if (!StringUtils.isEmpty(item.getCplResult())) {
info.setCplResult(item.getCplResult());
}
if (!StringUtils.isEmpty(item.getStandardYn())) {
info.setStandardYn(item.getStandardYn());
}
if (!StringUtils.isEmpty(item.getGumsaName())) {
info.setGumsaName(item.getGumsaName());
}
if (!StringUtils.isEmpty(item.getFromStandard())) {
info.setFromStandard(item.getFromStandard());
}
if (!StringUtils.isEmpty(item.getToStandard())) {
info.setToStandard(item.getToStandard());
}
response.addResultList(info);
}
}
return response.build();
}
}
|
C# | UTF-8 | 2,737 | 2.953125 | 3 | [] | no_license | using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
namespace ExchangeRateUpdater
{
public class ExchangeRateProvider
{
private const string ExchangeRatesUrl = "https://www.cnb.cz/en/financial-markets/foreign-exchange-market" +
"/central-bank-exchange-rate-fixing/central-bank-exchange-rate-fixing/daily.txt";
private readonly Currency CzkCurrency = new Currency("CZK");
/// <summary>
/// Should return exchange rates among the specified currencies that are defined by the source. But only those defined
/// by the source, do not return calculated exchange rates. E.g. if the source contains "EUR/USD" but not "USD/EUR",
/// do not return exchange rate "USD/EUR" with value calculated as 1 / "EUR/USD". If the source does not provide
/// some of the currencies, ignore them.
/// </summary>
public IEnumerable<ExchangeRate> GetExchangeRates(IEnumerable<Currency> currencies)
{
if (currencies == null || !currencies.Any())
{
return Enumerable.Empty<ExchangeRate>();
}
var result = new List<ExchangeRate>();
var response = GetExchangeData();
var extractedExchangeData = GetExtractedExchangeData(response);
foreach (var item in extractedExchangeData)
{
var lineArray = item.Split('|');
if (lineArray.Length < 3) continue;
var currency = lineArray[1];
if (!currencies.Any(x => x.Code == currency)) continue;
decimal.TryParse(lineArray[0], out decimal source);
decimal.TryParse(lineArray[2], out decimal target);
result.Add(new ExchangeRate(
new Currency(lineArray[1]),
CzkCurrency,
target / source));
}
return result;
}
private string GetExchangeData()
{
using (var client = new HttpClient())
{
var responseResult = client.GetAsync(ExchangeRatesUrl).Result;
if (responseResult.IsSuccessStatusCode)
{
return responseResult.Content.ReadAsStringAsync().Result;
}
}
return string.Empty;
}
private IEnumerable<string> GetExtractedExchangeData(string response)
{
Regex r = new Regex(@"(\d+)(\d|.+)");
var regexMatches = r.Matches(response).Cast<Match>()
.Select(x => x.Value);
return regexMatches.Skip(1);
}
}
}
|
JavaScript | UTF-8 | 352 | 3.375 | 3 | [] | no_license | const ler = require("prompt-sync")();
var cartas = 0;
do {
var valor = Number(ler("Digite o valor da carta: "));
cartas = cartas + valor;
} while (cartas < 21);
if (cartas > 21){
console.log("O carteiro venceu, o valor utrapassou e alcançou:", cartas,"cartas");
} else {
console.log("Parabéns você venceu. Total", cartas,"cartas")
} |
Python | UTF-8 | 111 | 2.703125 | 3 | [] | no_license | # https://www.codewars.com/kata/58b57f984f353b3dc9000030
palindrome=lambda n,c:c+c[-1]*(n-2*len(c)+1)+c[-2::-1] |
Python | UTF-8 | 343 | 2.59375 | 3 | [] | no_license |
def encrypt(key, message):
KD1=[x for x in zip(key[0::2], key[1::2])]
KD2=[x for x in zip(key[1::2], key[0::2])]
KD=[]
for x in KD1:
if all(y[0]!=x[0] for y in KD):
KD.append(x)
KD2=[x[::-1] for x in KD]
D=dict(KD+KD2)
res=''
for x in message:
if x in D:
res+=D[x]
else:
res+=x
return res
|
C++ | UTF-8 | 1,334 | 3.484375 | 3 | [] | no_license | #include "GameObject.h"
// Construct a GameObject
GameObject::GameObject(char in_code) {
this -> display_code = in_code;
this -> id_num = 1;
this -> state = 0;
cout << "GameObject constructed." << endl;
}
// Construct a GameObject
GameObject::GameObject(Point2D in_loc, int in_id, char in_code) {
this -> location = in_loc;
this -> id_num = in_id;
this -> display_code = in_code;
this -> state = 0;
cout << "GameObject constructed." << endl;
}
// GameObject destructor
GameObject::~GameObject() {
cout << "GameObject destructed." << endl;
}
// Returns the location of this object
Point2D GameObject::GetLocation() {
return this -> location;
}
// Returns the ID of this object
int GameObject::GetId() {
return this -> id_num;
}
// Returns the state of this object
char GameObject::GetState() {
return this -> state;
}
// Returns all information contained in class
void GameObject::ShowStatus() {
cout << this -> display_code << this -> id_num << " at " << this -> location << endl;
}
// Get function for display_code
char GameObject::GetDisplayCode() {
return this -> display_code;
}
// Adds display_code and id_num to char pointer
void GameObject::DrawSelf(char* char_ptr) {
*char_ptr = this -> GetDisplayCode();
*(char_ptr + 1) = '0' + this -> GetId();
} |
SQL | UTF-8 | 543 | 2.90625 | 3 | [] | no_license | CREATE Procedure sp_update_GRN_RecdInvoice(@GRNID Int,
@RecdInvoiceID Int)
As
Update GRNAbstract Set RecdInvoiceID = @RecdInvoiceID Where GRNID = @GRNID
IF (SELECT SUM(Pending) from InvoiceDetailReceived WHERE InvoiceID = @RecdInvoiceID) = 0
Update InvoiceAbstractReceived Set Status = IsNull(Status, 1) | 129 Where InvoiceID = @RecdInvoiceID
Else
Update InvoiceAbstractReceived Set Status = 32 | 128 Where InvoiceID = @RecdInvoiceID
--Update InvoiceAbstractReceived Set Status = IsNull(Status,0) | 32 Where InvoiceID = @RecdInvoiceID
|
PHP | UTF-8 | 2,274 | 2.59375 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | <?php
namespace Tracker\AdminBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Tracker\UserBundle\Entity\User;
use Tracker\StationBundle\Entity\Station;
use Tracker\CaptureBundle\Entity\Capture;
class CreateRealtimeCaptureCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('tracker:realtime:capture')
->setDescription('Create captures every 5 seconds')
->setDefinition(array(
new InputArgument('boxId', InputArgument::REQUIRED, 'Id box'),
new InputArgument('nbStations', InputArgument::REQUIRED, 'Nombre de stations maximum par 5 secondes')
))
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get('doctrine')->getManager();
$nbStations = $input->getArgument('nbStations');
$boxId = $input->getArgument('boxId');
$box = $em->getRepository('TrackerPlaceBundle:Box')->find($boxId);
// Boucle infini de création
while(1) {
$nb = mt_rand(0, $nbStations);
$output->writeln('Creation de '.$nb.' stations');
for($i = 0; $i < $nb; $i++) {
// Station
$station = new Station();
$station->setMac($this->generateMac());
$em->persist($station);
$em->flush();
// Capture
$capture = new Capture();
$capture->setBox($box);
$capture->setStation($station);
$capture->setDateCapture(new \DateTime());
$capture->setPower(rand(-90, -20));
$em->persist($capture);
$em->flush();
}
sleep(1);
}
}
private function generateMac()
{
$mac = '';
for( $i = 0; $i < 17; $i++)
{
if( ($i+1)%3 == 0)
$mac .= ':';
else
$mac .= dechex(mt_rand(0, 15));
}
return $mac;
}
} |
PHP | UTF-8 | 1,261 | 2.671875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: fintara
* Date: 07/01/2017
* Time: 23:11
*/
namespace AppBundle\Security\User;
use AppBundle\Entity\User;
use AppBundle\Repository\UserRepository;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
class MultiUserProvider implements UserProviderInterface
{
private $repository;
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
}
public function loadUserByUsername($email)
{
$user = $this->repository->findOneByEmail($email);
if ($user === null) {
throw new UsernameNotFoundException('User with email "'.$email.'" does not exist.');
}
return $user;
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof User) {
throw new UnsupportedUserException();
}
return $this->loadUserByUsername($user->getEmail());
}
public function supportsClass($class)
{
return User::class === $class;
}
} |
Shell | UTF-8 | 658 | 2.765625 | 3 | [] | no_license | # Contributor: phillipe <phillipe@archlinux.com.br>
pkgname=usbmanager
pkgver=1.0.0
pkgrel=1
pkgdesc="An USB storage management interface."
arch=('any')
url="https://launchpad.net/usbmanager"
depends=('hal' 'gtk2' 'python>=2.6' 'pygtk' 'python-notify')
optdepends=('mtools: to get the name [label] of the usb device.')
license=('GPL')
source=("http://launchpad.net/usbmanager/1.x/1.0.0/+download/${pkgname}-${pkgver}.tar.gz")
md5sums=('d51e01cf78e0c5b1628646e3652ea510')
build(){
cd ${srcdir}/${pkgname}
python setup.py install --root $pkgdir
sed -i 's/^Exec=usbmanager/Exec=usbmanager --tray/' ${pkgdir}/usr/share/applications/${pkgname}.desktop
rm -rf ${pkgdir}/root
}
|
Java | UTF-8 | 951 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | package net.spizzer.aoc2019.intcode;
import net.spizzer.aoc2019.common.ValueBase;
import java.util.ArrayList;
import java.util.List;
enum ParameterMode implements ValueBase<Integer> {
POSITION(0),
IMMEDIATE(1),
RELATIVE(2);
private final int value;
ParameterMode(int value) {
this.value = value;
}
@Override
public Integer getValue() {
return value;
}
public static ParameterMode[] fromInstruction(int instruction, int numberOfInputParameters) {
List<ParameterMode> modes = new ArrayList<>(numberOfInputParameters);
instruction = instruction / 100;
while (instruction > 0) {
modes.add(ValueBase.fromValue(values(), instruction % 10));
instruction = instruction / 10;
}
while (modes.size()<numberOfInputParameters+1) {
modes.add(POSITION);
}
return modes.toArray(ParameterMode[]::new);
}
}
|
Java | UTF-8 | 584 | 2.671875 | 3 | [] | no_license | package com.cleancode.core.contract.qualifier;
import java.util.Arrays;
public enum TypeLibrary {
SMALL("small"), BIG("big");
private String tipo;
TypeLibrary(final String tipo) {
this.tipo = tipo;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public static TypeLibrary recuperaPeloTipo(final String tipo) {
return tipo != null
? Arrays.stream(TypeLibrary.values()).filter(tipoLibrary -> tipoLibrary.tipo.equals(tipo)).findFirst().orElse(null)
: null;
}
}
|
C++ | UTF-8 | 3,518 | 2.609375 | 3 | [] | no_license | #include "GameConfig.h"
#include <fstream>
#include <cstdlib>
#include <sstream>
#define FAILURE 256
__uint32 ServerConfig::MAX_PLAYER_NUMBER = 2000;
__uint32 ServerConfig::MAX_ROOM_NUMBER = 50;
__uint32 ServerConfig::MAX_ROOM_PLAYER = 40;
__uint32 ServerConfig::SOCK_SEND_TIME_LIMIT = 500;
__uint32 ServerConfig::SOCK_RECV_TIME_LIMIT = 500;
__uint32 ServerConfig::SOCKET_TO_SYSTEM_TEMP = 0;
__uint32 ServerConfig::SYSTEM_TO_SOCKET_TEMP = 0;
__uint32 ServerConfig::HEARTBEAT_MECHANISM = 1;
__uint32 ServerConfig::HEARTBEAT_CHECK_INTERVAL = 1;
__uint32 ServerConfig::HEARTBEAT_CHECK_NUMBER = 3;
__uint32 ServerConfig::PORT = 30000;//端口号
float ServerConfig::DESTROY_COMPENSATION = 0.8;//摧毁塔的补偿
void ServerConfig::ReadConfig()
{
std::stringstream middle;
std::string temp, value;
std::fstream file;
std::string game_config = "Config/game_config";
std::string net_config = "Config/net_config";
std::string server_config = "Config/server_config";
//判断目录是否存在
if(system("find -P Config/") == FAILURE)
{
if(system("mkdir Config/") == FAILURE)
{
system("mv Config Config(Copy)");
system("mkdir Config/");
}
}
auto set_value = [&](std::string signal, __uint32 &arg)
{
file >> temp >> value;
if(temp == signal)
{
middle << value;
middle >> arg;
}
};
file.open(game_config, std::ios::in);
if(!file)
{
file.open(game_config, std::ios::out);
file << "compensation " << DESTROY_COMPENSATION << std::endl;
file << "max_player_number " << MAX_PLAYER_NUMBER << std::endl;
file << "max_room_number " << MAX_ROOM_NUMBER << std::endl;
file << "max_player_in_room " << MAX_ROOM_PLAYER << std::endl;
}
else
{
set_value("compensation", DESTROY_COMPENSATION);
set_value("max_player_number", MAX_PLAYER_NUMBER);
set_value("max_room_number", MAX_ROOM_NUMBER);
set_value("max_player_in_room", MAX_ROOM_PLAYER);
}
file.close();
file.open(net_config, std::ios::in);
if(!file)
{
file.open(net_config, std::ios::out);
file << "sock_send_time_limit " << SOCK_SEND_TIME_LIMIT << std::endl;
file << "sock_recv_time_limit " << SOCK_RECV_TIME_LIMIT << std::endl;
file << "socket_to_system_temp " << SOCKET_TO_SYSTEM_TEMP << std::endl;
file << "system_to_socket_temp " << SYSTEM_TO_SOCKET_TEMP << std::endl;
file << "heartbeat_mechanism " << HEARTBEAT_MECHANISM << std::endl;
file << "heartbeat_check_interval " << HEARTBEAT_CHECK_INTERVAL << std::endl;
file << "heartbeat_check_number " << HEARTBEAT_CHECK_NUMBER << std::endl;
}
else
{
set_value("sock_send_time_limit", SOCK_SEND_TIME_LIMIT);
set_value("sock_recv_time_limit", SOCK_RECV_TIME_LIMIT);
set_value("socket_to_system_temp", SOCKET_TO_SYSTEM_TEMP);
set_value("system_to_socket_temp", SYSTEM_TO_SOCKET_TEMP);
set_value("heartbeat_mechanism", HEARTBEAT_MECHANISM);
set_value("heartbeat_check_interval", HEARTBEAT_CHECK_INTERVAL);
set_value("heartbeat_check_number", HEARTBEAT_CHECK_NUMBER);
}
file.close();
file.open(server_config, std::ios::in);
if(!file)
{
file.open(net_config, std::ios::out);
file << "port " << PORT << std::endl;
}
else
{
set_value("port", PORT);
}
file.close();
}
|
Markdown | UTF-8 | 1,991 | 3.09375 | 3 | [] | no_license | ---
title: "How can chess positions be kept track of?"
author: "Josh Merrell"
date: "April 7, 2016"
commments: true
tags:
- R Packages
- Analytics
- Chess
categories:
- R Packages
---
I keep track of chess positions using a data frame of 64 variables, one for each square of the chessboard. An example of an empty chessboard can be generated with the *empty* function:
```r
load("chessDoodles.RData")
position <- empty(gameName = "example")
position
```
```
## a8 a7 a6 a5 a4 a3 a2 a1 b8 b7 b6 b5 b4 b3 b2 b1 c8 c7 c6 c5
## example_empty NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
## c4 c3 c2 c1 d8 d7 d6 d5 d4 d3 d2 d1 e8 e7 e6 e5 e4 e3 e2 e1
## example_empty NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
## f8 f7 f6 f5 f4 f3 f2 f1 g8 g7 g6 g5 g4 g3 g2 g1 h8 h7 h6 h5
## example_empty NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
## h4 h3 h2 h1
## example_empty NA NA NA NA
```
Note that columns are named after squares of the chessboard, and rows are named in gameName_move format. An example of a chessboard where the pieces have not been moved can be generated with the *setup* function (which internally calls the *empty* function):
```r
position <- setup(gameName = "game1")
position[,c("d1","e1","d8","e8")]
```
```
## d1 e1 d8 e8
## game1_empty <NA> <NA> <NA> <NA>
## game1_zero white Queen white King black Queen black King
```
The position object is built row-by-row using the *newPosition* function.
```r
newRow <- newPosition(new_pgn = "game1_1.e4", startPosition = nrow(position))
position <- rbind(position,newRow)
position[,c("e2","e4")]
```
```
## e2 e4
## game1_empty <NA> <NA>
## game1_zero white pawn <NA>
## game1_1.e4 <NA> white pawn
```
This *position* object is referenced by all the position-oriented functions I have written.
|
JavaScript | UTF-8 | 1,248 | 2.546875 | 3 | [
"MIT"
] | permissive | let fetch = require('node-fetch')
let handler = async (m, { conn, command }) => {
if (/^tod$/i.test(command)) {
conn.send3Button(m.chat, 'Truth or Dare', 'ariabotz | pesan otomatis', 'TRUTH', ',truth', 'DARE', ',dare', 'RANDOM', `${pickRandom([',dare', ',truth'])}`)
}
if (/^truth$/i.test(command)) {
let res = await fetch(global.API('pencarikode', '/api/truthid', {}, 'apikey'))
if (!res.ok) throw await `${res.status} ${res.statusText}`
let json = await res.json()
if (json.message == "") throw json
conn.send3Button(m.chat, json.message, '', 'TRUTH', ',truth', 'DARE', ',dare', 'RANDOM', `${pickRandom([',dare', ',truth'])}`)
}
if (/^dare$/i.test(command)) {
let res = await fetch(global.API('pencarikode', '/api/dareid', {}, 'apikey'))
if (!res.ok) throw await `${res.status} ${res.statusText}`
let json = await res.json()
if (json.message == "") throw json
conn.send3Button(m.chat, json.message, '', 'TRUTH', ',truth', 'DARE', ',dare', 'RANDOM', `${pickRandom([',dare', ',truth'])}`)
}
}
handler.help = ['tod']
handler.tags = ['fun']
handler.command = /^(tod|truth|dare)$/i
module.exports = handler
function pickRandom(list) {
return list[Math.floor(list.length * Math.random())]
} |
Python | UTF-8 | 575 | 3.921875 | 4 | [] | no_license | '''
Write a function called compact.
This function accepts a list and returns a list of values that are truthy values, without any of the falsey values.
compact([0,1,2,"",[], False, {}, None, "All done"]) # [1,2, "All done"]
'''
#1st Solution
# def compact(collection):
# buildlist = []
# for collect in collection:
# if collect:
# buildlist.append(collect)
# return buildlist
#2nd Solution
def compact(collection):
return [collect for collect in collection if collect]
print(compact([0,1,2,"",[], False, {}, None, "All done"])) |
Markdown | UTF-8 | 4,902 | 2.96875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # tusd
> **tus** is a protocol based on HTTP for *resumable file uploads*. Resumable
> means that an upload can be interrupted at any moment and can be resumed without
> re-uploading the previous data again. An interruption may happen willingly, if
> the user wants to pause, or by accident in case of an network issue or server
> outage.
tusd is the official reference implementation of the [tus resumable upload
protocol](http://www.tus.io/protocols/resumable-upload.html). The protocol
specifies a flexible method to upload files to remote servers using HTTP.
The special feature is the ability to pause and resume uploads at any
moment allowing to continue seamlessly after e.g. network interruptions.
**Protocol version:** 1.0.0
## Getting started
### Download pre-builts binaries (recommended)
You can download ready-to-use packages including binaries for OS X, Linux and
Windows in various formats of the
[latest release](https://github.com/tus/tusd/releases/latest).
### Compile from source
**Requirements:**
* [Go](http://golang.org/doc/install) (1.3 or newer)
**Running tusd from source:**
Clone the git repository and `cd` into it.
```bash
git clone git@github.com:tus/tusd.git
cd tusd
```
Now you can run tusd:
```bash
go run cmd/tusd/main.go
```
## Using tusd manually
Besides from running tusd using the provided binary, you can embed it into
your own Go program:
```go
package main
import (
"github.com/tus/tusd"
"github.com/tus/tusd/filestore"
"net/http"
)
func main() {
// Create a new FileStore instance which is responsible for
// storing the uploaded file on disk in the specified directory.
// If you want to save them on a different medium, for example
// a remote FTP server, you can implement your own storage backend
// by implementing the tusd.DataStore interface.
store := filestore.FileStore{
Path: "./uploads",
}
// A storage backend for tusd may consist of multiple different parts which
// handle upload creation, locking, termination and so on. The composer is a
// place where all those seperated pieces are joined together. In this example
// we only use the file store but you may plug in multiple.
composer := tusd.NewStoreComposer()
store.UseIn(composer)
// Create a new HTTP handler for the tusd server by providing a configuration.
// The StoreComposer property must be set to allow the handler to function.
handler, err := tusd.NewHandler(tusd.Config{
BasePath: "files/",
StoreComposer: composer,
})
if err != nil {
panic("Unable to create handler: %s", err)
}
// Right now, nothing has happened since we need to start the HTTP server on
// our own. In the end, tusd will start listening on and accept request at
// http://localhost:8080/files
http.Handle("files/", http.StripPrefix("files/", handler))
err = http.ListenAndServe(":8080", nil)
if err != nil {
panic("Unable to listen: %s", err)
}
}
```
Please consult the [online documentation](https://godoc.org/github.com/tus/tusd)
for more details about tusd's APIs and its sub-packages.
## Implementing own storages
The tusd server is built to be as flexible as possible and to allow the use
of different upload storage mechanisms. By default the tusd binary includes
[`filestore`](https://godoc.org/github.com/tus/tusd/filestore) which will save every upload
to a specific directory on disk.
If you have different requirements, you can build your own storage backend
which will save the files to S3, a remote FTP server or similar. Doing so
is as simple as implementing the [`tusd.DataStore`](https://godoc.org/github.com/tus/tusd/#DataStore)
interface and using the new struct in the [configuration object](https://godoc.org/github.com/tus/tusd/#Config).
Please consult the documentation about detailed information about the
required methods.
## Packages
This repository does not only contain the HTTP server's code but also other
useful tools:
* [**s3store**](https://godoc.org/github.com/tus/tusd/s3store): A storage backend using AWS S3
* [**filestore**](https://godoc.org/github.com/tus/tusd/filestore): A storage backend using the local file system
* [**memorylocker**](https://godoc.org/github.com/tus/tusd/memorylocker): An in-memory locker for handling concurrent uploads
* [**consullocker**](https://godoc.org/github.com/tus/tusd/consullocker): A locker using the distributed Consul service
* [**limitedstore**](https://godoc.org/github.com/tus/tusd/limitedstore): A storage wrapper limiting the total used space for uploads
## Running the testsuite
[](https://travis-ci.org/tus/tusd)
[](https://ci.appveyor.com/project/Acconut/tusd/branch/master)
```bash
go test -v ./...
```
## License
This project is licensed under the MIT license, see `LICENSE.txt`.
|
Markdown | UTF-8 | 3,975 | 2.5625 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Använd delade VM-avbildningar för att skapa en skalnings uppsättning i Azure PowerShell
description: Lär dig hur du använder Azure PowerShell för att skapa delade VM-avbildningar som ska användas för distribution av skalnings uppsättningar för virtuella datorer i Azure.
author: cynthn
ms.service: virtual-machine-scale-sets
ms.subservice: shared-image-gallery
ms.topic: how-to
ms.date: 05/04/2020
ms.author: cynthn
ms.reviewer: akjosh
ms.openlocfilehash: c6e8eaafa8d6e8b1f68873130b5ff56484fda049
ms.sourcegitcommit: 56b0c7923d67f96da21653b4bb37d943c36a81d6
ms.translationtype: MT
ms.contentlocale: sv-SE
ms.lasthandoff: 04/06/2021
ms.locfileid: "106444028"
---
# <a name="create-and-use-shared-images-for-virtual-machine-scale-sets-with-the-azure-powershell"></a>Skapa och Använd delade avbildningar för skalnings uppsättningar för virtuella datorer med Azure PowerShell
När du skapar en skalningsuppsättning, kan du ange en avbildning som ska användas när de virtuella datorinstanserna distribueras. Tjänsten Shared Image Gallery fören klar anpassningen av anpassade bilder i hela organisationen. Anpassade avbildningar liknar Marketplace-avbildningar, men du skapar dem själv. Anpassade avbildningar kan användas för startkonfigurationer, till exempel förinläsning av program, programkonfigurationer och andra OS-konfigurationer.
Med galleriet för delade avbildningar kan du dela dina anpassade VM-avbildningar med andra i din organisation, inom eller mellan regioner, inom en AAD-klient. Välj vilka bilder du vill dela, vilka regioner du vill göra tillgängliga i och vilka du vill dela dem med. Du kan skapa flera gallerier så att du kan gruppera delade avbildningar logiskt.
Galleriet är en resurs på den översta nivån som ger fullständig Azure-rollbaserad åtkomst kontroll (Azure RBAC). Avbildningar kan vara versioner och du kan välja att replikera varje avbildnings version till en annan uppsättning Azure-regioner. Galleriet fungerar bara med hanterade bilder.
Funktionen för delad bild galleri har flera resurs typer.
[!INCLUDE [virtual-machines-shared-image-gallery-resources](../../includes/virtual-machines-shared-image-gallery-resources.md)]
## <a name="before-you-begin"></a>Innan du börjar
Stegen nedan visar hur du tar en befintlig virtuell dator och omvandlar den till en återanvändbar anpassad avbildning som du kan skapa nya VM-instanser med.
Du måste ha en befintlig hanterad avbildning för att kunna slutföra exemplet i den här artikeln. Du kan följa [Självstudier: skapa och använda en anpassad avbildning för skalnings uppsättningar för virtuella datorer med Azure PowerShell](tutorial-use-custom-image-powershell.md) för att skapa en om det behövs. Om den hanterade avbildningen innehåller en datadisk får data disk storleken inte vara större än 1 TB.
När du arbetar genom artikeln ersätter du resurs gruppen och VM-namnen där det behövs.
[!INCLUDE [virtual-machines-common-shared-images-ps](../../includes/virtual-machines-common-shared-images-powershell.md)]
## <a name="next-steps"></a>Nästa steg
Du kan också skapa en delad resurs för avbildnings galleriet med hjälp av mallar. Det finns flera tillgängliga Azure snabb starts mallar:
- [Skapa ett Shared Image Gallery](https://azure.microsoft.com/resources/templates/101-sig-create/)
- [Skapa en avbildningsdefinition i ett Shared Image Gallery](https://azure.microsoft.com/resources/templates/101-sig-image-definition-create/)
- [Skapa en avbildningsversion i ett Shared Image Gallery](https://azure.microsoft.com/resources/templates/101-sig-image-version-create/)
- [Skapa en virtuell dator från avbildningsversion](https://azure.microsoft.com/resources/templates/101-vm-from-sig/)
Mer information om delade avbildnings gallerier finns i [översikten](../virtual-machines/shared-image-galleries.md). Om du stöter på problem, se [Felsöka delade avbildnings gallerier](../virtual-machines/troubleshooting-shared-images.md).
|
C | UTF-8 | 3,296 | 3.921875 | 4 | [] | no_license | // 把较长的输入行 “折” 成短一些的两行或者多行,
// 折行的位置在输入行的第n列之前的最后一个非空格之后
// 要保证程序能够智能地处理输入行很长以及在指定的列前
// 没有空格或者制表符的情况
#include <stdio.h>
#define MAXCOL 10 // maximum column of input
#define TABINC 8 // tab increment size
char line[MAXCOL]; // input line
int exptab(int pos);
int findblnk(int pos);
int newpos(int pos);
void printl(int pos);
/* fold long input lines into two or more shorter lines */
void main() {
int c, pos;
pos = 0; // postition in the line
while ((c=getchar()) != EOF) {
line[pos] = c; // store current character
if (c == '\t') { // expand tab character
pos = exptab(pos);
} else if (c == '\n'){
printl(pos); // print current input line
pos = 0;
} else if (++pos >= MAXCOL) {
pos = findblnk(pos);
printl(pos);
pos = newpos(pos);
}
}
}
/* printl: print line until pos column */
void printl(int pos) {
int i;
for (i=0; i<pos; ++i) {
putchar(line[i]);
}
if (pos>0){ // any chars printed?
putchar('\n');
}
}
/* exptab: find blank`s position */
int exptab(int pos) {
line[pos] = ' '; /* tab is at least one blank */
for (++pos; pos < MAXCOL && pos % TABINC != 0; ++pos) {
line[pos] = ' ';
}
if (pos < MAXCOL) { // room left in current line
return pos;
} else { // current line is full
printl(pos);
return 0; // reset current position
}
}
/* findblnk: find blank`s position */
int findblnk(int pos) {
while (pos > 0 && line[pos] != ' ') {
--pos;
}
if (pos == 0) { // no blanks in the line?
return MAXCOL; //
} else { // at least one blank
return pos + 1; // position after the blank
}
}
/* newpos: rearrange line with new position */
int newpos(int pos) {
int i,j;
if (pos <= 0 || pos>=MAXCOL) {
return 0; // nothing to rearrange
} else {
i = 0;
for (j = pos; j < MAXCOL; ++j) {
line[i] = line[j];
++i;
}
return i; // new position in line
}
}
/* MAXCOL 是一个符号常量,它给出了输入行的折行位置,即输入行的第n列。
整型变量pos是程序再文本行中的当前位置。
程序将在输入行的每一处的第n列之前对该输入行折行.
这个程序将把制表符扩展为空格;每遇到一个换行符就把此前输入的文本打印出来
每当变量pos的值达到MAXCOL时,就会对输入行进行折叠
函数findblnk从输入行的pos处开始倒退着寻找一个空格(目前时保持折行位置的单词的完整)。
如果找到了一个空格符,它就返回紧跟在该空格符后面的那个位置的下标
如果没有找到空格,他就返回MAXCOL
函数printl打印输出从位置零到位置pos-1之间的字符
函数newpos调整输入行,它将把从位置pos开始的字符复制到下一个输出行的开始,然后再返回变量pos的新值 */ |
Markdown | UTF-8 | 13,273 | 3.375 | 3 | [] | no_license |
- [概述](#概述)
- [区间问题](#区间问题)
- [435.无重叠区间](#435无重叠区间)
- [452.用最少数量的箭引爆气球](#452用最少数量的箭引爆气球)
- [1024. 视频拼接](#1024-视频拼接)
- [跳跃游戏](#跳跃游戏)
- [55. 跳跃游戏](#55-跳跃游戏)
- [45. 跳跃游戏 II](#45-跳跃游戏-ii)
- [134. 加油站](#134-加油站)
- [135. 分发糖果](#135-分发糖果)
# 概述
- 贪心:**每一步都做出一个局部最优的选择,最终的结果就是全局最优**
- 贪心算法可以认为是**动态规划算法的一个特例**,相比动态规划,使用贪心算法需要满足更多的条件(贪心选择性质),但是效率比动态规划要高
- 特点:基本也都是求最值
# 区间问题
- https://labuladong.gitee.io/algo/3/28/102/
## 435.无重叠区间
> 题目
<div align="center" style="zoom:80%"><img src="./pic/435-1.png"></div>
- 这类题目一般先画图,然后分析题目,需要根据题意,进行某项规则的排序
- 排序可以为贪心做保证
- 分析:**求最少需要移除的区间数量<=====>互相不重叠的区间,最多有多少个**
- 贪心:
- 总目标:在不重叠的情况下,尽可能的多取
- 构造可贪心条件:根据end进行升序排序
- 贪心体现:**每次取可选区间(不会与已选区间重合的)最早结束的**
> 代码
```cpp
class Solution {
public:
struct cmp{
bool operator () (vector<int> &a, vector<int> b){
return a[1] < b[1];
}
};
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
// 1. 构造贪心条件
sort(intervals.begin(), intervals.end(), cmp());
// 记录已有多少个不重复区间
int res = 0;
while(i < intervals.size()){
++res;
int j = i+1;
// 过滤掉到可选区间之前的所有相交的区间
while(j < intervals.size() && intervals[i][1] > intervals[j][0])
++j;
// 2. 贪心体现:去当前能取区间的的最早结束的一个(排序已经保证该区间是能取到最早结束的)
i = j;
}
return intervals.size()-res;
}
};
```
## 452.用最少数量的箭引爆气球
> 题目
<div align="center" style="zoom:80%"><img src="./pic/452-1.png"></div>
- 分析:**求必须射出的最小弓箭数 <====> 互相不重叠的区间,最多有多少个**
- 互补重叠的区间 必须用一枪,其他重叠部门都可以在其他重叠的区间顺便打了
- 等同上面的解法
- 贪心:
- 总目标:求得 互相不重叠的区间,最多有多少个
- 贪心保证:按右边区间升序排序
- 贪心体现:每次取右边区间最小的,只要和该区间有重合的,都可以一枪打爆
```cpp
struct ops{
bool operator()(vector<int> v1,vector<int> v2){
return v1[1] < v2[1];
}
};
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
int i = 0;
int res = 0; // 记录当前未相交集合有多少个,因为最少有多少个气球需要被单独射击 <=====> i = 0;
// 找出最多的不相交区间,就是答案
// 1.先排序
sort(points.begin(),points.end(),ops());
//
while( i < points.size() ){
int j = i+1;
++res;
while( j < points.size() && points[j][0] <= points[i][1] ){
++j;
}
i = j;
}
return res;
}
};
```
## 1024. 视频拼接
- 参考:https://labuladong.gitee.io/algo/3/28/104/
<div align="center" style="zoom:80%"><img src="./pic/1024-1.png"></div>
- 贪心:**选取的片段最少(每次选取 片段的潜力最大)====>在选取区间的每一次选取要使得片段的结束点尽可能远**
- 总目标:选取的片段最少
- 贪心保证:按起点升序,终点降序
- (贪心体现)每一步:比较所有起点小于等去 clips[0][1] 的区间,根据贪心策略,它们中**终点最大的那个区间就是第二个会被选中的视频**
<div align="center" style="zoom:80%"><img src="./pic/1024-2.png"></div>
```cpp
class Solution {
public:
struct cmp{
bool operator()(vector<int> &a, vector<int> &b){
if( a[0] < b[0]){
return true;
}else if( a[0] == b[0]){
return a[1] > b[1];
}else{
return false;
}
}
};
int videoStitching(vector<vector<int>>& clips, int time) {
sort(clips.begin(), clips.end(), cmp());
for(auto a : clips){
cout << a[0] << " " << a[1] << endl;
}
int curRight = 0; // 决定下一个可选区间(,curRight]
int res = 0; // 记录选择视频的个数
int nextRight = 0; // 记录在当前可选区间中,最优潜力的点的结束时间
int i = 0; // 遍历
while(i < clips.size() && clips[i][0] <= curRight){
// 在第 res 个视频区间内,贪心选择下一个视频
while(i <clips.size() && clips[i][0] <= curRight){
nextRight = max(nextRight, clips[i][1]);
++i;
}
++res;// 找到视频,更新结果
curRight = nextRight;
if(curRight >= time){
return res;
}
}
return -1;
}
};
```
# 跳跃游戏
## 55. 跳跃游戏
- 分析:**能不能到达最后一个下标 <=====> 能跳跃的最大长度是不是超过了最后一个下标,即求能跳跃的最大长度**
- 贪心:
- 总目标:求能跳跃的最大长度,记为 Fast,通过局部最优最终要求得该全局最优。
- 可选区间:从当前位置跳跃,所能到达的区间为可选区间
- (贪心本质,局部最优)每一步:选取所能到达的point,潜力最大的(即可以跳最远的)
- 限制:
- `i <= Fast`
<div align="center" style="zoom:80%"><img src="./pic/55-1.png"></div>
```cpp
class Solution {
public:
bool canJump(vector<int>& nums) {
int fast = 0;// 记录能跳到的最远距离,全局最优
int i = 0;
while(i < nums.size()){
if(i > fast)
return false;
// 计算局部最优,更新全局最优
fast = max(fast, i+nums[i]);
++i;
}
return fast >= nums.size() -1;
}
};
```
## 45. 跳跃游戏 II
<div align="center" style="zoom:80%"><img src="./pic/45-1.png"></div>
- 分析:**保证可以到达最后一个位置,问最少需要跳几次 <===> 每次跳跃跳到潜力最大的一个,就可以保证跳最少次**
- 贪心:
- 总目标:全局最优记为res,即跳跃的最小次数;每一次跳跃都跳到潜力最大的point,最终得到的结果就是跳跃的最小次数
- 可选区间:从当前位置跳跃,可以跳到的区间
- (贪心体现,局部最优)每一步:每一次选取可选区间中**潜力最大的为下一跳**(也就是说,**从当前位置跳跃到的那个点,在当前能跳跃到的所有点当中,能跳的更远**)
- 限制:
- 计算下一跳 跳的多远的时候,如果算到了结果,直接返回
```cpp
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size() == 1) return 0;
int fastNext = 0; // 下一跳的最远位置
int fastCur; // 当前跳的最远位置
int res = 0; // 结果
int i = 1; // (cur, fastCur]试探位置
fastCur = 0 + nums[0];
if(fastCur >= nums.size()-1)
return res+1;
while(i < nums.size()-1){
if(i > fastCur){
// 在(cur, fastCur] 之间选择一跳
++res;
fastCur = fastNext;
}
fastNext = max(fastNext,nums[i] + i);
++i;
if(fastNext >= nums.size()-1){
// 说明再经两跳就能到达结果, cur -第一跳-> i -第二跳-> dst
return res+2;
}
}
return res;
}
};
```
> labuladong 解法
```cpp
int jump(int[] nums) {
int n = nums.length;
int end = 0; // 记录当前可选区间
int farthest = 0; // 计算最大潜力
int jumps = 0; // 当前跳跃次数
for (int i = 0; i < n - 1; i++) {
farthest = Math.max(nums[i] + i, farthest);
if (end == i) {
jumps++;
end = farthest;
}
}
return jumps;
}
```
<div align="center" style="zoom:80%"><img src="./pic/45-2.png"></div>
# 134. 加油站
- 不是严格的贪心,倒像是利用了数学性质
<div align="center" style="zoom:80%"><img src="./pic/134-1.png"></div>
- 将 `gas[i] - cost[i]` 作为经过站点 i 的油量变化值,题目描述的场景就被抽象成了一个环形数组,数组中的第 i 个元素就是 `gas[i] - cost[i]`。
- **如果把这个「最低点」作为起点,就是说将这个点作为坐标轴原点,就相当于把图像「最大限度」向上平移了**
<div align="center" style="zoom:80%"><img src="./pic/134-3.png"></div>
<div align="center" style="zoom:80%"><img src="./pic/134-2.png"></div>
<div align="center" style="zoom:80%"><img src="./pic/134-4.png"></div>
<div align="center" style="zoom:80%"><img src="./pic/134-5.png"></div>
- 假设油量为 tank, 则 `tank += gas[i] - cost[i]`,需要保证大于0,如果小于0,则表示没油了
- 性质:
- 如果 gas_sum >= cost_sum,肯定有解(即使得tank都在x轴上方就行了);如果gas_sum <= cost_sum,肯定无解
- 如果从i开到j之后就开不动了(tank < 0),则从[i,j)之间的哪个个点出发都是开不到j的。
> 数学性质解法_找极小值
```cpp
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int minPoint=-1; // 注意,设置为-1
int minVal=0;
int tank = 0;
for(int i = 0; i <gas.size(); ++i){
tank += gas[i]-cost[i];
if(tank < minVal){
minVal = tank;
minPoint = i;
}
}
if(tank < 0) return -1;
else return minPoint+1;
}
};
```
> 贪心解法
- 贪心:能否开到 ===> 是不是能保证整个过程tank > 0
- (贪心体现)每一步:都得保证 `tank += gas[i] - cost[i] >=0`,如果不行,以 i+1 作为新的start
- 难点:最难的就是理解为什么选了新起点,遍历到数组尾部就够了,而不用循环遍历
- 利用了数学上的性质。
```cpp
int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += gas[i] - cost[i];
}
if (sum < 0) {
// 总油量小于总的消耗,无解
return -1;
}
// 记录油箱中的油量
int tank = 0;
// 记录起点
int start = 0;
for (int i = 0; i < n; i++) {
tank += gas[i] - cost[i];
if (tank < 0) {
// 无法从 start 走到 i
// 所以站点 i + 1 应该是起点
tank = 0;
start = i + 1;
}
}
return start == n ? 0 : start;
}
```
# 135. 分发糖果
<div align="center" style="zoom:80%"><img src="./pic/135.png"></div>
- 贪心:
- 贪心保证:减少规则。将题目规则拆分为 **左规则和右规则**,假设A在B的左边,A、B
- 左规则:rating_B > rating_A,B的糖比A多
- 右规则:rating_A < rating_B,A的糖比B多
- 贪心本质:
- 对于左规则:总目标为给的糖果最少。在满足左规则下,每个学生的最少糖果数leftCount[]
- 先给所有学生1颗糖
- 贪心体现:如果右边比左边分数高,则右边比左边多1颗,
- 对于右规则:总目标为给的糖果最少。在满足右规则下,每个学生的最少糖果数rightCount[]
- 先给所有学生1颗糖
- 贪心体现:如果左边比右边分数高,则左边比右边多1颗,
- 归并结果:`res[i] = max(leftCount[i], rightCount[i])`
```cpp
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> left,right;
int res = 0;
left.resize(ratings.size());
right.resize(ratings.size());
int i=1;
left[0] = 1;
for(; i < ratings.size(); ++i){
if(ratings[i-1] < ratings[i]){
left[i] = left[i-1]+1;
}else{
// ratings[i-1] >= ratings[i]
left[i] = 1;
}
}
i = ratings.size()-2;
right[ratings.size()-1] = 1;
for(; i >=0 ; --i){
if(ratings[i] > ratings[i+1]){
right[i] = right[i+1]+1;
}else{
// ratings[i-1] >= ratings[i]
right[i] = 1;
}
}
// 归并,取最大
for(int i = 0; i < ratings.size(); ++i){
res += max(left[i], right[i]);
}
return res;
}
};
``` |
C++ | UTF-8 | 3,378 | 3.203125 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <string>
#include <windows.h>
#include <stdio.h>
using namespace std;
string Input_Inf_Str(int &str) // метод ввода неопределенного количества строк
{
string s, result; // s - буферная строка, в нее читаем информацию с клавиатуры
//result - итоговая строка, скомпилированная из всех полученных строк в S
cout << "Для прекращения ввода символов необходимо нажать CTRL + Z или 2 раза на клавишу Enter" << '\n';
while ((getline(cin, s)) && (s.length()) > 0) // считываем символы
{
result += s + '\n';
str++; // счетчик строк
}
return result; // возвращается скомпилированная строка
}
string Get_Str(string s, int N) // метод получения строки по номеру строки
{
int i = 0; // количество разделителей
string buffer; // строка, вытаскиваемая по своему номеру
const char *result = (s.c_str()); // Указатель на начало строки s
while (i != N) // пока не встретится разделитель указанное число раз
{
while (*result != '\n') // ищется разделитель
{
if (i == N - 1) // если последующая итерация - последняя
buffer += *result; // собирается строка, взятая по номеру
*result++; // Переход к следующему символу
}
*result++; // Переход к следующему символу
i++; // Увеличивается счетчик разделителей
}
return buffer; // возвращается выбранная строка
}
void Sort_Strok(string *s, int N) // метод сортировки строк
{
for (int i = 0; i < N - 1; i++)
for (int j = i + 1; j < N; j++)
{
if (strcmp(s[i].c_str(), s[j].c_str()) > 0) // strcmp() осуществляет лексикографическую проверку двух строк, оканчивающихся нулевыми символами
// c_str() возвращает указатель на const char для того, что она может вернуть указатель на копию строки
swap(s[i], s[j]); // swap() обменивает значения своих аргументов
}
}
int main()
{
setlocale(LC_ALL, "Russian");
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
int str = 0;
string Current_Str = Input_Inf_Str(str);
cout << "Ввод данных закончен\n\n";
string *s = new string[str];
for (int i = 0; i < str; i++)
{
s[i] = Get_Str(Current_Str, i + 1); // заполняется массив строками
}
Sort_Strok(s, str); // сортируется массив
for (int i = 0; i < str; i++)
{
cout << s[i] << "\n";
}
cin.ignore();
delete[]s;
return 0;
}
// Если прога не работает с русскими символами, то в свойствах консоли надо поменять шрифт на
// Lucida Console |
Markdown | UTF-8 | 8,127 | 2.71875 | 3 | [] | no_license | Title: Release Management
Description: Create managed continuous deployment pipelines to release quickly, easily, and often
ms.TocTitle: Release
ms.ContentId: 008EE4E4-26E4-4A18-B60D-CD74106834DC
# Release Management
Manage the release of your app by deploying it to a specific
environment for each separate release step, and by controlling
the process through approvals for each step.


**Important**: _The topics below cover three different versions of Release Management._
* _If you are using the server and client version of Release
Management in Visual Studio 2015 and Team Foundation Server 2015, see
**[this section](#ver2015)** for more information._
* _If you are using the server and client version of Release
Management in Visual Studio 2013 and Team Foundation Server 2013, see
**[this section](https://msdn.microsoft.com/library/dn217874%28v%3Dvs.120%29.aspx)**
for more information._
* _If you are using the "vNext" version of Release Management as a
service in Visual Studio Online and in Team Foundation Server 2015,
see **[this section](#linklist)** for more information._
<a name="ver2015"></a>
## Release Management 2015 (server and client version)
* **[Overview](previous-version/release-management-overview.md)**
- [Install Release Management](previous-version/install-release-management.md)
* [System requirements for Release Management](previous-version/install-release-management/system-requirements.md)
* [Install Release Management server and client](previous-version/install-release-management/install-server-and-client.md)
* [Install deployment agents](previous-version/install-release-management/install-deployment-agent.md)
* [Connect Release Management to TFS](previous-version/install-release-management/connect-to-tfs.md)
- [Manage users, groups, and permissions](previous-version/add-users-and-groups.md)
* **[Manage your release](previous-version/manage-your-release.md)**
- [Release without deployment agents](previous-version/release-without-agents.md)
- [Release with deployment agents](previous-version/release-with-agents.md)
- [Trigger a release from a build](previous-version/trigger-a-release.md)
- [Deploy continuously to Azure](previous-version/deploy-continuously-to-azure.md)
- [Release actions to deploy an app](previous-version/release-actions.md)
* [Tools for release actions](previous-version/release-actions/release-action-tools.md)
- [Configuration variables and system variables](previous-version/config-and-system-variables.md)
## Release Management 2013 (server and client version)
* See [Automate deployments with Release Management](https://msdn.microsoft.com/library/dn217874%28v%3Dvs.120%29.aspx)
<a name="vernext"></a>
## Release Management "vNext" preview version
The following sections contain guidance for using Release Management in
Visual Studio Online, and in Team Foundation Server 2015 when you have
installed the Release Management service.
Release Management is currently in preview, and you must apply
to join the **[preview program](getting-started/join-preview.md)** in
order to use it.


_This version of Release Management is available only to users who have
joined the preview program. Some topics and features may not yet be available._
<a name="linklist"></a>
### Getting started
* **[Understanding Release Management](getting-started/understand-rm.md)**
- [When should I use Release Management?](getting-started/understand-rm.md#whentouse)
- [Where do I start?](getting-started/understand-rm.md#wheretostart)
- [Where can I deploy?](getting-started/understand-rm.md#wheretodeploy)
- [What about continuous integration?](getting-started/understand-rm.md#contintegration)
- [What is a release pipeline?](getting-started/understand-rm.md#pipeline)
- [Where do I go next?](getting-started/understand-rm.md#wherenext)
* **[Release notes](getting-started/release-notes.md)**
- [What's new?](getting-started/release-notes.md#whatsnew)
- [Known issues](getting-started/release-notes.md#knownissues)
- [Getting support](getting-started/release-notes.md#help)
* **[Deploying your .Net apps to Azure](getting-started/deploy-dotnet-to-azure.md)**
- [To Azure websites](getting-started/deploy-dotnet-to-azure.md#website)
- [To Azure cloud services](getting-started/deploy-dotnet-to-azure.md#cloudservice)
- To Azure resource groups
* **Deploying your .Net apps to any cloud**
- To IIS web servers using MSDeploy
- To IIS web servers using DSC push
- To Docker containers
* **Deploying your Java apps to any cloud**
- To Linux servers using SSH
- To Chef environments
* **[Configuring agents](getting-started/configure-agents.md)**
- [Hosted pool of agents](getting-started/configure-agents.md#hostedpool)
- [Security of agent pools and queues](getting-started/configure-agents.md#security)
- [Installing an agent](getting-started/configure-agents.md#installing)
- [Configuring and selecting an agent](getting-started/configure-agents.md#configuring)
- Deploying to on-premises servers from VSO
- [Notes and troubleshooting](getting-started/configure-agents.md#notesandtrouble)
### Authoring release definitions
* **What to deploy? Understanding Artifacts**
- Artifacts from Team Build
- Artifacts from Jenkins
- Artifacts from on-premise Team Foundation Server
- Artifacts from Nuget repository
* **[Where to deploy? Understanding Environments](author-release-definition/understanding-environments.md)**
- [Environment options](author-release-definition/understanding-environments.md#enviromentoptions)
- Configuring environments
- [Environment templates](author-release-definition/understanding-environments.md#templates)
- [Cloning environments](author-release-definition/understanding-environments.md#cloneenvironment)
- [Approvals and approvers](author-release-definition/understanding-environments.md#approvers)
- [Configuration properties](author-release-definition/understanding-environments.md#configproperties)
* **[How to deploy? Understanding Tasks](author-release-definition/understanding-tasks.md)**
- [Out-of-the-box tasks](author-release-definition/understanding-tasks.md#outofboxtasks)
- [Service connections](author-release-definition/understanding-tasks.md#serviceconnections)
- [Pre-defined variables](author-release-definition/understanding-tasks.md#predefvariables)
- Rollback upon failure
* **[More about release definitions](author-release-definition/more-release-definition.md)**
- [Viewing and editing release definitions](author-release-definition/more-release-definition.md#viewedit)
- [Running tests during a release](author-release-definition/more-release-definition.md#runtests)
- [Securing releases and managing users](author-release-definition/more-release-definition.md#security)
- [Global configuration properties](author-release-definition/more-release-definition.md#globalconfig)
- Release versioning
- [Triggers](author-release-definition/more-release-definition.md#triggers)
### Managing releases
* **[Creating a release or a release-in-draft](managing-releases/create-release.md)**
- Manually from Release hub
- Manually from Build hub
- [Automatically on completion of a build](managing-releases/create-release.md#automaticbuild)
- By using REST API
- [Pausing or terminating a release](managing-releases/create-release.md#pauseterminate)
* **[Tracking a release](managing-releases/track-release.md)**
- [Understanding the overview and list of releases](managing-releases/track-release.md#overview)
- [Approving a release](managing-releases/track-release.md#approve)
- [Viewing release logs](managing-releases/track-release.md#viewlogs)
- Notifications
- [Redeploying after failure](managing-releases/track-release.md#redeploy)
[!INCLUDE [wpfver-support-shared](_shared/wpfver-support-shared.md)]
|
Java | UTF-8 | 6,586 | 2.0625 | 2 | [] | no_license | package by.slivki.trainings.rest;
import by.slivki.trainings.dao.jpa.Role;
import by.slivki.trainings.dao.jpa.RoleEnum;
import by.slivki.trainings.rest.mapper.ApplicationMapper;
import by.slivki.trainings.service.api.ApplicationService;
import by.slivki.trainings.service.api.UserService;
import by.slivki.trainings.util.UserHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;
import java.util.Locale;
@Controller
public class DefaultController {
@Autowired
private ApplicationService applicationService;
@Autowired
private ApplicationMapper applicationMapper;
@Autowired
private UserHelper userHelper;
@GetMapping("/")
public String home1() {
return getHomePage();
}
@GetMapping("/home")
public String getHomePage() {
UserDetails userDetails = userHelper.getCurrentUser();
GrantedAuthority admin = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_ADMIN).getRoleName());
GrantedAuthority trainer = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_TRAINER).getRoleName());
GrantedAuthority user = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_USER).getRoleName());
String page = "/home";
if (userDetails != null && userDetails.getAuthorities().contains(admin)) {
page = "/admin/applications";
} else if (userDetails != null && userDetails.getAuthorities().contains(trainer)) {
page = "/trainer/trainings";
} else if (userDetails != null && userDetails.getAuthorities().contains(user)) {
page = "/user/trainings";
}
return page;
}
@GetMapping("/signUp")
public String signUp() {
return "/signUp";
}
@GetMapping("/error")
public String error() {
return "/error/404";
}
@GetMapping("/applications/password")
public String applicationPassword() {
return "/applications/password";
}
@GetMapping("/applications/trainer")
public String applicationTrainer() {
return "/applications/trainer";
}
@GetMapping("/applications")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String applications() {
return "/admin/applications";
}
@GetMapping("/applications/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ModelAndView applicationById(@PathVariable int id, Locale locale) {
ModelAndView modelAndView = new ModelAndView("/admin/application");
modelAndView.addObject("application",
applicationMapper.toApplicationDto(applicationService.getApplicationById(id), locale)
);
return modelAndView;
}
@GetMapping("/users")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String users() {
return "/admin/users";
}
@GetMapping("/categories")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String categories() {
return "/admin/categories";
}
@GetMapping("/trainings")
public String trainings() {
UserDetails userDetails = userHelper.getCurrentUser();
GrantedAuthority admin = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_ADMIN).getRoleName());
GrantedAuthority trainer = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_TRAINER).getRoleName());
GrantedAuthority user = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_USER).getRoleName());
String page = "/home";
if (userDetails != null && userDetails.getAuthorities().contains(admin)) {
page = "/error/403";
} else if (userDetails != null && userDetails.getAuthorities().contains(trainer)) {
page = "/trainer/trainings";
} else if (userDetails != null && userDetails.getAuthorities().contains(user)) {
page = "/user/trainings";
}
return page;
}
@GetMapping("/trainings/create/")
@PreAuthorize("hasRole('ROLE_TRAINER')")
public String trainingToCreate() {
return "/trainer/create";
}
@GetMapping("/trainings/{id}")
public String trainingById(@PathVariable int id) {
UserDetails userDetails = userHelper.getCurrentUser();
GrantedAuthority admin = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_ADMIN).getRoleName());
GrantedAuthority trainer = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_TRAINER).getRoleName());
GrantedAuthority user = new SimpleGrantedAuthority(new Role(RoleEnum.ROLE_USER).getRoleName());
String page = "/home";
if (userDetails != null && userDetails.getAuthorities().contains(admin)) {
page = "/error/403";
} else if (userDetails != null && userDetails.getAuthorities().contains(trainer)) {
page = "/trainer/training";
} else if (userDetails != null && userDetails.getAuthorities().contains(user)) {
page = "/user/training";
}
return page;
}
@GetMapping("/trainings/edit/{id}")
@PreAuthorize("hasRole('ROLE_TRAINER')")
public String trainingToEditById() {
return "/trainer/edit/training";
}
@GetMapping("/user/trainings")
@PreAuthorize("hasRole('ROLE_USER')")
public String userTrainings() {
return "/user/mytrainings";
}
@GetMapping("/user/trainings/{id}")
@PreAuthorize("hasRole('ROLE_USER')")
public String userTrainingById() {
return "/user/mytraining";
}
@GetMapping("/user/reports")
@PreAuthorize("hasRole('ROLE_USER')")
public String reportsToUser() {
return "/user/reports";
}
@GetMapping("/reports")
@PreAuthorize("hasRole('ROLE_TRAINER')")
public String reportsToTrainer() {
return "/trainer/reports";
}
@GetMapping("/profile")
@PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_TRAINER')")
public String profile() {
UserDetails userDetails = userHelper.getCurrentUser();
if (userHelper.isRoleAuthority(userDetails, RoleEnum.ROLE_TRAINER)) {
return "/trainer/profile";
} else {
return "/user/profile";
}
}
} |
Java | UTF-8 | 7,046 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2004-2009 Tobias Gierke <tobias.gierke@code-sourcery.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.codesourcery.planning;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import de.codesourcery.planning.impl.AbstractJob;
import de.codesourcery.planning.impl.SimpleJob;
/**
* A job that has been assigned to a specific {@link IFactorySlot}.
*
* <pre>
* Jobs are always linked to the {@link IJobTemplate} they
* have been created from.
*
* Jobs come in two flavors:
*
* 1.) Simple jobs
*
* Simple jobs are jobs that do not depend on
* the completion of other jobs before they
* can be started.
*
* 2.) Complex jobs
*
* Complex jobs depend on the completion
* of AT LEAST one other job before they
* can be started.
*
* </pre>
* @author tobias.gierke@code-sourcery.de
* @see IFactorySlot#add(IJob, Date)
* @see SimpleJob
* @see SimpleJob
* @see AbstractJob
*/
public interface IJob
{
/**
* Comparator that compares to jobs by
* their start dates.
*/
public static Comparator<IJob> START_DATE_COMPARATOR = new Comparator<IJob>() {
@Override
public int compare(IJob o1, IJob o2)
{
return o1.getStartDate().compareTo( o2.getStartDate() );
}
};
/**
* A jobs processing status.
*
* @author tobias.gierke@code-sourcery.de
*/
public enum JobStatus {
/**
* A planned job that
* has not been finalized.
*/
PROSPECTIVE {
@Override
public boolean mayTransitionTo(JobStatus next)
{
return next == NOT_STARTED || next == CANCELLED;
}
},
/**
* A scheduled job
* that has not started yet.
*/
NOT_STARTED {
@Override
public boolean mayTransitionTo(JobStatus next)
{
return next == PENDING || next == CANCELLED;
}
},
/**
* A scheduled job
* that is currently running.
*/
PENDING {
@Override
public boolean mayTransitionTo(JobStatus next)
{
return next == CANCELLED || next == FINISHED;
}
},
CANCELLED {
@Override
public boolean mayTransitionTo(JobStatus next)
{
return false;
}
},
/**
* A scheduled job
* that has finished execution.
*/
FINISHED {
@Override
public boolean mayTransitionTo(JobStatus next)
{
return false;
}
};
public abstract boolean mayTransitionTo(JobStatus next);
}
public String getName();
/**
* Returns the {@link IJobTemplate} this job
* was created from.
*
* @return
*/
public IJobTemplate getTemplate();
/**
* Returns the jobs that need
* to be finished before this job can start.
* @return
*/
public List<IJob> getDependentJobs();
/**
* Adds a job that needs to finish
* before this job may start.
*
* @param job
*/
public void addDependentJob(IJob job);
/**
* Check whether this job depends
* upon completion of a given job.
* @param job
* @return
*/
public boolean dependsOn(IJob job);
/**
* Sets this job's status.
*
* @param status
*/
public void setStatus(JobStatus status);
/**
* Returns this job's status.
*
* @return
*/
public JobStatus getStatus();
/**
* Tests whether this job has a
* given status.
*
* @param s
* @return
*/
public boolean hasStatus(JobStatus... s);
/**
* Sets the starting date
* for this job.
*
* This method may <b>only</b>
* be invoked on simple jobs
* (since complex ones
* have a derived starting date).
*
* @param s
* @throws UnsupportedOperationException if this
* is a complex job.
*/
public void setStartDate(Date s);
/**
* Returns the date range this
* job covers.
*
* @return daterange( getStartDate() , getEndDate() )
*/
public DateRange getDateRange();
/**
* Returns the earliest starting date
* of this job.
*
* For simple jobs, this is their
* assigned start date , for
* complex jobs this is the latest
* earliest finishing date
* of all jobs this job depends on.
*
* @return
*/
public Date getEarliestStartDate();
/**
* Returns the earliest finishing date
* of this job.
*
* For simple jobs, this is always
* ( startDate + duration ) ,
* for complex jobs
* this is the latest
* earliest finishing date
* of all jobs this job depends on
* plus the duration of THIS job.
*
* @return
*/
public Date getEarliestFinishingDate();
/**
* Returns the starting date for this job.
*
* For simple jobs, this method
* returns the assigned starting date.
* For complex jobs, this method returns the
* latest earliest finishing date
* of all jobs this job depends on.
*
* @return
* @see #getEarliestStartDate()
* @see #getEarliestFinishingDate()
*/
public Date getStartDate();
/**
* Returns the duration of THIS job.
*
* The returned value does <b>NOT</b>
* include the duration of
* any jobs this job depends on. Use
* {@link #getTotalDuration()} to
* get this.
*
* @return this job's duration. Be careful,
* jobs <b>MAY</b> return an {@link Duration#UNKNOWN}
* as well !!
*
* @see Duration#isUnknown()
*/
public Duration getDuration();
/**
* Returns the end date of this job.
*
* @return getStartDate() + getDuration()
*/
public Date getEndDate();
/**
* Returns the total duration of this job.
*
* The returned value does include duration
* of all jobs this job depends on.
*
* @return this job's total duration. Be careful,
* jobs <b>MAY</b> return an {@link Duration#UNKNOWN}
* as well !!
*
* @see Duration#isUnknown()
*/
public Duration getTotalDuration();
/**
* Returns the duration left for this
* job after a given date.
*
* <pre>
* this.earliestFinishingDate < startDate: Duration.ZERO
* this.earliestStartDate > startDate: Duration.ZERO
* this.earliestStartDate <= startDate <= this.earliestFinishingDate: Duration( earliestFinishingDate - startDate )
* </pre>
* @param startDate
* @return
*/
public Duration getDurationFrom(Date startDate);
/**
* Returns the amount of time this job
* will be running within a given date range.
*
* @param startDate
* @param endDate
* @return
*/
public Duration getDurationWithin(Date startDate,Date endDate);
/**
* Sets the number of runs for this job.
*
* @param runs Number of runs, must be >=1
*/
public void setRuns(int runs);
/**
* Returns the number of runs for this job.
* @return
*/
public int getRuns();
/**
* Check whether this job runs at a given date.
* @param date
* @return
*/
public boolean runsAt(Date date);
}
|
Shell | UTF-8 | 325 | 3.21875 | 3 | [
"MIT"
] | permissive | #!/bin/bash
# Counts the number of backup points in a repo
while getopts u:r:p: option
do
case "${option}"
in
u) USER=${OPTARG};;
r) REPO=${OPTARG};;
p) PASSWORD=${OPTARG};;
esac
done
export BORG_PASSPHRASE=$PASSWORD
export BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK=YES
/usr/bin/borg list /home/$USER/$REPO | wc -l
|
Java | UTF-8 | 216 | 1.804688 | 2 | [] | no_license | package org.projectshop.pojo;
import java.util.Date;
public class MoviceType extends BasePojo {
private String type;
private Date createDate;
public String getType() {
return type;
}
} |
Swift | UTF-8 | 3,652 | 2.703125 | 3 | [] | no_license | //
// ViewController.swift
// YelpQuiz
//
// Created by Георгий Иванов on 25.05.17.
// Copyright © 2017 George Ivanov. All rights reserved.
//
import UIKit
import GoogleMaps
import CoreLocation
class ViewController: UIViewController, GMSMapViewDelegate {
var locationManager = CLLocationManager()
var businesses: [Business]!
let iconImage = UIImage(named: "logo")
override func loadView() {
// Setting up GMS
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 15)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.isMyLocationEnabled = true
mapView.delegate = self
//setting zoom range
mapView.setMinZoom(15, maxZoom: 30)
view = mapView
}
override func viewDidLoad() {
super.viewDidLoad()
//getting user location and setting it on map
if CLLocationManager.authorizationStatus() == .notDetermined {
self.locationManager.requestWhenInUseAuthorization()
}
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
//checking if location if avilable and moving camera to current location
if locationManager.location != nil {
let mapView = view as! GMSMapView
let target = CLLocationCoordinate2D(latitude: (locationManager.location?.coordinate.latitude)!, longitude: (locationManager.location?.coordinate.longitude)!)
mapView.camera = GMSCameraPosition(target: target, zoom: 15, bearing: 0, viewingAngle: 0)
}
}
//func that adds new POI based on coordinates
func updatePointOfInterest(latitude: Double,longitude:Double) {
Business.searchWithLocation(latitude: latitude, longitude: longitude) { (businesses: [Business]?, error: Error?) -> Void in
self.businesses = businesses
if let businesses = businesses {
for business in businesses {
print("\(business.name!) added on map!")
let info = "\(business.address!)\nRaing: \(business.rating!)/5\nTap to open more.."
self.placeMarker(tittle: business.name!, snippet: info, URL: business.url!, position: business.coordinates!)
}
}
}
}
//func that place a marker on a map
func placeMarker(tittle: String, snippet: String, URL: URL, position: CLLocationCoordinate2D) {
let marker = GMSYelpMarker()
marker.position = position
marker.title = tittle
marker.snippet = snippet
marker.yelpUrl = URL
marker.icon = iconImage
marker.map = view as? GMSMapView
}
//called after camera finished moving or scrolling
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
//reloading markers on map
updatePointOfInterest(latitude: position.target.latitude, longitude: position.target.longitude)
}
//called after mapView item been tapped to open webwindow with more
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
//this func works only with original class GMSMarker, so we downcast it to GMSYelpMarker here
if let yelpMarker = marker as? GMSYelpMarker {
if yelpMarker.yelpUrl != nil {
UIApplication.shared.open(yelpMarker.yelpUrl!, options: [:], completionHandler: nil)
}
}
}
}
|
Swift | UTF-8 | 3,585 | 4.46875 | 4 | [] | no_license | import UIKit
/**
Object = Data + Method
Object = Structure, Class
Data = Property
Method = Method
Structure vs. Class
value Types Reference Types
Copy Share
Stack Heap
Fast Slow
RAM
--- Stack vs. Heap
Fast Slow
Stack: 시스템에서 당장 실행해야하거나 타이트하게 컨트롤 및 매니징해야하는 것들은 Stack에서 주로 처리.ex) 함수
--> 효율적이고 빠르다.
Heap: 시스템에서 클래스같은 Reference Type을 저장하는데에 주로 사용. 큰 메모리 풀. 동적으로 할당 가능. Stack 처럼 자동으로 메모리를 제거하지 않으므로 직접 제거 해주어야 함.
하지만 크게 신경 쓰지 않도록 xCode 같은 곳에서 지원 중.
--> 조금 복잡하고 구조적으로 간단하지 않으므로 Stack 보다는 느리다.
- 실제 생성된 class 인스턴스는 Heap에 있고 이 것을 할당 받은 변수 그 자체는 Stack 공간에 생성이 된다. 이 변수는 주소를 가지고 있다.
--- mutating은 Struct에서만 사용한다!
*/
/**
Struct vs. Class
언제, 무엇을 쓸까?
---- Struct
1. 두 object를 "같다, 다르다" 로 비교해야 하는 경우
2. Copy된 각 객체들이 독립적인 상태를 가져야 하는 경우
3. 코드에서 오브젝트의 데이터를 여러 스레드 걸쳐 사용할 경우
--> value type의 경우 인스턴스가 유니크 하다. 그래서 여러 스레드에 걸쳐 사용할 때 안전하게 사용 가능.
한 객체에 여러 스레드가 접근하면 충돌이 일어난다.
---- Class
1. 두 object의 인스턴스 자체가 같음을 확인해야 할 때
2. 하나의 객체가 필요하고, 여러 대상에 의해 접근되고 변경이 필요한 경우
--> iOS에서는 UI App 객체는 유일한 객체인데 여러 Object가 접근을 해야하는 경우이다.
==>
1. 일단 Struct로 쓰자. 후에 Class로 변경이 필요하면 그 때 바꾸자.
- Swift는 Struct를 좋아한다.
*/
struct PersonStruct {
var firstName: String
var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
var fullName: String {
return "\(firstName) \(lastName)"
}
// mutating은 Struct에서만 사용.
mutating func uppercaseName() {
firstName = firstName.uppercased()
lastName = lastName.uppercased()
}
}
class PersonClass {
var firstName: String
var lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
var fullName: String {
return "\(firstName) \(lastName)"
}
func uppercaseName() -> Void {
self.firstName = firstName.uppercased()
self.lastName = lastName.uppercased()
}
}
var personStruct1 = PersonStruct(firstName: "SeongHyeon", lastName: "Lim")
var personStruct2 = personStruct1
var personClass1 = PersonClass(firstName: "Hyeon", lastName: "Lim")
var personClass2 = personClass1
personStruct2.firstName = "Jay"
personStruct1.firstName
personStruct2.firstName
personClass2.firstName = "Jay"
personClass1.firstName
personClass2.firstName
personClass2 = PersonClass(firstName: "Bob", lastName: "Sponge")
personClass1.firstName
personClass2.firstName
personClass1 = personClass2
personClass1.firstName
personClass2.firstName
|
Java | UTF-8 | 2,657 | 2.28125 | 2 | [] | no_license | package swing;
import edu.wis.jtlv.env.Env;
import edu.wis.jtlv.env.module.SMVModule;
import edu.wis.jtlv.env.spec.Spec;
import edu.wis.jtlv.lib.AlgExceptionI;
import edu.wis.jtlv.lib.mc.LTL.LTLModelCheckAlg;
import edu.wis.jtlv.lib.mc.RTCTLK.TextRTCTLModelCheckAlg;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Run {
public void smvRun(TextEditor currentText) throws AlgExceptionI {
String src=currentText.contralPanel.fileOperation.getPath();
String name=currentText.contralPanel.fileOperation.getFileName();
String url=src+name+".smv";
Env.resetEnv();
try {
Env.loadModule(url);
} catch (IOException e) {
e.printStackTrace();
return;
}
SMVModule main = (SMVModule) Env.getModule("main");
main.setFullPrintingMode(true);
currentText.jtext.setText(currentText.jtext.getText().toString()+"\n========= DONE Loading Modules ============");
String parse=GetProperty(currentText.text.getText().toString());
System.out.println("parse---"+parse);
Spec[] all_specs = Env.loadSpecString(parse);
currentText.jtext.setText(currentText.jtext.getText().toString()+"\n========= DONE Loading Specs ============");
for (int i = 0; i < all_specs.length; i++)
if (all_specs[i].isCTLSpec()||all_specs[i].isRTCTLSpec()||all_specs[i].isCTLKSpec()||all_specs[i].isRTCTLKSpec())
{
TextRTCTLModelCheckAlg checker = new TextRTCTLModelCheckAlg(main,all_specs[i]);
checker.SetText(currentText.jtext);
checker.preAlgorithm();
//System.out.println(i+checker.doAlgorithm().resultString());
currentText.jtext.setText(currentText.jtext.getText().toString()+"\n"+i+checker.doAlgorithm().resultString());
}
else if (all_specs[i].isLTLSpec()||all_specs[i].isRTLTLSpec()||all_specs[i].isRTLTLKSpec())
{
LTLModelCheckAlg checker = new LTLModelCheckAlg(main,all_specs[i]);
checker.preAlgorithm();
//System.out.println(i+checker.doAlgorithm().resultString());
currentText.jtext.setText(currentText.jtext.getText().toString()+"\n"+i+checker.doAlgorithm().resultString());
}
}
public String GetProperty(String spec) {
String ms=spec.replaceAll("[-]+[\\s\\S&&[^\n]]*[\r\n]+", "");
String regEx = "(CTLSPEC|LTLSPEC|SPEC)[\\s\\S&&[^\n]]*\\;[\\s]*$";
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx,Pattern.MULTILINE); ;
Matcher matcher = pattern.matcher(ms);
ArrayList<String> tempList = new ArrayList<String>();
while(matcher.find()){
tempList.add(matcher.group());
}
String s="";
for(String temp : tempList){
s=s + temp;
}
return s;
}
}
|
PHP | UTF-8 | 8,976 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
//
// Description
// ===========
// This method will return all the information about an market.
//
// Arguments
// ---------
// api_key:
// auth_token:
// tnid: The ID of the tenant the seller is attached to.
// market_id: The ID of the market to get the details for.
//
// Returns
// -------
//
function ciniki_marketplaces_marketSellerGet($ciniki) {
//
// Find all the required and optional arguments
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'prepareArgs');
$rc = ciniki_core_prepareArgs($ciniki, 'no', array(
'tnid'=>array('required'=>'yes', 'blank'=>'no', 'name'=>'Tenant'),
'seller_id'=>array('required'=>'yes', 'blank'=>'no', 'name'=>'Seller'),
'items'=>array('required'=>'no', 'blank'=>'no', 'name'=>'Items'),
));
if( $rc['stat'] != 'ok' ) {
return $rc;
}
$args = $rc['args'];
//
// Make sure this module is activated, and
// check permission to run this function for this tenant
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'marketplaces', 'private', 'checkAccess');
$rc = ciniki_marketplaces_checkAccess($ciniki, $args['tnid'], 'ciniki.marketplaces.marketSellerGet');
if( $rc['stat'] != 'ok' ) {
return $rc;
}
$modules = $rc['modules'];
//
// Load the tenant intl settings
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'tenants', 'private', 'intlSettings');
$rc = ciniki_tenants_intlSettings($ciniki, $args['tnid']);
if( $rc['stat'] != 'ok' ) {
return $rc;
}
$intl_timezone = $rc['settings']['intl-default-timezone'];
$intl_currency_fmt = numfmt_create($rc['settings']['intl-default-locale'], NumberFormatter::CURRENCY);
$intl_currency = $rc['settings']['intl-default-currency'];
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbQuote');
ciniki_core_loadMethod($ciniki, 'ciniki', 'users', 'private', 'dateFormat');
$date_format = ciniki_users_dateFormat($ciniki);
//
// Load marketplaces maps
//
ciniki_core_loadMethod($ciniki, 'ciniki', 'marketplaces', 'private', 'maps');
$rc = ciniki_marketplaces_maps($ciniki, $modules);
if( $rc['stat'] != 'ok' ) {
return $rc;
}
$maps = $rc['maps'];
//
// Get the seller details
//
$strsql = "SELECT ciniki_marketplace_sellers.id, "
. "ciniki_marketplace_sellers.market_id, "
. "ciniki_marketplace_sellers.customer_id, "
. "ciniki_marketplace_sellers.status, "
. "ciniki_marketplace_sellers.status AS status_text, "
. "ciniki_marketplace_sellers.flags, "
. "ciniki_marketplace_sellers.flags AS flags_text, "
. "ciniki_marketplace_sellers.num_items "
. "FROM ciniki_marketplace_sellers "
. "WHERE ciniki_marketplace_sellers.tnid = '" . ciniki_core_dbQuote($ciniki, $args['tnid']) . "' "
. "AND ciniki_marketplace_sellers.id = '" . ciniki_core_dbQuote($ciniki, $args['seller_id']) . "' "
. "";
ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbHashQueryTree');
$rc = ciniki_core_dbHashQueryTree($ciniki, $strsql, 'ciniki.marketplaces', array(
array('container'=>'sellers', 'fname'=>'id', 'name'=>'seller',
'fields'=>array('id', 'market_id', 'customer_id', 'status', 'status_text', 'flags', 'flags_text', 'num_items'),
'maps'=>array('status_text'=>$maps['seller']['status'], 'flags_text'=>$maps['seller']['flags']),
),
));
if( $rc['stat'] != 'ok' ) {
return $rc;
}
if( !isset($rc['sellers']) || !isset($rc['sellers'][0]) ) {
return array('stat'=>'fail', 'err'=>array('code'=>'ciniki.marketplaces.12', 'msg'=>'Unable to find seller'));
}
$seller = $rc['sellers'][0]['seller'];
//
// If include customer information
//
if( $seller['customer_id'] > 0 ) {
ciniki_core_loadMethod($ciniki, 'ciniki', 'customers', 'hooks', 'customerDetails');
$rc = ciniki_customers_hooks_customerDetails($ciniki, $args['tnid'], array(
'customer_id'=>$seller['customer_id'],
'phones'=>'yes',
'emails'=>'yes',
'addresses'=>'yes',
'subscriptions'=>'no',
));
if( $rc['stat'] != 'ok' ) {
return $rc;
}
$seller['customer_details'] = $rc['details'];
}
//
// Get the items the seller has
//
if( isset($args['items']) && $args['items'] == 'yes' ) {
//
// Get the list of market items for a seller
//
$strsql = "SELECT ciniki_marketplace_items.id, "
. "ciniki_marketplace_items.code, "
. "ciniki_marketplace_items.name, "
. "ciniki_marketplace_items.type, "
. "ciniki_marketplace_items.category, "
. "ciniki_marketplace_items.price, "
. "ciniki_marketplace_items.fee_percent, "
. "DATE_FORMAT(ciniki_marketplace_items.sell_date, '" . ciniki_core_dbQuote($ciniki, $date_format) . "') AS sell_date, "
. "IF(ciniki_marketplace_items.sell_price=0, '', ciniki_marketplace_items.sell_price) AS sell_price, "
. "IF(ciniki_marketplace_items.tenant_fee=0, '', ciniki_marketplace_items.tenant_fee) AS tenant_fee, "
. "IF(ciniki_marketplace_items.seller_amount=0, '', ciniki_marketplace_items.seller_amount) AS seller_amount, "
. "ciniki_marketplace_items.notes "
. "FROM ciniki_marketplace_items "
. "WHERE ciniki_marketplace_items.tnid = '" . ciniki_core_dbQuote($ciniki, $args['tnid']) . "' "
. "AND ciniki_marketplace_items.seller_id = '" . ciniki_core_dbQuote($ciniki, $args['seller_id']) . "' "
. "ORDER BY code, name "
. "";
$rc = ciniki_core_dbHashQueryTree($ciniki, $strsql, 'ciniki.marketplaces', array(
array('container'=>'items', 'fname'=>'id', 'name'=>'item',
'fields'=>array('id', 'code', 'name', 'type', 'category',
'price', 'fee_percent', 'sell_date', 'sell_price', 'tenant_fee', 'seller_amount', 'notes')),
));
if( $rc['stat'] != 'ok' ) {
return $rc;
}
if( !isset($rc['items']) ) {
$seller['items'] = array();
} else {
$seller['items'] = $rc['items'];
$seller['item_totals'] = array('price'=>0, 'sell_price'=>0, 'tenant_fee'=>0, 'seller_amount'=>0);
foreach($seller['items'] as $iid => $item) {
$seller['items'][$iid]['item']['fee_percent'] = (float)$item['item']['fee_percent'];
if( $item['item']['price'] != '' ) {
$seller['items'][$iid]['item']['price'] = numfmt_format_currency($intl_currency_fmt,
$item['item']['price'], $intl_currency);
$seller['item_totals']['price'] = bcadd($seller['item_totals']['price'], $item['item']['price'], 4);
}
if( $item['item']['sell_price'] != '' ) {
$seller['items'][$iid]['item']['sell_price'] = numfmt_format_currency($intl_currency_fmt,
$item['item']['sell_price'], $intl_currency);
$seller['item_totals']['sell_price'] = bcadd($seller['item_totals']['sell_price'], $item['item']['sell_price'], 4);
}
if( $item['item']['tenant_fee'] != '' ) {
$seller['items'][$iid]['item']['tenant_fee'] = numfmt_format_currency($intl_currency_fmt,
$item['item']['tenant_fee'], $intl_currency);
$seller['item_totals']['tenant_fee'] = bcadd($seller['item_totals']['tenant_fee'], $item['item']['tenant_fee'], 4);
}
if( $item['item']['seller_amount'] != '' ) {
$seller['items'][$iid]['item']['seller_amount'] = numfmt_format_currency($intl_currency_fmt,
$item['item']['seller_amount'], $intl_currency);
$seller['item_totals']['seller_amount'] = bcadd($seller['item_totals']['seller_amount'], $item['item']['seller_amount'], 4);
}
}
$seller['item_totals']['price'] = numfmt_format_currency($intl_currency_fmt,
$seller['item_totals']['price'], $intl_currency);
$seller['item_totals']['sell_price'] = numfmt_format_currency($intl_currency_fmt,
$seller['item_totals']['sell_price'], $intl_currency);
$seller['item_totals']['tenant_fee'] = numfmt_format_currency($intl_currency_fmt,
$seller['item_totals']['tenant_fee'], $intl_currency);
$seller['item_totals']['seller_amount'] = numfmt_format_currency($intl_currency_fmt,
$seller['item_totals']['seller_amount'], $intl_currency);
}
}
return array('stat'=>'ok', 'seller'=>$seller);
}
?>
|
C# | UTF-8 | 701 | 2.609375 | 3 | [] | no_license | using RpgBE.Core.Model.Characters;
using RpgBE.Core.Model.Enums;
namespace RpgBE.Core.Model.Battles
{
public class BattleParticipant
{
public Character Character { get; private set; }
public Team Team { get; private set; }
public bool IsAlive
{
get { return Character.HealthPoints > 0; }
}
public double TicksToAction { get; set; }
public double Ticks { get; set; }
public BattleParticipant(Character character, Team team)
{
Character = character;
Team = team;
TicksToAction = 100.0 / (Character.Agility + 1);
Ticks = Character.Agility;
}
}
} |
Go | UTF-8 | 3,749 | 3 | 3 | [] | no_license | package pool
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTwoDimByteSlice(t *testing.T) {
var bs TwoDimByteSlice
{
bs.Grow(512, 10, 10)
assert.Equal(t, 0 , bs.Dim())
assert.Equal(t, 0 , len(bs.data))
assert.Equal(t, 512, cap(bs.data))
assert.Equal(t, 0 , len(bs.flat))
assert.LessOrEqual(t, 100, cap(bs.flat))
assert.Equal(t, 0 , len(bs.dim))
assert.Equal(t, 10, cap(bs.dim))
{
// dim 1
bs.NewDim()
bs.Append([]byte("a"))
bs.Append([]byte("b"))
bs.Append([]byte("c"))
bs.AppendConcat([]byte("d"), []byte("e"))
assert.Equal(t, 1 , bs.Dim())
assert.Equal(t, 4 , bs.Len(0))
assert.Equal(t, 9 , len(bs.data))
assert.Equal(t, 512, cap(bs.data))
assert.Equal(t, 4 , len(bs.flat))
assert.LessOrEqual(t, 100, cap(bs.flat))
}
{
// dim 2
bs.NewDim()
bs.Append([]byte("j"))
bs.Append([]byte("k"))
assert.Equal(t, 2 , bs.Dim())
assert.Equal(t, 2 , bs.Len(1))
assert.Equal(t, 13 , len(bs.data))
assert.Equal(t, 512, cap(bs.data))
assert.Equal(t, 6 , len(bs.flat))
assert.LessOrEqual(t, 100, cap(bs.flat))
}
{
// growing
bs.Grow(1024, 20, 20)
assert.Equal(t, 2 , bs.Dim())
assert.Equal(t, 13 , len(bs.data))
assert.Equal(t, 1024, cap(bs.data))
assert.Equal(t, 6 , len(bs.flat))
//assert.LessOrEqual(t, 400, cap(bs.flat)) // go机制限制不预留太多空间
assert.Equal(t, 2 , len(bs.dim))
assert.LessOrEqual(t, 20, cap(bs.dim))
}
var bs2 [50][]byte
{
// dim 1
s := bs.ToBytes(0, bs2[:0])
assert.Equal(t, 4, len(s))
assert.Equal(t, []byte("a") , s[0])
assert.Equal(t, []byte("b") , s[1])
assert.Equal(t, []byte("c") , s[2])
assert.Equal(t, []byte("de"), s[3])
}
{
// dim 2
s := bs.ToBytes(1, bs2[:0])
assert.Equal(t, 2, len(s))
assert.Equal(t, []byte("j") , s[0])
assert.Equal(t, []byte("k") , s[1])
}
assert.Equal(t, []byte("a") , bs.Index(0, 0))
assert.Equal(t, []byte("b") , bs.Index(0, 1))
assert.Equal(t, []byte("c") , bs.Index(0, 2))
assert.Equal(t, []byte("de"), bs.Index(0, 3))
assert.Equal(t, []byte("j") , bs.Index(1, 0))
assert.Equal(t, []byte("k") , bs.Index(1, 1))
}
bs.Reset()
assert.Equal(t, 0 , bs.Dim())
assert.Equal(t, 0 , len(bs.data))
assert.Equal(t, 1024, cap(bs.data))
assert.Equal(t, 0 , len(bs.flat))
//assert.LessOrEqual(t, 400, cap(bs.flat)) // go机制限制不预留太多空间
assert.Equal(t, 0 , len(bs.dim))
assert.Equal(t, 20 , cap(bs.dim))
}
func TestTwoDimByteSliceEmptyAndNil(t *testing.T) {
var bs TwoDimByteSlice
bs.NewDim()
bs.Append([]byte("0"))
bs.Append(nil)
bs.AppendConcat([]byte("2"), []byte("3"))
bs.AppendConcat(nil, nil)
assert.Equal(t, 4, bs.Len(0))
assert.Equal(t, []byte("0"), bs.Index(0, 0))
assert.Equal(t, false , bs.IsNil(0, 0))
assert.Equal(t, []byte(nil), bs.Index(0, 1))
assert.Equal(t, true , bs.IsNil(0, 1))
assert.Equal(t, []byte("23"), bs.Index(0, 2))
assert.Equal(t, false , bs.IsNil(0, 2))
assert.Equal(t, []byte(nil), bs.Index(0, 3))
assert.Equal(t, true , bs.IsNil(0, 3))
}
|
Markdown | UTF-8 | 1,558 | 3.203125 | 3 | [] | no_license | ## ITMD 361, Production Problem 2: HTML Validation
For this production problem, you will learn to pull changes from a remote Git repository and then work with the HTML Validator. Follow the steps below exactly in order to receive full credit.
1. Make sure that you have added the instructor’s repository as a second remote.
From your command line and within the `itmd-361-pp` directory, run the command:
$ git remote -v
You should see output something like this:
instructor https://github.com/profstolley/itmd-361-pp.git (fetch)
instructor https://github.com/profstolley/itmd-361-pp.git (push)
origin https://github.com/USERNAME/itmd-361-pp.git (fetch)
origin https://github.com/USERNAME/itmd-361-pp.git (push)
If you do not have the `instructor` remote, be sure to run the following command:
$ git remote add instructor https://github.com/profstolley/itmd-361-pp.git
** To receive the remaining week’s Production Problems **, you will always change into your
`itmd-361-pp` directory and run
$ git pull instructor master
2. Once you’ve pulled this week’s problem, you need to upload the `index.html` file to the W3C
HTML validator at http://validator.w3.org/
There are five errors in the HTML. Correct them one by one, starting with the first error in
the validator. After **each** correction, make a commit stating precisely what you fixed.
3. Finally, remember to push your work to your own Production Problems repository by running
$ git push origin master |
C++ | UTF-8 | 3,035 | 2.875 | 3 | [] | no_license | //
// Compressor.cpp
// TextCompression
//
// Created by Viet Nguyen on 12/4/16.
// Copyright © 2016 Viet Nguyen. All rights reserved.
//
#include "Compressor.hpp"
#include <cmath>
Compressor::Compressor(string filename, string tofile, vector<wchar_t> symbols, vector<string> codes)
{
fileSourse = filename;
fileTo = tofile;
for(int i = 0; i < symbols.size(); ++ i)
map.insert(pair<wchar_t, string>(symbols[i], codes[i]));
//reverse(map.begin(), map.end());
}
vector<bool> Compressor::getBits(wchar_t c)
{
string code = map[c];
vector<bool> result = *new vector<bool>;
for(int i = 0 ; i < code.size(); ++i)
result.push_back( code[i]=='1');
return result;
}
void Compressor::CreateHeader(ofstream & comp)
{
int size = (int)map.size(); //Write number of row in table
comp.write((char*)&size,sizeof(size));
for (auto i = map.begin() ; i != map.end(); ++i)
{
wchar_t c = (*i).first;
comp.write((char*)&c,sizeof(c));
int s = (int)(*i).second.size();
comp.write((char*)&s,sizeof(s));
}
int count = 0;
char buffer = 0;
for(auto i = map.begin() ; i != map.end(); ++i)
{
wchar_t s = (*i).first;
vector<bool> bits = getBits(s);
for(int i = 0; i < bits.size(); ++i)
{
buffer = buffer | (bits[i]? 1: 0) << (7 - count);
count++;
if (count == 8)
{
count = 0;
comp.put(buffer);
buffer = 0;
}
}
}
if(buffer != 0)
comp.put(buffer);
// comp.put(-1);
}
void Compressor::CompressText()
{
//Open sourse text file to get text
setlocale(LC_ALL, "ru_RU.UTF-8");
wifstream input (fileSourse);
#ifdef PREFER_BOOST
boost::locale::generator gen;
std::locale loc = gen("ru_RU.UTF-8");
#else
std::locale loc("ru_RU.UTF-8");
#endif
input.imbue(loc);
wcout.imbue(loc);
//Create new file
ofstream comp (fileTo, ofstream::binary);
CreateHeader(comp);
int count = 0;
int buffer = 0;
while (!input.eof())
{
unsigned wchar_t ch = input.get();
vector<bool> bits = getBits(ch);
for(int i = 0; i < bits.size(); ++i)
{
buffer = buffer | (bits[i]? 1: 0) << (7 - count);
count++;
if (count == 8)
{
comp.put(buffer);
buffer = 0;
count = 0;
}
}
}
//Adding pseudo EOF
vector<bool> bits = getBits(-1);
for(int i = 0; i < bits.size(); ++i)
{
buffer = buffer | (bits[i]? 1: 0) << (7 - count);
count++;
if (count == 8)
{
comp.put(buffer);
buffer = 0;
count = 0;
}
}
if(buffer != 0)
comp.put(buffer);
input.close();
comp.close();
}
|
Markdown | UTF-8 | 7,310 | 2.703125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: 'Självstudie: lägga till noder i ett Azure FXT Edge-kluster'
description: Lär dig hur du lägger till klusternoder till lagrings-cachen i Azure FXT Edge och aktiverar funktionen för hög tillgänglighet (HA).
author: ekpgh
ms.author: rohogue
ms.service: fxt-edge-filer
ms.topic: tutorial
ms.date: 06/20/2019
ms.openlocfilehash: 85ad78eeb095b427b1a6334f57c351e926022dff
ms.sourcegitcommit: f28ebb95ae9aaaff3f87d8388a09b41e0b3445b5
ms.translationtype: MT
ms.contentlocale: sv-SE
ms.lasthandoff: 03/29/2021
ms.locfileid: "96021885"
---
# <a name="tutorial-add-cluster-nodes-to-an-azure-fxt-edge-filer-cluster"></a>Självstudie: lägga till klusternoder i ett Azure FXT Edge-kluster
Ett nytt Azure FXT Edge-kluster skapas med bara en nod. Du bör lägga till minst två noder och aktivera hög tillgänglighet innan du gör en annan konfiguration.
I den här självstudien beskrivs hur du lägger till klusternoder och aktiverar funktionen hög tillgänglighet (HA).
I den här kursen lär du dig:
> [!div class="checklist"]
>
> * Så här lägger du till noder i FXT-klustret
> * Så här aktiverar du HA
Stegen i den här självstudien tar cirka 45 minuter att slutföra.
Innan du börjar den här självstudien kan du använda de noder som du vill lägga till och [Ange de ursprungliga lösen orden](fxt-node-password.md).
## <a name="1-load-the-cluster-nodes-page"></a>1. Läs in sidan klusternoder
Öppna klustrets kontroll panel i en webbläsare och logga in som administratör. (Detaljerade instruktioner finns i översikts artikeln under [Öppna sidan Inställningar](fxt-cluster-create.md#open-the-settings-pages).)
Fliken **instrument panel** visas på kontroll panelen när den öppnas.

Den här bilden visar instrument panelen för ett nyskapat kluster, med en enda nod.
## <a name="2-locate-the-node-to-add"></a>2. Leta upp noden som ska läggas till
Om du vill lägga till noder klickar du på fliken **Inställningar** och väljer sidan **FXT noder** i **kluster** avsnittet.

I **FXT-noderna** visas alla otilldelade FXT-noder (de flesta data Center har bara några. Hitta de FXT-noder som du vill lägga till i klustret.
> [!Tip]
> Om du inte hittar den nod som du vill använda i listan över **frånkopplade** , kontrollerar du att den uppfyller följande krav:
>
> * Den är påslagen och har fått en [rot lösen ords uppsättning](fxt-node-password.md).
> * Den är ansluten till ett nätverk som du har åtkomst till. Om du använder VLAN måste det finnas i samma VLAN som klustret.
> * Den kan identifieras med Bonjour-protokollet.
>
> Vissa brand Väggs inställningar blockerar TCP/UDP-portarna som används av Bonjour, vilket förhindrar att operativ systemet FXT identifierar noderna automatiskt.
>
> Om den nod som du vill lägga till inte finns med i listan kan du prova följande lösningar:
>
> * Klicka på knappen **manuell identifiering** för att hitta den via IP-adress.
>
> * Tilldela temporära IP-adresser manuellt. Detta är sällsynt men kan behövas om du använder taggade VLAN och noderna inte finns i rätt nätverk, eller om nätverket inte tillåter självtilldelade IP-adresser. Följ anvisningarna i den äldre versionen av det här dokumentet om du vill [Ange en statisk IP-adress manuellt](https://azure.github.io/Avere/legacy/create_cluster/4_8/html/static_ip.html).
Nodens namn, IP-adress, program varu version och status för berättigande visas i listan. Normalt säger kolumnen **status** "vill du ansluta" eller beskriver ett system-eller maskin varu problem som gör att noden inte är tillgänglig för att ansluta till klustret.
Kolumnen **åtgärder** innehåller knappar som låter dig lägga till noden i klustret eller uppdatera dess program vara. Uppdaterings knappen installerar automatiskt den program varu version som matchar noderna som redan finns i klustret.
Alla noder i ett kluster måste använda samma version av operativ systemet, men du behöver inte uppdatera program vara innan du lägger till en nod. När du klickar på knappen **Tillåt att ansluta** , kontrollerar kluster kopplings processen automatiskt och installerar den OS-programvara som matchar versionen i klustret.
Om du vill veta mer om alternativen på den här sidan kan du läsa [ **cluster** > **FXT-noder**](https://azure.github.io/Avere/legacy/ops_guide/4_7/html/gui_fxt_nodes.html) i guiden kluster konfiguration.
## <a name="3-click-the-allow-to-join-button"></a>3. Klicka på knappen "Tillåt att ansluta"
Klicka på knappen **Tillåt anslutning** _ i kolumnen _ *åtgärder** för den nod som du vill lägga till.
När du klickar på knappen kan nodens status ändras när dess program vara uppdateras i förberedelse för att lägga till den i klustret.
Bilden nedan visar en nod som håller på att ansluta till klustret (förmodligen hämtas en OS-uppdatering innan den läggs till). Inga knappar visas i kolumnen **åtgärder** för noder som håller på att läggas till i klustret.

Efter en liten stund ska den nya noden visas i listan över klusternoder överst på **FXT** -nodens inställnings sida.
Upprepa processen för att lägga till de andra noderna i klustret. Du behöver inte vänta på att en nod ska sluta ansluta till klustret innan du påbörjar en ny.
## <a name="enable-high-availability"></a>Aktivera hög tillgänglighet
När du har lagt till en andra nod i klustret kan du se ett varnings meddelande på kontroll panelens instrument panel att funktionen hög tillgänglighet inte har kon figurer ATS.
Hög tillgänglighet (HA) gör det möjligt för klusternoderna att kompensera för varandra om den ena slutar. HA är inte aktiverat som standard.

> [!Note]
> Aktivera inte HA förrän du har minst tre noder i klustret.
Följ den här proceduren för att aktivera HA:
1. Läs in sidan med **hög tillgänglighet** i **kluster** -avsnittet på fliken **Inställningar** .

2. Klicka på rutan **Aktivera ha** och klicka på knappen **Skicka** .
En avisering visas på **instrument panelen** för att bekräfta att ha Aktiver ATS.

## <a name="next-steps"></a>Nästa steg
När du har lagt till alla noder i klustret fortsätter du installationen genom att konfigurera klustrets långsiktiga lagring.
> [!div class="nextstepaction"]
> [Lägg till Server dels lagring och konfigurera det virtuella namn området](fxt-add-storage.md) |
Python | UTF-8 | 406 | 3.59375 | 4 | [
"MIT"
] | permissive | from __future__ import print_function
kPa = float(input("Input your pressure in kiloPascals: "))
psi = kPa / 6.89476
mmhg = kPa * 7.50062
atm = kPa / 101.325
atm2 = kPa * 0.00986923
print("The pressure in pounds per square inch: %.2f psi" % psi)
print("The pressure in millimeter of mercury: %.2f mmHg" % mmhg)
print("Atmosphere pressure: %.2f atm." % atm)
print("Atmosphere pressure: %.2f atm." % atm2)
|
C++ | UTF-8 | 3,156 | 2.71875 | 3 | [
"NIST-Software"
] | permissive | //
// Created by tjb3 on 10/30/19.
//
#ifndef HEDGEHOG_TUTORIALS_UNIFIED_MATRIX_BLOCK_DATA_H
#define HEDGEHOG_TUTORIALS_UNIFIED_MATRIX_BLOCK_DATA_H
#include <hedgehog/hedgehog.h>
#include "matrix_block_data.h"
template<class Type, char Id>
class UnifiedMatrixBlockData : public MatrixBlockData<Type, Id, Order::Column>,
public hh::ManagedMemory {
private:
size_t
ttl_ = 0;
cudaEvent_t
event_ = {};
bool releaseMemory_ = false;
bool eventCreated_ = false;
public:
UnifiedMatrixBlockData() : releaseMemory_(false){}
explicit UnifiedMatrixBlockData(size_t blockSize) : releaseMemory_(true) {
checkCudaErrors(cudaMallocManaged((void **) this->adressBlockData(), sizeof(Type) * blockSize * blockSize));
}
UnifiedMatrixBlockData(
size_t rowIdx, size_t colIdx,
size_t blockSizeHeight, size_t blockSizeWidth, size_t leadingDimension,
Type *fullMatrixData, Type *blockData)
: MatrixBlockData<Type, Id, Order::Column>(
rowIdx, colIdx,
blockSizeHeight, blockSizeWidth, leadingDimension,
fullMatrixData, blockData) {}
template<char OldId>
explicit UnifiedMatrixBlockData(UnifiedMatrixBlockData<Type, OldId> &o) {
this->rowIdx_ = o.rowIdx_;
this->colIdx_ = o.colIdx_;
this->blockSizeHeight_ = o.blockSizeHeight_;
this->blockSizeWidth_ = o.blockSizeWidth_;
this->leadingDimension_ = o.leadingDimension_;
this->fullMatrixData_ = o.fullMatrixData_;
this->blockData_ = o.blockData_;
}
template<char OldId>
explicit UnifiedMatrixBlockData(std::shared_ptr<UnifiedMatrixBlockData<Type, OldId>> &o) {
this->rowIdx_ = o->getRowIdx();
this->colIdx_ = o->getColIdx();
this->blockSizeHeight_ = o->getBlockSizeHeight();
this->blockSizeWidth_ = o->getBlockSizeWidth();
this->leadingDimension_ = o->getLeadingDimension();
this->fullMatrixData_ = o->getFullMatrixData();
this->blockData_ = o->getBlockData();
}
virtual ~UnifiedMatrixBlockData() {
if (eventCreated_) {
checkCudaErrors(cudaEventDestroy(event_));
}
if (releaseMemory_) {
checkCudaErrors(cudaFree(this->blockData()));
}
}
Type **adressBlockData() { return &this->blockData_; }
void recordEvent(cudaStream_t stream) {
if (!eventCreated_) {
checkCudaErrors(cudaEventCreate(&event_));
eventCreated_ = true;
}
checkCudaErrors(cudaEventRecord(event_, stream));
}
void synchronizeEvent() {
checkCudaErrors(cudaEventSynchronize(event_));
}
void ttl(size_t ttl) { ttl_ = ttl; }
void postProcess() override { --this->ttl_; }
bool canBeRecycled() override { return this->ttl_ == 0; }
friend std::ostream &operator<<(std::ostream &os, UnifiedMatrixBlockData const &data) {
os << "UnifiedMatrixBlockData " << Id << " position Grid: (" << data.rowIdx_ << ", " << data.colIdx_ << ")"
<< std::endl;
os << "Block: (" << data.blockSizeHeight() << ", " << data.blockSizeWidth() << ") leadingDimension="
<< data.leadingDimension_
<< " ttl: " << data.ttl_ << std::endl;
return os;
}
};
#endif //HEDGEHOG_TUTORIALS_UNIFIED_MATRIX_BLOCK_DATA_H
|
PHP | UTF-8 | 1,456 | 2.609375 | 3 | [] | no_license | <?php
namespace Mintmesh\Services\Notification;
use Aws\Common\Aws;
use Aws\Sns\SnsClient as snsClient;
class NotificationManager {
// Initiate SNS object
private $obj = null;
private function getInstance() {
if (is_null($this->obj)) {
$this->obj = \AWS::get('sns');
}
return $this->obj;
}
public function createPlatformEndpoint($token, $platformApplicationArn) {
$options = array(
'PlatformApplicationArn' => $platformApplicationArn,
'Token' => $token,
);
try {
$res = $this->getInstance()->createPlatformEndpoint($options);
} catch (Exception $e) {
return false;
}
return $res;
}
public function publish($message, $EndpointArn) {
try {
$res = $this->getInstance()->publish(array(
'Message' => $message,
'TargetArn' => $EndpointArn
));
} catch (Exception $e) {
return false;
}
return $res;
}
public function publishJson($message, $EndpointArn) {
try {
$res = $this->getInstance()->publish(array(
'Message' => $message,
'MessageStructure' => 'json',
'TargetArn' => $EndpointArn
));
} catch (Exception $e) {
return false;
}
return $res;
}
} |
Python | UTF-8 | 1,551 | 3.6875 | 4 | [
"MIT"
] | permissive | """https://adventofcode.com/2020/day/15"""
import io
def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int:
"""
Given your starting numbers, what will be the 2020th number spoken?
"""
return nth(stdin, stderr, 2020)
def part2(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int:
"""
Given your starting numbers, what will be the 30000000th number spoken?
"""
return nth(stdin, stderr, 30000000)
def nth(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper, end: int) -> int:
"""
Brute-force the nth number spoken given an input set of numbers.
"""
debug_interval = end // 100
numbers = parse(stdin)
number = next(reversed(numbers.keys()))
for turn in range(len(numbers), end):
(prev, last) = numbers.get(number)
if turn % debug_interval == 0:
stderr.write(
f"{turn}: {number} was previously spoken in turn {prev}"
)
if prev is None:
number = 0
else:
number = last - prev
if turn % debug_interval == 0:
stderr.write(f", so I say \"{number}\"\n")
if prev is None:
number = 0
else:
number = last - prev
numbers[number] = (numbers.get(number, (None, None))[1], turn)
return number
def parse(stdin: io.TextIOWrapper) -> list:
"""
Parse the input into a list of ints.
"""
return {
int(v): (None, k)
for k, v in enumerate(stdin.read().strip().split(","))
}
|
Markdown | UTF-8 | 299 | 2.59375 | 3 | [] | no_license | # Google Translate API:
A Simple Class to Use Google Translate Api
# Usage:
<code> GoogleTranslate::translate(LANG_SOURCE, LANG_TARGET, TEXT) </code>
# Example:
<code>
require('GoogleTranslate.Class.php');
$translation = GoogleTranslate::translate("auto", 'fa', 'Hello World!');
</code>
|
Python | UTF-8 | 230 | 4.15625 | 4 | [] | no_license | # 3. Write a program to get the sum and multiply of all the items in a given list.
b = [2, 4, 6, 8, 10]
print("Sum of all numbers in list b:", sum(b))
res = 1
for i in b:
res = res * i
print("multiplication of numbers:", res) |
Java | UTF-8 | 5,680 | 3.3125 | 3 | [] | no_license | package innotechum.task1.entity;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Trash {
/*List<BigDecimal> temp = new ArrayList<BigDecimal>();
BigDecimal sal = new BigDecimal(0);
for (Department dep : departments.values()) {
// делаем список зп первого отдела
dep.getEmployeeList().forEach((c) -> temp.add(c.getSalary()));
// открываем первый отдел
if (avgEmp.get(0).compareTo(avgEmp.get(1)) > 0) {
// сверяем зп
if (sal.compareTo(temp.get(0)) < 0){
sal = temp.get(0);
}
}
}
System.out.println(sal);*/
// Находим сотрудника в отделе с наибольшей средней зп,
// который будет иметь зп между двумя средними отделов
/*if (avgEmp.get(0) > avgEmp.get(1)) {
for (Department dep : departments.values()) {
if (avgEmployee > departments.values().getEmployeeList(){
Double avgEmployee = dep.salaryAvg();
}
avgEmp.add(avg);
System.out.println("Средняя заработная плата отдела " + dep.getName () + ": " + avg);
}
}*/
//for (Map.Entry<String, Department> entry : departments.entrySet()) {
// if(avgEmployee > entry.getValue().getEmployeeList().forEach((c)));
// тут продолжение
//}
/*List<BigDecimal> salarys1 = new ArrayList<>();
Double avgEmployee = 0.0;
for (Map.Entry<String, Department> entry : departments.entrySet()) {
String key = entry.getKey();
entry.getValue().getEmployeeList().forEach((c) -> salarys1.add(c.getSalary()));
if (key.equals("Первый")) {
for (BigDecimal number : salarys1) {
System.out.println(number);
}
}
if (key.equals("Второй")) {*/
//}
//systemMessage(2);
/* ЗДЕЕССССССССССССССССССССССССССССССССССССССССССССССССССь
else if (avgEmp.get(0).compareTo(avgEmp.get(1)) < 0) {
employeeList .addAll(
department2.getEmployeeList().stream() // проходим по второму листу и сравниваем
.filter(emp -> emp.getSalary().compareTo(avgEmp.get(0)) < 0 && emp.getSalary().compareTo(avgEmp.get(1)) > 0)
.collect(Collectors.toList()));
} else {
System.out.println("Нет сотрудника для увеличения ср зп");
}
*/
//}
//}
//for (Double number : salarys) {
// System.out.println(number);
//for (Map.Entry<String, Department> entry : departments.entrySet())
// System.out.println(entry.getKey() + " - " + entry.getValue());
/*String key;
if (avgEmp.get(0).compareTo(avgEmp.get(1)) > 0) {
key = "Первый отдел имеет большую среднюю зп";
} else {
key = "Второй отдел имеет большую среднюю зп";
}
System.out.println(empswap(departments, key, avgEmp));*/
public static BigDecimal empswap(Map<String, Department> departments, String key, List<BigDecimal> avgEmp) {
BigDecimal sal = new BigDecimal(0);
List<BigDecimal> temp = new ArrayList<>();
for (Department dep : departments.values()) {
if (key.equals("Первый отдел имеет большую среднюю зп") && dep.getName().equals("Первый")) {
int i = 0;
// Сохраняю в List данные о зп первого отдела
dep.getEmployeeList().forEach((c) -> temp.add(c.getSalary()));
for (BigDecimal number : temp) {
// Ищу макс. зп, которая находится между двух средних зп по отделам
if (temp.get(i).compareTo(avgEmp.get(0)) > 0 && temp.get(i).compareTo(avgEmp.get(1)) > 0) {
sal = temp.get(i);
}
i++;
}
break;
}
if (key.equals("Второй отдел имеет большую среднюю зп") && dep.getName().equals("Второй")) {
int i = 0;
// Сохраняю в List данные о зп первого отдела
dep.getEmployeeList().forEach((c) -> temp.add(c.getSalary()));
for (BigDecimal number : temp) {
// Ищу макс. зп, которая находится между двух средних зп по отделам
if (temp.get(i).compareTo(avgEmp.get(0)) > 0 && temp.get(i).compareTo(avgEmp.get(1)) > 0) {
sal = temp.get(i);
}
i++;
}
break;
}
//else continue;
}
return sal;
}
}
|
PHP | UTF-8 | 3,872 | 2.703125 | 3 | [] | no_license | <?php
namespace RKW\RkwConsultant\ViewHelpers;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
$currentVersion = \TYPO3\CMS\Core\Utility\VersionNumberUtility::convertVersionNumberToInteger(TYPO3_version);
if ($currentVersion < 8000000) {
/**
* Class HtmlLinkViewHelper
*
* @author Maximilian Fäßler <maximilian@faesslerweb.de>
* @author Steffen Kroggel <developer@steffenkroggel.de>
* @copyright Rkw Kompetenzzentrum
* @package RKW_RkwConsultant
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later
* @deprecated
*/
class HtmlLinkViewHelper extends AbstractViewHelper
{
/**
* Sets HTML-Links from plaintext
*
* @param string $value string to format
* @return string the altered string.
* @api
*/
public function render($value = null)
{
return static::renderStatic(
array(
'value' => $value,
),
$this->buildRenderChildrenClosure(),
$this->renderingContext
);
}
/**
* Applies preg_replace on the specified value.
*
* @param array $arguments
* @param \Closure $renderChildrenClosure
* @param \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext
* @return string
*/
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext)
{
$value = $arguments['value'];
if ($value === null) {
$value = $renderChildrenClosure();
}
return preg_replace('/(http:\/\/([^\s]+))/i', '<a href="$1" target="_blank">$2</a>', $value);
}
}
} else {
/**
* Class HtmlLinkViewHelper
*
* @author Maximilian Fäßler <maximilian@faesslerweb.de>
* @author Steffen Kroggel <developer@steffenkroggel.de>
* @copyright Rkw Kompetenzzentrum
* @package RKW_RkwConsultant
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later
*/
class HtmlLinkViewHelper extends AbstractViewHelper
{
/**
* Sets HTML-Links from plaintext
*
* @param string $value string to format
* @return string the altered string.
* @api
*/
public function render($value = null)
{
return static::renderStatic(
array(
'value' => $value,
),
$this->buildRenderChildrenClosure(),
$this->renderingContext
);
}
/**
* Applies preg_replace on the specified value.
*
* @param array $arguments
* @param \Closure $renderChildrenClosure
* @param RenderingContextInterface $renderingContext
* @return string
*/
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
{
$value = $arguments['value'];
if ($value === null) {
$value = $renderChildrenClosure();
}
return preg_replace('/(http:\/\/([^\s]+))/i', '<a href="$1" target="_blank">$2</a>', $value);
}
}
}
|
SQL | UTF-8 | 4,098 | 3.265625 | 3 | [
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 01-03-2015 a las 01:36:18
-- Versión del servidor: 5.6.17
-- Versión de PHP: 5.5.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `talleresintegra`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `departaments`
--
CREATE TABLE IF NOT EXISTS `departaments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`departament` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `migrations`
--
CREATE TABLE IF NOT EXISTS `migrations` (
`migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Volcado de datos para la tabla `migrations`
--
INSERT INTO `migrations` (`migration`, `batch`) VALUES
('2015_02_15_191053_create_users_table', 1),
('2015_02_20_191744_create_departaments_table', 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`lastname_1` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`lastname_2` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`nick` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`rfc` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`phone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`celphone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`street` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`number` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
`suburb` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`ps` varchar(7) COLLATE utf8_unicode_ci DEFAULT NULL,
`city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`state` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`rank` int(11) NOT NULL DEFAULT '1',
`status` tinyint(1) NOT NULL DEFAULT '1',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_nick_unique` (`nick`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
--
-- Volcado de datos para la tabla `users`
--
INSERT INTO `users` (`id`, `name`, `lastname_1`, `lastname_2`, `nick`, `email`, `password`, `rfc`, `phone`, `celphone`, `street`, `number`, `suburb`, `ps`, `city`, `state`, `rank`, `status`, `created_at`, `updated_at`, `remember_token`) VALUES
(1, 'Israel', 'Hohenheim', '', 'Shikari', 'Shikari.Guns@gmail.com', '$2y$10$oDAoxZEf0J9wlzztV1q1N.2Jc2vD4pKQ8W7aCbqxklO.3u8ovXY/u', '', '', '', '', '', '', '', '', '', 2, 1, '2015-03-01 00:32:56', '2015-03-01 00:33:51', 'eagxsoGkAUSzA2qHN8nPUkNg18U2nLPVuLC1XPlKkcNveJ169pAUlVLainol'),
(2, 'Demo', 'Demo', '', 'Demo', 'demo@demo.com', '$2y$10$FOIe4VcoAtU8Vgek6AG0Ju2GUet0HYBlT0sM6tmhr1XZfe/zBuKeW', '', '', '', '', '', '', '', '', '', 2, 1, '2015-03-01 00:33:37', '2015-03-01 00:33:37', NULL);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java | UTF-8 | 569 | 2.703125 | 3 | [] | no_license | package com.example.hellospring.workshop01;
import org.junit.jupiter.api.Test;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.*;
class Random7 implements IRandom {
@Override
public int nextInt(int bound) {
return 7;
}
}
class GenerateUUIDTest {
@Test
public void getUUID() {
GenerateUUID generateUUID = new GenerateUUID();
generateUUID.setRandom(new Random7()); // Dependency Injection (DI)
String uuid = generateUUID.get("somkiat");
assertEquals("XYZsomkiat7", uuid);
}
} |
Python | UTF-8 | 2,427 | 3.203125 | 3 | [] | no_license | import random
import urllib
import sys
word_url="http://learncodethehardway.org/words.txt"
words=[]
phrases={
"class %%%(%%%)":"Make class named %%% that is a %%%",
"class %%%(object) :\n\tdef_init_(self,***)":"class %%% has a function _init_ that takes self and *** parameters.",
"class %%%(object):\n\t def_***(self,@@@)":"Class %%% has a function *** which takes a self and @@@ arguments",
"*** =%%%()":"Set *** to instance of class %%%",
"***.***(@@@)":"Call the function *** from *** class Using self and @@@ arguments",
"***.***=***":"Set *** attribute of class *** with value ***"
}
if len(sys.argv)==2 and sys.argv[1]=="english" :
pharse_first=True
else :
pharse_first=False
for word in urllib.urlopen(word_url).readlines():
words.append(word.strip());
def convert(snippets,phrase):
class_names=[w.capitalize() for w in random.sample(words,snippet.count("%%%"))]
#print class_names
other_names=random.sample(words,snippet.count("***"))
#print other_names
results=[]
param_names=[]
for i in range(0,snippet.count("@@@")):
param_count=random.randint(1,3)
param_names.append(','.join(random.sample(words,param_count)))
#print param_names
for sentence in [snippet, phrase]:
#print sentence
result=sentence[:]
#print result
#result=[snippet,phrase]
for word in class_names:
result=result.replace('%%%',word,1)
#print word
#print result+"a class names"
for word in other_names :
result=result.replace("***",word,1)
#print word
#print result+"a other names"
for word in param_names:
result=result.replace("@@@",word,1)
#print word
#print result+"a param names"
results.append(result)
#print results
#print result
return results
try :
while True:
snippets=phrases.keys()
random.shuffle(snippets)
for snippet in snippets:
phrase=phrases[snippet]
question,answer=convert(snippet,phrase)
#answer=convert(snippet,phrase).{question}
if pharse_first:
question,answer=answer,question
print question
#raw_input("->")
#print "Answer:%s\n\n" %(answer)
print "%s \n" %answer
except EOFError:
print"\n BYE!"
|
Java | UTF-8 | 1,752 | 2.984375 | 3 | [] | no_license | import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Integer.parseInt;
import static java.util.Arrays.*;
public class ArgsParser1 {
private HashMap<String, Object> values;
private final HashMap<String, String> schemaMap;
public ArgsParser1(String schema) {
schemaMap = parseSchema(schema);
}
public void parse(String[] args) {
values = new HashMap();
for (Map.Entry<String, String> entry : schemaMap.entrySet()) {
String flagName = entry.getKey();
String flagType = entry.getValue();
if (flagType.equals("boolean")) {
values.put(flagName, asList(args).contains("-" + flagName));
} else {
String value = args[asList(args).indexOf("-" + flagName) + 1];
if (flagType.equals("int")) {
values.put(flagName, parseInt(value));
} else {
values.put(flagName, value);
}
}
}
}
private HashMap<String, String> parseSchema(String schema) {
//l:boolean p:int d:string
HashMap<String, String> schemaMap = new HashMap<>();
String[] array = schema.split(" ");
for (String pair : array) {
String[] flagDefinition = pair.split(":");
schemaMap.put(flagDefinition[0], flagDefinition[1]);
}
schemaMap.put(array[0].split(":")[0], array[0].split(":")[1]);
schemaMap.put(array[1].split(":")[0], array[1].split(":")[1]);
schemaMap.put(array[2].split(":")[0], array[2].split(":")[1]);
return schemaMap;
}
public Object getValue(String flag) {
return values.get(flag);
}
}
|
TypeScript | UTF-8 | 789 | 2.6875 | 3 | [] | no_license | import * as Yup from "yup"
import { PHONE_MASK, ALPHA_MASK, PromotionCodes } from "helpers"
export const schema = Yup.object().shape({
firstname: Yup.string()
.min(2)
.max(32)
.matches(ALPHA_MASK)
.required(),
surname: Yup.string()
.min(2)
.max(32)
.matches(ALPHA_MASK)
.required(),
email: Yup.string()
.email()
.required(),
phone: Yup.string()
.matches(PHONE_MASK)
.required(),
code: Yup.string()
.test("promotion-code", "promotion code is not valid", value => PromotionCodes.isValid(value))
.required(),
agreement: Yup.bool()
.oneOf([true])
.required(),
})
export const initialValues: Yup.InferType<typeof schema> = {
firstname: "",
surname: "",
email: "",
phone: "",
code: "",
agreement: true,
}
|
JavaScript | UTF-8 | 5,371 | 2.859375 | 3 | [] | no_license | var colors = require('colors');
var _ = require('lodash');
var log = require('../../../backend/utilities/logger.js');
var database = require('../../../backend/utilities/database.js');
var AUTH_COOKIE = "544a4603c639328a1adc6723";
var EVENT_ID = database.getObjectID("544a8c615161f3314349f1ab");
var USER_ID = database.getObjectID("544b7656702a87d900b4392f");
var FAKE = database.getObjectID("544ce6a966509b000046d959");
/**
* [getSubObjects description]
* @param {[type]} body - an object of any depth
* @param {[type]} string - A string delimited by decimals to denote another layer in an object,
* Works also with no decimals
* @return {[type]} "result.result" will get "hello" from: {result: {result: "hello"}}
*/
var getSubObjects = function(body, string) {
return _.reduce(string.split('.'), function(prev, curr) {
//ENSURE SUB OBJECT EXISTS
if (!prev[curr]) {
throw new Error('Sub object not found in test');
}
return prev[curr];
}, body);
};
module.exports = {
// CONSTANTS
DELAY: 1000,
//DEPRECATED, PLEASE REMOVE (DO NOT USE)
hasAppropriateProperties: function(err, res, body) {
body = JSON.parse(body);
if (body.success === false && !body.error_message) {
throw new Error('API returning incorrect properties (no error_message)');
}
if (body.success === true && !body.result) {
throw new Error('API returning incorrect properties (no result)');
}
},
hasResultProperty: function(err, res, body, property, type, val) {
body = JSON.parse(body);
if (!body.result) {
throw new Error('API does not return success');
}
//CHECK PROPERTY EXISTS
if (!body.result || body.result[property] === undefined) {
throw new Error('Expected result.' + property + ' to exist ');
}
//CHECK TYPEOF THE PROPERTY
if (typeof body.result[property] !== type) {
throw new Error('Expected ' + property + ' property of result to be of type' + type);
}
//CHECK VALUE OF THE PROPERTY
var value = body.result[property];
if (val && body.result[property] !== val) {
throw new Error('Expected value of ' + property + ' to be: ' + val + ' instead got ' + value);
}
},
propertyHasLength: function(err, res, body, property, length) {
// FORMAT REQUEST BODY
body = JSON.parse(body);
//GET SUB OBJECT IF NECESSARY
var value = getSubObjects(body, property);
//CHECK PROPERTY EXISTS
if (!value) {
throw new Error('cannot check length of undefined');
}
var property_length = value.length;
//CHECK PROPERTY IS A NUMBER
if (!value instanceof Array) {
throw new Error('Can only check the length of arrays');
}
//CHECK PROPERTY LENGTH IS AS EXPECTED
if (property_length !== length) {
var output = [
"expected:",
property,
"to be of length",
length,
"but found as",
property_length
];
throw new Error(output.join(' '));
}
},
successIsFalse: function(err, res, body) {
body = JSON.parse(body);
// THROW ERROR IF TEST ISN'T FALSE
if (body.success !== false) {
throw new Error('Expected success to be false');
}
},
successIsTrue: function(err, res, body) {
body = JSON.parse(body);
// THROW ERROR IF REST ISN'T FALSE
if (body.success !== true) {
throw new Error('Expected success to be true, error message: ' + body.error_message);
}
},
hasErrorMessage: function(err, res, body, message) {
body = JSON.parse(body);
if (body.error_message !== message) {
throw new Error('Error message is incorrect, expected: ' + message + ' but got: ' + body.error_message);
}
},
resultMessageIs: function(err, res, body, message) {
body = JSON.parse(body);
if (body.result !== message) throw new Error('Expecting result message' + message + 'but got ' + body.result);
},
hasSuccessMessage: function(err, res, body, message) {
//FORMAT REQUEST BODY
body = JSON.parse(body);
//THROW ERROR IF MESSAGE IS NOT EXPECTED
if (body.result !== message) {
var output = [
'Success message is incorrect, expected:',
message,
' but got: ',
body.result,
'error message was:',
body.error_message
];
throw new Error(output.join('\n'));
}
},
// SET OUTGOING REQUEST AS MONGO AUTH COOKIE CONSTANT
setAuthCookie: function(outgoing) {
outgoing.headers['Cookie'] = 'auth=' + AUTH_COOKIE;
return outgoing;
},
// GET CONSTANT MONGO ID
getAuthCookie: function() {
return database.getObjectID(AUTH_COOKIE);
},
//COLLECTION OF DUMMY ID'S FOR STUBBING TESTS
dummy_id: {
//USE EVENTS AS EVENT IS A RESERVED WORD
EVENT_ID: EVENT_ID,
USER_ID: USER_ID,
FAKE: FAKE
}
}; |
C++ | GB18030 | 2,414 | 3.140625 | 3 | [] | no_license | #include "readCSVFile.h"
int GetTotalLineCount(FILE *fp)
{
int i = 0;
char strLine[MAX_LINE_SIZE];
fseek(fp, 0, SEEK_SET); //fpָָͷ
while (fgets(strLine, MAX_LINE_SIZE, fp)) //fgetsһLine
i++;
fseek(fp, 0, SEEK_SET);
return i;
}
int GetTotalColCount(FILE *fp)
{
int i = 0;
char strLine[MAX_LINE_SIZE];
fseek(fp, 0, SEEK_SET);
if (fgets(strLine, MAX_LINE_SIZE, fp))
{
i = strlen(strLine)/ 2; //˴ΪCSVԶ","ΪָԳ2
}
else
{
fseek(fp, 0, SEEK_SET);
return -1;
}
fseek(fp, 0, SEEK_SET);
return i;
}
//ָͨ䶯̬ռ
int AssignSpaceForData(int inumdata)
{
pnCsvData = NULL;
pnCsvData = (int *)malloc(sizeof(int)*inumdata);
if (pnCsvData == NULL)
return 0;
memset(pnCsvData, 0, sizeof(int)*inumdata); //ٵĶ̬ռʼΪ0
return 1;
}
//ͷŶ̬ڴ
void FreeCsvData()
{
free(pnCsvData);
pnCsvData = NULL;
}
//[ؼ]CSVļ
int ReadCsvData(char * csvFilePath)
{
FILE *fCsv;
char *ptr;
char strLine[MAX_LINE_SIZE];
int i;
int j;
//ݣɾ
if (pnCsvData != NULL)
FreeCsvData();
if (fopen_s(&fCsv, csvFilePath, "r") != 0)
{
printf("Open file %s failed ", csvFilePath);
return -1;
}
else
{
nNumRow = GetTotalLineCount(fCsv);
nNumCol = GetTotalColCount(fCsv);
nNumData = nNumRow*nNumCol;
char *_buf; //Ϊstrtok_sֵָĴ
for (i = 0; i < nNumRow; i++)
{
j = 0;
if (fgets(strLine, MAX_LINE_SIZE, fCsv))
{
//strtok_sԭ
//char *strtok_s( char *strToken, const char *strDelimit, char **buf);
ptr = strtok_s(strLine, ",", &_buf);
while (ptr != NULL)
{
pnCsvData[i*nNumCol + j] = *ptr;
j++;
ptr = strtok(NULL, ","); //ļжȡĵǰʣַ飬ȡַ,ǰֽ
}
}
}
// رļ
fclose(fCsv);
}
return 1;
}
//̨ͨʾȡcsv
void ShowCsvData()
{
int i;
int j;
for (i = 0; i < nNumRow; i++)
{
printf("Line %i :", i + 1); //ÿек Line :
for (j = 0; j < nNumCol; j++)
{
printf("%i", pnCsvData[i*nNumCol + j]); // ӡCSV
}
printf("\n"); //
}
}
|
Java | UTF-8 | 1,838 | 3.8125 | 4 | [] | no_license | package DP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class DP_1463_make_one {
/**
* X가 3으로 나누어 떨어지면, 3으로 나눈다.
* X가 2로 나누어 떨어지면, 2로 나눈다.
* 1을 뺀다.
* -> 연산의 최소 카운트 수
*
* 10 -> 9 -> 3 -> 1
*/
/**
*
* 1번 규칙 (3으로 나누어 떨어진다) : D[N] = D[N/3] + 1
* 2번 규칙 (2로 나누어 떨어진다) : D[N] = D[N/2] + 1
* 3번 규칙 ( 1 을 뺀다 ): D[N] = D[N-1] + 1
* 작은 문제서 부터 큰 문제를 풀어가는 방식입니다.
* 숫자 1에서 부터
* 2로 갈때의 경우의 수 중 가장 작은 방법.
* 3으로 갈때의 경우의 수 중 가장 작은 방법.
* .
* .
* .
* N일때 가장 작은 방법.
* 으로 구하면됩니다.
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int dp[] = new int[N+1];
/**
* dp
* n = 1일 때 가장 작은 방법
* n = 2일 때 가장 작은 방법
* ....
* n = 10일 때 가장 작은 방법을 구해간다.
*/
dp[1] = 0;
for (int j = 2; j <= N; j++) {
dp[j] = dp[j - 1] + 1;
if (j % 2 == 0) {
dp[j] = Math.min(dp[j], dp[j/2] + 1);
}
if (j % 3 == 0) {
dp[j] = Math.min(dp[j], dp[j/3] + 1);
}
System.out.println(dp[j]);
}
System.out.println(dp[N]);
}
}
|
Java | UTF-8 | 1,512 | 2.53125 | 3 | [] | no_license | package com.javaquarium.business;
import java.util.ArrayList;
import java.util.List;
import com.javaquarium.beans.data.UserDO;
import com.javaquarium.beans.web.UserVO;
import com.javaquarium.dao.IUserDAO;
import com.javaquarium.dao.UserDAO;
/**
* @author Alex Service pour la gestion des utilisateurs
*/
public class UserService implements IUserService {
private IUserDAO userDao;
public UserService() {
userDao = new UserDAO();
}
@Override
public List<UserVO> getAllUser() {
final List<UserDO> listUser = userDao.getAllUser();
List<UserVO> users = new ArrayList<UserVO>(listUser.size());
for (final UserDO user : listUser) {
users.add(map(user));
}
return users;
}
@Override
public void save(UserVO user) {
UserDO u = this.map(user);
userDao.insert(u);
}
@Override
public UserVO map(final UserDO user) {
final UserVO userVO = new UserVO();
userVO.setLogin(user.getLogin());
userVO.setPassword(user.getPassword());
userVO.setRepeatPassword("");
return userVO;
}
@Override
public UserDO map(final UserVO user) {
final UserDO userDO = new UserDO();
userDO.setLogin(user.getLogin());
userDO.setPassword(user.getPassword());
return userDO;
}
@Override
public UserVO getUser(String login) {
UserVO user = map(userDao.find(login));
return user;
}
/**
* setter userDao
*
* @param userDao
*/
public void setUserDAO(IUserDAO userDao) {
this.userDao = userDao;
}
}
|
Python | UTF-8 | 10,350 | 2.875 | 3 | [] | no_license | import jesql_utils
import operator
import sys
import os
class Statement(object):
"""class docstring"""
def __init__(self, tokens):
self.tokens = tokens
self.result_column = None
self.subquery = None
self.join_clause = None
self.expression = None
self.evaluate_tokens()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def __str__(self):
return 'result_column: {}\nsubquery: {}\njoin_clause: {}\nexpression: {}'.format(self.result_column, self.subquery, self.join_clause, self.expression)
def evaluate_tokens(self):
if self.tokens:
remaining_tokens, rc = self.evaluate_clause(self.tokens, 'from')
remaining_tokens, sq = self.evaluate_clause(remaining_tokens[1:], 'where', 'inner', 'left')
self.result_column = ResultColumn(rc)
self.subquery = Subquery(sq)
if not remaining_tokens:
return
elif remaining_tokens[0] == 'where':
self.expression = Expression(remaining_tokens[1:])
else:
remaining_tokens, jc = self.evaluate_clause(remaining_tokens, 'join', include_delimiter=True)
self.join_clause = JoinClause(jc)
remaining_tokens, jtable = self.evaluate_clause(remaining_tokens[1:], 'on')
self.subquery.insert(jtable)
self.expression = Expression(remaining_tokens[1:])
def evaluate_clause(self, tokens, *delimiters, include_delimiter=False):
if delimiters:
delimiter_index = -1
expression = []
for index, token in enumerate(tokens):
for delimiter in delimiters:
if token.lower() == delimiter.lower():
delimiter_index = index
if include_delimiter:
expression.append(token)
break
if delimiter_index == -1:
expression.append(token)
if delimiter_index != -1:
return tokens[delimiter_index:], expression
else:
return None, expression
else:
print('ERROR: evaluate_clause: no delimiters specified', file=sys.stderr)
class ResultColumn(object):
def __init__(self, tokens):
self.tokens = tokens
self.table_names = []
self.column_names = []
self.parse_result_column()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def __eq__(self, other):
for index, table in enumerate(self.table_names):
try:
if table != other.table_names[index]:
return False
except IndexError:
return False
for index, column in enumerate(self.column_names):
try:
if column != other.column_names[index]:
return False
except IndexError:
return False
return True
def __str__(self):
output_string = ''
for table, column in zip(self.table_names, self.column_names):
output_string += '{{table_name: "{}", column_name: "{}"}},'.format(table, column)
output_string = output_string[:-1]
return '[{}]'.format(output_string)
def __iter__(self):
self.result_index = 0
return self
def __next__(self):
if self.result_index >= len(self.table_names):
raise StopIteration
else:
table_name = self.table_names[self.result_index]
column_name = self.column_names[self.result_index]
self.result_index += 1
return table_name, column_name
def parse_result_column(self):
table_count = 0
column_count = 0
for token in self.tokens:
if '.' in token:
split_token = token.split('.')
if split_token[1] == '*':
self.evaluate_splat(split_token[0])
else:
self.table_names.append(split_token[0])
self.column_names.append(split_token[1].replace(',', ''))
table_count += 1
column_count += 1
else:
self.table_names.append(None)
self.column_names.append(token)
column_count += 1
if table_count != column_count and table_count != 0:
print('ERROR: parse_result_column: expected "." missing', file=sys.stderr)
def evaluate_splat(self, table):
table_path = os.path.join(os.getcwd(), table)
jesql_reader = jesql_utils.Reader(table_path, is_file=True)
header = jesql_reader.read_header()
for header_col in header:
self.table_names.append(table)
self.column_names.append(header_col['name'])
def insert_alias(self, subquery):
for index, (table, column) in enumerate(zip(self.table_names, self.column_names)):
for sq_table, sq_alias in zip(subquery.tables, subquery.aliases):
if table == sq_table:
if sq_alias:
self.column_names[index] = sq_alias + '.' + column
def pop(self):
self.table_names.pop(0)
self.column_names.pop(0)
class Subquery(object):
"""class docstring"""
def __init__(self, tokens):
self.tokens = tokens
self.tables = []
self.aliases = []
self.parse_subquery()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def __eq__(self, other):
for index, table in enumerate(self.tables):
try:
if table != other.tables[index]:
return False
except IndexError:
return False
for index, alias in enumerate(self.aliases):
try:
if alias != other.aliases[index]:
return False
except IndexError:
return False
return True
def __str__(self):
output_string = ''
for table, alias in zip(self.tables, self.aliases):
output_string += '{{table_name: "{}", alias: "{}"}},'.format(table, alias)
output_string = output_string[:-1]
return '[{}]'.format(output_string)
def __iter__(self):
self.query_index = 0
return self
def __next__(self):
if self.query_index >= len(self.tables):
raise StopIteration
else:
table = self.tables[self.query_index]
try:
alias = self.aliases[self.query_index]
except IndexError:
alias = None
self.query_index += 1
return table, alias
def parse_subquery(self):
# if the subquery was just a table
token_string = ' '.join(self.tokens)
new_tokens = token_string.split(',')
for token in new_tokens:
split_tokens = token.strip().split(' ')
if len(split_tokens) == 2:
self.tables.append(split_tokens[0])
self.aliases.append(split_tokens[1])
else:
self.tables.append(split_tokens[0])
self.aliases.append(None)
def insert(self, tokens):
if len(tokens) == 1:
self.tables.append(tokens[0])
self.aliases.append(None)
if len(tokens) == 2:
self.tables.append(tokens[0])
self.aliases.append(tokens[1])
else:
print('ERROR: insert: invalid number of arguments supplie', file=sys.stderr)
class JoinClause(object):
def __init__(self, tokens):
self.tokens = tokens
self.join_type = None
self.join_modifier = None
self.parse_join()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def __str__(self):
return '{{join_type: "{}", join_modifier: "{}"}}'.format(self.join_type, self.join_modifier)
def parse_join(self):
if self.tokens[0] == 'join' or self.tokens[0] == 'inner':
self.join_type = 'inner'
elif self.tokens[0] == 'left':
self.join_type = 'outer'
self.join_modifier = 'left'
elif self.tokens[0] == 'right':
self.join_type = 'outer'
self.join_modifier = 'right'
else:
print('ERROR: parse_join: invalid join type specified', file=sys.stderr)
class Expression(object):
"""class docstring"""
opers = { "<": operator.lt,
"<=": operator.le,
"=": operator.eq,
"!=": operator.ne,
">": operator.gt,
">=": operator.ge,
}
def __init__(self, tokens):
self.tokens = tokens
self.left_value = None
self.oper = None
self.right_value = None
self.parse_expression()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def __eq__(self, other):
if self.left_value != other.left_value:
print('1')
return False
elif self.oper != other.oper:
print('2')
return False
elif self.right_value != other.right_value:
print('3')
return False
else:
return True
def __str__(self):
return '{{left_value: "{}", oper: {}, right_value: "{}"}}'.format(self.left_value, self.oper, self.right_value)
def parse_expression(self):
if len(self.tokens) == 3:
for key, value in self.opers.items():
if self.tokens[1] == key:
self.oper = value
if self.oper == None:
print('ERROR: parse_expression:', self.tokens[1], 'is not a valid operator', file=sys.stderr)
return
self.left_value = self.tokens[0]
self.right_value = self.tokens[2]
else:
print('ERROR: parse_expression: malformed expression supplied', file=sys.stderr)
|
C++ | UTF-8 | 1,093 | 3.53125 | 4 | [] | no_license | #include <gtest/gtest.h>
/*
You are climbing a stair case and it takes A steps to reach to the top.
Each time you can either climb 1 or 2 steps.
In how many distinct ways can you climb to the top?
The first and the only argument contains an integer A, the number of steps.
Return an integer, representing the number of ways to reach the top.
1 <= A <= 36
*/
int solution(int A){
if(A <= 1){
return 1;
}
int a = 1, b = 1, tmp;
for(int i = 0; i < A; ++i){
tmp = b;
b += a;
a = tmp;
}
return a;
}
TEST(StairsSuite, Example_1) {
ASSERT_EQ(2, solution(2));
}
TEST(StairsSuite, Example_2) {
ASSERT_EQ(3, solution(3));
}
TEST(StairsSuite, Trivial_1) {
ASSERT_EQ(1, solution(1));
}
TEST(StairsSuite, Complex_4) {
ASSERT_EQ(5, solution(4));
//[1111],[22], [211], [112], [121]
}
TEST(StairsSuite, Complex_5) {
ASSERT_EQ(8, solution(5));
//[11111],[221],[212],[122],[2111],[1112],[1211],[1121]
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} |
C++ | UTF-8 | 2,332 | 2.75 | 3 | [] | no_license | math::rVector3d into_cell( math::rVector3d const &_vec,
math::rMatrix3d const &_cell,
math::rMatrix3d const &_inv)
{
math::rVector3d result( _inv * _vec );
result(0) -= std::floor(result(0)+types::roundoff);
result(1) -= std::floor(result(1)+types::roundoff);
result(2) -= std::floor(result(2)+types::roundoff);
return _cell * result;
}
math::rVector3d zero_centered( math::rVector3d const &_vec,
math::rMatrix3d const &_cell,
math::rMatrix3d const &_inv)
{
math::rVector3d result( _inv * _vec );
result(0) -= std::floor(5e-1+result(0)+types::roundoff);
result(1) -= std::floor(5e-1+result(1)+types::roundoff);
result(2) -= std::floor(5e-1+result(2)+types::roundoff);
// numerical stability check.
if( math::eq(result(0), 5e-1) ) result(0) = -5e-1;
else if( math::lt(result(0), -5e-1)) result(0) += 1e0;
if( math::eq(result(1), 5e-1) ) result(1) = -5e-1;
else if( math::lt(result(1), -5e-1)) result(1) += 1e0;
if( math::eq(result(2), 5e-1) ) result(2) = -5e-1;
else if( math::lt(result(2), -5e-1)) result(2) += 1e0;
return _cell * result;
}
math::rVector3d into_voronoi( math::rVector3d const &_vec,
math::rMatrix3d const &_cell,
math::rMatrix3d const &_inv)
{
math::rVector3d result( _inv * _vec );
result(0) -= std::floor(result(0)+types::roundoff);
result(1) -= std::floor(result(1)+types::roundoff);
result(2) -= std::floor(result(2)+types::roundoff);
// numerical stability check.
if( math::eq(result(0), -1e0) or math::eq(result(0), 1e0) ) result(0) = 0e0;
if( math::eq(result(1), -1e0) or math::eq(result(1), 1e0) ) result(1) = 0e0;
if( math::eq(result(2), -1e0) or math::eq(result(2), 1e0) ) result(2) = 0e0;
math::rVector3d const orig(result);
types::t_real min_norm = (_cell*orig).squaredNorm();
for(int i(-1); i < 2; ++i)
for(int j(-1); j < 2; ++j)
for(int k(-1); k < 2; ++k)
{
math::rVector3d const translated = orig + math::rVector3d(i,j,k);
types::t_real const d( (_cell*translated).squaredNorm() );
if( math::gt(min_norm, d) )
{
min_norm = d;
result = translated;
}
}
return _cell * result;
}
|
PHP | UTF-8 | 11,068 | 2.890625 | 3 | [
"PHP-3.01"
] | permissive | <?php
include $_SERVER['DOCUMENT_ROOT']."/recipe_site/db/db.php";
// 서버에 있는 아이디를 $userid 변수에 삽입
if(!isset($_SESSION))
{
session_start();
}
$userid = $_SESSION['mem_id'];
$sql = mq("select * from member where mem_id='".$userid."'");
// $sql에 있는 fetch_array(): 인덱스를 변수에 삽입
$member = $sql->fetch_array();
// 콤마를 기준으로 나눠서 배열로 저장
$filter_Array = explode(",", $member['mem_filter']);
$spicy_Array = explode(",", $member['mem_spicy']);
// $email 변수에 데이터베이스에 있는 mem_email 삽입
$email = $member['mem_email'];
// $filter_Array에 값이 존재하는 지 확인
$i = 0;
if($member['mem_filter'] != null){
// 반복문을 이용하여 배열에 값이 null이 아닐 경우에 'checked' 문자열 삽입
// count(배열) 배열의 총 숫자보다 i가 작을 때 까지 반복한다.
while($i < count($filter_Array)){
if($filter_Array[$i] != ""){
$num[$i] = "checked";
} else {
$num[$i] = "";
}
$i++;
}
} else {
while($i < 6){
$num[$i] = "";
$i++;
}
}
echo "<br>";
$j = 0;
// $spicy_Array에 값이 존재하는 지 확인
if($member['mem_spicy']!= null){
// 반복문을 이용하여 배열에 값이 null이 아닐 경우에 'checked' 문자열 삽입
// count(배열) 배열의 총 숫자보다 i가 작을 때 까지 반복한다.
while($j < count($spicy_Array)){
if($spicy_Array[$j] != ""){
$idx[$j] = "checked";
} else {
$idx[$j] = "";
}
$j++;
}
} else {
while($j < 4){
$idx[$j] = "";
$j++;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>마이페이지</title>
<script src="/recipe_site/js/jquery-3.5.1.min.js"></script>
<script src="/recipe_site/js/bootstrap.min.js"></script>
<script>
// 체크박스를 모두 체크해주는 함수
$(document).ready(function () {
$(".check_all").click(function () {
$(".check").prop("checked", this.checked);
});
$(".check_all2").click(function () {
$(".check2").prop("checked", this.checked);
});
});
</script>
<link rel="stylesheet" href="/recipe_site/css/bootstrap.min.css" />
<link rel="stylesheet" href="/recipe_site/css/bootstrap-theme.min.css" />
</head>
<body>
<!-- Bootstrap의 콘텐츠는 항상 class="container"태그 내에 기술한다. 이것에 의해 폭이 자동 조정이 된다.-->
<div class="container-fluid">
<!-- 이것은 콘텐츠의 row(가로 열)를 작성하기 위한 컨테이너이다. 그리드 시스템에서는 이 class="row" 태그 안에 표시할 내용을 준비한다.
그로 인해, 이 class="row" 태그 안에 포함된 콘텐츠의 태그가 자동으로 가로로 나란히 정렬되거나, 세로로 정렬되거나 한다.-->
<div class="row">
<!-- 폭 조정을 하는 클래스 col-종류-숫자 형태로 작성한다 md:태블릿-->
<div class="col-md-12">
<!-- class="page-header"라는 스타일은 헤더 부분의 스타일 클래스-->
<div class="page-header">
<h3 class="text-info"><a href ="./mypage.php">마이페이지</a></h3>
<br>
<img src="../signup/img/logo.png" alt="" width="200" class="img-responsive left-block">
</div>
<!-- <form class="form-inline"> : 입력폼의 입력 항목이 가로로 표시되게 된다. -->
<form class="form-inline" method="get" action="./myfilter.php">
<fieldset>
<legend>체크박스다냥</legend>
<div class="checkbox">
<!--<label>태그는 양식 입력 창 (form control)을 설명하는 이름표다.
label 요소로 묶인 텍스트를 클릭하면, form control(양식 입력 창)이 선택 됨.
<label for = 'id'> 는 해당 입력폼의 id를 지정함-->
재료 :
<label>
<input type="checkbox" name="pork" value="pork" <?php echo $num[0];?>/>돼지고기
</label>
<label>
<input type="checkbox" name="beef" value="beef" <?php echo $num[1];?>/>소고기
</label>
<label>
<input type="checkbox" name="chicken" value="chicken" <?php echo $num[2];?>/>닭고기
</label>
<label>
<input type="checkbox" name="vegetable" value="vegetable" <?php echo $num[3];?>/>채소
</label>
<label>
<input type="checkbox" name="fruit" value="fruit" <?php echo $num[4];?>/>과일
</label>
<label>
<input type="checkbox" name="seasoning" value="seasoning" <?php echo $num[5];?>/>조미료
</label>
</div>
</br>
<div class="checkbox">
매운맛 :
<label>
<input type="checkbox" name="spicy0" value="0" <?php echo $idx[0];?>/> 안 매운맛
</label>
<label>
<input type="checkbox" name="spicy1" value="1" <?php echo $idx[1];?>/> 조금 매운맛
</label>
<label>
<input type="checkbox" name="spicy2" value="2" <?php echo $idx[2];?>/> 매운맛
</label>
<label>
<input type="checkbox" name="spicy3" value="3" <?php echo $idx[3];?>/> 그냥 죽여라냥
</label>
</div>
</fieldset>
<div><input type="submit" class="btn btn-info pull-right" value="저장"></div>
</form>
<br><br>
<fieldset>
<legend>내정보</legend>
<table class="table table-bordered">
<tr>
<th class="info" style="width: 17%;">ID:</th>
<td style="width: 83%;"><?php echo $userid ?></td>
</tr>
<tr>
<th class="info" style="width: 17%;">email:</th>
<td style="width: 83%;"><?php echo $email;?></td>
</tr>
</table>
</fieldset>
<sapn><a href="./member_modify.php" class="btn btn-info pull-right">정보수정</a></sapn>
<sapn><a href="./member_withdrawal.php" class="btn btn-info pull-right">회원탈퇴</a></sapn>
<br><br>
<form class="form-inline">
<fieldset>
<legend>작성한 후기리스트</legend>
<table class="table table-bordered">
<tr class="info">
<th><label><input type="checkbox" value="all" class="check_all"> 선택</label></th>
<th>제목</th>
<th colspan="3">내용</th>
</tr>
<tr>
<td><label><input type="checkbox" value="num" class="check" /></label></td>
<td>오현우</td>
<td>오현우님이 살아계신다</td>
</tr>
<tr>
<td><label><input type="checkbox" value="num" class="check" /></label></td>
<td>오현우</td>
<td>오현우님은 살아계신다</td>
</tr>
<tr>
<td><label><input type="checkbox" value="num" class="check" /></label></td>
<td>오현우</td>
<td>오현우는 살아계신다</td>
</tr>
</table>
</fieldset>
</form>
<sapn><a href="" class="btn btn-info pull-right">게시물 삭제</a></sapn>
<br><br>
<form class="form-inline">
<fieldset>
<legend>좋아요 리스트</legend>
<table class="table table-bordered">
<tr class="info">
<th><label><input type="checkbox" value="all" class="check_all2"> 선택</label></th>
<th>제목</th>
<th colspan="3">내용</th>
</tr>
<tr>
<td><label><input type="checkbox" value="num" class="check2" /></label></td>
<td>오현우</td>
<td>오현우님이 살아계신다</td>
</tr>
<tr>
<td><label><input type="checkbox" value="num" class="check2" /></label></td>
<td>오현우</td>
<td>오현우님은 살아계신다</td>
</tr>
<tr>
<td><label><input type="checkbox" value="num" class="check2" /></label></td>
<td>오현우</td>
<td>오현우는 살아계신다</td>
</tr>
</table>
</fieldset>
</form>
<sapn><a href="" class="btn btn-info pull-right">좋아요 취소</a></sapn>
<br><br><br>
<div class="text-center"><a href="" class="btn btn-info">홈으로</a></div>
</div>
</div>
</div>
</body>
</html> |
TypeScript | UTF-8 | 2,312 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | import anyTest, { TestInterface } from 'ava';
import { rafPolyfill, cafPolyfill } from '../../worker-thread/AnimationFrame';
const test = anyTest as TestInterface<{
runTimeout: Function;
runAllTimeouts: Function;
}>;
const originalSetTimeout = globalThis.setTimeout;
test.beforeEach((t) => {
const timeouts: Array<Function> = [];
globalThis.setTimeout = ((cb: any) => timeouts.push(cb)) as any;
function runTimeout() {
let cb = timeouts.shift();
if (cb) {
cb();
}
}
function runAllTimeouts() {
while (timeouts.length) {
runTimeout();
}
}
t.context = { runTimeout, runAllTimeouts };
});
test.afterEach((t) => {
t.context.runAllTimeouts();
globalThis.setTimeout = originalSetTimeout;
});
test.serial('rafPolyfill should return a number', (t) => {
t.assert(Number.isInteger(rafPolyfill(() => {})), 'should return a number');
});
test.serial('rafPolyfill executes the body of the supplied callback', (t) => {
rafPolyfill(() => t.pass());
t.context.runTimeout();
});
test.serial('rafPolyfill executes all callbacks, even if some throw', async (t) => {
let raf2Executed = false;
rafPolyfill(() => {
throw new Error();
});
rafPolyfill(() => (raf2Executed = true));
try {
t.context.runAllTimeouts();
} catch (err) {}
t.true(raf2Executed);
});
test.serial('all the accumulated callbacks are called in the same frame', async (t) => {
let raf1Executed = false;
let raf2Executed = false;
rafPolyfill(() => (raf1Executed = true));
rafPolyfill(() => (raf2Executed = true));
t.context.runTimeout();
t.true(raf1Executed && raf2Executed);
});
test.serial('raf within a raf gets scheduled for the next batch', async (t) => {
let raf1Executed = false;
let raf2Executed = false;
rafPolyfill(() => {
raf1Executed = true;
rafPolyfill(() => (raf2Executed = true));
});
t.context.runTimeout();
t.true(raf1Executed);
t.false(raf2Executed);
t.context.runTimeout();
t.true(raf1Executed && raf2Executed);
});
test.serial('cafPolyfill can cancel execution of a callback', (t) => {
let executed = false;
let raf1handle = rafPolyfill(() => (executed = true));
rafPolyfill(() => {});
cafPolyfill(raf1handle);
t.context.runAllTimeouts();
t.false(executed, 'raf1 should not have executed');
});
|
PHP | UTF-8 | 1,315 | 2.640625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: su
* Date: 2017/12/29
* Time: 18:21
*/
namespace trhui\data;
use trhui\TpamException;
/**
* 会员自助登录
* 后台接口
* 商户会员登录
* TODO 请求地址:/club/service/interface/memberLogin
* Class MemberLogin
* @package trhui\data
*/
class MemberLogin extends DataBase
{
public function __construct()
{
$this->serverInterface = self::$SERVER_INTERFACE[self::SERVER_MEMBER_LOGIN];
$this->serverCode = self::$SERVER_CODE[self::SERVER_MEMBER_LOGIN];
}
/**
* 商户平台会员ID
* 由商户平台定义
* @param $value
*/
public function SetUserId($value)
{
$this->params['userId'] = $value;
}
public function GetUserId()
{
return $this->params['userId'];
}
public function IsUserIdSet()
{
try {
if (!(array_key_exists('userId', $this->params) && !empty($this->params['userId']))) {
throw new TpamException('清算通系统会员ID未设置');
}
return true;
} catch (TpamException $e) {
$this->addError(__FUNCTION__, $e->getMessage(), $e->getFile(), $e->getLine());
}
return false;
}
} |
Java | UTF-8 | 6,623 | 2.671875 | 3 | [] | no_license | package modifyDlg;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import geometry.Point;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
@SuppressWarnings("serial")
public class DlgPointMod extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField textXCor;
private JTextField textYCor;
private Color color;
private JTextField textColor;
private Point p;
int x,y;
boolean flag=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
DlgPointMod dialog = new DlgPointMod();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public DlgPointMod() {
setBounds(100, 100, 300, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
JLabel lblXCoordinate = new JLabel("X coordinate -->");
lblXCoordinate.setFont(new Font("Tahoma", Font.PLAIN, 15));
JLabel lblYCoordinate = new JLabel("Y coordinate -->");
lblYCoordinate.setFont(new Font("Tahoma", Font.PLAIN, 15));
textXCor = new JTextField();
textXCor.setFont(new Font("Tahoma", Font.PLAIN, 13));
textXCor.setColumns(10);
textYCor = new JTextField();
textYCor.setFont(new Font("Tahoma", Font.PLAIN, 13));
textYCor.setColumns(10);
setModal(true);
setLocationRelativeTo(null);
setTitle("Modify--Point--Modify");
JButton btnColor = new JButton("Color->>");
btnColor.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
color = JColorChooser.showDialog(null, "Color--Select Point Color--Color", p.getColor());
if(color == null) {
color = p.getColor();
}
textColor.setBackground(color);
}
});
textColor = new JTextField();
textColor.setFont(new Font("Tahoma", Font.PLAIN, 13));
textColor.setColumns(10);
textColor.setEditable(false);
GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
gl_contentPanel.setHorizontalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING, false)
.addComponent(lblYCoordinate, GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
.addComponent(lblXCoordinate, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnColor, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addComponent(textColor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textYCor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textXCor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(49, Short.MAX_VALUE))
);
gl_contentPanel.setVerticalGroup(
gl_contentPanel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addGap(29)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnColor, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE)
.addComponent(textColor, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.TRAILING)
.addComponent(lblXCoordinate)
.addComponent(textXCor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(33)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblYCoordinate)
.addComponent(textYCor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(39))
);
contentPanel.setLayout(gl_contentPanel);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton btnModify = new JButton("Modify");
btnModify.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnModify.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textXCor.getText().trim().equals("") || textYCor.getText().trim().equals("")) {
JOptionPane.showMessageDialog(null, "Fields can not be empty!", "ERROR", JOptionPane.ERROR_MESSAGE, null);
return;
}
try {
x = Integer.parseInt(textXCor.getText());
y = Integer.parseInt(textYCor.getText());
flag = true;
dispose();
} catch(NumberFormatException ece) {
JOptionPane.showMessageDialog(null, "Incorrect data type inserted, please insert data again!", "ERROR", JOptionPane.ERROR_MESSAGE, null);
}
}
});
btnModify.setActionCommand("OK");
buttonPane.add(btnModify);
getRootPane().setDefaultButton(btnModify);
}
{
JButton btncancel = new JButton("Cancel");
btncancel.setFont(new Font("Tahoma", Font.PLAIN, 13));
btncancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btncancel.setActionCommand("Cancel");
buttonPane.add(btncancel);
}
}
}
public void fillAll(Point selectedShape) {
this.p = selectedShape;
textXCor.setText(String.valueOf(p.getX()));
textYCor.setText(String.valueOf(p.getY()));
color = p.getColor();
textColor.setBackground(color);
}
public boolean isFlag() {
return flag;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Color getColor() {
return color;
}
}
|
Java | UTF-8 | 1,298 | 3.03125 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class hwalgo0828_서울_8반_천창민_fail_2 {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
int N = Integer.parseInt(st.nextToken()); // 접시 수
int d = Integer.parseInt(st.nextToken()); // 초밥의 가짓수
int k = Integer.parseInt(st.nextToken()); // 연속해서 먹는 접시의 수
int c = Integer.parseInt(st.nextToken()); // 쿠폰 번호
int [] belt = new int[N+k];
for(int i=0; i<N; i++) {
belt[i] = Integer.parseInt(bf.readLine());
}
for(int i=0; i<k; i++) {
belt[N+i] = belt[i];
}
int max = 0;
for(int i=0; i<N; i++) {
int cnt = eating(d,k,Arrays.copyOfRange(belt, i, i+k),c);
if(max < cnt) max = cnt;
if(max == d+1) break;
}
System.out.println(max);
}
private static int eating(int d, int k, int [] list, int c) {
int sum = k;
boolean [] check = new boolean[d+1];
for(int i=0; i<k; i++) {
if(check[list[i]]) sum --;
check[list[i]] = true;
}
if(!check[c]) sum++;
return sum;
}
}
|
Java | UTF-8 | 922 | 1.9375 | 2 | [] | no_license | package cn.opt.service;
import java.util.List;
import com.github.pagehelper.PageInfo;
import cn.opt.po.Student;
public interface StudentService {
/**
* 查询所有学生
*/
public PageInfo<Student> getAllStu(Integer currentPage, Integer pageSize);
/**
* easyui
*/
public List<Student> getAllStu1(Integer page, Integer rows);
/**
* 总记录数
*/
public Integer getCounts();
/**
* 根据id查询学生
*/
public Student findStuById(Integer id);
/**
* 根据姓名查询学生
*/
public List<Student> findStuByName(String name);
public Student findStuByTel(String tel);
/**
* 根据id删除一个学生
*/
public void deleteStuById(Integer id);
/**
* 更新学生
*/
public void updateStu(Integer stuid,Student stu);
/**
* 忘记密码
*/
public void updatePwd(Integer stuid, String pass) throws Exception;
}
|
Java | UTF-8 | 9,369 | 1.648438 | 2 | [] | no_license | package com.app.farmerswikki.model.state_wise_info.view.fragment;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.app.farmerswikki.R;
import com.app.farmerswikki.model.state_wise_info.pojo.StateWiseDataResponse;
import com.app.farmerswikki.model.weather.view.fragment.WeatherNewsFragment;
import com.app.farmerswikki.service.IwebService;
import com.app.farmerswikki.service.WebService;
import com.app.farmerswikki.util.custom.TextViewBold;
import com.app.farmerswikki.util.custom.TextViewRegular;
import com.app.farmerswikki.util.data.Constant;
import com.app.farmerswikki.util.data.UtilityOfActivity;
import com.google.gson.GsonBuilder;
import com.jpardogo.android.googleprogressbar.library.GoogleProgressBar;
import com.jpardogo.android.googleprogressbar.library.NexusRotationCrossDrawable;
import java.util.List;
/**
* Created by ORBITWS19 on 31-May-2017.
*/
public class StateInfoFragment extends Fragment implements IwebService {
View view;
String stateName;
String url;
StateWiseDataResponse stateWiseDataResponse;
TextView aboutState,stateNameTv;
NestedScrollView nestedScrollViewLayout;
LinearLayout krishiVigyanKendraLinearLayout,childLinearLayoutScrollView,childLinearLayoutHorizontalScrollView;
boolean flag=true;
String response;
GoogleProgressBar circularProgressBarStateInfoFrag;
LayoutInflater inflater ;
FloatingActionButton weatherPredictButton;
String cityId=null;
AppBarLayout appBarLayout;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getActivity().findViewById(R.id.parent_container).setBackground(ContextCompat.getDrawable(getActivity(),R.drawable.app_main_background));
view=inflater.inflate(R.layout.state_info_layout,container,false);
Bundle bundle=getArguments();
if(bundle.getString("stateName")!=null){
stateName=bundle.getString("stateName");
}
url= Constant.stateInfoUrl;
setView();
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getStateInfoResponse();
weatherPredictButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment fragment=new WeatherNewsFragment();
Bundle bundle=new Bundle();
bundle.putString("CityId",cityId);
Toast.makeText(getActivity(),cityId,Toast.LENGTH_LONG).show();
fragment.setArguments(bundle);
//getActivity().findViewById(R.id.parent_container).setForeground(ContextCompat.getDrawable(getActivity(),R.drawable.gradient_grey_and_white));
UtilityOfActivity.moveFragment(fragment,"WeatherNewsFragment",R.id.container,(AppCompatActivity)getActivity());
}
});
}
public void setView(){
appBarLayout=(AppBarLayout) view.findViewById(R.id.appBarLayout);
nestedScrollViewLayout=(NestedScrollView) view.findViewById(R.id.nestedScrollViewLayout);
aboutState=(TextViewRegular) view.findViewById(R.id.aboutState);
stateNameTv=(TextViewBold) view.findViewById(R.id.stateNameTv);
circularProgressBarStateInfoFrag=(GoogleProgressBar) view.findViewById(R.id.circularProgressBarStateInfoFrag);
try{
circularProgressBarStateInfoFrag.setIndeterminateDrawable(new NexusRotationCrossDrawable.Builder(getActivity()).colors(getResources().getIntArray(R.array.progressLoader)).build());
//circularProgressBar.setIndeterminateDrawable(new NexusRotationCrossDrawable.Builder(getActivity()).colors(getResources().getIntArray(R.array.progressLoader)).build());
}
catch (IndexOutOfBoundsException e)
{
e.printStackTrace();
Log.d("circularProgressBar", "onCreate() returned: " + e );
}
childLinearLayoutScrollView=(LinearLayout) view.findViewById(R.id.childLinearLayoutScrollView);
childLinearLayoutHorizontalScrollView=(LinearLayout) view.findViewById(R.id.childLinearLayoutHorizontalScrollView);
weatherPredictButton=(FloatingActionButton) view.findViewById(R.id.weatherPredictButton);
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void getStateInfoResponse(){
try {
WebService webService=new WebService();
webService.GetRequestThroughVolley(StateInfoFragment.this,null,url, Request.Method.GET,"GetStateInfoResponse");
}
catch (Exception e) {
Log.d("", "");
}
}
@Override
public void Result(String response,String calledBy) {
this.response=response;
switch (calledBy){
case "GetStateInfoResponse":{
new AsyncCaller().execute();
break;
}
}
}
public void setData(StateWiseDataResponse stateWiseDataResponse){
//nestedScrollViewLayout.setVisibility(View.VISIBLE);
for(StateWiseDataResponse.StateInfoList stateInfoList:stateWiseDataResponse.stateInfoList){
if(stateName.equalsIgnoreCase(stateInfoList.stateName)){
cityId=stateInfoList.id;
aboutState.setText(stateInfoList.about.replaceAll("\\s+", " "));//removes the extra spaces from the string
stateNameTv.setText(stateInfoList.stateName.toUpperCase());//removes the extra spaces from the string
setKrishiVigyanKendras(stateInfoList.vigyanKendra);
setCropsDetails(stateInfoList.crops);
setViewVisibilityVisible();
}
}
}
public void setKrishiVigyanKendras(List<StateWiseDataResponse.StateInfoList.VigyanKendra> vigyanKendrasList){
for(StateWiseDataResponse.StateInfoList.VigyanKendra vigyanKendra:vigyanKendrasList){
View view = inflater.inflate(R.layout.layout_kirshi_vigyan_kendra, null);
TextView krishiVigyanKendraValue=(TextView) view.findViewById(R.id.krishiVigyanKendraValue);
String stringAfterRemovingExtraSpaces=vigyanKendra.location.replaceAll("\\s+", " ");
String locationAfterCommaSplitted="";
String arrLocation[]=stringAfterRemovingExtraSpaces.split(",");
for(String locationName:arrLocation){
locationAfterCommaSplitted=locationAfterCommaSplitted+locationName+"\n";
}
krishiVigyanKendraValue.setText(locationAfterCommaSplitted);
childLinearLayoutScrollView.addView(view);
}
}
public void setCropsDetails(List<StateWiseDataResponse.StateInfoList.Crops> cropsList){
int pos=1;
for(StateWiseDataResponse.StateInfoList.Crops cropDetails:cropsList){
View view = inflater.inflate(R.layout.layout_crops_details, null);
TextView cropsNameTv=(TextView) view.findViewById(R.id.cropsNameTv);
TextView cultivationSeasonTv=(TextView) view.findViewById(R.id.cultivationSeasonTv);
cropsNameTv.setText(String.valueOf(pos++)+". "+cropDetails.name);
cultivationSeasonTv.setText(cropDetails.cultivationSeason);
childLinearLayoutHorizontalScrollView.addView(view);
}
}
private class AsyncCaller extends AsyncTask<Void, Void, StateWiseDataResponse>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected StateWiseDataResponse doInBackground(Void... params) {
stateWiseDataResponse=new GsonBuilder().create().fromJson(response,StateWiseDataResponse.class);
return stateWiseDataResponse;
}
@Override
protected void onPostExecute(StateWiseDataResponse result) {
super.onPostExecute(result);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setData(stateWiseDataResponse);
circularProgressBarStateInfoFrag.setVisibility(View.GONE);
}
}, 1000);
//this method will be running on UI thread
}
}
public void setViewVisibilityVisible(){
appBarLayout.setVisibility(View.VISIBLE);
weatherPredictButton.setVisibility(View.VISIBLE);
nestedScrollViewLayout.setVisibility(View.VISIBLE);
}
}
|
Python | UTF-8 | 164 | 2.796875 | 3 | [] | no_license | #/usr/bin/python3
# coding:utf-8
def normalize(name):
return name.capitalize()
L1 = ['baidu', 'tencent', 'alibaba']
L2 = list(map(normalize, L1))
print (L2)
|
C++ | UTF-8 | 1,351 | 2.609375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "common/binary_search_tree/ext/base/remove_right__default.h"
#include <stack>
namespace bst {
namespace ext {
namespace base {
template <class TNode, class TKey>
inline TNode* RemoveByKeySkipUpdate(TNode* root, const TKey& key,
TNode*& removed_node,
TNode*& first_changed_node) {
thread_local std::stack<TNode*> s;
TNode *node = root, *c;
for (;;) {
s.push(node);
node->ApplyAction();
if (node->key < key) {
if (!node->r) return root;
node = node->r;
} else if (key < node->key) {
if (!node->l) return root;
node = node->l;
} else {
s.pop();
break;
}
}
removed_node = node;
TNode* p = s.empty() ? nullptr : s.top();
if (node->l && node->r) {
TNode* l = RemoveRightDefault<TNode>(node->l, c, first_changed_node);
(p ? ((node == p->l) ? p->l : p->r) : root) = c;
c->SetL(l);
c->SetR(node->r);
c->SetP(p);
c->UpdateInfo();
} else {
first_changed_node = p;
c = (node->l ? node->l : node->r);
(p ? ((node == p->l) ? p->l : p->r) : root) = c;
if (c) c->SetP(p);
}
node->ResetLinksAndUpdateInfo();
for (; !s.empty(); s.pop()) s.top()->RemoveOrUpdateInfo(node);
return root;
}
} // namespace base
} // namespace ext
} // namespace bst
|
Java | UTF-8 | 212 | 1.882813 | 2 | [] | no_license | package com.pro.DAO;
import com.pro.model.Order;
import java.util.List;
public interface OrderDAO
{
public boolean saveOrder(Order order);
public boolean updateCart(String username, int orderId);
} |
JavaScript | UTF-8 | 1,629 | 2.890625 | 3 | [
"MIT"
] | permissive | const fs = require('fs');
//object destrucure
// writing files
const writeFile = fileContent => {
const {
projectName,
description,
installInstructions,
usage,
license,
contact,
otherLanguages,
primary,
contributors,
test,
github
} = fileContent
const readMeGenerated = `
# ${projectName}

## Description
${description}
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Credits](#credits)
* [License](#license)
* [Badge](#badge)
* [Contributing](#contributing)
* [Test](#test)
* [Questions](#questions)
## <a name="installation">Installation</a>
${installInstructions}
## <a name="usage">Usage</a>
* ${usage}
## <a name="credits">Credits</a>
* ${contributors}
## <a name="license">License</a>
* ${license}
## <a name="badge">Badges & Primary Languages</a>

* Other Languages/Resources Used: ${otherLanguages}
## <a name="contributing">Contributing</a>
* [Contributor Covenant](https://www.contributor-covenant.org/)
## <a name="test">Tests</a>
* ${test}
## <a name="questions">Questions</a>
contact me at:
* github: [${github}](${github})
* email: [${contact}](${contact})
`
//End to return promise
return new Promise((resolve, reject) => {
fs.writeFile('./output/README.md', readMeGenerated, err => {
if (err) {
reject(err);
return;
}
resolve({
ok: true,
message: 'File created!'
});
});
});
};
module.exports = { writeFile }; |
Markdown | UTF-8 | 1,770 | 3.203125 | 3 | [] | no_license | # Innodb和Memory引擎
#### Memory引擎
* InnoDB 引擎把数据放在主键索引上,其他索引上保存的是主键 id。这种方式,我们称之为索引组织表(Index Organizied Table)。
* 而 Memory 引擎采用的是把数据单独存放,索引上保存数据位置的数据组织形式,我们称之为堆组织表(Heap Organizied Table)。
#### 引擎的区别
* InnoDB 表的数据总是有序存放的,而内存表的数据就是按照写入顺序存放的;
* 当数据文件有空洞的时候,InnoDB 表在插入新数据的时候,为了保证数据有序性,只能在固定的位置写入新值,而内存表找到空位就可以插入新值;
* 数据位置发生变化的时候,InnoDB 表只需要修改主键索引,而内存表需要修改所有索引;
* InnoDB 表用主键索引查询时需要走一次索引查找,用普通索引查询的时候,需要走两次索引查找。而内存表没有这个区别,所有索引的“地位”都是相同的。
* InnoDB 支持变长数据类型,不同记录的长度可能不同;内存表不支持 Blob 和 Text 字段,并且即使定义了 varchar(N),实际也当作 char(N),也就是固定长度字符串来存储,因此内存表的每行数据长度相同
#### 内存引擎的问题
* 锁粒度问题 不支持行锁
* 数据持久化问题
* 备库重启会导致主备同步停止
* 备库重启后删除内存临时表,在双M的结构中会把另外一个主库的内存表也清除
#### 内存临时表可以使用的原因
* 临时表不会被其他线程访问,没有并发性的问题;
* 临时表重启后也是需要删除的,清空数据这个问题不存在;
* 备库的临时表也不会影响主库的用户线程。
#### |
C++ | GB18030 | 1,837 | 2.796875 | 3 | [] | no_license | #include "CBullet.h"
//ӵ
void CBullet::ClearBullet(CBullet bullet/*, CMap pMap*/)
{
int y = bullet.y;
int x = bullet.x;
WriteChar(x, y, " ", 7, 1);
}
//ӵ
void CBullet::DrawBullet(CBullet bullet, CMap* pMap)
{
if (bullet.isValid == 1)
{
if ( pMap->GameMap[g_level][x][y]== WALL3 && bullet.tankID == PLAYER_0) //0ӵ
{
WriteChar(bullet.x, bullet.y, "", Wall3_color, 1);
}
else if (bullet.tankID == PLAYER_0 )
{
WriteChar(bullet.x, bullet.y, "", 7, 1);
}
else if (bullet.tankID == PLAYER_1) {
WriteChar(bullet.x, bullet.y, "", 2, 1);
}
else {
WriteChar(bullet.x, bullet.y, "", 7, 1);
}
}
}
// ȡӵһ
// int CBullet::GetBulletNextObj(CBullet bullet, CMap pMap)
// {
// if (bullet.isValid == 1)
// {
// CBullet temp = bullet;
// int x = temp.x; //
// int y = temp.y; //
// switch (temp.dir)
// {
// case UP:
// y = temp.y--;
// break;
// case DOWN:
// y = temp.y++;
// break;
// case LEFT:
// x = temp.x--;
// break;
// case RIGHT:
// x = temp.x++;
// break;
// }
// return WALL6== pMap.GameMap[x][y];
// }
// return -1;
// }
//
//
// ԭӵһ壬
// int CBullet::GetBulletNextObj(CBullet bullet, CMap pMap)
// {
// if (bullet.isValid == 1)
// {
// CBullet temp = bullet;
// int x = temp.x; //
// int y = temp.y; //
// switch (temp.dir)
// {
// case UP:
// y = temp.y++;
// break;
// case DOWN:
// y = temp.y--;
// break;
// case LEFT:
// x = temp.x++;
// break;
// case RIGHT:
// x = temp.x--;
// break;
// }
// return WALL6 == pMap.GameMap[x][y];
// }
// return -1;
// } |
PHP | UTF-8 | 551 | 2.671875 | 3 | [] | no_license | <?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="email" placeholder="email">
<input type="password" name="password" placeholder="password">
<input type="submit">
</form>
<?php
if (isset($_SESSION['errors'])) {
foreach ($_SESSION['errors'] as $error) {
echo $error;
}
$_SESSION = array();
}
?>
</body>
</html>
|
C++ | UTF-8 | 658 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include "loss_function_factory.h"
#include "least_square_loss_function.h"
#include "logistic_loss_function.h"
#include <common_utils.h>
using namespace lncc;
using namespace std;
LossFunction* LossFunctionFactory::CreateLossFunction(const std::string& loss_func) {
LossFunction* obj = NULL;
if (loss_func == "logistic") {
obj = new LogisticLossFunction();
} else if (loss_func == "least_square") {
obj = new LeastSquareLossFunction();
} else {
log_error("Invalid loss function: %s\n", loss_func.c_str());
}
if (obj) {
log_info("Using loss function %s\n", loss_func.c_str());
}
return obj;
}
|
JavaScript | UTF-8 | 1,171 | 3.71875 | 4 | [] | no_license | const expenses = [
{id: 1, desc: "bought potato", amount: 100},
{id: 2, desc: "bought coleslaw", amount: 250},
{id: 3, desc: "bought wheat grass", amount: 150},
];
const newExpenses= [
{id: 4, desc: "bought plastics", amount: 500},
{id: 5, desc: "bought flours", amount: 500}
]
//spread operator to add items into array
let mergedExpenses =[...expenses, ...newExpenses]
//we can also do this if the new expense is a single item.
// const mergedExpenses =[...expenses, newExpenses]
console.log(mergedExpenses);
console.log('****************remove item with id 3 from the array***********************');
// remove item with id number 3 from array
console.log(mergedExpenses =mergedExpenses.filter((expense)=> expense.id!== 3));
console.log('***************************************');
newUpdate ={id: 4, desc: "bought more plastics", amount: 250},
editExpense = (expenses) => {
return expenses.map((expense) =>{
if(expense.id ==4){
return {
...expense,
...newUpdate
}
}else{
return expense;
}
})
};
console.log(editExpense(mergedExpenses));
|
TypeScript | UTF-8 | 2,585 | 2.53125 | 3 | [] | no_license | // Routes to interact with login.
import express from "express";
import { pool } from "../dao/database";
import userDao, { sanitizeUser } from "../dao/userDao";
import { compareHash, hash } from "../hashing";
var jwt = require("jsonwebtoken");
var bodyParser = require("body-parser");
const router = express.Router();
const dao = new userDao(pool);
// to translate JSON in the body
router.use(bodyParser.json());
let publicKey;
const privateKey = (publicKey = "This is my super secret key");
let user;
router.use(express.static("public"));
router.post("/", (req, res) => {
dao.getHashOfUser(req.body.email, (status, data) => {
user = data[0];
if (typeof user != "undefined") {
if (compareHash(user.hash, req.body.password, user.salt)) {
let token = jwt.sign({ email: req.body.email }, privateKey, {
expiresIn: 3600
});
res.json({ jwt: token });
res.status(200);
} else {
res.status(204);
res.json({ error: "Not authorized" });
}
} else {
res.status(204);
res.json({ error: "brukeren finnes ikke" });
}
});
});
router.post("/token", (req, res) => {
let newToken = "";
var token = req.headers["harmoni-token"];
if (token !== undefined) {
jwt.verify(token, publicKey, (err, decoded) => {
if (err) {
res.status(401);
res.json({ error: "You are not logged in" });
} else {
newToken = jwt.sign({ email: decoded.email }, privateKey, {
expiresIn: 1800
});
dao.getUserAllInfoByEMail(decoded.email, (status, data) => {
let id = data[0] === undefined ? undefined : data[0];
res.json({ jwt: newToken, userData: sanitizeUser(data[0]) });
});
}
});
} else {
res.status(401);
res.json({ error: "Token not defined" });
}
});
router.post("/register", (req, res) => {
let data = hash(req.body.password);
req.body.hash = data.hash;
req.body.salt = data.salt;
dao.getUserByEMail(req.body.email, (status, data) => {
user = data[0];
if (typeof user === "undefined") {
dao.addUser(req.body, status => {
if (status !== 401) {
let token = jwt.sign({ email: req.body.email }, privateKey, {
expiresIn: 1800
});
res.json({ jwt: token });
} else {
res.status(401);
res.json({ error: "Could not add user" });
}
});
} else {
res.status(409);
res.json({ error: "the user exists error code:" + status });
}
});
});
module.exports = router;
|
Java | UTF-8 | 701 | 1.882813 | 2 | [] | no_license | package com.rorasoft.roragame.Services.preferences;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.CheckBoxPreference;
import android.util.AttributeSet;
public class SmallIconCheckboxPreference extends CheckBoxPreference {
public SmallIconCheckboxPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SmallIconCheckboxPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return PreferenceConfiguration.getDefaultSmallMode(getContext());
}
}
|
JavaScript | UTF-8 | 3,866 | 2.8125 | 3 | [] | no_license | require('dotenv').config()
const { expect } = require('chai')
const searchAd = require('.')
const { database, models: {User, Advertisement, Merchant } } = require('generisad-data')
const { random } = Math
const { env: { DB_URL_TEST }} = process
describe('logic - search ads', () => {
before(() => database.connect(DB_URL_TEST))
let name, surname, email, password
let image1, title1, description1, price1, location1, date1, product1Id
let image2, title2, description2, price2, location2, date2, product2Id
let query
let domain, name_domain, merchant
beforeEach(async () => {
name = `name-${Math.random()}`
surname = `surname-${Math.random()}`
email = `email-${Math.random()}@domain.com`
password = `password-${Math.random()}`
image1 = `img-${Math.random()}`
title1 = `TitLe-${random()}`
description1 = `description-${Math.random()}`
price1 = `price-${Math.random()}`
location1 = `location-${Math.random()}`
date1 = new Date()
image2 = `img-${Math.random()}`
title2 = `TitLe-${random()}`
description2 = `description-${Math.random()}`
price2 = `price-${Math.random()}`
location2 = `location-${Math.random()}`
date2 = new Date()
name_domain = `name_domain-${Math.random()}`
domain = `domain-${Math.random()}`
await Merchant.deleteMany()
const _merchant = await Merchant.create({ name: name_domain, domain })
merchant = _merchant.id
await User.deleteMany()
const user = await User.create({ name, surname, email, password, merchant_owner: merchant })
id = user.id
await Advertisement.deleteMany()
const product1 = await Advertisement.create({ image: image1, title: title1, description: description1, price: price1, location: location1, date: date1, owner:id,merchant_owner: merchant })
product1Id= product1.id
const product2 = await Advertisement.create({image: image2, title: title2, description: description2, price: price2, location: location2, date: date2, owner:id, merchant_owner: merchant})
product2Id= product2.id
})
it('should succeed on correct data', async () =>{
query = "title"
const ad = await searchAd(query, domain)
expect(ad[0]).to.exist
expect(ad[0].image).to.equal(image1)
expect(ad[0].title).to.equal(title1)
expect(ad[0].description).to.equal(description1)
expect(ad[0].price).to.equal(price1)
expect(ad[0].location).to.equal(location1)
expect(ad[0].merchant_owner.toString()).to.equal(merchant)
expect(ad[1]).to.exist
expect(ad[1].image).to.equal(image2)
expect(ad[1].title).to.equal(title2)
expect(ad[1].description).to.equal(description2)
expect(ad[1].price).to.equal(price2)
expect(ad[1].location).to.equal(location2)
expect(ad[0].merchant_owner.toString()).to.equal(merchant)
})
it('should succeed on query not found', async () =>{
let wrongquery = "oihane"
try{
const ad = await searchAd(wrongquery,domain)
}catch(error) {
expect(error).to.exist
expect(error.message).to.equal(`there are not ads with query ${wrongquery}`)
}
})
it('should fail on wrong ad id type', () =>
expect(() => searchAd(123)).to.throw(`query with value 123 is not a string`)
)
it('should fail on empty or blank', () =>
expect(() => searchAd("")).to.throw(`query is empty or blank`)
)
it('should fail on wrong ad id type', () =>
expect(() => searchAd(undefined)).to.throw(`query with value undefined is not a string`)
)
after(() => database.disconnect())
}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.