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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 5,537 | 2.125 | 2 | [] | no_license | package org.feedworker.client.frontend.panel;
//IMPORT JAVA
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import org.feedworker.client.frontend.table.tableSubtitleDest;
import org.jfacility.javax.swing.Swing;
/**
*
*
* @author luca
*/
public class paneSubtitleDest extends paneAbstract {
private static paneSubtitleDest jpanel = null;
private tableSubtitleDest jtable;
public static paneSubtitleDest getPanel() {
if (jpanel == null)
jpanel = new paneSubtitleDest();
return jpanel;
}
private paneSubtitleDest() {
super("Subtitle Destination");
initializePanel();
initializeButtons();
initListeners();
}
@Override
void initializePanel() {
jtable = new tableSubtitleDest(proxy.getNameTableSubtitleDest());
JScrollPane jScrollTable1 = new JScrollPane(jtable);
jScrollTable1.setAutoscrolls(true);
jpCenter.add(jScrollTable1);
}
@Override
void initializeButtons() {
JButton jbAddRow = new JButton(" + ");
jbAddRow.setToolTipText("Aggiungi riga alla tabella");
jbAddRow.setBorder(BORDER);
jbAddRow.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
jbAddRowMouseClicked();
}
});
JButton jbRemoveRow = new JButton(" - ");
jbRemoveRow.setToolTipText("Rimuovi riga selezionata dalla tabella");
jbRemoveRow.setBorder(BORDER);
jbRemoveRow.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
jbRemoveRowMouseClicked();
}
});
JButton jbRemoveAll = new JButton(" Remove All ");
jbRemoveAll.setToolTipText("Rimuove tutte le serie dalla tabella");
jbRemoveAll.setBorder(BORDER);
jbRemoveAll.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
jtable.removeAllRows();
}
});
JButton jbSaveRules = new JButton(" Salva ");
jbSaveRules.setToolTipText("Salva impostazioni");
jbSaveRules.setBorder(BORDER);
jbSaveRules.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
proxy.saveRules(jtable);
}
});
JButton jbAddDir = new JButton(" Destinazione ");
jbAddDir.setToolTipText("");
jbAddDir.setBorder(BORDER);
jbAddDir.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
jbAddDirMouseClicked();
}
});
int x = 0;
jpAction.add(jbAddRow, gbcAction);
gbcAction.gridx = ++x;
jpAction.add(jbRemoveRow, gbcAction);
gbcAction.gridx = ++x;
jpAction.add(jbRemoveAll, gbcAction);
gbcAction.gridx = ++x;
jpAction.add(jbSaveRules, gbcAction);
gbcAction.gridx = ++x;
jpAction.add(jbAddDir, gbcAction);
}
private void initListeners(){
jtable.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
// Left mouse click
if (SwingUtilities.isRightMouseButton(e)){
// get the coordinates of the mouse click
final Point p = e.getPoint();
if (jtable.columnAtPoint(p)==3){
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem jmiOpenFolder = new JMenuItem("Apri cartella");
jmiOpenFolder.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jmiOpenFolderClicked(p);
}
});
popupMenu.add(jmiOpenFolder);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
});
proxy.setTableListener(jtable);
}
private void jbAddRowMouseClicked() {
DefaultTableModel dtm = (DefaultTableModel) jtable.getModel();
dtm.insertRow(0, new Object[]{null, 1, "normale", null, null, null, false});
}
private void jbRemoveRowMouseClicked() {
int row = jtable.getSelectedRow();
if (row > -1){
row = jtable.convertRowIndexToModel(row);
((DefaultTableModel) jtable.getModel()).removeRow(row);
}
}
private void jbAddDirMouseClicked() {
int row = jtable.getSelectedRow();
if (row > -1) {
String dir = Swing.getDirectory(this, "");
if (dir != null) {
DefaultTableModel dtm = (DefaultTableModel) jtable.getModel();
dtm.setValueAt(dir, row, 3);
}
}
}
private void jmiOpenFolderClicked(Point p){
int row = jtable.rowAtPoint(p);
proxy.openFolder(jtable.getValueAt(row, 3).toString());
}
} |
SQL | UTF-8 | 768 | 2.9375 | 3 | [] | no_license | create trigger editar_pasajero_vista
on reg_pasajero
instead of update
as
begin
update identificacion
set
descripcion = (select descripcion from inserted)
where cod_pasajero = (select cod_pasajero from inserted)
update pasajero
set
nombre_pasajero = (select nombre_pasajero from inserted),
apellido_paterno = (select apellido_paterno from inserted) ,
apellido_materno = (select apellido_materno from inserted) ,
fecha_nacimiento = (select fecha_nacimiento from inserted),
email_pasajero = (select email_pasajero from inserted),
sexo = (select nombre_pasajero from inserted),
cod_pais = (select cod_pais from pais where nombre_pais = (select nombre_pais from inserted))
where cod_pasajero = (select cod_pasajero from deleted)
end |
Java | UTF-8 | 1,735 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package info.pelleritoudacity.android.rcapstone.data.db.entry;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@SuppressWarnings("unused")
@Entity(tableName = "_data")
public class DataEntry {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "_after")
private String after;
@ColumnInfo(name = "_dist")
private int dist;
@ColumnInfo(name = "_mod_hash")
private String modHash;
@ColumnInfo(name = "_whitelist_status")
private String whitelistStatus;
@ColumnInfo(name = "_childrens")
private int childrens;
@ColumnInfo(name = "_before")
private String before;
public DataEntry() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAfter() {
return after;
}
public void setAfter(String after) {
this.after = after;
}
public int getDist() {
return dist;
}
public void setDist(int dist) {
this.dist = dist;
}
public String getModHash() {
return modHash;
}
public void setModHash(String modHash) {
this.modHash = modHash;
}
public String getWhitelistStatus() {
return whitelistStatus;
}
public void setWhitelistStatus(String whitelistStatus) {
this.whitelistStatus = whitelistStatus;
}
public int getChildrens() {
return childrens;
}
public void setChildrens(int childrens) {
this.childrens = childrens;
}
public String getBefore() {
return before;
}
public void setBefore(String before) {
this.before = before;
}
}
|
Java | UTF-8 | 2,416 | 3.1875 | 3 | [] | no_license | package duke.ui;
import duke.task.Task;
import duke.task.TaskList;
/**
* A class that store all the possible String format for Duke for code simplicity.
*/
public class Ui {
public static final String LINEBREAK = "\n";
public static final String LOGO = "D U K E";
public static final String WRONG_DATE_FORMAT = "!!!Err, wrong date format.. (yyyy-mm-dd)!!!";
public static final String KEY_IN_NUMBER = "!!!!!PLease Lah! Key in number!!!!!!";
public static final String EMPTY_TASK = "!!!Walao!NO TASK!!!";
public static final String MISSING_DATE = "Fill ur date lah (add date with / in yyyy-mm-dd format)!";
public static final String COMMAND_ERROR = "!!I DON'T KNOW WHAT U SAYING BRO!!";
public static final String TASK_ERROR = "!!!!!!!!!!Walao, no such task!!!!!!!!!";
public static final String SAVE_TO_FILE_ERROR = "Huh? Where your file?";
public static final String EMPTY_COMMAND = "!!!Walao, command cannot be empty!!!";
public static final String SUCCESSFUL_SAVE = "~File Saved Successfully!~";
public static final String FAREWELL = " I Zao Liao. Don't Miss Meeeeeee.";
public static final String GREETING = "** Awww, need help ah? **";
public static final String EMPTY_FILE = "*Awwww~ You don't have any history of tasks *";
public static final String SUCESSFUL_LOAD = "*Sir, here is your past history: *\n";
public static final String EMPTY_LIST = "Awwww, there is nothing in the list yet";
/**
* Display a message to indicate the given task as done.
* @param t the task to be displayed as done.
*/
public static String doneTask(Task t) {
return "Wah~ You done the task: "
+ " " + t.toString();
}
/**
* Display a message to indicate the given task as deleted.
* @param t the task to be displayed as deleted.
*/
public static String deleteTask(Task t) {
return "Awww~ You've deleted the task: "
+ " " + t.toString();
}
/**
* make a Bigger ChatBox that wrap the name of a given Task.
*
* @param t task to be wrapped.
* @return the String representation of the task name wrapped in a chatBox.
*/
public static String createAddResponse(Task t) {
return "Added liao: "
+ t.toString() + Ui.LINEBREAK
+ "You have " + TaskList.getTasksSize() + " tasks in the list!";
}
}
|
Python | UTF-8 | 396 | 3.65625 | 4 | [] | no_license | #Write your puthon code
s= 'this is my familly and there are many 3 types of family'
# Printing Tricks
#\n meaning new line
#\t meaning tab
#\'' if we want print with ''
#\= Backslash is used as escape character
print 'apple\nbabana'
print 'apple\tmango\torange\tgraphes'
print "'apple\\'mango\\''orange\\''graphes'"
print "'apple\'mango\''orange\''graphes'"
print "https://www.google.com"
|
Python | UTF-8 | 581 | 2.703125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json, datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
return (datetime.datetime.min + obj).time().isoformat()
else:
return super(DateTimeEncoder, self).default(obj)
def extract_datetime(s):
if isinstance(s, datetime.datetime):
return s
return datetime.datetime.strptime(s[:-3] + s[-2:], '%Y-%m-%dT%H:%M%S')
|
Markdown | UTF-8 | 804 | 3.15625 | 3 | [] | no_license | 邮政编码是我们所说的一个精确分类。我们通常依赖于代码保持稳定。如果邮政编码是10012,这个建筑是在曼哈顿。这没什么好争论的,就是这样。
模糊分类需要考虑更多来决定东西应该在哪里出现。模棱两可的东西越多,争论就越多。
电影流派如喜剧和喜剧可能看起来精确。但如果让三个电影评论家呆在一个房间里,让他们把黑色喜剧分到这两个流派之中,他们可能会互相挑战。
模糊和精确也是和上下文相关的。
例如,在编辑这本书的时候,Nicole建议我在上面的例子中使用术语『Postal code』而不是『Zip code』。两者都表达了这一点,但是根据上下文其中一个更精确,其中包括了美国以外的读者。
|
Markdown | UTF-8 | 3,062 | 3.234375 | 3 | [] | no_license | ---
$title: Extensions
$category: Reference
$order: 9
---
# Extensions
[TOC]
Grow has a powerful and simple extension system that enables you to extend the functionality of Grow with plugins.
Extensions are standard Python modules, so your site's `extensions` folder must be set up appropriately, with `__init__.py` files:
[sourcecode:bash]
├── /extensions* # All your extensions
| ├── /__init__.py* # Empty file, required by Python
| ├── /triplicate.py # An example of a Jinja2 extension
| └── /preprocessors* # Subfolder for preprocessor extensions
| ├── /__init__.py* # Empty file, required by Python
| ├── /hello.py # An example of a preprocessor extension
[/sourcecode]
## Jinja2 extensions
Sites can directly extend Grow's Jinja2 rendering environment by including custom Jinja2 extensions. Jinja2 extensions can add site-specific filters, tests, globals, and extend the template parser. [See Jinja2's documentation on extensions](http://jinja.pocoo.org/docs/extensions/).
Specify additional, site-specific Jinja2 extensions in `podspec.yaml`:
[sourcecode:yaml]
# podspec.yaml
extensions:
jinja2:
- extensions.triplicate.Triplicate
[/sourcecode]
Define the extension in a corresponding place in the `/extensions/` folder.
[sourcecode:python]
# /extensions/triplicate.py
from jinja2.ext import Extension
def do_triplicate(value):
return value * 3
class Triplicate(Extension):
def __init__(self, environment):
super(Triplicate, self).__init__(environment)
environment.filters['triplicate'] = do_triplicate
[/sourcecode]
Now you can use your custom `triplicate` filter in your Jinja2 templates.
[sourcecode:yaml]
# /views/base.html
{{10|triplicate}}
[/sourcecode]
## Custom preprocessors
Sites can define custom preprocessors to do pretty much anything at build time and run time. Custom preprocessors can leverage all of the builtin preprocessor controls, such as the `grow preprocess` command, the `--preprocess` flag, and options like `name`, `autorun`, and `tags`.
Specify and use your custom preprocessor in `podspec.yaml`:
[sourcecode:yaml]
# podspec.yaml
extensions:
preprocessors:
- extensions.preprocessors.hello.HelloPreprocessor
preprocessors:
- kind: hello
person: Zoey
[/sourcecode]
Define the preprocessor in a corresponding place in the `/extensions/` folder. Grow preprocessors should subclass `grow.Preprocessor` and use ProtoRPC Messages to define their configuration.
[sourcecode:python]
# /extensions/preprocessors/hello.py
import grow
from protorpc import messages
class HelloPreprocessor(grow.Preprocessor):
"""Says hello to a person."""
KIND = 'hello'
class Config(messages.Message):
person = messages.StringField(1)
def run(self, build=True):
print 'Hello, {}!'.format(self.config.person)
[/sourcecode]
Now, you can use the preprocessor.
[sourcecode:shell]
$ grow preprocess
Hello, Zoey!
[/sourcecode]
|
JavaScript | UTF-8 | 371 | 2.765625 | 3 | [
"CC0-1.0"
] | permissive | function mapInit() {
// follow the Leaflet Getting Started tutorial here
return map;
}
async function dataHandler(mapObjectFromFunction) {
// use your assignment 1 data handling code here
// and target mapObjectFromFunction to attach markers
}
async function windowActions() {
const map = mapInit();
await dataHandler(map);
}
window.onload = windowActions; |
Java | UTF-8 | 3,252 | 3.640625 | 4 | [] | no_license | package com.datastructures.stack;
import java.util.Stack;
public class StackProblems2 {
public int precedance(char i) {
int r = -1;
if (i == '^')
r = 3;
else if (i == '*' || i == '/')
r = 2;
else if (i == '+' || i == '-')
r = 1;
return r;
}
public boolean isOperator(char ch)
{
return ((ch >='A' && ch<='Z')||(ch >='a' && ch<='z') || Character.isDigit(ch));
}
public String infixToPostfix(String exp) {
StringBuilder op = new StringBuilder();
Stack<Character> st = new Stack<Character>();
for (int i = 0; i < exp.length(); i++) {
char c = exp.charAt(i);
if (Character.isAlphabetic(c) || Character.isDigit(c))
op.append(c);
else {
if (st.isEmpty() || (this.precedance(st.peek()) < this.precedance(c)) || c == '(')
st.push(c);
else if (c == ')') {
while (!st.isEmpty() && st.peek() != '(')
op.append(st.pop());
st.pop();
} else {
while (!st.isEmpty() && this.precedance(st.peek()) >= this.precedance(c))
op.append(st.pop());
st.push(c);
}
}
}
while (!st.isEmpty())
op.append(st.pop());
return op.toString();
}
public String infixToPrefix(String exp)
{
StringBuffer s=new StringBuffer(exp);
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)==')')
s.setCharAt(i,'(');
else if(s.charAt(i)=='(')
s.setCharAt(i,')');
}
exp=s.reverse().toString();
s=new StringBuffer(this.infixToPostfix(exp));
return s.reverse().toString();
}
public String postfixToInfix(String exp)
{
Stack<String> st=new Stack<String>();
for(int i=0;i<exp.length();i++)
{
String s="";
if(!isOperator(exp.charAt(i)))
{
String a=st.pop();
String b=st.pop();
s="("+a+exp.charAt(i)+b+")";
}
else
{
s=""+exp.charAt(i);
}
st.push(s);
}
StringBuffer c=new StringBuffer(st.peek());
for(int i=0;i<c.length();i++)
{
if(c.charAt(i)==')')
c.setCharAt(i,'(');
else if(c.charAt(i)=='(')
c.setCharAt(i,')');
}
return c.reverse().toString();
}
public String prefixToInfix(String exp)
{
Stack<String> st=new Stack<String>();
exp=new StringBuffer(exp).reverse().toString();
for(int i=0;i<exp.length();i++)
{
String s="";
if(!isOperator(exp.charAt(i)))
{
String a=st.pop();
String b=st.pop();
s="("+a+exp.charAt(i)+b+")";
}
else
{
s=""+exp.charAt(i);
}
st.push(s);
}
return st.peek();
}
}
|
C# | UTF-8 | 788 | 3.0625 | 3 | [] | no_license | namespace Molmed.SQAT.DBObjects
{
public class Plate : Identifiable
{
private string MyDescription;
public Plate(int ID, string name, string description)
: base(ID, name)
{
MyDescription = description;
}
public string Description
{
get
{
return MyDescription;
}
}
}
public class PlateCollection : System.Collections.CollectionBase
{
public void Add(Plate newItem)
{
List.Add(newItem);
}
public Plate Item(int Index)
{
return (Plate)List[Index];
}
public void SetItem(int Index, Plate Item)
{
List[Index] = Item;
}
}
} |
Java | UTF-8 | 2,246 | 2.046875 | 2 | [] | no_license | package de.ancud.camunda.connector.sql.impl;
import de.ancud.camunda.connector.sql.SqlConnector;
import de.ancud.camunda.connector.sql.SqlRequest;
import de.ancud.camunda.connector.sql.SqlResponse;
import de.ancud.camunda.connector.sql.constants.ConnectorKeys;
import de.ancud.camunda.connector.sql.init.DataSourceConfig;
import de.ancud.camunda.connector.sql.service.SqlConnectorService;
import de.ancud.camunda.connector.sql.validator.RequestTypeChecker;
import org.camunda.connect.impl.AbstractConnector;
import org.camunda.connect.spi.ConnectorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* @author bnmaxim.
*/
public class SqlConnectorImpl extends AbstractConnector<SqlRequest, SqlResponse> implements SqlConnector {
private static Logger _log = LoggerFactory.getLogger(SqlConnectorImpl.class.getName());
private final RequestTypeChecker checker = new RequestTypeChecker();
private final DataSourceConfig dataSourceConfig = new DataSourceConfig();
private SqlConnectorService connectorService;
public SqlConnectorImpl() {
this(SqlConnector.ID);
}
public SqlConnectorImpl(String connectorId) {
super(connectorId);
}
public SqlRequest createRequest() {
return new SqlRequestImpl(this);
}
public ConnectorResponse execute(SqlRequest request) {
Map<String, Object> params = request.getRequestParameters();
SqlResponseImpl sqlResponse = new SqlResponseImpl();
if (checker.isSqlSelect(params)) {
String selectQuery = (String) params.get(ConnectorKeys.INPUT_KEY_SQL_SELECT);
List<Map<String, Object>> sqlResult = getSqlConnectorService(params).executeSelectQuery(selectQuery);
sqlResponse.addSqlResultParameter(sqlResult);
}
return sqlResponse;
}
private SqlConnectorService getSqlConnectorService(Map<String, Object> params) {
if (this.connectorService == null) {
Properties connProps = dataSourceConfig.getDBConnectionInfo(params);
this.connectorService = new SqlConnectorService(connProps);
}
return this.connectorService;
}
}
|
C++ | UTF-8 | 2,386 | 2.90625 | 3 | [] | no_license | #include "pscx_bios.h"
#include <fstream>
#include <iterator>
//------------------------------------------------
// TODO : to implement the loadBios function.
// It should load the BIOS binary file into array of bytes u8 (m_data).
//
// Rust:
// pub fn new(path: &Path) -> Result<Bios> {
// let file = try!(File::open(path));
//
// let mut data = Vec::new();
//
// Load the BIOS
// try!(file.take(BIOS_SIZE).read_to_end(&mut data));
//
// if data.len() == BIOS_SIZE as usize {
// Ok(Bios { data: data })
// } else {
// Err(Error::new(ErrorKind::InvalidInput,
// "Invalid_BIOS_size"))
// }
//--------------------------------------------------
Bios::BiosState Bios::loadBios(std::string path)
{
// // TODO : to implement the loadBios function.
// // It should load the BIOS binary file into array of bytes u8 (m_data).
// // https://stackoverflow.com/questions/15138353/how-to-read-a-binary-file-into-a-vector-of-unsigned-chars
// выбрасывает std::bad_cast exception
std::basic_ifstream<char> biosFile(path, std::ios::in | std::ios::binary);
if (!biosFile.good())
return BIOS_STATE_INCORRECT_FILENAME;
const uint32_t biosSize = 512 * 1024; // 512 kb
// Load the BIOS
m_data.insert(m_data.begin(), std::istreambuf_iterator<char>(biosFile), std::istreambuf_iterator<char>());
biosFile.close();
if (m_data.size() != biosSize)
return BIOS_STATE_INVALID_BIOS_SIZE;
//##################### old version
// FILE *file;
// if((file = fopen(path.c_str(), "rb")) == NULL)
// {
// return BIOS_STATE_INCORRECT_FILENAME;
// }
// size_t bios_size = 512 * 1024;
// size_t bytes_readed;
// m_data.resize(bios_size);
// bytes_readed = fread(m_data.data(), sizeof(uint8_t), bios_size, file);
// fclose(file);
// if(bytes_readed != bios_size)
// return BIOS_STATE_INVALID_BIOS_SIZE;
return BIOS_STATE_SUCCESS;
}
uint32_t Bios::load32(uint32_t offset) const
{
uint32_t b0 = m_data[offset + 0];
uint32_t b1 = m_data[offset + 1];
uint32_t b2 = m_data[offset + 2];
uint32_t b3 = m_data[offset + 3];
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
uint8_t Bios::load8(uint32_t offset) const
{
return m_data[offset];
} |
Python | UTF-8 | 4,626 | 3.28125 | 3 | [] | no_license | import csv
import time
from crate import client
import random
from datetime import datetime
import os.path as path
def connectCrate():
time.sleep(10)
# 1- Creamos la conexion
try:
connection = client.connect('crate:4200',timeout=5,error_trace=True,backoff_factor=0.2)
print("CONNECT OK")
except Exception as err:
print("CONNECT ERROR: %s" % err)
# 2- Cogemos el cursor
cursor = connection.cursor()
# 3- Creamos una tabla llamada peliculas
try:
print("CREATE TABLE: create table peliculas(id int, titulo text, ano int)")
cursor.execute("CREATE TABLE peliculas(id int, titulo text, ano int)")
print("CREATE TABLE OK")
except Exception as err:
print("No se ha podido crear la tabla")
# 4- Añadimos 10 peliculas a la tabla
try:
print ("INSERTS:")
cursor.execute("insert into peliculas values (1, 'Pinocho',1940)")
print ("\tinsert into peliculas values (1, 'Pinocho',1940)")
cursor.execute("insert into peliculas values (2, 'Dumbo',1941)")
print("\tinsert into peliculas values (2, 'Dumbo',1941)")
cursor.execute("insert into peliculas values (3, 'Peter Pan',1953)")
print("\tinsert into peliculas values (3, 'Peter Pan',1953)")
cursor.execute("insert into peliculas values (4, 'La dama y el vagabundo',1955)")
print("\tinsert into peliculas values (4, 'La dama y el vagabundo',1955)")
cursor.execute("insert into peliculas values (5,'101 dalmatas',1961)")
print("\tinsert into peliculas values (5,'101 dalmatas',1961)")
cursor.execute("insert into peliculas values (6, 'Mary Poppins',1964)")
print ("\tinsert into peliculas values (6, 'Mary Poppins',1964)")
cursor.execute("insert into peliculas values (7, 'El libro de la selva',1967)")
print("\tinsert into peliculas values (7, 'El libro de la selva',1967)")
cursor.execute("insert into peliculas values (8, 'Los tres mosqueteros',1993)")
print("\tinsert into peliculas values (8, 'Los tres mosqueteros',1993)")
cursor.execute("insert into peliculas values (9, 'El rey leon',1994)")
print("\tinsert into peliculas values (9, 'El rey leon',1994)")
cursor.execute("insert into peliculas values (10, 'Toy Story',1995)")
print("\tinsert into peliculas values (10, 'Toy Story',1995)")
print("INSERT OK")
except Exception as err:
print("No se ha podido insertar datos en la tabla peliculas")
# 5- Haremos un select para ver que se han añadido bien las 10 peliculas
try:
time.sleep(10)
print ("SELECT: select * from peliculas order by id")
cursor.execute("select * from peliculas order by id")
print("SELECT OK")
print ("Los elementos añadidos son: ", cursor.fetchall())
except Exception as err:
print("No se ha podido realizar la select")
#Ahora crearemos una segunda tabla. que añada cada 30 segundos un numero aleatorio.
#5º CREAMOS LA TABLA NUMEROS
try:
print("CREATE TABLE: create table numeros(numeros int, fecha text, hora text)")
cursor.execute("CREATE TABLE numeros(numero int, fecha text, hora text)")
print("TABLA CREADA OK")
except Exception as err:
print("No se ha podido crear la tabla")
#6º MIRAR SI EXISTE EL FICHERO, Y SI EXISTE AÑADIMOS LOS ROWS QUE HAY EN EL FICHERO
if not path.exists('rows.csv'):
print("Creando fichero rows.csv")
with open('rows.csv', 'w', newline='') as csvfile:
fieldnames = ['numero', 'fecha','hora']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
#7º - CADA 30 segundos, AÑADIREMOS UN NUEVO ROW EN LA BASE DE DATOS, Y ESCRIBIREMOS EN EL FICHERO LOS DATOS.
while True:
numero = random.randint(1, 100) # coge un numero aleatorio del 1 al 100
now = datetime.now()
date=now.date() # coge la fecha de hoy
hora=now.time().__str__() # coge la hora exacta
cursor.execute("insert into numeros values (?, ?, ?)", (numero,str(date),hora)) # añadimos el elemento en la tabla
texto ="".join((str(numero),",",str(date),",",hora))
print("insert into numeros values (",texto,")",)
#cerraremos y abriremos el fichero cada vez para q se vayan actualizando los datos.
file = open('rows.csv', 'a', newline='') # abriremos el fichero
file.write(texto+"\n") # escribimos la linea
print ("Linea añadida al fichero: ",texto)
file.close() # cerramos el fichero
time.sleep(30) # espera 30 segundos
if __name__ == "__main__":
connectCrate()
|
JavaScript | UTF-8 | 2,668 | 3.703125 | 4 | [] | no_license | const select = document.querySelector('select');
document.body.style.padding = '10px';
select.onchange = function() {
const choice = select.value;
createCalendar(choice, 2022);
}
function daysInMonth(month, year)
{
var d = new Date(year, month, 0);
return d.getDate();
}
const list = document.querySelector('.output');
function createCalendar(choice, yr) {
// alert(choice);
let m = choice;
//let yr = 2022;
let tmpDate = new Date(yr,m,0);
tmpDate.setDate(1);//set to 1st of a month
let num = daysInMonth(m, yr);
let dayofweek = tmpDate.getDay(); //index : 0 for sun, 1 mon, --- 6 for sat
// alert("date: " + tmpDate);
// alert("days in month: " + num);
// alert("day of week: " + dayofweek);
list.innerHTML = '';
let calTable = document.createElement("table");
let tblbody = document.createElement("tbody");
let weekdays = ["B.", "B.e.", "Ç.a.", "Ç.", "C.a.", "C.", "Ş."];
let headRow = document.createElement('tr');
for (let d of weekdays) {
let dayCell = document.createElement("td");
dayCell.setAttribute("style","width: 10%;");
let dayTxt = document.createTextNode(d);
dayCell.appendChild(dayTxt);
headRow.appendChild(dayCell);
}
// cRow.classList.add("head");
tblbody.appendChild(headRow);
//h1.textContent = choice;
let total_entries = num + dayofweek;
let t_rows = Math.round(total_entries /7.0);
// alert(t_rows);
let count = 1;
for (let i = 0; i <= t_rows; i++) {
let cRow = document.createElement('tr');
for(let j = 0; j < 7; j++) {
let cCell = document.createElement('td');
cCell.setAttribute("style","width: 10%;");
if(i === 0 && j < dayofweek){
let cellTxt = document.createTextNode(" ");
cCell.appendChild(cellTxt);
}
else if (count <= num){
let cellTxt = document.createTextNode(count.toString());
cCell.appendChild(cellTxt);
//cCell.innerHTML = count;
count ++;
}
else {
break;
}
cRow.appendChild(cCell);
}
tblbody.appendChild(cRow);
}
calTable.appendChild(tblbody);
// sets the border attribute of tbl to 2;
calTable.setAttribute("border", "8");
calTable.setAttribute.backgroundColor = "red";
calTable.setAttribute("style", "background-color: lightblue; padding: 3%;");
// calTable.setAttribute("style", "padding: 1%;")
list.appendChild(calTable);
}
createCalendar(1, 2022); //Jan 2022 |
Markdown | UTF-8 | 5,581 | 2.765625 | 3 | [] | no_license | # 安裝 PHP 語言
## 安裝前準備
* 請先安裝 [Apache](../12-Apache/)
## 安裝各版本的 PHP
* 安裝 PHP 5.6 版本 `brew install php@5.6`
* 安裝 PHP 7.0 版本 `brew install php@7.0`
* 安裝 PHP 7.1 版本 `brew install php@7.1`
* 安裝 PHP 最新 版本 `brew install php`
## Cli 指令模式設定
* 用 Sublime Text 2 打開編輯 `~/.zshrc`,終端機執行指令 `subl ~/.zshrc`
* 稍微檢查一下以下路徑是否存在後在檔案最後方新增以下內容
```
## PHP 5.6
#export PATH="/usr/local/opt/php@5.6/bin:$PATH"
#export PATH="/usr/local/opt/php@5.6/sbin:$PATH"
## PHP 7.0
#export PATH="/usr/local/opt/php@7.0/bin:$PATH"
#export PATH="/usr/local/opt/php@7.0/sbin:$PATH"
## PHP 7.1
#export PATH="/usr/local/opt/php@7.1/bin:$PATH"
#export PATH="/usr/local/opt/php@7.1/sbin:$PATH"
## PHP 7
#export PATH="/usr/local/opt/php/bin:$PATH"
#export PATH="/usr/local/opt/php/sbin:$PATH"
```
* **Cli** 要切換版本的話,就把 `~/.zshrc` 該版的註解拿掉
* 然後終端機執行指令 `source ~/.zshrc`
## Apache 模式設定
* 用 Sublime Text 2 打開編輯 `/usr/local/etc/httpd/httpd.conf`,終端機執行指令 `subl /usr/local/etc/httpd/httpd.conf`
* 稍微檢查一下以下路徑是否存在後在檔案最後方加入以下內容
```
#LoadModule php5_module /usr/local/opt/php@5.6/lib/httpd/modules/libphp5.so
#LoadModule php7_module /usr/local/opt/php@7.0/lib/httpd/modules/libphp7.so
#LoadModule php7_module /usr/local/opt/php@7.1/lib/httpd/modules/libphp7.so
#LoadModule php7_module /usr/local/opt/php@7.2/lib/httpd/modules/libphp7.so
```
* 若要更換版本,就把 **LoadModule** 該版本註解拿掉後,重開 Apache 即可
## 設定 Apache 讀取執行 PHP
* 用 Sublime Text 2 打開編輯 `/usr/local/etc/httpd/httpd.conf`,終端機執行指令 `subl /usr/local/etc/httpd/httpd.conf`,修改以下內容
```
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
```
```
<IfModule dir_module>
DirectoryIndex index.php index.html
</IfModule>
<FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>
```
* 重開 Apache,終端機執行指令 `sudo apachectl -k restart`
## 各版本的 php.ini
* PHP 5.6 版本 - `/usr/local/etc/php/5.6/php.ini`
* PHP 7.0 版本 - `/usr/local/etc/php/7.0/php.ini`
* PHP 7.1 版本 - `/usr/local/etc/php/7.1/php.ini`
* PHP 7.2 版本 - `/usr/local/etc/php/7.2/php.ini`
## 安裝 imagick
* 先要安裝 **imagemagick**,終端機執行指令 `brew install imagemagick`
* :exclamation: 請先將 Cli 的 php 切換到指定的版本,可以用 `php -v` 檢查目前 Cli 的 php 版本
* 終端機執行指令 `pecl install imagick`,中間有個 `Please provide the prefix of Imagemagick installation [autodetect]`,直接按 `enter` 即可
* 結果若是失敗如果出現 `configure: error: Please reinstall the pkg-config distribution`,那就終端機執行指令 `brew reinstall pkg-config` 後再執行 `pecl install imagick` 即可
* 檢查該版本的 `php.ini` 內是否有 `extension="imagick.so"`
* Cli 下要找 php.ini 位置,終端機執行指令 `php --ini` 即可
* 完成後重開 Apache,終端機執行指令 `sudo apachectl -k restart`,然後看 `phpinfo()` 是否有 `imagick`
## 安裝 redis
* 先要安裝 **redis**,終端機執行指令 `brew install redis`
* :exclamation: 請先將 Cli 的 php 切換到指定的版本,可以用 `php -v` 檢查目前 Cli 的 php 版本
* 終端機執行指令 `pecl install redis`,中間有個 `enable igbinary serializer support? [no] :` 與 `enable lzf compression support? [no] :`,都直接按 `enter` 即可
* 結果若是失敗如果出現 `configure: error: Please reinstall the pkg-config distribution`,那就終端機執行指令 `brew reinstall pkg-config` 後再執行 `pecl install redis` 即可
* 檢查該版本的 `php.ini` 內是否有 `extension="redis.so"`
* Cli 下要找 php.ini 位置,終端機執行指令 `php --ini` 即可
* 完成後重開 Apache,終端機執行指令 `sudo apachectl -k restart`,然後看 `phpinfo()` 是否有 `redis`
## 安裝 Deployer 部署器
* 終端機執行指令 `curl -LO https://deployer.org/deployer.phar`
* 終端機執行指令 `mv deployer.phar /usr/local/bin/dep`
* 終端機執行指令 `chmod +x /usr/local/bin/dep`
* 檢查是否安裝成功,重新開啟終端機,執行指令 `dep -v`
## 安裝 Composer 套件管理
* 終端機執行指令 `php -r "readfile('https://getcomposer.org/installer');" > composer-setup.php`
* 終端機執行指令 `php composer-setup.php`
* 終端機執行指令 `php -r "unlink('composer-setup.php');"`
* 終端機執行指令 `mv composer.phar /usr/local/bin/composer`
* 檢查是否安裝成功,重新開啟終端機,執行指令 `composer -v`
## 重點整理
* PHP 5.6 版本 ini 檔案 - `/usr/local/etc/php/5.6/php.ini`
* PHP 7.0 版本 ini 檔案 - `/usr/local/etc/php/7.0/php.ini`
* PHP 7.1 版本 ini 檔案 - `/usr/local/etc/php/7.1/php.ini`
* PHP 7.2 版本 ini 檔案 - `/usr/local/etc/php/7.2/php.ini`
* Apache 若要更換版本,就用 Sublime Text 2 打開編輯 `/usr/local/etc/httpd/httpd.conf`,終端機執行指令 `subl /usr/local/etc/httpd/httpd.conf`,把 **LoadModule** 該版本註解拿掉後,重開 Apache 即可
* Cli 要切換版本的話,就用 Sublime Text 2 打開編輯 `~/.zshrc`,終端機執行指令 `subl ~/.zshrc`,把要的版本註解拿掉,然後終端機執行指令 `source ~/.zshrc` 即可
|
C# | UTF-8 | 1,473 | 2.796875 | 3 | [
"MIT"
] | permissive | using OpenTK.Graphics.OpenGL;
namespace GameStructure {
class FPSTestState : IGameObject
{
TextureManager _textureManager;
Font _font;
Text _fpsText;
Text _longText;
Renderer _renderer = new Renderer();
FramesPerSecond _fps = new FramesPerSecond();
public FPSTestState(TextureManager textureManager) {
_textureManager = textureManager;
_font = new Font(textureManager.Get("font"), FontParser.Parse("Fonts/Arial/font.fnt"));
_fpsText = new Text("FPS:", _font);
}
public void Update(double deltaTime)
{
_fps.Process(deltaTime);
}
public void Render()
{
GL.ClearColor(0,0,0,0);
GL.Clear(ClearBufferMask.ColorBufferBit);
_fpsText = new Text ("FPS: " + _fps.CurrentFPS.ToString("00.0"), _font);
_fpsText.SetPosition(-(_fpsText.Width / 2),0);
_fpsText.SetColor(new Color(1,1,1,1));
// Let's simulate drawing a ton of sprites
// for (int i = 0; i < 10000; i++) {
// _renderer.DrawText(_fpsText);
// }
_longText = new Text("The quick brown fox jumps over the lazy dog", _font, 300);
_longText.SetPosition(-(_longText.Width / 2), -30);
_longText.SetColor(new Color(1,1,1,1));
_renderer.DrawText(_longText);
_renderer.Render();
}
}
} |
Java | UTF-8 | 950 | 2.0625 | 2 | [] | no_license | package info.bubna.up.controller;
import info.bubna.up.dto.WebDisciplineDTO;
import info.bubna.up.dto.WebMarkDTO;
import info.bubna.up.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping("/{id}/disciplines")
public List<WebDisciplineDTO> getDisciplines(@PathVariable("id") UUID id) {
return userService.getDisciplines(id);
}
@GetMapping("/{id}/marks")
public List<WebMarkDTO> getMarks(@PathVariable("id") UUID id) {
return userService.getMarks(id);
}
}
|
Python | UTF-8 | 706 | 2.625 | 3 | [] | no_license | import cv2
import numpy
def generate():
model = cv2.face.LBPHFaceRecognizer_create()
face_list = []
face_ids = []
for x in range(1, 31):
image = cv2.imread(f"./dataset-train/{x}.jpg", cv2.IMREAD_GRAYSCALE)
face_recognizer = cv2.CascadeClassifier('./models/haarcascade_frontalface_default.xml')
face = face_recognizer.detectMultiScale(image, 1.01, 125)
if face is not None and len(face) > 0:
for (x, y, w, h) in face:
face_image = image[y:y + h, x:x + w]
face_list.append(face_image)
face_ids.append(1)
model.train(face_list, numpy.array(face_ids))
model.write('./models/trained_model.yml')
|
Java | UTF-8 | 682 | 2.203125 | 2 | [] | no_license | package com.myfinance.personalbudget.domain;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.List;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString(exclude = "transactions")
public class Counterparty extends AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
@NotBlank(message = "Name is mandatory")
private String name;
@OneToMany(mappedBy = "counterparty", cascade = CascadeType.ALL)
private List<Transaction> transactions;
public Counterparty(String name) {
this.name = name;
}
}
|
Markdown | UTF-8 | 9,955 | 3.328125 | 3 | [] | no_license | # 这是开篇
有人说,暂存区是 Git 最精彩的设计,同时也是最难理解的部分,两者我都感觉不太明显,但当我想写关于暂存区的理解后,发现的确不怎么好讲,这个玩意,有点只可意会的感觉,用 Git 用熟练了,很自然体会到暂存区设计的精彩之处。
在我看来,学习其他命令之前,对暂存区有一个概念和大概理解是非常重要的,因为,很多命令都涉及到了它。
# 为什么 commit 之前要先 add 一下呢?
我在刚接触 Git 命令的时候,对 Git 没什么概念,就是赶鸭子上线式的学习,用到什么,就去 Google 什么,例如第一天我搜索的就是“git first commit”,然后搜到很多 Git 的初级教程,几乎都有说先执行 git add ,然后 git commit。在我照着教程一步步 add & commit 的时候,我就在想,commit 就 commit唄,为什么 commit 之前必须要 add 一下呢?
当时才疏学浅,不敢胡乱尝试,担心试错了整不回来原来的样子。现在胆子大了些,决定尝试一下没有 add 的 commit。
通过 echo 命令给 master.txt 文件加了一行内容,然后执行提交:


测试结果很明显,commit 失败,失败原因是没有可以提交的修改,然而奇怪的是,查看 master.txt 文件,内容却已经添加成功。
好在 Git 非常贴心的给了我们详细的错误说明,下面仔细看一下:
```
On branch master
Changes not staged for commit:
modified: master.txt
no changes added to commit
123456
```
英语渣的我最近热衷于翻译:
```
在 master 分支
修改没有被暂存起来以备提交
修改: master.txt
没有可以提交的修改
123456
```
从这个提示信息中,我似乎嗅到了一丝丝的真(jian)相(qing),commit 时检测是否有修改的 master.txt,好像不是我看到的 master.txt。那我看到 master.txt 是什么?我没看到的又是什么?而且它在哪里?
答案就比较明显了,肯定在 Git 的暂存区(不然我为啥要举这个例子,哈哈)。
git commit 执行时,会提交暂存区的内容。git add 命令会将我们看到的修改添加到暂存区中,这就是为什么 git commit 之前要先执行 git add 的原因。
接着上面的问题,思维稍微发散一下,还可以问出很多问题,例如,add 将修改放入暂存区,那么 add 之前数据存放在哪里?commit 又将存储区的数据提交到什么地方了呢?以及为什么要这么分为几个存储部分?等看完这篇博客,希望你这些问题,都能找到答案。
# Git 可以大概分为三个区
Git 本地数据管理,大概可以分为三个区,工作区,暂存区和版本库。
- **工作区(Working Directory)**
是我们直接编辑的地方,例如 Android Studio 打开的项目,记事本打开的文本等,肉眼可见,直接操作。
- **暂存区(Stage 或 Index)**
数据暂时存放的区域,可在工作区和版本库之间进行数据的友好交流。
- **版本库(commit History)**
存放已经提交的数据,push 的时候,就是把这个区的数据 push 到远程仓库了。
下面是,当开发者通过 git 修改数据时,各区之间的数据传递流程示意图。

为了验证以上流程的正确性,我们可以自己动手实验一下,为了对比三个区之间的数据差别,过程中,可以借助神奇的 diff 命令。
| 命令 | 作用 |
| ----------------- | ---------------- |
| git diff | 工作区 vs 暂存区 |
| git diff head | 工作区 vs 版本库 |
| git diff --cached | 暂存区 vs 版本库 |
现在三个区的数据是一致的,执行 git diff 命令都为空
| 命令 | 接果 |
| ------------------------------------- | ------------------------------------------------------------ |
| (工作区 vs 暂存区)git diff |  |
| | |
| (工作区 vs 版本库)git diff head |  |
| | |
| (暂存区 vs 版本库)git diff --cached |  |
| | |
然后给 master.txt 添加一行内容后,现在工作区内容发生变化,暂存区和版本库内容不变。

| 命令 | 接果 |
| ------------------------------------- | ------------------------------------------------------------ |
| (工作区 vs 暂存区)git diff |  |
| | |
| (工作区 vs 版本库)git diff head |  |
| | |
| (暂存区 vs 版本库)git diff --cached |  |
| | |
执行git add 操作后,修改同步到暂存区,现在工作区和暂存区数据一致。

| 命令 | 接果 |
| ------------------------------------- | ------------------------------------------------------------ |
| (工作区 vs 暂存区)git diff |  |
| | |
| (工作区 vs 版本库)git diff head |  |
| | |
| (暂存区 vs 版本库)git diff --cached |  |
执行 git commit 操作后,修改已经同步到版本库,三区数据再次保持一致。

| 命令 | 接果 |
| ------------------------------------- | ------------------------------------------------------------ |
| (工作区 vs 暂存区)git diff |  |
| (工作区 vs 版本库)git diff head |  |
| | |
| (暂存区 vs 版本库)git diff --cached |  |
| | |
# Stage 赋予 Git 更多灵活性
不知道时,你对它可能毫无所感。知道后,你一定会感动地想哭,并十分之膜拜 Git 的开发者- Linus Torvalds ,stage 就是这么精彩的玩意。以下看起来比较束手无策的场景,只要理解 stage,用好相应命令,都能轻易解决:
- 修改了4个文件,在不放弃任何修改的情况下,其中一个文件不想提交,如何操作?(没add : git add 已经add: git reset --soft )
- 修改到一半的文件,突然间不需要或者放弃修改了,怎么恢复未修改前文件? (git checkout)
- 代码写一半,被打断去做其他功能开发,未完成代码保存?(git stash)
- 代码写一半,发现忘记切换分支了?(git stash & git checkout)
- 代码需要回滚了?(git reset)
- 等等
上面提到的 checkout & stash & reset 等命令,通过不同的参数搭配使用,可以在工作区,暂存区和版本库之间,轻松进行数据的来回切换。
例如前篇 Branch 博客用到的 git reset 回滚命令,带上不同参数就有不同的作用,如下:
| 命令 | 作用 |
| ----------------- | ---------------------- |
| git reset --soft | 暂存区->工作区 |
| git reset --mixed | 版本库->暂存区 |
| git reset --hard | 版本库->暂存区->工作区 |
完事大家可以自己新建一个测试 Demo,多尝试一下,相信你会因为暂存区的存在更加地喜欢 Git。
# 这是结尾
暂存区是介于工作区和版本库之间的一个中间存储状态,很多命令都会涉及暂存区的状态,因此理解暂存区这一个存在是至关重要的。
希望这篇文章能给你的 Git 学习带来帮助,同时,如有错误之处还望指出,下篇博客见,see you next blog!
|
C++ | UTF-8 | 482 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int LCS(char A[ ], int n, char B[ ], int m) {
}
int find(int A[ ], int e, int lo, int hi) {
while ((lo < hi--) && (e != A[hi])) cout << hi << endl;
return hi;
}
int main() {
//int A[2] = {0, 2};
//int idx = find(A, 1, 0, 2);
//cout << "idx = " << idx << endl;
int i = 1, j = 2, k;
k = i+++j;
cout << k << endl;
cout << i << endl;
cout << j << endl;
return 0;
}
|
Markdown | UTF-8 | 6,177 | 2.875 | 3 | [] | no_license | 自作のReact Hooksをメモするためのプロジェクト
## ビルド
```
$ npm start
```
## hooks
### usePrevious
レンダリング時に、指定した値が変更される前の値を取得することができる
cloneDeepを使って、deepなオブジェクトの深い部分が変更されても前の値を保持できるようにしている
```.ts
interface UsePreviousOption {
deepCopy?: boolean
}
/**
* 引数に指定した値を保存し、次のレンダリング時に返り値として所得することができます。
* 初回レンダリング時の返り値は undefined になります
*
* @param value 保存する値
* @param deepCopy trueを指定することで、lodashのcloneDeepを使ってdeepCopyした値を保存する
*
* @return preValue 前回保存された値
*/
export function usePrevious<T>(
value: T,
option: UsePreviousOption = {}
): T | undefined {
const ref = useRef<T>()
useEffect(() => {
const _value = option.deepCopy ? cloneDeep(value) : value
ref.current = _value
}, [value])
return (ref.current as unknown) as T
}
```
#### 使い方
``` .ts
const preVal = usePrevious(val)
```
### useWatch
```.ts
/**
* マウントのときに発火しないuseEffectを提供します
* アンマウント時に実行する処理を指定することもできます
* @param func 実行する処理
* @param arr 監視対象の値の配列
* @param onDestroy アンマウント時に実行される処理
*/
export function useWatch(
func: () => void | undefined,
arr: any[],
onDestroy: () => void | undefined = () => {}
) {
const [afterMountd, setMounted] = useState(false)
useEffect(() => {
if (afterMountd) {
func()
} else {
setMounted(true)
}
}, arr)
useEffect(() => {
return onDestroy
}, [])
}
```
#### 使い方
useEffectと同じ
```.ts
useWatch(() => {
console.log('watchが発火')
}, [counter])
```
### useCreated
Vue.jsのcreated相当の機能を提供する
コンポーネントマウント時にDOMの更新が行われるよりも先に実行される
```.ts
const useCreatedOpt = {
/**
* コンポーネントが破棄されるときに一度だけ発火する関数
*/
onDestroy: () => {},
/**
* 指定されたonCreated関数の実行をawaitするかどうか
*/
isAwait: false
}
/**
* DOMがレンダリングされる前に一度だけ指定した関数を実行します
* @param onCreated コンポーネントがマウントする前に一度だけ発火する関数。
* @param onDestroy コンポーネントが破棄されるときに発火する関数
* @param isAwait 指定されたonCreated関数の実行をawaitするかどうか
*/
export async function useCreated(
onCreated: () => void,
opt: Partial<typeof useCreatedOpt> = {}
) {
const _opt = {
...useCreatedOpt,
...opt
}
const [isCreated, setCreated] = useState(false)
if (!isCreated) {
setCreated(true)
if (_opt.isAwait) {
await onCreated()
} else {
onCreated()
}
}
useEffect(() => {
return _opt.onDestroy
}, [])
}
```
### 使い方
useEffectなどと同じ、第2引数の型は変わっているので注意
```.ts
useCreated(() => {
console.log('created関数だよ')
})
```
### useInteractJS
InteractJSを使ってコンポーネントを動かすためのフック
```.ts
const initPosition = {
width: 100,
height: 100,
x: 0,
y: 0
}
/**
* HTML要素を動かせるようにする
* 返り値で所得できるrefと、styleをそれぞれ対象となるHTML要素の
* refとstyleに指定することで、そのHTML要素のリサイズと移動が可能になる
* @param position HTML要素の初期座標と大きさ、指定されない場合はinitPositionで指定された値になる
*/
export function useInteractJS(
position: Partial<typeof initPosition> = initPosition
) {
const [_position, setPosition] = useState({
...initPosition,
...position
})
const [isEnabled, setEnable] = useState(true)
const interactRef = useRef(null)
let { x, y, width, height } = _position
const enable = () => {
interact((interactRef.current as unknown) as HTMLElement)
.draggable({
inertia: false
})
.resizable({
// resize from all edges and corners
edges: { left: true, right: true, bottom: true, top: true },
preserveAspectRatio: false,
inertia: false
})
.on('dragmove', event => {
x += event.dx
y += event.dy
setPosition({
width,
height,
x,
y
})
})
.on('resizemove', event => {
width = event.rect.width
height = event.rect.height
x += event.deltaRect.left
y += event.deltaRect.top
setPosition({
x,
y,
width,
height
})
})
}
const disable = () => {
interact((interactRef.current as unknown) as HTMLElement).unset()
}
useEffect(() => {
if (isEnabled) {
enable()
} else {
disable()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isEnabled])
useEffect(()=>{
return disable
},[])
return {
ref: interactRef,
style: {
transform: `translate3D(${_position.x}px, ${_position.y}px, 0)`,
width: _position.width + 'px',
height: _position.height + 'px',
position: 'absolute' as CSSProperties['position']
},
position: _position,
isEnabled,
enable: () => setEnable(true),
disable: () => setEnable(false)
}
}
```
#### 使い方
動かしたいコンポーネントにstyleとrefを設定する
```.ts
const App: React.FC = () => {
const interact = useInteractJS()
return (
<div className="App">
<button onClick={() => interact.enable()}>有効化</button>
<button onClick={() => interact.disable()}>無効化</button>
<div
ref={interact.ref}
style={{
...interact.style,
border: '2px solid #0489B1',
backgroundColor: '#A9D0F5'
}}
/>
</div>
)
}
``` |
PHP | UTF-8 | 2,420 | 2.953125 | 3 | [] | no_license | <?php
require_once 'game.php';
header('Content-type: application/json');
$player1 = 0;
$player2 = 1;
function test_vertical() {
global $game_template, $player1, $player2;
$game = (object) $game_template;
for ($i = 0; $i < 14; $i++) {
$col = $i % 2;
if ($col == 0) {
$player = $player1;
}
else {
$player = $player2;
}
if (!make_move($game, $player, $col)) {
// echo 'row full' . '\n';
}
if (has_won($game, $player)) {
printf("%s won the game\n", $player);
break;
}
}
echo json_encode($game) . "\n";
}
function test_horizontal() {
global $game_template, $player1, $player2;
$game = (object) $game_template;
for ($i = 0; $i < 6; $i++) {
if (!make_move($game, $player1, $i)) {
// echo 'row full' . '\n';
}
if (has_won($game, $player1)) {
printf("%s won the game\n", $player1);
break;
}
}
echo json_encode($game) . "\n";
}
function test_diagnoal() {
global $game_template, $player1, $player2;
$game = (object) $game_template;
make_move($game, $player1, 0);
make_move($game, $player2, 1);
make_move($game, $player1, 2);
make_move($game, $player2, 2);
make_move($game, $player1, 1);
make_move($game, $player2, 3);
make_move($game, $player1, 2);
make_move($game, $player2, 3);
make_move($game, $player1, 4);
make_move($game, $player2, 3);
make_move($game, $player1, 3);
if (has_won($game, $player1)) {
printf("%s won the game\n", $player1);
}
echo json_encode($game) . "\n";
}
function test_diagonal_reversed() {
global $game_template, $player1, $player2;
$game = (object) $game_template;
make_move($game, $player1, 5);
make_move($game, $player2, 4);
make_move($game, $player1, 3);
make_move($game, $player2, 3);
make_move($game, $player1, 4);
make_move($game, $player2, 2);
make_move($game, $player1, 3);
make_move($game, $player2, 2);
make_move($game, $player1, 1);
make_move($game, $player2, 2);
make_move($game, $player1, 2);
if (has_won($game, $player1)) {
printf("%s won the game\n", $player1);
}
echo json_encode($game) . "\n";
}
// test_vertical();
// test_horizontal();
// test_diagnoal();
test_diagonal_reversed();
?> |
C++ | UTF-8 | 551 | 3.015625 | 3 | [] | no_license | #include "Point.h"
#include "Segment.h"
using namespace std;
double Point::distanceToSegment(const Segment &seg) const
{
Point AC(seg.p1().x - x, seg.p1().y - y);
Point BC(seg.p2().x - x, seg.p2().y - y);
Point AB = seg.dP();
double dAH = (AB.x * AC.x + AB.y * AC.y) / AB.norm();
if (dAH < 0 || dAH > AB.norm())
{
return min(AC.norm(), BC.norm());
}
return sqrt(AC.norm2() + dAH * dAH);
}
ostream& operator<<(ostream &out, const Point &p)
{
out << "(" << p.x << "," << p.y << ")";
return out;
}
|
Java | UTF-8 | 557 | 2.265625 | 2 | [] | no_license | package com.security.security;/**
* Created by HT on 2017/10/26.
*/
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.stereotype.Component;
/**
* @author HT
* @create 2017-10-26 11:14
**/
@Component
public class DemoConnectionSignUp implements ConnectionSignUp{
// 根据社交用户信息默认创建用户并返回用户唯一标识
@Override
public String execute(Connection<?> connection) {
return connection.getDisplayName();
}
}
|
Java | UTF-8 | 2,289 | 2.3125 | 2 | [] | no_license | package fun.build4.playground.httpbin;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class AnythingServerApplication {
public static void main(String[] args) {
var app = new SpringApplication(AnythingServerApplication.class);
app.setBannerMode(Mode.OFF);
app.run(args);
}
@RequestMapping({"/anything", "/anything/**"})
public AnythingResponse anything(HttpServletRequest req) {
return AnythingResponse.fromReq(req);
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
private static final class AnythingResponse {
@NonNull private String method;
@NonNull private String url;
@NonNull private String origin;
@NonNull private Map<String, String> headers;
static AnythingResponse fromReq(@NonNull HttpServletRequest req) {
return AnythingResponse.builder()
.method(req.getMethod())
.url(req.getRequestURL().toString())
.origin(getOriginFromRequest(req))
.headers(getHeadersFromRequest(req))
.build();
}
static String getOriginFromRequest(@NonNull HttpServletRequest req) {
var xForwardedFor = req.getHeader("X-Forwarded-For");
if (xForwardedFor != null && !"".equals(xForwardedFor)) {
return xForwardedFor;
}
return req.getRemoteAddr();
}
static Map<String, String> getHeadersFromRequest(@NonNull HttpServletRequest req) {
final Map<String, String> rv = new HashMap<>();
var headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
var key = headerNames.nextElement();
rv.put(key, req.getHeader(key));
}
return rv;
}
}
}
|
PHP | UTF-8 | 3,374 | 3 | 3 | [] | no_license | <?php
function loadRegistrations($filepath){
$jsondata = file_get_contents($filepath);
$arr_data = json_decode($jsondata,true);
return $arr_data;
}
function saveDataJson($filepath, $name, $email, $phone){
try {
$contact = array(
'name' => $name,
'email' => $email,
'phone' => $phone
);
// lay du lieu tu file json ra
$arr_data = loadRegistrations($filepath);
// push du lieu nguoi dung vao mang
array_push($arr_data,$contact);
// tra ve dang json
$jsonData = json_encode($arr_data,JSON_PRETTY_PRINT);
// Luu du lieu tro lai file data.json
file_put_contents($filepath,$jsonData);
echo "<span style='color: blue'>luu du lieu thanh cong !</span>";
}catch (Exception $e){
echo "loi: ",$e->getMessage(), "<br>";
}
}
$nameErr = null;
$emailErr = null;
$phoneErr = null;
$name = null;
$email = null;
$phone = null;
if ($_SERVER["REQUEST_METHOD"]=="POST"){
$name= $_POST["name"];
$phone= $_POST["phone"];
$email= $_POST["email"];
$has_error = false;
// var_dump($_POST);
if (empty($name)){
$nameErr = "Nhap ten!";
$has_error = true;
}
if (empty($email)){
$emailErr = "nhap Email!";
$has_error = true;
}else{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Dinh dang Email sai (name@abc.abc)!";
$has_error = true;
}
}
if (empty($phone)){
$phoneErr = "Nhap so dien thoai!";
$has_error = true;
}
if ($has_error== false){
saveDataJson("data.json", $name, $email, $phone);
$name = null;
$email = null;
$phone = null;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dang ky nguoi dung</title>
</head>
<style>
table{
border-collapse: collapse;
border: 2px solid;
}
th, td{
padding: 5px;
font-size: 16px;
color: blue;
border: 1px solid;
}
</style>
<body>
<form method="post">
<fieldset>
<legend>Dang ky nguoi dung</legend>
<label for="name">Ten: </label><br>
<input type="text" name="name" id="name">
<span style="color: red"><?php echo $nameErr; ?></span> <br>
<label for="email"> Email: </label><br>
<input type="text" name="email" id="email">
<span style="color: red"><?php echo $emailErr; ?></span> <br>
<label for="phone"> So dien thoai : </label><br>
<input type="text" name="phone" id="phone">
<span style="color: red"><?php echo $phoneErr; ?></span> <br>
<button type="submit">dang ky</button>
</fieldset>
</form>
<?php
$loadData = loadRegistrations("data.json");
?>
<h2>danh sach da dang ky</h2>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<?php foreach ($loadData as $key): ?>
<tr>
<td><?php echo $key['name'] ?></td>
<td><?php echo $key['email'] ?></td>
<td><?php echo $key['phone'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
|
Python | UTF-8 | 509 | 2.734375 | 3 | [] | no_license | import os
from django.core.exceptions import ValidationError
def validate_file_extension(value):
valid_extensions = ['.ods', '.xls', '.xlsx']
validate(value,valid_extensions)
def validate_file_extension_csv(value):
valid_extensions = ['.csv']
validate(value,valid_extensions)
def validate(value,valid_extensions):
ext = os.path.splitext(value.name)[1]
if not ext in valid_extensions:
raise ValidationError(u'File extension not valid, must be ' + ', '.join(valid_extensions)) |
Swift | UTF-8 | 7,784 | 2.578125 | 3 | [] | no_license | //
// FormMDSignature.swift
// SimpleDraw
//
// Created by DNA on 1/17/17.
// Copyright © 2017 DNA. All rights reserved.
//
import UIKit
class FormMDSignature: UIView {
var lastPoint = CGPoint(x: 0, y: 0)
var topLeftPoint = CGPoint(x: 0, y: 0)
var bottomRightPoint = CGPoint(x: 0, y: 0)
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 3.0
var opacity: CGFloat = 1.0
var swiped = false
@IBOutlet weak var mainImageView: UIImageView!
let nibName = "FormMDSignature"
var view : UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetUp()
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetUp()
}
func xibSetUp() {
self.view = loadViewFromNib()
self.view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)
NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
topConstraint.isActive = true
bottomConstraint.isActive = true
leadingConstraint.isActive = true
trailingConstraint.isActive = true
self.addConstraints([topConstraint,
bottomConstraint,
leadingConstraint,
trailingConstraint])
self.clearCanvas()
}
func loadViewFromNib() ->UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.swiped = false
if let touch = touches.first {
self.lastPoint = touch.location(in: self)
if self.lastPoint.x < self.topLeftPoint.x {
self.topLeftPoint.x = self.lastPoint.x
}
if self.lastPoint.y < self.topLeftPoint.y {
self.topLeftPoint.y = self.lastPoint.y
}
if self.lastPoint.x > self.bottomRightPoint.x {
self.bottomRightPoint.x = self.lastPoint.x
}
if self.lastPoint.y > self.bottomRightPoint.y {
self.bottomRightPoint.y = self.lastPoint.y
}
print("topLeftPoint: \(topLeftPoint)")
print("bottomRightPoint: \(bottomRightPoint)")
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: self)
self.drawLine(from: self.lastPoint, to: currentPoint)
self.lastPoint = currentPoint
if self.lastPoint.x < self.topLeftPoint.x {
self.topLeftPoint.x = self.lastPoint.x
}
if self.lastPoint.y < self.topLeftPoint.y {
self.topLeftPoint.y = self.lastPoint.y
}
if self.lastPoint.x > self.bottomRightPoint.x {
self.bottomRightPoint.x = self.lastPoint.x
}
if self.lastPoint.y > self.bottomRightPoint.y {
self.bottomRightPoint.y = self.lastPoint.y
}
print("topLeftPoint: \(topLeftPoint)")
print("bottomRightPoint: \(bottomRightPoint)")
}
}
func drawLine(from: CGPoint, to: CGPoint) {
UIGraphicsBeginImageContext(self.frame.size)
let context = UIGraphicsGetCurrentContext()
let width = self.frame.size.width
let height = self.frame.size.height
self.mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
context?.move(to: from)
context?.addLine(to: to)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(self.brushWidth)
context?.setStrokeColor(red: self.red, green: self.green, blue: self.blue, alpha: self.opacity)
context?.setBlendMode(.normal)
context?.strokePath()
self.mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
self.mainImageView.alpha = self.opacity
UIGraphicsEndImageContext()
}
@IBAction func clear(_ sender: UIButton) {
self.clearCanvas()
}
@IBAction func save(_ sender: UIButton) {
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
print("Documents Directory: \(documentsDirectory)")
return documentsDirectory
}
UIGraphicsBeginImageContext(CGSize(width: mainImageView.frame.size.width, height: mainImageView.frame.size.height))
mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: mainImageView.frame.size.width, height: mainImageView.frame.size.height))
if let image = UIGraphicsGetImageFromCurrentImageContext() {
if let img = self.cropToBounds(image: image) {
if let data = UIImagePNGRepresentation(img) {
let filename = getDocumentsDirectory().appendingPathComponent("temp.png")
try? data.write(to: filename)
}
}
}
UIGraphicsEndImageContext()
}
func cropToBounds(image: UIImage) -> UIImage? {
let x = self.topLeftPoint.x
let y = self.topLeftPoint.y
let width = self.bottomRightPoint.x - x
let height = self.bottomRightPoint.y - y
let contextImage: UIImage = UIImage(cgImage: image.cgImage!)
var posX = x
var posY = y
var cgwidth = width
var cgheight = height
posX = posX - 10
cgwidth = cgwidth + 20
posY = posY - 20
cgheight = cgheight + 30
let rect: CGRect = CGRect(x: posX ,y: posY, width: cgwidth, height: cgheight)
print("rect: \(rect)")
if let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect) {
let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
return image
}
return nil
}
func rotated() {
self.clearCanvas()
}
func clearCanvas() {
self.mainImageView.image = nil
self.lastPoint = CGPoint(x: 0, y: 0)
if self.frame.size.height == 0 || self.frame.size.width == 0 {
self.topLeftPoint = CGPoint(x: CGFloat(UInt16.max), y: CGFloat(UInt16.max))
}
else {
self.topLeftPoint = CGPoint(x: self.view.frame.size.width, y: self.view.frame.size.height)
}
self.bottomRightPoint = CGPoint(x: 0, y: 0)
}
}
|
Python | UTF-8 | 2,028 | 3.59375 | 4 | [] | no_license | #! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard
# Pyperclip is a cross-platform Python module to copy and paste strings.
# pip install pyperclip
import pyperclip, re
# triple-quote syntax to create a multiline string
# ? makes the group that precedes it as optional
# re.VERBOSE as a second argument to enable comments
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? # area code \d\d\d or (\d\d\d)
(\s|-|\.)? # separator ' ' or - or .
(\d{3}) # first 3 digits \d\d\d
(\s|-|\.) # separator ' ' or - or .
(\d{4}) # last four digits \d\d\d\d
(\s*(ext|x|ext.)\s*(\d{2,5}))? # extension space (ext or x or ext) space 2-5 digits
)''', re.VERBOSE)
# + means concatenation
emailRegex = re.compile(r'''(
[a-zA-Z0-9._%+-]+ # username
@ # @ symbol
[a-zA-Z0-9.-]+ # domain name
(\.[a-zA-Z]{2,4}) # dot-something
)''', re.VERBOSE)
# Find matches in clipboard text.
# use paste() function to get a string value of the text on the clipboard
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
if groups[1] != '':
# join the area code, first 3 digits, & last 4 digits with '-'
phoneNum = '-'.join([groups[1],groups[3],groups[5]])
# add the phoneNum to the matches list
matches.append(phoneNum)
else:
# if there is no area code, join first 3 digits & last 4 digits with '-'
phoneNum = '-'.join([groups[3],groups[5]])
# add the phoneNum to the matches list
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
# Copy results to the clipboard.
# if any matches were found
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard:')
print('\n'.join(matches))
else:
print('No phone numbers or email addresses found.') |
JavaScript | UTF-8 | 6,947 | 2.78125 | 3 | [] | no_license | const http = require('http');
//Host IP of the server
const hostname = '127.0.0.1';
//Host Port of the Server
const port = 3001;
//Module to handle the Database
var mongoose = require('mongoose');
//URL to the Database
//CHANGE IF YOU ARE USING VALUES OTHER THAN THE DEFAULT ONES!
var mongoDBurl = "mongodb://192.168.33.10:27017/TwitterDB";
//Schema-model to handle the data from the Database
var post = require('./model/post');
//Module for Hosting the Server
var express = require('express');
var app = express();
//Module to handle and parse JSON/text elements
var bodyParser= require('body-parser')
//Applying the Body-parser to the server
app.use(bodyParser.urlencoded({extended: true}));
//Create the Server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
// Connect the server to the db
monDB = mongoose.connect(mongoDBurl, {useNewUrlParser:true});
//API to count the amount of users in the DB
//Q: How many Twitter users are in the database?
//Note that using the Distinc-eliminates duplicates! The result is therefore X out of 1600000 documents
app.get('/usercount',function(req,res){
post.distinct('user').exec(function(err,users){
if(err){
res.status(500).send("Error!")
} else {
console.log(users.length)
res.send("The amount of (unique) twitter users in the Database is: " + users.length +" (out of 1600000 documents)")
}
}
)
})
//API Twitters users link
//Find the top 10 users with most links
//The Users "mention" each other in the "text"-element, by @[username]
//Need to find the top 10 users, who has the most @[username]
//Need to use $regex?
//Need to use $regex to search for @[username] and end at first "space", count the mentions and return the top 10
//Added a new field to keep track of mentions!
app.get('/mostlinks', function(req,res){
post.aggregate([
{'$match':{'text':{'$regex':/@\w+/}}}, {'$addFields': {"mentions":1}},{'$group':{"_id":"$user", "mentions":{'$sum':1}}}, {'$sort':{"mentions":-1}}, ]).
limit(10).allowDiskUse(true).exec(function(err,user){
if(err){
res.status(500).send("Error!")
} else {
console.log("wha")
res.status(200).send(user);
}
})
})
//API for showing the top 10 most mentioned Twitter users
//Need to locate and save the usernames
app.get('/mostmentioned', function(req,res){
post.aggregate([
{'$addFields': {'words':{'$split':['$text', ' ']}}},
{'$unwind':"$words"},
{'$match':{'words':{'$regex':/@\w+/,'$options':'m'}}},
{'$group':{'_id':"$words",'total':{'$sum':1}}},
{'$sort':{'total':-1}}
]).limit(5).allowDiskUse(true).exec(function(err,result){
if(err){
res.status(500).send("Error: " + err.name)
} else {
res.status(200).send(result);
}
})
})
//API to count the Top 10 Most Active users
//The query is based on counting the "user"-field of all the users, sort it from high to low and limit the result to the top 10.
//Query seems to fail, if I try to replace the "_id" with something more fitting, like "name" or "username", err message states that: The field \'_username\' must be an accumulator object.
//WARNING: Can (potentially) be slow! Putting the "limit(10)" REALLY helped the speed/response!
//WARNING WARNING! Don't remove the "limit(10)"! Unless you REALLY want to see the result for ALL users, in which case: Start the function, brew some cofee, and come back (:
//NOTE: "allowDiskUse(true)" was originally set when I tested for ALL users, since the query needed to use more memory than was available (Think default allowed is 100mb).
app.get('/mostactive', function(req,res){
post.aggregate([{'$group':{
_id:"$user",count:{$sum:1}}},
{$sort:{count:-1}}
]).allowDiskUse(true).limit(10).exec(function(err, user){
if(err){
console.log(err)
res.status(500).send("Error!")
} else {
res.status(200).send(user);
}
})
})
//API NEGATIVE-Polarity
//Show the five users with the most Negative tweets and the five users with the most positive tweets
app.get('/negativepolarity', (req,res) => {
post.aggregate([
{'$group':{'_id':"$user", 'polarity': {'$avg': "$polarity"}, 'AmountOfNegativeTweets': {'$sum': 1}}},
{'$sort':{ 'polarity': 1, 'AmountOfNegativeTweets':-1}}
]).limit(5).allowDiskUse(true).exec(function(err,result){
if(err){
res.status(500).send("Error: " + err.name)
} else {
res.status(200).send(result);
}
})
})
//API POSITIVE-Polarity
//Show the five users with the most Positive tweets and the five users with the most positive tweets
app.get('/positivepolarity', (req,res) => {
post.aggregate([
{'$group':{'_id':"$user", 'polarity': {'$avg': "$polarity"}, 'AmountOfHappyTweets': {'$sum': 1}}},
{'$sort':{ 'polarity': -1, 'AmountOfHappyTweets':-1}}
]).limit(5).allowDiskUse(true).exec(function(err,result){
if(err){
res.status(500).send("Error: " + err.name)
} else {
res.status(200).send(result);
}
})
})
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
/* --- ! TEST AREA ! --- */
//TEST POLARITY WITH AGGREGATE
//Testing to see the range of the field "polarity"
//Results:
// 0 : 800000 (one is prob. from the top field)
// 4 : 800000
//From the results one must conclude, that some users might have multiple tweets with a polarity score.
// From Standford : the polarity of the tweet (0 = negative, 2 = neutral, 4 = positive)
app.get('/polAgg', (req,res) => {
post.aggregate([{'$group':{_id:"$polarity",count:{$sum:1}}},{$sort:{count:-1}}]).exec( function(err,user){
if(err){
res.status(500).send("Error!")
} else {
res.status(200).send(user);
}
})
})
//TEST API!
//Just wanted to see if any user had any text in the field "query" other than "NO_QUERY"
//Spoiler: None!
app.get('/testQuery', function(req,res){
post.aggregate([{'$group':
{_id:{query:"$query"}, count:{$sum:1}}},
{$sort:{"_id.source":-1}}]).allowDiskUse(true).limit(10).exec(function(err, user){
if(err){
console.log(err)
res.status(500).send("Error!")
} else {
res.status(200).send(user);
}
})
})
app.get('/api/test', (req,res) => {
console.log("Running");
post.find({user: "_TheSpecialOne_"}, function(err,user){
if(err){
res.status(500).send("Error!")
} else {
console.log("wha")
res.status(200).send(user);
}
})
})
app.get('/api', function (req,res){
res.send("Here we go!");
})
//Function to check if we can see the collection of training.1600000.processed.noemoticon
//In the TwitterDB
/*monDB.on('open', function () {
monDB.db.listCollections().toArray(function (err, collectionNames) {
if (err) {
console.log(err);
return;
}
console.log(collectionNames);
monDB.close();
});
});
*/
|
TypeScript | UTF-8 | 2,528 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | import { Type } from "class-transformer";
import {
Equals,
IsArray,
IsIn,
IsNotEmptyObject,
IsNumber,
IsOptional,
IsString,
ValidateNested,
} from "class-validator";
export abstract class NotificationBase {
@IsString()
version: string;
@IsString()
id: string;
@IsString()
"detail-type": string;
@Equals("aws.medialive")
source: "aws.medialive";
@IsString()
account: string;
@IsString()
time: string;
@IsString()
region: string;
@IsArray()
@IsString({ each: true })
resources: string[];
}
export class ChannelStateChangeDetail {
@IsNumber()
pipelines_running_count: number;
@IsIn(["RUNNING", "STOPPED", "STOPPING", "DELETING", "CREATED", "DELETED", "STARTING"])
state: "RUNNING" | "STOPPED" | "STOPPING" | "DELETING" | "CREATED" | "DELETED" | "STARTING";
@IsOptional()
@IsString()
pipeline?: string;
@IsString()
channel_arn: string;
@IsString()
message: string;
}
export class ChannelStateChange extends NotificationBase {
@Equals("MediaLive Channel State Change")
"detail-type": "MediaLive Channel State Change";
@ValidateNested()
detail: ChannelStateChangeDetail;
}
export class ChannelInputChangeDetail {
@IsString()
active_input_switch_action_name: string;
@IsString()
active_input_attachment_name: string;
@IsString()
pipeline: string;
@IsString()
message: string;
@IsString()
channel_arn: string;
}
export class ChannelInputChange extends NotificationBase {
@Equals("MediaLive Channel Input Change")
"detail-type": "MediaLive Channel Input Change";
@ValidateNested()
detail: ChannelInputChangeDetail;
}
export class ChannelAlert extends NotificationBase {
@Equals("MediaLive Channel Alert")
"detail-type": "MediaLive Channel Alert";
}
export class MediaLiveNotification {
@Equals("notification")
type: "notification";
@ValidateNested()
@Type(() => NotificationBase, {
keepDiscriminatorProperty: true,
discriminator: {
property: "detail-type",
subTypes: [
{ value: ChannelStateChange, name: "MediaLive Channel State Change" },
{ value: ChannelInputChange, name: "MediaLive Channel Input Change" },
{ value: ChannelAlert, name: "MediaLive Channel Alert" },
],
},
})
@IsNotEmptyObject()
notification: ChannelStateChange | ChannelInputChange | ChannelAlert;
}
|
Python | UTF-8 | 2,232 | 4.0625 | 4 | [] | no_license | """
Time complexity analysis:
Insert each line into a 2D dictionary in O(n) where n is the total number of lines in the file.
We sort the dates in O(m log m) where m is the total number of unique dates.
We sort the URLs count in in O(m log p) where m is as above and p the total number or unique URLs on a given date.
We print the sorted dictionary in O(mp) which represents the total number of unique date and URL pairs.
Overall, the total run-time is O(n) + O(m log m) + O(m log p) + O(mp).
Therefore, the run-time is O(n).
"""
import time
from operator import itemgetter
def main():
# Verifying the file actually exists. If not, then return an error without crashing.
try:
file = open("input.txt", "r")
except:
print("File Doesn't Exist")
return
dateURLDict = {}
for line in file:
if str(line.strip()):
epoch, url = _seperateDateURL(line)
date = _epochToDate(epoch)
if date not in dateURLDict:
dateURLDict[date] = {}
dateURLDict[date][url] = 1
elif url not in dateURLDict[date]:
dateURLDict[date][url] = 1
else:
dateURLDict[date][url] += 1
_printSortedDateUrlDict(dateURLDict)
def _printSortedDateUrlDict (dateURLDict):
"""
Prints the sorted dictionary
:param dateURLDict: the 2D dictionary storing the data from the input files
:return:
"""
for i in sorted(dateURLDict.items()):
print(i[0])
sorted_urls_count = sorted(i[1].items(), key=itemgetter(1), reverse=True)
for url in sorted_urls_count:
print (url[0], url[1])
def _seperateDateURL (input):
"""
This function splits each line from input file by the "|" character
:param input: A single line from the input file
:return: The epoch time (int) and URL (string)
"""
epochURL = input.split("|")
return int(epochURL[0]), epochURL[1].strip()
def _epochToDate (epoch):
"""
Converts the epoch to a GMT date
:param epoch: A single epoch
:return: A date in GMT (string)
"""
return time.strftime('%m/%d/%Y GMT', time.gmtime(epoch))
if __name__ == "__main__":
main()
|
Java | UTF-8 | 1,968 | 1.5625 | 2 | [] | no_license | package com.atmshop.constant;
/**
* Created by Anil Sharma on 2/2/16.
*/
public interface IJson {
//Login Screen
String mobile_no = "mobileNumber";
String password = "password";
String userId = "userId";
String active = "active";
String userName = "userName";
//Owner
String ownerId = "ownerId";
String owner_name = "ownerName";
String ownerMobileNo = "ownerMobileNo";
String ownerAlternativeMobileNo = "ownerAlternativeMobileNo";
//Shop Location
String appartmentName = "appartmentName";
String area = "area";
String district = "district";
String state = "state";
String pincode = "pincode";
//Shop Details
String shopHeight = "shopHeight";
String shopWidth = "shopWidth";
String internalWidth = "internalWidth";
String internalDepth = "internalDepth";
String carpetArea = "carpetArea";
String internalHeight = "internalHeight";
String shopId = "shopId";
// Shop rent
String rentId = "rentId";
String shopRent = "shopRent";
String negotiableRent = "negotiableRent";
// Shop Photo
String image_string = "imageData";
String imageType = "imageType";
String latitude = "latitude";
String longitude = "longitude";
String imageId = "imageId";
//Qstion
String companyReference = "companyReference";
String referenceName = "referenceName";
String referenceMobileNo = "referenceMobileNo";
String shopFloor = "shopFloor";
String shopRoof = "shopRoof";
String nearAtmFirst = "nearAtmFirst";
String nearAtmSecond = "nearAtmSecond";
String firstBankName = "firstBankName";
String secondBankName = "secondBankName";
String twoAtmBank = "twoAtmBank";
String shopArea = "shopArea";
String highFootfall = "highFootfall";
String highFootfallReason = "highFootfallReason";
String shopPoi = "shopPoi";
String atmMachines = "atmMachines";
String questionId = "questionId";
}
|
Markdown | UTF-8 | 3,027 | 3.9375 | 4 | [] | no_license | 字典就像列表一样,但是字典更通用。在列表中,索引位置必须是整数,但是在字典中,索引几乎可以是任意类型。
你可以把字典看作是一系列的索引(这里叫做键key)和一系列的值之间的映射。每个键对应一个值,键和值之间的关系成为键值对,有时也称为数据项。
举个例子,我们将创建一个英语映射到西班牙语的字典,键和值都是字符串。
`dict`函数创建了一个新的字典,没有任何的键值对。因为`dict`是内置函数的名称,所以不要用它做变量名。
```python
>>> eng2sp = dict()
>>> print(eng2sp)
{}
```
大括号{}表示一个空字典,要添加数据项到字典,可以使用中括号:
```python
>>> eng2sp['one'] = 'uno'
```
这行语句创建了一个从键one到值uno映射的数据项。再次打印这个字典,我们会看到一个键值对,间和值之间用冒号隔开:
```python
>>> print(eng2sp)
{'one': 'uno'}
```
这种输出的格式也是一种输入的格式,例如,你可以创建一个新的带有三个数据项的字典,但是如果你打印出eng2sp,你可能会有点惊讶:
```python
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print(eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
```
键值对的顺序发生了改变,事实上,如果你在你自己的电脑上运行同样的例子,得出的结果可能也不一样,一般而言,字典里面数据项的顺序是不可预测的。
但是,这并不是个问题,因为键值对并不是用整数来索引的,而是用键来查找对应的值。
```python
>>> print(eng2sp['two'])
'dos'
```
键two永远隐射着值dos,所以键值对的顺序并不重要。
如果键不在字典中,你会得到下面错误:
```python
>>> print(eng2sp['four'])
KeyError: 'four'
```
`len`函数也适用于字典,它返回字典中键值对的个数:
```python
>>> len(eng2sp)
3
```
`in`操作符也适用于字典,它可以告诉你,字典中是否存在这个键,不能用来判断是否存在这个值。
```python
>>> 'one' in eng2sp
True
>>> 'uno' in eng2sp
False
```
要判断字典中是否存在某个值,你可以使用`values`方法,它返回所有值的一个列表,然后你再用`in`操作符就可以判断了。
```python
>>> vals = list(eng2sp.values())
>>> 'uno' in vals
True
```
列表和字典中in操作符的算法实现是不一样的,在列表中,Python采用的是线性搜索策略,搜索时间和列表长度成正比。在字典中,Python使用了一种高效的哈希表算法,这种算法,不管字典里面有多少数据项,时间上话费几乎没有什么差别,这里呢,不展开讲哈希表,请自行Google。
**习题 9.1**
编写一个程序,读取words.txt文件中的单词,将它们作为键存储在字典中,这里不用关心键对应的值是什么,你随便给吧,然后用in操作符快速判断某一个字符型是否存在于字典中。
|
Java | UTF-8 | 1,076 | 2.203125 | 2 | [] | no_license | package com.wisewater.auto.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wisewater.base.BaseService;
import com.wisewater.auto.controller.CSelfTagForm;
import com.wisewater.auto.pojo.CSelfTag;
import com.wisewater.auto.repository.CSelfTagRepository;
@Service
public class CSelfTagServiceImpl extends BaseService implements CSelfTagService {
@Autowired
private CSelfTagRepository cselftagRepository;
/**
* 获取所有标签
*
* @return XingXingLvCha 2015年4月8日 下午4:28:32
*/
@Override
public List<CSelfTagForm> findAllCSelfTag(String token) {
List<CSelfTag> cSelfTagList = cselftagRepository.findAllCSelfTag(token);
List<CSelfTagForm> cSelfTagFormList = new ArrayList<CSelfTagForm>();
if (cSelfTagList.size() > 0) {
for (CSelfTag cSelfTag : cSelfTagList) {
cSelfTagFormList.add(mapper.map(cSelfTag, CSelfTagForm.class));
}
}
return cSelfTagFormList;
}
} |
Shell | UTF-8 | 12,185 | 3.96875 | 4 | [] | no_license | #!/bin/bash
################################################################################
# Sensu plugin to monitor ability of build Nova instances #
################################################################################
# DESCRIPTION: This script attempts to build a Nova instance (i.e., nova boot)
#+ from a randomly selected controller/conductor node (from nova service-list),
#+ ping the instance's public IP, ssh into the instance, and then delete it.
#+ It will run the process on each compute node for all availability zones.
#+ If, at any step along the process, something fails, it will alert which
#+ process(es) failed on which compute node and from which conductor node.
ALERT_NAME="CheckNovaBoot"
PROGNAME=$(`which basename` $0)
VERSION="Version 1.2"
AUTHOR="Christoph Champ <christoph.champ@gmail.com>"
# Exit codes
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4
source /etc/sensu/plugins/openrc
export OS_TENANT_NAME='admin' # override openrc
if [[ "$(hostname)" == "node-12.example.local" ]]; then
echo "${ALERT_NAME} OK: Skipping check on fuel-lab"
exit $STATE_OK
fi
PING=$(which ping)
GREP=$(which grep)
SSH=$(which ssh)
NOVA=$(which nova)
NEUTRON=$(which neutron)
SENSU_SSH_KEY=/etc/sensu/plugins/sensu-key
PACKET_LOSS=20 # ping packet loss threshold to trigger alert
NOVA_FLAVOR=m1.small
NOVA_IMAGE=TestVM
NOVA_SECGROUP=default
NOVA_KEYNAME=sensu
INSTANCE_NAME_PREFIX=sensu-nova-boot-check
NOVA_BUILD_TIMEOUT=300 # Exit with status "CRITICAL" if build takes longer than this
function print_val {
if [[ $verbosity -ge 1 ]]; then
echo $1
fi
}
# Main #########################################################################
# Verbosity level
verbosity=0
declare -A alert_array
function nova_boot() {
local az="$1"
local compute_node="$2"
local instance_name="$3"
local msg=""
local result="X:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Capture "node-XX" part
local node=$(sed -e 's/.*\(node-[0-9]\+\)/\1/g' <<< "${instance_name}")
# Start building instance
${NOVA} --os-tenant-name ${OS_TENANT_NAME} boot --flavor ${NOVA_FLAVOR} \
--image ${NOVA_IMAGE} --security-groups ${NOVA_SECGROUP} \
--nic net-id=${EXT_NET_ID} --key-name ${NOVA_KEYNAME} \
--availability-zone ${az}:${compute_node} \
${instance_name} > /dev/null 2>&1
sleep 2
# Get initial state of build
VM_INFO=$(${NOVA} --os-tenant-name ${OS_TENANT_NAME} list | \
awk -v regex="${instance_name}" '$4 ~ regex {printf "%s;%s;%s",$2,$6,$10}')
VM_UUID=$(echo ${VM_INFO}|awk -F';' '{print $1}')
VM_STATUS=$(echo ${VM_INFO}|awk -F';' '{print tolower($2)}')
VM_POWER_STATE=$(echo ${VM_INFO}|awk -F';' '{print tolower($3)}')
result="WAIT:${VM_UUID}"
# Keep checking state until success or failure
TIME_START=$(date +%s)
until [[ ${VM_STATUS} == "active" && ${VM_POWER_STATE} == "running" ]]; do
VM_INFO=$(${NOVA} --os-tenant-name ${OS_TENANT_NAME} list | \
awk -v regex="${instance_name}" '$4 ~ regex {printf "%s;%s;%s",$2,$6,$10}')
VM_STATUS=$(echo ${VM_INFO}|awk -F';' '{print tolower($2)}')
VM_POWER_STATE=$(echo ${VM_INFO}|awk -F';' '{print tolower($3)}')
sleep 5
TIME_END=$(date +%s)
TIME_DELTA=$((TIME_END-TIME_START))
if [[ ${TIME_DELTA} -gt ${NOVA_BUILD_TIMEOUT} ]]; then
#msg="${ALERT_NAME} CRITICAL: nova boot process on "
#msg+="${az}:${compute_node} took longer than "
#msg+="${NOVA_BUILD_TIMEOUT} seconds"
#delete_instance ${VM_UUID} ${instance_name}
#exit $STATE_CRITICAL
result="CRITICAL:${VM_UUID}"
break
fi
if [[ ${VM_STATUS} == "error" ]]; then
#msg="${ALERT_NAME} CRITICAL: nova boot process on "
#msg+="${az}:${compute_node} failed after ${NOVA_BUILD_TIMEOUT} "
#msg+=seconds"
#delete_instance ${VM_UUID} ${instance_name}
#exit $STATE_CRITICAL
result="CRITICAL:${VM_UUID}"
break
fi
done
# Instance should now be ACTIVE, so return results
result="OK:${VM_UUID}"
echo ${result}
}
function delete_instance() {
local vm_uuid="$1"
local instance_name="$2"
local node=$(sed -e 's/.*\(node-[0-9]\+\)/\1/g' <<< "${instance_name}")
DELETE_REQUEST=$(${NOVA} --os-tenant-name ${OS_TENANT_NAME} delete ${vm_uuid} 2>/dev/null | \
awk '/accepted/{print "SUCCESS"}')
sleep 10 # Give delete process time to complete
IS_DELETED_A=$(${NOVA} --os-tenant-name ${OS_TENANT_NAME} show ${vm_uuid} 2>&1 | \
awk '/No server with/{print "YES"}')
sleep 5 # Make sure instance has really been deleted
IS_DELETED_B=$(${NOVA} --os-tenant-name ${OS_TENANT_NAME} delete ${vm_uuid} 2>&1 | \
awk '/No server with/{print "YES"}')
if [[ ${DELETE_REQUEST} == "SUCCESS" && \
${IS_DELETED_A} == "YES" && ${IS_DELETED_B} == "YES" ]]; then
print_val "DEBUG: Successfully deleted ${instance_name}"
alert_array["delete"]+="${node}:${STATE_OK};"
else
print_val "DEBUG: WARNING: ${instance_name} might not have deleted successfully"
alert_array["delete"]+="${node}:${STATE_WARNING};"
fi
}
function cleanup_failed_deleted_instances() {
# This function checks if there are any sensu-nova-boot-check instances
# that failed to delete in the previous run of the check. If it finds
# any instances that match the check and are over 1 hour old, it will
# try to delete them.
fields="name,created"
instance_array=($(${NOVA} --os-tenant-name ${OS_TENANT_NAME} list --fields ${fields} | \
awk -W posix -F'|' '$2 ~ /[[:alnum:]-]{36}/{
gsub(" |\t","");printf "%s;%s;%s\n",$2,$3,$4}'))
for instance_data in ${instance_array[@]}; do
uuid=$(echo ${instance_data} | cut -d';' -f1)
vm_name=$(echo ${instance_data} | cut -d';' -f2)
created=$(echo ${instance_data} | cut -d';' -f3 | \
awk '{gsub("T"," ");gsub("Z","");print $0}')
let DELTA=($(date -u '+%s')-$(date -d "${created}" '+%s'))
match=$(awk -vsensu=${INSTANCE_NAME_PREFIX} \
'/sensu/{print substr($0,0,21)}' <<< "${vm_name}")
if [[ "${match}" == "${INSTANCE_NAME_PREFIX}" ]] && \
[[ ${DELTA} -gt 3600 ]]; then
delete_instance ${uuid} ${vm_name}
fi
done
}
# We generate an array of controller hostnames, pick a random one from the list
#+ and if the random hostname matches the hostname of the node this script is
#+ on, continue with the check process. Exit otherwise. This is to prevent the
#+ script being run on all of the controller nodes at the same time.
CONTROLLERS=($(nova service-list|awk -F'|' '/nova-conductor/{gsub(" ","",$0);print $4}'))
RANDOM_CONTROLLER=$(echo ${CONTROLLERS[$RANDOM % ${#CONTROLLERS[@]}]})
if [[ "$(hostname)" == "${RANDOM_CONTROLLER}" ]]; then
CONTROLLER=$(echo ${RANDOM_CONTROLLER} | sed -e 's/^\(node-[0-9]\+\).*/\1/g')
else
echo "${ALERT_NAME} OK: Check running on other controller node (${RANDOM_CONTROLLER})"
exit $STATE_OK
fi
cleanup_failed_deleted_instances
#== Begin the Nova boot check process =========================================
print_val "DEBUG: Retrieving external-network name..."
#EXT_NET_NAME=$(neutron net-external-list |\
# awk -W posix -F'|' '$2 ~ /[[:alnum:]-]{36}/{gsub(" ","");print $3}')
EXT_NET_NAME=$(${NOVA} floating-ip-list|awk '$2 ~ /^10\./{print $8;exit}')
if [[ -z ${EXT_NET_NAME} ]]; then
echo "${ALERT_NAME} CRITICAL: Could not retrieve external-network name"
exit $STATE_CRITICAL
fi
# Needs to be able to handle names like "ext_net05-10.211.128.0/18"
print_val "DEBUG: Retrieving external-network UUID..."
#EXT_NET_ID=$(neutron net-list -- --name ${EXT_NET_NAME} --fields id)
EXT_NET_ID=$(${NEUTRON} net-list |\
awk -v regex="${EXT_NET_NAME}" '$4 ~ regex {print $2}')
if [[ -z ${EXT_NET_ID} ]]; then
echo "${ALERT_NAME} CRITICAL: Could not retrieve external-network UUID"
exit $STATE_CRITICAL
fi
# Create an array of compute nodes for "az1"/"az2" availability zones
print_val "DEBUG: Getting a list of availability zones and associated compute nodes..."
ZONE_NAMES=( 'az1' 'az2' )
AZ_NODES=$(${NOVA} --os-tenant-name ${OS_TENANT_NAME} availability-zone-list)
AZ1_NODES=($(awk '/az1/,/^+/{if ($3 ~ /node/){print $3}}' <<< "${AZ_NODES}"))
AZ2_NODES=($(awk '/az2/,/az1/{if ($3 ~ /node/){print $3}}' <<< "${AZ_NODES}"))
# This is the main section where each function is run
# TODO: Collapse into a for-loop
#for zone in ${ZONE_NAMES[@]}; do
# Run through whole process in availability zone "az1"
zone="az1"
for compute_node in ${AZ1_NODES[@]}; do
#compute_node="node-11.example.com"
#node="node-11"
node=$(echo ${compute_node} | sed -e 's/\(node-[0-9]\+\).*/\1/g')
instance_name=${INSTANCE_NAME_PREFIX}-${CONTROLLER}-${node}
print_val "DEBUG: Running nova boot from ${CONTROLLER} on ${zone}:${node} (${compute_node})"
RESULT=$(nova_boot ${zone} ${compute_node} ${instance_name})
VM_UUID=${RESULT#*:}
if [[ ${RESULT%%:*} == "OK" ]]; then
alert_array["boot"]+="${node}:${STATE_OK};"
else
alert_array["boot"]+="${node}:${STATE_CRITICAL};"
fi
print_val "DEBUG: Attempting to delete instance [UUID: ${VM_UUID}]..."
delete_instance ${VM_UUID} ${instance_name}
done
# Run through whole process in availability zone "az2"
zone="az2"
for compute_node in ${AZ2_NODES[@]}; do
node=$(echo ${compute_node} | sed -e 's/\(node-[0-9]\+\).*/\1/g')
instance_name=${INSTANCE_NAME_PREFIX}-${CONTROLLER}-${node}
print_val "DEBUG: Running nova boot from ${CONTROLLER} on ${zone}:${node} (${compute_node})"
RESULT=$(nova_boot ${zone} ${compute_node} ${instance_name})
VM_UUID=${RESULT#*:}
if [[ ${RESULT%%:*} == "OK" ]]; then
alert_array["boot"]+="${node}:${STATE_OK};"
else
alert_array["boot"]+="${node}:${STATE_CRITICAL};"
fi
print_val "DEBUG: Attempting to delete instance [UUID: ${VM_UUID}]..."
delete_instance ${VM_UUID} ${instance_name}
done
# TODO: The following should really be in a function
declare -A boot_arr ping_arr ssh_arr delete_arr
is_critical=0
is_warning=0
re='^[0-9]$'
# Parse boot alerts
OLDIFS=$IFS; IFS=';' read -r -a bootvals <<< "${alert_array['boot']}"; IFS=$OLDIFS
for i in "${bootvals[@]}"; do
if ! [[ ${i#*:} =~ $re ]]; then
echo "${ALERT_NAME} UNKNOWN: Expecting integer value. Got \"${i}\" instead."
exit ${STATE_UNKNOWN}
fi
if [[ "${i#*:}" -eq "1" ]]; then
boot_arr["warning"]+="${i%%:*},"
is_warning=1
elif [[ "${i#*:}" -eq "2" ]]; then
boot_arr["critical"]+="${i%%:*},"
is_critical=1
else
boot_arr["ok"]+="${i%%:*},"
fi
done
# Parse delete alerts
OLDIFS=$IFS; IFS=';' read -r -a deletevals <<< "${alert_array['delete']}"; IFS=$OLDIFS
for i in "${deletevals[@]}"; do
if ! [[ ${i#*:} =~ $re ]]; then
echo "${ALERT_NAME} UNKNOWN: Expecting integer value. Got \"${i}\" instead."
exit ${STATE_UNKNOWN}
fi
if [[ "${i#*:}" -eq "1" ]]; then
delete_arr["warning"]+="${i%%:*},"
is_warning=1
elif [[ "${i#*:}" -eq "2" ]]; then
delete_arr["critical"]+="${i%%:*},"
is_critical=1
else
delete_arr["ok"]+="${i%%:*},"
fi
done
# using "! read" to override "set -e" (bit of a hack)
! read -r -d '' ALERT_MSG <<- EOM
OK: {"boot": "${boot_arr['ok']%,}", "delete": "${delete_arr['ok']%,}"}
WARNING: {"boot": "${boot_arr['warning']%,}", "delete": "${delete_arr['warning']%,}"}
CRITICAL: {"boot": "${boot_arr['critical']%,}", "delete": "${delete_arr['critical']%,}"}
EOM
if [[ ${is_critical} -eq 1 ]]; then
echo -e "${ALERT_NAME} CRITICAL: [${CONTROLLER}]\n${ALERT_MSG}"
exit ${STATE_CRITICAL}
elif [[ ${is_warning} -eq 1 ]]; then
echo -e "${ALERT_NAME} WARNING: [${CONTROLLER}]\n${ALERT_MSG}"
exit ${STATE_WARNING}
else
echo -e "${ALERT_NAME} OK: [${CONTROLLER}]\n${ALERT_MSG}"
exit ${STATE_OK}
fi
|
PHP | UTF-8 | 3,196 | 2.59375 | 3 | [] | no_license | <!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>InventoryTracking_1</title>
<!-- Reset browser defaults -->
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<!-- Custom Stylesheet -->
<link rel="stylesheet" href="css/InventoryTracking_2-Item.css">
</head>
<body>
<!-- Top navigation bar -->
<div class="topnav">
<!--Header-->
<h1>Inventory Tracking</h1>
</div>
<div id="rwd"> </div>
<!-- ESIM Logo -->
<p class="ESIM_logo">ESIM</p>
<!-- Display results -->
<div class="label">
<h2>Tracking report for:
<?php
// Gets all keys in POST array
$keys = array_keys($_POST);
// Sets $item = the first key of the POST array
$item = $keys[0];
// Prints item out
echo $item;
// Gets the value (itemid) to be used in SQL statement
$itemid = $_POST[$item];
?>
</h2>
</div>
<!-- Display results -->
<div class="results">
<?php
/* CONTINUE SESSION */
session_start();
// Check if logged in
if(!isset($_SESSION['username_stored'])) {
// Redirect to Login page if not
header('Location: https://cgi.soic.indiana.edu/~team59/app/Login.php');
}
// Connects to the database
$con = mysqli_connect("db.sice.indiana.edu", "i494f18_team59", "my+sql=i494f18_team59", "i494f18_team59");
//Check connection
if(mysqli_connect_errno())
{echo nl2br("Failed to connect to MySql:".mysqli_connent_error(). "\n");}
else
{echo nl2br("\n");}
// For the check-in/check-out quantity
$sql = "SELECT SUM(in_quantity), SUM(out_quantity) FROM $item;";
// For the last checkout_time
// $sql .= "SELECT checkout_time FROM employees WHERE '$itemid' != 0 ORDER BY checkout_time DESC LIMIT 1";
// For the last checkin_time
// $sql .= "SELECT checkout_time FROM employees WHERE '$itemid' != 0 ORDER BY checkout_time DESC LIMIT 1";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<table class='results_table'><thead><tr><th>Status</th><th>Qty</th><th>Timestamp</th></thead>";
//Work in Progress
//Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>CHECKED-OUT</td><td>".$row["SUM(out_quantity)"]."</td><td>".$row["checkout_time"]."</td></tr>";
echo "<tr><td>CHECKED-IN</td><td>".$row["SUM(in_quantity)"]."</td><td>".$row["checkout_time"]."</td></tr>";}
echo "</table>";
} else {
echo "0 results";
}
if(!mysqli_query($con, $sql))
{die('Error:'.mysqli_error($con));}
echo "";
mysqli_close($con);
?>
</div>
<!-- Logout Link -->
<a href="Login.php" class="Logout">Logout</a>
<!-- Return to Home Page Button -->
<button onclick=location.href="https://cgi.soic.indiana.edu/~team59/app/Home.php" class="button2">Return Home</button>
<!-- Who's Logged In -->
<p class="user">Logged in:</p>
<p class="user_logged_in"> <?php echo $_SESSION['username_stored']; ?> </p>
</body>
</html>
|
JavaScript | UTF-8 | 1,036 | 2.8125 | 3 | [] | no_license | import React from 'react';
import { Link } from 'react-router-dom';
import moment from 'moment';
export default ({ id, description, amount, createdAt, note }) => (
<Link className="list-item" to={`/edit/${id}`}>
<div className="list-item__container">
<div className="list-item__left">
<h3 className="list-item__title">{description}</h3>
<span className="list-item__sub-title">{moment(createdAt).format('D MMM YYYY')}</span>
</div>
<span className="list-item__note">{note}</span>
</div>
<h3 className="list-item__data">${(amount / 100).toFixed(2)}</h3>
</Link>
);
// This is how you do it without destructuring
// Note: in ExpenseList.js you have to pass in expense={expense} instead of {...expense}
//
// export default (props) => (
// <div>
// <h3>{props.expense.description}</h3>
// <p>${(props.expense.amount / 100).toFixed(2)}</p>
// <p>Created At: {props.expense.createdAt}</p>
// </div>
// ); |
Markdown | UTF-8 | 4,155 | 3 | 3 | [] | no_license | # Sync / Async
* 호출함수가 피호출함수 작업 완료를 확인하는지 여부
### Sync
* A 함수에서 B 함수 호출시, A 함수가 B 함수가 완료되었는지 확인후에 후처리 작업 수행하는 방식
### Async
* A 함수에서 B 함수 호출시, A 함수는 B 함수가 완료되었는지 신경쓰지 않고, B 함수 스스로 작업 완료시 후처리 작업(callback 메서드) 수행
<br>
# Blocking / Non-blocking
* 호출함수가 피호출함수 작업 완료를 기다리는지 여부

### Blocking
* A 함수에서 B 함수 호출시, B 함수의 작업이 모두 끝날때까지 A 함수가 대기하는 동작 방식
### Non-blocking
* A 함수에서 B 함수 호출시, (다른 스레드에 의해)B 함수의 작업이 수행되는동안, (메인스레드가)A 함수도 대기하지 않고 다음 작업 계속 수행하는것
> Spring 에선 비동기 메서드 호출시, Spring Task Executor 가 자신의 스레드 풀에서 스레드 할당하여 수행
> Tip
> * 통상적으로 얘기하는 Sync, Async 에 Blocking, Non-Blocking 개념이 포함되어있음
> * 다만 두 개념의 관심사가 다름 (Sync-Async : 피호출함수 작업완료 확인주체, Blocking-Non Blocking : 피호출함수 작업완료 대기여부)
> * Non-Blocking 과 Async 모두 피호출함수 수행을 기다리지 않고 호출함수가 계속 수행됨
> * 다만 Non-Blocking 은 호출함수 수행 중간중간에 지속적으로 피호출함수의 작업완료를 확인
> * 이렇게 피호출함수 작업완료 체크 시점마다 Blocking 처럼 동작하게됨
> * Async 는 호출함수가 아예 피호출함수의 작업완료 확인하지 않으므로 진정한 의미의 비동기
<br>
# Sync, Asycn + Blocking, Non Blocking

### Sync - Blocking
* 호출함수가 피호출함수의 작업완료를 대기
* 호출함수가 피호출함수 작업완료를 체크하여 후처리 로직 수행
* 일반적인 메서드 호출

### Sync - Non Blocking
* 호출함수가 피호출함수의 작업완료를 기다리지않고 다음작업 수행
* 호출함수가 피호출함수 작업완료를 체크하여 후처리 로직 수행
* 호출함수가 Non-Blocking 으로 계속 자신의 작업 수행하는 중간중간 Blocking 하고 피호출함수의 작업완료를 확인해야하므로 불필요한 리소스가 낭비되어 완전한 비동기라 할 수 없음
> cf) 폴링(Polling) : 작업이 완료되었는지 주기적으로 체크하는 방식
* callback 메서드를 등록하지 않고 비동기 메서드 호출

### Async - Blocking
* 호출함수가 피호출함수의 작업완료를 대기
* 호출함수는 피호출함수의 작업완료를 신경쓰지 않고, 피호출함수가 작업완료시 직접 후처리 로직(callback메서드) 수행
* Sync-Blocking 과 거의 동일

### Async - Non Blocking
* 호출함수가 피호출함수의 작업완료를 기다리지않고 다음작업 수행
* 호출함수는 피호출함수의 작업완료를 신경쓰지 않고, 피호출함수가 작업완료시 직접 후처리 로직(callback메서드) 수행
* 호출함수는 피호출함수의 작업을 기다리거나 확인하지 않고 계속 자신의 작업 수행하므로 완전한 비동기라 할 수 있음
* callback 메서드를 등록한 비동기 메서드 호출

> [이미지출처](http://homoefficio.github.io/2017/02/19/Blocking-NonBlocking-Synchronous-Asynchronous/) |
Markdown | UTF-8 | 778 | 2.53125 | 3 | [] | no_license | # Article D421-162
Les élèves du second degré de l'Ecole européenne de Strasbourg sont représentés au comité des élèves conformément à la
convention portant statut des écoles européennes faite à Luxembourg le 21 juin 1994 et au règlement général des écoles
européennes.
Le comité des élèves est composé des délégués élus de chaque classe du second degré de l'établissement.
Le comité des élèves exerce les attributions dévolues au conseil des délégués pour la vie lycéenne mentionnées à l'article R.
421-44.
**Liens relatifs à cet article**
**Créé par**:
- Décret n°2015-232 du 27 février 2015 - art. 1
**Cité par**:
- Code de l'éducation - art. D421-161 (V)
**Cite**:
- Code de l'éducation - art. R421-44
|
Go | UTF-8 | 404 | 4.0625 | 4 | [] | no_license | package main
import "fmt"
func main() {
var x [5]int
x[0] = 2
fmt.Println(x) // [2 0 0 0 0]
// array literal
y := [5]int{10, 20, 30, 40, 50}
fmt.Println(y) // [10 20 30 40 50]
// use of '...' -> will infer size
z := [...]int{1, 2, 3, 4}
fmt.Println(z) // [1 2 3 4]
// iteration
for index, value := range z {
fmt.Println(index, value)
}
fmt.Println("-----")
}
|
Python | UTF-8 | 938 | 2.53125 | 3 | [] | no_license | import pygame
import random
from Libs import funciones as f
pygame.mixer.init()
#COLORES
VERDE=[0,255,0]
BLANCO=[255,255,255]
NEGRO=[0,0,0]
ROJO=[255,0,0]
AZUL=[0,0,255]
#PANTALLA
width = 800
height = 600
screen = pygame.display.set_mode([width,height])
#CUADRICULA
ls_c=[]
ls_f=[]
#GRUPO DE SPRITES
todos = pygame.sprite.Group()
#VARIABLES JUEGO
end_game = False
algoritmo = True
#RELOJ
reloj = pygame.time.Clock()
#MARIO
limites = [7,7,7,7]
imagen_mario = 'imagenes/spritemario.png'
m_mario = f.Recortar(4,7,imagen_mario,limites,40,80)
MARIO_PLAYER = f.MARIO_BROS(m_mario)
todos.add(MARIO_PLAYER)
draw_first_time = False
#FOOD
imagen_honguito = 'imagenes/honguito.png'
limites = [1]
m_honguito = f.Recortar(1,1,imagen_honguito,limites,30,30)
draw_honguito = False
HONGUITO_FOOD = 0
x = 0
y = 0
#Algortimo
lm = []
algoritmo_start = True
#MUSICA
sonido_dir = 'Sonido/fondo.mp3'
sonido = pygame.mixer.music.load(sonido_dir)
|
Java | UTF-8 | 3,223 | 2.28125 | 2 | [
"MIT"
] | permissive | /*
* Gitea API.
* This documentation describes the Gitea API.
*
* OpenAPI spec version: 1.18.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.gitea.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* CreateTagOption options when creating a tag
*/
@ApiModel(description = "CreateTagOption options when creating a tag")
public class CreateTagOption {
@SerializedName("message")
private String message = null;
@SerializedName("tag_name")
private String tagName = null;
@SerializedName("target")
private String target = null;
public CreateTagOption message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@ApiModelProperty(value = "")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public CreateTagOption tagName(String tagName) {
this.tagName = tagName;
return this;
}
/**
* Get tagName
* @return tagName
**/
@ApiModelProperty(required = true, value = "")
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public CreateTagOption target(String target) {
this.target = target;
return this;
}
/**
* Get target
* @return target
**/
@ApiModelProperty(value = "")
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CreateTagOption createTagOption = (CreateTagOption) o;
return Objects.equals(this.message, createTagOption.message) &&
Objects.equals(this.tagName, createTagOption.tagName) &&
Objects.equals(this.target, createTagOption.target);
}
@Override
public int hashCode() {
return Objects.hash(message, tagName, target);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CreateTagOption {\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append(" tagName: ").append(toIndentedString(tagName)).append("\n");
sb.append(" target: ").append(toIndentedString(target)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
C++ | UTF-8 | 1,598 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "KeybindState.h"
KeybindState::KeybindState(sf::RenderWindow* window, std::map<std::string, int>* supportedKeys, sf::Font* font, sf::Color color, uint8_t size)
: State(window, supportedKeys), m_font(font)
{
InitializeText(color, size);
}
void KeybindState::InitializeKeybinds()
{
}
void KeybindState::InitializeBackground()
{
m_background.setSize(sf::Vector2f(1100.f, 1000.f));
m_background.setFillColor(sf::Color::Black);
}
void KeybindState::InitializeText(sf::Color color, uint8_t size)
{
std::stringstream ss_keys;
std::stringstream ss_actions;
std::ifstream in("../External/Resources/Config/gamestate_keybinds.ini");
if (in.is_open())
{
std::string action = "";
std::string key = "";
while (in >> action >> key)
{
ss_actions << action << std::endl;
ss_keys << key << std::endl;
}
}
else
throw "ERROR::KEYBINDS_STATE::KEYBINDS_NOT_FOUND";
in.close();
m_actions.setFont(*m_font);
m_actions.setString(ss_actions.str());
m_actions.setFillColor(color);
m_actions.setCharacterSize(size);
m_actions.setPosition(20, 20);
m_keybinds.setFont(*m_font);
m_keybinds.setString(ss_keys.str());
m_keybinds.setFillColor(color);
m_keybinds.setCharacterSize(size);
m_keybinds.setPosition(500, 20);
}
void KeybindState::UpdateInput(const float& dt)
{
CheckForQuit();
}
void KeybindState::Update(const float& dt)
{
UpdateKeytime(dt);
UpdateInput(dt);
}
void KeybindState::Render(sf::RenderTarget* target)
{
if (!target)
target = m_window;
target->draw(m_background);
target->draw(m_actions);
target->draw(m_keybinds);
}
|
Java | UTF-8 | 6,306 | 2.796875 | 3 | [] | no_license | package lottery;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
class CProcessConfig {
public String m_PrizeLevel;
public int m_PrizeNum;
public int m_NumPerRound;
public String m_PrizeType;
public String m_SpecialNames[] = {""};
private boolean m_debug = true;
public CProcessConfig(String ConfigLine) {
m_PrizeLevel = "";
m_PrizeNum = 0;
m_NumPerRound = 0;
m_PrizeType = "";
if ( ConfigLine != "" )
{
String[] words = ConfigLine.split(",");
int NumWords = words.length;
if ( m_debug ) { System.out.println( "NumWords: "+NumWords); }
if ( NumWords > 0 )
{
m_PrizeLevel = words[0].trim();
if ( m_debug ) { System.out.println( "m_PrizeLevel: "+m_PrizeLevel); }
}
if ( NumWords > 1 )
{
m_PrizeNum = Integer.parseInt(words[1]);
if ( m_debug ) { System.out.println( "m_PrizeNum: "+m_PrizeNum); }
}
if ( NumWords > 2 )
{
m_NumPerRound = Integer.parseInt(words[2]);
if ( m_debug ) { System.out.println( "m_NumPerRound: "+m_NumPerRound); }
}
if ( NumWords > 3 )
{
m_PrizeType = words[3].trim();
if ( m_debug ) { System.out.println( "m_PrizeType: "+m_PrizeType); }
}
if ( NumWords > 4 )
{
int idx = 0;
while(NumWords - idx - 4 > 0)
{
m_SpecialNames[idx] = words[4+idx].trim();
if ( m_debug ) { System.out.println( "m_SpecialNames["+idx+"]: "+m_SpecialNames[idx]); }
idx ++;
}
}
}
}
}
public class CInputs {
public CProcessConfig m_Process[] = new CProcessConfig[20];
public int m_ProcessCurrentLine = 0;
public int m_ProcessCurrentRound = 0;
private List<String> m_NameList = new ArrayList<String>();
private int m_NameListNum = 0;
private boolean m_debug = true;
public CInputs(){
LoadProcessConfig();
LoadNamelist();
}
public String[] StartStopRound(String operation) {
String[] str = new String[10];
if ( m_debug ) { System.out.println( "operation: "+operation+"m_Process.length: "+m_Process.length); }
for ( int k = 0; k < str.length; k++)
{
str[k] = "";
}
// check if all lines are proceeded
//if ( m_ProcessCurrentLine >= m_Process.length-1 )
if ( m_Process[m_ProcessCurrentLine] == null )
{
str[0] = "所有奖项都已抽完!";
return str;
}
/*
* Get the current process config
* */
int divider = m_Process[m_ProcessCurrentLine].m_NumPerRound;
if ( divider <= 0 )
{
divider = m_Process[m_ProcessCurrentLine].m_PrizeNum;
}
// how many rounds needed for the current line
int rounds = m_Process[m_ProcessCurrentLine].m_PrizeNum / divider;
if ( m_Process[m_ProcessCurrentLine].m_PrizeNum % divider > 0)
{
rounds ++;
}
if ( m_ProcessCurrentRound == 0 )
{
// initialize the current round
m_ProcessCurrentRound = rounds;
}
str[0] = m_Process[m_ProcessCurrentLine].m_PrizeLevel;
str[1] = m_Process[m_ProcessCurrentLine].m_PrizeType;
if ( m_debug ) { System.out.println( "++m_ProcessCurrentRound: "+m_ProcessCurrentRound); }
if ( m_debug ) { System.out.println( "++m_ProcessCurrentLine: "+m_ProcessCurrentLine); }
if ( m_ProcessCurrentRound > 0 )
{
if ( operation == "stop" )
{
m_ProcessCurrentRound -- ;
}
// Randomize the name list
Collections.shuffle(m_NameList);
if ( m_debug )
{
System.out.println( "shuffled name list: ");
for ( int m = 0; m < m_NameList.size(); m++ )
{
System.out.println( m + "-" + m_NameList.get(m) + "\n");
}
}
// TRICKY: special deal
int trickyNameSize = m_Process[m_ProcessCurrentLine].m_SpecialNames.length;
for ( int n = 0; n < trickyNameSize; n++)
{
String currentTrickyName = m_Process[m_ProcessCurrentLine].m_SpecialNames[n];
if ( currentTrickyName != "" )
{
boolean bAlreadyIn = false;
// Check duplicates, make sure not to occur several times
for (int dd = 0; dd < divider; dd++)
{
if ( m_NameList.get(dd) == currentTrickyName )
{
bAlreadyIn = true;
break;
}
}
if ( bAlreadyIn )
{
m_NameList.add(0, currentTrickyName);
}
}
}
if ( m_debug )
{
System.out.println( "name list after tricky: ");
for ( int z = 0; z < m_NameList.size(); z++ )
{
System.out.println( z + "-" + m_NameList.get(z) + "\n");
}
}
for (int i = 0; i < divider; i++)
{
str[2+i] = m_NameList.get(i);
if ( m_debug ) { System.out.println( "random: str[2+"+i+"]: "+str[2+i]); }
if ( operation == "stop" )
{
m_NameList.remove(i);
}
}
}
// all rounds finished for this line, switch to another line
if ( m_ProcessCurrentRound == 0 )
{
m_ProcessCurrentLine ++;
}
if ( m_debug ) { System.out.println( "--m_ProcessCurrentRound: "+m_ProcessCurrentRound); }
if ( m_debug ) { System.out.println( "--m_ProcessCurrentLine: "+m_ProcessCurrentLine); }
return str;
}
private void LoadNamelist() {
InputStream is = CLottery.class.getClassLoader().getResourceAsStream("namelist.txt");
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
if ( m_debug ) { System.out.println("initial name list: ");}
while ((line = br.readLine()) != null) {
if ( m_debug ) { System.out.println(line);}
m_NameList.add(line);
}
m_NameListNum = m_NameList.size();
} catch (IOException e) {
e.printStackTrace();
}
}
private void LoadProcessConfig() {
InputStream is = CLottery.class.getClassLoader().getResourceAsStream("process.txt");
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
int lineNum = -1;
while ((line = br.readLine()) != null) {
if ( m_debug ) { System.out.println( "LoadProcessConfig, line: "+line+" of lineNum: "+lineNum); }
if ( lineNum >= 0 ) // Skip first line which is a comment
{
m_Process[lineNum] = new CProcessConfig(line);
}
lineNum ++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private int random(int max) {
return (int) (Math.random() * max);
}
}
|
C | UTF-8 | 2,875 | 3.15625 | 3 | [] | no_license | /*****************************************************************************
* Copyright (C) 2017 by Snehal Sanghvi
*
* Redistribution, modification or use of this software in source or binary
* forms is permitted strictly for educational purposes. Users are
* permitted to modify this and use it to learn about the field of embedded
* software. Snehal Sanghvi and the University of Colorado are not liable for
* any misuse of this material.
*
*****************************************************************************/
/**
* @file test_cond.c
* @brief An implementation source code file having function calls for various
* pthread API functions involving conditional variables like pthread_cond_init,
* pthread_cond_wait, pthread_cond_signal, pthread_cond_destroy
* @author Snehal Sanghvi
* @date October 4 2017
* @version 1.0
* @compiler used to process code: GCC compiler
*/
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <stdio.h>
#include <sched.h>
#include <unistd.h>
#include <time.h>
#include <syslog.h>
#include <sys/param.h>
int flag;
pthread_mutex_t mutex;
pthread_cond_t cond;
//starting function for child thread
void *function(void *args){
printf("In child thread.\n");
pthread_mutex_lock(&mutex);
flag=1;
pthread_cond_signal(&cond);
printf("Signaling the sleeping thread to wake up.\n");
pthread_mutex_unlock(&mutex);
}
//test function that main calls for demonstration purposes
void test_function(void){
printf("Inside main's test function.\n");
pthread_mutex_lock(&mutex);
while(!flag){
printf("Main's thread put to sleep.\n");
pthread_cond_wait(&cond, &mutex);
}
printf("Main's thread wakes up.\n");
pthread_mutex_unlock(&mutex);
}
int main(){
pthread_t tid;
if(pthread_mutex_init(&mutex, NULL)){
printf("Could not initialize mutex.\n");
exit(1);
}
printf("Mutex initialized.\n");
if(pthread_cond_init(&cond, NULL)){
printf("Could not initialize condition variable.\n");
exit(1);
}
printf("Condition variable initialized.\n");
if(pthread_create(&tid, NULL, function, NULL)){
printf("Could not create thread.\n");
exit(1);
}
printf("In main thread.\n");
test_function();
printf("Back in main.\n");
if(!pthread_cond_destroy(&cond))
printf("Condition variable destroyed.\n");
else
printf("Unable to destroy condition variable.\n");
return 0;
} |
PHP | UTF-8 | 1,306 | 3.03125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Query Auth Example Implementation
*
* @copyright 2013 Jeremy Kendall
* @license https://github.com/jeremykendall/query-auth-impl/blob/master/LICENSE.md MIT
* @link https://github.com/jeremykendall/query-auth-impl
*/
namespace Example;
/**
* Stores your API key and secret
*/
class ApiCredentials
{
/**
* @var string API key
*/
private $key;
/**
* @var string API secret
*/
private $secret;
/**
* Public constructor
*
* @param string $key API key
* @param string $secret API secret
*/
public function __construct($key, $secret)
{
$this->key = $key;
$this->secret = $secret;
}
/**
* Gets API key
*
* @return string API key
*/
public function getKey()
{
return $this->key;
}
/**
* Sets API key
*
* @param string $key API key
*/
public function setKey($key)
{
$this->key = $key;
}
/**
* Gets API secret
*
* @return string API secret
*/
public function getSecret()
{
return $this->secret;
}
/**
* Sets API secret
*
* @param string $secret API secret
*/
public function setSecret($secret)
{
$this->secret = $secret;
}
}
|
C | UTF-8 | 152 | 3.171875 | 3 | [] | no_license | #include<stdio.h>
main()
{
char name[10];
printf("Enter a name:");
gets(name);
printf("Good morning %s",name);
return 0;
}
|
Python | UTF-8 | 2,741 | 4.40625 | 4 | [] | no_license | # -*- encoding: utf-8 -*-
# Stack() creates a new stack that is empty.
# It needs no parameters and returns an empty stack.
# push(item) adds a new item to the top of the stack.
# It needs the item and returns nothing.
# pop() removes the top item from the stack.
# It needs no parameters and returns the item. The stack is modified.
# peek() returns the top item from the stack but does not remove it.
# It needs no parameters. The stack is not modified.
# isEmpty() tests to see whether the stack is empty.
# It needs no parameters and returns a boolean value.
class TwoStack():
def __init__(self, size=10):
"""
Initialize python List with size of 10 or user given input.
Python List type is a dynamic array, so we have to restrict its
dynamic nature to make it work like a static array.
"""
self.size = size
self.stack = [None] * size
self.left_top = 0
self.right_top = size + 1
def push(self, value, mode="left"):
if self.isFull():
raise IndexError("stack is full")
else:
if mode == "left":
self.left_top += 1
self.stack[self.left_top - 1] = value
else:
self.right_top -= 1
self.stack[self.right_top - 1] = value
def pop(self, mode="left"):
if self.isEmpty(mode):
raise IndexError("stack is empty")
else:
if mode == "left":
value = self.stack[self.left_top - 1]
self.stack[self.left_top - 1] = None
self.left_top -= 1
else:
value = self.stack[self.right_top - 1]
self.stack[self.right_top - 1] = None
self.right_top += 1
return value
def peek(self, mode="left"):
if self.isEmpty(mode):
raise IndexError("stack is empty")
else:
if mode == "left":
return self.stack[self.left_top - 1]
else:
return self.stack[self.right_top - 1]
def isFull(self):
return self.left_top >= self.right_top
def isEmpty(self, mode):
if mode == "left":
return self.left_top == 0
else:
return self.right_top == self.size
def showStack(self):
print(self.stack)
if __name__ == '__main__':
stack = TwoStack(5)
stack.push(5, mode="left")
stack.push(8, mode="left")
stack.showStack()
stack.push(3, mode="right")
stack.push(9, mode="right")
stack.push(11, mode="right")
stack.showStack()
stack.pop(mode="left")
stack.pop(mode="right")
stack.pop(mode="right")
stack.showStack()
|
Ruby | UTF-8 | 157 | 2.578125 | 3 | [] | no_license | require 'sinatra'
get '/' do
@host = ["Adam", "Ben", "Chris"].sample
erb :index
end
get '/hello' do
@name = params[:name].capitalize
erb :index
end |
Java | UTF-8 | 33,909 | 1.945313 | 2 | [] | no_license | package com.joedobo27.enchantednature;
import com.wurmonline.mesh.Tiles;
import com.wurmonline.server.items.*;
import com.wurmonline.server.skills.SkillList;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.Bytecode;
import javassist.bytecode.Opcode;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.MethodCall;
import org.gotti.wurmunlimited.modloader.ReflectionUtil;
import org.gotti.wurmunlimited.modloader.classhooks.CodeReplacer;
import org.gotti.wurmunlimited.modloader.classhooks.HookManager;
import org.gotti.wurmunlimited.modloader.interfaces.*;
import org.gotti.wurmunlimited.modsupport.IdFactory;
import org.gotti.wurmunlimited.modsupport.IdType;
import org.gotti.wurmunlimited.modsupport.ItemTemplateBuilder;
import org.gotti.wurmunlimited.modsupport.actions.ModActions;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.joedobo27.enchantednature.BytecodeTools.addConstantPoolReference;
import static com.joedobo27.enchantednature.BytecodeTools.findConstantPoolReference;
/**
* :ENCHANTED TILE CREATION:
* new ActionEntry((short)388, "Enchant", "enchanting", Actions.EMPTY_INT_ARRAY)
* TileTreeBehaviour.getBehavioursFor() and TileGrassBehaviour.getBehavioursFor() along with logic to verify performer
* can enchant adds "Enchant" to the nature sub menu.
* TileBehaviour.action() and action #388 calls Terraforming.enchantNature().
*
* :USAGE:
* Creature.grazeNonCorrupt() This is where animal grazing can pack an enchanted grass tile.
* 1 in 20 to check packing every grazing. Enchanted grass has further rolls for packing; 1:80 off-deed, 1:120 deed
* with bad ration 1:240 for deed with good ration.
* Zone.createTrack() Every time a creature moves this is called. For grass, lawn, reed, dirt and Mycelium tiles there
* is a 2% chance when there are more then 20 tracks on a tile for it to pack.
*
* -------------------
* Polling tiles and the possibility of adding harvesting of grass, flowers and other non-enchanted features to enchanted tiles.
* TilePoller.pollNextTile() > TilePoller.checkEffects(). CheckEffects is the primary method for checking what should happen.
*/
public class EnchantedNatureMod implements WurmServerMod, Initable, Configurable, ServerStartedListener, ItemTemplatesCreatedListener {
private static Logger logger;
private static ClassPool classPool;
private boolean grazeNeverPacks = false;
private boolean noOverageStage = false;
private boolean fasterTreeGrowth = false;
private int growthAccelerator = 1;
private boolean pickSprouts = false;
private boolean enchantWithAlchemy = false;
private boolean cutGrass = false;
private static int treeEssenceTemplateId;
private static int bushEssenceTemplateId;
private static int grassEssenceTemplateId;
@Override
public void configure(Properties properties) {
grazeNeverPacks = Boolean.parseBoolean(properties.getProperty("grazeNeverPacks", Boolean.toString(grazeNeverPacks)));
noOverageStage = Boolean.parseBoolean(properties.getProperty("noOverageStage", Boolean.toString(noOverageStage)));
fasterTreeGrowth = Boolean.parseBoolean(properties.getProperty("fasterTreeGrowth", Boolean.toString(fasterTreeGrowth)));
growthAccelerator = Integer.parseInt(properties.getProperty("growthAccelerator", Integer.toString(growthAccelerator)));
pickSprouts = Boolean.parseBoolean(properties.getProperty("pickSprouts", Boolean.toString(pickSprouts)));
enchantWithAlchemy = Boolean.parseBoolean(properties.getProperty("enchantWithAlchemy", Boolean.toString(enchantWithAlchemy)));
cutGrass = Boolean.parseBoolean(properties.getProperty("cutGrass", Boolean.toString(cutGrass)));
}
@Override
public void init() {
try {
ModActions.init();
boolean isGrazeNeverPacks = disablePackingInGrazeNonCorrupt();
boolean isNoOverageStage = noOverageInCheckForTreeGrowth();
boolean isFasterTreeGrowth = fasterGrowthInCheckForTreeGrowth();
boolean isPickSprouts1 = pickSproutInGetNatureActions();
boolean isPickSprouts2 = pickSproutInAction();
boolean isPickSprouts3 = pickSproutInPickSprout();
boolean isCutGrass1 = grassGrowthOnEnchantedGrass();
boolean isCutGrass2 = cutGrassInGetNatureActions();
logger.log(Level.INFO, String.format("grazeNeverPacks %b, noOverageStage %b, fasterTreeGrowth %b", isGrazeNeverPacks,
isNoOverageStage, isFasterTreeGrowth));
logger.log(Level.INFO, String.format("isPickSprouts %b, isPickSprouts2 %b, isPickSprouts3 %b", isPickSprouts1,
isPickSprouts2, isPickSprouts3));
logger.log(Level.INFO, String.format("isCutGrass1 %b, isCutGrass2 %b", isCutGrass1, isCutGrass2));
} catch (NotFoundException | CannotCompileException e) {
logger.log(Level.WARNING, e.getMessage(), e);
}
}
@Override
public void onServerStarted() {
if (enchantWithAlchemy) {
ModActions.registerAction(new EnchantTileAction());
ModActions.registerAction(new DisenchantTileAction());
addCreationForNatureEssences();
makeEnchantedGrassInTile();
}
if (cutGrass) {
cutGrassInTile();
}
JAssistClassData.voidClazz();
}
@Override
public void onItemTemplatesCreated() {
if (enchantWithAlchemy) {
ItemTemplateBuilder treeEssenceTemplate = new ItemTemplateBuilder("jdbTreeEssenceTemplate");
treeEssenceTemplateId = IdFactory.getIdFor("jdbTreeEssenceTemplate", IdType.ITEMTEMPLATE);
treeEssenceTemplate.name("Tree essence", "Tree essence", "A mystical miniature tree. It's used to enchant or disenchant a tree tile.");
treeEssenceTemplate.size(3);
treeEssenceTemplate.itemTypes(new short[]{ItemTypes.ITEM_TYPE_MAGIC, ItemTypes.ITEM_TYPE_BULK});
treeEssenceTemplate.imageNumber((short) 484); // using sprout image number.
treeEssenceTemplate.behaviourType((short) 1); // item behaviour
treeEssenceTemplate.combatDamage(0);
treeEssenceTemplate.decayTime(86400L); // sprout decay time.
treeEssenceTemplate.dimensions(10, 10, 10);
treeEssenceTemplate.primarySkill(-10);
treeEssenceTemplate.modelName("model.resource.sprout.");
treeEssenceTemplate.difficulty(70.0f); // not sure about difficulty. use of the essence will be pass/fail so power may not matter.
treeEssenceTemplate.weightGrams(1000);
treeEssenceTemplate.material((byte) 21); // 21 for magic or 14 for sprout(which is log or wood)
treeEssenceTemplate.value(10000);
treeEssenceTemplate.isTraded(true);
try {
treeEssenceTemplate.build();
} catch (IOException e) {
e.printStackTrace();
}
ItemTemplateBuilder bushEssenceTemplate = new ItemTemplateBuilder("jdbBushEssenceTemplate");
bushEssenceTemplateId = IdFactory.getIdFor("jdbBushEssenceTemplate", IdType.ITEMTEMPLATE);
bushEssenceTemplate.name("Bush essence", "Bush essence", "A mystical miniature bush. It's used to enchant or disenchant a bush tile.");
bushEssenceTemplate.size(3);
bushEssenceTemplate.itemTypes(new short[]{ItemTypes.ITEM_TYPE_MAGIC, ItemTypes.ITEM_TYPE_BULK});
bushEssenceTemplate.imageNumber((short) 484); // using sprout image number.
bushEssenceTemplate.behaviourType((short) 1); // item behaviour
bushEssenceTemplate.combatDamage(0);
bushEssenceTemplate.decayTime(86400L); // sprout decay time.
bushEssenceTemplate.dimensions(10, 10, 10);
bushEssenceTemplate.primarySkill(-10);
bushEssenceTemplate.modelName("model.resource.sprout.");
bushEssenceTemplate.difficulty(70.0f); // not sure about difficulty. use of the essence will be pass/fail so power may not matter.
bushEssenceTemplate.weightGrams(1000);
bushEssenceTemplate.material((byte) 21); // 21 for magic or 14 for sprout(which is log or wood)
bushEssenceTemplate.value(10000);
bushEssenceTemplate.isTraded(true);
try {
bushEssenceTemplate.build();
} catch (IOException e) {
e.printStackTrace();
}
ItemTemplateBuilder grassEssenceTemplate = new ItemTemplateBuilder("jdbGrassEssenceTemplate");
grassEssenceTemplateId = IdFactory.getIdFor("jdbGrassEssenceTemplate", IdType.ITEMTEMPLATE);
grassEssenceTemplate.name("Grass essence", "Grass essence", "A mystical clump of grass. It's used to enchant or disenchant a grass tile.");
grassEssenceTemplate.size(3);
grassEssenceTemplate.itemTypes(new short[]{ItemTypes.ITEM_TYPE_MAGIC, ItemTypes.ITEM_TYPE_BULK});
grassEssenceTemplate.imageNumber((short) 702); // using mixed grass image number.
grassEssenceTemplate.behaviourType((short) 1); // item behaviour
grassEssenceTemplate.combatDamage(0);
grassEssenceTemplate.decayTime(86400L); // sprout decay time.
grassEssenceTemplate.dimensions(10, 10, 10);
grassEssenceTemplate.primarySkill(-10);
grassEssenceTemplate.modelName("model.flower.mixedgrass.");
grassEssenceTemplate.difficulty(70.0f); // not sure about difficulty. use of the essence will be pass/fail so power may not matter.
grassEssenceTemplate.weightGrams(1000);
grassEssenceTemplate.material((byte) 21); // 21 for magic or 14 for sprout(which is log or wood)
grassEssenceTemplate.value(10000);
grassEssenceTemplate.isTraded(true);
try {
grassEssenceTemplate.build();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void enchantedInIsGrassType() throws NotFoundException, CannotCompileException {
JAssistClassData tilesClass = JAssistClassData.getClazz("Tiles");
if (tilesClass == null)
tilesClass = new JAssistClassData("com.wurmonline.mesh.Tiles", classPool);
JAssistMethodData isGrassTypeWU = new JAssistMethodData(tilesClass, "(B)Z", "isGrassType");
CtMethod isGrassTypeMod = classPool.get("com.joedobo27.enchantednature.EnchantedNatureMod").getMethod("isGrassType",
"(B)Z");
isGrassTypeWU.getCtMethod().setBody(isGrassTypeMod, null);
}
private boolean makeEnchantedGrassInTile() {
try {
Field isNormal = ReflectionUtil.getField(Tiles.Tile.class, "isNormal");
for (Tiles.Tile tile : Tiles.Tile.getTiles()) {
if (tile != null && tile.getId() == 2) {
ReflectionUtil.setPrivateField(tile, isNormal, Boolean.TRUE);
}
}
}catch (NoSuchFieldException | IllegalAccessException e){
return false;
}
return true;
}
private boolean cutGrassInTile() {
try {
Field isGrass = ReflectionUtil.getField(Tiles.Tile.class, "isGrass");
for (Tiles.Tile tile : Tiles.Tile.getTiles()) {
if (tile != null && tile.getId() == 13) {
ReflectionUtil.setPrivateField(tile, isGrass, Boolean.TRUE);
}
}
} catch (NoSuchFieldException | IllegalAccessException e) {
return false;
}
return true;
}
/**
* Change TreeTileBehavior.getNatureActions() so cut grass on tree tile behaviour is possible.
* was-
* if (!theTile.isEnchanted() && growthStage != GrassData.GrowthTreeStage.LAWN) {...}
*
* becomes-
* change the return value of isEnchanted() to always be false.
*
* Bytecode index 527 which goes with line 239.
*
* @return boolean type, isSuccess.
* @throws NotFoundException JA related, forwarded.
* @throws CannotCompileException JA related, forwarded.
*/
private boolean cutGrassInGetNatureActions() throws NotFoundException, CannotCompileException {
final boolean[] successes = {false};
if (!cutGrass)
return successes[0];
JAssistClassData tileTreeBehaviour = JAssistClassData.getClazz("TileTreeBehaviour");
if (tileTreeBehaviour == null)
tileTreeBehaviour = new JAssistClassData("com.wurmonline.server.behaviours.TileTreeBehaviour", classPool);
JAssistMethodData getNatureActions = new JAssistMethodData(tileTreeBehaviour,
"(Lcom/wurmonline/server/creatures/Creature;Lcom/wurmonline/server/items/Item;IILcom/wurmonline/mesh/Tiles$Tile;B)Ljava/util/List;",
"getNatureActions");
getNatureActions.getCtMethod().instrument(new ExprEditor() {
@Override
public void edit(MethodCall methodCall) throws CannotCompileException{
if (Objects.equals("isEnchanted", methodCall.getMethodName()) && methodCall.getLineNumber() == 239) {
successes[0] = true;
methodCall.replace("$_ = false;");
}
}
});
return successes[0];
}
/**
* Editing TilePoller.checkEffects() with bytecode alteration. Make it so enchanted grass will be checked for grass growth.
* was-
* if (type == Tiles.Tile.TILE_GRASS.id || type == Tiles.Tile.TILE_KELP.id || type == Tiles.Tile.TILE_REED.id) {...)
*
* becomes-
* if (type == Tiles.Tile.TILE_ENCHANTED_GRASS.id || type == Tiles.Tile.TILE_GRASS.id || type == Tiles.Tile.TILE_KELP.id
* || type == Tiles.Tile.TILE_REED.id) {...}
*
* @return boolean type, isSuccess
* @throws NotFoundException JA related, forwarded.
*/
private boolean grassGrowthOnEnchantedGrass() throws NotFoundException {
JAssistClassData tilePoller = new JAssistClassData("com.wurmonline.server.zones.TilePoller", classPool);
JAssistMethodData checkEffects = new JAssistMethodData(tilePoller, "(IIIBB)V", "checkEffects");
//<editor-fold desc="find bytecode from Javap.exe">
/*
221: iload_3
222: getstatic #94 // Field com/wurmonline/mesh/Tiles$Tile.TILE_GRASS:Lcom/wurmonline/mesh/Tiles$Tile;
225: getfield #49 // Field com/wurmonline/mesh/Tiles$Tile.id:B
228: if_icmpeq 251
231: iload_3
232: getstatic #95 // Field com/wurmonline/mesh/Tiles$Tile.TILE_KELP:Lcom/wurmonline/mesh/Tiles$Tile;
235: getfield #49 // Field com/wurmonline/mesh/Tiles$Tile.id:B
238: if_icmpeq 251
241: iload_3
242: getstatic #96 // Field com/wurmonline/mesh/Tiles$Tile.TILE_REED:Lcom/wurmonline/mesh/Tiles$Tile;
245: getfield #49 // Field com/wurmonline/mesh/Tiles$Tile.id:B
248: if_icmpne 318
*/
//</editor-fold>
Bytecode find = new Bytecode(tilePoller.getConstPool());
find.addOpcode(Opcode.ILOAD_3);
find.addOpcode(Opcode.GETSTATIC);
byte[] poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.TILE_GRASS:Lcom/wurmonline/mesh/Tiles$Tile;");
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.GETFIELD);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.id:B");
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.IF_ICMPEQ); // 228: if_icmpeq 251
poolAddress = BytecodeTools.intToByteArray(23, 2);
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.ILOAD_3);
find.addOpcode(Opcode.GETSTATIC);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.TILE_KELP:Lcom/wurmonline/mesh/Tiles$Tile;");
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.GETFIELD);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.id:B");
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.IF_ICMPEQ); // 238: if_icmpeq 251
poolAddress = BytecodeTools.intToByteArray(13, 2);
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.ILOAD_3);
find.addOpcode(Opcode.GETSTATIC);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.TILE_REED:Lcom/wurmonline/mesh/Tiles$Tile;");
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.GETFIELD);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.id:B");
find.add(poolAddress[0], poolAddress[1]);
find.addOpcode(Opcode.IF_ICMPNE); // 248: if_icmpne 318
poolAddress = BytecodeTools.intToByteArray(70, 2);
find.add(poolAddress[0], poolAddress[1]);
Bytecode replace = new Bytecode(tilePoller.getConstPool());
replace.addOpcode(Opcode.ILOAD_3);
replace.addOpcode(Opcode.GETSTATIC);
poolAddress = addConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.TILE_ENCHANTED_GRASS:Lcom/wurmonline/mesh/Tiles$Tile;");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.GETFIELD);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.id:B");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.IF_ICMPEQ); // 218: if_icmpeq 251
poolAddress = BytecodeTools.intToByteArray(33, 2);
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.ILOAD_3);
replace.addOpcode(Opcode.GETSTATIC);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.TILE_GRASS:Lcom/wurmonline/mesh/Tiles$Tile;");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.GETFIELD);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.id:B");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.IF_ICMPEQ); // 228: if_icmpeq 251
poolAddress = BytecodeTools.intToByteArray(23, 2);
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.ILOAD_3);
replace.addOpcode(Opcode.GETSTATIC);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.TILE_KELP:Lcom/wurmonline/mesh/Tiles$Tile;");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.GETFIELD);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.id:B");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.IF_ICMPEQ); // 238: if_icmpeq 251
poolAddress = BytecodeTools.intToByteArray(13, 2);
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.ILOAD_3);
replace.addOpcode(Opcode.GETSTATIC);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.TILE_REED:Lcom/wurmonline/mesh/Tiles$Tile;");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.GETFIELD);
poolAddress = findConstantPoolReference(tilePoller.getConstPool(),
"// Field com/wurmonline/mesh/Tiles$Tile.id:B");
replace.add(poolAddress[0], poolAddress[1]);
replace.addOpcode(Opcode.IF_ICMPNE); // 248: if_icmpne 318
poolAddress = BytecodeTools.intToByteArray(70, 2);
replace.add(poolAddress[0], poolAddress[1]);
CodeReplacer codeReplacer = new CodeReplacer(checkEffects.getCodeAttribute());
try {
codeReplacer.replaceCode(find.get(), replace.get());
checkEffects.getMethodInfo().rebuildStackMapIf6(classPool, tilePoller.getClassFile());
}catch (BadBytecode e){
return false;
}
return true;
}
/**
* change Terraforming.pickSprout() is the pick sprout action works on enchanted trees.
* was-
* if (sickle.getTemplateId() == 267 && !theTile.isEnchanted()) {
*
* becomes-
* Alter isEnchanted() so it always returns false;
*
* Bytecode index 22, line number group 4843. isEnchanted methods isn't used again in method so not using line number.
*
* @return boolean type, isSuccess
* @throws NotFoundException JA related, forwarded.
* @throws CannotCompileException JA related, forwarded.
*/
private boolean pickSproutInPickSprout() throws NotFoundException, CannotCompileException{
final boolean[] successes = {false};
if (!pickSprouts)
return successes[0];
JAssistClassData terraforming = JAssistClassData.getClazz("Terraforming");
if (terraforming == null) {
terraforming = new JAssistClassData(
"com.wurmonline.server.behaviours.Terraforming", classPool);
}
JAssistMethodData pickSprout = new JAssistMethodData(terraforming,
"(Lcom/wurmonline/server/creatures/Creature;Lcom/wurmonline/server/items/Item;IIILcom/wurmonline/mesh/Tiles$Tile;FLcom/wurmonline/server/behaviours/Action;)Z",
"pickSprout"
);
pickSprout.getCtMethod().instrument(new ExprEditor() {
@Override
public void edit(MethodCall methodCall) throws CannotCompileException{
if (Objects.equals("isEnchanted", methodCall.getMethodName())){
successes[0] = true;
methodCall.replace("$_ = false;");
}
}
});
return successes[0];
}
/**
* was-
* else if (!theTile.isEnchanted() && action == 187) {
*
* becomes-
* Alter isEnchanted() so it always returns false;
*
* Bytecode index 113 goes on line 557
*
* @return boolean type, isSuccess
* @throws NotFoundException JA related, forwarded.
* @throws CannotCompileException JA related, forwarded.
*/
private boolean pickSproutInAction() throws NotFoundException, CannotCompileException {
final boolean[] successes = {false};
if (!pickSprouts)
return successes[0];
JAssistClassData tileTreeBehaviour = JAssistClassData.getClazz("TileTreeBehaviour");
if (tileTreeBehaviour == null) {
tileTreeBehaviour = new JAssistClassData(
"com.wurmonline.server.behaviours.TileTreeBehaviour", classPool);
}
JAssistMethodData action = new JAssistMethodData(tileTreeBehaviour,
"(Lcom/wurmonline/server/behaviours/Action;Lcom/wurmonline/server/creatures/Creature;Lcom/wurmonline/server/items/Item;IIZIISF)Z",
"action");
action.getCtMethod().instrument(new ExprEditor() {
@Override
public void edit(MethodCall methodCall) throws CannotCompileException {
if (Objects.equals("isEnchanted", methodCall.getMethodName()) && methodCall.getLineNumber() == 557) {
successes[0] = true;
methodCall.replace("$_ = false;");
}
}
});
return successes[0];
}
/**
* Change TileTreeBehaviour.getNatureActions() so pick sprout on tree tile behaviour is possible.
* was-
* if (subject.getTemplateId() == 267 && !theTile.isEnchanted()) {
*
* becomes-
* change the return value of isEnchanted() to always be false.
*
* Bytecode index 39 which goes with line 178.
*
* @return boolean type, isSuccess.
* @throws NotFoundException JA related, forwarded.
* @throws CannotCompileException JA related, forwarded.
*/
private boolean pickSproutInGetNatureActions() throws NotFoundException, CannotCompileException {
final boolean[] successes = {false};
if (!pickSprouts)
return successes[0];
JAssistClassData tileTreeBehaviour = JAssistClassData.getClazz("TileTreeBehaviour");
if (tileTreeBehaviour == null) {
tileTreeBehaviour = new JAssistClassData("com.wurmonline.server.behaviours.TileTreeBehaviour", classPool);
}
JAssistMethodData getNatureActions = new JAssistMethodData(tileTreeBehaviour,
"(Lcom/wurmonline/server/creatures/Creature;Lcom/wurmonline/server/items/Item;IILcom/wurmonline/mesh/Tiles$Tile;B)Ljava/util/List;",
"getNatureActions");
getNatureActions.getCtMethod().instrument(new ExprEditor() {
@Override
public void edit(MethodCall methodCall) throws CannotCompileException {
if (Objects.equals("isEnchanted", methodCall.getMethodName()) && methodCall.getLineNumber() == 178) {
successes[0] = true;
methodCall.replace("$_ = false;");
}
}
});
return successes[0];
}
/**
* was-
* final int chance = TilePoller.entryServer ? Server.rand.nextInt(20) : Server.rand.nextInt(225);
*
* becomes -
* Change the 255 arg to 64 if theTile.isEnchanted() is true. This should x4 the chance for an enchanted
* tree to age.
*
* Bytecode line 131.
*
* @return boolean type, isSuccess.
* @throws NotFoundException JA related, forwarded.
* @throws CannotCompileException JA related, forwarded.
*/
private boolean fasterGrowthInCheckForTreeGrowth() throws NotFoundException, CannotCompileException {
final boolean[] successes = {false};
if (!fasterTreeGrowth)
return successes[0];
JAssistClassData tilePoller = JAssistClassData.getClazz("TilePoller");
if (tilePoller == null) {
tilePoller = new JAssistClassData("com.wurmonline.server.zones.TilePoller", classPool);
}
String growthValue = Integer.toString(255 / growthAccelerator);
JAssistMethodData checkForTreeGrowth = new JAssistMethodData(tilePoller, "(IIIBB)V", "checkForTreeGrowth");
checkForTreeGrowth.getCtMethod().instrument(new ExprEditor() {
@Override
public void edit(MethodCall methodCall) throws CannotCompileException {
if (Objects.equals("nextInt", methodCall.getMethodName()) && methodCall.indexOfBytecode() == 131) {
successes[0] = true;
methodCall.replace("" +
"{" +
"$1 = theTile.isEnchanted() ? " + growthValue + " : 255;" +
"$_ = $proceed($$);" +
"}");
}
}
});
return successes[0];
}
/**
* was-
* final byte newType2 = convertToNewType(theTile, newData2);
*
* becomes-
* Change the value passed in for newData2 if the tree's age is 14 (overaged). Recalculate tree age using age 13(very old, sprout):
* newData2 = (byte)((age << 4) + partdata & 0xFF);
*
* Bytecode index 391 which goes in line number 1940. Note that in bytecode the local var is newData, not newData2.
*
* @return boolean type, isSuccess.
* @throws NotFoundException JA related, forwarded.
* @throws CannotCompileException JA related, forwarded.
*/
private boolean noOverageInCheckForTreeGrowth() throws NotFoundException, CannotCompileException {
final boolean[] successes = {false};
if (!noOverageStage)
return successes[0];
JAssistClassData tilePoller = JAssistClassData.getClazz("TilePoller");
if (tilePoller == null) {
tilePoller = new JAssistClassData("com.wurmonline.server.zones.TilePoller", classPool);
}
JAssistMethodData checkForTreeGrowth = new JAssistMethodData(tilePoller, "(IIIBB)V", "checkForTreeGrowth");
checkForTreeGrowth.getCtMethod().instrument(new ExprEditor() {
@Override
public void edit(MethodCall methodCall) throws CannotCompileException {
if (Objects.equals("convertToNewType", methodCall.getMethodName()) && methodCall.getLineNumber() == 1940) {
successes[0] = true;
methodCall.replace("" +
"{" +
"newData = (age == 14 && theTile.isEnchanted()) ? (byte)((13 << 4) + partdata & 0xFF) : newData;" +
"$_ = $proceed($$);" +
"}");
}
}
});
return successes[0];
}
/**
* was-
* type == Tiles.Tile.TILE_GRASS.id || type == Tiles.Tile.TILE_STEPPE.id ||
* (type == Tiles.Tile.TILE_ENCHANTED_GRASS.id && Server.rand.nextInt(enchGrassPackChance) == 0))
*
* becomes-
* if type == Tiles.Tile.TILE_ENCHANTED_GRASS.id alter the return value from TILE_ENCHANTED_GRASS.id so it's never true.
*
* Bytecode index 164&167 which goes with line number 6248 block.
*
* @return boolean type, isSuccess.
* @throws NotFoundException JA related, forwarded.
* @throws CannotCompileException JA related, forwarded.
*/
private boolean disablePackingInGrazeNonCorrupt() throws NotFoundException, CannotCompileException {
final boolean[] successes = {false};
if (!grazeNeverPacks)
return successes[0];
JAssistClassData creature = new JAssistClassData("com.wurmonline.server.creatures.Creature", classPool);
JAssistMethodData grazeNonCorrupt = new JAssistMethodData(creature,
"(IBLcom/wurmonline/server/villages/Village;)Z", "grazeNonCorrupt");
grazeNonCorrupt.getCtMethod().instrument(new ExprEditor() {
@Override
public void edit(FieldAccess fieldAccess) throws CannotCompileException {
if (Objects.equals("id", fieldAccess.getFieldName()) && fieldAccess.indexOfBytecode() == 167) {
successes[0] = true;
fieldAccess.replace("$_ = type == com.wurmonline.mesh.Tiles.Tile.TILE_ENCHANTED_GRASS.id ? 0 : type;");
}
}
});
return successes[0];
}
private void addCreationForNatureEssences() {
AdvancedCreationEntry treeEssenceTemplate = CreationEntryCreator.createAdvancedEntry(SkillList.ALCHEMY_NATURAL,
ItemList.fruitJuice, ItemList.sprout, treeEssenceTemplateId, false,false,
0.0f, true, false, CreationCategories.ALCHEMY);
treeEssenceTemplate.addRequirement(new CreationRequirement(1, ItemList.sourceSalt, 1, true));
treeEssenceTemplate.addRequirement(new CreationRequirement(2, ItemList.scrapwood, 1, true));
AdvancedCreationEntry bushEssenceTemplate = CreationEntryCreator.createAdvancedEntry(SkillList.ALCHEMY_NATURAL,
ItemList.fruitJuice, ItemList.sprout, bushEssenceTemplateId, false, false,
0.0f, true, false, CreationCategories.ALCHEMY);
bushEssenceTemplate.addRequirement(new CreationRequirement(1, ItemList.sourceSalt, 1, true));
bushEssenceTemplate.addRequirement(new CreationRequirement(2, ItemList.flowerRose, 1, true));
AdvancedCreationEntry grassEssenceTemplate = CreationEntryCreator.createAdvancedEntry(SkillList.ALCHEMY_NATURAL,
ItemList.fruitJuice, ItemList.mixedGrass, grassEssenceTemplateId, false, false,
0.0f, true, false, CreationCategories.ALCHEMY);
grassEssenceTemplate.addRequirement(new CreationRequirement(1, ItemList.sourceSalt, 1, true));
grassEssenceTemplate.addRequirement(new CreationRequirement(2, ItemList.mixedGrass, 1, true));
}
static int getTreeEssenceTemplateId() {
return treeEssenceTemplateId;
}
static int getBushEssenceTemplateId() {
return bushEssenceTemplateId;
}
static int getGrassEssenceTemplateId() {
return grassEssenceTemplateId;
}
@SuppressWarnings("unused")
public static boolean isGrassType(final byte tileId) {
switch (tileId & 0xFF) {
case Tiles.TILE_TYPE_GRASS:
case Tiles.TILE_TYPE_ENCHANTED_GRASS:
case Tiles.TILE_TYPE_KELP:
case Tiles.TILE_TYPE_REED:
case Tiles.TILE_TYPE_LAWN: {
return true;
}
default: {
return false;
}
}
}
static {
logger = Logger.getLogger(EnchantedNatureMod.class.getName());
classPool = HookManager.getInstance().getClassPool();
}
}
|
Markdown | UTF-8 | 8,377 | 2.609375 | 3 | [] | no_license | <div class="panel panel-default">
<div class="area-title">
<span>
题目描述
<small>Description</small>
</span></div>
<div class="panel-body">
<p style=""><span style="">BY<span style="">J</span></span><span style="">发现一堆长短不一的木棍<span style="">。</span>由于它们太混乱<span style="">,</span></span><span style="">BY<span style="">J</span></span><span style="">打算截长补短<span style="">,</span>使这些木棍的长</span></p><p style=""><span style="">度相同。</span></p><p style=""><span style="">BY</span><span style="">J</span><span style="">计算出这些</span><span style="">木棍长度的平均<span style="">数</span>(设平均数<span style="">为</span></span><span style="">s</span><span style="">,</span><span style="">保<span style="">证</span></span><span style="">s</span><span style="">为正整数<span style="">)</span><span style="">,</span>接着将所有木棍放在面前,进行如下操作:</span></p><p style=""><span style="">1</span><span style="">、从面前的木棍中找出最长的一根(长度为</span> <span style="">max</span><span style="">)和</span><span style="">最短的一根(长度为</span> <span style="">min</span><span style="">)</span><span style="">;</span> <span style="">2</span><span style="">、如<span style="">果</span></span><span style="">max+min>2s</span><span style="">,则<span style="">将</span></span><span style="">ma<span style="">x</span></span><span style="">截<span style="">为</span></span><span style="">max+min-s</span><span style="">,</span><span style="">mi<span style="">n</span></span><span style="">补<span style="">为</span></span><span style="">s</span><span style="">;</span></p><p style=""><span style="">3</span><span style="">、如<span style="">果</span></span><span style="">m</span><span style="">ax+</span><span style="">m</span><span style="">i<span style="">n<2s</span></span><span style="">,则<span style="">将</span></span><span style="">m</span><span style="">a</span><span style="">x</span><span style="">截<span style="">为</span></span><span style="">s</span><span style="">,</span><span style="">m</span><span style="">i<span style="">n</span></span><span style="">补<span style="">为</span></span><span style="">m</span><span style="">a</span><span style="">x+<span style="">m</span>in<span style="">-</span>s</span><span style="">;</span></p><p style=""><span style="">4</span><span style="">、如<span style="">果</span></span><span style="">max+min=2s</span><span style="">,则<span style="">将</span></span><span style="">ma<span style="">x</span></span><span style="">截<span style="">为</span></span><span style="">s</span><span style="">,</span><span style="">mi<span style="">n</span></span><span style="">补<span style="">为</span></span><span style="">s</span><span style="">;</span></p><p style=""><span style="">5</span><span style="">、将当前长度<span style="">为</span></span><span style="">s</span><span style="">的木棍放到一边(即这些木棍不再进行操作<span style="">)</span>;</span></p><p style=""><span style="">6</span><span style="">、如果面前没有木棍,则停止,否则回<span style="">到</span></span><span style="">1</span><span style="">。</span></p><p style=""><span style="">每重复一次,步数就加一。</span><span style="">BYJ </span><span style="">想知道使所有木棍的长度都变<span style="">成</span></span><span style="">s</span><span style="">所需要的步数。</span></p><p><br></p>
</div>
</div>
<div class="panel panel-default">
<div class="area-title">
<span>
输入描述
<small>Input Description</small>
</span></div>
<div class="panel-body">
<p style=""><span style="">//输入文件<span style="">为</span></span><span style="">cut.in</span><span style="">。</span></p><p style=""><span style="">第一行包含一个正整<span style="">数</span></span><span style="">N</span><span style="">,表示<span style="">有</span></span><span style="">N</span><span style="">根木棍。</span></p><p style=""><span style="">接下来<span style="">的</span></span><span style="">N</span><span style="">行,每行一个正整<span style="">数</span></span><span style="">L</span><span style="">,表示该木棍的长度<span style="">为</span></span><span style="">L</span><span style="">。</span></p><p><br></p>
</div>
</div>
<div class="panel panel-default">
<div class="area-title">
<span>
输出描述
<small>Output Description</small>
</span></div>
<div class="panel-body">
<p style="margin: 3px 0 0 28px;line-height: 18px"><span style="font-size:14px;font-family:宋体">//输出文件<span style="letter-spacing:2px">为</span></span><span style="font-size:14px">cut.out</span><span style="font-size:14px;font-family:宋体">。</span></p><p style="margin: 3px 0 0 28px;line-height: 18px"><span style="font-size:14px;font-family:宋体">输出只有一行,包含一个正整数,表示使所有木棍的长度都变<span style="letter-spacing:2px">成</span></span><span style="font-size: 14px;letter-spacing:3px">s</span><span style="font-size:14px;font-family:宋体">所需要的步数。</span></p><p><br/></p>
</div>
</div>
<div class="panel panel-default">
<div class="area-title">
<span>
样例输入
<small>Sample Input</small>
</span></div>
<div class="panel-body">
<p style=""><span style="font-family: 'Courier New';">6</span></p><p style=""><span style="font-family: 'Courier New';">2</span></p><p style=""><span style="font-family: 'Courier New';">9</span></p><p style=""><span style="font-family: 'Courier New';">1</span></p><p style=""><span style="font-family: 'Courier New';">6</span></p><p style=""><span style="font-family: 'Courier New';">4</span></p><p><span style="font-family: 'Courier New';">14</span></p><p><br></p>
</div>
</div>
<div class="panel panel-default">
<div class="area-title">
<span>
样例输出
<small>Sample Output</small>
</span></div>
<div class="panel-body">
<p>4<br></p>
</div>
</div>
<div class="panel panel-default">
<div class="area-title">
<span>
数据范围及提示
<small>Data Size & Hint</small>
</span></div>
<div class="panel-body">
<p style=""><span style="">【输入输出样例说明】</span></p><p style=""><span style="">第</span><span style="">1</span><span style="">次:从<span style="">第</span></span><span style="">6</span><span style="">根木棍上截<span style="">取</span></span><span style="">5</span><span style="">个单位长度补到<span style="">第</span></span><span style="">3</span><span style="">根木棍上;</span></p><p style=""><span style="">第</span><span style="">2</span><span style="">次:从<span style="">第</span></span><span style="">6</span><span style="">根木棍上截<span style="">取</span></span><span style="">3</span><span style="">个单位长度补到<span style="">第</span></span><span style="">1</span><span style="">根木棍上;</span></p><p style=""><span style="">第</span><span style="">3</span><span style="">次:从<span style="">第</span></span><span style="">2</span><span style="">根木棍上截<span style="">取</span></span><span style="">1</span><span style="">个单位长度补到<span style="">第</span></span><span style="">1</span><span style="">根木棍上;</span></p><p style=""><span style="">第</span><span style="">4</span><span style="">次:从<span style="">第</span></span><span style="">2</span><span style="">根木棍上截<span style="">取</span></span><span style="">2</span><span style="">个单位长度补到<span style="">第</span></span><span style="">5</span><span style="">根木棍上。</span></p><p style=""><span style="">【数据范围】</span></p><p style=""><span style="">对<span style="">于</span></span><span style="">20%</span><span style="">的数据,</span><span style="">1<span style="text-decoration: underline;"><</span>N<span style="text-decoration: underline;"><</span>10</span><span style="">。</span></p><p style=""><span style="">对<span style="">于</span></span><span style="">100%</span><span style="">的数据,</span><span style="">1<span style="text-decoration: underline;"><</span>N<span style="text-decoration: underline;"><</span>1000</span><span style="">。</span></p><p><br></p>
</div>
</div> |
C++ | UTF-8 | 2,945 | 2.609375 | 3 | [] | no_license | #include"persistentsegtree_faster.hpp"
using namespace std;
using namespace StetAlgo;
int main(){
vector<int> V;
int (*reducer)(int,int) = [](int a,int b){return a+b;};
using checkpointType = size_t;
checkpointType initChk = 0;
auto tree = makePersistentSegTree<500000>(V, reducer, initChk);
cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false);
int m;
cin >> m;
int elemCount = 0;
while(m--){
int queryType, x, k;
size_t L, R;
cin >> queryType;
if(queryType == 1){
cin >> x;
tree.checkout( ++elemCount , true); //overwriting
tree.update( x, 1 + tree.get(x, elemCount) );
}
else if(queryType == 2){
cin >> L >> R >> x;
auto now = tree.getRootNode(R);
auto past = tree.getRootNode(L-1);
Interval cover {0, 524287};
int left,right;
while(cover.first != cover.second){
left = (now->left->val != past->left->val) * ( 2 * (cover.first ^ x) + 1);
right = (now->right->val != past->right->val) * ( 2 * (rightHalf(cover).first^x ) + 1);
if(left>right){
now = now->left; past = past->left; cover = leftHalf(cover);
} else{
now = now->right; past = past->right; cover = rightHalf(cover);
}
}
cout << cover.first <<'\n';
}
else if(queryType == 3){
cin >> k;
tree.checkout( elemCount-k , false); // not overwriting
elemCount -=k ;
}
else if(queryType == 4){
cin >> L >> R >> x;
// cout << tree.reduce({0,x},R) << endl;
// cout << tree.reduce({0,x},L-1) << endl;
cout << tree.reduce({0,x},R) - tree.reduce({0,x},L-1) << '\n';
}
else if(queryType == 5){
cin >> L >> R >> k;
// kth largest number.
auto now = tree.getRootNode(R);
auto past = tree.getRootNode(L-1);
Interval cover{0,524287};
int leftval, rightval, a;
while( !now->terminal ){
leftval = now->left->val - past->left->val;
if(k==1){
if(leftval ==0){
now = now->right; past = past->right; cover = rightHalf(cover);
}
else{
now = now->left; past = past->left; cover = leftHalf(cover);
}
}
else if(k>leftval){
k -= leftval;
now = now->right; past = past->right; cover = rightHalf(cover);
}
else{
now = now->left; past = past->left; cover = leftHalf(cover);
}
}
cout << cover.first << '\n';
}
}
}
|
Shell | UTF-8 | 891 | 4.21875 | 4 | [] | no_license | #!/bin/bash
# copydir.sh
# 拷贝 (verbose) 当前目录($PWD)下的所有文件到
#+ 命令行中指定的另一个目录下.
E_NOARGS=65
if [ -z "$1" ] # 如果没有参数传递进来那就退出.
then
echo "Usage: `basename $0` directory-to-copy-to"
exit $E_NOARGS
fi
ls . | xargs -t -I % cp ./% $1
# ls . | xargs -i -t cp ./{} $1
# ^^ ^^ ^^
# -t 是 "verbose" (输出命令行到 stderr) 选项.
# -i 是"替换字符串"选项. mac 下是-I,后面指定替换符号 %
# {} 是输出文本的替换点.
# 这与在"find"命令中使用{}的情况很相像.
#
# 列出当前目录下的所有文件(ls .),
#+ 将 "ls" 的输出作为参数传递到 "xargs"(-i -t 选项) 中,
#+ 然后拷贝(cp)这些参数({})到一个新目录中($1).
#
# 最终的结果和下边的命令等价,
#+ cp*$1
#+ 除非有文件名中嵌入了"空白"字符.
exit 0
|
C# | UTF-8 | 2,980 | 3.140625 | 3 | [] | permissive | // Copyright (c) 2019 Glenn Watson. All rights reserved.
// Glenn Watson licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
namespace ReactiveGit.Gui.Core.Model.Branches
{
/// <summary>
/// A node in the branch structure.
/// </summary>
public abstract class BranchNode : IEquatable<BranchNode>
{
/// <summary>
/// Initializes a new instance of the <see cref="BranchNode" /> class.
/// </summary>
/// <param name="name">The name of the node.</param>
/// <param name="fullName">The full name of the node.</param>
protected BranchNode(string name, string fullName)
{
Name = name;
FullName = fullName;
}
/// <summary>
/// Gets gets or sets the full name of the node.
/// </summary>
public string FullName { get; }
/// <summary>
/// Gets the name of the node.
/// </summary>
public string Name { get; }
/// <summary>
/// Determines if the left and the right are logically equal.
/// </summary>
/// <param name="left">The left to compare.</param>
/// <param name="right">The right to compare.</param>
/// <returns>If they are logically equal.</returns>
public static bool operator ==(BranchNode left, BranchNode right)
{
return Equals(left, right);
}
/// <summary>
/// Determines if the left and the right are not logically equal.
/// </summary>
/// <param name="left">The left to compare.</param>
/// <param name="right">The right to compare.</param>
/// <returns>If they are not logically equal.</returns>
public static bool operator !=(BranchNode left, BranchNode right)
{
return !Equals(left, right);
}
/// <inheritdoc />
public bool Equals(BranchNode other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return string.Equals(FullName, other.FullName, StringComparison.InvariantCulture);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
var other = obj as BranchNode;
return (other != null) && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
return FullName?.GetHashCode() ?? 0;
}
/// <inheritdoc />
public override string ToString()
{
return Name;
}
}
} |
Java | UTF-8 | 971 | 1.921875 | 2 | [] | no_license | package com.itfac.amc.util;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import lombok.Data;
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
@CreatedBy
@Column(name = "saved_by", length = 15, updatable = false)
protected String savedBy;
@CreatedDate
@Column(name = "saved_on", updatable = false)
protected Date savedOn;
@LastModifiedBy
@Column(name = "last_modified_by")
protected String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_on")
protected Date lastModifiedOn;
}
|
Python | UTF-8 | 808 | 2.96875 | 3 | [] | no_license | import socket, sys
host, port = sys.argv[1:]
#look up th given data
results = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
#We may get multiple results back. Display each one.
for result in results:
print "-"*60
#print whether we got back an IPv4 or IPv6 result.
if result[0] == socket.AF_INET:
print "Family: AF_INET"
elif result[0] == socket.AF_INET6:
print "Family: AF_INET6"
else:
print "Family: result[0]"
#indicate whether it's a stream(TCP) or datagram (UDP) result.
if result[1] == socket.SOCK_STREAM:
print "Socket Type: SOCK_STREAM"
elif result[1] == socket.SOCK_DGRAM:
print "Scket Type: SOCK_DGRAM"
print "Protocol:", result[2]
print "Canonical Name:", result[3]
print "Socket Address:", result[4]
|
C++ | UTF-8 | 495 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <deque>
#include <algorithm>
#include <vector>
using namespace std;
int E,S,M;
int result = 1;
int main(){
cin >> E >> S >> M;
while(1){
if(E == 1 && S == 1 && M == 1){
break;
}
E--;
S--;
M--;
if(E == 0){
E = 15;
}
if(S == 0){
S = 28;
}
if(M == 0){
M = 19;
}
result ++;
}
cout << result;
return 0;
} |
Python | UTF-8 | 710 | 4.03125 | 4 | [] | no_license | # # In versions of Python prior to Python 3, os.listdir() is the method to use to get a directory listing:
#
# ______ __
# entries _ __.l_d_ my_directory/'
#
# # os.listdir() returns a Python list containing the names of the files and subdirectories in the directory given
# # by the path argument:
#
# __.l_d_('my_directory/')
# # ['sub_dir_c', 'file1.py', 'sub_dir_b', 'file3.txt', 'file2.csv', 'sub_dir']
#
# # A directory listing like that isn’t easy to read. Printing out the output of a call to os.listdir() using
# # a loop helps clean things up:
#
# entries _ __.l_d_ 'my_directory/'
# ___ entry __ ?
# print ?
#
#
# # sub_dir_c
# # file1.py
# # sub_dir_b
# # file3.txt
# # file2.csv
# # sub_dir
|
C | UTF-8 | 6,684 | 3.265625 | 3 | [] | no_license | #include "tree.h"
void flatten_list ( node_t* node );
void evaluate_expression ( node_t* node );
void replace_node ( node_t* node, node_t* other );
#ifdef DUMP_TREES
void
node_print ( FILE *output, node_t *root, uint32_t nesting )
{
if ( root != NULL )
{
fprintf ( output, "%*c%s", nesting, ' ', root->type.text );
if ( root->type.index == INTEGER )
fprintf ( output, "(%d)", *((int32_t *)root->data) );
if ( root->type.index == VARIABLE || root->type.index == EXPRESSION )
{
if ( root->data != NULL )
fprintf ( output, "(\"%s\")", (char *)root->data );
else
fprintf ( output, "%p", root->data );
}
fputc ( '\n', output );
for ( int32_t i=0; i<root->n_children; i++ )
node_print ( output, root->children[i], nesting+1 );
}
else
fprintf ( output, "%*c%p\n", nesting, ' ', root );
}
#endif
node_t *node_init ( node_t *nd, nodetype_t type, void *data, uint32_t n_children, ... ) {
node_t *node = nd;
node->type = type;
node->data = data;
node->n_children = n_children;
node->entry = NULL;
if ( n_children > 0 ) {
node->children = malloc(sizeof(node_t*)*n_children);
va_list args;
va_start ( args, n_children );
for ( int i = 0; i < node->n_children; i++ ) {
(node->children)[i] = va_arg ( args, node_t *);
}
va_end ( args );
} else
node->children = NULL;
return node;
}
void node_finalize ( node_t *discard ) {
free ( discard->data );
free ( discard->entry );
free ( discard );
}
void destroy_subtree ( node_t *discard ){
if ( discard == NULL )
return;
for ( int i = 0; i < discard->n_children; i++ )
destroy_subtree ( (discard->children)[i] );
node_finalize ( discard );
}
node_t *simplify_tree ( node_t *node ){
if ( node != NULL ){
// Recursively simplify the children of the current node
for ( uint32_t i=0; i < node->n_children; i++ ){
node->children[i] = simplify_tree ( node->children[i] );
}
// After the children have been simplified, we look at the current node
// What we do depend upon the type of node
switch ( node->type.index )
{
// These are lists which needs to be flattened. Their structure
// is the same, so they can be treated the same way.
case FUNCTION_LIST: case STATEMENT_LIST: case PRINT_LIST:
case EXPRESSION_LIST: case VARIABLE_LIST:
flatten_list ( node );
break;
// Declaration lists should also be flattened, but their stucture is sligthly
// different, so they need their own case
case DECLARATION_LIST:
// First do a check to remove the nil-node, afterwards this can be handled
// the same way as the other lists
if ( node->children[0] == NULL ) {
for (int i = 1; i < node->n_children; i++ )
node->children[i-1] = node->children[i];
node->n_children -= 1;
node_finalize (node->children[node->n_children]);
}
flatten_list ( node );
break;
// These have only one child, so they are not needed
case STATEMENT: case PARAMETER_LIST: case ARGUMENT_LIST:
if ( node != NULL ) {
node_t *child = node->children[0];
replace_node ( node, child );
}
break;
// Expressions where both children are integers can be evaluated (and replaced with
// integer nodes). Expressions whith just one child can be removed (like statements etc above)
case EXPRESSION:
evaluate_expression ( node );
break;
}
}
return node;
}
void flatten_list ( node_t *node ) {
if ( node != NULL && node->children[0]->type.index == node->type.index) {
node_t *child_list = node->children[0];
int n_children = child_list->n_children + 1;
node_t **children = malloc(sizeof(node_t *) * n_children);
for ( int i = 0; i < child_list->n_children; i++ )
children[i] = child_list->children[i];
children[n_children-1] = node->children[1];
node->n_children = n_children;
node->children = children;
}
}
void evaluate_expression ( node_t *node ) {
if ( node->n_children == 1 ) {
// Handle unary minus when the child is a number
if ( node->data != NULL && *((char *) node->data) == '-'
&& node->children[0]->type.index == INTEGER ) {
int *data = (int *)node->children[0]->data;
*data = -(*data);
node->children[0]->type = integer_n;
replace_node (node, node->children[0] );
}
// Replace the node with it's child if it is not unary minus
else if ( node->data == NULL || *((char *) node->data) != '-')
replace_node (node, node->children[0] );
}
for ( int i = 0; i < node->n_children; i++ ) {
if ( node->children[0]->type.index == INTEGER
&& node->children[1]->type.index == INTEGER ) {
char operator = *((char *) node->data);
int l_val ,
r_val,
result;
node_t *l_child = node->children[0];
node_t *r_child = node->children[1];
l_val = *((int *) l_child->data);
r_val = *((int *) r_child->data);
node_finalize ( r_child );
node_finalize ( l_child );
switch ( operator ) {
case '+':
result = l_val + r_val;
break;
case '-':
result = l_val - r_val;
break;
case '*':
result = l_val * r_val;
break;
case '/':
result = l_val / r_val;
break;
}
node->type = integer_n;
*((int *) node->data) = result;
node->n_children = 0;
node->children = NULL;
}
}
}
void replace_node ( node_t *node, node_t *other ) {
if ( node != NULL && other != NULL ) {
node->type = other->type;
node->data = other->data;
node->entry = other->entry;
node->n_children = other->n_children;
node->children = other->children;
free ( other );
}
} |
Python | UTF-8 | 2,850 | 3.484375 | 3 | [] | no_license | import random
letra = " "
letras_bien = 0
oport = 6
letras_usa = []
palabra_act = []
letras_sr = []
palabras = ["ventana", "libreria", "sonido", "universidad", "elefante"]
letras_correctas = ""
rand = random.randint(0,len(palabras)-1)
pal_esco = palabras[rand]
largo = len(pal_esco)
word = []
print("Bienvenido al juego de el ahorcado")
print("El largo de la palabra es:", largo)
for contador in range(largo):
word.append("_")
def imprimir(letra, palabra):
for cont in range(len(palabra)):
if letra in palabra[cont]:
word.insert(cont,letra)
del word[cont+1]
print("la palabra actual es",word)
def hombre(intentos):
if intentos == 6:
print("+---+")
print("| |")
print (" |")
print (" |")
print (" |")
print (" |")
print ("=========)")
elif intentos == 5:
print("+---+")
print("| |")
print ("O |")
print (" |")
print (" |")
print (" |")
print ("=========)")
elif intentos == 4:
print("+---+")
print("| |")
print ("O |")
print ("| |")
print (" |")
print (" |")
print ("=========)")
elif intentos == 3:
print(" +---+")
print(" | |")
print (" O |")
print ("/| |")
print (" |")
print (" |")
print (" =========)")
elif intentos == 2:
print(" +---+")
print(" | |")
print (" O |")
print ("/|\ |")
print (" |")
print (" |")
print (" =========)")
elif intentos == 1:
print(" +---+")
print(" | |")
print (" O |")
print ("/|\ |")
print ("/ |")
print (" |")
print (" =========)")
elif intentos == 0:
print(" +---+")
print(" | |")
print (" O |")
print ("/|\ |")
print ("/ \ |")
print (" |")
print (" =========)")
for cont in range(0, largo):
if pal_esco[cont] not in letras_sr:
letras_sr.append(pal_esco[cont])
while True:
#escoger()
letra = input()
if letra in letras_usa:
print("ya usaste esta letra")
elif letra in letras_sr:
print("le atinaste")
letras_usa.append(letra)
letras_bien += 1
hombre(oport)
imprimir(letra,pal_esco)
if letras_bien == len(letras_sr):
print("ganaste")
break
else:
print("esta letra no es")
letras_usa.append(letra)
oport -= 1
print("te quedan:",oport,"intentos")
imprimir(letra,pal_esco)
hombre(oport)
if oport== 0:
print("perdiste")
break |
JavaScript | UTF-8 | 1,557 | 2.609375 | 3 | [] | no_license | 'use strict';
var blessed = require('blessed');
var contrib = require('blessed-contrib');
function HSLtoRGB(color) {
var hue = color.hue;
var saturation = color.saturation;
var brightness = color.brightness;
var kelvin = color.kelvin;
}
class Main {
constructor(screen) {
this.screen = screen;
this.grid = new contrib.grid({rows: 12, cols: 8, screen: screen});
this.data = {};
this.tableArray = [];
}
update(data) {
this.data = data;
this.processData()();
this.setData()();
this.screen.render();
}
processData() {
return () => {
this.tableArray = [];
if (Object.keys(this.data).length > 0) {
var now = new Date();
Object.keys(this.data.lights).forEach((key) => {
var light = this.data.lights[key];
var elapsed = 0;
if (light.info)
elapsed = (now - light.info.lastSeen)/1000;
var arr = [String(light.label), String(light.status), String(elapsed)];
this.tableArray.push(arr);
});
}
this.getLayout();
}
}
setData() {
return () => {
this.statusTable.setData({
headers: ['name', 'on/off', 'last seen'],
data: this.tableArray
});
}
}
getLayout() {
return () => {
this.log = this.grid.set(8, 0, 4, 8, contrib.log, {
fg: "green",
selectedFg: "green",
label: "Status"
});
this.statusTable = this.grid.set(4, 0, 4, 8, contrib.table, {
keys: true,
fg: 'green',
selectedFg:'white',
selectedBg: 'blue',
interactive: false,
label: 'Lights',
columnWidth: [13, 4, 4]
});
}
}
}
module.exports = Main;
|
Python | UTF-8 | 5,328 | 3.171875 | 3 | [] | no_license | import random
import sqlite3
connect = sqlite3.connect('card.s3db')
cursor = connect.cursor()
# cursor.execute("DROP TABLE card")
cursor.execute("CREATE TABLE if not exists card (id INTEGER PRIMARY KEY AUTOINCREMENT, number TEXT, pin TEXT, balance INTEGER DEFAULT 0);")
connect.commit()
class Card():
def __init__(self):
self.number = None
self.pin = None
self.balance = None
def create(self):
number ='400000' + ''.join(str(random.randrange(9)) for _ in range(9))
self.number = number + str(luna(number,0))
self.pin = ''.join(str(random.randrange(10)) for _ in range(4))
self.balance = 0
print('\nYour card has been created\nYour card number:\n{}\nYou card PIN:\n{}\n'.format(self.number, self.pin))
cursor.execute("INSERT INTO card (number, pin, balance) VALUES (?, ?, ?);",
(self.number, self.pin, self.balance))
connect.commit()
def login(self, number, pin):
self.number = number
self.pin = database(number)
if self.pin != 0:
if self.pin == int(pin):
cursor.execute("SELECT balance FROM card WHERE number = (?)", [(self.number)])
balance = cursor.fetchone()
self.balance = balance[0]
print('\nYou have successfully logged in!\n')
return 1
else:
print('\nWrong card number or PIN!\n')
return 0
else:
print('\nWrong card number or PIN!\n')
return 0
def check(self):
print('\nBalance: {}\n'.format(self.balance))
def income(self, cost):
self.balance += int(cost)
cursor.execute("UPDATE card SET balance = ? WHERE number = ?", [self.balance, self.number])
connect.commit()
print('Income was added!\n')
def do_transfer(self):
number_recipient = input('Enter card number:\n')
if luna(number_recipient, 1):
if database(number_recipient):
money = int(input('Enter how much money you want to transfer:\n'))
if money <= self.balance:
self.balance -= money
cursor.execute("UPDATE card SET balance = ? WHERE number = ?", [self.balance, self.number])
connect.commit()
cursor.execute("SELECT balance FROM card WHERE number = ?", [(number_recipient)])
db_bal = cursor.fetchone()
new_balance = int(db_bal[0]) + money
cursor.execute("UPDATE card SET balance = ? WHERE number = ?", [new_balance, number_recipient])
connect.commit()
print('Success!\n')
else:
print('Not enough money!\n')
else:
print('Such a card does not exist.\n')
else:
print('Probably you made a mistake in the card number. Please try again!\n')
def delete(self):
cursor.execute("DELETE FROM card WHERE number = ?", [(self.number)])
connect.commit()
print('\nThe account has been closed!\n')
def luna(number, mode): # mode=0 -> search check sum. mode=1 -> check
s, odd = 0, 1
if mode == 1:
check = int(number) % 10
num_var = int(number) // 10
number = str(num_var)
for char in number:
n = int(char)
if odd % 2 == 1:
n *= 2
if n > 9:
n -= 9
odd += 1
s += n
if s % 10 != 0:
check_sum = 10 - (s % 10)
else:
check_sum = 0
if mode == 0:
return check_sum
else:
if check == check_sum:
return True
else:
print('\nProbably you made a mistake in the card number. Please try again!\n')
return False
def database(number):
cursor.execute("SELECT pin FROM card WHERE number = (?)", [(number)])
db_pin = cursor.fetchone()
if db_pin is None:
print('\nSuch a card does not exist.\n')
return 0
else:
return int(db_pin[0])
print('1. Create an account\n2. Log into account\n0. Exit')
login = 0
command = int(input())
while command != 0:
# Create card
if command == 1 and login == 0:
card = Card()
card.create()
# Balance
if command == 1 and login == 1:
card.check()
# Login
if command == 2 and login == 0:
command = -1
number = input('\nEnter your card number:\n')
pin = input('Enter your PIN:\n')
login = card.login(number, pin)
# Add income
if command == 2 and login == 1:
cost = input('\nEnter income:\n')
card.income(cost)
# Do transfer
if command == 3 and login == 1:
print('\nTransfer')
card.do_transfer()
# Delete
if command == 4 and login == 1:
card.delete()
login = 0
# Log out
if command == 5 and login == 1:
command = -1
login = 0
print('\nYou have successfully logged out!\n')
# Menu
if login == 0:
print('1. Create an account\n2. Log into account\n0. Exit')
else:
print('1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit')
command = int(input())
print('\nBye!')
|
Python | UTF-8 | 427 | 2.8125 | 3 | [] | no_license | # Import Komplettes Modul (Hauptmodul)
import datetime
a = datetime.datetime.fromtimestamp(123213213)
b = datetime.date.fromtimestamp(123213213)
print(datetime.__dict__)
print(a.hour)
print(a.day)
# Import UnterModul
from datetime import date
date.fromtimestamp(123213213)
# Import UnterModul
from datetime import datetime
datetime.fromtimestamp(123213213)
from datetime import datetime as dt
dt.fromtimestamp(123213213)
|
C++ | UTF-8 | 742 | 3.21875 | 3 | [] | no_license | #include "writinghabit.h"
#include <QStringList>
WritingHabit::WritingHabit(){
bioperator = comma = brace = total = 0;
}
WritingHabit &WritingHabit::operator+=(const WritingHabit &plus){
this->bioperator += plus.bioperator;
this->comma += plus.comma;
this->total = this->bioperator + this->comma;
return *this;
}
QString WritingHabit::toString() const{
return QString("%1\t%2\t%3").arg(this->bioperator).arg(this->comma).arg(this->brace);
}
WritingHabit WritingHabit::fromString(QString str){
QStringList strlist = str.split("\t");
WritingHabit habit;
if(!str.isEmpty()){
habit.bioperator = strlist.at(0).toInt();
habit.comma = strlist.at(1).toInt();
habit.total = habit.bioperator + habit.comma;
}
return habit;
}
|
Markdown | UTF-8 | 9,185 | 2.6875 | 3 | [
"MIT"
] | permissive | # release-script
Release tool for npm and bower packages.
[](https://travis-ci.org/AlexKVal/release-script)
---
#### Description
With this tool there is no need to keep (transpiled) `lib`, `build`
or `distr` files in the git repo.
Because `Bower` keeps its files in the github repo,
this tools helps to deal with that too.
Just create new additional github repo for `Bower` version of your project.
This repo will contain only commits generated by this tool.
Say the name of your project is
`original-project-name`
then name the `bower` github repo as
`original-project-name-bower`.
Add `'release-script'.bowerRepo` into your `package.json`:
```json
"release-script": {
"bowerRepo": "git@github.com:<author>/original-project-name-bower.git"
}
```
Then add additional step into your building process,
which will create `bower` package files in the `amd` folder,
(basically it is just a process of copying the `lib` files, README and LICENSE)
and that's all.
Now `release-script` will do all those steps (described next),
including `bower` publishing, for you - automatically.
_Initial idea is got from `React-Bootstrap` release tools `./tools/release`,
that have been written by [Matt Smith @mtscout6](https://github.com/mtscout6)_
_Kind of "migration manual"_ https://github.com/AlexKVal/release-script/issues/23
#### Documentation pages publishing
If your project generates static documentation pages (as `React-Boostrap` does)
and needs publishing them to a standalone repo (via `git push`), just create additional github repo for the documentation pages.
E.g. [react-bootstrap.github.io.git](https://github.com/react-bootstrap/react-bootstrap.github.io)
Add it as `'release-script'.docsRepo` into your `package.json`:
```json
"release-script": {
"docsRepo": "git@github.com:<author>/original-project-name-github.io.git"
}
```
Default folders for documentation pages are:
- `"docsRoot": "docs-built"` folder where the files will be built to. (by your custom building script)
- `"tmpDocsRepo": "tmp-docs-repo"` temporary folder. (for the release-script usage)
It is advised to add them both into `.gitignore`.
You can customize them as you need:
```json
"release-script": {
"docsRepo": "git@github.com:<author>/original-project-name-github.io.git",
"docsRoot": "docs-built",
"tmpDocsRepo": "tmp-docs-repo"
}
```
If you need to publish only documentation pages (say with some minor fixes),
you can do it this way:
```
> release --only-docs
```
In this case the `package.json` version will be bumped with `--preid docs` as `0.10.0` => `0.10.0-docs.0`.
If `npm run docs-build` script is present, then it will be used instead of `npm run build` script.
*Note: Documentation pages are not published when you are releasing "pre-release" version,
(i.e. when you run it with `--preid` option).*
#### Pre-release versions publishing
Say you need to publish pre-release `v0.25.100-pre.0` version
with the `canary` npm tag name (instead of default one `latest`).
You can do it this way:
```
> release 0.25.100 --preid pre --tag canary
or
> npm run release 0.25.100 -- --preid pre --tag canary
```
If your `preid` tag and npm tag are the same, then you can just:
```
> release 0.25.100 --preid beta
```
It will produce `v0.25.100-beta.0` and `npm publish --tag beta`.
`changelog` generated output will go into `CHANGELOG-alpha.md` for pre-releases,
and with the next release this file will be removed.
#### Alternative npm package root folder
Say you want to publish the content of your `lib` folder as an npm package's root folder.
Then you can do it as simple as adding the following to your `package.json`
```json
"release-script": {
"altPkgRootFolder": "lib"
}
```
and that's all.
#### The special case. `build` step in `tests` step.
If you run building scripts within your `npm run test` step, e.g.
```json
"scripts": {
"test": "npm run lint && npm run build && npm run tests-set",
}
```
then you can prevent `npm run build` step from running
by setting `'release-script'.skipBuildStep` option:
```json
"release-script": {
"skipBuildStep": "true"
}
```
#### Options
All options for this package are kept under `'release-script'` node in your project's `package.json`
- `bowerRepo` - the full url to github project for the bower pkg files
- `bowerRoot` - the folder name where your `npm run build` command will put/transpile files for bower pkg
- `default` value: `'amd'`
- `tmpBowerRepo` - the folder name for temporary files for bower pkg.
- `default` value: `'tmp-bower-repo'`
- `altPkgRootFolder` - the folder name for alternative npm package's root folder
- `versionPrefix` - the prefix to use for versions ( e.g. 'v')
It is advised to add `bowerRoot` and `tmpBowerRepo` folders to your `.gitignore` file.
Example:
```json
"release-script": {
"bowerRepo": "git@github.com:<org-author-name>/<name-of-project>-bower.git",
"bowerRoot": "amd",
"tmpBowerRepo": "tmp-bower-repo",
"altPkgRootFolder": "lib"
}
```
#### GitHub releases
If you need this script to publish github releases,
you can generate a github token at https://github.com/settings/tokens
and put it to `env.GITHUB_TOKEN` this way:
```sh
> GITHUB_TOKEN="xxxxxxxxxxxx" && release-script patch
```
or into your shell scripts
```sh
export GITHUB_TOKEN="xxxxxxxxxxxx"
```
You can set a custom message for github release via `--notes` CLI option:
```
> release patch --notes "This is a small fix"
```
#### If you need `dry-run` mode by default
You can setup the `release-script` to run in `dry-run` mode by default.
It can be done by setting `"true"` the `defaultDryRun` option in your `package.json`:
```json
"release-script": {
"defaultDryRun": "true"
}
```
Then to actually run your commands you will have to add `--run`.
#### This script does the following steps:
- ensures that git repo has no pending changes
- ensures that the latest version is fetched
- checks linting and tests by running `npm run test` command
- does version bumping
- builds all by running `npm run build` command
- If there is no `build` script, then `release-script` just skips the `build` step.
- if one of `[rf|mt]-changelog` is used in 'devDependencies', then changelog is to be generated
- adds and commits `package.json` with changed version and `CHANGELOG.md` if it's used
- adds git tag with new version and changelog message if it's used
- pushes changes to github repo
- if github token is present the script publishes the release to the GitHub
- if `--preid` tag set then `npm publish --tag` command for npm publishing is used
- with `--tag` option one can set `npm tag name` for a pre-release version (e.g. `alpha` or `canary`)
- otherwise `--preid` value will be used
- if `altPkgRootFolder` isn't set it will just `npm publish [--tag]` as usual. Otherwise:
- the release-script will `npm publish [--tag]` from the inside `altPkgRootFolder` folder
- `scripts` and `devDependencies` will be removed from `package.json`
- if `bowerRepo` field is present in the `package.json` then bower package will be released.
- the script will clone the bower repo to the `tmpBowerRepo` folder
- clean up all files but `.git` in the `tmpBowerRepo` folder
- copy all files from `bowerRoot` to `tmpBowerRepo` (they has to be generated by `npm run build`)
- add all files to the temporary git repo with `git add -A .`
- then it will commit, tag and push. The same as for the `npm` package.
- and at the end it will remove the `tmpBowerRepo` folder
- if `docsRepo` option is set then documentation pages are being pushed to their repo.
It is done the same way as `bower` publishing process.
If `--only-docs` command line option is set then `github`, `npm` and `bower` publishing steps will be skipped.
## Installation
```sh
> npm install -D release-script
```
If you need `bower` releases too then add `'release-script'.bowerRepo` into your `package.json`:
```json
"release-script": {
"bowerRepo": "git@github.com:<org-author-name>/<name-of-project>-bower.git"
}
```
If you have smth like that in your shell:
```sh
# npm
export PATH="./node_modules/.bin:$PATH"
```
or you had installed `release-script` globally via `npm install -g release-script`,
then you can release your new versions this way:
```sh
> release patch
or
> release minor --preid alpha
```
Otherwise you need to type in the commands this way:
```sh
> ./node_modules/.bin/release minor --preid alpha
```
You can as well add some helpful `script` commands to your `package.json`:
```json
"scripts": {
...
"patch": "release patch",
"minor": "release minor",
"major": "release major"
```
And you can add it like this:
```json
"scripts": {
...
"release": "release",
```
This way it became possible to run it like that:
```
> npm run release minor -- --preid alpha
> npm run release patch -- --notes "This is small fix"
> npm run release major --dry-run // for dry run
etc
```
_Notice: You have to add additional double slash `--` before any `--option`. This way additional options get through to `release-script`._
## License
`release-script` is licensed under the [MIT License](https://github.com/alexkval/release-script/blob/master/LICENSE).
|
C# | UTF-8 | 571 | 3.046875 | 3 | [] | no_license | List<List<string>> list = new List<List<string>>();
try
{
for (UInt32 I = 0; I < 134217727; I++)
{
List<string> SubList = new List<string>();
list.Add(SubList);
for (UInt32 x = 0; x < 134217727; x++)
{
SubList.Add("random string");
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
Microsoft.VisualBasic.Devices.ComputerInfo CI = new ComputerInfo();
Console.WriteLine(CI.AvailablePhysicalMemory);
}
|
TypeScript | UTF-8 | 786 | 2.5625 | 3 | [
"MIT"
] | permissive | import { NextApiRequest, NextApiResponse } from 'next'
import { getClient, getSimilarStories } from '../../../services'
export default async function searchEndpoint(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'GET') {
try {
const { id, n, field } = req.query
const nResults = n ? parseInt(n as string) : 10
const queryField = field ? (field as string) : 'title_embedding'
const client = getClient()
const response = await getSimilarStories(
client,
id as string,
nResults,
queryField as string
)
res.status(200).json(response)
} catch {
res.status(500).json({ error: 'Unable to query' })
}
} else {
res.status(405).json({ error: 'Method not allowed' })
}
}
|
Java | UTF-8 | 4,874 | 2.5 | 2 | [
"MIT"
] | permissive | /*
* ComposerApplication.java
*
* Created on September 19, 2003, 4:39 PM
*/
package processing;
import componentmodel.Component;
import util.Config;
import util.FileFactor;
/**
*
* @author alla
*/
public class ApplicationFactory {
private Component applComponents[];
private Component allComponents[];
private String path;
private String code = "";
/** Creates a new instance of ComposerApplication */
public ApplicationFactory(Component[] _components) {
allComponents = _components;
this.createApplication();
}
/**
*
*
*/
private void setPath(){
path = Config.getProjectPath();
FileFactor.makeDir(Config.getProjectPath());
}
/** */
private void setApplComponent(){
int size;
Component componentArray[];
size = this.allComponents.length;
componentArray = new Component[size];
int j = 0;
for(int i = 0; i < size; i++){
if(this.allComponents[i].getTypeAppl().equals(Component.VISUAL)){
componentArray[j] = this.allComponents[i];
j++;
}
}
applComponents = new Component[j];
System.arraycopy(componentArray, 0, this.applComponents, 0, j);
}
/**
*
*/
private void setDependenceCode(){
int size;
String depCode;
size = this.applComponents.length;
for(int i = 0; i < size; i++){
depCode = this.writeDependenceCode(this.applComponents[i].getDependence());
this.applComponents[i].setDependenceCode(depCode);
}
}
/**
*
*/
private String writeDependenceCode(Component _component){
CodeFactory composer;
Component compDep;
if(_component.getType().equals("Filter") || _component.getType().equals("Comunicator")){
return "";
}
compDep = _component.getDependence();
composer = new CodeFactory();
composer.setTemplate(Config.getTemplatePath() + "dependenceCodeAppl.vm");
composer.putSimpleValue("name", _component.getName());
if (compDep.getType().equals("Filter")){
composer.putSimpleValue("dependence", "filter");
} else {
composer.putSimpleValue("dependence", compDep.getName());
}
code = this.writeDependenceCode(compDep) + composer.toString();
return code;
}
/**
*
*/
private void createComposer(){
try {
int numberAppls;
CodeFactory composer = new CodeFactory();
numberAppls = applComponents.length;
composer.setTemplate(Config.getTemplatePath() + "Composer.vm");
composer.putSimpleValue("numberAppls", numberAppls);
composer.putArrayObject("listAllComponent", allComponents);
composer.putArrayObject("listApplComponent", applComponents);
composer.writeFileComp(path + "/Composer.java");
}catch (Exception ex){
ex.printStackTrace();
}
}
/**
*
*/
private void createFilter(){
try{
CodeFactory composer = new CodeFactory();
composer.setTemplate(Config.getTemplatePath() + "Filter.vm");
composer.putArrayObject("listApplComponent", applComponents);
composer.writeFileComp(path + "/Filter.java");
}catch (Exception ex){
ex.printStackTrace();
}
}
private void copyFiles(){
int size;
String compType;
size = allComponents.length;
for(int i = 0; i < size; i++){
compType = allComponents[i].getType();
FileFactor.copyDir(Config.getFatherPath() + compType+"/",
path + compType+"/");
//FileFactor.copyFile(Config.getFatherPath() + compType,
// Config.getProjectPath() + compType + Config.getExtension());
}
FileFactor.copyDir(Config.getFatherPath() + "util/",
path + "util/");
FileFactor.copyFile(Config.getFatherPath() + "Comunicator",
path + "Comunicator" + Config.getExtension());
FileFactor.copyFile(Config.getFatherPath() + "ObjectCanvas",
path + "ObjectCanvas" + Config.getExtension());
FileFactor.copyFile(Config.getFatherPath() + "BeanWatcher",
path + "BeanWatcher" + Config.getExtension());
}
/**
*
*/
private void createApplication(){
this.setPath();
this.setApplComponent();
this.setDependenceCode();
this.createComposer();
this.createFilter();
this.copyFiles();
}
}
|
C++ | UTF-8 | 672 | 2.609375 | 3 | [] | no_license | //
// demo.cpp
// codejam
// Problem URL: http://demo/url
//
// Created by ZhengDong on 15/9/23.
// Copyright (c) 2015年 ZhengDong. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define NOT_USE_STDIO
using namespace std;
int main(int argc, const char * argv[]) {
#ifdef NOT_USE_STDIO
ifstream input("/Users/zhengdong/Programming/codejam/data/demo.in");
ofstream output("/Users/zhengdong/Programming/codejam/data/demo.out");
streambuf *in = cin.rdbuf(input.rdbuf());
streambuf *out = cout.rdbuf(output.rdbuf());
#endif
#ifdef NOT_USE_STDIO
cin.rdbuf(in);
cout.rdbuf(out);
#endif
return 0;
}
|
Java | UTF-8 | 269 | 1.695313 | 2 | [] | no_license | package com.projet.DeuxMainsPourToi.metier.DTO;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter
@NoArgsConstructor
public class UpdPwdDTO {
private String email;
private String newPwd;
private String oldPwd;
}
|
SQL | UTF-8 | 337 | 3.078125 | 3 | [] | no_license | select pp.x,pp.Y from escuela e join poligono p on e.POLIGONO_ID = p.POLIGONO_ID
join contorno_poligono cp on p.POLIGONO_ID = cp.POLIGONO_ID
join contorno c on c.CONTORNO_ID = cp.CONTORNO_ID
join punto_contorno pc on pc.CONTORNO_ID = c.CONTORNO_ID
join punto pp on pp.punto_id = pc.punto_id
where e.CLAVE = "ESUR" group by pp.PUNTO_ID ; |
Java | UTF-8 | 4,904 | 2.28125 | 2 | [] | no_license | package challenge.webside.authorization;
import challenge.dbside.models.ChallengeDefinition;
import challenge.dbside.models.ChallengeInstance;
import challenge.dbside.models.User;
import challenge.dbside.models.status.ChallengeInstanceStatus;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
@Component
public class UserActionsProvider {
public Set<Action> getActionsForProfile(User userWhichMakesRequest, User userWhoseProfileRequested) {
Set<Action> actions = new HashSet<>();
if (userWhichMakesRequest.getId().equals(userWhoseProfileRequested.getId())) {
actions.add(Action.EDIT_CHALLENGE);
actions.add(Action.CREATE_CHALLENGE);
actions.add(Action.DELETE_CHALLENGE);
actions.add(Action.THROW_CHALLENGE_DEF);
actions.add(Action.WATCH_UNACCEPTED_CHALLENGES);
actions.add(Action.EDIT_PROFILE);
} else {
actions.add(Action.THROW_CHALLENGE_FOR_USER);
if (!userWhichMakesRequest.getFriends().contains(userWhoseProfileRequested)
&& !userWhoseProfileRequested.getIncomingFriendRequestSenders().contains(userWhichMakesRequest)
&& !userWhichMakesRequest.getIncomingFriendRequestSenders().contains(userWhoseProfileRequested)) {
actions.add(Action.ADD_FRIEND);
}
}
return actions;
}
public Set<Action> getActionsForChallengeDefinition(User user, ChallengeDefinition challenge) {
Set<Action> actions = new HashSet<>();
if (user != null) {
boolean canAccept = true;
List<ChallengeInstance> instances = challenge.getChallengeInstances();
for (ChallengeInstance chal : instances) {
if (chal.getAcceptor().equals(user) && chal.getStatus() == ChallengeInstanceStatus.ACCEPTED) {
canAccept = false;
break;
}
}
if (canAccept) {
actions.add(Action.ACCEPT_CHALLENGE_DEF);
}
if (user.getId().equals(challenge.getCreator().getId())) {
actions.add(Action.EDIT_CHALLENGE);
actions.add(Action.DELETE_CHALLENGE);
actions.add(Action.THROW_CHALLENGE_DEF);
}
}
return actions;
}
public Set<Action> getActionsForChallengeInstance(User user, ChallengeInstance challenge) {
Set<Action> actions = new HashSet<>();
if (user.getId().equals(challenge.getAcceptor().getId())) {
if (challenge.getStatus() == ChallengeInstanceStatus.ACCEPTED) {
actions.add(Action.ADD_STEPS);
}
switch (challenge.getStatus()) {
case ACCEPTED:
actions.add(Action.CLOSE_CHALLENGE);
break;
default:
break;
}
}
if (user.getSubscriptions().contains(challenge)) {
if (challenge.getStatus() == ChallengeInstanceStatus.PUT_TO_VOTE) {
if (challenge.getVotesFor().contains(user) || challenge.getVotesAgainst().contains(user)) {
actions.add(Action.WATCH_VOTES);
} else {
actions.add(Action.VOTE_FOR_CHALLENGE);
}
} else if (challenge.getStatus() == ChallengeInstanceStatus.COMPLETED || challenge.getStatus() == ChallengeInstanceStatus.FAILED) {
actions.add(Action.WATCH_VOTES);
}
} else {
if (!user.getId().equals(challenge.getAcceptor().getId()) &&
challenge.getStatus() == ChallengeInstanceStatus.ACCEPTED) {
actions.add(Action.SUBSCRIBE_CHALLENGE);
}
switch (challenge.getStatus()) {
case COMPLETED:
case FAILED:
case PUT_TO_VOTE:
actions.add(Action.WATCH_VOTES);
break;
default:
break;
}
}
return actions;
}
public void canUpdateChallenge(User user, ChallengeDefinition challenge) {
if (!getActionsForChallengeDefinition(user, challenge).contains(Action.EDIT_CHALLENGE)) {
throw new AccessDeniedException("You don't have permission to access this page");
}
}
public void canEditProfile(User user, User profileOwner) {
if (!getActionsForProfile(user, profileOwner).contains(Action.EDIT_PROFILE)) {
throw new AccessDeniedException("You don't have permission to access this page");
}
}
}
|
Java | UTF-8 | 469 | 2.0625 | 2 | [] | no_license | package com.emobile.application.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class PlanIdNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public PlanIdNotFoundException(String message) {
super(message);
}
public PlanIdNotFoundException(String message, Throwable t) {
super(message, t);
}
}
|
Python | UTF-8 | 801 | 2.6875 | 3 | [] | no_license | rela_esnmed = input()
ence = input()
nota_ence = int(input())
tipo_esco = input()
renda = float(input())
if ((rela_esnmed != "CLD") or (rela_esnmed != 'CVC') or (rela_esnmed != 'CSC') or (rela_esnmed != 'NCC')): print("Informacao sobre ensino medio invalida")
elif (rela_esnmed == 'CVC'): print("Voce terah direito a isencao")
elif (ence == 's') and (nota_ence >= 400): print("Voce terah direito a isencao")
elif ((tipo_esco == 'PUB') or (tipo_esco == 'PCB')) and (renda <= 1431): print("Voce terah direito a isencao")
elif (tipo_esco == 'PUB') or (tipo_esco == 'PCB') and (renda > 1431): print("Infelizmente voce nao tem direito a isencao")
elif (tipo_esco == 'PSB') or (tipo_esco == 'PPS') or (tipo_esco == 'PPB') or (tipo_esco == 'NFE'): print("Infelizmente voce nao tem direito a isencao")
|
Python | UTF-8 | 12,210 | 2.75 | 3 | [
"MIT"
] | permissive | #
# coding=utf-8
import copy
import os
from typing import List
import readline
from lib.thg.base.Interpreter.thgcmd import with_category
from .thgcmd.rl_utils import rl_type, RlType
MNTHG = "Menus THG"
MNTHGH = "MENU HELP"
@with_category(MNTHG)
class AddSubmenu(object):
"""Conveniently add a submenu (Cmd-like class) to a Cmd
e.g. given "class SubMenu(Cmd): ..." then
@AddSubmenu(SubMenu(), 'sub')
class MyCmd(cmd.Cmd):
....
will have the following effects:
1. 'sub' will interactively enter the cmdloop of a SubMenu instance
2. 'sub cmd args' will call thg_cmd(args) in a SubMenu instance
3. 'sub ... [TAB]' will have the same behavior as [TAB] in a SubMenu cmdloop
i.e., autocompletion works the way you think it should
4. 'help sub [cmd]' will print SubMenu's help (calls its thg_help())
"""
@with_category(MNTHG)
class _Nonexistent(object):
"""
Used to mark missing attributes.
Disable __dict__ creation since this class does nothing
"""
__slots__ = () #
@with_category(MNTHG)
def __init__(
self,
submenu,
command,
aliases=(),
#reformat_prompt="{super_prompt}::{sub_prompt}"
reformat_prompt="{sub_prompt}",
shared_attributes=True,
require_predefined_shares=True,
create_subclass=False,
preserve_shares=True,
persistent_history_file=None,
):
"""Set up the class decorator
submenu (Cmd): Instance of something cmd.Cmd-like
command (str): The command the user types to access the SubMenu instance
aliases (iterable): More commands that will behave like "command"
reformat_prompt (str): Format str or None to disable
if it's a string, it should contain one or more of:
{super_prompt}: The current cmd's prompt
{command}: The command in the current cmd with which it was called
{sub_prompt}: The subordinate cmd's original prompt
the default is "{super_prompt}{command} {sub_prompt}"
shared_attributes (dict): dict of the form {'subordinate_attr': 'parent_attr'}
the attributes are copied to the submenu at the last moment; the submenu's
attributes are backed up before this and restored afterward
require_predefined_shares: The shared attributes above must be independently
defined in the subordinate Cmd (default: True)
create_subclass: put the modifications in a subclass rather than modifying
the existing class (default: False)
:rtype: object
"""
self.submenu = submenu
self.command = command
self.aliases = aliases
if persistent_history_file:
self.persistent_history_file = os.path.expanduser(persistent_history_file)
else:
self.persistent_history_file = None
if reformat_prompt is not None and not isinstance(reformat_prompt, str):
raise ValueError("reformat_prompt should be either a format string or None")
self.reformat_prompt = reformat_prompt
self.shared_attributes = {} if shared_attributes is None else shared_attributes
if require_predefined_shares:
for attr in self.shared_attributes.keys():
if not hasattr(submenu, attr):
raise AttributeError(
"The shared attribute '{attr}' is not defined in {cmd}. Either define {attr} "
"in {cmd} or set require_predefined_shares=False.".format(
cmd=submenu.__class__.__name__, attr=attr
)
)
self.create_subclass = create_subclass
self.preserve_shares = preserve_shares
@with_category(MNTHG)
def _get_original_attributes(self):
return {
attr: getattr(self.submenu, attr, AddSubmenu._Nonexistent)
for attr in self.shared_attributes.keys()
}
@with_category(MNTHG)
def _copy_in_shared_attrs(self, parent_cmd):
for sub_attr, par_attr in self.shared_attributes.items():
setattr(self.submenu, sub_attr, getattr(parent_cmd, par_attr))
@with_category(MNTHG)
def _copy_out_shared_attrs(self, parent_cmd, original_attributes):
if self.preserve_shares:
for sub_attr, par_attr in self.shared_attributes.items():
setattr(parent_cmd, par_attr, getattr(self.submenu, sub_attr))
else:
for attr, value in original_attributes.items():
if attr is not AddSubmenu._Nonexistent:
setattr(self.submenu, attr, value)
else:
delattr(self.submenu, attr)
@with_category(MNTHG)
def __call__(self, cmd_obj):
"""Creates a subclass of Cmd wherein the given submenu can be accessed via the given command"""
@with_category(MNTHG)
def enter_submenu(parent_cmd, statement):
"""
This function will be bound to thg_<submenu> and will change the scope of the CLI to that of the
submenu.
"""
submenu = self.submenu
original_attributes = self._get_original_attributes()
history = _pop_readline_history()
if self.persistent_history_file and rl_type != RlType.NONE:
try:
readline.read_history_file(self.persistent_history_file)
except FileNotFoundError:
pass
try:
# copy over any shared attributes
self._copy_in_shared_attrs(parent_cmd)
if statement.args:
# Remove the menu argument and execute the command in the submenu
submenu.onecmd_plus_hooks(statement.args)
else:
if self.reformat_prompt is not None:
prompt = submenu.prompt
submenu.prompt = self.reformat_prompt.format(
super_prompt=parent_cmd.prompt[:-1],
command=self.command,
sub_prompt=prompt,
)
submenu.cmdloop()
if self.reformat_prompt is not None:
# noinspection PyUnboundLocalVariable
self.submenu.prompt = prompt
finally:
# copy back original attributes
self._copy_out_shared_attrs(parent_cmd, original_attributes)
# write submenu history
if self.persistent_history_file and rl_type != RlType.NONE:
readline.write_history_file(self.persistent_history_file)
# reset main app history before exit
_push_readline_history(history)
@with_category(MNTHG)
def complete_submenu(_self, text, line, begidx, endidx):
"""
This function will be bound to complete_<submenu> and will perform the complete commands of the submenu.
"""
submenu = self.submenu
original_attributes = self._get_original_attributes()
try:
# copy over any shared attributes
self._copy_in_shared_attrs(_self)
# Reset the submenu's tab completion parameters
submenu.allow_appended_space = True
submenu.allow_closing_quote = True
submenu.completion_header = ""
submenu.display_matches = []
submenu.matches_delimited = False
submenu.matches_sorted = False
return _complete_from_cmd(submenu, text, line, begidx, endidx)
finally:
# copy back original attributes
self._copy_out_shared_attrs(_self, original_attributes)
# Pass the submenu's tab completion parameters back up to the menu that called complete()
_self.allow_appended_space = submenu.allow_appended_space
_self.allow_closing_quote = submenu.allow_closing_quote
_self.completion_header = submenu.completion_header
_self.display_matches = copy.copy(submenu.display_matches)
_self.matches_delimited = submenu.matches_delimited
_self.matches_sorted = submenu.matches_sorted
original_thg_help = cmd_obj.thg_help
original_complete_help_command = cmd_obj.complete_help_command
@with_category(MNTHGH)
def help_submenu(_self, line):
"""
This function will be bound to help_<submenu> and will call the help commands of the submenu.
"""
tokens = line.split(None, 1)
if tokens and (tokens[0] == self.command or tokens[0] in self.aliases):
self.submenu.thg_help(tokens[1] if len(tokens) == 2 else "")
else:
original_thg_help(_self, line)
@with_category(MNTHG)
def _complete_submenu_help(_self, text, line, begidx, endidx):
"""autocomplete to match help_submenu()'s behavior"""
tokens = line.split(None, 1)
if len(tokens) == 2 and (
not (
not tokens[1].startswith(self.command)
and not any(tokens[1].startswith(alias) for alias in self.aliases)
)
):
return self.submenu.complete_help(
text,
tokens[1],
begidx - line.index(tokens[1]),
endidx - line.index(tokens[1]),
)
else:
return original_complete_help_command(_self, text, line, begidx, endidx)
if self.create_subclass:
class _Cmd(cmd_obj):
thg_help = help_submenu
complete_help = _complete_submenu_help
else:
_Cmd = cmd_obj
_Cmd.thg_help = help_submenu
_Cmd.complete_help = _complete_submenu_help
# Create bindings in the parent command to the submenus commands.
setattr(_Cmd, "thg_" + self.command, enter_submenu)
setattr(_Cmd, "complete_" + self.command, complete_submenu)
# Create additional bindings for aliases
for _alias in self.aliases:
setattr(_Cmd, "thg_" + _alias, enter_submenu)
setattr(_Cmd, "complete_" + _alias, complete_submenu)
return _Cmd
@with_category(MNTHG)
def _pop_readline_history(clear_history: bool = True) -> List[str]:
"""Returns a copy of readline's history and optionally clears it (default)"""
# noinspection PyArgumentList
if rl_type == RlType.NONE:
return []
history = [
readline.get_history_item(i)
for i in range(1, 1 + readline.get_current_history_length())
]
if clear_history:
readline.clear_history()
return history
@with_category(MNTHG)
def _push_readline_history(history, clear_history=True):
"""Restores readline's history and optionally clears it first (default)"""
if rl_type != RlType.NONE:
if clear_history:
readline.clear_history()
for line in history:
readline.add_history(line)
@with_category(MNTHG)
def _complete_from_cmd(cmd_obj, text, line, begidx, endidx):
"""Complete as though the user was typing inside cmd's cmdloop()"""
from itertools import takewhile
command_subcommand_params = line.split(None, 3)
if len(command_subcommand_params) < (3 if text else 2):
n = len(command_subcommand_params[0])
n += sum(1 for _ in takewhile(str.isspace, line[n:]))
return cmd_obj.completenames(text, line[n:], begidx - n, endidx - n)
command, subcommand = command_subcommand_params[:2]
n = len(command) + sum(1 for _ in takewhile(str.isspace, line))
cfun = getattr(cmd_obj, "complete_" + subcommand, cmd_obj.complete)
return cfun(text, line[n:], begidx - n, endidx - n)
|
JavaScript | UTF-8 | 350 | 3.34375 | 3 | [] | no_license | const producto = {
nombre: "Monitor 20 Pulgadas",
precio: 300,
disponible: true
}
// const nombre = producto.nombre;
// console.log(nombre);
// Destructuring
const { nombre } = producto;
console.log(nombre);
// Destructuring con arreglos
const numeros = [10, 20, 30, 40, 50];
const [primero, ...resto] = numeros;
console.log(resto); |
C++ | EUC-JP | 1,081 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
int map[100001];
int is_prime(int x) {
//mapޤäƤ顢֤ͤ
if (map[x]!=-1) {
return map[x];
}
//xprimeʤ1֤
if (x<2) {
map[x] = 0;
return 0;
}
if (x==2||x==3||x==5||x==7||x==11||x==13) {
map[x] = 1;
return 1;
}
if (x%2==0) {
map[x] = 0;
return 0;
}
if (x%3==0) {
map[x] = 0;
return 0;
}
if (x%5==0) {
map[x] = 0;
return 0;
}
if (x%7==0) {
map[x] = 0;
return 0;
}
if (x%11==0) {
map[x] = 0;
return 0;
}
if (x%13==0) {
map[x] = 0;
return 0;
}
for (int i=3;i*i <= x;i++) {
if (x%i == 0) {
map[x] = 0;
return 0;
}
}
map[x] = 1;
return 1;
}
int main(){
int q;
int l,r;
cin >> q;
//mapäɤ
for (int i=0;i<100001;i++) {
map[i] = -1;
}
for (int i=0;i<q;i++) {
cin >> l >> r;
int cnt = 0;
for (int x=r;x>=l;x-=2) {
int y = (x+1)/2;
if (is_prime(y) == 1) {
if (is_prime(x)==1) {
cnt++;
}
}
}
cout << cnt << endl;
}
return 0;
}
|
Java | UTF-8 | 1,989 | 1.804688 | 2 | [] | no_license | package meru.automation.placement.suite.A2_campus.A21_setup;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import app.automation.ui.WebTest;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class T2_UpdateCampusTest extends WebTest {
public T2_UpdateCampusTest() {
super("localhost:8080/i2par/campus");
}
@Test
public void pageTest() {
//********** selectCampusTreeItem **********
webPage.click(".//*[@id='header']/div[1]/span[1]");
webPage.click(".//*[@id='workArea']/div/div[1]/div[2]/div/div/li[2]/ul/li[1]/div/div[1]");
//assertTitle
webPage.assertTextEquals(".//*[@id='contentArea']/div/h1", "CAMPUS");
//********** selectCampus **********
webPage.click(".//*[@id='campusTable']/div[2]/table/tbody/tr");
//assertTitle
webPage.assertAttributeEquals(".//*[@id='CampusForm']/div[1]/div[1]/div[2]/div[2]/input", "disabled", "true");
//********** updateCampus **********
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[1]/div[9]/div[2]/select","1");
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[1]/div[10]/div[2]/select","22");
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[3]/div[2]/div[2]/select","41");
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[3]/div[3]/div[2]/select","51");
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[3]/div[4]/div[2]/select","71");
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[4]/div[2]/div[2]/input","6");
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[4]/div[3]/div[2]/select","93");
webPage.setInput(".//*[@id='CampusForm']/div[1]/div[4]/div[4]/div[2]/select","81");
webPage.click(".//*[@id='campusSubmit']");
//assertTitle
webPage.assertAttributeEquals(".//*[@id='CampusForm']/div[1]/div[1]/div[2]/div[2]/input", "disabled", "true");
webPage.assertAttributeEquals(".//*[@id='CampusForm']/div[1]/div[4]/div[2]/div[2]/input", "value", "6");
}
} |
Python | UTF-8 | 1,989 | 2.75 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
import os, argparse, sys, json, credentials
from Email import Email
from EmailParser import EmailParser
from EmailConverter import EmailConverter
from datetime import datetime
from PGSQLExporter import PGSQLExporter, PGSQLConfiguration
def parseEmailsFromDirectory(directory):
"""
Traverses a directory of zipped files containing emails and extracts the
email messages from them
"""
email_messages = {}
parser = EmailParser()
files = os.listdir(directory)
fullpaths = [os.path.join(directory, fi) for fi in files]
print "Parsing emails...",
for path in fullpaths:
print "\b.",
sys.stdout.flush()
email_messages[path] = parser.parse(path)
print "\nAll messages parsed"
return email_messages
def getDirectoryFromArguments():
"""
Gets the directory argument from the command line
"""
parser = argparse.ArgumentParser()
parser.add_argument('--directory',
help='Directory to traverse for zipped files \
with emails in text format',
required=True)
args = parser.parse_args()
return args.directory
if __name__ == "__main__":
directory = getDirectoryFromArguments()
messages = parseEmailsFromDirectory(directory)
emailConverter = EmailConverter()
configuration = PGSQLConfiguration(credentials.db_host,
credentials.db_username,
credentials.db_password,
credentials.db_database)
exporter = PGSQLExporter(configuration)
for path, messagelist in messages.items():
emails = emailConverter.convertEmailsFromMessages(messagelist)
exporter.export(emails)
for path, messagelist in messages.items():
emails = emailConverter.convertEmailsFromMessages(messagelist)
exporter.addReferences(emails)
exporter.closeConnection()
|
TypeScript | UTF-8 | 158 | 3.3125 | 3 | [] | no_license | function add(n1 : number, n2 : number){
return n1+n2;
}
const number1 = 4;
const number2 = 5;
const result = add(number1, number2);
console.log(result); |
Java | UTF-8 | 1,603 | 2.484375 | 2 | [
"MIT"
] | permissive | package benchmark;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import connection.MyConnectionAdmin;
import messages.MyObjectMessage;
import session.MySession;
import topic.MyTopic;
import utils.Utils;
public class ConsumerThread implements Runnable{
@Override
public void run() {
try{
Context ctx = new InitialContext(Utils.enviroment());
ConnectionFactory cfactory = (ConnectionFactory)ctx.lookup("ConnectionFactory");
Connection connection = cfactory.createConnection();
Session session = connection.createSession(false, MySession.AUTO_ACKNOWLEDGE);
connection.start();
MessageConsumer consumer = session.createConsumer(new MyTopic("a"));
long sum = 0;
consumer.receive();
long lastReceived = System.currentTimeMillis();
for(int i=0; i < Benchmark.MESSAGES - 1; i++){
MyObjectMessage m = (MyObjectMessage) consumer.receive();
try{
//System.out.println(m.getObject().toString());
}catch(Exception e){
e.printStackTrace();
}
long now = System.currentTimeMillis();
sum += now - lastReceived;
}
System.out.println("[" + connection.getClientID() + "] Average time: " + (sum/Benchmark.MESSAGES));
session.close();
System.out.println("Consumer close session");
connection.close();
System.out.println("Consumer close connection");
}catch(Exception e){
e.printStackTrace();
}
}
}
|
C++ | UTF-8 | 1,326 | 2.9375 | 3 | [] | no_license | #include "logger.hpp"
#include <ctime>
#include <sstream>
#include <iomanip>
#include <chrono>
#include <thread>
#include <unistd.h>
namespace
{
const std::string appPath = std::string{"../applications/"};
}
namespace Logger
{
LogHelper::~LogHelper()
{
std::cout << std::endl;
}
std::string getThreadId()
{
std::stringstream ss;
ss << std::hex << "0x" << std::this_thread::get_id();
return ss.str();
}
std::string getCurrentTime()
{
auto in_time_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::stringstream ss;
ss << std::put_time(std::localtime(&in_time_t), "%X");
return ss.str();
}
std::string getApplicationName(std::string filePath)
{
filePath = filePath.erase(0, appPath.size());
if (filePath.find_first_of('/') < std::string::npos)
{
auto fileName = filePath.substr(filePath.find_last_of('/')+1, std::string::npos);
filePath = filePath.erase(filePath.find_first_of('/'), std::string::npos);
filePath.append("::");
filePath.append(fileName);
}
if (std::isdigit(filePath[filePath.size()-1]))
{
filePath.pop_back();
}
return filePath;
}
}
|
Rust | UTF-8 | 2,214 | 3.359375 | 3 | [
"MIT"
] | permissive | //! This module provides an interface for working with the screen. With that I mean that you can get or wirte to the handle of the current screen. stdout.
//! Because crossterm can work with alternate screen, we need a place that holds the handle to the current screen so we can write to that screen.
use super::super::shared::functions;
use super::*;
use std::any::Any;
use std::fmt::Display;
use std::io::{self, Write};
#[cfg(target_os = "windows")]
use winapi::um::winnt::HANDLE;
/// Struct that stores an specific platform implementation for screen related actions.
pub struct ScreenManager {
screen_manager: Box<IScreenManager>,
}
impl ScreenManager {
/// Create new screen manager instance whereon screen related actions can be performed.
pub fn new() -> ScreenManager {
#[cfg(target_os = "windows")]
let screen_manager = functions::get_module::<Box<IScreenManager>>(
Box::from(WinApiScreenManager::new()),
Box::from(AnsiScreenManager::new()),
).unwrap();
#[cfg(not(target_os = "windows"))]
let screen_manager = Box::from(AnsiScreenManager::new()) as Box<IScreenManager>;
ScreenManager {
screen_manager: screen_manager,
}
}
/// Toggle a boolean to whether alternate screen is on or of.
pub fn toggle_is_alternate_screen(&mut self, is_alternate_screen: bool) {
self.screen_manager
.toggle_is_alternate_screen(is_alternate_screen);
}
/// Write an ANSI code as String.
pub fn write_string(&mut self, string: String) -> io::Result<usize> {
self.screen_manager.write_string(string)
}
/// Write an ANSI code as &str
pub fn write_str(&mut self, string: &str) -> io::Result<usize>
{
self.screen_manager.write_str(string)
}
/// Can be used to get an specific implementation used for the current platform.
pub fn as_any(&mut self) -> &mut Any {
self.screen_manager.as_any()
}
}
impl Write for ScreenManager {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.screen_manager.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.screen_manager.flush()
}
}
|
Shell | UTF-8 | 1,975 | 3.875 | 4 | [] | no_license | #!/bin/bash
# Define react-tools director
REACT_TOOLS_DIR="$HOME/devtools/react-tools"
echo "React Tools directory:"
echo $REACT_TOOLS_DIR
# Determine project settings and features
echo "Project name (no spaces):"
read projectname
echo "Is this project a Single Page Application? (y/N):"
read spa
echo "Will you be accessing external APIs? (y/N):"
read apiaccess
echo "Will you be using Redux? (y/N):"
read redux
echo "Will you be using styled-components? (y/N):"
read styled
# Setup project directory and base React boilerplate files
echo "Setup project files"
npx create-react-app $projectname &&
cd $projectname
mkdir src/components
PROJECT_DIR=$(pwd)
echo "Project directory:"
echo $PROJECT_DIR
echo "Copying custom favicon"
cp $REACT_TOOLS_DIR/templates/public/favicon.ico $PROJECT_DIR/public/
if [ $spa = 'y' ]; then
echo "Installing react-router-dom"
yarn add react-router-dom
mkdir $PROJECT_DIR/src/routes
touch $PROJECT_DIR/src/routes/index.js
mkdir $PROJECT_DIR/src/app
touch $PROJECT_DIR/src/app/index.js
echo "Created routes and app directories"
fi
if [ $apiaccess = 'y' ]; then
echo "Installing axios"
yarn add axios
fi
if [ $redux = 'y' ]; then
echo "Installing Redux components"
yarn add redux redux-thunk react-redux redux-logger &&
mkdir $PROJECT_DIR/src/config && touch $PROJECT_DIR/src/config/store.js &&
mkdir $PROJECT_DIR/src/actions $PROJECT_DIR/src/reducers && touch $PROJECT_DIR/src/reducers/index.js
echo "Created store, actions, reducers directories"
fi
if [ $styled = 'y' ]; then
echo "Installing styled-components"
yarn add styled-components styled-normalize
echo "Copying custom design components"
cp -a $REACT_TOOLS_DIR/templates/components/DesignComponents $PROJECT_DIR/src/components/
echo "Copying custom shared components"
cp -a $REACT_TOOLS_DIR/templates/components/SharedComponents $PROJECT_DIR/src/components/
fi
echo "List project directory contents"
ls $PROJECT_DIR
echo "Setup complete"
|
Python | UTF-8 | 2,562 | 2.859375 | 3 | [] | no_license | from sklearn.linear_model import LinearRegression
class Node:
def __init__(self,id):
self.sensor_id=id;
self.measurement_list=[]
def addMeasurement(self,temp,light,humidity):
measurement=[]
measurement.append(temp)
measurement.append(light)
measurement.append(humidity)
self.measurement_list.append(measurement)
def clear(self):
self.measurement_list=[]
def addMeasurementToNode(nodes,node,temp,light,humidity):
if node not in nodes:
newNode=Node(node)
newNode.addMeasurement(temp,light,humidity)
nodes[newNode.sensor_id]=newNode
else:
nodes[node].addMeasurement(temp,light,humidity)
return nodes
def findNodeCoefficients(node):
node_coefficients=[]
node_measurements=node.measurement_list
lag_one=[]
lag_two=[]
lag_three=[]
lag_four=[]
lag_five=[]
real=[]
for i in range(15,len(node_measurements)):
lag_one.append([node_measurements[i-1][0],node_measurements[i-6][0],node_measurements[i-11][0]])
lag_two.append([node_measurements[i-2][0],node_measurements[i-7][0],node_measurements[i-12][0]])
lag_three.append([node_measurements[i-3][0],node_measurements[i-8][0],node_measurements[i-13][0]])
lag_four.append([node_measurements[i-4][0],node_measurements[i-9][0],node_measurements[i-14][0]])
lag_five.appen([node_measurements[i-5][0],node_measurements[i-10][0],node_measurements[i-15][0]])
real.append(node_measurements[i][0])
lag_one_LM=LinearRegression()
lag_one_LM.fit(lag_one,real)
one_coeff=lag_one_LM.coef_.tolist()
one_coeff.append(lag_one_LM.intercept_)
lag_two_LM=LinearRegression()
lag_two_LM.fit(lag_two,real)
two_coeff=lag_two_LM.coef_.tolist()
two_coeff.append(lag_two_LM.intercept_)
lag_three_LM=LinearRegression()
lag_three_LM.fit(lag_three,real)
three_coeff=lag_three_LM.coef_.tolist()
three_coeff.append(lag_three_LM.intercept_)
lag_four_LM=LinearRegression()
lag_four_LM.fit(lag_four,real)
four_coeff=lag_four_LM.coef_.tolist()
four_coeff.append(lag_four_LM.intercept_)
lag_five_LM=LinearRegression()
lag_five_LM.fit(lag_five,real)
five_coeff=lag_five_LM.coef_.tolist()
five_coeff.append(lag_five_LM.intercept_)
node_coefficients.append(one_coeff)
node_coefficients.append(two_coeff)
node_coefficients.append(three_coeff)
node_coefficients.append(four_coeff)
node_coefficients.append(five_coeff)
return node_coefficients |
Java | UTF-8 | 2,458 | 3.21875 | 3 | [] | no_license | package task1.robot;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import task1.exception.UnitNullException;
import task1.unit.Unit;
public final class R2D2 extends Robot implements IRobot {
private final int batteryCharge = 100; // final attribute
private final static String PHRASE = "Beep Bloop Blop Bleep Boop"; // final static attribute
static int FLAMETHROWER_DAMAGE; // static attribute
private final static Logger LOG = Logger.getLogger(R2D2.class.getName());
static {
FLAMETHROWER_DAMAGE = 15; // static block
}
public R2D2() {
super();
this.name = "R2D2";
}
public void chargeBattery() {
if (battery < 100) {
this.battery = batteryCharge;
LOG.log(Level.INFO, "Charging... \nCharging...\nThe battery is fully charged.");
} else {
LOG.log(Level.INFO, "The battery is fully charged.");
}
}
public void talk() {
// static method
LOG.log(Level.INFO, PHRASE);
}
public final void useFlamethrower(Unit enemyUnit) {
// final method
try {
if (enemyUnit == null) {
throw new UnitNullException();
}
if (enemyUnit.getHealth() > 0) {
enemyUnit.setHealth(enemyUnit.getHealth() - FLAMETHROWER_DAMAGE);
this.fuel -= 25;
this.battery -= 25;
LOG.log(Level.INFO, "R2D2 uses flamethrower and does " + FLAMETHROWER_DAMAGE
+ " damage to the enemy number: " + enemyUnit.getUnitId());
if (enemyUnit.getHealth() <= 0) {
LOG.log(Level.WARNING, "An enemy has been defeated!");
enemyUnit.setHealth(0);
enemyUnit.setAlive(false);
}
LOG.log(Level.INFO, "The health of the enemy unit number " + enemyUnit.getUnitId() + " now is: "
+ enemyUnit.getHealth());
} else {
LOG.log(Level.INFO, "The enemy unit " + enemyUnit.getUnitId() + " is dead so you can't attack it.");
}
} catch (UnitNullException e) {
LOG.log(Level.INFO, e.getMessage());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Objects.hash(batteryCharge);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
R2D2 other = (R2D2) obj;
return batteryCharge == other.batteryCharge;
}
@Override
public String toString() {
return "R2D2 [name=" + name + ", battery=" + battery + ", fuel=" + fuel + "]";
}
}
|
Java | UTF-8 | 1,292 | 2.6875 | 3 | [] | no_license | package com.util.cache;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Assert;
import org.junit.Test;
public class TestRefCountCache {
private static int maxHandles = 20000;
private static int threadNum = 1000;
private static int cacheNum = 30000;
private static AtomicInteger count = new AtomicInteger(0);
private RefCountCacher<Integer, AtomicBoolean> cacher =
new RefCountCacher<Integer, AtomicBoolean>(
new TestOptions<Integer, AtomicBoolean>(maxHandles));
@Test
public void test() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(threadNum);
for (int i = 0; i < threadNum; i++) {
service.execute(new Do());
}
while(count.intValue() != cacheNum*threadNum) {
Thread.sleep(100);
}
Assert.assertTrue(0 == cacher.count());
}
class Do implements Runnable {
public void run() {
Random rand = new Random();
for (int i = 0; i < cacheNum; i++) {
int c = rand.nextInt(cacheNum);
Assert.assertTrue(cacher.get(c).get());
Thread.yield();
cacher.release(c);
count.incrementAndGet();
}
}
}
}
|
JavaScript | UTF-8 | 84 | 3.109375 | 3 | [] | no_license | function multiply (a,b){
var sum = a * b
console.log(sum)
}
multiply( 5, 5)
|
Java | UHC | 405 | 3.46875 | 3 | [] | no_license | public class Ex04
{
public static void main(String[] args)
{
AA aa = new AA();
aa.doA();
AA.doA();
System.out.println("");
AA.bb.bbb();
}
}
class AA
{
public static BB bb = new BB();
public static void doA()
{
System.out.println("static Լ Դϴ.");
}
}
class BB
{
public static void bbb()
{
System.out.println("bbb Լ : ");
}
} |
Markdown | UTF-8 | 2,904 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | In the previous section, you created a Knative `Service`. Run the following
command to verify the `Service` is available:
```execute-1
watch kn service describe helloworld-go
```
You will eventually see output similar to the following once your `Service` becomes
available:
```
Name: helloworld-go
Namespace: deploy-your-first-application-using-knative-w01-s001
Age: 19m
URL: http://helloworld-go.deploy-your-first-application-using-knative-w01-s001.example.com
Revisions:
100% @latest (helloworld-go-52ztg) [1] (19m)
Image: gcr.io/knative-samples/helloworld-go (at 5ea96b)
Conditions:
OK TYPE AGE REASON
++ Ready 19m
++ ConfigurationsReady 19m
++ RoutesReady 19m
```
The output above shows that a `Service` is created with a `Route`, which is the
value of the `URL` property. You can confirm this `Route` was created with your `Service`
by running the following command:
```execute-2
kn route list
```
The command output will show the same `URL` as the `Service` will have.
Under the `URL` property of the output from `kn service describe`, you will see a `Revisions`
property that shows all the `Revisions` this `Service` uses. Since this `Service` has never been
updated because it was just created, it only has one `Revision`.
You can confirm that only one `Revision` exists by running the following command:
```execute-2
kn revision list
```
You will notice from the output of `kn revision list` some important properties of this `Revision`, such
as the `SERVICE` property denoting that this revision is associated with the `helloworld-go` `Service`.
There is also a column called `TRAFFIC` that specifies what percentage of incoming requests to the
`helloworld-go` `Service` will be routed to this `Revision`. In this case, `100%` of requests will go to
this `Revision`.
The last resource created by the `helloworld-go` `Service` is a `Configuration`. Go ahead and run the following
command to confirm the `Configuration` was created:
```execute-2
kubectl get configuration
```
The output will show the name of the `Configuration` is the same as the name of the `Service`. The `LATESTCREATED` and
`LATESTREADY` columns denote which `Revision` is the most recent for the `Service` and also which `Revision` is the
most recent that is available. In this case, for both, the only `Revision` available for `helloworld-go` is both the
most recent and available to handle requests.
In the next section, you will send requests to `helloworld-go` to see some of the features of Knative `Serving` in
action.
Stop the watch on the `Service` in your first terminal once you have gotten a chance to see the output from `kn service describe`:
```execute-1
<ctrl+c>
```
Clear your terminals:
```execute-1
clear
```
```execute-2
clear
```
Click **Use Knative Service** to continue. |
C++ | UTF-8 | 319 | 2.625 | 3 | [] | no_license | #pragma once
#ifndef __ROUNDING_H__
#define __ROUNDING_H__
#include <stdint.h>
#include <math.h>
class Rounding
{
public:
static double nearest(double value, size_t precision);
static double up(double value, size_t precision);
static double down(double value, size_t precision);
};
#endif // __ROUNDING_H__ |
C# | UTF-8 | 1,908 | 2.859375 | 3 | [] | no_license | using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace WebApplication1.helper
{
public class CustomHelper
{
public static string Bibli()
{
try
{
return MakeList(GetFiles());
}
catch {
return "<p>Votre bibliotheque est probablement vide... Vous devez d'habord enregistrer un pdf depuis votre application avant de pouvoir le voir ici.</p>";
}
}
public static string MakeList(List<string> value)
{
string output = "<ul class=\"list-group list-group-flush\">";
value.ForEach(delegate (string text)
{
output += "<li class=\"list-group-item\" onclick=\"ViewFile(this)\" data-value=\"" + text+"\">" + string.Join("\\", text.Split(new string[] { "\\" }, StringSplitOptions.None).Skip(1)) + "</li>";
});
return output + "</ul>";
}
public static List<string> GetFiles(string id = null){
if(id==null) id = HttpContext.Current.Session["user"].ToString();
DirectoryInfo d = new DirectoryInfo(@"E:\TFE\WebApp\Data\"); //root folder for datas
//DirectoryInfo d = new DirectoryInfo(@"D:\jsp\tablature"); //root folder for datas
DirectoryInfo[] Ids = d.GetDirectories();
if (!Ids.Select(x => x.Name).ToList().Contains(id))
{
throw new FileNotFoundException();
}
FileInfo[] Files = Ids.Where(x => x.Name == id.ToString()).First().GetFiles("*.pdf"); // Getting pdf files
List<string> str = new List<string>();
foreach (FileInfo file in Files)
{
str.Add(id + @"\" + file.Name);
}
return str;
}
}
} |
Java | UTF-8 | 509 | 1.890625 | 2 | [] | no_license | package com.templateproject.constants;
public final class ErrorCodeConstants {
public static final String SCHEMA_NOT_VALID = "SCHEMA_NOT_VALID";
public static final String NOT_FOUND = "NOT_FOUND";
public static final String INTERNAL_ERROR = "INTERNAL_ERROR";
public static final String NOT_VALID = "NOT_VALID";
public static final String BV_ACCOUNT_AlREADY_EXISTS = "BV_1001";
public static final String BV_ACCOUNT_OVERDRAWN = "BV_1002";
private ErrorCodeConstants() {
}
}
|
C++ | UTF-8 | 2,357 | 2.890625 | 3 | [] | no_license | /**********************************************************************
* blaRAY -- photon mapper/raytracer
* (C) 2008 by Tomasz bla Fortuna <bla@thera.be>, <bla@af.gliwice.pl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* See Docs/LICENSE
*********************/
#ifndef _TYPES_H_
#define _TYPES_H_
#include <iostream>
#include "General/Debug.hh"
/** Original template
* Copyright (c) 2006
* Michal 'Sektor' Malecki
* Pawel Sikora
* Distributed under the Boost Software License, Version 1.0.
* ( See at http://www.boost.org/LICENSE_1_0.txt )
*
* template<class T>
* struct explicit_t
* {
* private:
* T value;
* template< class V > explicit_t( V t );
* public:
* operator T & () { return value; }
* explicit_t( const T& c ): value( c ) { }
* };
**/
/**
* \author Michal 'Sektor' Malecki
* \author Pawel Sikora
* \author Tomasz bla Fortuna
* \date 2006, 2008
*
* \brief Kills implicit conversions.
*
* Original license:
* Distributed under the Boost Software License, Version 1.0.
* ( See at http://www.boost.org/LICENSE_1_0.txt )
*
* Template allows us to kill any implicit conversions
* of built-in types. Especially int, short, unsigned *
* and double. Modifications allows to initialize arrays
* in classes and allows us creating T types from const T types.
*
*/
template<typename T>
struct explicit_t {
private:
/** Private constructor from any other type */
template<typename V> explicit_t(const V &t);
/** Real hidden in template value */
T value;
public:
/**@{ Constructor from allowed types */
explicit_t(const T &c) : value(c) {}
explicit_t() {};
/*@}*/
/** Returns reference */
operator T& () { return value; }
/** In case we have const this pointer
* return const reference */
operator const T& () const { return value; }
};
#if (DEBUG == 1)
# define e_t(t) explicit_t<t>
#else
# define e_t(t) t
#endif
/**@{ Basic types (not const!) */
typedef e_t(int) Int;
typedef e_t(double) Double;
typedef e_t(char) Char;
typedef e_t(bool) Bool;
typedef e_t(short) Short;
typedef e_t(unsigned int) UInt;
typedef e_t(unsigned short) UShort;
typedef e_t(unsigned char) UChar;
typedef e_t(double) Double;
typedef void Void;
/*@}*/
#endif
|
C | UTF-8 | 4,159 | 3.84375 | 4 | [] | no_license |
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
//将标准输出重定向到文件中
int main()
{
// //传统的方法:
// //1. 先关闭标准输出的文件描述符(标准输出的文件描述符为1)
// //2. 再打开一个文件(此时该文件的文件描述符从最小值开始分配),所以必定为1
// //3. 因为FILE结构体中封装了文件描述符,所以结构体变量:标准输出stdout中封装了文件描述符1
// //4. 利用printf输出时,其实是往标准输出stdout中输出,即最终找的是文件描述符1
// //5. 在关闭文件描述符1之后,printf还是往stdout中输出,找的还是文件描述符1
// // 不过此时,文件描述符1处对应的文件指针已经变成新打开的普通文件的指针
// // 所以,printf在输出时,其实是往新打开的文件中输出
// close(1);
// //此时fd必为1
// int fd = open("log.txt",O_CREAT|O_RDWR);
// if(fd < 0)//调用open时,如果文件已经存在,则会调用失败
// {
// perror("open");
// return 1;
// }
//
// printf("%d\n",fd);
//
//
// int i = 10;
// while(i--)
// {
// printf("hello world\n");
// fflush(stdout);
// }
// close(fd);
// //如果在打开新的文件描述符之后,在关闭标准输出,此时要将标准输出重定向到新的文件
// //就需要先关闭标准输出,再关闭新的文件描述符,在打开新的文件描述符,这样过于麻烦
// //而且在新文件第一次创建之后就已经存在了,如果再次打开的话会打开失败
// int fd = open("log.txt",O_CREAT|O_RDWR);
// close(1);
// close(fd);
// int fd1 = open("log.txt",O_CREAT|O_RDWR);
// if(fd1 < 0)
// {
// perror("open");
// return 1;
// }
// printf("%d\n",fd1);
// printf("bcsj\n");
// fflush(stdout);
//
//使用dup函数实现文件描述符的重定向:适用于在打开新的文件之后在关闭标准输出的文件描述符
//1. 首先打开一个新的文件
//2. 再关闭标准输出的文件描述符
//3. 将标准输出重定向到文件中,利用dup函数实现文件描述符的重定向
// 此时dup会为旧文件描述符分配一个未使用的最小的数组下标(文件描述符)
// 因为标准输出关闭了,所以新的文件描述符一定是1
// 即将旧的文件描述符对应的文件指针赋值一份到新的文件描述符中
// 此时,就完成了重定向,即将新的文件描述符重定向到打开的文件中,即将标准输出重定向到文件中
int fd = open("log.txt",O_CREAT|O_RDWR);
if(fd < 0)
{
perror("open error");
return 1;
}
close(1);
//注意:新文件描述符的内容是旧文件描述符内容的一份拷贝
int new_fd = dup(fd);
if(new_fd < 0)
{
perror("dup");
return 2;
}
close(fd);//因为文件已经重定向了,所以旧的文件描述符也就没有用了
//如果该文件描述符不关闭,也可对该文件进行读写
printf("new_fd:%d\n",new_fd);
write(fd,"hello",strlen("hello"));
int i = 10;
while(i--)
{
//printf重定向到普通文件,普通文件是全缓冲,
//即printf输出的数据会先保存在stdout结构体的缓冲区中
//等待程序结束才会刷新缓冲区,输出到文件中
//但是在本程序中,因为在程序结束之前已经close了文件描述符
//即在程序结束后找不到文件了,所以在close之前将缓冲区中的内容刷新到文件中
//所以要调用fflush来刷新缓冲区
//
//如果在程序结束之前没有close文件,也可以不用fflush刷新,程序结束后会自动刷新到缓冲区中
//但是为防止其他特殊情况,还是刷新一下比较好
printf("hello world\n");//printf重定向到普通文件,
fflush(stdout);
}
close(new_fd);
return 0;
}
|
Ruby | UTF-8 | 958 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer (data)
final = {}
data.each do |attribute, stat|
stat.each do |sub_attribute, pigeon|
pigeon.each do |name|
final[name] = {:color => [], :gender => [], :lives => []}
end
end
end
data.each do |attribute, stat|
if attribute == :color
stat.each do |sub_attribute, pigeon|
pigeon.each do |name|
final[name][:color] << sub_attribute.to_s
end
end
end
end
data.each do |attribute, stat|
if attribute == :gender
stat.each do |sub_attribute, pigeon|
pigeon.each do |name|
final[name][:gender] << sub_attribute.to_s
end
end
end
end
data.each do |attribute, stat|
if attribute == :lives
stat.each do |sub_attribute, pigeon|
pigeon.each do |name|
final[name][:lives] << sub_attribute.to_s
end
end
end
end
return final
end |
Rust | UTF-8 | 2,626 | 2.671875 | 3 | [] | no_license | use crate::core::scene::{Scene, SceneResult};
use crate::render::ui::{Gui, GuiContext};
use crate::resources::Resources;
use crate::save::get_wave_record;
use crate::scene::MainScene;
use bitflags::_core::time::Duration;
use glfw::{Key, WindowEvent};
use hecs::World;
#[derive(Default)]
pub struct WaveSelectionScene {
selected: usize,
possible: Vec<usize>,
start: bool,
}
impl WaveSelectionScene {
pub fn new(resources: &Resources) -> Self {
let mut possible: Vec<usize> = vec![1];
let record = get_wave_record(resources);
if record >= 5 {
let available = record / 5;
for i in 0..available {
possible.push(5 * (i + 1));
}
}
Self {
selected: 0,
possible,
start: false,
}
}
}
impl Scene<WindowEvent> for WaveSelectionScene {
fn update(
&mut self,
_dt: Duration,
_world: &mut World,
_resources: &Resources,
) -> SceneResult<WindowEvent> {
if self.start {
SceneResult::ReplaceScene(Box::new(MainScene::new(true, self.possible[self.selected])))
} else {
SceneResult::Noop
}
}
fn prepare_gui(
&mut self,
_dt: Duration,
_world: &mut World,
_resources: &Resources,
gui_context: &GuiContext,
) -> Option<Gui> {
let mut gui = gui_context.new_frame();
let center = gui_context.window_dim.to_vec2() / 2.0 - 100.0 * glam::Vec2::unit_y();
gui.centered_label(center, "Choose starting wave".to_string());
gui.centered_label(
center + 20.0 * glam::Vec2::unit_y(),
"Left/Right arrow to change, Enter to select".to_string(),
);
gui.centered_label(
center + 60.0 * glam::Vec2::unit_y(),
self.possible[self.selected].to_string(),
);
Some(gui)
}
fn process_input(&mut self, _world: &mut World, input: WindowEvent, _resources: &Resources) {
match input {
WindowEvent::Key(Key::Left, _, glfw::Action::Release, _) => {
if self.selected > 0 {
self.selected -= 1;
}
}
WindowEvent::Key(Key::Right, _, glfw::Action::Release, _) => {
if self.selected < self.possible.len() - 1 {
self.selected += 1;
}
}
WindowEvent::Key(Key::Enter, _, glfw::Action::Release, _) => {
self.start = true;
}
_ => (),
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.