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 | 1,353 | 2.25 | 2 | [] | no_license | package com.spring_gradle.springgradle.entity;
import java.time.LocalDate;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="tbl_hanRiverInfo")
public class HanRiver {
@Id
@GeneratedValue
private int no_;
private int type;
private String name;
private float temperature;
private LocalDateTime time;
private LocalDateTime created;
public int getNo_() {
return no_;
}
public void setNo_(int no_) {
this.no_ = no_;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getTemperature() {
return temperature;
}
public void setTemperature(float temperature) {
this.temperature = temperature;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public LocalDateTime getCreated() {
return created;
}
public void setCreated(LocalDateTime created) {
this.created = created;
}
}
|
Python | UTF-8 | 390 | 3.65625 | 4 | [] | no_license | #example code for slicing with positive indexing and negative indexing
#careful: You can also slice with negative indices.
#The same basic rule of starting from the start index and stopping one before
#the end index applies
s = "testing slicing 101"
print(len(s))
print(s[4:10])
print(s[2:10])
print(s[4:-7])
print(s[-7:-1])
print(s[-6:len(s)])
print(s[:5])
print(s[5:])
print(s[:])
|
Python | UTF-8 | 4,035 | 2.9375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 18 21:03:22 2021
@author: Administrator
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 18 18:16:49 2021
获取交易对的数据
@author: ljn
"""
import pandas as pd
import datetime
import os
import ccxt
import time
pd.set_option('expand_frame_repr', False) # 当列太多时不换行
pd.set_option('display.max_rows', 5000) # 最多显示数据的行数
time_interval = '1d' # K线的时间周期,其他可以尝试的值:'1m', '5m', '15m', '30m', '1h', '2h', '1d', '1w', '1M', '1y',并不是每个交易所都支持
DATA_LIMIT = 500
OKEX_LIMIT = 200
# =====获取最新数据
def get_history_exchanges_datas(exchange_name, exchange, symbol, start_time, end_time):
"""
循环获取指定交易所数据的方法.
:param exchange_name: 交易所名称.
:param exchange: 交易所对象实例
:param symbol: 请求的symbol: 交易对: BTC/USDT, ETH/USD等。
:param start_time: like 2018-1-1
:param end_time: like 2019-1-1
:return:
"""
print(exchange)
# exit()
#数据存储的位置和名称
current_path = os.getcwd()
file_dir = os.path.join(current_path, exchange_name, symbol.replace('/', ''))
if not os.path.exists(file_dir):
os.makedirs(file_dir)
#时间计算
start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d')
end_time = datetime.datetime.strptime(end_time, '%Y-%m-%d')
start_time_stamp = int(time.mktime(start_time.timetuple())) * 1000
end_time_stamp = int(time.mktime(end_time.timetuple())) * 1000
print(start_time_stamp) # 1529233920000
print(end_time_stamp)
#每次获取的数据个数
limit_count = 500
if exchange_name == 'bitfinex':
limit_count = DATA_LIMIT
elif exchange_name == 'bitmex':
limit_count = DATA_LIMIT
elif exchange_name == 'binance':
limit_count = DATA_LIMIT
elif exchange_name == 'okex':
limit_count = OKEX_LIMIT
else:
limit_count = 200
#循环获取
while True:
try:
print(start_time_stamp)
data = exchange.fetch_ohlcv(symbol=symbol, timeframe=time_interval, since=start_time_stamp, limit=limit_count)
df = pd.DataFrame(data)
df.rename(columns={0: 'open_time', 1: 'open', 2: 'high',
3: 'low', 4: 'close', 5: 'volume'}, inplace=True) # 重命名
start_time_stamp = int(df.iloc[-1]['open_time']) # 获取下一个次请求的时间.
df['candle_begin_time_real'] = pd.to_datetime(df['open_time'], unit='ms') # 整理时间
df['candle_begin_time'] = df['candle_begin_time_real'] + pd.Timedelta(hours=8) # 北京时间
df = df[['candle_begin_time', 'open', 'high', 'low', 'close', 'volume']] # 整理列的顺序
filename = str(start_time_stamp) + '.csv'
save_file_path = os.path.join(file_dir, filename)
print("文件保存路径为:%s" % save_file_path)
# exit()
df.set_index('candle_begin_time', drop=True, inplace=True)
df.to_csv(save_file_path)
if start_time_stamp > end_time_stamp:
print("完成数据的请求.")
break
time.sleep(3)
except Exception as error:
print("运行错误,原因如下:")
print(error)
time.sleep(10)
# =====主函数
if __name__ == '__main__':
# =====设定参数
symbol = 'BTC/USDT' # 抓取的品种。btc/usdt现货交易对。其他币种照例修改即可,例如ETH/USDT,LTC/USDT等
begin_time = '2017-5-1' #开始时间
end_time = '2021-1-1' #结束时间
# =====创建ccxt交易所
name = 'okex'
exchange = ccxt.okex() # okex
#exchange = ccxt.huobipro() # 火币
# exchange = ccxt.binance() # 币安
get_history_exchanges_datas(name, exchange, symbol, begin_time, end_time)
pass
|
C | UTF-8 | 983 | 4.125 | 4 | [] | no_license | //http://www.geeksforgeeks.org/minimum-number-of-squares-whose-sum-equals-to-given-number-n/
#include <stdio.h>
int
min (int a, int b)
{
if (a > b ) return a;
return b;
}
// Returns count of minimum squares that sum to n
int getMinSquares(unsigned int n)
{
// base cases
if (n <= 3)
return n;
// getMinSquares rest of the table using recursive
// formula
int res = n; // Maximum squares required is n (1*1 + 1*1 + ..)
// Go through all smaller numbers
// to recursively find minimum
for (int x = 1; x <= n; x++)
{
int temp = x*x;
if (temp > n)
break;
else {
printf("n %d res %d, temp %d\n", n, res, temp);
getchar();
res = min(res, 1+getMinSquares(n - temp));
printf("n2 %d res %d, temp %d\n", n, res, temp);
}
}
return res;
}
// Driver program
int main()
{
printf("Min SQ RT %d \n", getMinSquares(36));
return 0;
}
|
Java | UTF-8 | 8,579 | 2.1875 | 2 | [] | no_license | package psb.com.kidpaint.utils;
/*
* Created by AMiR Ehsan on 7/22/2017.
*/
import android.content.Context;
import android.content.SharedPreferences;
import psb.com.kidpaint.webApi.register.registerUserInfo.model.UserInfo;
public class UserProfile {
private static Context context;
private static String KEY_USER = "KEY_USER";
private static String KEY_PHONE_NUMBER = "KEY_PHONE_NUMBER";
private static String KEY_FIRST_NAME = "KEY_FIRST_NAME";
private static String KEY_LAST_NAME = "KEY_LAST_NAME";
private static String KEY_IMG_URL = "KEY_IMG_URL";
private static String KEY_FCM = "KEY_FCM";
private static String KEY_JWT = "KEY_JWT";
private static String KEY_SEX = "KEY_SEX";
private static String KEY_BRITH_DAY = "KEY_BRITH_DAY";
private static String KEY_USER_RANK = "KEY_USER_RANK";
private static String KEY_USER_SCORE = "KEY_USER_SCORE";
private static String KEY_USER_LEVEL = "KEY_USER_LEVEL";
private static String KEY_SHOW_FIRST_SCORE_PACKAGE_IN_PAINT_ACTIVITY = "KEY_SHOW_FIRST_SCORE_PACKAGE_IN_PAINT_ACTIVITY";
///////////////////////////////////////////////////////////////////////////
// getter
///////////////////////////////////////////////////////////////////////////
public UserProfile(Context context){
this.context = context;
}
public void set_KEY_USER_INFO(UserInfo userInfo) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_FIRST_NAME, userInfo.getFirstName());
editor.putString(KEY_LAST_NAME, userInfo.getLastName());
editor.putString(KEY_PHONE_NUMBER, userInfo.getPhoneNumber());
editor.putString(KEY_IMG_URL, userInfo.getImageUrl());
editor.putString(KEY_BRITH_DAY, userInfo.getBirthDay());
editor.putBoolean(KEY_SEX, userInfo.getMale());
editor.putInt(KEY_USER_RANK, userInfo.getRank());
editor.putInt(KEY_USER_SCORE, userInfo.getScore());
editor.putInt(KEY_USER_LEVEL, userInfo.getLevel());
editor.apply();
}
public void set_KEY_PHONE_NUMBER(String value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_PHONE_NUMBER, value);
editor.apply();
}
public void set_KEY_SHOW_FIRST_SCORE_PACKAGE_IN_PAINT_ACTIVITY(boolean value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(KEY_SHOW_FIRST_SCORE_PACKAGE_IN_PAINT_ACTIVITY, value);
editor.apply();
}
public void set_KEY_KEY_FIRST_NAME(String value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_FIRST_NAME, value);
editor.apply();
}
public void set_KEY_LAST_NAME(String value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_LAST_NAME, value);
editor.apply();
}
public void set_KEY_IMG_URL(String value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_IMG_URL, value);
editor.apply();
}
public void set_KEY_FCM(String value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_FCM, value);
editor.apply();
}
public void set_KEY_BIRTH_DAY(String value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_BRITH_DAY, value);
editor.apply();
editor.commit();
}
public void set_KEY_JWT(String value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_JWT, value);
editor.apply();
}
public void set_KEY_SCORE(int value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(KEY_USER_SCORE, value);
editor.apply();
}
public void set_KEY_LEVEL(int value) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(KEY_USER_LEVEL, value);
editor.apply();
}
public void REMOVE_KEY_USER_INFO() {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove(KEY_FIRST_NAME);
editor.remove(KEY_LAST_NAME);
editor.remove(KEY_PHONE_NUMBER);
editor.remove(KEY_IMG_URL);
editor.remove(KEY_JWT);
editor.remove(KEY_FCM);
editor.remove(KEY_BRITH_DAY);
editor.remove(KEY_SEX);
editor.remove(KEY_USER_SCORE);
editor.remove(KEY_USER_LEVEL);
editor.remove(KEY_SHOW_FIRST_SCORE_PACKAGE_IN_PAINT_ACTIVITY);
editor.apply();
}
///////////////////////////////////////////////////////////////////////////
// setter
///////////////////////////////////////////////////////////////////////////
public String get_KEY_PHONE_NUMBER(String defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getString(KEY_PHONE_NUMBER, defeult);
}
public String get_KEY_FIRST_NAME(String defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getString(KEY_FIRST_NAME, defeult);
}
public String get_KEY_LAST_NAME(String defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getString(KEY_LAST_NAME, defeult);
}
public String get_KEY_IMG_URL(String defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getString(KEY_IMG_URL, defeult);
}
public String get_KEY_FCM(String defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getString(KEY_FCM, defeult);
}
public String get_KEY_JWT(String defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getString(KEY_JWT, defeult);
}
public String get_KEY_BRITH_DAY(String defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getString(KEY_BRITH_DAY, defeult);
}
public boolean get_KEY_SEX(boolean defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getBoolean(KEY_SEX, defeult);
}
public Integer get_KEY_RANK(int defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getInt(KEY_USER_RANK, defeult);
}
public Integer get_KEY_SCORE(int defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getInt(KEY_USER_SCORE, defeult);
}
public Integer get_KEY_LEVEL(int defalt) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getInt(KEY_USER_LEVEL, defalt);
}
public boolean get_KEY_SHOW_FIRST_SCORE_PACKAGE_IN_PAINT_ACTIVITY(boolean defeult) {
SharedPreferences settings = context.getSharedPreferences(KEY_USER, Context.MODE_PRIVATE);
return settings.getBoolean(KEY_SHOW_FIRST_SCORE_PACKAGE_IN_PAINT_ACTIVITY, defeult);
}
} |
Java | UTF-8 | 6,869 | 2.046875 | 2 | [] | no_license | package com.swaaad.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.swaaad.dto.EvaluacionDTO;
import com.swaaad.model.Alumno;
import com.swaaad.model.Docente;
import com.swaaad.model.Evaluacion;
import com.swaaad.model.Usuario;
import com.swaaad.service.EvaluacionService;
import com.swaaad.service.PeriodoService;
import com.swaaad.service.UsuarioService;
@Controller
public class EvaluacionController {
private static final Logger logger = LoggerFactory.getLogger(NotaController.class);
@Autowired
private EvaluacionService objEvaluacionService;
@Autowired
private UsuarioService objUsuarioService;
@Autowired
private PeriodoService objPeriodoService;
@RequestMapping(value="/validarFormula",method=RequestMethod.POST)
public @ResponseBody String validarFormula(@RequestParam("formula") String formula) throws Exception {
EvaDTO eva= null;
String mensaje="";
try {
mensaje = objEvaluacionService.validarFormula(formula);
} catch (Exception e) {
e.getStackTrace();
}
return mensaje;
}
@RequestMapping(value="/generarFormula/{idEvaluacion}",method=RequestMethod.POST)
public @ResponseBody EvaDTO generarFormula(@PathVariable("idEvaluacion") int idEvaluacion) throws Exception {
Evaluacion evaluacion = null;
EvaDTO eva= null;
try {
evaluacion = objEvaluacionService.getEvaluacionById(idEvaluacion);
eva = new EvaDTO(evaluacion.getColorFondo(), evaluacion.getColorTexto(), evaluacion.getNombre());
} catch (Exception e) {
e.getStackTrace();
}
return eva;
}
@RequestMapping(value = "/newEvaluacion", method = RequestMethod.GET)
public ModelAndView newEvaluacion(ModelAndView model, HttpServletRequest request) throws Exception {
HttpSession session = request.getSession(false);
int idCurso = (Integer) session.getAttribute("idCurso");
int idPeriodo = (Integer) session.getAttribute("idPeriodo");
logger.info("newEvaluacion");
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
if (principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
}
Usuario usuario = objUsuarioService.getUsuarioById(Integer.valueOf(userDetails.getUsername()));
Docente docente = usuario.getDocentes().get(0);
String userName = docente.getApellidos() + " ," + docente.getNombre();
model.addObject("user", userName);
Evaluacion evaluacion = new Evaluacion();
evaluacion.setPeriodo(objPeriodoService.getPeriodoById(idPeriodo));
evaluacion.setColorFondo("#ffffff");
evaluacion.setColorTexto("#000000");
model.addObject("listEvaluaciones", objEvaluacionService.getAllEvaluacionesByIdCurso(idCurso));
model.addObject("evaluacion", evaluacion);
model.setViewName("form-evaluacion");
return model;
}
@RequestMapping(value = "/saveEvaluacion", method = RequestMethod.POST)
public ModelAndView saveEvaluacion(@ModelAttribute Evaluacion evaluacion, HttpServletRequest request) throws Exception {
logger.info("saveEvaluacion");
HttpSession session = request.getSession(false);
int idPeriodo = (Integer) session.getAttribute("idPeriodo");
evaluacion.setPeriodo(objPeriodoService.getPeriodoById(idPeriodo));
try {
if (evaluacion.getIdEvaluacion() == 0) {
objEvaluacionService.addEvaluacion(evaluacion);
} else {
objEvaluacionService.updateEvaluacion(evaluacion);
}
} catch (Exception e) {
System.out.println(e);
e.getStackTrace();
}
return new ModelAndView("redirect:/listNota");
}
@RequestMapping(value = "/editEvaluacion", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) throws Exception {
ModelAndView model = new ModelAndView("form-evaluacion");
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
if (principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
}
Usuario usuario = objUsuarioService.getUsuarioById(Integer.valueOf(userDetails.getUsername()));
Docente docente2 = usuario.getDocentes().get(0);
String userName = docente2.getApellidos() + " ," + docente2.getNombre();
model.addObject("user", userName);
HttpSession session = request.getSession(false);
int idCurso = (Integer) session.getAttribute("idCurso");
int idEvaluacion = Integer.parseInt(request.getParameter("id"));
logger.info("editEvaluacion ", idEvaluacion);
Evaluacion evaluacion= null;
try {
evaluacion = objEvaluacionService.getEvaluacionById(idEvaluacion);
} catch (Exception e) {
logger.info("Excepcion en edicion: ", e);
}
model.addObject("listEvaluaciones", objEvaluacionService.getAllEvaluacionesByIdCurso(idCurso));
model.addObject("evaluacion", evaluacion);
return model;
}
}
class EvaDTO {
private String colorFondo;
private String colorTexto;
private String nombre;
public EvaDTO(String colorFondo, String colorTexto, String nombre) {
super();
this.colorFondo = colorFondo;
this.colorTexto = colorTexto;
this.nombre = nombre;
}
public String getColorFondo() {
return colorFondo;
}
public void setColorFondo(String colorFondo) {
this.colorFondo = colorFondo;
}
public String getColorTexto() {
return colorTexto;
}
public void setColorTexto(String colorTexto) {
this.colorTexto = colorTexto;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
} |
C++ | WINDOWS-1251 | 991 | 2.734375 | 3 | [] | no_license | #include<iostream> /// cin/cout
using namespace std;
void main() // , ,
{ //
setlocale(LC_ALL, "Russian");
cout << "\t\t\t\t\tHello \"World\"!\n";
cout << "!\n"" ";
cout << "\n";
cout << endl;
cout << " ";
cout << "C:\\Windows\\System32\\\n";
}
//cout (Console Out) - .
//<< -
/*
----------------------------------------------------------
Escape-
- Slash ( )
\ - Backslash( )
\ -
----------------------------------------------------------
*/ |
Markdown | UTF-8 | 9,662 | 3.34375 | 3 | [] | no_license | # Part.7 Architecture
## CH.25 Layers and Boundaries
Architectural boundaries are everywhere from simple to complex systems. To achieve clean architecture, manifesting boundaries between system components and defining layers between them is important.
In the chapter the author walks through an example of a simple game that has increasingly complex requirements and how that leads to the discovery of potential boundaries that aren't apparent.
Takeaways from this chapter were:
- Even for simple software systems, we can come up with many architectural boundaries if we try hard enough.
- There are inherent trade-offs between the cost of implementing boundaries VS the cost of ignoring them:
* Implementing a boundary later on is costly and risky. Also, Permanently ignoring one where it is needed makes the project costly to maintain.
* Implementing a strict boundary when it could be ignored is a waste in cost and leads to over-engineering.
- So what we do is we weigh the cost of implementing vs ignoring to determine where boundaries should lie.
- Note that this is not a one time decision and as the project evolves, we watch what things are causing friction in the development and maintainability and implement boundaries.
- The goal is to implement the boundary at the point where the cost of implementation is less than the cost of ignoring.
## CH.26 The Main Component
The Main Component exists in every system and is responsible in creating, coordinating, and overseeing other parts of the system. The Main component is the ultimate detail and the lowest-level policy.
The job of the Main component is:
- To create all factories, strategies and other global facilities, then hand over control to the high-level portions of the system.
- To take in framework injected dependencies and distribute them and set them up throughout the system.
## CH.27 Services: Great and Small
The concept of vertical and horizontal layers and independence in service level architecture.
Recently, service-oriented "architectures" and microservices have become popular due to:
- Services seeming to be strongly decoupled from each other (only partially true).
- Services appearing to support independence of development and deployment (only partially true).
### Are Services an Architecture?
In short. No, services do not define the architecture because:
-> The architecture of a system is defined by boundaries that separate high-level policy from low-level detail. Services that simply separate application behaviors are little more than expensive function calls, and are not necessarily architecturally significant. Services are just function calls across processes and platform boundaries.

### Are the Benefits of Services Real?
#### The Decoupling Fallacy
One of the benefits of breaking a system up into services is that services are strongly decoupled from each other.
This is only partially true:
- Separate services are coupled by the structure of the data they pass to each other. If a field is added to the data in one place, all other services that get that data need to be modified
- Services might be using a shared resource (e.g redis) and a same data strucutre. If the schema of the data structure stored in the data store is modified all services that are dependent that data need to be adjusted.
#### The Independence of Development and Deployment Fallacy
The points above also show that independent development and deployment are also only partially true. For example, if services A and B share the database or the data format that is passed, when Service A changes the database schema, then Service B needs to change and the deployment needs to be coordinated.
### The Pitfall of Services by Functional Decomposition
A naive strategy for deciding how to divide a system into services is to divide them by functionality. For example, in a taxi-ordering system, the engineers could create the following microservices:
- Taxi Finder Service which keeps the inventory of all possible rides.
- Taxi Selector Service which selects the best ride for the user.
- Taxi Dispatcher Service which once selected, orders the ride.
The problem with type of decomposition is that it is a "purely horizontal" division and completely ignores the vertical layers.
The problem with this division is that a simple change of features would require a change throughout the whole system. For the example above, if the company now wanted the business to offer delivery of kities, the engineering team would be forced to modify every single microservice. Even worse, they face the risk of breaking the people delivery part of the business while working on the parcel delivery part.

### Objects To The Rescue
A solution to the problem is to divide services by vertical layers (Use Cases or groups of Use Cases) and have each service contain contain all functional concern it needs (all the horizontal layers).
The horizontal layers within each service are separated by architectural boundaries and follow the dependency rule.
Note that doing this requires the code to be divided vertically very early on. If you are in a situation where you already have microservices divided by functional decomposition, transforming the system to microservices by vertical decomposition might be impossibly expensive to do. However, not all hope is lost. If you already are in a situation where your system has microservices divided by functional decomposition, there are still things you can do to make it easier to change in the light of cross-cutting changes.


## Ch.28 The Test Boundary
Tests are part of the architecture of a system. The good news is that from the point of view of the architecture, unit tests, integration tests, behaviour tests etc, all look the same. They all are detailed, low-level components that always depend inward to the code being tested. In a way, tests are the outermost circle of the clean architecture.
### Design for Testability
Testing should be part of the considerations when designing a system. Not considering tests as part of the design is a mistake that leads to fragile tests that are expensive to maintain and often end up getting discarded.
Fragile test problems occur when tests depend on volatile things (like the GUI) to test stable things. For example, writing GUI driven tests to test business rules can cause many use case tests to break when unrelated changes in the GUI happen.
To avoid these problems, design the system and the tests so that business rules can be tested without using the GUI (or other volatile things). The recommended way to do this is by creating a testing API that has "superpowers". These super powers include avoiding security constraints, bypassing expensive resources such as databases and allowing developers to force the system into particular testable states.
### The Pitfall of Structural Coupling
Having the test suite structurally map the production code (e.g. one test file for every class and tests for every public method) is problematic.
Structural coupling of tests makes the production code hard to change because the tests must change to follow the structure.
Over time, structural coupling limits the necessary independent evolution that tests and production code should undergo: Tests suites should naturally become more concrete and specific over time, whereas production code should naturally become more abstract and general.
## Ch.29 Clean Embedded Architecture
Firmware is software that is tightly coupled to the hardware it runs on. This coupling results in the need to re-write when the hardware changes.
Hardware changes at a very fast pace. To shield businesses from this, firmware engineers should be writing more software (code that has been isolated from the hardware it runs on) and less firmware.
### App-titude Test: The problem with just making it work
A general software good practice is:
1. “First make it work.” You are out of business if it doesn't work.
2. “Then make it right.” Refactor the code so that you and others can understand it and evolve it as needs change or are better understood.
3. “Then make it fast.” Refactor the code for “needed” performance.
Many engineers stop at "making it work" (aka the app-titude test) and never go beyond that.In embedded software in particular, often 1 and 3 are done together and 2 is never considered.
### The Target-Hardware Bottleneck Problem
Yes, embedded software has to run in special constrained hardware. However, embedded software development is not SO special; the principles of clean architecture still apply.
In embedded systems, you know you have problems when you can only test your code on the target hardware (as opposed to being able to test the business rules of your code independent of the hardware). This is known as the target hardware bottleneck problem. A clean embedded architecture is a testable embedded architecture.
### Conclusion
Letting all code become firmware is not good for your product’s long-term health. Being able to test only in the target hardware is not good for your product’s long-term health. A clean embedded architecture is good for your product’s long-term health.
|
Java | UTF-8 | 2,343 | 3.734375 | 4 | [] | no_license | package com.gfg.array;
/*
Given an array A of size N, construct a Product Array P (of same size) such that P is equal to the
product of all the elements of A except A[i].
Input:
The first line of input contains an integer T denoting the number of test cases. T testcases follow.
Each testcase contains two lines of input. The first line is N. The second line contains N elements
separated by spaces.
Output:
For each testcase, print the Product array P.
Constraints:
1 <= T <= 10
1 <= N <= 1000
1 <= Ai <= 20
Example:
Input
2
5
10 3 5 6 2
2
12 20
Output
180 600 360 300 900
20 12
Explanation:
Testcase1: For the product array P, at i=0 we have 3*5*6*2. At i=1 10*5*6*2. At i=2 we have 10*3*6*2.
At i=3 we have 10*3*5*2. At i=4 we have 10*3*5*6
So P is 180 600 360 300 900
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Product_array_puzzle {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
int n=0;
// long x=0,y=0;
StringTokenizer tk;
int[] arr,p;
long prod;
while(t-->0)
{
//int l=0,r=0;
prod=1;
n=Integer.parseInt(br.readLine());
arr= new int[n];
//p=new int[n];
tk = new StringTokenizer(br.readLine());
for (int i = 0; i <n ; i++) {
arr[i]=Integer.parseInt(tk.nextToken());
prod*=arr[i];
}
for (int i = 0; i <n ; i++) {
sb.append(prod/arr[i]).append(" ");
}
/*for (int i = 0; i < n; i++) {
l=i-1; r=i+1;
prod=1;
while(l>=0 || r<n){
if(l>=0){
prod*=arr[l];
l--;
}
if(r<n){
prod*=arr[r];
r++;
}
}
// p[i]=prod;
sb.append(prod).append(" ");
}*/
sb.append("\n");
}
System.out.print(sb);
}
}
|
C | UTF-8 | 1,936 | 2.75 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* vec3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lwyl-the <lwyl-the@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/02 10:40:53 by rgyles #+# #+# */
/* Updated: 2019/04/13 14:56:08 by lwyl-the ### ########.fr */
/* */
/* ************************************************************************** */
#include "rt.h"
void vec3_add(t_vec3 *a, t_vec3 *b, t_vec3 *result)
{
result->x = a->x + b->x;
result->y = a->y + b->y;
result->z = a->z + b->z;
}
void vec3_subtract(t_vec3 *a, t_vec3 *b, t_vec3 *result)
{
result->x = a->x - b->x;
result->y = a->y - b->y;
result->z = a->z - b->z;
}
void vec3_scalar(t_vec3 *a, double number)
{
a->x *= number;
a->y *= number;
a->z *= number;
}
double vec3_dot(t_vec3 *a, t_vec3 *b)
{
return (a->x * b->x + a->y * b->y + a->z * b->z);
}
void vec3_cross(t_vec3 *a, t_vec3 *b, t_vec3 *c)
{
c->x = a->y * b->z - a->z * b->y;
c->y = a->z * b->x - a->x * b->z;
c->z = a->x * b->y - a->y * b->x;
}
double vec3_length(t_vec3 *vector)
{
return (sqrt(pow(vector->x, 2) + pow(vector->y, 2) + pow(vector->z, 2)));
}
void vec3_normalize(t_vec3 *vector, double length)
{
vector->x /= length;
vector->y /= length;
vector->z /= length;
}
void get_intersection_point(t_vec3 *source, t_vec3 *ray, double t, t_vec3 *p)
{
p->x = source->x + t * ray->x;
p->y = source->y + t * ray->y;
p->z = source->z + t * ray->z;
}
|
Markdown | UTF-8 | 1,044 | 2.90625 | 3 | [
"CC-BY-4.0"
] | permissive | ---
pageType: section
path: '/rules/naming'
title: '1. Naming rules'
---
GraphQL uses regexp `/[_A-Za-z][_0-9A-Za-z]*/` to validate property and type names. In other words, GraphQL lets you use multiple styles, such as camelCase, under_score, UpperCamelCase end CAPITALIZED_WITH_UNDERSCORES. Notice that that kebab-case is not supported.
The support for multiple naming conventions leads to a question of which one to use.
We looked at [Eye Tracking's](http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf) research that tried to analyze camelCase and under_score. However, it didn't find any favorites.
In the absence of conclusive research, we suggest following these rules:
<!-- card-links -->
- [1.1. Use `camelCase` for GraphQL fields and arguments.](./naming-fields-args.md)
- [1.2. Use `UpperCamelCase` for GraphQL types.](./naming-types.md)
- [1.3. Use `CAPITALIZED_WITH_UNDERSCORES` to name ENUM types.](./naming-enum.md)
- [1.4. Avoid using `get` in your Query resolvers.](./naming-query-resolvers.md)
|
Java | UTF-8 | 951 | 2.84375 | 3 | [
"MIT"
] | permissive | package it.polimi.ingsw.utils;
/**
* Class containing colors used in CLI
*/
public class ConsoleColors {
// Reset
public static final String RESET = "\033[0m"; // Text Reset
// Regular Colors
public static final String RED = "\033[0;31m";
public static final String GREEN = "\033[0;32m";
public static final String YELLOW = "\033[0;33m";
public static final String BLUE = "\033[0;34m";
public static final String PURPLE = "\033[0;35m";
// Bold
public static final String GREEN_BOLD = "\033[1;32m"; // GREEN
public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW
// High Intensity
public static final String BLACK_BRIGHT = "\033[0;90m"; // BLACK
public static final String WHITE_BRIGHT = "\033[0;97m"; // WHITE
// Background
public static final String RED_BACKGROUND = "\033[41m"; // RED
public static final String GREEN_BACKGROUND = "\033[42m"; // GREEN
} |
Shell | UTF-8 | 225 | 3 | 3 | [] | no_license | if [[ "$(pamixer --get-mute)" = "true" ]]; then
icon=""
color="#ffff00"
else
icon=""
color="#dddddd"
fi
vol=$(pamixer --get-volume)
printf "%s %s%%\n" "$icon" "$vol"
printf "Volume\n"
printf "$color\n"
|
Java | UTF-8 | 913 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | package com.opdar.gulosity.connection.protocol;
/**
* Created by Shey on 2016/8/19.
*/
public class HeaderProtocol implements Protocol {
private int bodyLength;
private byte sequence;
/**
Up to MySQL 3.22, 0xfe was followed by a 4-byte integer.
*/
public void fromBytes(byte[] data) {
this.bodyLength = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8) | ((data[2] & 0xFF) << 16);
sequence = data[3];
}
public byte[] toBytes() {
return new byte[]{(byte) (bodyLength & 0xFF),(byte) (bodyLength >>> 8),(byte) (bodyLength >>> 16),sequence};
}
public int getBodyLength() {
return bodyLength;
}
public void setBodyLength(int bodyLength) {
this.bodyLength = bodyLength;
}
public byte getSequence() {
return sequence;
}
public void setSequence(byte sequence) {
this.sequence = sequence;
}
}
|
C++ | ISO-8859-3 | 812 | 2.703125 | 3 | [] | no_license | /**
* BOJ
* No.1166
* @author peter9378
* @date 2021.01.26
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <cmath>
#include <map>
#include <queue>
#include <stack>
#include <unordered_set>
#include <unordered_map>
#include <cstring>
#include <iterator>
#include <numeric>
#include <complex>
using namespace std;
// main function
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int N, L, W, H;
cin >> N >> L >> W >> H;
double left = 0, right = 9876543210, mid;
for(int i = 0; i < 10000; i++)
{
mid = (left + right) / 2;
if (((long long)(L/mid))*((long long)(W/mid))*((long long)(H/mid)) < N)
right = mid;
else
left = mid;
}
printf("%.10lf", left);
return 0;
}
|
Java | UTF-8 | 1,628 | 2.296875 | 2 | [] | no_license | package com.hasanemreerkek.services;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
/**
* Created by Emre on 19.10.2015.
*
* Captche Service
*/
@Service
public class CaptcheService {
/**
* get status of the Captcha is valid or is not valid
* @param grecaptchaResponse the responce of Google ReCaptche
* @return status of the Captcha is valid or is not valid
* @throws IOException
*/
public boolean isSuccess(String grecaptchaResponse) throws IOException {
String secretKey = "6LffLA8TAAAAAFUqxEzl_IPCtemoHUt1fuDeRXNQ";
String url = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + grecaptchaResponse;
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
ObjectMapper mapper = new ObjectMapper();
HashMap map = mapper.readValue(result.toString(), HashMap.class);
return (Boolean) map.get("success");
}
}
|
Markdown | UTF-8 | 1,465 | 2.890625 | 3 | [] | no_license | # Crazy little thing called love
```
This thing called love, I just can't handle it
This thing called love, I must get round to it
I ain't ready
Crazy little thing called love
This thing (this thing)
Called love (called love)
It cries (like a baby)
In a cradle all night
It swings (woo woo)
It jives (woo woo)
It shakes all over like a jelly fish
I kinda like it
Crazy little thing called love
There goes my baby
She knows how to rock 'n' roll
She drives me crazy
She gives me hot and cold fever
Then she leaves me in a cool cool sweat
I gotta be cool, relax, get hip
And get on my track's
Take a back seat, hitch-hike
And take a long ride on my motorbike
Until I'm ready
Crazy little thing called love
{Solo}
I gotta be cool, relax, get hip
And get on my track's
Take a back seat (ah hum), hitch-hike (ah hum)
And take a long ride on my motorbike
Until I'm ready (ready Freddie)
Crazy little thing called love
This thing called love, I just can't handle it
This thing called love, I must get round to it
I ain't ready
Ooh ooh ooh ooh
Crazy little thing called love
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
Crazy little thing called love, yeah, yeah
```
|
Java | UTF-8 | 2,263 | 2.203125 | 2 | [] | no_license | package ecorau.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ecorau.demo.entities.User;
import ecorau.demo.service.ServiceResult;
import ecorau.demo.service.UserService;
@RestController
@RequestMapping("/ecorau")
public class UserController {
@Autowired
private UserService customerService;
/* ---------------- GET ALL User ------------------------ */
@GetMapping("/get-all-user")
public ResponseEntity<ServiceResult> findAll() {
return new ResponseEntity<ServiceResult>(customerService.findAllUser(), HttpStatus.OK);
}
/* ---------------- GET User BY ID ------------------------ */
@GetMapping("/get-user-by-id/{id}")
public ResponseEntity<ServiceResult> findById(@PathVariable int id) {
return new ResponseEntity<ServiceResult>(customerService.findByIdUser(id), HttpStatus.OK);
}
/* ---------------- CREATE NEW User ------------------------ */
@PostMapping("/create-user/{id}")
public ResponseEntity<ServiceResult> create(@RequestBody User user,@PathVariable int id) {
return new ResponseEntity<ServiceResult>(customerService.createUser(user,id), HttpStatus.OK);
}
/* ---------------- UPDATE User ------------------------ */
@PutMapping("/update-user")
public ResponseEntity<ServiceResult> update(@RequestBody User user) {
return new ResponseEntity<ServiceResult>(customerService.updateUser(user), HttpStatus.OK);
}
/* ---------------- DELETE User ------------------------ */
@DeleteMapping("/delete-user")
public ResponseEntity<ServiceResult> delete(@RequestBody DeleteUserRequest request) {
return new ResponseEntity<ServiceResult>(customerService.deleteUser(request.getId()), HttpStatus.OK);
}
}
|
Python | UTF-8 | 1,821 | 2.671875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sat May 30 14:23:29 2020
@author: Mariusz
"""
# -*- coding: utf-8 -*-
"""
Created on Sat May 30 13:47:10 2020
Script to detect objects using Google Net classifier
it required following files:
bvlc_googlenet.prototxt
bvlc_googlenet.caffemodel
classification_classes_ILSVRC2012.txt
@author: Mariusz
"""
import numpy as np
import cv2 as cv
import sys
proto = "bvlc_googlenet.prototxt"
model = "bvlc_googlenet.caffemodel"
classification = "classification_classes_ILSVRC2012.txt"
confidence = 0.3
mean = (104, 117, 123)
capture = cv.VideoCapture(0)
size = (224,224)
swapRB = False
classes = []
if not capture.isOpened():
print ("error opening camera")
sys.exit(0)
# loading pretrained model
net = cv.dnn.readNet(model, proto)
# load classification to list
with open(classification) as file:
classes = file.read().splitlines()
while True:
ret, frame = capture.read()
if ret == False:
print("frame not captured,")
sys.exit(0)
h, w = frame.shape[:2]
# create blob
blob = cv.dnn.blobFromImage(frame, 1.0, size, mean, swapRB, False)
# Pass blob to network and calculate network output
net.setInput(blob)
detection = net.forward()
# calculate valcues and confidence
minVal, maxVal, minLoc, maxLoc = cv.minMaxLoc(detection)
# add text with description of the item in the video and percentage in confidence
cv.putText(frame, classes[maxLoc[0]], (10,30), cv.FONT_HERSHEY_SIMPLEX, 0.7,\
(0,0,255),2)
cv.putText(frame, "confidence: {:0.2f} %".format(maxVal * 100), (10,60),\
cv.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255),2)
cv.imshow("Image", frame)
if cv.waitKey(30) == 27:
break
cv.destroyAllWindows() |
Markdown | UTF-8 | 1,448 | 2.6875 | 3 | [] | no_license | # Sparkify Udacity Data Scientist Nano Degree Capstone Project:
## Index:
Dependencies
Project Motivation
Files Description
Results
Acknowledgements
## Dependencies
The following libraries are used to implement this project:
Pandas
PySpark
Spark
Matplotlib
Seaborn
## Project Motivation
The current project is a part of the Udacity's Data Scientist Nanodegree program analyzing the behaviour of users for an app called Sparkify to predict user churn. Sparkify is an app similar to Spotify and the dataset contains user behaviour log for the past few months. It contains some basic information about the users as well as information about a particular action they have taken. A user can have multiple actions which leads to multiple entries for a user, we can identify when a user churned through the action of account cancellation.
## Sparkify file Description
Sparkify.ipynb is the main notebook where we do all the preprocessing, feature engineering and modelling.
## Results
Support Vector Machines, Random Forest and Gradient Boosted Trees are trained on the data set. Performance between the three models and Gradient Boosted Trees outperformed the rest by a large margin. The metric we used to evaluate performance is F-1 Score as that gives us a better representation of the model performance.
The final metrics for our Gradient Boosted Trees Classifier are as follows:
The accuracy is 0.866
The F-1 Score is 0.869
|
C# | UTF-8 | 7,461 | 2.796875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using CommandController.Core;
namespace CommandController.FrontEnds.CommandLine
{
/// <summary>
/// Controller for the command line front-end.
/// </summary>
public class CommandLineController : IFrontEndController
{
#region IFrontEndController Members
public int Start(object data)
{
if (!(data is string[]))
{
throw new ArgumentException("The data parameter should be a string array containing command line arguments.");
}
string[] args = (string[])data;
string[] subArgs = null;
if (args.Length == 0)
{
Console.WriteLine(@"
Usage:
{0} /operation_id: Runs the operation with the ID: ""operation_id"".
Getting help:
{0}: Prints this message.
{0} /?: Prints a list of available operations.
{0} /help operation_id: Prints detailed help for the operation identified by
""operation_id"".
{0} /fullhelp: Prints detailed help for all available operations.
", ExeName
);
return 0;
}
else
{
List<string> subArgsList = new List<string>();
for (int i = 1; i < args.Length; i++)
{
subArgsList.Add(args[i]);
}
subArgs = subArgsList.ToArray();
}
try
{
string opKey = args[0];
if (opKey.StartsWith("/", StringComparison.OrdinalIgnoreCase))
{
opKey = opKey.Substring(1).ToLowerInvariant();
switch (opKey)
{
case "?":
Console.Write(GetUsage(false, null));
return 0;
case "help":
if (args.Length > 1)
{
string opArg = args[1];
Console.Write(GetUsage(true, opArg));
}
else
{
Console.Write("Please specify an operation to get help for.");
}
return 0;
case "fullhelp":
Console.Write(GetUsage(true, null));
return 0;
default:
return OperationController.InvokeOperationById(opKey, new CommandLineValueProvider(subArgs));
}
}
Console.Write(GetUsage(false, null));
return 1;
}
catch (InvalidOperationArgumentException ioae)
{
Console.WriteLine("Invalid \"{0}\" value specified.", ioae.ViolatedArgument.Id);
return 1;
}
catch (ArgumentExclusivityException aee)
{
Console.WriteLine("The \"{0}\" argument cannot be specified with any other arguments.", aee.ViolatedArgument.Id);
return 1;
}
catch (ArgumentRequirementException are)
{
Console.WriteLine("The \"{0}\" argument must be specified.", are.ViolatedArgument.Id);
return 1;
}
catch (ArgumentNotDefinedException ande)
{
Console.WriteLine("\"{0}\" has not been defined as an argument for the current operation. " +
"Ensure that a reference to it is retured by the operation's Arguments property.", ande.ViolatedArgument.Id);
return 1;
}
catch (Exception ex)
{
Console.WriteLine("ERROR");
StaticUtils.PrintExceptionDetails(ex);
return 1;
}
}
#endregion
internal static string ExeName = Assembly.GetEntryAssembly().GetName().Name;
private static string GetUsage(bool full, string operationId)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
if (!String.IsNullOrEmpty(operationId) && !OperationController.HasOperation(operationId))
{
sb.AppendFormat("Operation: {0} does not exist.", operationId);
sb.AppendLine();
}
else
{
IEnumerable<Operation> availableOperations = OperationController.Operations
.Where(op =>
(String.IsNullOrEmpty(operationId) && op.Visible) ||
(!String.IsNullOrEmpty(operationId) && op.OperationId == operationId));
if (availableOperations.Count() > 0)
{
foreach (Operation op in availableOperations)
{
sb.AppendFormat("Operation: {0}", op.OperationId);
sb.AppendLine();
sb.AppendFormat("Usage: {0} /{1}", ExeName, op.OperationId);
List<string> argumentUsageStrings = new List<string>();
foreach (IArgument argument in op.Arguments)
{
argumentUsageStrings.Add(GetArgumentUsageString(argument));
}
sb.AppendFormat(" " + String.Join(" ", argumentUsageStrings.ToArray()));
sb.AppendLine();
sb.AppendLine();
if (full)
{
sb.Append(op.UsageDescription);
sb.AppendLine();
sb.Append("Arguments:");
sb.AppendLine();
foreach (IArgument argument in op.Arguments)
{
sb.AppendFormat(" {0}: {1}", GetArgumentUsageString(argument), argument.Description);
sb.AppendLine();
}
}
sb.AppendFormat("---");
sb.AppendLine();
sb.AppendLine();
}
}
else
{
sb.Append("No visible operations found.");
sb.AppendLine();
}
}
return sb.ToString();
}
private static string GetArgumentUsageString(IArgument argument)
{
string retval;
if (argument is FlagArgument)
{
retval = argument.Id;
}
else if (argument is IntegerArgument)
{
retval = argument.Id + "=x";
}
else if (argument is StringArgument)
{
retval = argument.Id + "=<" + argument.FriendlyName + ">";
}
else
{
return String.Empty;
}
if (!argument.Mandatory)
{
retval = "[" + retval + "]";
}
return retval;
}
}
}
|
JavaScript | UTF-8 | 575 | 2.796875 | 3 | [] | no_license | import React from 'react'
import { render } from 'react-dom'
class ComplimentMachine extends React.Component{
constructor(props){
super(props)
this.state = {name : '________'}
}
handleInput(event){
this.setState({
name: event.target.value
})
console.log(event.target.value)
}
render(){
return(
<div>
<input type="text" onChange={this.handleInput.bind(this)} />
<h2>Hey {this.state.name} wanna</h2>
<i>{this.props.compliment}</i>
</div>
)
}
}
export default ComplimentMachine
|
Markdown | UTF-8 | 1,010 | 3.40625 | 3 | [] | no_license |
### Leetcode 78
#### [Subsets](https://leetcode.com/problems/subsets)
##### ***Problem:***
Given a set of distinct integers, nums, return all possible subsets.
The solution set must not contain duplicate subsets.
##### ***Example:***
Input: [1,2]
Output: [[], [1], [2], [1,2]]
##### *Method #1*
``` java
/*
*Author: yeh
*Time: 2017_08_07
*Language: Java
*
*/
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (nums == null) return ret;
//empty set is subset of any set
List<Integer> newSubSet = new ArrayList<Integer>();
ret.add(newSubSet);
for (int i = 0; i < nums.length; i++) {
for (int j = ret.size() - 1; j >= 0; j--) {
newSubSet = new ArrayList<Integer>(ret.get(j));
newSubSet.add(nums[i]);
ret.add(newSubSet);
}
}
return ret;
}
}
```
|
C++ | UTF-8 | 1,582 | 2.59375 | 3 | [] | no_license | #ifndef PROCESSDATA_H
#define PROCESSDATA_H
#include <atomic>
#include <vector>
#include <map>
#include <boost/thread.hpp>
#include "IODataTypes.h"
class ProcessData
{
public:
ProcessData(unsigned int update_intervall);
std::atomic<bool> run_;
virtual ~ProcessData();
/**
* parsing ds buffer and safes it to data_buffer_ map with the procedure as id
**/
void processData(data_segment_buffer& data_to_add);
/**
* calculate the y coordinates that the renderarea needs for displaying diagram
**/
void calcDataPoints();
void setGpuInfo(gpu_info& info);
__inline void setTau(int tau) {tau_ = tau;}
__inline int getTau() {return tau_;}
void setPause(bool p);
private:
std::atomic<bool> pause_;
std::map<int, std::vector<parsed_data> > data_buffer_;
std::map<int, char*> procedure_names_;
boost::mutex pause_lock_;
boost::condition_variable_any pause_cond_;
boost::mutex data_buffer_lock_;
boost::condition_variable_any data_buffer_cond_;
unsigned int tau_; ///< time in milliseconds to trigger calculation of data points
std::map<int, uint64_t> y_coordinates_absolute_; ///< key is procedure id, value is absolute value of used time overall
std::map<int, long double> y_coordinates_percentage_; ///< key is procedure id, value is auslastung on gpu in %
boost::thread* process_data_points_;
boost::system_time timeout_;
gpu_info* gpu_info_;
uint64_t overall_cycles_counter_;
void runDataPointsThread();
void waitTau();
};
#endif // PROCESSDATA_H
|
C | UTF-8 | 920 | 4.375 | 4 | [] | no_license | #include <stdio.h>
/* 描述: 直接插入排序,该函数最终将数据排列成升序。 */
void insert_sort(int *data, int nitems)
{
int sorted_pos = 0;
int cur_pos = 0;
int cur_data;
if (nitems == 1) {
return;
}
for (sorted_pos = 0; sorted_pos < nitems; sorted_pos ++)
{
cur_data = data[sorted_pos + 1];
for (cur_pos = sorted_pos ; cur_pos >= 0; cur_pos --)
{
if (cur_data < data[cur_pos]) {
data[cur_pos + 1] = data[cur_pos];
} else {
break;
}
}
data[cur_pos + 1] = cur_data;
}
}
void print_data(int *data, int nitems)
{
int index = 0;
if (data == NULL) {
return;
}
for (index = 0; index < nitems; index ++) {
printf("%d ", data[index]);
}
printf("\r\n");
}
int main(void)
{
int data[] = {9, 7, 2, 3, 6, 8, 5, 4, 1};
print_data(data, sizeof(data)/sizeof(int));
insert_sort(data, sizeof(data)/sizeof(int));
print_data(data, sizeof(data)/sizeof(int));
}
|
Java | UTF-8 | 2,392 | 2.75 | 3 | [] | no_license | // Copyright (C) 2016-2017 GWGW All rights reserved
package com.mmc.java.base.system.io.seria;
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
/**
* ClassName: Blip3<br/>
* Description: 对象序列化完整保存恢复实现<br/>
* Author: GW<br/>
* Create: 2017年8月19日<br/>
*
* History: (Version) Author dateTime description <br/>
*/
public class Blip3 implements Externalizable {
private String s;
private int i;
public Blip3(){}
public Blip3(int iinit, String sinit) {
this.i = iinit;
this.s = sinit;
}
/**
* @return the s
*/
public String getS() {
return s;
}
/**
* @param s the s to set
*/
public void setS(String s) {
this.s = s;
}
/**
* @return the i
*/
public int getI() {
return i;
}
/**
* @param i the i to set
*/
public void setI(int i) {
this.i = i;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Blip3: [i= + " + i + ", s= " + s + "]";
}
/* (non-Javadoc)
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(s);
out.writeInt(i);
}
/* (non-Javadoc)
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.s = (String) in.readObject();
this.i = in.readInt();
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
String path = "E:\\bak\\file\\Blip3.out";
Blip3 blip3 = new Blip3(1, "blip3");
System.out.println("before " + blip3);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
System.out.println("saving object ");
oos.writeObject(blip3);
oos.close();
System.out.println("recoving object ");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
blip3 = (Blip3) ois.readObject();
System.out.println("after " + blip3);
ois.close();
}
}
|
Markdown | UTF-8 | 1,837 | 2.546875 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | <!--author=SharS last changed: 9/17/15-->
#### <a name="to-create-a-new-service"></a>创建新服务
1. 使用 Microsoft 帐户凭据登录到 [Microsoft Azure 政府门户](https://portal.azure.us/)。
2. 在政府门户中,单击 **+**,然后在应用商店中单击“查看所有”。 搜索“StorSimple 物理”。 选择并单击“StorSimple 物理设备系列”,单击“创建”。 或者,在政府门户中,单击 **+**,然后在“存储”下单击“StorSimple 物理设备系列”。
3. 在“StorSimple 设备管理器”边栏选项卡中,执行以下步骤:
1. 为服务提供唯一“资源名称”。 此名称是可用来标识服务的友好名称。 名称可以为 2 到 50 个字符,包括字母、数字和连字符。 名称必须以字母或数字开头和结尾。
2. 从下拉列表中选择一个“订阅” 。 订阅链接到计费帐户。 如果只有一个订阅,此字段不存在。
3. 对于“资源组”,请使用现有组或创建新组。 有关详细信息,请参阅 [Azure 资源组](https://azure.microsoft.com/documentation/articles/virtual-machines-windows-infrastructure-resource-groups-guidelines/)。
4. 为服务提供“位置” 。 位置是指要部署设备的地理区域。 选择“美国爱荷华州政府”或“美属维京政府”。
5. 选择“新建存储帐户” 自动通过该服务创建存储帐户。 为此存储帐户指定名称。 如果需要将数据存储在不同位置,请取消选中此框。
6. 如果希望在仪表板上显示此服务的快速链接,请选中“固定到仪表板”。
7. 单击“创建”以创建 StorSimple 设备管理器。 创建服务需要几分钟时间。 在服务成功创建后,会发出一条通知并且会打开新的服务边栏选项卡。
|
PHP | UTF-8 | 1,289 | 2.53125 | 3 | [] | no_license | <?php
namespace Tests\Unit;
use Tests\TestCase;
class ConverterTest extends TestCase
{
public function testI()
{
$response = $this->get('/api/convert?number=I');
$response->assertJson([
'result' => 1,
]);
}
public function testV()
{
$response = $this->get('/api/convert?number=V');
$response->assertJson([
'result' => 5,
]);
}
public function testX()
{
$response = $this->get('/api/convert?number=X');
$response->assertJson([
'result' => 10,
]);
}
public function testL()
{
$response = $this->get('/api/convert?number=L');
$response->assertJson([
'result' => 50,
]);
}
public function testC()
{
$response = $this->get('/api/convert?number=C');
$response->assertJson([
'result' => 100,
]);
}
public function testD()
{
$response = $this->get('/api/convert?number=D');
$response->assertJson([
'result' => 500,
]);
}
public function testM()
{
$response = $this->get('/api/convert?number=M');
$response->assertJson([
'result' => 1000,
]);
}
} |
TypeScript | UTF-8 | 300 | 2.8125 | 3 | [] | no_license | export let pi2: number = Math.PI * 2;
export let angle270: number = Math.PI * 1.5;
export function getDistance (x1: number, y1: number, x2: number, y2: number): number {
let xDistance = x1 - x2;
let yDistance = y1 - y2;
let d = Math.sqrt(xDistance**2 + yDistance**2);
return d;
}
|
Markdown | UTF-8 | 827 | 2.890625 | 3 | [] | no_license | ## Tic Tac Toe with Allegro
### Presenteation
Le jeu de Tic Tac Toe implémenté en C avec la bibliothéque Allegro5.
Propose un mode Solo et un mode multijoueur.
Le mode Solo propose 3 niveaux :
* Easy (facile) : L'ordinateur joue de facon aléatoire (faut vraiment le vouloir pour perdre x) ).
* Medium (Moyen) : L'ordinateur essaie de gagner ET d'éviter de perdre mais il reste tout de meme possible de le vaincre.
* Impossible : Implémenté en MiniMax, vous ne gagnerez jamais, l'ordinateur traite touts les cas possibles et ne choisit que ceux
où il est gagant (ou au pire n y est pas perdant).
### technologies utilisés
Le jeu a été codé en C, grace à la bibliothéque [ALlegro5](http://liballeg.org/).
### Demonstration



|
C | UTF-8 | 4,839 | 3.453125 | 3 | [] | no_license | #include <ctype.h>
#include <errno.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
enum { MAX_STRING_LENGTH = 63 };
char get_char(int is_input_file, FILE *stream) {
if (is_input_file) {
return fgetc_unlocked(stream);
} else {
return getchar_unlocked();
}
}
int is_char_correct(char c) {
if (c == '\t' || c == '\n' || c == '\r') {
return 1;
}
if ((0 <= c && c <= 31) || c == 127) {
return 0;
}
return 1;
}
int parse_int32(char *s, int32_t *out) {
char *eptr;
errno = 0;
int64_t value = strtol(s, &eptr, 10);
if (!*s || *eptr || errno) {
return 0;
}
if (value == (int32_t)value) {
*out = (int32_t)value;
return 1;
} else {
return 0;
}
}
int parse_double(char *s, double *out) {
int only_digits = 1;
char *s_copy = s;
if (!*s) {
return 0;
}
if (*s_copy == '+' || *s_copy == '-') {
++s_copy;
}
for (; *s_copy; ++s_copy) {
if (isdigit(*s_copy)) {
continue;
}
only_digits = 0;
break;
}
if (only_digits) {
return 0;
}
char *eptr;
errno = 0;
double value = strtod(s, &eptr);
if (!*s || *eptr || errno) {
return 0;
}
*out = value;
return 1;
}
int main(int argc, char* argv[]) {
FILE *stream = NULL;
int is_input_file = 0;
if (argc > 2) {
fprintf(stderr, "too many arguments\n");
return 1;
}
if (argc > 1) {
is_input_file = 1;
if (!(stream = fopen(argv[1], "r"))) {
fprintf(stderr, "error of fopen()\n");
return 1;
}
}
int32_t max_int = 0;
double min_double = 0.0;
size_t string_size = 0;
int c;
int is_int_found = 0, is_double_found = 0, is_nan_found = 0;
char *s = malloc(sizeof(char) * (MAX_STRING_LENGTH + 1));
if (!s) {
fprintf(stderr, "malloc() for string failed\n");
return 1;
}
while (42) {
c = get_char(is_input_file, stream);
if (!is_char_correct(c) && c != EOF) {
fprintf(stderr, "invalid characters in input\n");
free(s);
return 1;
}
if (c == EOF || isspace(c)) {
if (string_size) {
// 0-terminate a string.
*(s + string_size) = '\0';
string_size = 0;
// Parse a string.
int32_t int_value = 0;
if (parse_int32(s, &int_value)) {
if (is_int_found) {
if (max_int < int_value) {
max_int = int_value;
}
} else {
// It's the first int number in the input.
is_int_found = 1;
max_int = int_value;
}
if (c == EOF) {
break;
} else {
continue;
}
}
double double_value = 0;
if (parse_double(s, &double_value)) {
if (!is_nan_found) {
if (isnan(double_value)) {
is_nan_found = 1;
is_double_found = 1;
min_double = NAN;
} else if (is_double_found) {
if (min_double > double_value) {
min_double = double_value;
}
} else {
// It's the first double number in the input.
is_double_found = 1;
min_double = double_value;
}
}
if (c == EOF) {
break;
} else {
continue;
}
}
}
if (c == EOF) {
break;
} else {
continue;
}
} else {
if (string_size == MAX_STRING_LENGTH) {
fprintf(stderr, "string size > %d\n", MAX_STRING_LENGTH);
free(s);
return 1;
} else {
// Add char to string.
*(s + (string_size++)) = c;
}
}
}
if (!is_int_found) {
fprintf(stderr, "int number not found\n");
free(s);
return 1;
}
if (!is_double_found) {
fprintf(stderr, "double number not found\n");
free(s);
return 1;
}
fprintf(stdout, "%d %.10g\n", max_int, min_double);
free(s);
return 0;
}
|
C++ | UTF-8 | 456 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include "model.h"
using namespace std;
int main(int argcc, char** argv)
{
srand48( time( NULL ) );
int num_part = 1000;
int MAX_ITER = 1000;
Model model;
model.initiate(num_part);
model.decompose_domain(5);
clock_t begin = clock();
model.simulate(MAX_ITER);
model.save();
clock_t end = clock();
double elapsed_time = double(end - begin) / CLOCKS_PER_SEC;
cout << elapsed_time << endl;
return 0;
}
|
Markdown | UTF-8 | 714 | 2.625 | 3 | [] | no_license | # Docker Config Server Example
> Simple Docker example of config server/service app
## config-server
Contain jar file of project config-server in this directory to create image
Run Dockerfile to create image
```
docker build -t “config-server:Dockerfile” .
```
## bank-account-service
Contain jar file of project bank-account-service in this directory to create image
Run Dockerfile to create image
```
docker build -t “bank-account-service:Dockerfile” .
```
## docker-compose
Once the images are created run the compose file to create and run container
```bash
# Run in Docker
docker-compose up
# use -d flag to run in background
# Tear down
docker-compose down
|
C++ | UTF-8 | 4,352 | 3.125 | 3 | [] | no_license | #ifndef _zString_H_
#define _zString_H_
#include <string>
namespace Tools
{
inline std::string& string_replace(std::string& str, const std::string& str_src, std::string& str_dst)
{
std::string::size_type pos(0);
std::string::size_type src_len = str_src.size();
std::string::size_type dst_len = str_dst.size();
while ((pos = str.find(str_src, pos)) != std::string::npos)
{
str.replace(pos, src_len, str_dst);
pos += dst_len;
}
return str;
}
template <typename Container>
inline void stringtok(Container& container, std::string const& in, const char* const delimiters=" \t\n", const int deep = 0)
{
container.clear();
const std::string::size_type len = in.length();
std::string::size_type i = 0;
int count = 0;
while (i < len)
{
i = in.find_first_not_of(delimiters, i);
if (i == std::string::npos)
return;
std::string::size_type j = in.find_first_of(delimiters, i);
++count;
if (j == std::string::npos || (deep > 0 && count > deep))
{
container.push_back(in.substr(i));
return;
}
else
{
container.push_back(in.substr(i, j-i));
}
i = j + 1;
}
}
struct ToLower
{
char operator() (char c) const
{
return std::tolower(c);
}
};
inline void to_lower(std::string& s)
{
std::transform(s.begin(), s.end(), s.begin(), ToLower());
}
struct ToUpper
{
char operator() (char c) const
{
return std::toupper(c);
}
};
inline void to_upper(std::string& s)
{
std::transform(s.begin(), s.end(), s.begin(), ToUpper());
}
struct strtol : public std::unary_function<std::string, long>
{
long operator() (std::string str)
{
return std::atol(str.c_str());
}
};
struct strtoi : public std::unary_function<std::string, int>
{
int operator() (std::string str)
{
return atoi(str.c_str());
}
};
struct strtof : public std::unary_function<std::string, double>
{
double operator() (std::string str)
{
return std::atof(str.c_str());
}
};
template <typename Target, typename Source>
inline Target lexical_cast(Source arg)
{
Target target = Target();
std::stringstream ss;
ss << arg;
ss >> target;
return target;
}
template<>
inline std::string lexical_cast<std::string, const char*>(const char* arg)
{
return std::string(arg);
}
template<>
inline std::string lexical_cast<std::string, char*>(char* arg)
{
return std::string(arg);
}
template<>
inline std::string lexical_cast<std::string, const std::string>(const std::string arg)
{
return std::string(arg);
}
template<>
inline std::string lexical_cast<std::string, std::string>(std::string arg)
{
return std::string(arg);
}
template<typename Container>
inline size_t strtok(const std::string& str, Container cont, const std::string& delim = " ", size_t depth = 0)
{
cont.clear();
size_t size = 0;
std::string::size_type beg = 0;
std::string::size_type end = 0;
beg = std.find_first_not_of(delim);
while (std::string::npos != beg)
{
end = str.find_first_of(delim, beg);
if (std::string::npos == end)
end = str.length();
typename Container::value_type value;
value = lexical_cast<typename Container::value_type>(str.substr(beg, end - beg));
cont.insert(cont.end(), value);
++size;
if (depth && size >= depth)
return size;
beg = std.find_first_not_of(delim, end);
}
return size;
}
template<typename InputIterator>
inline size_t tokstr(InputIterator first, InputIterator end, std::string& str, const std::string& delim = " ", size_t depth = 0)
{
size_t size = 0;
std::stringstream ss;
InputIterator iter = first;
for (; iter != end; ++iter)
{
ss << *iter << delim;
++size;
if (depth && size >= depth)
break;
}
str = ss.str();
if (str.length() >= delim.length())
str.erase(str.length() - delim.length(), delim.length());
return size;
}
template<typename InputIterator>
inline std::string tokstr(InputIterator first, InputIterator end, const std::string& delim = " ", size_t depth = 0)
{
std::string str;
tokstr(first, end, str, delim, depth);
return str;
}
template<typename InputIterator>
inline std::string tokstr(const Container& cont, const std::string& delim = "", const size_t depth = 0)
{
return tokstr(cont.begin(), cont.end(), delim, depth);
}
}
#endif // _zString_H_
|
Markdown | UTF-8 | 1,644 | 3.40625 | 3 | [] | no_license | **Signup**
----
Register a new user account with the given email address and password, if they match the validation criterias (valid email format and password at least 6 characters including letters and numbers).
* **URL**
/v1/user/signup
* **Method:**
`POST`
* **URL Params**
* None
* **Data Params**
**Required:**
* **Type:** application/json <br />
**Content:** `{ "email": "<user email>", "password": "<user password>"}`
* **Success Response:**
* **Code:** 200 <br />
**Content:** `{ "token": "<token string>", "role": "PARTICIPANT" }`
* **Error Response:**
* **Code:** 400 Bad request <br />
**Content:** `{ "error" : "<error message>" }` <br />
**Typical reason:** Data format (json body of the Post request) wrong, e.g. missing key for email or password.
* **Code:** 400 Bad request <br />
**Content:** `{ "error" : "email address already in use" }` <br />
**Typical reason:** Email address already used for an other account.
* **Code:** 500 Internal server error <br />
**Content:** `{ "error" : "<error message>" }` <br />
**Typical reason:** Something went wrong during the token generation. User's input are ok, but method failed generating a valid token, e.g. because signing key is not available.
* **Sample Call:**
```go
creds := &userCredentials{
Email: "your@email.com", // `json:"email"`
Password: "yourpassword", // `json:"password"`
}
payload, err := json.Marshal(creds)
resp, err := http.Post(auth-service-addr + "/v1/user/signup", "application/json", bytes.NewBuffer(payload))
defer resp.Body.Close()
```
* **Notes:**
* None
|
Rust | UTF-8 | 1,073 | 3.015625 | 3 | [
"BSD-3-Clause",
"MIT",
"Python-2.0"
] | permissive | use crate::geometry::Axis;
use crate::geometry::Ball;
use crate::geometry::Bone;
use crate::geometry::Vector;
use crate::render::GroupTracer;
use crate::render::WorldView;
#[derive(Clone, Debug)]
pub struct Leg {
pub hip: Ball,
pub knee: Ball,
pub hoof: Ball,
pub calf: Bone,
pub shin: Bone,
}
impl Leg {
pub fn new(hip: Ball, knee: Ball, hoof: Ball) -> Leg {
let calf = Bone::new(hip.clone(), knee.clone());
let shin = Bone::new(knee.clone(), hoof.clone());
Leg {
hip,
knee,
hoof,
calf,
shin,
}
}
pub fn add_traceable(&self, mut tracer: &mut GroupTracer, world_view: &WorldView) {
self.calf.add_traceable(&mut tracer, world_view);
self.shin.add_traceable(&mut tracer, world_view);
}
pub fn rotate_around(&self, other: &Vector, angle: f64, axis: Axis) {
self.hip.rotate_around(other, angle, axis);
self.knee.rotate_around(other, angle, axis);
self.hoof.rotate_around(other, angle, axis);
}
}
|
Java | UTF-8 | 4,410 | 2.390625 | 2 | [] | no_license | package com.liger.myzhihu.model;
import java.util.List;
/**
* 最新新闻 实体类
* Created by Shuai on 2015/12/19.
*/
public class Latest {
/**
* date : 20151219
* stories : [{"images":["http://pic4.zhimg.com/9a79d6be3a24861e586c6eee89144d43.jpg"],"type":0,"id":7619784,
* "ga_prefix":"121909","title":"官员、银行家、高管\u2026\u2026总觉得这些「精英」肯定信不过"},{"title":"《魂斗罗》中的角色,趴下的时候总是要「萝莉式屈腿俯卧」",
* "ga_prefix":"121908","images":["http://pic1.zhimg.com/343db59b88d6754c3d6988f40f7d456c.jpg"],"multipic":true,
* "type":0,"id":7611185},{"images":["http://pic2.zhimg.com/c51610b16bc8974da7a110f56a37bad9.jpg"],"type":0,
* "id":7615718,"ga_prefix":"121907","title":"相比较其它地区,北京考生上清北有多大优势?"},{"images":["http://pic1.zhimg
* .com/d39ae3c757b0524f351c0874ad9f7fc0.jpg"],"type":0,"id":7531212,"ga_prefix":"121907","title":"买哪台电脑好,我真的是靠算出来的"},
* {"images":["http://pic2.zhimg.com/3b32ab44de832e50b6c4f119e0c07509.jpg"],"type":0,"id":7567902,"ga_prefix":"121907",
* "title":"想在楼顶种一大片花花草草,需要慢慢来"},{"images":["http://pic1.zhimg.com/08c1e536dede1ba73d414b8eed628030.jpg"],"type":0,
* "id":7621777,"ga_prefix":"121906","title":"瞎扯 · 如何正确地吐槽"}]
* top_stories : [{"image":"http://pic1.zhimg.com/202cf9520ddf666c19200009581814c0.jpg","type":0,"id":7611185,
* "ga_prefix":"121908","title":"《魂斗罗》中的角色,趴下的时候总是要「萝莉式屈腿俯卧」"},{"image":"http://pic3.zhimg
* .com/6c4ec13d0d48c0fabc06dd5ecbd9131a.jpg","type":0,"id":7615718,"ga_prefix":"121907",
* "title":"相比较其它地区,北京考生上清北有多大优势?"},{"image":"http://pic1.zhimg.com/33fe5a45ff8845089e714634da19790c.jpg","type":0,
* "id":7442302,"ga_prefix":"121821","title":"他的动画电影,走在幻想与现实的边界,好看得无话可说"},{"image":"http://pic3.zhimg
* .com/f14d5a1e088105123378951cf58dde76.jpg","type":0,"id":7620938,"ga_prefix":"121819",
* "title":"周末到了,推荐读读日报里的好文章,各位可要读一读"},{"image":"http://pic2.zhimg.com/5f56ecaaac226107710a0d15571b95f9.jpg","type":0,
* "id":7608078,"ga_prefix":"121817","title":"在黄河漂流是我干过最疯狂的事,有人上了船再也没能回来"}]
*/
private String date;
/**
* images : ["http://pic4.zhimg.com/9a79d6be3a24861e586c6eee89144d43.jpg"]
* type : 0
* id : 7619784
* ga_prefix : 121909
* title : 官员、银行家、高管……总觉得这些「精英」肯定信不过
*/
private List<StoriesEntity> stories;
private List<TopStoriesEntity> top_stories;
public void setDate(String date) {
this.date = date;
}
public void setStories(List<StoriesEntity> stories) {
this.stories = stories;
}
public void setTop_stories(List<TopStoriesEntity> top_stories) {
this.top_stories = top_stories;
}
public String getDate() {
return date;
}
public List<StoriesEntity> getStories() {
return stories;
}
public List<TopStoriesEntity> getTop_stories() {
return top_stories;
}
/**
* 界面顶部 ViewPager 滚动显示的内容
*/
public static class TopStoriesEntity {
private String image;
private int type;
private int id;
private String ga_prefix;
private String title;
public void setImage(String image) {
this.image = image;
}
public void setType(int type) {
this.type = type;
}
public void setId(int id) {
this.id = id;
}
public void setGa_prefix(String ga_prefix) {
this.ga_prefix = ga_prefix;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public int getType() {
return type;
}
public int getId() {
return id;
}
public String getGa_prefix() {
return ga_prefix;
}
public String getTitle() {
return title;
}
}
}
|
Java | UTF-8 | 1,086 | 2.359375 | 2 | [] | no_license | package me.littlekey.update;
import android.content.Context;
import android.text.TextUtils;
/**
* A class to hold global update configure.
* <p/>
* Created by nengxiangzhou on 16/4/13.
*
*/
public class UpdateConfig {
private static final String PREFS_UMENG_UPDATE = "update";
private static final String KEY_IGNORE_MD5S = "ignore";
private static boolean mUpdateForce = false;
public static void saveIgnoreMd5(Context context, String md5) {
context.getApplicationContext()
.getSharedPreferences(PREFS_UMENG_UPDATE, Context.MODE_PRIVATE)
.edit().putString(KEY_IGNORE_MD5S, md5).commit();
}
public static String getIgnoreMd5(Context context) {
String md5 = context.getApplicationContext()
.getSharedPreferences(PREFS_UMENG_UPDATE, Context.MODE_PRIVATE)
.getString(KEY_IGNORE_MD5S, null);
return TextUtils.isEmpty(md5) ? null : md5;
}
public static boolean isUpdateForce() {
return mUpdateForce;
}
public static void setUpdateForce(boolean mUpdateForce) {
UpdateConfig.mUpdateForce = mUpdateForce;
}
}
|
Markdown | UTF-8 | 1,526 | 3.703125 | 4 | [] | no_license | # 泛型和类型声明
## 泛型
在声明函数时不指定具体类型, 调用的时候再去指定
> 由于很多时候需要通用函数, 但是限制死参数过后, 函数就不够通用了, 因此我们需要将类型也变成一个统一的参数
如下:
```typeScript
// 但是这个函数只能创建数字类型的数组, 不能创建string类型的数组, 这一就不太行了
function createNumArr (lenght: number, vlaue: number): number[] {
return Array<number>(length).fill(value);
}
// 因此更合理的办法就是使用泛型, 就是将类型也变成参数
// 泛型就是使用一个尖括号, 一般使用T代表不明确的名称
function createArr<T> (length: number, value: T): T[] {
// Array是一个泛型类, 因此可以传递泛型参数, 调用时再去传递具体类型, 不指定泛型就是一个any类型的数组
const arr = Array<T>(length).fill(value);
return arr;
}
const res = createArr<string>(3, 'foo');
const numArr = createArr<number>(3, 100);
```
## 类型声明
实际开发过程中, 使用的第三方模块, 不一定使用ts写的, 因此他们可能没有类型校验。就会出现找不到类型声明的文件。
使用的时候也不会有任何的类型提示
因此需要使用类型声明
```typeScript
import {camelCase} from 'lodash';// 一般鼠标放上去, 就会告诉我们需要去安装对应地类型声明模块, .d.ts结尾, 专用于做类型声明
declare function camelCase;
const res = camelCase('hello android');
```
|
Markdown | UTF-8 | 8,871 | 2.8125 | 3 | [] | no_license | 一零二
白奇点头承认:
“十足收齐,我的规矩,向来不赊不欠,一次头尾付清。”
靳百器沉重的道:
“没有考虑的余地了么?”
白奇语声颇有憾意:
“我们这一行的情形与传统,相信你不会陌生,接下买卖,收过代价,就算一锤敲定,天皇老子也扭不回转,靳百器,坦白说我对你的印象蛮好,要不是承诺在先,这笔生意我可能会重新考虑……”
靳百器平静的道:
“见到你,觉得你并不像一般杀手那样形色狰狞,张牙舞爪,我才希望你再加斟酌;白奇‘大龙会’姓赵的买凶前来谋害于我,已不止一遭了,可是,事实摆在眼前,我活着,那些个杀手却阴阳转世去了。”
白奇有点不大高兴的道:
“他们是他们,我是我,靳百器,在我们这一行里,我是最好的,顶尖的,那些家伙只能算是业余一一另外一个事实也摆在眼前,我取过一百九十九只人耳,不是仍然活生生的站在这里?”
靳百器的双眸在夜色中闪着冷冽的芒彩,他慢慢的道:
“那么,你是决定了?”
白奇这一次的笑容有些不同了,在烂亮的笑意后面,竟蕴涵着令人足以感受得到的冷锐及狠酷:
“我说过,靳百器,这桩事已经一锤敲定,天皇老子也挽不回转,这是行规——尽管我内心里亦不无遗憾。”
点点头,靳百器道:
“也罢,不过我要特别提醒你,你那只坛子里的一百九十九只干腌人耳,可没有一只是我的耳朵,白奇,割我的耳朵不很容易。”
白奇笑道:
“我明白,我十分明白,而我一直也不会认为这件事会很容易。”
靳百器道:
“在你下手割取我的耳朵之前,还有句话想问你,不知你能否再给我一点时间?”
白奇一派大度的道:
“当然可以,隔着天亮尚有一阵子,不是么?”
靳百器道:
“请告诉我,你是怎么找来‘回雁坪’这个地方的?是从哪里得到线索,知道我隐匿于此?”
白奇略微踟蹰的道:
“这个问题,对你很重要么?”
靳百器严肃的道:
“非常重要。”
白奇耸耸肩膀,道:
“好吧,我便说予你听,讲起来也叫凑巧,原来我并不确知你的落脚处所,‘大龙会’提供给我的消息相当笼统,又指出你可能的活动范围是在距离‘西河大霸’‘燕子窝’周沿大约三至五百里的区域之内,你想想,三到五百里,加上东南西北的纵深,该是多大多宽的一片地方?‘大龙会’所提供的消息,严格论起来,不算有什么价值,但他们仅知道这么一点,再详尽的线索就没有了,而我既然接下买卖,拿人钱财,便得替人消灾,无奈何只好跑一趟……”
靳百器仔细的道:
“‘大龙会’何以根据我的藏身之处就在‘西河大霸’‘燕子窝”在近不远?莫非是以我们突击‘黑巾党’的事由做为推断?”
白奇笑道:
“完全正确,他们研判远兵不至攻坚,你们在目前颇为局促的情形下,犹敢敲了‘黑巾党’这么一记狠棍,可见集居之所必不太远,但话是这么说,没有一个准确的地点,不太远却又到哪里去找?虽不像大海捞针,也和大海捞针差不多了,我再三寻思,苦无良策,只有亲自查访,试着碰碰运气……”
靳百器道:
“看来,你的运气挺不错。”
白奇摇头道:
“不是我的运气不错,靳百器,似乎是你的运气不够好,否则,怎么会连八字都不见一撇的事居然就被我朦上了?”
靳百器道:
“这话是怎么说?”
白奇极有耐心的继续往下述说,模样不似面对死敌,倒像在同老友叙旧:
“自从离开‘天目山’,我先赶到‘西河大霸’‘燕子窝’,因‘黑巾党’的留守人马业已溃散,老窑变成了一片焦土,鬼影不见一个,想问问当时情形亦难找对象,忽然间,一切的路子好象全断了,我越累便越烦,几次寻思,真不打算干啦,就在这山穷水尽节骨眼上,哈,偏偏被我遇到一位贵人,靳百器,你猜猜那人是谁?”
靳百器道:
“我猜不出。”
白奇兴致勃勃的道:
“查三仞,你听说过这个人么?
“哦”了一声,靳百器道:
“‘大九雄’的首领‘银环套月’查三仞?”
哈哈一笑,白奇道:
“好见识,就是这老小子,我和查三仞虽说交情不深,但却合作过几次买卖,有点利害上的来往,平日里,彼此亦相处不恶,我碰上他的时候,正是他从‘落花荡’急匆匆赶往‘紫竹圩’的辰光,路经‘燕子窝’十里之外的一条驿道。恰巧就被坐在凉亭里喝茶的我看到了……
靳百器沉声问:
“查三仞只有一个人么?”
白奇伸出双手,只勾曲一只指头:
“怎会只有一人?‘大九雄’九条英雄好汉全来齐了;查三仞一看到我,也高兴得什么似的,三句话未话完,马上拉我帮他去“紫竹圩”讨价,哈,风流债加上人命债,是‘幻形七妖’欠的,那七个浪得虚名的窝囊废居然胆上生毛,在一次轰饮之后,竟把查三仞回门探亲的四姨太半路上给轮奸了,这还不说,奸而灭口,却又灭不干净,当堂跑掉了一名轿夫,这个轿夫回来一哭一诉,那七个杂碎便没有好日子过了,‘大九雄’的人马三番五次堵去‘落花荡’,非要佟继道他们七颗人头不可,七妖看看不是光景,最后只好落荒而逃,却不知怎的漏了行藏,被‘大九雄’摸得他们隐匿之处,‘燕子窝’驿道上碰头的时候,他们正是赶去追杀七妖……”
靳百器道:
“怕是迟了一步,杀不成了。”
白奇笑嘻嘻的道:
“正是杀不成了,我跟‘大九雄’从‘紫竹圩’又进到‘七星岩’那幢破烂樵屋,不见七妖半口活人,死尸倒有遍地,好家伙,真正一个不剩,只看到一个大小子在那里一面哭,一面准备收尸……”
靳百器轻轻的道:
“阿丁?”
白奇笑得更偷快了:
“不错,阿丁,用不着怎么唬,他已经一五一十细说了原委,我们才知道人是你和牟长山两个联手杀的,‘大九雄’跳了一顿脚,也只有悻悻离去,临行邀我,我却另有计较,拱手不陪啦。”
靳百器凝思着道:
“阿丁并不清楚我的住处……”
白奇双眼微眯,稍尖的下巴向前挺出:
“他不清楚,我可以另找人问,譬如说,‘紫竹圩’的‘大利钱庄’就是阿丁告诉我的一条好路子,而钱庄的萧掌柜亦不算什么铁打金刚,叫他开口吐实,并非难事,结果证明我的判断相当正确。”
靳百器道:
“在萧祥面前,我们也不曾露底,他又如何知晓?”
白奇有几分得意的道:
“你不曾露底,牟长山也不曾露底,但牟长山的手下人却不像二位这样守口如瓶,为了他儿子被掳的事,牟长山派遣过好几拨人去‘紫竹圩’及‘大利钱庄’明查暗访,言谈之间,分寸就拿捏得没那么准了。”
靳百器沉默片歇,才悠悠的道:
“也是劫数……”
白奇同情的道:
“可不,人算不如天算啊。”
劫数固劫数,但不知是谁的劫数?靳百器注视着眼前这位鼎鼎大名的江湖杀手,油然生起一股悲悯之念——对白奇,也对他自己。
于是,白奇不笑了,那种冷锐狠酷的气息又开始转为浓烈:
“前因后果,已经说清,靳百器,对我的陈述,希望你还满意。”
靳百器忽道:
“白奇,那叫阿丁的半桩小子,你没有收取他的性命吧?”
白奇似乎一时忘记阿丁是何许人了,眨眨眼,他始摇头道:
“我要他的命干什么?他就算求我割他一只耳朵,还不够格呢。”
抬脸望着黝黑的天空,靳百器像是对着虚无中的幽灵呢喃,声音极轻极轻:
“除开阿丁和‘大利钱庄’,的萧掌柜以外,白奇,尚有其他人知道你来‘回雁平’么?你曾否通知‘大龙会’你的发现?”
白奇正色道:
“一人做事一人当,我有我的行为准则,尽其在我,成败在天,又何须四通声气,予人以告援之疑?如果我连这些许承担都没有,至少‘大九雄’的朋友就可以光临来了替我帮场!”
|
PHP | UTF-8 | 2,711 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: compiler
* Date: 18-3-23
* Time: 下午8:40
*/
namespace app\api\controller\v1;
use app\api\controller\BaseController;
use app\api\model\UserAddressModel;
use app\api\model\UserModel;
use app\api\service\Token as TokenService;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;
class Address extends BaseController //为了使用tp5的前置方法,需要继承tp5基类 Controller。
{
protected $beforeActionList = [ //Controller 的成员变量
'checkPrimaryScope' => ['only'=>'createOrUpdateAddress,getUserAddress'] //执行 createOrUpdateAddress 之前先执行前置方法 checkPrimaryScope
];
// 该方法已提取到基类 BaseController
// protected function checkPrimaryScope(){
// $scope = TokenService::getCurrentTokenVar('scope');
// if ($scope){
// if ($scope >= ScopeEnum::User){
// return true;
// }else{
// throw new ForbiddenException();
// }
// }else{
// throw new TokenException();
// }
// }
public function getUserAddress(){
$uid = TokenService::getCurrentUid();
$userAddress = UserAddressModel::where('user_id',$uid) -> find();
if (!$userAddress){
throw new UserException([
'msg' => '用户地址不存在',
'errorCode' => 60001
]);
}
return $userAddress;
}
/**
* @return SuccessMessage
* @throws UserException
* @url bis.com/api/v1/address
*/
public function createOrUpdateAddress(){
//(new AddressNew()) ->goCheck();
$validate = new AddressNew();
$validate ->goCheck();
// 根据token来获取uid
// 根据uid来查找用户数据,判断用户是否存在,如果不存在则抛出异常
// 获取用户从客户端提交的地址信息
// 根据用户地址信息是否存在, 判断是新增地址还是更新地址
$uid = TokenService::getCurrentUid();
//return $uid;
$user = UserModel::get($uid);
if (!$user){
throw new UserException();
}
$dataArray = $validate->getDataByRule(input('post.')); //input('post.') 获取post 传过来的所有变量
$userAddress = $user->address; //这里address 是什么?
if (!$userAddress){
$user->address()->save($dataArray); //这里address() 是什么?
}else{
$user->address->save($dataArray); //注意address和address()的区别。
}
return json(new SuccessMessage(),201);
}
} |
Python | UTF-8 | 271 | 2.625 | 3 | [] | no_license | import sys
import requests
#print(sys.version)
print(sys.executable)
def greet(who_to_greet):
greeting = 'Hello, {}'.format(who_to_greet)
return greeting
print (greet('Life!'))
print(greet('Life!'))
r = requests.get('ht
tps://python.org')
print(r.status_code) |
Java | UTF-8 | 3,398 | 3.84375 | 4 | [] | no_license | package cn.skyjilygao.leetcode;
import java.util.Arrays;
/**
* 题目:给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
* <p> 说明:1. 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
* <br> 2. 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
* <p> Leetcode题: <a href="https://leetcode-cn.com/problems/merge-sorted-array"> 88. 合并两个有序数组 </a>
*
* @author skyjilygao
* @date 20201010
*/
public class MergeSortedArray {
public static void main(String[] args) {
// int[] nums1 = new int[]{0}; int len1 = 0; int[] nums2 = new int[]{1}; int len2 = 1;
int[] nums1 = new int[]{1,2,0,0,0,0}; int len1 = 2; int[] nums2 = new int[]{1,3,5,6}; int len2 = 4;
// int[] nums1 = new int[]{0,0}; int len1 = 0; int[] nums2 = new int[]{1,3}; int len2 = 2;
// int[] nums1 = new int[]{2,0}; int len1 = 1; int[] nums2 = new int[]{1}; int len2 = 1;
// int[] nums1 = new int[]{1,0}; int len1 = 1; int[] nums2 = new int[]{2}; int len2 = 1;
// int[] nums1 = new int[]{1, 2, 3, 0, 0, 0}; int len1 = 3; int[] nums2 = new int[]{}; int len2 = 0;
// int[] nums1 = new int[]{1, 2, 3, 0, 0, 0}; int len1 = 3; int[] nums2 = new int[]{2, 5, 6}; int len2 = 3;
// int[] nums1 = new int[]{1, 2, 3, 0, 0, 0}; int len1 = 3; int[] nums2 = new int[]{4, 5, 6}; int len2 = 3;
merge(nums1, len1, nums2, len2);
for (int n : nums1) {
System.out.print(n+"\t");
}
}
/**
* 思路1:临时数组 + 双指针
*
* <p> 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
* <p> 内存消耗:39 MB, 在所有 Java 提交中击败了44.55%的用户
* @param nums1
* @param m
* @param nums2
* @param n
*/
public static void merge1(int[] nums1, int m, int[] nums2, int n) {
int len = nums1.length;
int[] numsTmp = new int[len];
int i1,i2,it;
i1=i2=it=0;
while (i1<m && i2 <n) {
numsTmp[it++] = nums1[i1] < nums2[i2] ? nums1[i1++] : nums2[i2++];
}
if(i1 < m){
System.arraycopy(nums1, i1, numsTmp, it, m - i1);
}
if(i2 < n){
System.arraycopy(nums2, i2, numsTmp, it, n - i2);
}
System.arraycopy(numsTmp, 0, nums1, 0 , len);
}
/**
* 思路2:合并 + 排序
* <p> 执行用时:1 ms, 在所有 Java 提交中击败了23.75%的用户
* <p> 内存消耗:38.7 MB, 在所有 Java 提交中击败了90.99%的用户
* @param nums1
* @param m
* @param nums2
* @param n
*/
public static void merge2(int[] nums1, int m, int[] nums2, int n) {
System.arraycopy(nums2, 0, nums1, m, n);
Arrays.sort(nums1);
}
/**
* 思路3:双指针 + 倒序遍历
* @param nums1
* @param m
* @param nums2
* @param n
*/
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int len = nums1.length;
int i1 = m - 1;
int i2 = n - 1;
int i = len - 1;
while (i2 >=0 && i1 >= 0){
nums1[i--] = nums1[i1] < nums2[i2] ? nums2[i2--] : nums1[i1--];
}
System.arraycopy(nums2, 0, nums1, 0, i2 + 1);
}
}
|
Python | UTF-8 | 220 | 3.75 | 4 | [] | no_license | #replace() method
#find() method
string = ' she is beautiful and she is good dancer'
#print(string.replace('','_'))
print(string.replace('is','was',1))
pos_1 = string.find('is',)
print(string.find('is',pos_1+1))
|
JavaScript | UTF-8 | 1,616 | 2.625 | 3 | [] | no_license | function dump_model() {
var elemObjects = []
$("#main .component").each(function (idx, elem) {
var $elem = $(elem);
var nextElem = {
group : $elem.attr('group'),
type : $elem.attr('type'),
id: $elem.attr('id'),
title : $elem.text(),
fields : {},
x: parseInt($elem.css("left"), 10),
y: parseInt($elem.css("top"), 10)
}
nextElem.fields = loadModel(nextElem.id);
elemObjects.push(nextElem);
});
var connObjects = [];
$.each(jsPlumb.getConnections(), function (idx, connection) {
connObjects.push({
id: connection.id,
source: connection.sourceId,
target: connection.targetId
});
});
return JSON.stringify({
elements : elemObjects,
connections : connObjects
});
}
function load_model(jsonData) {
var data = JSON.parse(jsonData);
var elements = data.elements;
var connections = data.connections;
var createdElementMap = {};
for (var i = 0 ; i < elements.length; i++) {
var element = elements[i];
var divId = element.id;
var elementType = element.type;
addElement(divId, element.title, elementType, element.group);
setPosition(divId, element.x, element.y);
createdElementMap[divId] = configurePlumbElement(divId, getUIType(elementType));
saveModel(divId, element.fields);
}
for (var j = 0 ; j < connections.length; j++) {
var connection = connections[j];
var sourceEndpoint = createdElementMap[connection.source][0];
var targetEndpoint = createdElementMap[connection.target][1];
jsPlumb.connect({source:sourceEndpoint, target:targetEndpoint});
}
}
|
Markdown | UTF-8 | 1,607 | 2.671875 | 3 | [
"MIT"
] | permissive | ---
title: "Animal World"
category: "Education/Accessible Technology"
date: "2015"
order: 7
image: "../../images/animalworld-thumbnail@2x.jpg"
alt: "Kids Sensory Wall"
role: "Creative technologist"
tasks: "User centered design, circuit design, hardware design, fabrication, coding"
technology: "Arduino, Eagle, Othermill, Vectorworks, Laser cutter, capactive touch sensors, neopixels, small voltage motors"
---
Children with various disabilities crave sensory input, and there are many styles of rooms which assist with this needed stimulation. However, there is room for innovation. Combining elements of assistive technology, custom hardware, and digital fabrication, we set out to make a technology-heavy wall that would allow for a one-of-a-kind experience for children.
After extensive user-testing and ideating with our team and experts in therapy and technology, we used magnets to make solid electrical connections. Students can play with 11 different animals and move them where ever they’d like on the wall, but when they close connections where steel circles are present, that animals will illuminate, vibrate, make sounds, and spin. Flowers on the wall respond to hands being nearby, and the tree being touched allows for circuits to close. We opted for an animal theme through which therapists will be able to teach students about the animal kingdom.
<div class="iframeWrapper">
<iframe width="560" height="315" src="https://www.youtube.com/embed/N__qRoU-y7I" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
|
PHP | UTF-8 | 2,026 | 2.515625 | 3 | [] | no_license | <?php
namespace app\models;
use MongoDate;
class friends extends \Phalcon\Mvc\Collection
{
public $ts;
public $uid;
public $fid;
public function getSource()
{
return 'friends';
}
public function beforeCreate()
{
$this->ts = new MongoDate();
}
public function _exist($uid, $fid)
{
$friend = friends::findFirst(array(array('uid' => (int)$uid, 'fid' => (int)$fid)));
if ($friend)
{
return true;
} else
{
return false;
}
}
public function _create($uid, $fid, $fidKey)
{
$mongo = $this->getDI()->getShared('mongo');
if ($uid == $fid || $fid <= 0 || $fid == null)
return false;
$friend = new \stdClass();
$friend->ts = new MongoDate(); //$this->ts... is removed when phalcon bug is fixed
$friend->uid = (int)$uid;
$friend->fid = (int)$fid;
$friend->fidKey = $fidKey;
if ($mongo->friends->insert($friend)['ok'] == 1)
return true;
return false;
}
public function _delete($uid, $fid)
{
$friend = friends::findFirst(array(array('uid' => (int)$uid, 'fid' => (int)$fid)));
if (!$friend) return true;
if ($friend->delete())
return true;
return false;
}
public function _get($uid)
{
$mongo = $this->getDI()->getShared('mongo');
$friends = $mongo->friends->find(array('uid' => (int)$uid));
return iterator_to_array($friends, false);
}
} |
Java | UTF-8 | 501 | 3.25 | 3 | [] | no_license | package multithreading;
public class ThreadExample1 {
public static void main(String[] args) {
MyThreadClass t1 = new MyThreadClass();
MyThreadClass t2 = new MyThreadClass();
MyThreadClass t3 = new MyThreadClass();
MyThreadClass t4 = new MyThreadClass();
MyThreadClass t5 = new MyThreadClass();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class MyThreadClass extends Thread{
@Override
public void run() {
System.out.println("thread running man");
}
}
|
Java | UTF-8 | 1,958 | 2.984375 | 3 | [] | no_license | package cs3500.animator.model;
import java.util.Iterator;
import java.util.List;
/**
* A ExCellence Model interface that does not allow for any mutation.
*/
public interface ImmutableModel {
/**
* Access a list of IShapes that appear in the given time frame.
* INVARIANT: the shapes are returned in the order they should be rendered in the frame.
* @param time the time for which we would like to get the frame
* @return the list of shapes in the specified frame
*/
List<IShape> getFrame(int time);
/**
* Access the width of this model.
* @return an int representing the width
*/
int getWidth();
/**
* Access the height of this model.
* @return an int representing the height
*/
int getHeight();
/**
* Access the x coordinate location of this model.
* @return an int representing the x coordinate
*/
int getX();
/**
* Access the y coordinate of location of this model.
* @return an int representing the y coordinate
*/
int getY();
/**
* Return an iterator that will progress over all this model's shapes alphabetically.
* @return the iterator
*/
Iterator<IShape> getShapes();
/**
* Return an iterator that will progress over all the KeyFrames for the given shape in order
* of starting time.
* @param shape the shape to get the animations from.
* @return the iterator
*/
Iterator<IKeyFrame> getAnimationsFrom(IShape shape);
/**
* Return an iterator of all the layers within the animation.
* @return the layers.
*/
Iterator<Integer> getLayers();
/**
* Gets all the shapes based on the given layer.
* @param layer the layer
* @return the shapes in the given layer.
*/
Iterator<IShape> getShapesAt(Integer layer);
/**
* Accesses the end time of the animation. This is considered to be the last point in time with
* an existing keyframe.
* @return the end time of this model
*/
int getEndTime();
}
|
Python | UTF-8 | 562 | 4.28125 | 4 | [] | no_license | # Replacing all 'my_x' type variable names with 'x' - shorter names
name = 'Zed A. Shaw'
age = 35 # years
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usually {teeth} depending on the coffee.")
# tricky line
total = age + height + weight
print(f"If I add {age}, {height}, and {weight}, I get {total}.")
|
PHP | UTF-8 | 743 | 2.609375 | 3 | [] | no_license | <?php
namespace Bluegrass\Blues\Component\Widget\View;
use Bluegrass\Blues\Component\View\ViewModel;
/**
* Representa una estructura con la información necesaria para ser
* representada en una vista de un widget.
*
* @author ldelia
*/
class WidgetViewModel extends ViewModel
{
public function getTemplate()
{
return $this->get( 'template' );
}
public function setTemplate( $template )
{
$this->set( 'template', $template );
}
public function getBlockName()
{
return $this->get( 'blockName' );
}
public function setBlockName( $blockname )
{
$this->set( 'blockName', $blockname );
}
}
|
Python | UTF-8 | 370 | 3.625 | 4 | [] | no_license | import random
import time
def rand_boo():
rand_num = random.randint(0,10)
time.sleep(int(rand_num))
print("boo")
def rand_trt():
rand_numb = random.randint(1,2)
if rand_numb == 1:
print("TRICK")
if rand_numb == 2:
print("TREAT")
def string(sentence):
full_sentence = ("spooky" + str(sentence))
print(full_sentence)
|
JavaScript | UTF-8 | 565 | 3.1875 | 3 | [] | no_license | const eventsURL = "cckoga.json"
fetch(eventsURL)
.then ((response)=>response.json())
.then ((jsObject)=>{
const events = jsObject['events'];
for (let i = 1; i<4; i++){
let name = document.createElement('h3');
name.textContent = events[i].name;
let div = document.createElement('div');
div.className = "eventitem";
const img = document.createElement('img');
let imgurl = events[i].imgurl;
img.setAttribute('src', imgurl);
img.setAttribute('alt', name);
img.style.display = 'block';
div.append(img,name);
document.querySelector('.events').appendChild(div);
}
}); |
C# | UTF-8 | 1,511 | 2.703125 | 3 | [
"MIT"
] | permissive | namespace WDModernise.Core
{
public class WDSentinelLowLevel : IWDSentinel
{
/*
* This class does not work yet.
*
* The intent of the Low Level class is to write a complete implementation of the communication with the hardware components of
* the NAS. We don't want to use any WD DLLs here, and instead write as much as possible, using only Open Source libraries which
* are under or compatible with the MIT license this software uses, and even then the less libraries that are used the better.
*
* If someone is able to write this Low Level implementation, that would be awesome!
*/
public void Dispose()
{
throw new System.NotImplementedException();
}
public void InitialiseLcd()
{
throw new System.NotImplementedException();
}
public void ClearLcd()
{
throw new System.NotImplementedException();
}
public void SetLcdContrast(int contrast)
{
throw new System.NotImplementedException();
}
public void SetLcdLineOne(string line)
{
throw new System.NotImplementedException();
}
public void SetLcdLineTwo(string line)
{
throw new System.NotImplementedException();
}
public void SetSystemFanSpeed(int speed)
{
throw new System.NotImplementedException();
}
}
}
|
TypeScript | UTF-8 | 4,786 | 2.625 | 3 | [] | no_license | import { Expr, ExprArg } from 'faunadb'
/*
* Ideally we limit the amount of calls that come to Login.
*/
const faunadb = require('faunadb')
const q = faunadb.query
const {
If,
Epoch,
Match,
Index,
Update,
Collection,
Let,
Var,
Paginate,
Select,
TimeDiff,
Or,
GTE,
Abort,
Create,
IsEmpty,
Count,
LT,
Do,
Now,
And,
Not,
Equals,
} = q
const rateLimitingConfig = {
get_fweets: {
calls: 5,
perSeconds: 60 * 1000,
},
get_fweets_by_tag: {
calls: 5,
perSeconds: 60 * 1000,
},
get_fweets_by_author: {
calls: 5,
perSeconds: 60 * 1000,
},
create_fweet: {
calls: 5,
perSeconds: 300 * 1000, // one fweet a minute please (5 per 5 minutes)
},
login: {
calls: 3, // login will be reset by a succesful login.
perSeconds: 0,
},
// A global register limit to protect against bots creating many users
register: {
calls: 10, // 10 users per 10 minutes
perSeconds: 10 * 1000,
},
}
const getRateLimitingConf = (action: string) => {
const conf = rateLimitingConfig[action as keyof typeof rateLimitingConfig]
if (conf) {
return conf
} else {
throw new Error(`No rate limiting configuration defined (or passed) for ${action}
Either define it in the config or pass it to the AddRateLimiting function`)
}
}
// This function shows that you can add complex logic within FQL without a problem and
// Completely abstract it away. For example here we are adding Rate limiting by wrapping it around any other
// FQL function that we pass in. FQL is a powerful programming language.
function AddRateLimiting(
action: string,
Identifier: ExprArg,
FqlQueryToExecute: Expr,
calls?: number,
perSeconds?: number
) {
const conf =
calls !== undefined && perSeconds !== undefined
? { calls, perSeconds }
: getRateLimitingConf(action)
return Let(
{
rateLimitingPage: Paginate(
Match(Index('rate_limiting_by_action_and_identity'), action, Identifier)
),
},
If(
// Check whether there is a value
IsEmpty(Var('rateLimitingPage')),
// THEN: we store the initial data. Since our collection has a Time To Live set to one day.
// older data will be automatically reclaimed (e.g. users that don't use the application anymore)
Do(
Create(Collection('rate_limiting'), {
data: {
action: action,
identity: Identifier,
},
}),
FqlQueryToExecute
),
// ELSE: we actually retrieve a page of the last X events for this rate limiting entry, take the first (the oldest of this page)
// and verify whether they are long enough ago to allow another call.
VerifyRateLimitingAndUpdate(
action,
conf.calls,
conf.perSeconds,
FqlQueryToExecute,
Identifier
)
)
)
}
function VerifyRateLimitingAndUpdate(
action: string,
numberOfEvents: number,
maxAgeInMs: number,
FqlQueryToExecute: Expr,
Identifier: ExprArg
) {
return Let(
// We split up the calculation for educational purposes. First we get the first X events of the ratelimiting entry in reverse order (before: null does that)
{
eventsPage: Paginate(
q.Events(Select(['data', 0], Var('rateLimitingPage'))),
{
size: numberOfEvents,
before: null,
}
),
page: Select(['data'], Var('eventsPage')),
// then we retrieve the first element of that page. If X would be 3, it would be the 3th oldest event
firstEventOfPage: Select([0], Var('page')),
// then we get the timestamp of the event
timestamp: Select(['ts'], Var('firstEventOfPage')),
// transform the Fauna timestamp to a Time object
time: Epoch(Var('timestamp'), 'microseconds'),
// How long ago was that event in ms
ageInMs: TimeDiff(Var('time'), Now(), 'milliseconds'),
},
If(
// if there are 'numberOfEvents' timestamps in the page, take the first of the page and see if it is old enough
// If maxAgeInMs is 0 we don't care about the time, something in the FqlQueryToExecute will reset
// delete the rate-limiting events in order to reset (e.g. useful for max 3 faulty logins).
Or(
LT(Count(Var('page')), numberOfEvents),
And(Not(Equals(0, maxAgeInMs)), GTE(Var('ageInMs'), maxAgeInMs))
),
// Then great we update
Do(
Update(Select(['document'], Var('firstEventOfPage')), {
data: {
action: action,
identity: Identifier,
},
}),
FqlQueryToExecute
),
// Else.. Abort! Rate-limiting in action
Abort('Rate limiting exceeded for this user/action')
)
)
}
export { AddRateLimiting }
|
Java | UTF-8 | 1,705 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | package net.ssehub.easy.varModel.cst;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import net.ssehub.easy.varModel.model.datatypes.IntegerType;
import net.ssehub.easy.varModel.model.datatypes.OclKeyWords;
import net.ssehub.easy.varModel.model.values.Value;
import net.ssehub.easy.varModel.model.values.ValueDoesNotMatchTypeException;
import net.ssehub.easy.varModel.model.values.ValueFactory;
/**
* Tests the {@link Comment} class.
* @author El-Sharkawy
*
*/
public class CommentTest {
private ConstraintSyntaxTree cst;
private Comment comment;
private String commentText;
/**
* Initializes objects needed for testing.
* @throws ValueDoesNotMatchTypeException Must not occur, otherwise {@link ValueFactory} is broken.
*/
@Before
public void setUp() throws ValueDoesNotMatchTypeException {
Value intValue = ValueFactory.createValue(IntegerType.TYPE, "1");
ConstantValue constValue = new ConstantValue(intValue);
cst = new OCLFeatureCall(constValue, OclKeyWords.PLUS, constValue);
commentText = "1 + 1";
comment = new Comment(cst, commentText);
}
/**
* Tests whether the comment has the same behavior as the nested elements.
*/
@Test
public void testEqualityOfNestedElements() {
Assert.assertSame(cst, comment.getExpr());
Assert.assertEquals(cst.hashCode(), comment.getExpr().hashCode());
Assert.assertEquals(commentText.hashCode(), comment.getComment().hashCode());
Assert.assertFalse(comment.equals(cst));
Assert.assertNotSame(cst, comment);
Assert.assertSame(commentText, comment.getComment());
}
}
|
Java | UTF-8 | 693 | 3.53125 | 4 | [] | no_license | package util;
/**
* Created with IntelliJ IDEA.
* User: melvinj
* Date: 12/17/14
* Time: 12:03 AM
* A utility class to help print different data structures
*/
public class PrintUtils {
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + "\t");
}
System.out.println();
}
public static void printLinkedList(ListNode root) {
if (root == null) {
return;
}
if (root.next == null) {
System.out.println(root.val);
return;
}
while(root.next != null) {
System.out.print(root.val + " --> ");
root = root.next;
}
System.out.println(root.val);
}
}
|
PHP | UTF-8 | 10,149 | 2.875 | 3 | [] | no_license | <?php
namespace CIOS ;
class StarDate
{
public $Stardate ;
function __construct( $SDT = 0 )
{
$this -> StarDate ( $SDT ) ;
}
function __destruct()
{
}
public function StarDate ( $SDT )
{
if ( is_a ( $SDT , "CIOS\StarDate" ) ) {
$this -> Stardate = $SDT -> Stardate ;
} else {
$this -> Stardate = $SDT ;
} ;
}
public function setSD($SD)
{
$this -> StarDate ( $SDT ) ;
}
public function isValid()
{
return ( $this -> Stardate > 0 ) ;
}
// unix timestamp to stardate
public function setTime($T)
{
$this -> Stardate = $T + 1420092377704080000 ;
return $this -> Stardate ;
}
public function Seconds($D,$H,$M,$S)
{
return $this -> Days ( $D ) +
$this -> Hours ( $H ) +
$this -> Minutes ( $M ) +
$S ;
}
public function Minutes($M)
{
return ( $M * 60 ) ;
}
public function Hours($H)
{
return ( $H * 3600 ) ;
}
public function Days($D)
{
return ( $D * 84600 ) ;
}
public function Add($S)
{
$this -> Stardate += $S ;
return $this -> Stardate ;
}
public function AddDuration($S)
{
$SS = explode ( ":" , $S ) ;
$TT = 0 ;
$CNT = count ( $SS ) ;
if ( $CNT > 0 ) {
$II = 0 ;
while ( $II < $CNT ) {
$TT = $TT * 60 ;
$XX = $SS [ $II ] ;
$XX = intval ( $XX , 10 ) ;
$TT = $TT + $XX ;
$II = $II + 1 ;
} ;
$this -> Add ( $TT ) ;
} ;
return $this -> Stardate ;
}
public function Subtract($S)
{
$this -> Stardate -= $S ;
return $this -> Stardate ;
}
public function Now()
{
return $this -> setTime ( time ( ) ) ;
}
// stardate to unix timestamp
public function Timestamp()
{
return intval ( $this -> Stardate - 1420092377704080000 , 10 ) ;
}
public function secondsTo($SD)
{
return ( $SD -> Stardate - $this -> Stardate ) ;
}
public function fromDateTime($DT)
{
return $this -> setTime ( $DT -> getTimestamp ( ) ) ;
}
public function fromFormat($dtString,$TZ="")
{
if ( strlen ( $TZ ) > 0 ) {
$TX = new \DateTimeZone ( $TZ ) ;
$DT = \DateTime::createFromFormat ( "Y/m/d H:i:s" , $dtString , $TX ) ;
} else {
$DT = \DateTime::createFromFormat ( "Y/m/d H:i:s" , $dtString ) ;
} ;
return $this -> fromDateTime ( $DT ) ;
}
public function fromInput($inpString,$TZ="")
{
$dtxString = str_replace ( "T" , " " , $inpString ) ;
$dtxString = str_replace ( "-" , "/" , $dtxString ) ;
$cnt = substr_count ( $dtxString , ":" ) ;
if ( $cnt == 1 ) $dtxString = $dtxString . ":00" ;
return $this -> fromFormat ( $dtxString , $TZ ) ;
}
public function ShrinkMinute()
{
$TS = $this -> Timestamp ( ) ;
$TS = $TS % 60 ;
$this -> Subtract ( $TS ) ;
}
public function ShrinkHour()
{
$TS = $this -> Timestamp ( ) ;
$TS = $TS % 3600 ;
$this -> Subtract ( $TS ) ;
}
public function toDateTime($TZ)
{
$TX = new \DateTimeZone ( $TZ ) ;
$DT = new \DateTime ( ) ;
$DT -> setTimezone ( $TX ) ;
$DT -> setTimestamp ( $this -> Timestamp ( ) ) ;
unset ( $TX ) ;
return $DT ;
}
public function Weekday($TZ)
{
$DT = $this -> toDateTime ( $TZ ) ;
$WD = $DT -> format ( "N" ) ;
////////////////////////////////////////
unset ( $DT ) ;
////////////////////////////////////////
return intval ( $WD , 10 ) ;
}
public function isPM($TZ)
{
$DT = $this -> toDateTime ( $TZ ) ;
$HD = $DT -> format ( "G" ) ;
////////////////////////////////////////
unset ( $DT ) ;
////////////////////////////////////////
$HD = intval ( $HD , 10 ) ;
////////////////////////////////////////
return ( $HD < 12 ) ? 0 : 1 ;
}
public function toDateString($TZ,$FMT="Y/m/d")
{
$DT = $this -> toDateTime ( $TZ ) ;
$DS = $DT -> format ( $FMT ) ;
unset ( $DT ) ;
return $DS ;
}
public function toTimeString($TZ,$FMT="H:i:s")
{
$DT = $this -> toDateTime ( $TZ ) ;
$DS = $DT -> format ( $FMT ) ;
unset ( $DT ) ;
return $DS ;
}
public function toDateTimeString($TZ,$JOIN="T",$DateFormat="Y-m-d",$TimeFormat="H:i:s")
{
$DX = $this -> toDateTime ( $TZ ) ;
$DS = $DX -> format ( $DateFormat ) ;
$DT = $DX -> format ( $TimeFormat ) ;
unset ( $DX ) ;
return $DS . $JOIN . $DT ;
}
public function toLongString($TZ,$DateFormat="Y-m-d",$TimeFormat="H:i:s")
{
$Correct = true ;
////////////////////////////////////////////////////////////////////////////
if ( isset ( $GLOBALS [ "WeekDays" ] ) ) {
$WeekDays = $GLOBALS [ "WeekDays" ] ;
} else $Correct = false ;
////////////////////////////////////////////////////////////////////////////
if ( isset ( $GLOBALS [ "AMPM" ] ) ) {
$AMPM = $GLOBALS [ "AMPM" ] ;
} else $Correct = false ;
////////////////////////////////////////////////////////////////////////////
if ( $Correct ) {
$SW = $WeekDays [ $this -> Weekday ( $TZ ) ] ;
$SP = $AMPM [ $this -> isPM ( $TZ ) ] ;
$SJ = " {$SW} {$SP} " ;
} else $SJ = " " ;
////////////////////////////////////////////////////////////////////////////
return $this -> toDateTimeString ( $TZ , $SJ , $DateFormat , $TimeFormat ) ;
}
// php time format calcuation
public function Calculate($DTS)
{
$this -> setTime ( strtotime ( $DTS , $this -> Timestamp ( ) ) ) ;
}
public function SecondsOfDay($TZ)
{
$DX = $this -> toDateString ( $TZ , "Y-m-d" ) ;
$DX = "{$DX}T00:00:00" ;
$XS = new StarDate ( ) ;
$XS -> Stardate = $XS -> fromInput ( $DX ) ;
$XV = $XS -> secondsTo ( $this ) ;
$XV = intval ( (string) $XV , 10 ) ;
return $XV ;
}
// calcuate a person's age
public function YearsOld($TZ)
{
$TDT = $this -> toDateTime ( $TZ ) ;
$NDT = new \DateTime ( ) ;
$DIF = $NDT -> diff ( $TDT ) ;
return $DIF -> y ;
}
public static function StarDateToString($DT,$Tz,$FMT)
{
$SD = new StarDate ( ) ;
$SD -> Stardate = $DT ;
$DX = $SD -> toDateTime ( $Tz ) ;
$SS = $DX -> format ( $FMT ) ;
///////////////////////////////////
unset ( $SD ) ;
unset ( $DX ) ;
///////////////////////////////////
return $SS ;
}
public static function StarDateString($DT,$FMT)
{
$Tz = TimeZones::GetTZ ( ) ;
return self::StarDateToString ( $DT , $Tz , $FMT ) ;
}
public static function UntilToday($DATE,$TZ,$YEARSTR,$MONTHSTR)
{
//////////////////////////////////////////////////////
if ( strlen ( $DATE ) <= 0 ) return "" ;
$NOW = new StarDate ( ) ;
$NOW -> Now ( ) ;
//////////////////////////////////////////////////////
$XXXZ = $NOW -> toDateString ( $TZ , "Y-m-d" ) ;
$DATE = str_replace ( "/" , "-" , $DATE ) ;
//////////////////////////////////////////////////////
$ZZZ = explode ( "-" , $DATE ) ;
$WWW = explode ( "-" , $XXXZ ) ;
//////////////////////////////////////////////////////
$YYY = intval ( $WWW [ 0 ] , 10 ) ;
$YYY -= intval ( $ZZZ [ 0 ] , 10 ) ;
//////////////////////////////////////////////////////
$MMM = intval ( $WWW [ 1 ] , 10 ) ;
$MMM -= intval ( $ZZZ [ 1 ] , 10 ) ;
//////////////////////////////////////////////////////
$DDD = intval ( $WWW [ 2 ] , 10 ) ;
$DDD -= intval ( $ZZZ [ 2 ] , 10 ) ;
//////////////////////////////////////////////////////
if ( $DDD < 0 ) $MMM = $MMM - 1 ;
if ( $MMM < 0 ) {
$MMM = $MMM + 12 ;
$YYY = $YYY - 1 ;
} ;
//////////////////////////////////////////////////////
$YST = str_replace ( "$(TOTAL)" , $YYY , $YEARSTR ) ;
$MST = str_replace ( "$(TOTAL)" , $MMM , $MONTHSTR ) ;
$MSG = "" ;
if ( $YYY > 0 ) $MSG = $MSG . $YST ;
if ( $MMM > 0 ) $MSG = $MSG . $MST ;
if ( strlen ( $MSG ) <= 0 ) $MSG = "0" ;
//////////////////////////////////////////////////////
return $MSG ;
}
//////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////
?>
|
Python | UTF-8 | 3,081 | 3.4375 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
"""TcEx Framework Redis Module"""
from builtins import str
import redis
class TcExRedis(object):
"""Create/Read Data in/from Redis"""
def __init__(self, host, port, rhash):
"""Initialize the Class properties.
Args:
host (string): The Redis host.
port (string): The Redis port.
rhash (string): The rhash value.
"""
self.hash = rhash
self.r = redis.StrictRedis(host=host, port=port)
def blpop(self, keys, timeout=30):
"""RPOP a value off the first empty list in keys.
.. note:: If timeout is 0, the block indefinitely.
Args:
keys (string|list): The key(s) to pop the value.
timeout (int): The number of seconds to wait before blocking stops.
Returns:
(string): The response from Redis.
"""
return self.r.blpop(keys, timeout)
def create(self, key, value):
"""Create key/value pair in Redis.
Args:
key (string): The key to create in Redis.
value (any): The value to store in Redis.
Returns:
(string): The response from Redis.
"""
return self.r.hset(self.hash, key, value)
def delete(self, key):
"""Alias for hdel method."""
return self.hdel(key)
def hdel(self, key):
"""Delete data from Redis for the provided key.
Args:
key (string): The key to delete in Redis.
Returns:
(string): The response from Redis.
"""
return self.r.hdel(self.hash, key)
def hget(self, key):
"""Read data from Redis for the provided key.
Args:
key (string): The key to read in Redis.
Returns:
(any): The response data from Redis.
"""
data = self.r.hget(self.hash, key)
if data is not None and not isinstance(data, str):
data = str(self.r.hget(self.hash, key), 'utf-8')
return data
def hgetall(self):
"""Read data from Redis for the provided key.
Args:
key (string): The key to read in Redis.
Returns:
(any): The response data from Redis.
"""
return self.r.hgetall(self.hash)
def hset(self, key, value):
"""Create key/value pair in Redis.
Args:
key (string): The key to create in Redis.
value (any): The value to store in Redis.
Returns:
(string): The response from Redis.
"""
return self.r.hset(self.hash, key, value)
def read(self, key):
"""Alias for hget method."""
return self.hget(key)
def rpush(self, name, values):
"""Append/Push values to the end of list ``name``.
Args:
name (string): The channel/name of the list.
timeout (int): The number of seconds to wait before blocking stops.
Returns:
(string): The response from Redis.
"""
return self.r.rpush(name, values)
|
Java | UTF-8 | 348 | 1.976563 | 2 | [] | no_license | package br.com.agendaAPI.service.exceptions;
public class ContactNotFound extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 2426058236132643557L;
public ContactNotFound(String mensagem) {
super(mensagem);
}
public ContactNotFound(String mensagem, Throwable error) {
super(mensagem, error);
}
}
|
JavaScript | UTF-8 | 495 | 2.546875 | 3 | [
"ISC"
] | permissive | 'use strict'
const humanizeNumber = require('humanize-number')
const pluralize = require('pluralize')
module.exports = (benchmark) => {
const ops = benchmark.hz // Can be null on the first run if it executes really quickly
? humanizeNumber(benchmark.hz.toFixed(benchmark.hz < 100 ? 2 : 0))
: 0
const marginOfError = benchmark.stats.rme.toFixed(2)
const runs = pluralize('run', benchmark.stats.sample.length, true)
return `${ops} ops/sec ±${marginOfError}% (${runs} sampled)`
}
|
Python | UTF-8 | 4,358 | 3.3125 | 3 | [] | no_license | import numpy as np
import itertools
import networkx as nx
import matplotlib.pyplot as plt
# Tested on Python 3.5, use with Python 3+
class UndirectedErdosRenyi:
def __init__(self, num_vertices, p_edge, rand_low, rand_high):
self.num_vertices = num_vertices
self.adjacency_matrix = [ [ None for j in range(num_vertices) ] for i in range(num_vertices) ]
random_matrix = np.random.rand(num_vertices, num_vertices)
for row_number, row in enumerate(random_matrix):
for column_number, rand_matrix_entry in enumerate(row):
if column_number == row_number:
self.adjacency_matrix[row_number][column_number] = 0
elif rand_matrix_entry < p_edge:
rand_int = np.random.randint(rand_low, rand_high)
self.adjacency_matrix[row_number][column_number] = rand_int
self.adjacency_matrix[column_number][row_number] = rand_int
else:
self.adjacency_matrix[row_number][column_number] = 0
self.adjacency_matrix[column_number][row_number] = 0
self.connected_bool = nx.is_connected(nx.from_numpy_matrix(np.array(self.adjacency_matrix)))
def draw_graph(self):
nx_matrix = nx.from_numpy_matrix(np.array(self.adjacency_matrix))
all_weights = []
pos = nx.circular_layout(nx_matrix)
for (node1, node2, data) in nx_matrix.edges(data=True):
all_weights.append(data['weight'])
unique_weights = list(set(all_weights))
for weight in unique_weights:
weighted_edges = [(node1, node2) for (node1, node2, edge_attr) in nx_matrix.edges(data=True) if
edge_attr['weight'] == weight]
width = weight
nx.draw_networkx_edges(nx_matrix, pos, edgelist=weighted_edges, width=width)
nx.draw_networkx(nx_matrix, pos, cmap=plt.get_cmap('jet'), node_color=range(self.num_vertices))
plt.axis('off')
plt.title('Connected graph with {:d} nodes'.format(self.num_vertices))
plt.show()
if self.connected_bool:
T = nx.algorithms.minimum_spanning_tree(nx_matrix)
all_weights = []
for (node1, node2, data) in T.edges(data=True):
all_weights.append(data['weight'])
unique_weights = list(set(all_weights))
for weight in unique_weights:
weighted_edges = [(node1, node2) for (node1, node2, edge_attr) in T.edges(data=True) if
edge_attr['weight'] == weight]
width = weight
nx.draw_networkx_edges(T, pos, edgelist=weighted_edges, width=width)
nx.draw_networkx(T, pos, cmap=plt.get_cmap('jet'), node_color=range(self.num_vertices))
plt.axis('off')
plt.title("Minimum Spanning Tree")
plt.show()
# https://stackoverflow.com/questions/2429098/how-to-treat-the-last-element-in-list-differently-in-python
def notlast(itr):
itr = iter(itr) # ensure we have an iterator
prev = itr.__next__()
for item in itr:
yield prev
prev = item
def main():
# Erdos Renyi graph will be connected almost surely if p_edge > ln(num_vertices)/num_vertices
num_vertices = 10
p_edge = .5 # prob of an edge 0 <= p_edge <= 1
rand_low = 1 # random weight for edge low bbound
rand_high = 10 # random weight for edge high bound
draw_graph = True
print_to_file = False
if print_to_file:
f1 = open('graph_output.txt', 'w+') # Change to None for not output file
else:
f1 = None
while True:
random_graph = UndirectedErdosRenyi(num_vertices, p_edge, rand_low, rand_high)
if random_graph.connected_bool:
print('int adj_matrix[{:d}][{:d}] = {{'.format(num_vertices, num_vertices), file=f1)
for row in random_graph.adjacency_matrix:
print("{", end='', file=f1)
for item in notlast(row):
print("{:d}".format(item), end=", ", file=f1)
print("{:d}".format(row[-1]), end="}, ", file=f1)
print("", file=f1)
print('};', file=f1)
break
if draw_graph:
random_graph.draw_graph()
if __name__ == "__main__":
main()
|
JavaScript | UTF-8 | 2,238 | 2.6875 | 3 | [
"MIT"
] | permissive | import fs from 'fs';
import path from 'path';
import semver from 'semver';
/**
* @param {Object} request {name: ?, scope: ?, version: ?}
* @param {Function} getPackageJson get package.json
* @param {Function} updatePackageJson update package.json
* @param {Function} removePackage remove package
* @param {String} storageLocation storage location
* @return {Boolean} package removed
*/
export default function (request,
getPackageJson,
updatePackageJson,
removePackage,
storageLocation) {
return new Promise((resolve, reject) => {
let packageName = request.name;
let packageScope = request.scope;
let packageVersion = request.version;
let packageLocation = path.join(storageLocation, packageName);
let tarballLocation = path.join(packageLocation, packageName + packageVersion + '.tgz');
fs.exists(packageLocation + '/package.json', (exists) => {
if (!exists) {
reject("Invalid request, aborting");
}
// location is valid
fs.unlink(tarballLocation, () => {
let packageJson = getPackageJson({
name: packageName,
scope: packageScope
}).then(() => {
delete (packageJson.versions[packageVersion]);
// If this was the last version of the package, we can remove it completely
if (packageJson.versions.size === 0) {
removePackage({
name: packageName,
scope: packageScope
});
return true;
}
if (packageJson['dist-tags'].latest === packageVersion) {
// need to update dist-tags
let highestVersion = '0.0.1';
for (let key in packageJson.versions) {
if (semver.satisfies(key, '>' + highestVersion)) {
highestVersion = key;
}
}
packageJson['dist-tags'].latest = highestVersion;
}
updatePackageJson({
name: packageName,
scope: packageScope
}, packageJson)
.then((result) => {
resolve(result);
});
});
});
});
});
} |
Rust | UTF-8 | 1,332 | 3.09375 | 3 | [] | no_license | pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl Solution {
pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
let mut i = 0;
let mut result = 0;
while let Some(&num) = nums.get(i) {
if num == 0 {
i += 1;
} else {
let start = i;
i += 1;
loop {
if let Some(&num) = nums.get(i) {
if num == 0 {
result = result.max(i - start);
i += 1;
break;
}
i += 1;
} else {
return result.max(i - start) as _;
}
}
}
}
result as _
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
Self::find_max_consecutive_ones(nums)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
|
Python | UTF-8 | 881 | 2.953125 | 3 | [] | no_license | import pymysql as pm
try:
con = pm.connect(host='localhost', database='acadviewdb',\
user='root', password='root')
cursor = con.cursor()
query = 'create table zipcode(zipcodeid int(5) primary key, \
state varchar(10), city varchar(4)'
cursor.execute(query)
print('Table created successfully!!')
"""query = "insert into zipcode(zipcodeid, state, city) \
values(%s, %s, %s, %s)"
records = [(1, 'abc', 'aaa' )
(2, 'def', 'sss')
(3, 'ghi', 'ddd')]
cursor.executemany(query, records)
con.commit()"""
except pm.DatabaseError as e:
if con:
con.rollback()
print('Problem occured: ', e)
finally:
if cursor:
cursor.close()
if con:
con.close()
print('DONE!!')
|
Java | UTF-8 | 801 | 3.21875 | 3 | [] | no_license | package com.dsalgo;
/**
* Created with IntelliJ IDEA.
* User: saikat
* Date: 8/10/13
* Time: 2:16 PM
* To change this template use File | Settings | File Templates.
*/
public class ArithmaticSequence {
public static void main(String[] args){
int[] a = {2,5,3,6,9,12,15,34,23};
findMaxArithmaticSequence(a);
}
static void findMaxArithmaticSequence(int[] a){
int maxSeq=0;
int diff = 0;
int curDiff = 0;
int curSeq = 0;
for(int i=1;i<a.length;i++){
curDiff = a[i]-a[i-1];
if(diff==curDiff){
curSeq++;
maxSeq = curSeq;
}else{
curSeq=0;
diff=curDiff;
}
}
System.out.print(maxSeq+1);
}
}
|
PHP | UTF-8 | 608 | 2.78125 | 3 | [] | no_license | <?php
/**
* Description of sfWidgetFormChoiceBooleanRadio
* Widget affichant plusieurs radio buttons en une ligne (utilise une classe css)
* @author William
*/
class gridWidgetFormChoiceRadioAligne extends sfWidgetFormChoice{
public function __construct($options = array(), $attributes = array()) {
if (!array_key_exists('expanded', $options)){
$options['expanded'] = true;
}
if (!array_key_exists('renderer_options', $options)){
$options['renderer_options'] = array('class' => 'radio_liste_horizontale');
}
parent::__construct($options, $attributes);
}
}
?>
|
C++ | UTF-8 | 310 | 2.515625 | 3 | [] | no_license | #ifndef _STRING_CONVERT_H
#define _STRING_CONVERT_H
#include <string>
class StringConvert
{
public:
static int StringToInt(std::string strValue);
static std::string IntToString(long nValue);
static bool StringToBool(std::string strValue);
static std::string BoolToString(const bool bValue);
};
#endif
|
C++ | UTF-8 | 895 | 2.734375 | 3 | [] | no_license | #ifndef NAMEDBEANUSERNAMECOMPARATOR_H
#define NAMEDBEANUSERNAMECOMPARATOR_H
#include "comparatort.h"
#include "alphanumcomparator.h"
template<class B>
class NamedBeanUserNameComparator : public ComparatorT<B>
{
public:
NamedBeanUserNameComparator() {}
/*public*/ int compare(B n1, B n2) {
QString s1 = n1->getUserName();
QString s2 = n2->getUserName();
int comparison = 0;
AlphanumComparator* comparator = new AlphanumComparator();
// handle both usernames being null or empty
if ((s1 == "" || s1.isEmpty()) && (s2 == "" || s2.isEmpty())) {
return n1->compareTo(n2);
}
if (s1 == "" || s1.isEmpty()) {
s1 = n1->getSystemName();
}
if (s2 == "" || s2.isEmpty()) {
s2 = n1->getSystemName();
}
return comparison != 0 ? comparison : comparator->compare(s1, s2);
}
};
#endif // NAMECBEANUSERNAMECOMPARATOR_H
|
Ruby | UTF-8 | 643 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'json'
module Slurper
class Story
attr_accessor :attributes
def initialize(attrs={})
self.attributes = (attrs || {}).symbolize_keys
end
def to_post_params
{
name: name,
desc: description,
due: nil
}
end
def error_message; @response.body end
def name; attributes[:name] end
def description
return nil unless attributes[:description].present?
attributes[:description].split("\n").map(&:strip).join("\n")
end
def valid?
if name.blank?
raise "Name is blank for story:\n#{to_json}"
end
end
end
end
|
Java | UTF-8 | 600 | 2.203125 | 2 | [] | no_license | package main;
public class ReviewVO {
private String review_content, review_scope, member_nickname;
public String getReview_content() {
return review_content;
}
public void setReview_content(String review_content) {
this.review_content = review_content;
}
public String getReview_scope() {
return review_scope;
}
public void setReview_scope(String review_scope) {
this.review_scope = review_scope;
}
public String getMember_nickname() {
return member_nickname;
}
public void setMember_nickname(String member_nickname) {
this.member_nickname = member_nickname;
}
}
|
Java | UTF-8 | 669 | 2.921875 | 3 | [] | no_license | package com.unindra.flq.data;
/**
* One question in challenge mode
*
*
*/
public class Question {
private String goodAnswer;
private String bad1;
private String bad2;
private String bad3;
private int image;
public Question(String goodAnswer, String bad1, String bad2, String bad3, int image){
this.goodAnswer = goodAnswer;
this.bad1 = bad1;
this.bad2 = bad2;
this.bad3 = bad3;
this.image = image;
}
public String getGoodAnswer() {
return goodAnswer;
}
public String getBad1() {
return bad1;
}
public String getBad2() {
return bad2;
}
public String getBad3() {
return bad3;
}
public int getImage() {
return image;
}
}
|
Swift | UTF-8 | 5,035 | 2.640625 | 3 | [] | no_license | //
// LeftViewController.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 12/3/14.
//
import UIKit
enum LeftMenu: Int {
case main = 0
case peopleICanSee
case requestAccept
case profile
case setting
}
protocol LeftMenuProtocol : class
{
func changeViewController(_ menu: LeftMenu)
}
class LeftViewController : UIViewController, LeftMenuProtocol
{
@IBOutlet weak var tableView: UITableView!
var menus = ["Home","People I can see", "Request Access","Profile", "Settings"]
var mainViewController: UIViewController!
var peopleIcanseeVC:UIViewController!;
var requestAcceptVC:UIViewController!;
var profileVC:UIViewController!;
var settingVC: UIViewController!
var imageHeaderView: ImageHeaderView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.separatorColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1.0)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.mainViewController = UINavigationController(rootViewController: mainViewController)
let peopleIcanseeVC = storyboard.instantiateViewController(withIdentifier: "PeopleICanSeeVC") as! PeopleICanSeeVC
self.peopleIcanseeVC = UINavigationController(rootViewController:peopleIcanseeVC)
let requestAcceptVC = storyboard.instantiateViewController(withIdentifier: "RequestAcceptVC") as! RequestAcceptVC
self.requestAcceptVC = UINavigationController(rootViewController:requestAcceptVC)
let profileVC = storyboard.instantiateViewController(withIdentifier: "ProfileVC") as! ProfileVC
self.profileVC = UINavigationController(rootViewController: profileVC)
let settingVC = storyboard.instantiateViewController(withIdentifier: "SettingVC") as! SettingVC
self.settingVC = UINavigationController(rootViewController: settingVC)
self.tableView.registerCellClass(BaseTableViewCell.self)
self.imageHeaderView = ImageHeaderView.loadNib()
self.view.addSubview(self.imageHeaderView)
}
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
self.imageHeaderView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 160)
self.view.layoutIfNeeded()
}
func changeViewController(_ menu: LeftMenu)
{
switch menu
{
case .main:
self.slideMenuController()?.changeMainViewController(self.mainViewController, close: true)
case .peopleICanSee:
self.slideMenuController()?.changeMainViewController(self.peopleIcanseeVC, close: true)
case .requestAccept:
self.slideMenuController()?.changeMainViewController(self.requestAcceptVC, close: true)
case .profile:
self.slideMenuController()?.changeMainViewController(self.profileVC, close: true)
case .setting:
self.slideMenuController()?.changeMainViewController(self.settingVC, close: true)
}
}
}
extension LeftViewController : UITableViewDelegate
{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
if let menu = LeftMenu(rawValue: indexPath.row)
{
switch menu
{
case .main, .peopleICanSee, .requestAccept, .profile, .setting:
return BaseTableViewCell.height()
}
}
return 0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if let menu = LeftMenu(rawValue: indexPath.row)
{
self.changeViewController(menu)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
if self.tableView == scrollView
{
}
}
}
extension LeftViewController : UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return menus.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if let menu = LeftMenu(rawValue: indexPath.row)
{
switch menu
{
case .main, .peopleICanSee, .requestAccept, .profile, .setting:
let cell = BaseTableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: BaseTableViewCell.identifier)
cell.setData(menus[indexPath.row])
return cell
}
}
return UITableViewCell()
}
}
|
C# | UTF-8 | 1,033 | 2.6875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Species
{
public class RowAndColumnSwapMutator : Mutator
{
public override void Mutate(Random random, int[] field, int w, int h, int mutations)
{
for (int i = 0; i < mutations; i++)
if (random.Next(0, 2) == 0)
swapColumn(field, random.Next(0, w), random.Next(0, w), w, h);
else
swapRow(field, random.Next(0, h), random.Next(0, h), w, h);
}
public override void Mutate(Random random, ExecutionEnvironment.Arr<int> field, int mutations)
{
for (int i = 0; i < mutations; i++)
if (random.Next(0, 2) == 0)
field.SwapColumn(random.Next(0, field.W), random.Next(0, field.W));
else
field.SwapRow(random.Next(0, field.H), random.Next(0, field.H));
}
}
}
|
Java | UTF-8 | 222 | 1.695313 | 2 | [] | no_license | package com.javarush.task.task15.task1523;
public class SubSolution extends Solution {
public SubSolution() {
super();
}
protected SubSolution(String s) {
}
SubSolution(double j) {
}
}
|
C | UTF-8 | 489 | 3.546875 | 4 | [] | no_license | #include <unistd.h>
/* echo - program wypisujacy na standardowe wyjscie dane przeczytane
* ze standardowego wejscia */
int main(int argc, char **argv)
{
char msg[] = "Wpisz \"x\" aby zakonczyc program\n";
char ch = 'y';
/* wypisuje komunikat na ekran - stdout*/
write(1, msg, sizeof(msg));
while (ch != 'x'){
read(0, &ch, 1); /* czytam jeden bajt z stdin */
write(1, &ch, 1); /* zapisuje jeden bajt do stdout */
}
return 0;
}
|
Java | UTF-8 | 5,693 | 2.015625 | 2 | [] | no_license | package fr.liglab.adele.cube.extensions.joram.impl;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.lang.InterruptedException ;
import java.lang.Thread ;
import fr.liglab.adele.cube.AutonomicManager;
import fr.liglab.adele.cube.autonomicmanager.CMessage;
import fr.liglab.adele.cube.autonomicmanager.MessagesListener;
import fr.liglab.adele.cube.autonomicmanager.RuntimeModel;
import fr.liglab.adele.cube.autonomicmanager.RuntimeModelListener;
import fr.liglab.adele.cube.extensions.AbstractMonitorExecutor;
import fr.liglab.adele.cube.extensions.Extension;
import fr.liglab.adele.cube.extensions.core.model.Component;
import fr.liglab.adele.cube.metamodel.Attribute;
import fr.liglab.adele.cube.metamodel.ManagedElement;
import fr.liglab.adele.cube.metamodel.Notification;
import java.io.File;
import java.io.PrintWriter;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.JMSContext;
import javax.jms.ConnectionFactory;
import javax.jms.JMSRuntimeException;
import org.objectweb.joram.client.jms.tcp.TcpConnectionFactory;
import fr.dyade.aaa.agent.AgentServer;
public class JoramExtensionExecutor extends AbstractMonitorExecutor implements MessagesListener {
private static final String NAME = "joram-executor";
private AutonomicManager agent ;
/** Constant used to specified a queue */
protected static final String QUEUE = "queue";
/** Constant used to specified a topic */
protected static final String TOPIC = "topic";
private short id = 0;
private String user ="root" ;
private String pass= "root" ;
private String hostname ="localhost" ;
private int joramPort = 16010 ;
private int jndiPort = 16400 ;
private AgentServer joramAgent ;
private JoramServerThread server;
private boolean isStarted = false;
public JoramExtensionExecutor(Extension extension) {
super(extension) ;
this.agent = extension.getAutonomicManager();
}
public String getName() {
return NAME;
}
public AutonomicManager getCubeAgent(){
return this.agent;
}
public void setUser(String user){
this.user= user;
}
public void setPass(String pass){
this.pass=pass;
}
public void setHostname(String hostname){
this.hostname = hostname;
}
public void setJoramPort(int port){
this.joramPort= port;
}
public void start() {
info("JORAM EXTENSION started.");
}
private void info(String s){
System.out.println("[JORAM EXECUTOR] "+ s);
}
private class JoramServerThread extends Thread {
private JoramExtensionExecutor e;
public JoramServerThread(JoramExtensionExecutor e){
this.e=e;
}
public void run() {
try{
e.createAndStartJoramServer();
} catch (Exception e){
info(e.toString());
}
}
}
public void update(RuntimeModel rm, Notification notification) {
if (notification.getNotificationType() == RuntimeModelListener.UPDATED_RUNTIMEMODEL) {
System.out.println("updateJoram");
updateJoram();
}
}
public synchronized void updateJoram(){
List<ManagedElement> mes = this.agent.getRuntimeModelController().getRuntimeModel().getManagedElements();
info("in updateJoram " + mes.size() + " elements") ;
for (ManagedElement elem : mes){
if (elem instanceof Component){
Component comp= (Component)elem ;
try {
if (comp.getAttribute("isJoram")!=null){
info("component is joram") ;
if (!this.isStarted){
this.server = new JoramServerThread(this);
server.start();
// createAndStartJoramServer();
info("joram thread started");
this.isStarted=true;
}
}
} catch(Exception e){
}
}
}
}
public void createAndStartJoramServer() throws Exception {
info("in createAndStartJoramServer");
StringBuffer strbuf = new StringBuffer();
strbuf.append("<?xml version=\"1.0\"?>\n")
.append("<config>\n")
.append("<property name=\"Transaction\" value=\"fr.dyade.aaa.ext.NGTransaction\"/>\n" +"<server id=\"")
.append(this.id)
.append("\" name=\"S")
.append(this.id)
.append("\" hostname=\"")
.append(this.hostname)
.append("\">\n" +"<service class=\"org.objectweb.joram.mom.proxies.ConnectionManager\" args=\"")
.append(this.user).append(' ').append(this.pass)
.append("\"/>\n" +"<service class=\"org.objectweb.joram.mom.proxies.tcp.TcpProxyService\" args=\"")
.append(this.joramPort)
.append("\"/>\n" +"<service class=\"fr.dyade.aaa.jndi2.server.JndiServer\" args=\"")
.append(this.jndiPort)
.append("\"/>\n" +"</server>\n" + "</config>\n");
PrintWriter pw = new PrintWriter(new File("a3servers.xml"));
pw.println(strbuf.toString());
pw.flush();
pw.close();
info("command created " + strbuf);
try{
AgentServer.init((short) this.id,
new File("S" + this.id).getPath(),
null);
info("init done ");
AgentServer.start();
info("\nstarted ");
} catch(Exception e){
info("unspecialized exception while starting joram");
throw e ;
}
}
/**
* Stops a previously started Joram server.
*/
public static void stopJoramServer() {
AgentServer.stop();
}
public void destroy() {
}
public void receiveMessage(CMessage msg) {
}
public synchronized void stop() {
}
@Override
public String toString() {
return "JORAM EXECUTOR";
}
}
|
C++ | UTF-8 | 747 | 3.234375 | 3 | [] | no_license | //给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
//
// 示例 1:
//
// 输入: 16
//输出: true
//
//
// 示例 2:
//
// 输入: 5
//输出: false
//
// 进阶:
//你能不使用循环或者递归来完成本题吗?
// Related Topics 位运算
#include "header.h"
namespace LeetCode342 {
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
bool isPowerOfFour(int num) {
return solution1(num);
}
// num 只有一个高位1,且在偶数位
bool solution1(int num) {
return num > 0 && !(num & (num - 1)) && (num & 0x55555555);
}
};
//leetcode submit region end(Prohibit modification and deletion)
} |
Markdown | UTF-8 | 3,961 | 2.765625 | 3 | [] | no_license | # Lyrics App - React Native
This mobile application was developed using React Native v0.63, Typescript and Redux. The data is retrieved from the https://api.lyrics.ovh/v1/ API.
This app has three sections:
- SEARCH:
- A screen with a form consisting of two text inputs: ‘artist’ and ‘song title’. After filling both inputs and submitting, a screen containing the song lyrics is presented.
- Lyrics are retrieved from the https://lyricsovh.docs.apiary.io/ Rest API.
- An error message is be displayed if the lyrics can’t be retrieved for whatever reason.
- Below the search form, a ‘Previous search’ section showing the artist and song title of the latest lyrics successfully retrieved after a search (only if there was a previous successful search). The user is able to tap on it to see the lyrics on a new screen.
- Search functionality is only available while having internet access.
- HISTORY:
- A screen listing the previously retrieved songs.
- The user must can tap on any song to see its lyrics on a new screen.
- History section is available without internet access.
- The history can be be cleared.
- LYRICS:
- A screen showing the complete lyrics of the song.
## Demo Videos
- [Video on iPhone 11 Simulator](https://drive.google.com/file/d/1r4RDQ6kkwjmFrIWDGNwgvfwjFlRTFa7N/view?usp=sharing)
- [Video on Android Pixel Emulator](https://drive.google.com/file/d/1lZFhiORNRlkcu1GPH7Zpg2zbITDBVQs-/view?usp=sharing)
## Getting started
- First make sure to have `node`, `yarn` and `react-native-cli` installed on your machine.
- You will need a Mac in order to run the iOS app. In that case, make sure to have `cocoapods` installed.
- You also need to have Android Studio and XCode (if on Mac) installed.
After cloning the repository to your local machine, open a terminal on the project's root folder and execute the following command to install the needed `node_modules`:
```
$ yarn install
```
Then (if on Mac), execute this command to install the needed `Pods`:
```
$ cd ios && pod install
```
Finally, go back to the project's root folder:
```
cd ..
```
## Create the .env file
Create a `.env` file in project's root folder and write this inside the file:
```
API_URL=https://api.lyrics.ovh/v1/
```
## Launch iOS
Execute:
```
$ react-native run-ios
```
or launch the app from XCode opening the `.workspace` file.
## Launch Android
- Make sure to have an Android emulator running or a physical device connected to your machine. Then execute:
```
$ react-native run-android
```
## VSCode extensions
- Prettier
- ESLint
- TSLint
- Editorconfig
## Libraries used
- React Native v0.63.0
- TypeScript v3.8.3
- `react-native-config` -
This library is used to be able to access environmental variables defined in a `.env` file. On real projects, the `.env` is not committed to the repository and is a way to keep data safe, such as API's URLs, services Keys such as Google, Stripe, among other sensitive data.
- `redux` (along with `react-redux` and `redux-thunk`) -
Used for global state management on the app.
- `redux-form` -
Used for user form inputs and provides good handling of data and validation. The filled form data can be accessed from any part of the app as it is centralized in the Redux store.
- `styled-components` -
Nice way to add styles to components and write then in a very intuitive and clean way.
- `react-navigation` v5 -
Used to add navigation to the app.
- `react-native-vector-icons` -
Used to add generic, predefined and public icons in the app.
- `eslint` and `prettier` -
Used to find and fix problems in the code. Also, ensure consistency in code writing along the project.
- `husky` (along with `lint-staged`) -
Used to run specific scripts at the moment a commit is done. In the case of this project, it is used to check that there are no TypeScript errors and then, using `lint-staged` automatically fixes issues related to `prettier`
:v: **Enjoy!**
|
Ruby | UTF-8 | 3,216 | 3.15625 | 3 | [] | no_license | #!/usr/bin/env ruby
##
# Parse a LinkedIn Sales Navigator HTML page of people to TSV.
#
# This script converts HTML to TSV (Tab Separated Values),
# which can be useful for spreadsheets such as Microsoft Excel.
#
# You can also edit this script to customize it for your needs,
# such as exporting CSV (Comma Separated Values), JSON, or text.
#
# This script is not affiliated with the LinkedIn company in any way.
# Please limit your use of this script to only your own valid uses.
# Use at your own risk. There is no warranty, express or implied.
#
# Version: 1.0.0
# Created: 2016-12-10
# Updated: 2016-12-10
# License: GPL
# Contact: Joel Parker Henderson (joel@joelparkerhenderson.com)
##
require 'cgi'
require 'nokogiri'
public
# Create namespaces
module LinkedIn
module SalesNavigator
end
end
class LinkedIn::SalesNavigator::Page
attr_accessor :html, :entities
def initialize(html)
@html = html
end
def scrub
html.css('path').remove
html.css('svg').remove
html.css('nav').remove
html.css('button').remove
html.css('input').remove
html.css('*[class~="sublinks-container"]').remove
html.css('*[class~="secondary-action-item"]').remove
html.css('*[class~="secondary-actions-container"]').remove
html.css('*[class~="hover-border"]').remove
html.css('*[class~="custom-badges-wrapper"]').remove
html.css('*[class~="a11y-hidden"]').remove
end
def entities
@entities = html.css('div[class~="entity-info"]')
end
end
class LinkedIn::SalesNavigator::User
attr_accessor \
:html,
:person_name,
:company_name,
:title,
:employment_duration,
:geo_area,
:info_values
def initialize(html)
@html = html
end
def to_s
html.to_xhtml(indent: 2)
end
def to_h
return {
"person_name" => person_name,
"graph_distance" => graph_distance,
"company_name" => company_name,
"title" => title,
"employment_duration" => employment_duration,
"geo_area" => geo_area,
}
end
def to_tsv
[
person_name,
graph_distance,
company_name,
title,
employment_duration,
geo_area,
].join("\t")
end
def person_name
@person_name ||= person_name_tags&.text.sub(/,.*$/,'')
end
def person_name_tags
html.css('*[class~="name-link"]')&.first
end
def company_name
@company_name ||= company_name_tags&.first&.text
end
def company_name_tags
html.css('*[class~="company-name"]')
end
def title
@title ||= info_values[0]
end
def graph_distance
@graph_distance ||= graph_distance_tags&.first&.text&.to_i
end
def graph_distance_tags
html.css('*[class~="degree-icon"]')
end
def employment_duration
@employment_duration ||= info_values[1].sub(/^\|/,'').sub(/\|/,' | ')
end
def geo_area
@geo_area ||= info_values[2]
end
def info_values
@info_values ||= info_value_tags&.map{|tag| tag.text }
end
def info_value_tags
html.css('*[class~="info-value"]')
end
end
def main
s=$stdin.read
html=Nokogiri::HTML(s)
page=LinkedIn::SalesNavigator::Page.new(html)
users=page.entities.map{|entity| LinkedIn::SalesNavigator::User.new(entity) }
users.each{|user| puts user.to_tsv }
end
main
|
C# | UTF-8 | 1,721 | 2.921875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Respawned
{
public class SellRule
{
private string _name;
private int _itemType;
private int _minIlvl;
private SellRuleCriteria[] _criterias;
private int _priority = -1;
public SellRule() { }
public SellRule(string name, int itemType, int minIlvl, SellRuleCriteria[] criterias)
{
Name = name;
ItemType = itemType;
MinIlvl = minIlvl;
Criterias = criterias;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public int ItemType
{
get { return _itemType; }
set { _itemType = value; }
}
public int MinIlvl
{
get { return _minIlvl; }
set { _minIlvl = value; }
}
public SellRuleCriteria[] Criterias
{
get { return _criterias; }
set { _criterias = value; }
}
public int Priority
{
get { return _priority; }
set { _priority = value; }
}
public override string ToString()//return the string to send to the API here
{
string value = Name + ";" + ItemType + ";" + MinIlvl + ";" + Priority + ":";
for (int i = 0; i < _criterias.Length; i++)
{
value += _criterias[i].StatID + ";";
value += _criterias[i].MinAmount;
if (i < _criterias.Length - 1)
value += ";";
}
return value;
}
}
}
|
JavaScript | UTF-8 | 2,277 | 2.734375 | 3 | [] | no_license |
//home sliders
const homesliders=document.querySelector('.image-div')
db.collection('homesliders').onSnapshot(snap=>{
let count=0;
homesliders.innerHTML="";
snap.docs.forEach(nap => {
// console.log(nap.data().slider)
let slide=nap.data().sliders;
slide.forEach(cap=>{
const div=document.createElement('div');
console.log(cap);
div.innerHTML=`
<img src="${cap}" alt="alt" id="i${count}">
<p class="close" id="r${count}">x</p>
`;
homesliders.append(div)
console.log(count)
const close=document.querySelector(`#r${count}`)
const imagelink=document.querySelector(`#i${count}`).src;
close.addEventListener('click',(e)=>{
removeslide(imagelink);
})
count=count+1;
})
});
})
//removing photo in home sliders
function removeslide(link){
console.log("removing items in sliding")
db.collection('homesliders').doc('sliding').update({
sliders : firebase.firestore.FieldValue.arrayRemove(link)
})
.then(function(){
console.log("removed")
})
.catch(err=> console.log(err,"error while removing items in sliding"))
}
//upload new photo to sliders
const adharfront=document.querySelector('.adharfront');
adharfront.addEventListener('change',(e)=>{
var file=e.target.files[0];
console.log("adhar click")
uploaderf=document.querySelector('#uploaderf');
// crate storage ref
var storageref=storage.ref('homesliders/' + file.name);
//upload file
var task=storageref.put(file);
//update progress bar
task.on('state_changed',
function progress(snapshot){
var percentage=(snapshot.bytesTransferred / snapshot.totalBytes)*100;
uploaderf.value=percentage;
},
function error(err){
console.log(err)
},
function complete(){
console.log("adhar front uploaded successfully")
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
db.collection('homesliders').doc('sliding').update({
sliders:firebase.firestore.FieldValue.arrayUnion(downloadURL)
})
uploaderf.value=0;
});
}
);
})
|
C | UTF-8 | 1,537 | 3.84375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* Perform a `strncat` into a too small buffer.
*
* Try:
* $ ./strcpy3 15 SummerCSC209
*
* Notice that `strncat` is NOT copying the NUL from `src` if `n < strlen(src)`:
*
* $ ./strcpy3 10 SummerCSC209
*
* The extra '#' padding characters are ones we specifically chose to show
* this behaviour. If we had not done that, there would have been no NUL and
* `printf` or any other function expecting a string might have continued
* reading memory way past the end of the space allocated for `s`.
*/
int main(int argc, char *argv[])
{
if (argc != 3) {
printf("usage: %s len src\n", argv[0]);
return -1;
}
// Collect arguments
size_t len = atoi(argv[1]);
char *src = argv[2];
// Allocate enough space for destination, with some padding
size_t pad = 16;
char *dest = (char *) malloc(len + pad);
if (!dest) {
perror("malloc");
return -1;
}
// Provide a safety net in the event that `strncpy` does not copy the NUL byte
memset(dest, '#', len + pad);
dest[len + pad - 1] = '\0';
// Destination is initially empty
dest[0] = '\0';
// Do a limited copy
strncpy(dest, src, len);
/* Uncomment the following line to be safe even when `n < strlen(src)`. You
* can only do this is you allocated at least `len + 1` bytes for `dest`.
* */
//dest[len] = '\0';
printf("src : %s\n", src);
printf("dest: %s\n", dest);
return 0;
}
|
Swift | UTF-8 | 7,157 | 2.828125 | 3 | [] | no_license | //
// SpaceShip.swift
// SpaceCrash
//
// Created by Simas Abramovas on 27/03/15.
// Copyright (c) 2015 Simas Abramovas. All rights reserved.
//
import SpriteKit
class SpaceShip : SKSpriteNode {
let ATLAS_NAME = "SpaceShip"
let TEXTURE_NAME_FORMAT = "SpaceShip%d"
let ACTION_MOVEMENT = "movement_action"
let ACTION_ANIMATE = "animate_action"
let ACTION_ANIMATE_RESTORE = "animate_restore_action"
let atlas: SKTextureAtlas
let textureCountPerSide: Int
let defaultTexture : SKTexture
var leftTextures = [SKTexture]()
var rightTextures = [SKTexture]()
var queuedMovement : Direction?
var movementDelay = NSTimeInterval(0)
var restoring = false
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
// Texture atlas
atlas = SKTextureAtlas(named: ATLAS_NAME)
// Default texture
defaultTexture = atlas.textureNamed(String(format: TEXTURE_NAME_FORMAT, arguments: [0]))
// Left and right textures
textureCountPerSide = (atlas.textureNames.count - 1) / 2;
for i in reverse(-textureCountPerSide..<0) {
leftTextures += [atlas.textureNamed(String(format: TEXTURE_NAME_FORMAT, arguments: [i]))]
}
for i in 1...textureCountPerSide {
rightTextures += [atlas.textureNamed(String(format: TEXTURE_NAME_FORMAT, arguments: [i]))]
}
super.init(texture: defaultTexture, color: nil, size: CGSizeMake(102.4, 72.4))
// Physics
physicsBody = SKPhysicsBody(texture: texture, size: size)
physicsBody!.dynamic = false
physicsBody!.categoryBitMask = SpaceScene.Mask.SPACE_SHIP
physicsBody!.contactTestBitMask = SpaceScene.Mask.SPACE_SHIP | SpaceScene.Mask.ASTEROID | SpaceScene.Mask.SCENE
physicsBody!.collisionBitMask = SpaceScene.Mask.SPACE_SHIP | SpaceScene.Mask.ASTEROID | SpaceScene.Mask.SCENE
}
// ToDo Movement/Animation actions easeIn. When restoring everything should be faster.
func move(direction: Direction) {
if restoring {
queuedMovement = direction
return
}
// Restore default texture gradually
returnToDefault()
// ToDo queue animate after restoration
// However movement will have to be executed
// ToDo make a movement action that increases its speed gradually based on current texture index
switch (direction) {
case .Left:
runAction(SKAction.animateWithTextures(leftTextures, timePerFrame: 0.1, resize: false, restore: false), withKey: ACTION_ANIMATE)
case .Right:
runAction(SKAction.animateWithTextures(rightTextures, timePerFrame: 0.1, resize: false, restore: false), withKey: ACTION_ANIMATE)
default:
return
}
movementBasedOnCurrentTexture()
}
func movementBasedOnCurrentTexture() {
runAction(SKAction.repeatActionForever(SKAction.sequence([
SKAction.runBlock({
// Calc movement speed and duration based on current texture
if let index = self.getCurrentTextureIndex() {
let index = CGFloat(index)
let by = CGVectorMake(1 * index, 0)
let duration = NSTimeInterval(abs(0.1 * index))
self.runAction(SKAction.moveBy(by, duration: duration))
self.movementDelay = duration
}
}),
SKAction.waitForDuration(movementDelay)
])), withKey: self.ACTION_MOVEMENT)
}
func stopMovement() {
queuedMovement = nil
// Restore default texture gradually
returnToDefault()
// Remove movement and animation actions
removeActionForKey(ACTION_ANIMATE)
}
func returnToDefault() {
if let curTextureInfo = getCurrentTextureInfo() {
var textures : [SKTexture]
switch (curTextureInfo.1) {
case .Left:
// From left to default
textures = Array(leftTextures[0...curTextureInfo.0].reverse())
case .Right:
// From right to default
textures = Array(rightTextures[0...curTextureInfo.0].reverse())
default:
return
}
textures += [defaultTexture]
runAction(SKAction.sequence([
SKAction.runBlock({
self.restoring = true
}),
// ToDo make restoration faster also possibly easeIn
SKAction.animateWithTextures(textures, timePerFrame: 0.1, resize: false, restore: false),
SKAction.runBlock({
self.restoring = false
// Restoration done
// Remove ongoing movements
self.removeActionForKey(self.ACTION_MOVEMENT)
// Run queued movement (if any)
if let queuedMovement = self.queuedMovement {
self.move(queuedMovement)
}
// ToDo what about left -> release -> left before restoration ended?
// ToDo LEFT_RESTORATION / RIGHT_RESTORIATION if appropriate movement is executed, remove restoration and continue animate
})
]), withKey: ACTION_ANIMATE_RESTORE)
}
}
func getCurrentTextureInfo() -> (Int, Direction)? {
if let texture = texture {
if texture == defaultTexture {
return (0, .None)
} else if let index = find(leftTextures, texture) {
return (index, .Left)
} else if let index = find(rightTextures, texture) {
return (index, .Right)
}
}
return nil
}
func getCurrentTextureIndex() -> Int? {
if let info = getCurrentTextureInfo() {
switch (info.1) {
case .Left:
return -info.0
case .Right:
return info.0
case .None:
return 0
default:
return nil
}
}
return nil
}
func shoot() {
// ToDo delay between shots
// ToDo based where the guns are, based on cur texture
// getCurrentTextureIndex()
let leftLaser = Laser()
let rightLaser = Laser()
// Position lasers (depends on the ship position and texture)
leftLaser.position = scene!.convertPoint(CGPointMake(43, 50), fromNode: self)
rightLaser.position = scene!.convertPoint(CGPointMake(-43, 50), fromNode: self)
// Add the laser to scene
scene?.addChild(leftLaser)
scene?.addChild(rightLaser)
// ToDo group movement?
leftLaser.startMovement()
rightLaser.startMovement()
}
} |
Java | UTF-8 | 298 | 1.6875 | 2 | [] | no_license | package hl7.pseudo.message;
import hl7.bean.Structure;
public class CSU_C11 extends hl7.model.V2_3.message.CSU_C11{
public CSU_C11(){
super();
}
public static CSU_C11 CLASS;
static{
CLASS = new CSU_C11();
}
public Structure[][] getComponents(){
return super.getComponents();
}
}
|
Java | UTF-8 | 1,055 | 2.265625 | 2 | [] | no_license | package com.project.Servlets;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.project.Methods.GetAllClass;
import com.project.Model.Department;
import com.project.Model.Employee;
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GetAllClass gac = new GetAllClass();
List<Employee> list_emp = gac.getAllEmp();
List<Department> list_dept = gac.getAllDept();
request.setAttribute("emps", list_emp);
request.setAttribute("depts", list_dept);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
|
Markdown | UTF-8 | 728 | 2.703125 | 3 | [] | no_license | # bump-all
Permet de mettre à jour plusieurs projets d'une organisation github en même temps de de faire les PR
```bash
php app/console composer:update GITHUB_TOKEN ORGANISATION DEPENDENCY VERSION
```
## with docker
1/ Build the image
```bash
docker build -t bumper:latest .
```
2/ Run the command
```bash
docker run -it --rm --env GITHUB_TOKEN="<your_github_token>" bumper:latest bumper "<organisation>" "<dependency>" "<version>"
```
#### Pro-tip: use an alias
create the alias in your .(ba|z)shrc
```bash
alias bumper='docker run -it --rm --env GITHUB_TOKEN="<yout_github_token>" bumper:latest bumper'
```
You can now simply use ```bumper "<organisation>" "<dependency>" "<version>"``` to bump your dependencies
|
Java | UTF-8 | 1,625 | 3.859375 | 4 | [] | no_license | package com.example.guozaiss.explain;
import java.util.Stack;
/**
* Created by guozaiss on 16/1/21.
* 处理与解释相关的一些业务
*/
public class Calculator {
//声明一个Stack栈存储并操作所有相关的解释器
public Stack<ArithmeticExpression> mExpStack = new Stack<ArithmeticExpression>();
/**
* 计算
*
* @param expression
*/
public Calculator(String expression) {
//声明两个Arithmetic类型的临时变量,存储运算符左右两边的数字解释器
ArithmeticExpression exp1, exp2;
//根据空格分隔表达字符串
String[] elements = expression.split(" ");
//循环遍历表达式元素数组
for (int i = 0; i < elements.length; i++) {
switch (elements[i].charAt(0)) {
case '+':
exp1 = mExpStack.pop();
exp2 = new NumExpression(Integer.valueOf(elements[++i]));
mExpStack.push(new AdditionExpression(exp1, exp2));
break;
case '-':
exp1=mExpStack.pop();
exp2 = new NumExpression(Integer.valueOf(elements[++i]));
mExpStack.push(new SubtrationExpression(exp1, exp2));
break;
default:
mExpStack.push(new NumExpression(Integer.valueOf(elements[i])));
break;
}
}
}
/**
* 最终的计算结果
*
* @return
*/
public int calculator() {
return mExpStack.pop().interpreter();
}
}
|
Go | UTF-8 | 1,453 | 4.25 | 4 | [] | no_license | package main
import (
"errors"
"fmt"
"math"
)
type person struct {
name string
age int
}
func main() {
fmt.Println("Hello World")
x := 20
fmt.Println(x)
a := [5]int{2, 3, 4, 5, 6}
a[2] = 3
fmt.Println(a)
//slices are an abstraction of arrays
b := []int{2, 3, 4, 5, 6}
b[2] = 3
fmt.Println(b)
list := make(map[string]int)
list["one"] = 2
list["two"] = 3
list["three"] = 5
delete(list, "three")
fmt.Println(list)
//loops
for i := 0; i < 5; i++ {
fmt.Println(i)
}
//range
arr := []string{"a", "b", "c"}
for index, value := range arr {
fmt.Println("index", index, "value", value)
}
//map[type]type
m := make(map[string]string)
m["A"] = "alpha"
m["B"] = "beta"
for key, value := range m {
fmt.Println("key", key, "value", value)
}
//calling a function outside the main func scope
result := sum(2, 3)
fmt.Println(result)
// result, err := sqrt(16)
//
// if err != nil {
// fmt.Println(err)
// } else {
// fmt.Println(result)
// }
p := person{name: "Artie", age: 37}
fmt.Println("Person:", p.name)
//the pointer to the memory address of z
z := 7
inc(&z)
fmt.Println("pointer value:", z)
}
func sum(x int, y int) int {
return x + y
}
func sqrt(x float64) (float64, error) {
if x < 0 {
return 0, errors.New("Undefined for neg numbers")
}
return math.Sqrt(x), nil
}
//pointers * => &
//dereference the incrementer and point to the original variable
func inc(x *int) {
*x++
}
|
SQL | UTF-8 | 1,246 | 3.65625 | 4 | [] | no_license | create database db_farmaciaDoBem;
use db_farmaciaDoBem;
create table tb_categoria(
id bigint not null auto_increment,
categoria varchar(20) not null,
promocao boolean not null,
primary key(id)
);
create table tb_produto(
id bigint not null auto_increment,
produto varchar(30) not null,
valor decimal (5,2) not null,
disp_estoque bigint not null,
id_categoria bigint,
primary key(id),
foreign key(id_categoria) references tb_categoria(id)
);
insert into tb_categoria values
(default, 'Suplementos', true),
(default, 'Analgésicos', false),
(default, 'Infantil', false),
(default, 'Doces', false),
(default, 'Coletores menstruais', false);
insert into tb_produto values
(default, 'Vitamina B12', 52, 65, 1),
(default, 'ChocoSoy', 7, 20, 4),
(default, 'Shampoo Infantil', 15, 35, 3),
(default, 'Bananinha', 2, 25, 4),
(default, 'Vitamina D', 40, 90, 1);
select * from tb_produto where valor > 50;
select * from tb_produto where valor between 3 and 60 order by valor desc;
select * from tb_produto where produto like '%B%' order by produto;
select * from tb_produto p join tb_categoria c on p.id_categoria = c.id order by produto;
select * from tb_produto p join tb_categoria c on p.id_categoria = c.id where c.categoria = 'Suplementos' order by produto; |
Java | UTF-8 | 1,141 | 2.203125 | 2 | [] | no_license | package ftp.client.controller;
import ftp.client.component.tab.TabWindowController;
import ftp.client.service.AnchorService;
import ftp.client.service.RouterService;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import java.net.URL;
import java.util.ResourceBundle;
import static ftp.client.config.Consts.TAB_VIEW;
public class MainController implements Initializable {
@FXML
private TabPane tabPane;
public void initialize(URL location, ResourceBundle resources) {
newSessionAction();
}
@FXML
public void newSessionAction() {
createNewTab();
}
private void createNewTab() {
Pane pane = (Pane) RouterService.getInstance().getView(TAB_VIEW);
TabWindowController tabWindowController = (TabWindowController) RouterService.getInstance().getController();
Tab tab = new Tab();
tabWindowController.init();
AnchorService.getInstance().anchorNode(pane);
tab.setId(tabWindowController.getName());
tab.setContent(pane);
tabPane.getTabs().add(tab);
}
} |
JavaScript | UTF-8 | 913 | 2.578125 | 3 | [] | no_license | const axios = require('axios');
const URL = "https://api.smash.gg/gql/alpha";
async function run_query (query, variables, token) {
const data = {
query: query,
variables: variables
}
const headers = {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
}
}
try
{
const response = await axios.post(URL, data, headers);
return response;
}
catch(error)
{
if(error.response.status === 429) {
throw new Error("Sending too many requests right now, try again in like 30 seconds -- this will usually fix the error");
}else if(error.response.status > 299 || error.response.status < 200) {
throw new Error(`error code: ${error.response.status}\nerror response: ${error.response.statusText}`)
}
}
}
module.exports = { run_query }; |
C++ | UTF-8 | 3,459 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | /*
Copyright (c) 2012-2016, Kai Hugo Hustoft Endresen <kai.endresen@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sepia/util/progargs.h>
#include <iostream>
namespace sepia
{
namespace util
{
std::map< std::string, std::string > ProgArgs::sm_LongArgs;
std::map< std::string, std::pair< std::string, std::string> > ProgArgs::sm_defaults;
void ProgArgs::init( int argc, char** argv )
{
std::string* last_value = NULL;
bool last_was_argument = false;
for( int i = 1; i < argc; i++ ) // i = 0 is the executable.
{
std::string str( argv[i] );
if( ( str.length() > 2 )
&& ( str.compare( 0, 2, "--" ) == 0 ) )
{
str.erase( str.begin(), str.begin() + 2 );
last_value = &sm_LongArgs[ str ];
last_was_argument = true;
}
else if( last_value != NULL && last_was_argument )
{
*last_value = str;
last_was_argument = false;
}
else
{
last_was_argument = false;
}
}
}
bool ProgArgs::contains( const std::string& a_string )
{
std::map< std::string, std::string >::const_iterator it = sm_LongArgs.find( a_string );
return it != sm_LongArgs.end();
}
const std::string ProgArgs::value( const std::string& a_string, bool* a_valid )
{
std::map< std::string, std::string >::const_iterator it = sm_LongArgs.find( a_string );
if( it != sm_LongArgs.end() )
{
if( a_valid )
{
*a_valid = true;
}
return it->second;
}
else
{
if( a_valid )
{
*a_valid = false;
}
return std::string();
}
}
void ProgArgs::printHelp()
{
for( const auto& item : sm_defaults )
{
std::cerr << "\t --" << item.first << ": " << item.second.second << " (default: " << item.second.first << ")" << std::endl;
}
}
void ProgArgs::addDefault( const std::string& a_option, const std::string& a_value, const std::string& a_description )
{
sm_defaults[ a_option ] = std::make_pair( a_value, a_description );
}
void ProgArgs::addOptionDefaults( const std::string& a_option, const std::string& a_description )
{
addDefault( a_option, std::string(), a_description );
}
}
}
|
Java | UTF-8 | 1,081 | 2.234375 | 2 | [] | no_license | package com.test.searchplace.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import com.test.searchplace.dao.PlaceDao;
import com.test.searchplace.model.Place;
import com.test.searchplace.model.Tag;
public class PlaceDaoImpl implements PlaceDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void createPlace(Place place) {
StringBuilder sb = new StringBuilder();
List<Tag> list = place.getTags();
for(Tag t : list) {
sb.append(t.getNameTag());
}
jdbcTemplate.update("INSERT INTO place (place_name, tag_name) VALUES (?, ?)", place.getNamePlace(), sb.toString());
}
@Override
public List<Place> getPlace(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void updatePlace(Place place) {
// TODO Auto-generated method stub
}
@Override
public void deletePlace(Place place) {
// TODO Auto-generated method stub
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
} |
PHP | UTF-8 | 361 | 2.640625 | 3 | [] | no_license | <?php
$str='host = localhost port=5432 dbname=test user=postgres password=329033';
$link = pg_connect($str);
$select='select name,job,dno from employee1';
$result=pg_query($link,$select);
$index=0;
while(@$res=pg_fetch_array($result,$index))
{
echo "employee $res[0] has job $res[1] and works for department $res[2] </br>";
$index++;
} |
Markdown | UTF-8 | 1,668 | 2.578125 | 3 | [] | no_license |
# BlinkdotNet
BlinkdotNet is the unofficial .NET implementation of the Blink Monitor Protocol as originally documented by MattTW [here](https://github.com/MattTW/BlinkMonitorProtocol).
BlinkdotNet allows developers to interact with Blink networks and cameras easily without the need for complicated REST calls.
## Build Status
[](https://dev.azure.com/dccoder/DCCoders/_build/latest?definitionId=3?branchName=master)
[](https://vsrm.dev.azure.com/dccoder/_apis/public/Release/badge/eed6374e-ee58-4c21-8c9a-d479c6d82805/1/1)
## Release Notes
Currently BlinkdotNet is in an alpha release state, and is availible through Nuget.org. To download via Nuget Package Manager ensure that you have "Include Prerelease" checked.
## Documentation
Documentation can be found on the [wiki](https://github.com/DCCoder90/BlinkdotNet/wiki)
## Usage
### Getting Started
In order to get started using BlinkdotNet you must first create a new instance of the IBlinkApiClient passing it the login credentials to your [Blink account](https://blinkforhome.com/)
```C#
IBlinkApiClient client = new BlinkApiClient("exampleeamil@example.com", "mys3cretp@ssword");
```
Once you have your IBlinkApiClient implementation you simply call it like so:
```C#
var networks = await client.GetNetworksAsync();
foreach (var network in networks)
{
Console.WriteLine(network.Name);
}
```
It is important to note that all methods implmented by IBlinkApiClient are asynchronous.
|
Ruby | UTF-8 | 76 | 2.765625 | 3 | [] | no_license | puts "私の名前は八島洋介です。年齢は" + 26.to_s + "歳です" |
Markdown | UTF-8 | 11,745 | 2.859375 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Monitor your StorSimple 8000 series device
description: Describes how to use the StorSimple Device Manager service to monitor usage, I/O performance, and capacity utilization.
author: alkohli
ms.service: storsimple
ms.topic: conceptual
ms.date: 10/17/2017
ms.author: alkohli
---
# Use the StorSimple Device Manager service to monitor your StorSimple device
## Overview
You can use the StorSimple Device Manager service to monitor specific devices within your StorSimple solution. You can create custom charts based on I/O performance, capacity utilization, network throughput, and device performance metrics and pin those to the dashboard. For more information, go to [customize your portal dashboard](../azure-portal/azure-portal-dashboards.md).
To view the monitoring information for a specific device, in the Azure portal, select the StorSimple Device Manager service. From the list of devices, select your device and then go to **Monitor**. You can then see the **Capacity**, **Usage**, and **Performance** charts for the selected device.
## Capacity
**Capacity** tracks the provisioned space and the space remaining on the device. The remaining capacity is then displayed as locally pinned or tiered.
The provisioned and remaining capacity is further broken down by tiered and locally pinned volumes. For each volume, the provisioned capacity, and the remaining capacity on the device is displayed.

## Usage
**Usage** tracks metrics related to the amount of data storage space that is used by the volumes, volume containers, or device. You can create reports based on the capacity utilization of your primary storage, your cloud storage, or your device storage. Capacity utilization can be measured on a specific volume, a specific volume container, or all volume containers.
By default, the usage for past 24 hours is reported. You can edit the chart to change the duration over which the usage is reported by selecting from:
* Past 24 hours
* Past 7 days
* Past 30 days
* Past 90 days
* Past year
Two key metrices, growth and range are reported for the usage charts. Range refers to the maximum value and the minimum values of the usage reported over the selected duration (fo instance, Past 7 days).
Growth refers to the increase in usage from the first day to the last day over the selected duration.
Growth and range can also be represented by the following equations:
```
Range = {Usage(minimum), Usage(maximum)}
Growth = Usage(Last day) - Usage(first day)
Growth (%) = [{Usage(last day) - Usage(first day)} X 100]/Usage(first day)
```
The primary, cloud, and local storage used can be described as follows:
### Primary storage usage
These charts show the amount of data written to StorSimple volumes before the data is deduplicated and compressed. You can view the primary storage used by all volumes in a volume container or for a single volume. The primary storage used is further broken down by primary tiered storage used and primary locally pinned storage used.
The following charts show the primary storage used for a StorSimple device before and after a cloud snapshot was taken. As this is just volume data, a cloud snapshot should not change the primary storage. As you can see, the chart shows no difference in the primary tiered or locally pinned storage used as a result of taking a cloud snapshot. The cloud snapshot started at around 11:50 pm on that device.

If you now run IO on the host connected to your StorSimple device, you will see an increase in primary tiered storage or primary locally pinned storage used depending upon which volumes (tiered or locally pinned) you write the data to. Here are the primary storage usage charts for a StorSimple device. On this device, the StorSimple host started serving writes at around 2:30 pm on a tiered volume on the device. You can see the peak in the write bytes/s corresponding to the IO running on the host.

If you look at the primary tiered storage used, that has gone up whereas the primary locally pinned usage stays unchanged as there are no writes served to the locally pinned volumes on the device.

If you are running Update 3 or higher, you can break down the primary storage capacity utilization by an individual volume, all volumes, all tiered volumes, and all locally pinned volumes as shown below. Breaking down by all locally pinned volumes will allow you to quickly ascertain how much of the local tier is used up.


You can further click on each of the volumes in the list and see the corresponding usage.

### Cloud storage usage
These charts show the amount of cloud storage used. This data is deduplicated and compressed. This amount includes cloud snapshots which might contain data that isn't reflected in any primary volume and is kept for legacy or required retention purposes. You can compare the primary and cloud storage consumption figures to get an idea of the data reduction rate, although the number will not be exact.
The following charts show the cloud storage utilization of a StorSimple device when a cloud snapshot was taken.
* The cloud snapshot started at around 11:50 am on that device and you can see that before the cloud snapshot, there was no cloud storage used.
* Once the cloud snapshot completed, the cloud storage utilization shot up 0.89 GB.
* While the cloud snapshot was in progress, there is also a corresponding peak in the IO from device to cloud.



### Local storage usage
These charts show the total utilization for the device, which will be more than primary storage usage because it includes the SSD linear tier. This tier contains an amount of data that also exists on the device's other tiers. The capacity in the SSD linear tier is cycled so that when new data comes in, the old data is moved to the HDD tier (at which time it is deduplicated and compressed) and subsequently to the cloud.
Over time, primary storage used and local storage used will most likely increase together until the data begins to be tiered to the cloud. At that point, the local storage used will probably begin to plateau, but the primary storage used will increase as more data is written.
The following charts show the primary storage used for a StorSimple device when a cloud snapshot was taken. The cloud snapshot started at 11:50 am and the local storage started decreasing at that time. The local storage used went down from 1.445 GB to 1.09 GB. This indicates that most likely the uncompressed data in the linear SSD tier was deduplicated, compressed, and moved into the HDD tier. Note that if the device already has a large amount of data in both the SSD and HDD tiers, you may not see this decrease. In this example, the device has a small amount of data.

## Performance
**Performance** tracks metrics related to the number of read and write operations between either the iSCSI initiator interfaces on the host server and the device or the device and the cloud. This performance can be measured for a specific volume, a specific volume container, or all volume containers. Performance also includes CPU utilization and Network throughput for the various network interfaces on your device.
### I/O performance for initiator to device
The chart below shows the I/O for the initiator to your device for all the volumes for a production device. The metrics plotted are read and write bytes per second. You can also chart read, write, and outstanding IO, or read and write latencies.

### I/O performance for device to cloud
For the same device, the I/O operations are plotted for the data from the device to the cloud for all the volume containers. On this device, the data is only in the linear tier and nothing has spilled to the cloud. There are no read-write operations occurring from device to the cloud. Therefore, the peaks in the chart are at an interval of 5 minutes that corresponds to the frequency at which the heartbeat is checked between the device and the service.
For the same device, a cloud snapshot was taken for volume data starting at 11:50 am. This resulted in data flowing from the device to the cloud. Writes were served to the cloud in this duration. The IO chart shows a peak in the Write Bytes/s corresponding to the time when the snapshot was taken.

### Network throughput for device network interfaces
**Network throughput** tracks metrics related to the amount of data transferred from the iSCSI initiator network interfaces on the host server and the device and between the device and the cloud. You can monitor this metric for each of the iSCSI network interfaces on your device.
The following charts show the network throughput for the Data 0, 1 1 GbE network on your device, which was both cloud-enabled (default) and iSCSI-enabled. On this device on June 14 at around 9 pm, data was tiered into the cloud (no cloud snapshots were taken at that time which points to tiering being the mechanism to move the data into the cloud) which resulted in IO being served to the cloud. There is a corresponding peak in the network throughput graph for the same time and most of the network traffic is outbound to the cloud.

If we look at the Data 1 interface throughput chart, another 1 GbE network interface which was only iSCSI-enabled, then there was virtually no network traffic in this duration.

## CPU utilization for device
**CPU utilization** tracks metrics related to the CPU utilized on your device. The following chart shows the CPU utilization stats for a device in production.

## Next steps
* Learn how to [use the StorSimple Device Manager service device dashboard](storsimple-device-dashboard.md).
* Learn how to [use the StorSimple Device Manager service to administer your StorSimple device](storsimple-manager-service-administration.md).
|
C# | UTF-8 | 3,554 | 2.8125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | using FluentAssertions;
using Xunit;
namespace System.Linq.Dynamic.Core.Tests;
public partial class ExpressionTests
{
[Fact]
public void ExpressionTests_Add_Number()
{
// Arrange
var values = new[] { -1, 2 }.AsQueryable();
// Act
var result = values.Select<int>("it + 1");
var expected = values.Select(i => i + 1);
// Assert
result.Should().Contain(expected);
}
[Fact]
public void ExpressionTests_Add_String()
{
// Arrange
var values = new[] { "a", "b" }.AsQueryable();
// Act
var result = values.Select<string>("it + \"z\"");
var expected = values.Select(i => i + "z");
// Assert
result.Should().Contain(expected);
}
[Fact]
public void ExpressionTests_SupportedOperands_IAddAndSubtractSignatures_DateTime_Subtracts_DateTime()
{
// Arrange
var values = new[]
{
new
{
Value1 = new DateTime(2023, 1, 4),
Value2 = new DateTime(2023, 1, 3)
}
}.AsQueryable();
// Act
var result = values.Select<TimeSpan>("Value1 - Value2");
var expected = values.Select(x => x.Value1 - x.Value2);
// Assert
result.Should().Contain(expected);
}
[Fact]
public void ExpressionTests_SupportedOperands_IAddAndSubtractSignatures_DateTime_Adds_TimeSpan()
{
// Arrange
var values = new[]
{
new
{
Value1 = new DateTime(2023, 1, 4),
Value2 = TimeSpan.FromDays(1)
}
}.AsQueryable();
// Act
var result = values.Select<DateTime>("Value1 + Value2");
var expected = values.Select(x => x.Value1 + x.Value2);
// Assert
result.Should().Contain(expected);
}
[Fact]
public void ExpressionTests_SupportedOperands_IAddAndSubtractSignatures_DateTime_Subtracts_TimeSpan()
{
// Arrange
var values = new[]
{
new
{
Value1 = new DateTime(2023, 1, 4),
Value2 = TimeSpan.FromDays(1)
}
}.AsQueryable();
// Act
var result = values.Select<DateTime>("Value1 - Value2");
var expected = values.Select(x => x.Value1 - x.Value2);
// Assert
result.Should().Contain(expected);
}
[Fact]
public void ExpressionTests_SupportedOperands_IAddAndSubtractSignatures_TimeSpan_Adds_TimeSpan()
{
// Arrange
var values = new[]
{
new
{
Value1 = TimeSpan.FromDays(1),
Value2 = TimeSpan.FromDays(1)
}
}.AsQueryable();
// Act
var result = values.Select<TimeSpan>("Value1 + Value2");
var expected = values.Select(x => x.Value1 + x.Value2);
// Assert
result.Should().Contain(expected);
}
[Fact]
public void ExpressionTests_SupportedOperands_IAddAndSubtractSignatures_TimeSpan_Subtracts_TimeSpan()
{
// Arrange
var values = new[]
{
new
{
Value1 = TimeSpan.FromDays(7),
Value2 = TimeSpan.FromDays(1)
}
}.AsQueryable();
// Act
var result = values.Select<TimeSpan>("Value1 - Value2");
var expected = values.Select(x => x.Value1 - x.Value2);
// Assert
result.Should().Contain(expected);
}
} |
Markdown | UTF-8 | 2,585 | 3.546875 | 4 | [] | no_license | [shovel coding #2 leetcode - Add Two Numbers]
> 원문 링크 : https://leetcode.com/problems/add-two-numbers/description/
## Description
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
```
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
```
## Solution
```
var addTwoNumbers = function(l1, l2) {
var x = 0, y = 0, i = 0;
var arr1 = [];
var arr2 = [];
arr1[0] = [];
arr1[1] = [];
while(l1) {
arr1[0].push(l1.val);
l1 = l1.next;
}
while(l2) {
arr1[1].push(l2.val);
l2 = l2.next;
}
var length = (arr1[0].length > arr1[1].length) ? arr1[0].length : arr1[1].length;
while (i < length) {
if (arr1[0][i] === undefined) arr1[0][i] = 0;
if (arr1[1][i] === undefined) arr1[1][i] = 0;
var sum = arr1[0][i] + arr1[1][i] + x;
x = 0;
y = sum % 10;
x = parseInt(sum / 10);
arr2.push(y);
i++;
if ((i >= length) && (x > 0)) {
length += 1;
}
}
return arr2;
};
```
컴퓨터 없이 손으로만 짜보니 너무 힘들었다. 결국 머리 터지고 키보드를 두들겼다. 부끄럽다 저 코드... while이 몇개냐...
해결을 위한 주먹구구식 처리.
신기한건 속도는 나름 나왔다는 것. (your runtime beats 96.01% of javascript submissions.)
## Reference
### Other Solution
```
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
```
대부분 비슷하게 구현한 것으로 보인다.
## End
오직 머리와 손으로 풀려고 하다보니 어려움이 이만저만 아니다. 결국 컴퓨터의 힘을 빌리게 되지만, 조금씩 하다보면 능숙한 손코딩 / 뇌컴파일링 / 눈디버깅이 되지 않을까?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.