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 |
|---|---|---|---|---|---|---|---|
C | UTF-8 | 8,935 | 3.4375 | 3 | [] | no_license | // ATM code by using c programming language
#include<stdio.h>
#include<stdlib.h>
void pingenerate();
int pin(int a);
void condition();
int balance(int amount);
int credit(int credit_amount);
int check_account(int account_number);
int main(){
int option;
//To disply the option
printf(" 1.How to use the YASH ATM\n");
printf("2. BANKING\t"); printf("3. PIN GENERATE\t");
printf("\n4. PIN CHANGE\t"); printf("5. TRANSFER\t");
printf("\n**********************************************************");
printf("\nEnter the option number: ");
scanf("%d",&option);
//First switch statement
long long int count=0;
int p,ret,option2; //Variable declaration
switch(option)
{
case 1: //First switch case 1
//conditions of the yash Atm
condition();
break;
case 2:
//banking
printf("1. WITHDRAWL\t"); printf("2. BALANCE ENQUIRY\t");
printf("\n3. MINISTATEMENT\t"); printf("4. CREDIT\t");
printf("\n*********************************************************************");
printf("\nEnter the option number: ");
scanf("%d",&option2);
switch(option2){
case 1:
//Withdrawl
printf("Enter your pin number: ");
scanf("%d",&p);
ret=pin(p); //Function call
if(ret==4){
long long int amount,available=100000,available1;
printf("Enter the money: ");
scanf("%lld",&amount);
ret=balance(amount); //function call
if(ret==1){
available -= amount;
if(available>=0){
printf("\nPlease collect your cash");
printf("\nAvailable balance is : %lld",available);
printf("\nThank you for using YASH ATM..\nVisit Again");
}else{
printf("Sorry!\nyou don't have sufficient money in your account\n");
printf("available Balance is: %lld",available1);
printf("\nVisit again");
}
}
}
break;
case 2:
//balance ENQUIRY
printf("Enter your pin number: ");
scanf("%d",&p);
ret=pin(p);
int available=100000;
if(ret==4){
printf("Available balance is:%d",available);
printf("\nThank you for using YASH ATM");
}else{
printf("Wrong pin number!\n");
}
break;
case 3:
//ministstment
printf("Enter your pin number: ");
scanf("%d",&p);
ret=pin(p);
if(ret==4){
printf("Transection 1: ");
printf("Transection 2: ");
printf("Transection 3: ");
printf("Transection 4: ");
printf("Transection 5: ");
}
break;
case 4:
//credit
printf("Enter your pin number: ");
scanf("%d",&p);
ret=pin(p);
if(ret==4){
long long int credit_cash;
printf("Enter the amount to credit:");
scanf("%lld",&credit_cash);
if(1==credit(credit_cash))
printf("%lld cash is succesfully credited\n",credit_cash);
}else{
printf("Wrong pin number!\n");
printf("please try again!\n\n***** Thanks for using YASH ATM *****\n");
}
break;
}
break;
case 3:
//pin generate
pingenerate();
break;
case 4:
//pin CHANGE
printf("Enter pin number:");
scanf("%d",&p);
ret=pin(p);
if(ret==4){
int new_pin;
printf("Enter new pin number:");
scanf("%d",&new_pin);
ret=pin(new_pin);
if(ret==4) printf("your pin is succesfully generated\n");
else printf("Your pin is not generated!\n");
}
break;
case 5:
//transfer
printf("Enter pin number:");
scanf("%d",&p);
ret=pin(p);
if(ret==4){
long long int atm_number;
printf("Enter tranfered ATM number:");
scanf("%lld",&atm_number);
ret=check_account(atm_number);
if(ret<=16){
long long int trans_amount;
printf("Enter the amount:");
scanf("%lld",&trans_amount);
printf("%lld cash is succesfully transfered\n",trans_amount);
printf("Thanks for using YASH ATM\n");
}else printf("Please enter the valaid ATM number\nThanks for using YASH ATM\n");
}else{
printf("Please enter the valid pin number!\n");
}
break;
}
return 0;
}
//pin generate function
void pingenerate(){
long long account,mobile;
printf("Enter the your account number:");
scanf("%lld",&account);
int ret;
ret=check_account(account);
if(ret>=10){
printf("Enter your mobile number:");
scanf("%lld",&mobile);
ret=check_account(mobile);
if(ret==10){
int p;
printf("Enter your new pin number:");
scanf("%d",&p);
ret=pin(p);
if(ret==4){
printf("New pin is succesfully generated\n");
}else{printf("This pin not generated!\nTry another pin number\n");}
}else{printf("please enter the valid mobile number!\nit must be linked with your account \n");}
}else{
printf("Please enter the valid account number!\n");
printf("Thank you for using YASH ATM\n");
}
}
// pin checking function
//int remainder,remainder2;
int pin(int pin){
int remainder,remainder2;
int pin2; //Variable declaration
long long int count=0;
pin2=pin;
while(pin!=0)
{
remainder=pin%10;
pin=pin/10;
remainder2=pin%10;
if(remainder>remainder2){
count++;
}
}
return count;
}
//conditions function
void condition(){
printf("\nCondition of the YASH ATM is as follows:\n");
printf("\n1. First of all enter the option number\n");
printf("2. secrete pin number is must have 4 digits and\n");
printf(" it is in the form of ascending order\n");
printf("3. Account number is must have greater than 15 digits\n");
printf("4. ATM number must have 16 digits\n");
printf("5.In your account fixed deposit amount is: 100000\n");
}
// available balance function
int balance(int amount){
int amount2;
amount2=amount;
if(amount>40000)
{
printf("\n\nSorry! plese enter the amount below 40000 ");
printf("\nthank you for using YASH ATM");
}else{
return 1;
}
}
// credit function
int credit(int credit_money){
long long int credit_amount=credit_money;
do{
if(credit_amount<=40000){
printf("place the %d money\n",credit_amount);
break;
}else{
printf("place money 40000\n");
credit_amount=credit_amount-40000;
}
}while(credit_amount!=0);
return 1;
}
//Account number checking
int check_account(int account_number){
long long int count=0;
while(account_number!=0)
{
account_number=account_number/10;
count++;
}
return count;
}
|
Markdown | UTF-8 | 7,975 | 2.84375 | 3 | [] | no_license | Title: My view on microservice arch
Date: 2020-08-24 09:48
Tags: thoughts
Slug: my view on microservice arch
Author: Feng Xia
<figure class="col s12">
<img src="images/DSC_1100384.JPG"/>
</figure>
This is an email w/ teammates regarding my thinkings on microservice
arch and a few other things happening in the project which I
dislike.
Read at your convenience ~~
# SOA is hard, and I haven't seen it working
I first learned [SOA][1] (and an IBM [book][2], very comprehensive) in
2013. I was in charge of designing the architecture of a 3-million $$
project for a Fortune 500 company. Yes it was SOA-ed, but not, no one
can implement it.
I have been in this trade long enough to see these patterns come and go,
every so many years they come back in a new emperor's
dress. Microservice arch seems to be the same thing. It's popular in all
meetings and talks. We assume ourselves ignorant if we can't name a
single project personally that has successfully pulled it off. But the
reality, I'm afraid, is that except a few deep pocket giants, no one has
done it according to book, and it never will.
SOA requires a ESB (enterprise service bus) for messaging (data), and
[BPM][4] engine for workflow orchestration. Both concepts are sound. I
love them. But they are very difficult to implement. The bottleneck is
not technology, but to abstract biz workflow so much so it can be
delegated to BPM engine, and maintenance (BPMN is too hard for client to
learn) because biz logic is constantly changing.
# Talk is cheap (rant)
It's a cheap word to make one look good and sophisticated. But here is
my view — if you propose it, you do it. I'm frustrated that
_architects_ roll of their tongue these buzz words as if they are ready
to grab, but they never code any of them, and they usually end the
sentence "Any question? If no, you do it".
There is another popular version of the same superficial talk in China,
[so-and-so technology is mature and simple][7] used to justify the proposal
is low risk.. just because you can say the word, doesn't make it
simple. There are different level of credits to this statement (best ->
worst, in order):
1. Yourself has coded it, even as small part of a large proj/module.
2. You have a die-hard buddy John, and he has done it and showed to you
before.
3. Your friend John has a friend Alex who claims he is coding it.
4. You and John and Alex all read about it on a SO post, or a book, or a
meetup, and know it's a trendy thing to do right now.
5. You all know that Google is using this technology and it's
awesome (but, are you Google?)
You get the spirit. I had same conversation w/ my client in 2013. It's a
common mistake non-engineer make. Just because Google can do it, doesn't
mean I can, or this team can. There are plenty such example in
life. Pick up any Physics book, the theory of atomic bomb is
printed. Can you then build one? Yeah we all know US has built a bunch
for a while, does it make it easy if you, or your country, to build one?
Talkers don't care details; but they dont sweat making the claim
that "it is simple", either.
# container, microservice
Microservice architecture is good, but too good to be true. Forget about
benefits. Let's talk problems we can perceive.
1. It's not justified _monotholic_ design is natively bad. One common
sales pitch is "your company's systems are all silos, and mine is a
one-stop-shop".
If each micro-service is a full stand-alone thing, aren't we then
creating a bunch of _silos_?
2. Modular.
Code naturally become modular because repetitive pattern emerge
during coding, and I hate to copy&paste. So up to 10th time, I start
think to make it a _module_ (whatever the name is) so I write one
line to call it. I'm sure you echo this.
I worked w/ an IT woman in 2010. At a lunch break, we were talking
how tolerant you are before you want to _automate_ sth. I considered
myself pretty hardcore to eliminate repetitive works using
scripts. Her answer was, "1". It's an exaggeration I thought. But the
mentality is sound -- constantly think how to combine things into a
logical group, thus "module", so to save yourself the trouble.
3. Top down design.
Top down to do modular in design is great, if the person has deep
knowledge of the domain, and is responsible. His/her view essentially
makes decisions that function XYZ should be a service/module on its
own, or not. It's a very difficult decision. Whoever says it's easy
is a liar.
My first job was in a semiconductor company making lithography
machine. The entire project (300+ people) was directly by this one
guy. He was an engineer, 60s maybe, gave us a talk every week, and he
knew everything of that product -- mechanical, real-time control (my
job), everything. I haven't ever met such situation after. Guru is
wonderful, if they are real. In 99.999% cases, it's _con artist_ w/
impressive title.
4. Container.
Container is a packaging choice. It can't package anything. Some code
can and benefit from it; some don't. The one single blocker I would
consider is that it is a single process -- if your thing can live w/
it, good. Otherwise, you need other trick to scale horizontally,
which adds complexity in knowledge and maintenance. Therefore,
speaking "containerizing" sth as if it were a given is ignorant (the
atomic bomb example above).
My view is that a container is yesterday's CD/ISO. Fit your music on
a CD doesn't make your music suddenly good, if it were bad.
By choosing docker and k8s, it comes an _ecosystem_ that makes things
_easier_. But. It shouldn't replace the knowledge if you were to do
it without them -- if you can't maintain an accounting book using
paper and ink (let's say all the Excels are dead today), are you
still an accountant? These ecosystems, like python native and 3rd
party libraries, require you to learn, to try, and some work out of
box, others don't as claimed. So, it's same engineering practice, not
magic.
I know LXCO architecture is microservice _oriented_, at least some
components, such as an aggregator (API proxy), access gateway. It's a
living example to examine. I don't know the status of it, nor how
good/bad it is. Find it out yourself if you are interested in. Talk to
engineers who code it, not manager's PPT.
# in CP?
We can't, and we shouldn't.
Service MUST maintains its own state. Each will have at least an admin
interface (aka. UI), and an API.
Therefore, there can't be one UI team coding all these UIs. Each service
has a UI person to code and maintain and add feature and debug. Same for
UX.
This leads to more considerations -- how to reuse components, or not?
and common technology stack, or not?...
CP is sort of service-oriented. What can be done is to break up
components into its own repo, its own build pipeline, its own release
schedule, and of course, finish each w/ an admin interface and API if
missing.
Now, the million $$ problem, is the STATEs. The complexity has been
hidden by Postgres & Scylla, because [DB's model and constraints][5]
**guarantee** a logical relationship between two data points. But in a
group of isolated services, it's fishy. I don't have knowledge to
suggest further reading or thinking. At least, read [this][6].
Remember. Technology might be _mature_, but until we built one crude
versioin, that wonderful theory is, theory.
[1]: https://en.wikipedia.org/wiki/Service-oriented_architecture
[2]: https://www.redbooks.ibm.com/redbooks/pdfs/sg246303.pdf
[3]: https://en.wikipedia.org/wiki/Enterprise_service_bus
[4]: https://en.wikipedia.org/wiki/Business_Process_Model_and_Notation
[5]: https://www.codeproject.com/Articles/359654/11-important-database-designing-rules-which-I-fo-2
[6]: https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing
[7]: {filename}/thoughts/tech%20maturity.md
|
Java | UTF-8 | 977 | 2.21875 | 2 | [] | no_license | package ar.edu.unlam.diit.scaw.services;
import java.util.List;
import ar.edu.unlam.diit.scaw.entities.Usuario;
public interface UsuarioService {
public void crearUsuario(Usuario usuario) throws Exception;
public Boolean usuarioYaExiste(String username);
public List<Usuario> getListaDeUsuarios();
public Usuario getUsuarioPorNombre(String nombreUsuario);
public Integer getLogueo(String nombre, String contrasena) throws Exception;
public List<Usuario> getListaDeUsuariosNoAprobados();
public Usuario buscarUnUsuarioPorId(Integer id);
public void aprobarUsuario(Usuario usuario);
public void eliminarUnUsuario(Integer idUsuario);
/*public void modificarUsuario(Integer idUsuario,String nombreU,String apellidoU,String contrasenaU,Integer estaParobado);
public List<Usuario>buscaUsuariosEnLaBDDConLike(String nombreUsuario,Integer usuarioActual);*/
public List<Usuario> getListaDeParticipantesDeUnaTareaPorIdTarea(Integer idTarea);
}
|
Java | UTF-8 | 2,697 | 2.265625 | 2 | [] | no_license | package com.forever.zhb.server.server.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import com.forever.zhb.server.server.BaseTest;
public class FileControllerTest extends BaseTest {
@Test
public void uploadTest() throws Exception {
System.out.println("---------");
String result = mockMvc.perform(
MockMvcRequestBuilders
.multipart("/file/upload")
.file(
new MockMultipartFile("files", "test.yaml", ",multipart/form-data", "hello upload".getBytes("UTF-8"))
)
.file(
new MockMultipartFile("files", "test1.yaml", ",multipart/form-data", "hello upload23232323".getBytes("UTF-8"))
)
.param("fileName", "test.yaml")
.header("from", "gateway")
).andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
/*MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"----------ThIs_Is_tHe_bouNdaRY_$", Charset.defaultCharset());
multipartEntity.addPart("files",new FileBody(new File("E:\\123.txt"),"txt"));
HttpGet request = new HttpGet("http://127.0.0.1:8080//file/upload");
request.setEntity(multipartEntity);
request.addHeader("Content-Type","multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response =httpClient.execute(request);
InputStream is = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
System.out.println("发送消息收到的返回:"+buffer.toString());*/
}
}
|
C# | UTF-8 | 467 | 2.703125 | 3 | [] | no_license | using System;
using System.Linq.Expressions;
namespace SpecUI.Extensions
{
public static class ExpressionExtensions
{
public static string GetName<T>(this Expression<Func<T>> exp) {
var body = exp.Body as MemberExpression;
if (body == null) {
var ubody = (UnaryExpression)exp.Body;
body = ubody.Operand as MemberExpression;
}
return body.Member.Name;
}
}
} |
Markdown | UTF-8 | 2,648 | 2.546875 | 3 | [
"MIT"
] | permissive | # p2p-gate
Шлюз Bank-gate обеспечивает перевод с карты на карту через банк Тинькофф, резерв Бин-Банк
---
Перед сборкой билда необходимо отредактировать следуцющие переменные в файле .config
**CALL_BACK_PAY***=http://<имя хоста докера>:8226/pay/confirm
**ERROR_PAGE** страница на которую будет переадресовываться пользователь при не успешной операции
**SUCCESS_PAGE** страница на которую будет переадресовываться пользователь при успешной операции
**RECEIVER_CARD** - карта на которую зачисляются деньги
**JWT_ISS** - справочная информация для генерации JWT
**JWT_KEY** - ключ шифрования JWT в формате Base64
**UUID_NAMESPACE** ключ для генерации jti - уникальный ID JWT (в формате UUID5)
Успешный ответ будет содержать переменную payid, в формате encrypted JWT, содержащую следующую информацию:
*{
"jti": "5e2e5974-b647-5eb9-b1c4-26070dcea4af",
"iat": 1571933200,
"sub": "fixed",
"iss": "ru.phone4pay",
"pay_id": "123456",
"sum": "100.0",
"transaction_id": "868720704"
}*
Успешность проведение операции проверяется по JWT:
1. Валидная цифровая подпись
2. Совпадение номера операции (pay_id) и суммы операции (sum) c данными инициации операции
3. iat - timestamp
4. JTI формируется как UUID5(UUID_NAMESPACE, pay_id+iat)
**Запуск собранного билда :**
docker run -d -p 8226:8226 <имя билда>
**8226** - http порт шлюза
Для тестирования работы шлюза можно использовать встроенную тестовую страницу
***http://<имя хоста докера>:8226/pay/page?payid=123456&sum=100&text=Test***
Обязательные параметры :
**payid** - ID платежной операции, устанавливается для идентификации ответа после успешного/не успешного выполнения перевода
**sum** - Сумма операции в формате float
**text** - Назначение платежа
|
C++ | UTF-8 | 3,440 | 2.6875 | 3 | [
"MIT",
"JSON"
] | permissive | #include "screenshot.hpp"
#include "../util/file_system.hpp"
#include <iostream>
#include <string>
#include <gtk/gtk.h>
#include <unistd.h>
#include <xcb/xcb.h>
const std::string g_defaultModule = "screenshot_static";
std::string g_filename = "";
std::string g_module = "";
GtkBuilder* g_pBuilder = nullptr;
GtkWidget* g_pMainWnd = nullptr;
// Can the application start capturing already?
// (GTK+ doesn't destroy the windows immediately so this will be used to tell whether it's been destroyed or not)
bool g_ProceedCapture = false;
void TakeScreenshot(std::string filename = "")
{
EasyGIF::App::ScreenshotStatic ss;
ss.RunUI();
if(filename == "")
filename = "./screenshot_static.png";
ss.Save(filename);
}
void RecordGIF(std::string filename = "")
{
EasyGIF::App::ScreenshotGIF sg;
sg.RunUI();
if(filename == "")
filename = "./screenshot_gif.gif";
sg.Save(filename);
}
extern "C" {
void ui_btn_capture_gif(GtkButton* widget, gpointer user_data)
{
GtkWidget* pCaptureWnd = gtk_widget_get_toplevel(GTK_WIDGET(widget));
gtk_widget_destroy(pCaptureWnd);
gtk_main_quit();
g_module = "screenshot_gif";
}
void ui_btn_capture_ss(GtkButton* widget, gpointer user_data)
{
GtkWidget* pCaptureWnd = gtk_widget_get_toplevel(GTK_WIDGET(widget));
gtk_widget_hide(pCaptureWnd);
gtk_widget_destroy(pCaptureWnd);
gtk_main_quit();
g_module = "screenshot_static";
}
void ui_btn_capture(GtkButton* widget, gpointer user_data)
{
std::cout << "You clicked \"Capture\"" << std::endl;
GtkWidget* pCaptureWnd = GTK_WIDGET(gtk_builder_get_object(g_pBuilder, "captureDlgWnd"));
std::cout << "captureDlgWnd grabbed" << std::endl;
gtk_widget_show(pCaptureWnd);
std::cout << "captureDlgWnd shown" << std::endl;
gtk_widget_destroy(g_pMainWnd);
std::cout << "mainWnd destroyed" << std::endl;
}
void ui_btn_capture_destroy(GtkButton* widget, gpointer user_data)
{
g_ProceedCapture = true;
}
}
int main(int argc, char** argv)
{
GError* error = nullptr;
gtk_init(&argc, &argv);
g_pBuilder = gtk_builder_new();
if(!gtk_builder_add_from_file(g_pBuilder, EasyGIF::FileSystem::GetAssetPath("./ui/ezapp.glade").c_str(), &error))
{
g_warning("%s", error->message);
//g_free(error);
return 1;
}
gtk_builder_connect_signals(g_pBuilder, nullptr);
gtk_builder_add_callback_symbol(g_pBuilder, "ui_btn_capture", G_CALLBACK(ui_btn_capture));
gtk_builder_add_callback_symbol(g_pBuilder, "ui_btn_capture_gif", G_CALLBACK(ui_btn_capture_gif));
gtk_builder_add_callback_symbol(g_pBuilder, "ui_btn_capture_ss", G_CALLBACK(ui_btn_capture_ss));
g_pMainWnd = GTK_WIDGET(gtk_builder_get_object(g_pBuilder, "mainWnd"));
// check if user wants to launch a specific module (e.g. screenshot_gif) right away
if(argc > 1)
g_module = argv[1];
if(argc > 2)
g_filename = argv[2];
if(g_module == "screenshot_static")
TakeScreenshot(g_filename);
else if(g_module == "screenshot_gif")
RecordGIF(g_filename);
else if(g_module != "")
std::cout << "Unknown module \"" << g_module << std::endl;
else if(g_module == "")
{
gtk_widget_show(g_pMainWnd);
gtk_main();
// TODO: This will need to be fixed
// but it works for now so I'll leave it like this
//if(g_ProceedCapture)
//{
if(g_module == "screenshot_static")
TakeScreenshot(g_filename);
else if(g_module == "screenshot_gif")
RecordGIF(g_filename);
//}
}
g_object_unref(G_OBJECT(g_pBuilder));
return 0;
}
|
C | UTF-8 | 3,974 | 4.0625 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <math.h>
/*
* Lab Sheet 3
*/
/* Question 1
Complete the function below which converts a hexadecimal string into its decimal value. (Do not use a C standard library function.)
The main function calls this function with an example hexadecimal value. Change this value to test your program.
*/
/* Converts individual Hex character to Dec */
int decDefine(char x) {
int decChar;
if(x == '0') {
decChar = 0;
}
else if (x == '1') {
decChar = 1;
}
else if (x == '2') {
decChar = 2;
}
else if (x == '3') {
decChar = 3;
}
else if(x == '4') {
decChar = 4;
}
else if (x == '5') {
decChar = 5;
}
else if (x == '6') {
decChar = 6;
}
else if (x == '7') {
decChar = 7;
}
else if (x == '8') {
decChar = 8;
}
else if (x == '9') {
decChar = 9;
}
else if(x == 'A' || x == 'a') {
decChar = 10;
}
else if (x == 'B' || x == 'b') {
decChar = 11;
}
else if (x == 'C' || x == 'c') {
decChar = 12;
}
else if (x == 'D' || x == 'd') {
decChar = 13;
}
else if (x == 'E' || x == 'e') {
decChar = 14;
}
else if (x == 'F' || x == 'f') {
decChar = 15;
}
return decChar;
}
/* Hex can be converted to Dec by the following:
* For "FF3", where "F" = 15 and "3" = 3, since Hex is a base 16 number
* Dec = 15*16^2 + 15*16^1 + 3*16^0
* So the Dec equivalent of the Hex character is multiplied by 16 raised
* to the power of the digit location.
* The last character has a location of 0, the 2nd to last is 1, and so on.
*/
long int hexToDec(char hex[]){
/* Calculates length of Hex code */
int len = strlen(hex);
long int deciCode = 0;
/* Calculates Dec equivalent of each Hex character and adds to 'deciCode' */
for(int i = 0; i <= len - 1; i++) {
deciCode = deciCode + decDefine(hex[i]) * pow(16, len - i - 1);
}
return deciCode;
}
/* Question 2
Complete the function below that print out a tree shape such as the following:
*
***
*****
*******
*********
***
***
***
***
Note you can (and probably should) implement additional functions to help.
You can assume that the width of the tree will be odd and hence every line will have an odd number of asterisks. The trunk will always have a width of three.
Call this function from the main to test your program.
*/
void printTree(int width, int trunkLength){
/* Used to calculate amount of whitespace before asterisks */
int whitespace;
int whitespaceReset = (width - 1)/2;
/* Used to print correct number of asterisks for tree */
int numLeaves;
int leavesReset = 1;
/* Used to determine when to stop printing asterisks for tree */
int widthReset = width;
printf("Tree:\n");
while(widthReset > 0) {
/* Prints whitespace before asterisks for leaves */
for(whitespace = whitespaceReset; whitespace > 0; whitespace--) {
printf(" ");
}
/* Prints asterisks */
for(numLeaves = 1; numLeaves <= leavesReset; numLeaves += 1) {
printf("*");
}
/* Reduces whitespace before asterisks and length of loop by 1 */
widthReset--;
whitespaceReset--;
/* Increases number of asterisks printed for next iteration by 2 */
if(leavesReset < width) {
leavesReset = leavesReset + 2;
}
/* Breaks out of loop is next iteration prints more asterisks than width */
else {
printf("\n");
break;
}
printf("\n");
}
int trunkWidth = 3;
/* Whitespace before asterisks for trunk */
int trunkWhite;
while(trunkLength > 0) {
/* Prints whitespace before asterisks for trunk */
for(trunkWhite = (width - 1)/2 - 1; trunkWhite > 0; trunkWhite--) {
printf(" ");
}
/* Prints asterisks for trunk */
for(widthReset = trunkWidth; widthReset > 0; widthReset--) {
printf("*");
}
printf("\n");
/* Reduces length of loop */
trunkLength--;
}
}
int main(void) {
char hex[40] = "FF3";
printf("The hex value %s is %ld in decimal\n\n", hex, hexToDec(hex));
int width = 13;
int trunkLength = 4;
printTree(width, trunkLength);
return 0;
} |
Java | UTF-8 | 4,269 | 2.6875 | 3 | [] | no_license | package com.agileengine.analyzer.parser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Parses the specified document and provides a functionality
* for manipulations with it.
*/
public class DocumentParser {
private static final Logger LOGGER = Logger.getLogger(DocumentParser.class.getName());
private static final String CHARSET_NAME = "UTF-8";
private static final String PATH_ELEMENTS_DELIMITER = " > ";
private final Path pathToFile;
public DocumentParser(String fileName) throws IOException {
pathToFile = Files.find(Paths.get(fileName), 8,
(path, basicFileAttributes) -> path.endsWith(fileName))
.findFirst()
.orElseThrow(FileNotFoundException::new);
}
public Element getElementById(String elementId) throws IOException {
Document document = getDocument();
String expression = "#" + elementId;
Elements foundElements = document.select(expression);
if (foundElements == null || foundElements.isEmpty()) {
LOGGER.log(Level.WARNING, "No elements with id " + elementId + " found");
return null;
}
if (foundElements.size() > 1) {
LOGGER.log(Level.WARNING, "There are more than one element with id " + elementId + " found");
}
Element resultedElement = foundElements.first();
LOGGER.log(Level.INFO, "Found element: " + resultedElement);
return resultedElement;
}
public Elements findSimilarElements(Element exampleElement) throws IOException {
String expression = getSameParentAndChildExpression(exampleElement);
Elements similarElements = getDocument().select(expression);
LOGGER.log(Level.INFO, "Found elements with the same parent and tag: " + similarElements.size());
return similarElements;
}
public static String getPathToElement(Element element) {
Elements parents = element.parents();
StringBuilder stringBuilder = new StringBuilder();
for (int i = parents.size() - 1; i >= 0; i--) {
Element parent = parents.get(i);
String elementDescription = getElementDescription(parent);
stringBuilder.append(elementDescription)
.append(PATH_ELEMENTS_DELIMITER);
}
stringBuilder.append(getElementDescription(element));
return stringBuilder.toString().trim();
}
private static String getElementDescription(Element element) {
String nodeName = element.nodeName();
Integer currentElementIndex = element.elementSiblingIndex();
List<Element> siblingElements = getSiblingsWithSameNodeName(element, nodeName);
String elementDescription;
if (!siblingElements.isEmpty()) {
elementDescription = appendElementIndex(currentElementIndex, siblingElements, nodeName);
} else {
elementDescription = nodeName;
}
return elementDescription;
}
private static String appendElementIndex(Integer currentElementIndex, List<Element> siblingElements,
String elementDescription) {
long similarSiblingsCount = siblingElements.stream()
.filter(el -> el.elementSiblingIndex() < currentElementIndex)
.count();
long elementIndex = similarSiblingsCount + 1;
elementDescription += "[" + elementIndex + "]";
return elementDescription;
}
private static List<Element> getSiblingsWithSameNodeName(Element element, String nodeName) {
return element.siblingElements().stream()
.filter(el -> el.nodeName().equals(nodeName))
.collect(Collectors.toList());
}
private Document getDocument() throws IOException {
return Jsoup.parse(pathToFile.toFile(), CHARSET_NAME);
}
private String getSameParentAndChildExpression(Element exampleElement) {
return exampleElement.parent().nodeName() + " > " + exampleElement.nodeName();
}
}
|
JavaScript | UTF-8 | 889 | 3.875 | 4 | [] | no_license | //"async and await make promises easier to write"
// async makes a function return a Promise
// await makes a function wait for a Promise
//here i am work with js promise
async function myDisplay()
{
try{
let myPromise = new Promise(function(myResolve, myReject)
{
setTimeout(function() {
let flag = false;
if(flag){
myResolve("fullfilled");
}
else{
myReject('not fullfilled')
}
},4000);
});
// myPromise.then(function(resolve)
// {
// console.log("promise"+resolve )
// }
// )
console.log( await myPromise);
}
catch(error){
console.log("error is " +error)
}
}
myDisplay();
|
Go | UTF-8 | 2,126 | 3.34375 | 3 | [] | no_license | package eventhandler
import (
"fmt"
"sync"
)
// Registry stores the concrete `eventhandler.Interface` implementations registered with the system.
type Registry struct {
mutex sync.RWMutex
registry map[EventType]Interface
}
// NewRegistry creates a new `Registry` object.
//
// This should typically only be used for testing or for niche scenarios that require isolation in the
// face of multi-tenancy -- the expected production scenario is to just use `GlobalRegistry`().
func NewRegistry() *Registry {
return &Registry{
registry: make(map[EventType]Interface),
}
}
var globalRegistry = NewRegistry()
// GlobalRegistry provides access to the one shared global `Registry` for the entire system to use.
func GlobalRegistry() *Registry {
return globalRegistry
}
// RegisterEventHandler registers an `eventhandler.Interface` implementation to be invoked at runtime
// for all events of a particular `EventType`.
//
// It returns `error` if a nil implementation is provided, or if this method has already previously been
// called for the same `EventType`.
//
// The call to this method is typically expected to be made in each handler package's `init`() function.
func (r *Registry) RegisterEventHandler(eventType EventType, eventHandler Interface) error {
r.mutex.Lock()
defer r.mutex.Unlock()
if eventHandler == nil {
return fmt.Errorf("nil EventHandler provided for EventType '%s'", eventType)
}
if _, dup := r.registry[eventType]; dup {
return fmt.Errorf("EventHandler for EventType '%s' is already registered", eventType)
}
r.registry[eventType] = eventHandler
return nil
}
// GetHandlerForEvent returns the previously-registered `eventhandler.Interface` implementation for
// a particular `EventType`.
//
// It returns `error` if no prior call to `RegisterEventHandler`() was made for the `EventType`.
func (r *Registry) GetHandlerForEvent(eventType EventType) (Interface, error) {
r.mutex.RLock()
eventHandler, ok := r.registry[eventType]
r.mutex.RUnlock()
if !ok {
return nil, fmt.Errorf("no EventHandler registered for EventType '%s'", eventType)
}
return eventHandler, nil
}
|
Java | UTF-8 | 2,484 | 3.578125 | 4 | [] | no_license | import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Set<Integer>> bingoLines;
List<List<Integer>> card = new ArrayList<List<Integer>>(5);
int number, plays, n = scanner.nextInt();
boolean finished;
scanner.nextLine();
while(n-- > 0) {
plays = 0;
finished = false;
card.clear();
for(int i=0; i<5; ++i){
card.add(Arrays.stream(scanner.nextLine().split("\\s+")).map(Integer::parseInt).collect(Collectors.toList()));
}
card.get(2).add(2, -1);
bingoLines = getBingoLines(card);
for(int i=0; i<75; ++i){
number = scanner.nextInt();
if(finished) continue;
++plays;
for(int j=0; j<bingoLines.size(); ++j){
int finalNumber = number;
bingoLines.get(j).removeIf(x -> x == finalNumber);
if(bingoLines.get(j).size() == 0 || (bingoLines.get(j).size() == 1 && bingoLines.get(j).contains(-1))) {
finished = true;
}
}
}
scanner.nextLine();
System.out.println("BINGO after " + plays + " numbers announced");
}
}
public static List<Set<Integer>> getBingoLines(List<List<Integer>> card) {
List<Set<Integer>> bingoLines = new ArrayList<Set<Integer>>();
// Get Rows
for(int i=0; i<5; ++i){
bingoLines.add(new HashSet<Integer>());
int index = i;
card.get(i).stream()
.forEach(x -> bingoLines.get(index).add(x));
}
// Get Columns
int initialSize = bingoLines.size();
for(int j=0; j<5; ++j){
bingoLines.add(new HashSet<Integer>());
for(int i=0; i<5; ++i){
bingoLines.get(initialSize+j).add(card.get(i).get(j));
}
}
// Diagonals
bingoLines.add(new HashSet<Integer>());
bingoLines.add(new HashSet<Integer>());
for(int i=0; i<5; ++i){
// 0,0 to 4,4
bingoLines.get(bingoLines.size()-2).add(card.get(i).get(i));
// 0,4 to 4,0
bingoLines.get(bingoLines.size()-1).add(card.get(i).get(4-i));
}
return bingoLines;
}
}
|
Java | UTF-8 | 509 | 1.960938 | 2 | [] | no_license | package com.lanpang.server.service.impl;
import com.lanpang.server.dao.UserDao;
import com.lanpang.server.dataobject.UserInfo;
import com.lanpang.server.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService implements IUserService {
@Autowired
private UserDao userDao;
@Override
public UserInfo findUserByOpenid(String uid) {
return userDao.findByOpenid(uid);
}
}
|
C# | UTF-8 | 856 | 3.109375 | 3 | [] | no_license | using Xunit;
namespace Solutions.Event2017.Day08 {
public class Tests {
[Fact]
public void Problem1_Example1() {
string[] input = {
"b inc 5 if a > 1",
"a inc 1 if b < 5",
"c dec -10 if a >= 1",
"c inc -20 if c == 10"
};
(var highestFinal, var highestStored) = Interpreter.LargestRegisterCount(input);
Assert.Equal(1, highestFinal);
Assert.Equal(10, highestStored);
}
[Fact]
public void FirstStar()
{
var actual = new Problem().FirstStar();
Assert.Equal("4448", actual);
}
[Fact]
public void SecondStar()
{
var actual = new Problem().SecondStar();
Assert.Equal("6582", actual);
}
}
}
|
Rust | UTF-8 | 1,363 | 3.484375 | 3 | [
"MIT"
] | permissive | /*!
* https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/599/week-2-may-8th-may-14th/3738/
*/
pub struct Solution {}
impl Solution {
// /// a normal way
// pub fn count_primes(n: i32) -> i32 {
// (0..n)
// .filter(|x| *x == 2 || *x % 2 != 0)
// .filter(|x| Self::is_prime(x))
// .count() as i32
// }
// fn is_prime(x: &i32) -> bool {
// *x > 1 && !(2..*x).filter(|i| i * i <= *x).any(|i| *x % i == 0)
// }
pub fn count_primes(n: i32) -> i32 {
if n <= 2 {
return 0;
}
let n = n as usize;
let mut nums = vec![true; n];
nums[0] = false;
nums[1] = false;
let mut i = 2;
while i * i < n {
if nums[i] {
let mut j = 2;
while i * j < n {
nums[i * j] = false;
j += 1;
}
}
i += 1;
}
nums.iter().filter(|&&x| x).count() as i32
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example_1() {
assert_eq!(Solution::count_primes(10), 4);
}
#[test]
fn example_2() {
assert_eq!(Solution::count_primes(0), 0);
}
#[test]
fn example_3() {
assert_eq!(Solution::count_primes(1), 0);
}
}
|
Go | UTF-8 | 3,441 | 3 | 3 | [
"Apache-2.0"
] | permissive | package beehive
import "fmt"
// CellKey represents a key in a dictionary.
type CellKey struct {
Dict string
Key string
}
// AppCellKey represents a key in a dictionary of a specific app.
type AppCellKey struct {
App string
Dict string
Key string
}
// Cell returns the CellKey of this AppCellKey.
func (ack AppCellKey) Cell() CellKey {
return CellKey{
Dict: ack.Dict,
Key: ack.Key,
}
}
// IsNil returns whether the AppCellKey represents no cells.
func (ack AppCellKey) IsNil() bool {
return ack.App == ""
}
// MappedCells is the list of dictionary keys returned by the map functions.
type MappedCells []CellKey
func (mc MappedCells) String() string {
return fmt.Sprintf("Cells{%v}", []CellKey(mc))
}
func (mc MappedCells) Len() int { return len(mc) }
func (mc MappedCells) Swap(i, j int) { mc[i], mc[j] = mc[j], mc[i] }
func (mc MappedCells) Less(i, j int) bool {
return mc[i].Dict < mc[j].Dict ||
(mc[i].Dict == mc[j].Dict && mc[i].Key < mc[j].Key)
}
// LocalBroadcast returns whether the mapped cells indicate a local broadcast.
// An empty set means a local broadcast of message. Note that nil means drop.
func (mc MappedCells) LocalBroadcast() bool {
return len(mc) == 0
}
type cellStore struct {
// colonyid -> term
Colonies map[uint64]uint64
// appname -> dict -> key -> colony
CellBees map[string]map[string]map[string]Colony
// beeid -> dict -> key
BeeCells map[uint64]map[string]map[string]struct{}
}
func newCellStore() cellStore {
return cellStore{
Colonies: make(map[uint64]uint64),
CellBees: make(map[string]map[string]map[string]Colony),
BeeCells: make(map[uint64]map[string]map[string]struct{}),
}
}
func (s *cellStore) assign(app string, k CellKey, c Colony) {
s.assignCellBees(app, k, c)
s.assignBeeCells(app, k, c)
}
func (s *cellStore) assignCellBees(app string, k CellKey, c Colony) {
dicts, ok := s.CellBees[app]
if !ok {
dicts = make(map[string]map[string]Colony)
s.CellBees[app] = dicts
}
keys, ok := dicts[k.Dict]
if !ok {
keys = make(map[string]Colony)
dicts[k.Dict] = keys
}
keys[k.Key] = c
}
func (s *cellStore) assignBeeCells(app string, k CellKey, c Colony) {
dicts, ok := s.BeeCells[c.Leader]
if !ok {
dicts = make(map[string]map[string]struct{})
s.BeeCells[c.Leader] = dicts
}
keys, ok := dicts[k.Dict]
if !ok {
keys = make(map[string]struct{})
dicts[k.Dict] = keys
}
keys[k.Key] = struct{}{}
}
func (s *cellStore) colony(app string, cell CellKey) (c Colony, ok bool) {
dicts, ok := s.CellBees[app]
if !ok {
return Colony{}, false
}
keys, ok := dicts[cell.Dict]
if !ok {
return Colony{}, false
}
c, ok = keys[cell.Key]
return c, ok
}
func (s *cellStore) cells(bee uint64) MappedCells {
dicts, ok := s.BeeCells[bee]
if !ok {
return nil
}
c := make(MappedCells, 0, len(dicts))
for d, dict := range dicts {
for k := range dict {
c = append(c, CellKey{Dict: d, Key: k})
}
}
return c
}
func (s *cellStore) updateColony(app string, oldc Colony, newc Colony,
term uint64) error {
if t, ok := s.Colonies[newc.ID]; ok {
if term < t {
return fmt.Errorf("cellstore: colony is older than %v", t)
}
}
s.Colonies[newc.ID] = term
bcells := s.BeeCells[oldc.Leader]
if oldc.Leader != newc.Leader {
s.BeeCells[newc.Leader] = bcells
delete(s.BeeCells, oldc.Leader)
}
acells := s.CellBees[app]
for d, dict := range bcells {
for k := range dict {
acells[d][k] = newc
}
}
return nil
}
|
Java | UTF-8 | 687 | 2.5 | 2 | [] | no_license | package com.ctbu.javateach666.util;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* BCrypt加密
* @author luokan
*
*/
public class BCryptEncoderUtil {
public final static String passwordEncoder(String password){
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
return hashedPassword;
}
public final static boolean passwordMatch(String noEncoderPass, String encodedPass){
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
boolean ismatch = passwordEncoder.matches(noEncoderPass, encodedPass);
return ismatch;
}
}
|
Python | UTF-8 | 1,817 | 2.75 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import cv2
import numpy as np
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def stretch(pixel, mini, maxi):
return (pixel-min_i)*(max_o-min_o)/(max_i-min_i)+min_o
def shrink(pixel, mini, maxi, mins, maxs):
return (max_s-min_s)*(pixel-min_i)/(max_i-min_i)+min_s
def realzado(image):
img = image #carga imagen de entrada
rows, cols, ch = img.shape
b,g,r = cv2.split(img)
equ_b = cv2.equalizeHist (b)
equ_g = cv2.equalizeHist (g)
equ_r = cv2.equalizeHist (r)
'''
#Filtro Paso-Bajo
blur_b = cv2.blur(b, (5,5))
blur_g = cv2.blur(g, (5,5))
blur_r = cv2.blur(r, (5,5))
#shrink image
shrink_img_b = np.zeros((int(rows),int(cols)), dtype='uint8')
shrink_img_g = np.zeros((int(rows),int(cols)), dtype='uint8')
shrink_img_r = np.zeros((int(rows),int(cols)), dtype='uint8')
for x in range(rows):
for y in range(cols):
shrink_img_b[x,y]=shrink(blur_b[x,y],30, 240,30,150)
shrink_img_g[x,y]=shrink(blur_g[x,y],30, 240, 30, 150)
shrink_img_r[x,y]=shrink(blur_r[x,y],30, 240, 30, 150)
#Subtract
img_subtract_b = cv2.subtract(b, shrink_img_b)
img_subtract_g = cv2.subtract(g, shrink_img_g)
img_subtract_r = cv2.subtract(r, shrink_img_r)
#Stretch
stretch_img_b = np.zeros((int(rows),int(cols)), dtype='uint8')
stretch_img_g = np.zeros((int(rows),int(cols)), dtype='uint8')
stretch_img_r = np.zeros((int(rows),int(cols)), dtype='uint8')
for x in range(rows):
for y in range(cols):
stretch_img_b[x,y]=stretch(img_subtract_b[x,y], 0, 100)
stretch_img_g[x,y]=stretch(img_subtract_g[x,y], 0, 100)
stretch_img_r[x,y]=stretch(img_subtract_r[x,y], 0, 100)
'''
return cv2.merge((equ_b,equ_g,equ_r))
|
JavaScript | UTF-8 | 1,800 | 2.609375 | 3 | [] | no_license | function MyStool(scene) {
CGFobject.call(this,scene);
this.tableAppearance = new CGFappearance(this.scene);
this.tableAppearance.loadTexture("../resources/images/table.jpg");
this.tableAppearance.setDiffuse(1,1,1,1);
this.tableAppearance.setSpecular(0,0,0,1);
this.tableAppearance.setShininess(200);
this.unitCube = new MyUnitCubeQuad(this.scene);
this.materialMetal = new CGFappearance(this.scene);
this.materialMetal.setAmbient(0.2,0.2,0.2,1);
this.materialMetal.setDiffuse(0.3,0.3,0.3,1);
this.materialMetal.setSpecular(0.4,0.4,0.4,1);
this.materialMetal.setShininess(120);
}
MyStool.prototype = Object.create(CGFobject.prototype);
MyStool.prototype.constructor = MyStool;
MyStool.prototype.display = function() {
// Top
this.scene.pushMatrix();
this.scene.translate(0, 2, 0);
this.scene.scale(2, 0.2, 2);
this.scene.setDiffuse(0.8, 0.6, 0.2, 1.0);
this.scene.setSpecular(0.1, 0.1, 0.1, 1.0);
this.tableAppearance.apply();
this.unitCube.display();
this.scene.popMatrix();
// Leg 1
this.scene.pushMatrix();
this.scene.translate(-.8, 1, 0.8);
this.scene.scale(0.3, 2, 0.3);
this.scene.setDiffuse(0.7, 0.7, 0.7, 1.0);
this.scene.setSpecular(0.8, 0.8, 0.8, 1.0);
this.materialMetal.apply();
this.unitCube.display();
this.scene.popMatrix();
// Leg 2
this.scene.pushMatrix();
this.scene.translate(0.8, 1, 0.8);
this.scene.scale(0.3, 2, 0.3);
this.unitCube.display();
this.scene.popMatrix();
// Leg 3
this.scene.pushMatrix();
this.scene.translate(0.8, 1, -0.80);
this.scene.scale(0.3, 2, 0.3);
this.unitCube.display();
this.scene.popMatrix();
// Leg 4
this.scene.pushMatrix();
this.scene.translate(-0.8, 1, -0.8);
this.scene.scale(0.3, 2, 0.3);
this.unitCube.display();
this.scene.popMatrix();
} |
Markdown | UTF-8 | 2,525 | 2.65625 | 3 | [] | no_license |
# Purpose
This is a basic API written as a learning exercise to understand http requests
writing to a Mongo-memory-server.
Tests demo the functionality.
# Infrastructure - INCREASE KNOWLEDGE OF DEV OPS
Node server can be run as a docker container.
To progress I first set up AWS Codepipeline for CI/CD. This was consuming high amount of resource so I stopped instance.
__jenkinsindocker__ This branch builds a pipeline using Jenkins in a docker container to push a docker image to repository
Jenkins:
- Build app from pipeline
- Tests - proceed if passes
- Build -> Docker image
- Push to DockerHub
NEXT STAGE:
- Ansible playbook to create infrastructure for build/ test/ deploy to webserver on EC2 LINUX AMI instance
# Dependencies
* Jest test runner
* Node version >= 10.15.3
* npm >= 6.4.1
* body-parser
* cors
* express
* helmet
* mongodb
* mongodb-memory-server
* morgan
# Process for Docker container running Jenkins
1. To start a docker container of jenkinsci
```
docker run \
-—name jenkins \
--rm \
-u root \
-p 8080:8080 \
-v jenkins-data:/var/jenkins_home \
-v /var/run/docker.sock:/var/run/docker.sock \
-v "$HOME":/home \
jenkinsci/blueocean
```
# Enhancement: docker-compose.yml
```docker-compose up``` follow up with ```docker-compose down``` to clean up
Container port has been opened on 8080
```
bash-4.4# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
35864caaa9e4 jenkinsci/blueocean "/sbin/tini -- /usr/…" 45 hours ago Up 45 hours 0.0.0.0:8080->8080/tcp, 50000/tcp dummyapi_jenkins_1
```
2. Set up Jenkins with the admin password
3. Can access container via docker using name as shown above
docker exec -it dummyapi_jenkins_1 bash
Browse to http://localhost:8080
4. Stop Jenkins via CLI (ctrl + C), the settings for Jenkins repo are lost as container cleans up on stop.
5. Create initial pipeline as Jenkinsfile. - persists in git hub repo, along with /Jenkins/scripts
6. Pipeline downloads NODE docker image then builds - installing dependencies (npm install) and runs node app as a docker container.
7. Git pulled repo maps to home repo of Jenkins container downloaded to the node_modules workspace
(within the /var/jenkins_home/workspace/dummyapi_js directory in the Jenkins container).
|
Swift | UTF-8 | 5,719 | 2.5625 | 3 | [] | no_license | //
// SearchController.swift
// ClickAndShare
//
// Created by Madhusudhan B.R on 7/19/17.
// Copyright © 2017 Madhusudhan. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
class SearchController : UICollectionViewController,UICollectionViewDelegateFlowLayout,UISearchBarDelegate {
let cellId = "cell"
var users = [User]()
var filteredUsers = [User]()
lazy var searchBar: UISearchBar = {
let sb = UISearchBar()
sb.placeholder = "Enter search text"
sb.delegate = self
UITextField.appearance(whenContainedInInstancesOf:[UISearchBar.self]).backgroundColor = .white //UIColor.rgb(red: 230, green: 230, blue: 230)
return sb
}()
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredUsers = self.users.filter({ (user) -> Bool in
return user.username.lowercased().contains(searchText.lowercased())
})
if searchText.isEmpty {
filteredUsers = users
}
collectionView?.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(SearchCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.backgroundColor = UIColor.white
collectionView?.keyboardDismissMode = .interactive
fetchUsers()
collectionView?.alwaysBounceVertical = true
navigationController?.navigationBar.addSubview(searchBar)
let navBar = navigationController?.navigationBar
searchBar.anchor(top: navBar?.topAnchor, left: navBar?.leftAnchor, bottom: navBar?.bottomAnchor, right: navBar?.rightAnchor, paddingTop: 0, paddingLeft: 8, paddingBottom: 0, paddingRight: 8, width: 0, height: 0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchBar.isHidden = false
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filteredUsers.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SearchCell
let user = filteredUsers[indexPath.item]
cell.user = user
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
searchBar.isHidden = true
searchBar.resignFirstResponder()
let userProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout())
userProfileController.userId = filteredUsers[indexPath.item].uid
navigationController?.pushViewController(userProfileController, animated: true)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 60)
}
func fetchUsers(){
// Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
// guard let userDictionary = snapshot.value as? [String: Any] else { return }
// if snapshot.key == Auth.auth().currentUser?.uid {
// return
// }
//
// let user = User(uid: snapshot.key, dictionary: userDictionary)
// self.users.append(user)
//
//
// }) { (error) in
// print(error)
// }
//
// self.users.sort(by: { (user1, user2) -> Bool in
// return user1.username.compare(user2.username) == .orderedAscending
// })
// self.collectionView?.reloadData()
let _ = Database.database().reference().child("users").observeSingleEvent(of: .value, with: { (snapshot) in
guard let userDictionaries = snapshot.value as? [String: Any] else { return }
userDictionaries.forEach({ (key,value) in
guard let dict = value as? [String: Any] else { return }
if key == Auth.auth().currentUser?.uid {
return
}
if self.checkIfUserIsBlocked(userID: key) {
let user = User(uid: key, dictionary: dict)
self.users.append(user)
}
self.users.sort(by: { (user1, user2) -> Bool in
return user1.username.compare(user2.username) == .orderedAscending
})
})
self.filteredUsers = self.users
self.collectionView?.reloadData()
}) { (error) in
print(error)
}
}
func checkIfUserIsBlocked(userID: String) -> Bool {
let defaults = UserDefaults.standard
// var blockedList = [User]()
if let blockedList = defaults.object(forKey: "blockedUsersID") as? [String] {
for blockedUser in blockedList {
if userID == blockedUser{
print("returned false")
return false
}
else {
return true
}
}
}
return true
}
}
|
Java | UTF-8 | 1,868 | 3.546875 | 4 | [
"Apache-2.0"
] | permissive | package EffectiveJava3rd.hMethods;
//50 必要时进行防御性拷贝
public class H50 {
//愉快使用Java的原因,它是一种安全的语言(safe language)。
//必须防御性地编写程序,假定类的客户端尽力摧毁类其不变量。
//从Java8开始,使用Instant(或LocalDateTime或ZonedDateTime)代替Date。
//防御性拷贝是在检查参数(条目49)的有效性之前进行的,有效性检查是在拷贝上而不是在原始实例上进行的。虽然这看起来不自然,但却是必要的。
//不要使用clone方法对其类型可由不可信任子类化的参数进行防御性拷贝。
//在访问器中,与构造方法不同,允许使用clone方法来制作防御性拷贝。
//参数的防御性拷贝不仅仅适用于不可变类。每次编写在内部数据结构中存储对客户端提供的对象的引用的方法或构造函数时,请考虑客户端提供的对象是否可能是可变的。如果是,请考虑在将对象输入数据结构后,你的类是否可以容忍对象的更改。
//在将内部组件返回给客户端之前进行防御性拷贝也是如此。无论你的类是否是不可变的,在返回对可变的内部组件的引用之前,都应该三思。可能的情况是,应该返回一个防御性拷贝。
//记住,非零长度数组总是可变的。因此,在将内部数组返回给客户端之前,应该始终对其进行防御性拷贝。或者,可以返回数组的不可变视图。
//如果一个类有从它的客户端获取或返回的可变组件,那么这个类必须防御性地拷贝这些组件。
//如果拷贝的成本太高,并且类信任它的客户端不会不适当地修改组件,则可以用文档替换防御性拷贝,该文档概述了客户端不得修改受影响组件的责任。
}
|
Java | UTF-8 | 3,285 | 2.203125 | 2 | [] | no_license | package com.xuh.platform.module.account.controller;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.xuh.platform.base.constants.Constants;
import com.xuh.platform.base.controller.BaseController;
import com.xuh.platform.base.util.SpringUtil;
import com.xuh.platform.base.util.StringUtil;
import com.xuh.platform.base.util.UUIDGenerator;
import com.xuh.platform.module.account.entity.WxBaseAccount;
import com.xuh.platform.module.account.service.WxBaseAccountService;
/**
* 微信账号controller
* @author xufeng
* @date 2014.9.13
*/
@Controller
@RequestMapping("/account")
public class WxBaseAccountController extends BaseController{
@Autowired
private WxBaseAccountService wxBaseAccountService;
/**
* 首页跳转
* @return
*/
@RequestMapping
public ModelAndView intoPage(Model model) {
try {
//从session中获得微信账号信息
WxBaseAccount wxBaseAccount = (WxBaseAccount)SpringUtil.getSession().getAttribute(Constants.SESSION_WEIXIN_ACCOUNT);
model.addAttribute("wxBaseAccount", wxBaseAccount);
} catch (Exception e) {
e.printStackTrace();
}
return forword("module/account/accountAdd");
}
/**
* 保存(新增或编辑)
* @param communication
* @param response
*/
@RequestMapping(value="/save",method=RequestMethod.POST)
public @ResponseBody
void save(@ModelAttribute WxBaseAccount wxBaseAccount,HttpServletResponse response) {
if (wxBaseAccount==null||StringUtil.isEmpty(wxBaseAccount.getAccountid())) {
try {
wxBaseAccount.setAccountid(UUIDGenerator.generate());
wxBaseAccount.setUpdatetime(new Date());
wxBaseAccountService.save(wxBaseAccount);
sendSuccessMessage(response, "保存成功");
} catch (Exception e) {
e.printStackTrace();
sendSuccessMessage(response, "保存失败!");
}
} else {
try {
wxBaseAccount.setUpdatetime(new Date());
wxBaseAccountService.update(wxBaseAccount);
sendSuccessMessage(response, "编辑成功");
} catch (Exception e) {
e.printStackTrace();
sendFailureMessage(response, "编辑失败!");
}
}
//向session中设置微信账号
SpringUtil.getSession().setAttribute(Constants.SESSION_WEIXIN_ACCOUNT,wxBaseAccount);
}
/**
* 验证微信账户是否绑定
* @return
*/
@RequestMapping(value="validate",method=RequestMethod.POST)
public void validate(HttpServletResponse response) {
try {
//从session中获得微信账号信息
WxBaseAccount wxBaseAccount = (WxBaseAccount)SpringUtil.getSession().getAttribute(Constants.SESSION_WEIXIN_ACCOUNT);
if(wxBaseAccount!=null){
sendSuccessMessage(response, "");
}else{
sendFailureMessage(response, "未绑定微信账号,请先绑定微信账号!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
TypeScript | UTF-8 | 1,180 | 2.609375 | 3 | [
"MIT"
] | permissive | import type { PayloadAction } from '@reduxjs/toolkit';
import { initialBubbleState } from '../../state';
import type {
BubbleStateElementsEnvironmentAction,
BubbleStateElementsEnvironmentItemList,
BubbleState,
} from '@bubble/types';
export const addEnvironmentInList = (
state: BubbleState,
action: PayloadAction<BubbleStateElementsEnvironmentItemList>
): void => {
state.elements.environment.list = [
...state.elements.environment.list,
action.payload,
];
};
export const removeEnvironmentInList = (
state: BubbleState,
action: PayloadAction<{ id: string }>
): void => {
state.elements.environment.list = state.elements.environment.list.filter(
(item) => item.id !== action.payload.id
);
};
export const resetEnvironment = (state: BubbleState): void => {
state.elements.environment = initialBubbleState.elements.environment;
};
export const setActionEnvironment = (
state: BubbleState,
action: PayloadAction<BubbleStateElementsEnvironmentAction>
): void => {
state.elements.environment.action = action.payload;
};
export const resetActionEnvironment = (state: BubbleState): void => {
state.elements.environment.action = null;
};
|
C# | UTF-8 | 1,469 | 2.84375 | 3 | [] | no_license | using System.Linq;
using FoodCalendar.BL.Models;
using FoodCalendar.DAL.Entities;
using FoodCalendar.DAL.Factories;
namespace FoodCalendar.BL.Mappers
{
public static class MealMapper
{
public static MealModel MapEntityToModel(Meal entity)
{
if (entity != null)
{
return new MealModel()
{
Id = entity.Id,
MealName = entity.MealName,
Calories = entity.Calories,
TotalTime = entity.TotalTime,
Process = ProcessMapper.MapEntityToModel(entity.Process),
IngredientsUsed = entity.IngredientsUsed.Select(IngredientAmountMapper.MapEntityToModel).ToList()
};
}
return null;
}
public static Meal MapModelToEntity(MealModel model, EntityFactory entityFactory)
{
var entity = entityFactory.Create<Meal>(model.Id);
entity.Id = model.Id;
entity.MealName = model.MealName;
entity.Calories = model.Calories;
entity.TotalTime = model.TotalTime;
entity.Process = ProcessMapper.MapModelToEntity(model.Process, entityFactory);
entity.IngredientsUsed = model.IngredientsUsed
.Select(ia => IngredientAmountMapper.MapModelToEntity(ia, entityFactory))
.ToList();
return entity;
}
}
} |
SQL | UTF-8 | 1,001 | 3.359375 | 3 | [] | no_license | drop database LzAGV;
create database LzAGV;
use LzAGV;
-- creat table
-- t_transport_plan
create table t_transport_plan(
id int(8) unsigned primary key auto_increment,
product varchar(30),
start_place varchar(30),
end_place varchar(30),
car_num varchar(10),
start_time timestamp default CURRENT_TIMESTAMP,
end_time timestamp default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
st tinyint(4)
);
-- t_his_transport
create table t_his_transport(
id int(8) unsigned primary key auto_increment,
product varchar(30),
start_place varchar(30),
end_place varchar(30),
car_num varchar(10),
start_time timestamp default CURRENT_TIMESTAMP,
end_time timestamp default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
);
-- 创建触发器,当t_transport_plan的st字段,更新值为1后,将当期记录备份,然后删除
--create trigger backupUpdateTrsPlanColSt
-- after update on t_transport_plan
-- for each row
--begin
--
--end
-- end
--commit;
|
Ruby | UTF-8 | 1,308 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | Dir.chdir("..") if File.basename(Dir.pwd) == "examples"
$LOAD_PATH.unshift(Dir.pwd + "/lib")
require "use"
module Mod_A
def meth_a
"hello"
end
def meth_b
"world"
end
end
module Mod_B
def meth_a
"goodbye"
end
def meth_b
"new york"
end
def meth_c
"adios"
end
end
# Various ways to mixin methods using 'use'. Note that I am intentionally
# putting multiple 'use' statements within the classes for the sake of brevity
# and demonstration. In practice, you would not use more than one per module.
#
class Foo
use Mod_A # include all methods from Mod_A
use Mod_A, :meth_a # or, include only meth_a from Mod_A
use Mod_A, include => :meth_a # same as above
end
class Bar
use Mod_B, :include => [:meth_b, :meth_c] # include only meth_a and meth_b
use Mod_B, :exclude => :meth_c # same net result as above
end
class Baz
use Mod_A, :meth_a # mixin meth_a from Mod_A
use Mod_B, :alias => {:meth_a, :meth_z} # mixin meth_a from Mod_B, but as meth_z
end
# Alias every method from Mod_B, as well as mixin Mod_A's meth_b.
class Zap
use Mod_B, :alias => {
:meth_a => :meth_x,
:meth_b => :meth_y,
:meth_c => :meth_z
}
use Mod_A, :meth_b
end
|
Markdown | UTF-8 | 8,498 | 3.140625 | 3 | [
"MIT"
] | permissive | ---
title: "Quickstart and Examples"
---
`parallel`'s main goal is to make the process of parallelizing code transparent to us developers. For that, it offers 2 main functions (with their respective non-blocking versions):
* `parallel.map`: to parallelize the same function with multiple arguments.
* `parallel.par`: to spawn different functions.
### `parallel.map`
Used to spawn multiple executions of the same function with different parameters:
```python
def download_and_store(url, expected_code=200):
resp = requests.get(url)
if resp.status_code != expected_code:
raise ValueError()
result = store_in_db(resp.json())
return result
urls = ['https://python.org', 'https://rmotr.com', '...']
results = parallel.map(download_and_store, urls)
python_result = results[0]
```
Multiple params can be passed just as sequences:
```python
urls = [
('https://python.org', 204),
('https://rmotr.com', 201),
]
results = parallel.map(download_and_store, urls)
```
And in dictionaries:
```python
urls = {
'python': ('https://python.org', 204),
'rmotr': ('https://rmotr.com', 201),
}
results = parallel.map(download_and_store, urls)
python_result = results['python']
```
(more about parameters below)
#### `parallel.par`
Used when you need to run different functions in parallel:
```python
def get_price_bitcoin(exchange):
pass
def get_price_ether(exchange):
pass
def get_price_ripple(exchange):
pass
def index(request):
prices = parallel.par({
'btc': (get_price_bitcoin, 'bitstamp')
'eth': parallel.future(get_price_ether, exchange='bitfinex'),
'xrp': parallel.future(get_price_ripple, 'bitstamp'),
})
return render_template('index.html', context={
'prices': prices
})
```
We'll keep using these same examples to explore all the features of `parallel`. For most parts, these will work in the same way for all `map`, `async_map`, `par` and `async_par`.
### Choosing an executor
`parallel` can transparently provide multithreading or multiprocess execution for your code.
```python
# Multithreading:
results = parallel.thread.map(download_and_store, urls) # Attribute
results = parallel.map(download_and_store, urls,
executor=parallel.THREAD_EXECUTOR) # Parameter
# Multiprocessing:
results = parallel.process.map(download_and_store, urls) # Attribute
results = parallel.map(download_and_store, urls,
executor=parallel.PROCESS_EXECUTOR) # Parameter
```
Parameters for executors can be passed directly (similar to `concurrent.futures`):
```python
results = parallel.map(
download_and_store, urls,
executor=parallel.THREAD_EXECUTOR,
timeout=10,
max_workers=5)
```
### Decorating functions
If you rely on parallel tasks in a constant basis, you can choose to decorate the function to make it easier for later:
```python
@parallel.decorate
def download_and_store(url):
pass
urls = ['https://python.org', 'https://rmotr.com', '...']
results = download_and_store.map(urls) # Use the function as a handler
```
Executors and parameters all work in the same way:
```python
results = download_and_store.thread.map(urls, timeout=10, max_workers=5)
results = download_and_store.process.map(urls, timeout=10, max_workers=5)
```
For `parallel.par`, the advantage of decorating functions is the easy passage of parameters:
```python
@parallel.decorate
def get_price_bitcoin(exchange):
pass
@parallel.decorate
def get_price_ether(exchange):
pass
prices = parallel.par({
'btc': get_price_bitcoin.future('bitstamp'),
'eth': get_price_ether.future(exchange='bitfinex'),
})
```
Any decorated function can still be used normally, the decorator only adds the `parallel` attributes:
```python
result = download_and_store('https://python.org')
btc = get_price_bitcoin('bitstamp')
```
## Parameters for ease of mind
One of the biggest limitations with `concurrent.futures` is the passage of parameters. `parallel` resolves all those issues and even incorporates some good ideas to simplify your work:
### Sequences or dictionaries
Do you prefer to see results in a sequential manner, or in a _named_ one? Either can be used:
```python
def download_and_store(url):
pass
# Sequential:
results = parallel.map(download_and_store, [
'https://python.org',
'https://rmotr.com'
])
results == ['python.org results', 'rmotr.com results']
# Named (with a dictionary):
results = parallel.map(download_and_store, {
'python': 'https://python.org',
'rmotr': 'https://rmotr.com'
})
results == {
'python': 'python.org results',
'rmotr': 'rmotr.com results'
}
```
### Named and optional parameters
When functions get more advanced, or invocations vary dynamically, `concurrent.futures` is more limited. `parallel` works with all the use cases that you might encounter. Consider the following function as an example:
```python
def download_and_store(url, content_type, db_table='websites', log_level='info', options=None):
# ... some code ...
pass
```
##### Passing multiple arguments
In its simplest form, passing multiple ordered arguments works just by passing the parameters in a sequence:
```python
results = parallel.map(download_and_store, [
('https://python.org', 'json'), # download_and_store('https://python.org', 'json')
('https://rmotr.com', 'xml') # download_and_store('https://rmotr.com', 'xml')
])
```
##### Passing named parameters
To pass named parameters, just use a dictionary inside the parameter's sequence:
```python
results = parallel.map(download_and_store, [
# download_and_store('https://python.org', 'json', db_table='webpages')
('https://python.org', 'json', {'db_table': 'webpages'}),
# download_and_store('https://rmotr.com', 'xml', db_table='debug')
('https://rmotr.com', 'xml', {'log_level': 'debug'})
])
```
### Extras, to avoid repeating yourself
Instead of passing the same named parameter over and over again, pass it as an _extra_:
```python
results = parallel.map(download_and_store, [
('https://python.org', 'json'),
('https://rmotr.com', 'xml')
], extras={
'db_table': 'temporary_webpages'
})
```
In this example, all the URLs will be stored in `temporary_webpages`.
### Advanced use cases
When faced with very extreme scenarios of function invocation, you can resort back to `parallel.arg`. For example, if your function receives a dictionary as parameter, `parallel` by default will interpret it as a named parameter. To avoid that, just use `parallel.arg`:
```python
results = parallel.map(download_and_store, {
'python': parallel.arg('https://python.org', options={'Content-Type': 'application/json'}),
'rmotr': 'https://rmotr.com'
})
```
For `parallel.par`, you can use `parallel.future`:
```python
prices = parallel.par({
'btc': parallel.future(get_price_bitcoin, exchange='bitstamp')
'eth': parallel.future(get_price_ether, 'bitfinex',
options={'Content-Type': 'application/json'}),
})
```
## Error Handling
By default, if a function raises an exception, `parallel` will propagate it, this is the expected behavior. But `parallel` also includes error handling capabilities. By using the `silent` argument, you can _silence_ exceptions and access the details of the failed tasks afterwards (including the exception raised).
```python
def add(x, y):
pass
results = parallel.map(add, [
(2, 3),
('a', 5), # will fail
('hello ', 'world')
], silent=True)
print(results.failures)
# True (there are failed tasks)
r1, r2, r3 = results
assert r1 == 5
assert r3 == 'hello world'
assert r2 == parallel.FailedTask(
params=('a', 5),
ex=TypeError('unsupported operand type(s) for +: 'int' and 'str'')
)
# Read below for more info on `replace_failed`
assert results.replace_failed(None) == [5, None, 'hello world']
```
The `parallel.FailedTask` model includes information of the failed tasks, including the arguments (both sequential and named) passed.
What `map`, `par` and other methods return is an instance of the `parallel.BaseResult` class. These results include a few convenient methods:
* `results.failures` (_Boolean_): `True` if there were any tasks that failed with an exception.
* `results.failed` (_List_): A list of all the failed tasks.
* `results.succeeded` (_List_): A list of all the successful tasks.
* `results.replace_failed`: Receives a value to use for replacement of all the failed tasks. |
C++ | GB18030 | 1,680 | 3.671875 | 4 | [] | no_license | /*
time : 2015-5-14
author : ht
comment: ѾŹе鹹Ϊƽ
*/
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
//Definition for a binary tree node.
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* Node(struct TreeNode* current, int*array, int nums)
{
// ʽ
current = (struct TreeNode*)malloc(sizeof(struct TreeNode*));
int midIndex = nums / 2;
if (nums<= 2)
{
if (nums == 1)
{
current->val = array[0];
current->left = NULL;
current->right = NULL;
}
else
{
current->val = array[1];
current->left = Node(current->left, array, 1);
//ֻʣһ
current->right = NULL;
}
}
else
{
current->val = array[midIndex];
int len1 = midIndex;
current->left = Node(current->left, array, midIndex);
//leftߵǴarray 0ʼmidIndex-1
int start = 1 + midIndex;
int len2 = nums - start;
current->right = Node(current->right, array +start ,len2 );
}
return current;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
struct TreeNode* root = NULL;
if (numsSize <= 0)
return NULL;
root = Node(root, nums, numsSize);
return root;
}
int main()
{
//int value[6] = { 1,-1,2,3,-1,2};
int value[13] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
//int value[15] = { 1, 2, 4, -1, -1, 5, -1, -1, 2, 5, -1, -1, 2, -1, -1 };
TreeNode* root = NULL, *p = NULL;
int index = 0;
int nums = 13;
for (int i = 0; i < nums; i++)
value[i] -= 1;
//root = Node(root, value, nums);
root = sortedArrayToBST(value,nums);
return 0;
} |
Java | UTF-8 | 2,805 | 2.0625 | 2 | [] | no_license | package com.brothersplant.domain;
import java.util.Date;
public class UserInfoVO {
private String id;
private String password;
private String name;
private String nickname;
private String birth;
private String email;
private String tel;
private String addr;
private String profile;
private String secure;
private String secure_ans;
private String regdate;
private String updatedate;
private int auth;
private int myBoards;
private int replyCount;
@Override
public String toString() {
return "UserInfoVO [id=" + id + ", password=" + password + ", name=" + name + ", nickname=" + nickname
+ ", birth=" + birth + ", email=" + email + ", tel=" + tel + ", addr=" + addr + ", profile=" + profile
+ ", secure=" + secure + ", secure_ans=" + secure_ans + ", regdate=" + regdate + ", updatedate="
+ updatedate + "auth=" + auth +"myBoards="+myBoards+"replyCount="+replyCount+"]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getSecure() {
return secure;
}
public void setSecure(String secure) {
this.secure = secure;
}
public String getSecure_ans() {
return secure_ans;
}
public void setSecure_ans(String secure_ans) {
this.secure_ans = secure_ans;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public String getUpdatedate() {
return updatedate;
}
public void setUpdatedate(String updatedate) {
this.updatedate = updatedate;
}
public int getAuth() {
return auth;
}
public void setAuth(int auth) {
this.auth = auth;
}
public int getMyBoards() {
return myBoards;
}
public void setMyBoards(int myBoards) {
this.myBoards = myBoards;
}
public int getReplyCount() {
return replyCount;
}
public void setReplyCount(int replyCount) {
this.replyCount = replyCount;
}
}
|
Java | UTF-8 | 8,672 | 3.34375 | 3 | [] | permissive | package Thirteenth;
// 17명의 사람이 있다. 17명을 임의로 1 ~ 4 팀으로
// 나눌것이다.
// 1 팀 : 4 명
// 2 팀 : 4 명
// 3 팀 : 4 명
// 4 팀 : 5 명 으로 나눠야 한다.
// 팀을 나누는건 랜덤하게 나눠져야 한다.
// 1번. 17명에게 임의의 배열 번호를 부여한다.
// 2번. 17명에게 0 ~ 16 번의 랜덤숫자를 부여한다
// 3번. 부여받은 숫자를 기준으로 4 / 4 / 4 / 5 를 나눈다.
import java.util.ArrayList;
import java.util.Iterator;
class RadomTeamSelection {
private int teamMember;
private int randomTeam;
private int teamFixnum, memberFixnum;
private int numOfTeam;
private int numOfTeamMember;
private int i = 0;
private int randNum;
private int choiceMember;
private int[] teamNuberArr;
private int[] teamMemberArr;
private int[] checkDup;
//private ArrayList<Integer> teamAllayList;
//private ArrayList<Integer> memberAllayList;
public RadomTeamSelection(int numOfTeamMember) {
// 전체팀원의 숫자와 팀 갯수의 값을 조절하기 퍈하게 하기 위해
//teamFixnum = numOfTeam;
memberFixnum = numOfTeamMember;
//this.numOfTeam = numOfTeam;
this.numOfTeamMember = numOfTeamMember;
// 1차열 배열 17개 배열을 생성
teamMemberArr = new int[memberFixnum];
// 4개 팀을 정보를 받기 위해 만든다? 선언한다?
//teamAllayList = new ArrayList<Integer>();
// 17 명의 정수를 받기 위해 만든다? 선언한다?
//memberAllayList = new ArrayList<Integer>();
}
// checkDup 배열에 0 ~ 16 까지의 정수를 0으로 셋팅
// checkDup[0] = 0
// checkDup[1] = 0
// ...
// checkDup[16] = 0
public void allocArrTeamMemberZeroValue() {
checkDup = new int[memberFixnum];
while (i < checkDup.length) {
checkDup[i] = 0;
System.out.printf("checkDup[%d] = %d\n", i, checkDup[i]);
i++;
}
}
// 해당 배열에 value값을 넣어주자
public void allocArrTeamChoice() {
boolean choiceDup = false;
int randNum;
// checkDup[i] 배열의 모든 값은 0이다
// 그럼 choiceMember에게 값을 넘겨주면 0을 할당하게 된다.
choiceMember = checkDup[i];
// choiceDup 을 false 로 설정한다.
do {
// 랜덤 번호 할당한다.
// randNum 에 랜덤번호를 할당해준다.
randNum = (int) (Math.random() * memberFixnum) + 1;
//System.out.println(randNum);
//System.out.println("----------------------------");
// checkDup[i - 1] 배열안의 값이 0이 아닐때 while문으로 인해
// 다시 반복한다. else 문에서 checkDup[i - 1] 안의 값에다가
// 0 이 아닌 수를 할당하기 위해서다.
if (teamMemberArr[randNum -1] != 0) {
System.out.println( teamMemberArr[choiceMember] );
choiceDup = true;
} else {
choiceDup = false;
//teamMemberArr[randNum - 1] = checkDup;
System.out.printf("checkDup[%d] = %3\n", checkDup[i - 1], randNum);
}
} while (choiceDup);
}
public void printRandomTeamArr() {
int cnt = 1;
// 입력받은 배열의 길만큼 반복한다.
for(int i = 0; i < checkDup.length; i++) {
// 입력되는 배열자리의 + 1 값만큼 표시한다.
System.out.printf("%3d", checkDup[i] );
if (cnt % 5 == 0) {
System.out.println("");
}
cnt++;
}
}
}
/*
// 입력받은 numOfTeamMember 값을 기준으로 해당하는 1차열 배열을 생성
// ex ) 17명이니 numOfTeamMember 값에 17을 넣으면
// arr[ 0 ~ 16 ] 생성
// 해당 배열에 저장되어있는 value 값을 사람으로 생각해도 된다.
// 그렇기 때문에 17개의 배열을 생성해서 값을 넣는다.
// 1번 이정현 2번 오무개 ..... 17번 아무개 다
// 즉, 해당 배열자리에 값을 넣기 위해 만든것이다
// arr[0] = 7 , arr[1] = 16 , arr[2] = 0 ..... 이런식
public int allocArrTeamMemberRandomNumber(int numOfTeamMember) {
boolean isDup = false;
int memberRandNum;
// 0 ~ 16 사이의 배열에 임의로 생성하고
// 생성된 숫자를 해당번호를 넣어준
do {
memberRandNum = (int) (Math.random() * memberFixnum);
if (teamMemberArr[memberRandNum] != 0) {
isDup = true;
} else {
isDup = false;
teamMemberArr[memberRandNum] = numOfTeamMember;
}
} while(isDup);
return memberRandNum;
}
// arr 사용
// 17 개의 임의의 정수를 만들자.
// 배열의 들어갈 value값을 생성하자.
public void allocArrTeamMemberNumberVlaue(int memberRandNum) {
boolean isDup = false;
int randNum = memberRandNum;
int memberValue;
int randNumVaule;
do {
randNumVaule = (int) (Math.random() * memberFixnum) + 1;
// teamMemberArr[randNum] = n
// 즉 n 값에 임의의 숫자를 넣고 그 숫자가 중복되지
// 않아야 한다.
memberValue = randNum;
teamMemberArr[memberValue] = randNumVaule;
if (teamMemberArr[memberValue] == 0) {
isDup = true;
} else {
isDup = false;
}
} while (isDup);
}
*/
/*
public void printMemberArr () {
for (int i = 0; i < teamMemberArr.length; i++) {
System.out.printf("%3d", teamMemberArr[i]);
if (i % 5 == 0) {
System.out.println("");
}
cnt++;
}
}
/*
/*
// AllayList 사용
// 17명의 사람들에게 임의의 정수 0 ~ 16 까지 할당하자
public int allocTeamMemberNumber() {
boolean isDup = false;
int randNum;
do {
randNum = (int) (Math.random() * teamFixnum);
if (memberAllayList.contains(randNum)) {
// memberAllayList 에 랜덤으로 만들어진 randNum 값이
// 포함 되있으면 true 이기 때문에 while 로 가서
// 포함 안될때까지 무한루프
isDup = true;
} else {
// memberAllayList 에 랜덤으로 만들어진 randNum 값이
// 포함 되어있지 않으면 isDup은 false 값이 들어감으로
// 빠져나온다.
isDup = false;
// false 면 memberAllayList 값 안에 해당 랜덤값이 없으므로
// memberAllayList.add(randNum); 으로 randNum 에 다가
// 값을 추가해준다.
memberAllayList.add(randNum);
}
} while (isDup);
return randNum;
}
*/
/*
// allocTeamMemberNumber 가 0 ~ 16까지 랜덤하게
// 할당됬는지 확인하는 print
public void printTeamMemberNumber(){
//int cnt = 1;
Integer MemberNum;
Iterator e = memberAllayList.iterator();
while(e.hasNext()) {
MemberNum = (Integer) e.next();
System.out.printf("%3d", MemberNum);
//if (cnt % 5 == 0) {
// System.out.println("");
//}
//cnt++;
}
}
*/
// 임의로 부여된 숫자의 값을 저장하자.
// 값을 어떤식으로 저장할까? 단순한 더하기는 안된다.
// 임의의 변수에 += 하면 총 합이 나올뿐이다.
// 그렇다면 해당 배열의 자리에 넣어줘야한다.
/*
public void saveTeamMemberNuber(){
}
// 17명을 a ~ d 팀 또는 1 ~ 4 팀 처럼 나눠서 넣어주자
// 나눠서 넣어줄려면 어떻게 해야할까?
// 17명에게 랜덤한 숫자를 넘겨줬으니 17 % 4 == 0 로 나누면
// 4개의 팀으로 나눠질 것이다.
// 0 ~ 4 = 5명
// 5 ~ 8 = 4명
// 9 ~ 12 = 4명
// 13 ~ 16 = 4명
public void divisonTeamMember() {
if(memberFixnum % teamFixnum == 0) {
}
}
}
*/ |
JavaScript | UTF-8 | 172 | 2.75 | 3 | [] | no_license | /** get minimum angle between angles */
const MinAngleBetween = function(a, b) {
return Math.atan2(Math.sin(b - a), Math.cos(b - a))
};
export default MinAngleBetween;
|
Java | UTF-8 | 1,666 | 2.8125 | 3 | [] | no_license | package dto;
import entities.Rental;
import java.util.Date;
public class RentalDTO {
public long id;
public String userName;
public int rentalDays;
public Date rentalDate;
public double totalRentalPrice;
public String brand;
public String model;
public int year;
public double pricePerDay;
public RentalDTO(Rental order) {
this.id = order.getId();
this.userName = order.getUser().getUserName();
this.rentalDate = order.getRentalDate();
this.rentalDays = order.getRentalDays();
this.totalRentalPrice = order.getTotalRentPrice();
this.brand = order.getCar().getBrand();
this.model = order.getCar().getModel();
this.year = order.getCar().getYear();
this.pricePerDay = order.getCar().getPricePrDay();
}
@Override
public int hashCode() {
int hash = 7;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final RentalDTO other = (RentalDTO) obj;
if (this.id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return "RentalDTO{" + "id=" + id + ", userName=" + userName + ", rentalDays=" + rentalDays + ", rentalDate=" + rentalDate + ", totalRentalPrice=" + totalRentalPrice + ", brand=" + brand + ", model=" + model + ", year=" + year + ", pricePerDay=" + pricePerDay + '}';
}
} |
C++ | UTF-8 | 865 | 2.96875 | 3 | [] | no_license | // link to question - https://leetcode.com/problems/number-of-digit-one/
class Solution {
public:
int countDigitOne(int num) {
if(num < 0) return 0;
int ans = 0, c1 = 0, c2, rem, val;
string n = to_string(num);
for(int i = n.size() - 1; i >= 0; i--){
c1++;
val = rem = n[i] - '0';
if(rem == 0) continue;
if(c1 == 1){
ans += 1; continue;
}
rem = rem * pow(10, c1 - 1);
c2 = 1;
while(c2 < c1){
ans += rem / 10;
c2++;
}
if(val == 1)
ans += stoi(n.substr(n.size() + 1 - c1)) + 1;
else
ans += pow(10, c2 - 1);
}
return ans;
}
}; |
C++ | UTF-8 | 5,220 | 2.890625 | 3 | [
"MIT"
] | permissive | #include "dfs_time.h"
#include "dfs_string.h"
static char *week[] = { (char *)"Sun", (char *)"Mon", (char *)"Tue",
(char *)"Wed", (char *)"Thu", (char *)"Fri", (char *)"Sat" };
static char *months[] = { (char *)"Jan", (char *)"Feb", (char *)"Mar",
(char *)"Apr", (char *)"May", (char *)"Jun", (char *)"Jul",
(char *)"Aug", (char *)"Sep", (char *)"Oct", (char *)"Nov",
(char *)"Dec", nullptr };
void time_localtime(time_t s, struct tm *tm)
{
(void) localtime_r(&s, tm);
tm->tm_mon++;
tm->tm_year += 1900;
}
uchar_t * time_to_http_time(uchar_t *buf, time_t t)
{
struct tm tm;
time_gmtime(t, &tm);
return string_xxsprintf(buf, "%s, %02d %s %4d %02d:%02d:%02d GMT",
week[tm.tm_wday],
tm.tm_mday,
months[tm.tm_mon - 1],
tm.tm_year,
tm.tm_hour,
tm.tm_min,
tm.tm_sec);
}
uchar_t * time_to_http_cookie_time(uchar_t *buf, time_t t)
{
struct tm tm;
time_gmtime(t, &tm);
/*
* Netscape 3.x does not understand 4-digit years at all and
* 2-digit years more than "37"
*/
return string_xxsprintf(buf,
(tm.tm_year > 2037) ?
"%s, %02d-%s-%d %02d:%02d:%02d GMT":
"%s, %02d-%s-%02d %02d:%02d:%02d GMT",
week[tm.tm_wday],
tm.tm_mday,
months[tm.tm_mon - 1],
(tm.tm_year > 2037) ? tm.tm_year:
tm.tm_year % 100,
tm.tm_hour,
tm.tm_min,
tm.tm_sec);
}
void time_gmtime(time_t t, struct tm *tp)
{
int yday;
uint32_t n, sec, min, hour, mday, mon, year, wday, days, leap;
/* the calculation is valid for positive time_t only */
n = (uint32_t) t;
days = n / 86400;
/* Jaunary 1, 1970 was Thursday */
wday = (4 + days) % 7;
n %= 86400;
hour = n / 3600;
n %= 3600;
min = n / 60;
sec = n % 60;
/*
* the algorithm based on Gauss' formula,
* see src/http/dfs_http_parse_time.c
*/
/* days since March 1, 1 BC */
days = days - (31 + 28) + 719527;
/*
* The "days" should be adjusted to 1 only, however, some March 1st's go
* to previous year, so we adjust them to 2. This causes also shift of the
* last Feburary days to next year, but we catch the case when "yday"
* becomes negative.
*/
year = (days + 2) * 400 / (365 * 400 + 100 - 4 + 1);
yday = days - (365 * year + year / 4 - year / 100 + year / 400);
if (yday < 0)
{
leap = (year % 4 == 0) && (year % 100 || (year % 400 == 0));
yday = 365 + leap + yday;
year--;
}
/*
* The empirical formula that maps "yday" to month.
* There are at least 10 variants, some of them are:
* mon = (yday + 31) * 15 / 459
* mon = (yday + 31) * 17 / 520
* mon = (yday + 31) * 20 / 612
*/
mon = (yday + 31) * 10 / 306;
/* the Gauss' formula that evaluates days before the month */
mday = yday - (367 * mon / 12 - 30) + 1;
if (yday >= 306)
{
year++;
mon -= 10;
/*
* there is no "yday" in Win32 SYSTEMTIME
*
* yday -= 306;
*/
}
else
{
mon += 2;
/*
* there is no "yday" in Win32 SYSTEMTIME
*
* yday += 31 + 28 + leap;
*/
}
tp->tm_sec = (int) sec;
tp->tm_min = (int) min;
tp->tm_hour = (int) hour;
tp->tm_mday = (int) mday;
tp->tm_mon = (int) mon;
tp->tm_year = (int) year;
tp->tm_wday = (int) wday;
}
int time_monthtoi(const char *s)
{
char ch1 = 0;
char ch2 = 0;
ch1 = *(s + 1);
ch2 = *(s + 2);
switch (*s)
{
case 'J':
if (ch1 == 'a')
{
if (ch2 == 'n')
{
return TIME_MONTH_JANUARY;
}
return NGX_ERROR;
}
if (ch1 != 'u')
{
return NGX_ERROR;
}
if (ch2 == 'n')
{
return TIME_MONTH_JUNE;
}
if (ch2 == 'l')
{
return TIME_MONTH_JULY;
}
break;
case 'F':
if (ch1 == 'e' && ch2 == 'b')
{
return TIME_MONTH_FEBRUARY;
}
break;
case 'M':
if (ch1 != 'a')
{
return NGX_ERROR;
}
if (ch2 == 'r')
{
return TIME_MONTH_MARCH;
}
if (ch2 == 'y')
{
return TIME_MONTH_MAY;
}
break;
case 'A':
if (ch1 == 'p' && ch2 == 'r')
{
return TIME_MONTH_APRIL;
}
if (ch1 == 'u' && ch2 == 'g')
{
return TIME_MONTH_AUGUST;
}
break;
case 'S':
if (ch1 == 'e' && ch2 == 'p')
{
return TIME_MONTH_SEPTEMBER;
}
break;
case 'O':
if (ch1 == 'c' && ch2 == 't')
{
return TIME_MONTH_OCTOBER;
}
break;
case 'N':
if (ch1 == 'o' && ch2 == 'v')
{
return TIME_MONTH_NOVEMBER;
}
break;
case 'D':
if (ch1 == 'e' && ch2 == 'c')
{
return TIME_MONTH_DECEMBER;
}
break;
default:
break;
}
return NGX_ERROR;
}
|
Java | UTF-8 | 22,165 | 2.046875 | 2 | [] | no_license | package com.yash.RMS.TestAction.ProjectAttribute;
import org.openqa.selenium.By;
import com.yash.RMS.CustomProperties.Constant;
import com.yash.RMS.CustomProperties.Report;
import com.yash.RMS.POM.ProjectAttribute.PageObjects_ProjectAttribute;
import com.yash.RMS.POM.ResourceAttribute.PageObjects_ResourceAttribute;
public class Action_ProjectCategoryAddDel {
private static final String UpdatedPriority = null;
public static String ProjectCategoryAdd_name;
/*public static String output;
public static String Editoutput;
*/
//******FOR NAVIGATION******************************************************************************************
//Masterdata Link
public static void projectCategorypage_Navigation() throws Throwable {
try {
//Thread.sleep(4000);
//(Constant.driver).manage().window().maximize();
if (PageObjects_ProjectAttribute.masterDataLink(Constant.driver).isDisplayed()) {
PageObjects_ProjectAttribute.masterDataLink(Constant.driver).click();
Report.ReporterOutput("STEP","Verify master data Link is displayed ","Master Data link", "Click on master data link","master data link should be displayed and clicked", "Pass", null);
} else {
Report.ReporterOutput("STEP","Master Data link is displayed ","Master Data link","Click on master data link","master data link not displayed","Fail",null);
}
//Thread.sleep(2000);
//Project Attribute Link
if (PageObjects_ProjectAttribute.projectAttributeLink(Constant.driver).isDisplayed()) {
PageObjects_ProjectAttribute.projectAttributeLink(Constant.driver).click();
Report.ReporterOutput("STEP","Project Attribute Link is displayed ","Project Attribute Link","Click on Project Attribute Link","Project Attribute Link should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Project Attribute Link is displayed ","Project Attribute Link","Click on Project Attribute Link","Project Attribute Link is not displayed","Fail",null);
}
Thread.sleep(2000);
//ProjectCategory_Link
// Thread.sleep(2000);
if (PageObjects_ProjectAttribute.projectCategory_Link(Constant.driver).isDisplayed()) {
PageObjects_ProjectAttribute.projectCategory_Link(Constant.driver).click();
Report.ReporterOutput("STEP","Verify projectCategory_Link is displayed "," projectCategory_Link","Click on projectCategory_Link","projectCategory_Link should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify projectCategory_Link is displayed ","projectCategory_Link","Click on projectCategory_Link","projectCategory_Link not displayed","Fail",null);
}
// Project Category Page Text
String Page_Project_Category = PageObjects_ProjectAttribute.projectCategory_pageText(Constant.driver).getText();
if (Page_Project_Category.equalsIgnoreCase("Project Category")) {
Report.ReporterOutput("STEP","Verify Page_Project_Category is Visible "," Page_Project_Category","Click on Page_Project_Category","Page_Project_Category is visible","Pass",null);
} else {
Report.ReporterOutput("STEP","Verify Page_Project_Category is Visible ","Page_Project_Category","Click on Page_Project_Category","Page_Project_Category is not visible","Fail",null);
}
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
//*********************************************************************************************************************************************
//For Adding Project Category
public static void projectCategorypage_Add(String ProjectCategoryAdd_name) throws Throwable {
try {
if (PageObjects_ProjectAttribute.projectCategory_addNewLink(Constant.driver).isDisplayed()) {
PageObjects_ProjectAttribute.projectCategory_addNewLink(Constant.driver).click();
Thread.sleep(2000);
Report.ReporterOutput("STEP","Verify ProjectCategory_addNewLink is displayed ","ProjectCategory_addNewLink","Click on ProjectCategory_addNewLink","ProjectCategory_addNewLink should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_addNewLink is displayed ","ProjectCategory_addNewLink","Click on ProjectCategory_addNewLink","ProjectCategory_addNewLink not displayed","Fail",null);
}
//Thread.sleep(2000);
/*char[] chars = "ABC123DFGHI68JKLMNOPQRSTUVWXYZ7895".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 8; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
output = sb.toString();
//System.out.println("first output "+output);*/
if (PageObjects_ProjectAttribute.projectCategory_nameBoxSorting(Constant.driver).isDisplayed()) {
PageObjects_ProjectAttribute.projectCategory_nameBoxSorting(Constant.driver).click();
PageObjects_ProjectAttribute.projectCategory_nameBoxSorting(Constant.driver).sendKeys(ProjectCategoryAdd_name);
Report.ReporterOutput("STEP","Verify ProjectCategory_nameBoxSorting is displayed ","ProjectCategory_addNewLink","Click on ProjectCategory_addNewLink","ProjectCategory_addNewLink should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_addNewLink is displayed ","ProjectCategory_addNewLink","Click on ProjectCategory_addNewLink","ProjectCategory_addNewLink not displayed","Fail",null);
}
//Thread.sleep(2000);
// to click on Save button/Verify new Location has been added
if(Constant.driver.findElement(By.linkText("Save")).isEnabled());
{
Report.ReporterOutput("STEP","Verify Save button is enabled ","Save button","Save button should be enabled","Save button is enabled","Pass",null);
Constant.driver.findElement(By.linkText("Save")).click();
}
Thread.sleep(2000);{
Report.ReporterOutput("STEP","Verify new Project Category has been created","new Project Category creation","new Project Category should be created","new Project Category has been created","Pass",null);
}
/*if (PageObjects_ProjectAttribute.projectCategory_saveButton(Constant.driver).isDisplayed()) {
PageObjects_ProjectAttribute.projectCategory_saveButton(Constant.driver).click();
Report.ReporterOutput("STEP","Verify ProjectCategory_saveButton is Visible ","ProjectCategory_saveButton","Click on ProjectCategory_saveButton","ProjectCategory_saveButton should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_saveButton is Visible ","ProjectCategory_saveButton","Click on ProjectCategory_saveButton","ProjectCategory_saveButton is not displayed","Fail",null);
}
Thread.sleep(2000);*/
/*if (PageObjects_ProjectAttribute.projectCategory_saveButtonConfirmationMessage(Constant.driver).isDisplayed()) {
Report.ReporterOutput("STEP","Verify ProjectCategory_saveButtonConfirmationMessage is displayed ","ProjectCategory_saveButtonConfirmationMessage","Click on saveButton Confirmation Message","ProjectCategory_saveButtonConfirmationMessage should be displayed","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_saveButtonConfirmationMessage is displayed ","ProjectCategory_saveButtonConfirmationMessage","Click on ProjectCategory_saveButtonConfirmationMessage","ProjectCategory_saveButtonConfirmationMessage not displayed","Fail",null);
}*/
} catch (Exception e) {
e.printStackTrace();
}
}
//************************************************************************************************************************************************************************
//************ to Search and verify created Project Category Name **************************************
public static void projectCategorypage_Search(String ProjectCategory_name) throws Throwable
{
try
{
Thread.sleep(12000);
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).clear();
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).sendKeys(ProjectCategory_name);
//Thread.sleep(5000);
Thread.sleep(3000);
String msgA= Constant.driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div/div[2]/div/table/tbody/tr/td[2]")).getText().trim();
String msgB= ProjectCategory_name;
System.out.println(msgA);
//Thread.sleep(2000);
if(msgA.contains(msgB))
{
Report.ReporterOutput("STEP","Verify new ProjectCategory Name "+ProjectCategory_name+" is searched and verified.",ProjectCategory_name,"New ProjectCategory Name "+ProjectCategory_name+" should be searched and verification.","New ProjectCategory Name "+ProjectCategory_name+" searched and verified.","Pass",null);
}
//Thread.sleep(3000);
}
catch(Exception e2)
{
Report.ReporterOutput("STEP","Verify new ProjectCategory Name "+ProjectCategory_name+" is searched and verified.",ProjectCategory_name,"New ProjectCategory Name "+ProjectCategory_name+" should be searched and verification.","New ProjectCategory Name "+ProjectCategory_name+" is not searched and verified.","Fail",null);
}
}
//**********************************************************************************************************************************************
//For Editing Project Category
public static void projectCategorypage_searchEdit(String ProjectCategoryAdd_name) throws Throwable {
try {
Thread.sleep(12000);
// for search
if (PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).isEnabled()) {
/*PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).click();*/
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).clear();
//Giving output from First add Method
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).sendKeys(ProjectCategoryAdd_name);
Thread.sleep(2000);
Report.ReporterOutput("STEP","Verify ProjectCategory_searchButton is Visible ","ProjectCategory_searchButton ","Click on ProjectCategory_searchButton ","ProjectCategory_searchButton should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_searchButton is Visible ","ProjectCategory_searchButton ","Click on ProjectCategory_searchButton ","ProjectCategory_searchButton not displayed","Fail",null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//**********************************************************************************************************************************************
//
public static void projectCategorypage_Edit(String Editoutput) throws Throwable {
try {
Thread.sleep(4000);
if (PageObjects_ProjectAttribute.projectCategory_editButton(Constant.driver).isDisplayed()) {
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_editButton(Constant.driver).click();
Report.ReporterOutput("STEP","Verify ProjectCategory_editButton is Visible ","ProjectCategory_editButton","Click on ProjectCategory_editButton","ProjectCategory_editButton should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_editButton is Visible ","ProjectCategory_editButton","Click on ProjectCategory_editButton","ProjectCategory_editButton is not displayed","Pass",null);
}
/*//Generate random No 2nd to Edit
char[] chars1 = "ABC123DFGHI68JKLMNOPQRSTUVWXYZ7895".toCharArray();
StringBuilder sb1 = new StringBuilder();
Random random1 = new Random();
for (int i = 0; i < 8; i++) {
char c = chars1[random1.nextInt(chars1.length)];
sb1.append(c);
}
Editoutput = sb1.toString();
System.out.println(Editoutput);*/
if (PageObjects_ProjectAttribute.projectCategory_nameBoxSorting(Constant.driver).isDisplayed()) {
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_nameBoxSorting(Constant.driver).click();
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_nameBoxSorting(Constant.driver).clear();
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_nameBoxSorting(Constant.driver).sendKeys(Editoutput);
Report.ReporterOutput("STEP","Verify Project Category Name Box is displayed ","Project Category Name Box","Click on Project Category Name Box","Project Category Name Box should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify Project Category Name Box is displayed ","Project Category Name Box","Click on Project Category Name Box","Project Category Name Box not displayed","Fail",null);
}
//Thread.sleep(2000);
if (PageObjects_ProjectAttribute.projectCategory_saveButton(Constant.driver).isDisplayed()) {
PageObjects_ProjectAttribute.projectCategory_saveButton(Constant.driver).click();
Report.ReporterOutput("STEP","Verify Project Category Save Button is Visible ","Project Category Save Button","Click on Project Category Save Button","Project Category Save Button should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify Project Category Save Button is Visible ","Project Category Save Button","Click on Project Category Save Button","Project Category Save Button is not displayed","Pass",null);
}
// To verify Priority field has been updated
try
{
Thread.sleep(12000);
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).clear();
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).sendKeys(Editoutput);
//Thread.sleep(2000);
String msgA1= Constant.driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div/div[2]/div/table/tbody/tr/td[2]")).getText().trim();
String msgB1= Editoutput;
System.out.println(msgA1);
//Thread.sleep(2000);
if(msgA1.contains(msgB1))
{
Report.ReporterOutput("STEP","Verify Project Category Name has been updated.","Name Updated","Project Category Name should be updated.","Project Category Name has been updated.","Pass",null);
}
//Thread.sleep(3000);
}
catch(Exception e2)
{
Report.ReporterOutput("STEP","Verify Project Category Name has been updated.","Name Updated","Project Category Name should be updated.","Project Category Name is not updated successfully.","Pass",null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//**********************************************************************************************************************************************
// For Delete
public static void projectCategorypage_searchDel(String Editoutput) throws Throwable {
try {
Thread.sleep(12000);
// for search
if (PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).isDisplayed()) {
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).click();
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).clear();
//System.out.println("For DEleteeeeeeeee"+Editoutput);
//Giving output from First add Method
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).sendKeys(Editoutput);
Report.ReporterOutput("STEP","Verify ProjectCategory_searchButton is Visible ","ProjectCategory_searchButton ","Click on ProjectCategory_searchButton","ProjectCategory_searchButton should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_searchButton Visible ","ProjectCategory_searchButton ","Click on ProjectCategory_searchButton ","ProjectCategory_searchButton not displayed","Pass",null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//**********************************************************************************************************************************************
//public static void projectCategorypage_Delete(String Editoutput) throws Throwable {
public static void projectCategorypage_Delete(String Editoutput) throws Throwable {
// for search functionality 2nd Time To Delete
Thread.sleep(2000);
if (PageObjects_ProjectAttribute.projectCategory_deleteButton(Constant.driver).isDisplayed()) {
//Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_deleteButton(Constant.driver).click();
Report.ReporterOutput("STEP","Verify ProjectCategory_deleteButton is Visible ","ProjectCategory_deleteButton ","Click on ProjectCategory_deleteButton","ProjectCategory_deleteButton should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_deleteButton is Visible ","ProjectCategory_deleteButton","Click on ProjectCategory_deleteButton","ProjectCategory_deleteButton is not displayed","Fail",null);
}
if (PageObjects_ProjectAttribute.projectCategory_deleteokButton(Constant.driver).isDisplayed()) {
// Thread.sleep(2000);
PageObjects_ProjectAttribute.projectCategory_deleteokButton(Constant.driver).click();
Thread.sleep(2000);
Report.ReporterOutput("STEP","Verify ProjectCategory_deleteokButton is Visible ","ProjectCategory_deleteokButton","Click on ProjectCategory_deleteokButton","ProjectCategory_deleteokButton should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_deleteokButton is Visible ","ProjectCategory_deleteokButton","Click on ProjectCategory_deleteokButton","ProjectCategory_deleteokButton is not displayed","Fail",null);
}
//Thread.sleep(2000);
if (PageObjects_ProjectAttribute.projectCategory_deleteConfirmationMsg(Constant.driver).isDisplayed()) {
Report.ReporterOutput("STEP","Verify ProjectCategory_deleteConfirmationMsg is Visible ","ProjectCategory_deleteConfirmationMsg","Click on delete Confirmation Msg","ProjectCategory_deleteConfirmationMsg should be displayed and clicked","Pass",null);
}
else {
Report.ReporterOutput("STEP","Verify ProjectCategory_deleteConfirmationMsg is Visible ","ProjectCategory_deleteConfirmationMsg","Click on delete Confirmation Msg","ProjectCategory_deleteConfirmationMsg is not displayed","Fail",null);
}
Thread.sleep(12000);
//Verify New Location By has been deleted
// exact
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).clear();
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).sendKeys(Editoutput);//function parameter esend need to pass here
//Thread.sleep(5000);
// Thread.sleep(3000);
String delete = PageObjects_ProjectAttribute.projectCategory_nomatchingRecordsText(Constant.driver).getText();
String deletetoverify ="No matching records found";
if(delete.equalsIgnoreCase(deletetoverify)){
//Report.ReporterOutput("STEP","Verify Skill Type Name has been deleted","Skill Type Name deletion","Skill Type Name should be deleted succesfully","Skill Type Name has not been deleted succesfully","fail",null);
//Thread.sleep(2000);
Report.ReporterOutput("STEP","Verify Deleted ProjectCategory Type Name : "+Editoutput+" has been Deleted","Delete ProjectCategory Type Name","Delete ProjectCategory Type Name : "+Editoutput+" should be Deleted","Delete ProjectCategory Type Name "+Editoutput+" has been Deleted","Pass",null);
}else
{
//Report.ReporterOutput("STEP","Verify Skill Type Name has been deleted","Skill Type Name deletion","Skill Type Name should not be deleted succesfully","Skill Type Name has not been deleted succesfully","Pass",null);
Report.ReporterOutput("STEP","Verify Deleted ProjectCategory Type Name : "+Editoutput+" has been Deleted","Delete ProjectCategory Type Name","Delete ProjectCategory Type Name : "+Editoutput+" should be Deleted","Delete ProjectCategory Type Name "+Editoutput+" has NOT been Deleted","Fail",null);
}
//Thread.sleep(2000);
PageObjects_ProjectAttribute.searchBox(Constant.driver).clear();
PageObjects_ProjectAttribute.masterDataLink(Constant.driver).click();
//OR
//Verify New Project Category By has been deleted
/*PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).clear();
PageObjects_ProjectAttribute.projectCategory_searchButton(Constant.driver).sendKeys(Editoutput);
String msgA1= Constant.driver.findElement(By.xpath("html/body/div[1]/div[1]/div[2]/div/div[2]/div/table/tbody/tr/td[2]")).getText().trim();
Thread.sleep(2000);
String msgB1= Editoutput;
System.out.println(msgA1);
Thread.sleep(2000);
if(msgA1.contains(msgB1))
{
Report.ReporterOutput("STEP","Verify Project Category has been deleted","Project Category Deletion","Project Category should be deleted succesfully","Project Category has not been deleted succesfully","fail",null);
}
{
Report.ReporterOutput("STEP","Verify Project Category has been deleted","Project Category Deletion","Project Category should be deleted succesfully","Project Category has been deleted succesfully","Pass",null);
}*/
// **********************************************************************************
// to click on Home page
try
{
if(Constant.driver.findElement(By.xpath("html/body/div[1]/header/a/span[2]/img")).isDisplayed());
{
Constant.driver.findElement(By.xpath("html/body/div[1]/header/a/span[2]/img")).click();
Report.ReporterOutput("STEP","Verify User is navigated to RMS Home page","RMS Home page","User should be navigated to RMS Home page","User is navigated to RMS Home page","Pass",null);
}
}
catch(Exception e8)
{
System.out.println( e8.getMessage());
}
}
// **********************************************************************************
}//End of class
|
Java | UTF-8 | 243 | 2.34375 | 2 | [] | no_license | package Inheritance;
public class App {
public static void main(String[] args)
{
Machine obj1=new Machine();
obj1.start();
obj1.stop();
Car obj2=new Car();
obj2.start();
obj2.wipewindshield();
obj2.accelerate();
obj2.stop();
}
}
|
Java | UTF-8 | 1,238 | 2.25 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package beans;
import dao.Dao;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import pojo.Weather;
@ManagedBean(name = "weather_bean")
@SessionScoped
public class WeatherBeans {
private Dao dao = new Dao();
private Weather weather = dao.getWeather();
public String getDate() {
return weather.getDate();
}
public int getDirectionWind() {
return weather.getDirectionWind();
}
public double getSpeedWind() {
return weather.getSpeedWind();
}
public double getTemperature() {
return weather.getTemperature();
}
public int getHumidity() {
return weather.getHumidity();
}
public double getRadiation() {
return weather.getRadiation();
}
public double getPressure() {
return weather.getPressure();
}
public double getPrecipitation() {
return weather.getPrecipitation();
}
}
|
Markdown | UTF-8 | 3,029 | 2.609375 | 3 | [] | no_license | ---
layout: blog
title: Strange Day
lede: Alchemy & Autism
featured_image: >-
https://res.cloudinary.com/dthkwbvgt/image/upload/t_BlogCardThumb/v1586267897/668473906_2ee0e3f97b_c_efyzdk.jpg
date: 2020-04-06T15:25:02.054Z
tags:
- autism
- symbols
- home learning
- home schooling
- lessons
---
What was I doing a month ago at 10:00 on a Thursday morning?
I suppose I'd have just finished the daily remote meeting with my team at work and would be pouring my second or third cup of coffee and starting into whatever work I was assigned to.
## Now
On this Thursday morning I'm home-schooling my 6 year old, flicking between a page of alchemical symbols in one browser tab and a page of circuit diagrams in another.

There was, of course, some context for this - he hadn't been assigned a neophyte curriculum in western high magick by his primary school.
## Connections
K had decided to start the day with drawing, which is what tends to happen if I'm not completely prepared to start a literacy task at the end of the daily Joe Wicks workout, or am otherwise distracted by the toddler.
So he was making up symbols, which has been a bit of a theme of late, and taking his cue from sources like [Ninjago](https://en.wikipedia.org/wiki/Ninjago_(TV_series)) and [Avatar](https://en.wikipedia.org/wiki/Avatar:_The_Last_Airbender) these turned out to be variations on the [classical elements](https://en.wikipedia.org/wiki/Classical_element).

I was trying to show him that there were already some well-established symbols for Earth, Air, Fire and Water, and (if I'm honest) I __was__ slightly hoping the magical aspect of it would spark his imagination, but he was more interested in his own representations.
The referents of his symbols could broadly be considered as forms of energy or force, and in comparing electrical diagrams I was reminded to try and tap into last weeks' interest in magnetism by building and electromagnet.
Gawd. You don't need to tell me that stuff like that is too old for him, I know it.
## Improvising
Taking inspiration from the kind of task on the school's more age-appropriate lesson grid, we looked for different examples of symbols around the house and having a general conversation about them.
It was interesting.
We talked about how symbols
- can convey meaning or obscure it
- transcend language
- use different levels of abstaction
- ought to mean precisely one thing
- are sometimes part of a system
## And
Part of the reason we weren't able to stick to the 'normal' schedule was that there was a video call planned as part of K's ASD assessment process, which has been ongoing for a year or more.
That was more decisive than I expected, too.
## So
All in all a very unusual day, even by the standards of global pandemic lockdown. |
Java | UTF-8 | 340 | 1.539063 | 2 | [] | no_license | package me.wang.featureconfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FeatureconfigApplication {
public static void main(String[] args) {
SpringApplication.run(FeatureconfigApplication.class, args);
}
}
|
Java | UTF-8 | 1,039 | 2.1875 | 2 | [
"MIT"
] | permissive | package tv.dyndns.kishibe.qmaclone.server;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import com.google.common.base.Preconditions;
@SuppressWarnings("serial")
public class DelegatingWebServlet extends HttpServlet {
private final HttpServlet stub;
protected DelegatingWebServlet(HttpServlet stub) {
this.stub = Preconditions.checkNotNull(stub);
}
@Override
public void destroy() {
stub.destroy();
}
@Override
public ServletConfig getServletConfig() {
return stub.getServletConfig();
}
@Override
public String getServletInfo() {
return stub.getServletInfo();
}
@Override
public void init(ServletConfig config) throws ServletException {
stub.init(config);
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
stub.service(req, res);
}
}
|
Ruby | UTF-8 | 145 | 2.609375 | 3 | [] | no_license | class TennisTournament
def max_courts
max_courts = p / 2
return max_courts if c > max_courts
return c if c <= max_courts
end
end
|
Java | UTF-8 | 371 | 1.710938 | 2 | [
"MIT"
] | permissive | //,temp,QueueStorePrefetch.java,97,106,temp,QueueStorePrefetch.java,70,80
//,3
public class xxx {
@Override
protected synchronized boolean isStoreEmpty() {
try {
return this.store.isEmpty();
} catch (Exception e) {
LOG.error("Failed to get message count", e);
throw new RuntimeException(e);
}
}
}; |
Markdown | UTF-8 | 46,469 | 3.078125 | 3 | [] | no_license | title: 一些 iOS 小技巧与注意点(持续更新)
date: 2017/2/9 10:07:12
categories: iOS
tags:
- 学习笔记
- 持续更新
------
这篇中将收集一些关于 iOS 开发中的一些小技巧以及注意事项,可能比较零散。
<!--more-->
### 隐藏Xcode 对于 performSelector 方法的⚠️
使用 performSelector 方法,Xcode 会提示会可能产生内存泄漏,可以添加这两句宏在方法上,就不会有⚠️了:
```objc
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
```
### 后台任务
app进入后台,会停止所有线程;需要在 `applicationDidEnterBackground` 中调用 `beginBackgroundTaskWithExpirationHandler` 申请更多的app执行时间,以便结束某些任务:
```objc
- (void)applicationDidEnterBackground:(UIApplication *)application {
_backtaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void){
... 任何后台任务要做的事
// 取消后台任务,在id不是UIBackgroundTaskInvalid的情况下,通过 endbackgroundTask 停止任务,并将id设置回invalid
if (_backtaskIdentifier!=UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:_backtaskIdentifier];
_backtaskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
```
其中 `_backtaskIdentifier` 是 `UIBackgroundTaskIdentifier` 类型
### 浏览器缓存策略
从浏览器的缓存中可以学到一些有关客户端缓存方案的实现方式
#### Cache-Control
Cache-Control 提供一个 max-age 字段,用于描述过期时间。浏览器是否再次请求数据决定于:
```
浏览器当前时间 > 浏览器上次请求时间 + max-age
```
#### Last-Modified/If-Modified-Since
浏览器每次请求后,服务器会返回一个资源在服务端上次更新的时间。下次请求的时候会带上这个时间。如果服务端发现这个时间之后没有更新过资源就会返回 304,让浏览器用本地数据
但是如果碰到某些文件会被定期生成, 而内容其实并没有发生任何变化的情况,这种情况下 Last-Modified改变了, 但这种情况其实应该返回304。因此设计了 ETag 方式。
ETag 用于唯一的标识一个文件。如果两个文件 ETag 相同,那么就表示两个文件是一致的,不会重复返回。
> 这两种方式:
>
> - 一种是用于客户端是否要去请求。
> - 一种是用于客户端请求了服务端是否要返回数据。
### atomic 与线程安全
`atomic`的原子粒度是Getter/Setter,但对多行代码的操作不能保证原子性:
```objc
@property (atomic, assign) int num;
// thread A
for (int i = 0; i < 10000; i++) {
self.num = self.num + 1;
NSLog(@"Thread A: %d\d ",self.num);
}
// thread B
for (int i = 0; i < 10000; i++) {
self.num = self.num + 1;
NSLog(@"Thread B: %d\d ",self.num);
}
```
最终的结果不一定是 20000,因为这个过程包含了,读取 num,给 num 加一,写 num 三个操作。读写是原子性的,但是这三个操作不是原子性的。
### `__attribute__` 的使用
`__attribute__` 是编译指令,一般以`__attribute__(xxx)`的形式出现在代码中,方便开发者向编译器表达某种要求。
#### constructor
`__attribute__((constructor))` 加上这个属性的函数会在可执行文件 load 时被调用。可以理解为在 main() 函数调用前执行:
```c++
__attribute__((constructor))
static void beforeMain(void) {
NSLog(@"beforeMain");
}
__attribute__((destructor))
static void afterMain(void) {
NSLog(@"afterMain");
}
int main(int argc, const char * argv[]) {
NSLog(@"main");
return 0;
}
// Console:
// "beforeMain" -> "main" -> “afterMain"
```
constructor 和 +load 都是在 main 函数执行前调用,但 +load 比 constructor 更加早一丢丢,因为 dyld(动态链接器,程序的最初起点)在加载 image(可以理解成 Mach-O 文件)时会先通知 objc runtime 去加载其中所有的类,每加载一个类时,它的 +load 随之调用,全部加载完成后,dyld 才会调用这个 image 中所有的 constructor 方法。所以 constructor 是一个干坏事的绝佳时机:
1. 所有Class都已经加载完成
2. main 函数还未执行
3. 无需像 +load 还得挂载在一个Class中
#### section
通常情况下,编译器会将对象放置于DATA段的*data*或者*bss*节中。但是,有时我们需要将数据放置于特殊的自定义 section 中,此时*section*可以达到目的。例如,BeeHive中就把module注册数据存在__DATA数据段里面的“BeehiveMods”section中。
```objc
char * kShopModule_mod __attribute((used, section("__DATA,""BeehiveMods"""))) = """ShopModule""";
```
其中 `used` 告诉编译器,即使它没有被使用,也不要优化掉。
### nil Null Nil NSNull 区别
nil 定义某实例对象为空:
```objc
NSObject* obj = nil;
```
Nil 定义类为空
```objc
Class someClass = Nil;
```
NULL 用于 c 语言数据类型的指针为空:
```objc
char *pointerToChar = NULL;
```
NSNull 是空对象,放在 NSArray 中
```objc
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];
mutableDictionary[@"someKey"] = [NSNull null];
```
### SafeArea
iOS11 提供了 `safeAreaLayoutGuide` 和 `safeAreaInsets` 来帮助刘海屏的适配。
前者你可以把它当做是一个 view。我们一般配合 Masonry 使用。Masonry 提供了 `mas_safeAreaLayoutGuide`,`mas_safeAreaLayoutGuideRight/Left/Top/Bottom` 来辅助布局:
```objc
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view.mas_safeAreaLayoutGuide).inset(10.0);
}];
......
[rightTopView mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
make.width.height.equalTo(@(size));
}];
```
后者则是一个 inset,适合在 frame 布局的时候使用。但是要注意,`safeAreaInsets` 是在系统方法 `viewSafeAreaInsetsDidChange` 之后才会变为正确的值的,所以我们需要在之后的生命周期方法,比如 `viewDidLayoutSubviews` 方法中设置:
```objc
static inline UIEdgeInsets sgm_safeAreaInset(UIView *view) {
if (@available(iOS 11.0, *)) {
return view.safeAreaInsets;
}
return UIEdgeInsetsZero;
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
UIEdgeInsets safeAreaInsets = sgm_safeAreaInset(self.view);
CGFloat height = 44.0; // 导航栏原本的高度,通常是44.0
height += safeAreaInsets.top > 0 ? safeAreaInsets.top : 20.0; // 20.0是statusbar的高度,这里假设statusbar不消失
if (_navigationbar && _navigationbar.height != height) {
_navigationbar.height = height;
}
```
### UIView 的生命周期
```objc
- (void)didAddSubview:(UIView *)subview;
- (void)willRemoveSubview:(UIView *)subview;
- (void)willMoveToSuperview:(nullable UIView *)newSuperview;
- (void)didMoveToSuperview;
```
`willMoveToSuperview` 会在添加到父视图和从父视图移除的时候调用,移除的时候参数为 `nil`(类似于 `willMoveToParentViewController`)
`didMoveToSuperview` 也比较重要,在这个方法中可以拿到父视图的大小,进行相应的布局
### 判断是否点击了某个 View
```objc
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
// 将 touch 转化到 View 的坐标系
CGPoint touchPoint = [touch locationInView:self];
if (CGRectContainsPoint(self.bounds, touchPoint)) {
// 点在了 View 中
}
}
```
### 画一条一个像素的线
根据当前屏幕的缩放因子计算出1 像素线对应的Point,然后设置偏移
```objc
#define SINGLE_LINE_WIDTH (1 / [UIScreen mainScreen].scale)
#define SINGLE_LINE_ADJUST_OFFSET ((1 / [UIScreen mainScreen].scale) / 2)
UIView *view = [[UIView alloc] initWithFrame:CGrect(x - SINGLE_LINE_ADJUST_OFFSET, 0, SINGLE_LINE_WIDTH, 100)];
```
iOS设备上,有逻辑像素(point)和 物理像素(pixel)之分。point和pixel的比例是通过[[UIScreen mainScreen] scale]来制定的。在没有视网膜屏之前,1point = 1pixel;但是2x和3x的视网膜屏出来之后,1point等于2pixel或3pixel。
在UI设计师提供的设计稿标注,和在代码中设置frame,其中x,y,width,height的单位是 **逻辑像素(point)**;GPU在渲染图形之前,系统会将**逻辑像素(point)**换算成 **物理像素(pixel)**。
### 缓存行高
在cell离开屏幕后,保存行高:
```objc
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
[self.heightDict setObject:@(cell.height) forKey:key];
DEBUG_LOG(@"第%@行的计算的最终高度是%f",key,cell.height);
}
```
如果已经缓存了行高,那么直接返回高度,否则返回预估行高:
```objc
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [NSString stringWithFormat:@"%ld",indexPath.row];
if (self.heightDict[key] != nil) {
NSNumber *value = _heightDict[key];
DEBUG_LOG(@"%@行的缓存下来的高度是%f",key,value.floatValue);
return value.floatValue;
}
return UITableViewAutomaticDimension;
}
```
### 部分页面支持旋转
在一些视频应用中,播放视频的时候是支持屏幕旋转的,但是其他时候则不支持,iOS 在 UIViewController 中提供了一个方法 `supportedInterfaceOrientations()`。
当 iOS 设备旋转到一个新的方向时,`supportedInterfaceOrientations()` 方法就会被调用。如果这个方法的返回值中包含新的方向,应用程序就会旋转当前视图,否则不旋转。每个视图控制器都可以重写这个方法,对于单个试图控制器,可以在特定条件下支持特定的方向。
```swift
override func supportedInterfaceOrientations)_ -> UIInterfaceOrientationMasl {
return UIInterfaceOrientationMask(rawValue:(UIInterfaceOrientationMask.portait.rawValue | UIInterfaceOrientationMask.landscapeLeft.rawValue))
}
```
### 通过 GCD 判断是否是主队列
先要明白队列和线程的关系。主线程中除了主队列还有可能运行其他的全局队列。而主队列只会在主线程中运行
关于如何判断是否是主队列,可以使用 GCD:
```objc
BOOL RCTIsMainQueue()
{
static void *mainQueueKey = &mainQueueKey;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dispatch_queue_set_specific(dispatch_get_main_queue(),
mainQueueKey, mainQueueKey, NULL);
});
return dispatch_get_specific(mainQueueKey) == mainQueueKey;
}
```
其实就是在主线程中添加了一个 key-value 映射,只有在主线程的情况下,才能拿到这个 key-value
还有一种方式,通过获取当前队列的 label 和 主队列的 label 进行比较:
```objc
dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(dispatch_get_main_queue())
```
### 模拟器弹出键盘
一般情况下,模拟器的输入框是不会弹出键盘的,我们可以设置其为弹出键盘:`command+shift+k`。其实勾掉了选项中的 connect kardware keyboard:

### import 尖括号和双引号的区别
import "xxx.h"的路径搜索顺序:
1. USE_HEADERMAP
2. USER_HEADER_SEARCH_PATHS
3. HEADER_SEARCH_PATHS
import <xxx.h> 的路径搜索顺序:
1. 系统路径
2. HEADER_SEARCH_PATHS
USE_HEADERMAP 是在 Build Settings 中的 Use Header Maps 中设置,默认为 YES,表示系统会自动为编译期提供一个文件映射。我们自己 new 出来的文件就是通过它找到的。
其实就是双引号是自己创建的文件里找,尖括号是从系统的文件里找。没找到的话,都会到 HEADER_SEARCH_PATHS 中找。
### Framework Search Paths 和 Header Search Paths
一般情况下,直接把文件或者 framework 拖进工程里,并且勾上 `copy if needed`,不会出现任何问题。但是有时候,我们的头文件或者 framework 并不能直接放到工程里。比如一个 RN 应用,framework 是保存在 RN 的 src 中的某个文件夹内的。这个时候就会出现头文件找不到的问题。
因为通过 `copy if needed` 添加的文件会被 Xcode 自动添加到 Framework Search Paths 或者 Header Search Paths 里。但是如果不是这种情况,我们就需要手动添加 Search Paths
> 主工程中引入了目标库,子target没有引入目标库。由于目标库已经在工程中了,因此只要在子target只要设置头文件搜寻地址即可。
>
> 以上适用于静态库,对于动态库,主工程中需要引入目标库,子 target 中还需要将动态库通过 Link Binary With Libraries 引入,不用设置头文件搜寻地址了。
### 为什么不在 iOS 项目中使用 redux
redux 将所有状态组合在一起,配合 react 食用更佳,那么我们为什么不把他使用子啊 iOS 中呢?我想到了两个理由:
1. oc 或者 swift 是强类型语言。如果把状态都放在 store 里维护,意味着 store 里需要 import 各种 model 类。产生强耦合。而 js 则是弱类型。不用在意 store 里的某个属性究竟是什么类型,也就不需要 import 那么多 model。
2. react 是相应式的,store 里的属性修改了就能反映到 UI 上,但是 iOS 编程不是响应式的,即使 store 里的实行改变了,你还是要使用 `setText` 等类似方法,刷新 UI。所以即使使用也最好配合 RxSwift

### 封装原则
- 明确目标:首先靠考虑好,封装要做什么,不要写着写着换目标。
- 单一功能原则:其次,要将一个大目标分解成若干步小目标分别实现。然后串联起来
- 外界知道最少:找出外界必须知道的,作为封装输出
- 重复代码复用:找出重复代码,塞到封装内
- 写伪代码:逻辑复杂,不要想着一步到位。先写伪代码,然后把相同的部分归类。
### Image.Assets 存放图片和在文件夹里存放的区别
Assets.xcassets 一般是以蓝色文件夹形式在工程中,以Image Set的形式管理。当一组图片放入的时候同时会生成描述文件Contents.json。**且在打包后以Assets.car的形式存在,以此方式放入的图片并不在mainBundle中**,不能使用 contentOfFile 这样的API来加载图片(因为这个方法相当于是去mainBundle里面找图片,但是这些图片都被打包进了Assets.car文件),interface builder中使用图片时不需要后缀和倍数标识(@2x这样的)优点是性能好,节省Disk。
直接拖到文件夹里的图片,都是存在 mainBundle 中的。所以可以使用 contentOfFile 来加载图片。另外我们也可以把资源文件打成一个 bundle,放在主工程下(mainBundle 下)。
### copy groups 和 copy folder reference 的区别
#### 什么是 Group
Group 其实是仅在 Xcode 中虚拟的用来组织文件的一种方式, **它对文件系统没有任何影响**, 无论你创建或者删除一个 Group, 都不会导致实际的文件的增加或者移除。
#### 两者区别
打包的时候, xode 目录下的所有文件,除了 Image.Assets 以及动态库,都会保存到 mainBundle 中去(静态库是在 mainBundle 中的)。以 `copy groups` 引入的文件,没有文件层级,就**相当于直接把 group 里的文件扔到了 mainBundle 中去**,而以 `copy folder reference` 引入的文件会保持文件层级。
Group 在我们的工程中就是黄色的文件夹, 而 Folder 是蓝色的文件夹。
### 基本类型的指针
我们知道,基本类型的变量作为入参传入函数产生改变时不会影响外部的变量值。所以如果不能返回的话,就需要传入一个基本类型的指针:
```objc
BOOL roolback = YES;
BOOL *r = &roolback;
---
// 假设传入了某个方法,然后在其中改变了值
*r = NO;
---
NSLog(@"%d,roolback 从1变为了0",roolback);
```
非基本类型的指针的赋值直接就是 `p = Person()` 这种地址的赋值就行了,**不存在 `*p` 的情况**。基本类型的指针必须通过 `*r` 拿到堆上的值 `*r = No。
### 为文本加上下划线
基本就是用 `NSMutableAttributedString` 代替原来的 `NSString`,然后为文本长度的 range 内添加一个下划线的属性。
下面演示一个为按钮添加下划线:
```objc
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:button.titleLabel.text];
NSRange strRange = {0,[string length]};
[string addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
[button setAttributedTitle:string forState:UIControlStateNormal];
```
### 如何让 xib 中的两个视图平分父视图
说是平分,其实就是两个视图的宽度相同。最开始的办法是设置一个空白视图居于父视图的中间,然后两个视图分别贴着这个空白视图的左右,但是这个方法非常的蠢。其实只要选中两个视图,然后设置为 `equal width` 就行了,就在设置约束的地方。
### VC 中使用 self.view 获取屏幕宽高出错
**错误描述:**在 `viewDidLoad` 中视图通过 `self.view` 获取屏幕宽高,但是获取数值有误。
**原因:**这种情况一般是使用 xib 设置页面的时候出现。使用xib设置页面的时候,选择的是iPhone7的布局,宽度是375.当从 xib 加载页面后,`viewDidLoad` 时,约束没有更新。所以 `self.view` 的宽度和高度还是 xib 设计的高宽。要等到 `viewDidAppear` 时页面约束就会更新。
建议不要在 `viewDidLoad` 中直接使用 `self.view.bounds` 的高宽来计算其他属性的 `frame`。 而是使用 `[UIScreen mainScreen].bounds` 获取手机屏幕的真实高宽。
### 如何在二级页面隐藏 `tabbar`
一般会在 `TabBarController` 中设置多个 `NavigationController` 作为各个 `tab` 的 `ViewController`。我们只要写一个 `BaseViewController`,在其中重写 `pushViewController:animated` 方法,在其中判断是否需要隐藏就行。设置 `hidesBottomBarWhenPushed` 属性来控制在跳转的时候隐藏。
```objc
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
if (self.viewControllers.count) {
viewController.hidesBottomBarWhenPushed = YES;
}
[super pushViewController:viewController animated:animated];
}
```
### 如何在 `pop` 的时候清理资源
仍然是在 `BaseViewController` 中重写 `popViewControllerAnimated:` 方法。在其中调用特定方法,来做一些清理资源的善后工作。
```objc
- (UIViewController *)popViewControllerAnimated:(BOOL)animated{
if ([[self.viewControllers lastObject] isKindOfClass:[BaseViewController class]]) {
BaseViewController *viewController=[self.viewControllers lastObject];
[viewController willPopViewController];
}
return [super popViewControllerAnimated:animated];
}
```
### `UIImage` 的渲染模式 `imageWithRenderingMode:`
该方法用来设置属性 `renderingMode`。它使用 `UIImageRenderingMode` 枚举值来设置图片的 `renderingMode` 属性。该枚举中包含下列值:
```objc
UIImageRenderingModeAutomatic // 根据图片的使用环境和所处的绘图上下文自动调整渲染模式。
UIImageRenderingModeAlwaysOriginal // 始终绘制图片原始状态,不使用Tint Color。
UIImageRenderingModeAlwaysTemplate // 始终根据Tint Color绘制图片,忽略图片的颜色信息。
```
应用场景是什么呢?比如设置一个 `tabbar` 的 `UIImage` 如果不将其设置为 `UIImageRenderingModeAlwaysOriginal`。那么图片的选中状态的颜色就会跟随系统的 `tintColor`。
### 封装一个没有数据时显示空白页
没有数据的时候通常需要显示一个空白页。空白页长得都差不多,基本上都是一段话加上一张图。我们当然不要每次都写一遍这个视图,因此就需要将这些操作放到 base 中去。
在 `BaseViewController` 中添加一个 `reloadDataWithBlank` 方法,每次从网络获取完数据后,调用即可(省去了每次都要判断数据是否为空的麻烦):
```objc
- (void)reloadDataWithBlank{
//多段就看每个数组,一段就直接看元素个数
if (_isMultiSection) {
BOOL isCountZero=YES;
for (NSArray *array in self.dataSource) {
if (array.count!=0) {
isCountZero=NO;
break;
}
}
if (isCountZero) {
[_tableView addSubview:self.blankHintView];
}else{
[self.blankHintView removeFromSuperview];
}
}else{
if (self.dataSource.count==0) {
[_tableView addSubview:self.blankHintView];
}else{
[self.blankHintView removeFromSuperview];
}
}
[_tableView reloadData];
}
```
其中 `blankHintView` 就是空白提示视图:
```objective-c
-(UIView *)blankHintView{
if (!_blankHintView) {
[self initBlankHintView];
}
return _blankHintView;
}
-(void)initBlankHintView{
_blankHintView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(self.tableView.width/2-40,self.tableView.height/2-40-30,80,80)];
if (_blankHintImage) {
imageView.image = _blankHintImage;
}else{
imageView.image = [UIImage imageNamed:@"nonetworkdefault"];
}
imageView.contentMode=UIViewContentModeScaleAspectFit;
UILabel *hintLabel = [[UILabel alloc]initWithFrame:CGRectMake(imageView.x-10, imageView.y+imageView.height, 200, 30)];
hintLabel.numberOfLines = 0;
hintLabel.lineBreakMode = NSLineBreakByWordWrapping;
hintLabel.textColor=[UIColor colorWithHexString:@"9e9e9e"];
hintLabel.backgroundColor = [UIColor clearColor];
hintLabel.textAlignment=NSTextAlignmentLeft;
hintLabel.font=FONT(15);
hintLabel.text=_blankHintString;
[_blankHintView addSubview:hintLabel];
[_blankHintView addSubview:imageView];
[hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(imageView.mas_bottom).offset(0);
make.centerX.equalTo(imageView.mas_centerX).offset(0);
make.height.equalTo(@30);
}];
}
```
每次在 `viewDidLoad` 中,或者在这个方法内再创建一个功能更明确的 `loadDefaultDataSource` 方法,在其中中添加默认的 `title` 和 `image` 即可。
```objective-c
-(void)loadDefaultDataSource{
[super loadDefaultDataSource];
self.blankHintImage = [UIImage imageNamed:@"default_nomessage"];
self.blankHintString=@"暂无通知消息";
}
```
### 设置手势事件
关于手势,通常需要先声明一个手势,再在另一处添加这个手势的处理方法,这样设置事件和方法本身就会分隔开来,回顾代码的时候找起来会很麻烦。可以为 `UIView` 设置添加一个处理手势的范畴(category),在其中通过 block 回调的方式将方法保存起来:
```objc
@implementation UIView (BlockGesture)
- (void)addTapActionWithBlock:(GestureActionBlock)block{
UITapGestureRecognizer *gesture = [self associatedValueForKey:_cmd];
if (!gesture){
gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
[self addGestureRecognizer:gesture];
[self setAssociateValue:gesture withKey:_cmd];
}
[self setAssociateCopyValue:block withKey:&kActionHandlerTapBlockKey];
self.userInteractionEnabled = YES;
}
- (void)handleActionForTapGesture:(UITapGestureRecognizer*)gesture{
if (gesture.state == UIGestureRecognizerStateRecognized){
GestureActionBlock block = [self associatedValueForKey:&kActionHandlerTapBlockKey];
if (block){
block(gesture);
}
}
}
```
先把 `gesture` 保存起来,再把手势对应的 `block` 保存起来。使用的时候调用即可:
```objc
[label addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
...
}];
```
### 图像显示过程与一些注意事项
#### 显示过程
**这里首先强调,这里说的所有都是针对 View 而不是 Controller。** 自动布局将视图显示到屏幕上的步骤总共分为三步:
1. 更新约束。它为布局准备好必要的信息,而这些布局将在实际设置视图的 frame 时被传递过去并被使用。你可以通过调用 `setNeedsUpdateConstraints` 来触发这个操作。谈到自定义视图,**可以重写 `updateConstraints` 来为你的视图的本地约束进行修改(一般不会用啦)**,但要确保在你的实现中修改了任何你需要布局子视图的约束条件**之后**,调用一下 `[super updateConstraints]`。
2. 布局。将约束条件应用到视图上。可以**通过重写 `layoutSubViews` 实现**,也就是在调用 `[super layoutSubviews]` 前修改一些约束信息。可以通过调用 `setNeedsLayout` 来触发一个操作请求,这并不会立刻应用布局,而是在稍后再进行处理。因为所有的布局请求将会被合并到一个布局操作中去。可以调用 `layoutIfNeeded` 来强制系统立即更新视图树的布局。
3. 显示。可以通过调用 `setNeedsDisplay` 来触发,这将会导致所有的调用都被合并到一起推迟重绘。重写熟悉的 `drawRect:` ,通过这个方法我们可以在 `UIView` 中绘制图形,比如绘制个角标之类的。

#### `layoutSubViews` 的注意事项
`layoutSubViews` 方法给 View 提供了一个统一设置子视图大小布局的地方,不能在 `init` 方法中。因为当外部创建该 view 时,如果外部调用 `init` 方法而不是调用 `initWithFrame` (即没有给这个 view 设置大小),那么 view 中子视图就无法正确初始化出大小。因此,**子视图的 `bounds` 等属性(例如 `center` 等)的设置必须放在 `layoutSubviews` 中,即外部 view 大小已经确定,就要显示的时候。**
---
**记一个错误容易犯的错误:**
`frame`,`center` 都是相对于父 View 的。所以如果你要让一个子 View 在 父 View 居中,你绝对不能写 `subView.center = parentView.center`,因为 `parentView.center` 又是相对于其父 View 的。你应该通过父 View 的 `bounds` 计算得到:
```objc
- (void)layoutSubViews {
subView.center = CGPointMake(self.bounds.size.width/2,self.bounds.size.height/2);
}
```
**记另一个容易犯的错误**
上面重写了 `layoutSubViews` 这个方法,并没有调用父类方法 `[super layoutSubViews]`,那么到底要不要调用呢?答案是最好调用,否则可能会出错。下面简述可能会出错的情况。
比如一个 CollectionViewCell,其中有一层图层 `contentView`。我们添加的视图一般都是添加在 `contentView` 上。当 cell 的 bounds 发生变化的时候,`contentView` 的大小不会立即变化,而是在调用了系统的 `[super layoutSubViews]` 后才会将 `contentView` 变为和 cell 一样大。如果你不调用父类方法,那么你就不能将你添加的子视图的位置依赖于 `contentView` 的 bounds
其实就是系统会在 `[super layoutSubViews]` 中修改系统自身添加的子视图的位置信息。如果你要用到系统的子视图,你就必须要先调用 `[super layoutSubViews]`
---
**注意,不是添加子视图。子视图在 `init` 方法中添加。一定不要在 `layoutSubviews` 方法中添加子视图。因为 `layoutSubviews` 方法会被多次调用,不可能每次调用都添加一遍子视图吧。**
**另外最好不要孤立地改动在 `layoutSubviews` 中设置过的子视图(比如大小,位置等)。因为 `layoutSubviews` 会被多次调用。在被调用后,改动又会变回去了。要改动也是要先将要改动的属性保存起来,让 `layoutSuibviews` 调用的时候通过这个属性设置 View。**
> 这个方法只是在要设置子视图 frame 的时候重写。如果你使用的是 autolayout 来设定位置,那么直接在 `init` 中设置 constraints 就可以了,因为这个方法会被调用多次,在这个方法里添加约束会导致约束重复添加。
>
> 什么时候用 autolayout 什么时候用 frame 就见仁见智了。一般来说只与父视图有关的话,那么就用 frame 设置位置,如果与兄弟视图有关的话,还是用 autolayout 教好一些。
>
> 同样的还有 ViewController 的 `viewDidLayoutSubviews` 方法,这个方法会在 VC 的 view 调用其 `layoutSubViews` 后调用(相当于调用了 `[super layoutSubViews]`)。如果要设置 VC 中的视图的 frame,可以考虑在这个方法里设置。但是一般我们都是在 `viewDidLoad` 方法里设置的无论是 frame 还是 constraint。
#### frame 修改 AutoLayout
AutoLayout 最后也是将约束设置为要展示的位置信息。所以我们也是可以使用 frame 来改变 autolayout 产生的位置的。但是修改的时机很重要。比如你在 xib 中设置了约束,然后你再 `viewDidLoad` 方法中修改了某个空间的 frame 那是没有用的。**因为,autolayout 的布局,本质上还是 frame 的形式。系统会在 layout subViews 时加载约束信息,将其转换为 frame。**所以如果你想改变 autolayout 的布局,你需要在 `viewDidLayoutSubviews` 中设置 frame
#### 改变约束的注意事项
**任何地方都能够添加修改约束**(包括 init 方法)。但是修改过约束后,并不能触发视图的更新,所以一般要调用 `layoutIfNeeded` 方法查看更新约束后的视图。更新视图的动画方法一般设置为:
```objc
[UIView animateWithDuration:1.0f delay:0.0f usingSpringWithDamping:0.5f initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
[self.view layoutIfNeeded];
} completion:NULL];
```
#### `updateConstraints` 的使用时机
不要将 `updateConstraints` 用于视图的初始化设置。**当你需要在单个布局流程(single layout pass)中添加、修改或删除大量约束的时候,用它来获得最佳性能。如果没有性能问题,直接更新约束更简单。**
如果一定要用这个方法,那么在更新约束之前,请先移除之前设置的约束,否则约束重复了会编译不过的。 移除约束的方法是:` [self removeConstraints:self.constraints];`。
**对于手撸一个 view 来说,一般不用重写 `updateConstraints`,只有在某些情况要大量修改约束的时候才用到,请把建立 constraints 的工作放在 `init` 或 `viewDidLoad` 階段。**
#### 关于 `drawRect`
`drawRect` 方法通过 `CGContextRef context = UIGraphicsGetCurrentContext();` 拿到上下文句柄,然后将自己要画的图形添加到这个上下文上。具体可以在要用的时候看看例子。
### 设置 view 的一些注意事项
- 重写 `UIView` 的 `initWithFrame:` 而不是 `init` 方法。 因为当外部调用 `init` 的方法的时候,其内部也会默默地调用 `initWithFrame:`方法。
- 不要在构造方法里面直接取自身(self,或者说本视图)的宽高,这时候取到的宽高是不准的.
- 当在代码中设置视图和它们的约束条件时候,一定要记得将该视图的 `translatesAutoResizingMaskIntoConstraints` 属性设置为 NO。如果忘记设置这个属性几乎肯定会导致不可满足的约束条件错误。
- 在 `initWithFrame:` 方法中将子控件加到 view 而不是设置尺寸。因为 view 有可能是通过 `init` 方法创建的,这个时候 view 的 frame 可能是 不确定的。这种情况下各个子控件的尺寸都会是0,因为这个 view 的 frame 还没有设置。设置尺寸的工作放在 `layoutSubviews` 中去做。
- `allowsGroupOpacity` 属性允许子控件的不透明度继承于其父控件,默认是开启的 `yes`。不过这会影响性能,自定义控件的时候最好设置为 `self.layer.allowsGroupOpacity = NO;`
- `clipsToBounds` 是 `UIView` 的属性,如果设置为 `yes`,则不显示超出父 View 的部分;`masksToBounds` 是 `CALayer` 的属性,如果设置为 `yes`,则不显示超出父 View layer 的部分.
- 设置视图的时候一定要先设置大小再设置 center ,center 是为了确定 CGRect 的,如果当时CGRect为0,那么此时设置 center,就像当于给 CGRect 设置了 origin。
-
### 用 UIImageView 播放动图
app 中的加载等候经常需要播放一个动图,那么怎么让图片动起来呢?`UIImageView` 就能解决。
把所需要的 GIF 打包到一个叫做 Loading 的 Bundle 中去,加载 Bundle 中的图片:
```objc
- (NSArray *)animationImages
{
// 拿到所有文件的文件名的数组
NSFileManager *fielM = [NSFileManager defaultManager];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Loading" ofType:@"bundle"];
NSArray *arrays = [fielM contentsOfDirectoryAtPath:path error:nil];
// 遍历文件名,拿到文件名对应的 UIImage 加入到 UIImage 的数组中
NSMutableArray *imagesArr = [NSMutableArray array];
for (NSString *name in arrays) {
UIImage *image = [UIImage imageNamed:[(@"Loading.bundle") stringByAppendingPathComponent:name]];
if (image) {
[imagesArr addObject:image];
}
}
return imagesArr;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:frame];
// 将 UIImage 数组设置给 UIImageView
gifImageView.animationImages = [self animationImages]; //获取Gif图片列表
gifImageView.animationDuration = 5; //执行一次完整动画所需的时长
gifImageView.animationRepeatCount = 1; //动画重复次数
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
}
```
### 获取一个指定的 View
想要获取一个指定的 view 的方法是遍历一个 view 的所有 subview,然后判断 view 的类型是否是指定的。在 `MBProgressHUD` 中的方式是:
```objc
+ (MBProgressHUD *)HUDForView:(UIView *)view {
NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator];
for (UIView *subview in subviewsEnum) {
if ([subview isKindOfClass:self]) {
return (MBProgressHUD *)subview;
}
}
return nil;
}
```
这个方法是找到并隐藏相应 hud。这里面使用了 `NSEnumerator` 这个枚举类,通过 `reverseObjectEnumerator` 反向浏览集合。
### 获取当前 ViewController
### 通过 View
为了做到数据与视图的分离,我们一般会将一个页面的局部视图以自定义 `UIView` 的方式独立出来,如果在该视图中有触发事件(事件处理不需要父视图的上下文),就会遇到在 `UIView` 中获取 `UIViewController` 的情况,可以写一个 `UIView` 的范畴 `UIView(UIViewController)`:
```objc
#pragma mark - 获取当前view的viewcontroller
+ (UIViewController *)getCurrentViewController:(UIView *) currentView
{
for (UIView* next = [currentView superview]; next; next = next.superview)
{
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
{
return (UIViewController *)nextResponder;
}
}
return nil;
}
```
### 通过 rootViewController
```objc
- (UIViewController *)findCurrentViewController
{
UIWindow *window = [[UIApplication sharedApplication].delegate window];
UIViewController *topViewController = [window rootViewController];
while (true) {
if (topViewController.presentedViewController) {
topViewController = topViewController.presentedViewController;
} else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
topViewController = [(UINavigationController *)topViewController topViewController];
} else if ([topViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tab = (UITabBarController *)topViewController;
topViewController = tab.selectedViewController;
} else {
break;
}
}
return topViewController;
}
```
### pop 到指定 ViewController
`UINavigationController` 有个 Property,是一个存储所有 push 进 navigationcontroller 的视图的集合,是一个栈结构,当我们要 POP 到某个 ViewController 的时候,直接用 `for in` 去遍历 viewControllers 即可:
```objc
for (UIViewController viewController in self.navigationController.viewControllers){
if ([viewController isKindOfClass:[AccountManageViewController class]]){
[self.navigationController popToViewController:viewController animated:YES];
}
}
```
### 一个规范的 ViewController 的代码结构
一个 ViewController 中的代码如果不分类,那么查看起来就会非常混乱,经常需要到处跳转。因此写代码的时候按照顺序来分配代码块的位置。先是 `life cycle`,然后是`Delegate方法实现`,然后是`event response`,然后才是`getters and setters`,用 `#pragma mark - ` 分隔开。这样后来者阅读代码时就能省力很多。
> getter和setter全部都放在最后
因为一个ViewController很有可能会有非常多的view,如果getter和setter写在前面,就会把主要逻辑扯到后面去,其他人看的时候就要先划过一长串getter和setter,这样不太好。
> 每一个delegate都把对应的protocol名字带上,delegate方法不要到处乱写,写到一块区域里面去
比如UITableViewDelegate的方法集就老老实实写上`#pragma mark - UITableViewDelegate`。这样有个好处就是,当其他人阅读一个他并不熟悉的Delegate实现方法时,他只要按住command然后去点这个protocol名字,Xcode就能够立刻跳转到对应这个Delegate的protocol定义的那部分代码去,就省得他到处找了。
> event response专门开一个代码区域
所有button、gestureRecognizer的响应事件都放在这个区域里面,不要到处乱放。
> 关于private methods,正常情况下ViewController里面不应该写
不是delegate方法的,不是event response方法的,不是life cycle方法的,就是private method了。对的,正常情况下ViewController里面一般是不会存在private methods的,这个private methods一般是用于日期换算、图片裁剪啥的这种小功能。这种小功能要么把它写成一个category,要么把他做成一个模块,哪怕这个模块只有一个函数也行。
ViewController基本上是大部分业务的载体,本身代码已经相当复杂,所以跟业务关联不大的东西能不放在ViewController里面就不要放。另外一点,这个private method的功能这时候只是你用得到,但是将来说不定别的地方也会用到,一开始就独立出来,有利于将来的代码复用。
### 一些宏
#### #define
为一段代码设置一个缩写,这段代码可以是一个数字,也可以是一个函数。
```objc
#define SERVER_ONLINE_DEVELOPMENT
```
#### #if DEBUG
通过 `Build Configuration` 设置调试版本,分为 `debug` 和 `release`。正式发行的版本和 `release` 一致(但是真机调试的时候还是用develop证书)。可以使用预设宏来为开发环境添加一些额外的操作:
```objc
#if DEBUG
#define HttpDefaultURL HttpFormal
#else
#define HttpDefaultURL HttpSimulation
#endif
```
这样就不用自己设置环境了。
如果要设置非 `debug`,那么使用 `#if !DEBUG`
#### #ifdef
该宏判断后面的宏是否被定义过:
```objc
#ifdef SERVER_ONLINE_DEVELOPMENT
...
#endif
```
### 如何定义一个结构
使用结构保存多个相关数据。
```objc
struct Person{
float height;
int age;
};
```
使用:`struct Person mikey;`
使用 `typedef` 简化。`typedef` 可以为某类型声明一个等价的别名,该别名用法和常规数据类型无异。
```objc
typedef struct {
float height;
int age;
} Person;
```
使用,就当做一个普通类型使用:
```objc
Person mikey;
mikey.length = 1.45
```
### extern和static
我们知道在 `@interface...@end`,`@implementation...@end` 之外的是全局变量。OC 提供了两个关键字 `static` 和 `extern` 修饰。
#### static
用 `static` 声明局部变量(定义在方法内),使其变为静态存储方式(静态数据区),作用域不变(**其他方法不能使用**),但是延长了生命周期(程序结束才销毁)
用 `static` 声明外部变量(在方法外),使其**只在本文件内部有效**,而其他文件不可连接或引用该变量。
##### 变量
```objc
// 方法中或者 @implementation...@end 之外
static int a = 789;
```
`static` 可以在任意位置声明。一般我们都将其声明在 `.m` 文件中。可以声明在方法中,或者 `@implementation...@end` 之外。
##### 方法
```objc
static int method() {
return 1;
}
```
`static` 的方法可以放在 `@implementation...@end` 之内,也可以放在之外。效果都是一样的。
#### extern
`static` 修饰的全局变量只能在该文件内访问,那么文件如何访问别的文件定义的全局变量呢?使用 `extern` 关键字。使用 `extern` 意味着**该变量或者方法在别处实现**。(你必须先用 `extern` 声明一下,这是为了告诉编译器进行全局变量的链接,否则直接编译的时候就会报错。)
如果全局变量和局部变量重名,则在局部变量作用域内,全局变量被屏蔽,不起作用。编程时候尽量不使用全局变量。
##### 变量
```objc
// 任意的某一个 .m 的 @implementation...@end 之外
NSString *s = @"global";
// 要用到全局变量的 .h 中
extern NSString *s;
```
在任意的一个 `.m` 中定义一个全局变量。然后要用到这个全局变量的地方使用 `extern`关键字即可。编译的时候就会链接到这个全局变量。
`extern` 的变量写在任意位置都是可以的,包括 `.h` 的 `@interface...@end` 之内或之外或者`.m` 的 `@implementation...@end` 的之内之外。不过推荐写在 `.h` 的 `@interface...@end` 之外。
##### 方法
```objc
// 任意的 .m 中
int method() {
return 1;
}
// 要用到的全局变量的 .h 中
extern method();
```
全局方法写在 `.m` 的 `@implementation...@end` 之内还是之外都行,因为这种方式定义的方法就已经表明它是全局方法了。
### 添加 UIGestureRecognizer 点击事件不响应
1. 设置 `UIView` 的 `userInteractionEnabled` 属性值为 `YES`,否则 `UIView` 会忽略那些原本应该发生在其自身的诸如 touch 和 keyboard 等用户事件,并将这些事件从消息队列中移除出去。
2. 循环创建对象的时候,不能只创建一个 `UIGestrueRecognizer`,而要在每个循环里为每个 `UIView` 创建并添加 `UITapGestureRecognizer` 。
3. 父view 太小,子view 通过 `addSubView` 的方式添加到父view 外部,导致响应链无法传递到子 view 中,无法响应 `UIGestureRecognizer`(被这个坑过很久)
### 倒计时按钮(每秒触发)
通过 gcd 设置一个每秒都会触发执行的队列,然后自己控制时间,何时退出。
```objc
// 开启倒计时效果
-(void)openCountdown{
__block NSInteger time = 59; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(time <= 0){ //倒计时结束,关闭
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//设置按钮的样式
[self.authCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
[self.authCodeBtn setTitleColor:[UIColor colorFromHexCode:@"FB8557"] forState:UIControlStateNormal];
self.authCodeBtn.userInteractionEnabled = YES;
});
}else{
int seconds = time % 60;
dispatch_async(dispatch_get_main_queue(), ^{
//设置按钮显示读秒效果
[self.authCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
[self.authCodeBtn setTitleColor:[UIColor colorFromHexCode:@"979797"] forState:UIControlStateNormal];
self.authCodeBtn.userInteractionEnabled = NO;
});
time--;
}
});
dispatch_resume(_timer);
}
```
注意:
> 我们在创建Button时, 要设置Button的样式:
> 当type为: UIButtonTypeCustom时 , 是读秒的效果.
> 当type为: 其他时, 是一闪一闪的效果.
### 获取float的前两位小数
当我们直接把 `float` 转为 `NSString` 会发现小数点后有很多小数,可以按照需求截取几位小数:
```objc
NSString *strDistance=[NSString stringWithFormat:@"%.xf", kilometers]; //x表示具体显示多少位
```
|
Python | UTF-8 | 9,263 | 2.765625 | 3 | [] | no_license | import re;
import gconst;
import parsing
import os;
from collections import *;
from Bio.Seq import reverse_complement;
from itertools import combinations, product, combinations_with_replacement;
Mismatch = namedtuple("Mismatch", "fr, to, position");
Deletion = namedtuple("Deletion", "fr, position");
Insertion = namedtuple("Insertion", "to, position");# "position" means BEFORE what position in the original sequence insertion happened
class Mismatched(object):
def __init__(self, initial_sequence, mismatches):
l = list(initial_sequence);
#print l
for m in mismatches:
l[m.position] = m.to;
self.seq = "".join(l);
self.mismatches = mismatches;
class Inserted(object):
def __init__(self, initial_sequence, insertions):
l = list(initial_sequence);
for i in sorted(insertions, key = lambda x: x.position, reverse = True):
l.insert(i.position, i.to)
self.seq = "".join(l);
self.insertions = insertions;
class Deleted(object):
def __init__(self, initial_sequence, deletions):
l = list(initial_sequence);
for d in deletions:
l[d.position] = ""
self.seq = "".join(l);
self.deletions = deletions;
class Seed(object):
def __init__(self, mirseq, mirid, start=1, end = 8):
self.id = mirid;
self.mirseq = mirseq;
self.seed = mirseq[start:end];
self.match = reverse_complement(self.seed);
self.mismatched = [];
self.inserted = [];
self.deleted = [];
self.start, self.end = start, end;
#print self.seed
#print self.match;
def generate_mismatches(self, upto = 1, start = False, end = False):
if(start or end):
match = reverse_complement(self.mirseq[start:end])
else:
match = self.match;
level = [];
for positions in combinations(range(len(match)), upto):
locker = [match[p] for p in sorted(positions)]
variants_raw = product("ACTG", repeat = len(positions));
variants = [];
for v in variants_raw:
for i in range(len(v)):
if(v[i] == locker[i]):
break;
else:
variants.append(v);
for v in variants:
mismatches = [];
for i in range(len(v)):
mismatches.append(Mismatch(match[positions[i]], v[i], positions[i]))
level.append(Mismatched(match, mismatches))
self.mismatched.append(level);
return None;
def generate_deletions(self, upto = 1):
for num in range(1,1+upto):
level = [];
for positions in combinations(range(1, len(self.match)-1), num):
deletions = [];
for p in positions:
deletions.append(Deletion(self.match[p], p))
level.append(Deleted(self.match, deletions))
#for d in level:
#print d.seq, d.deletions;
#print "\n"
self.deleted.append(level);
return None;
def generate_insertions(self, upto = 1):
for num in range(1,1+upto):
level = [];
for positions in combinations_with_replacement(range(1, len(self.match)), num):
variants = product("ACTG", repeat = len(positions));
for v in variants:
insertions = [];
for i in range(len(v)):
insertions.append(Insertion(v[i], positions[i]))
level.append(Inserted(self.match, insertions))
#for d in level:
#print d.seq, d.insertions;
#print "\n"
self.inserted.append(level);
return None;
def generate_default_variants(self):
self.generate_mismatches(upto = 1);
self.generate_mismatches(upto = 2, start = 1, end = 8);
self.generate_deletions(upto = 1);
self.generate_insertions(upto = 1);
def associated_values(self, mtype):
def get_ass_list(mtype, reflist):
r = [];
for i, el1 in enumerate(reflist):
r.append([]);
for el2 in el1:
r[i].append(mtype())
return r
self.ass_match = mtype();
self.ass_mismatched = get_ass_list(mtype, self.mismatched);
self.ass_inserted = get_ass_list(mtype, self.inserted);
self.ass_deleted = get_ass_list(mtype, self.deleted);
def find_once(self, seq):
'''hierarchically searches for match or its variations inside the sequence provided'''
ans = [];
if(self.match in seq):
ans.append(self.match);
return "match", ans;
for mismatched in self.mismatched[0]:
if(mismatched.seq in seq):
ans.append(mismatched);
if(ans):
return "mismatch", ans
for inserted in self.inserted[0]:
if(inserted.seq in seq):
ans.append(inserted);
if(ans):
return "insertion", ans
if(len(self.mismatched) > 1):
for mismatched in self.mismatched[1]:
if(mismatched.seq in seq):
ans.append(mismatched);
if(ans):
return "mismatch2", ans
for deleted in self.deleted[0]:
if(deleted.seq in seq):
ans.append(deleted);
if(ans):
return "deletion", ans
return "no_match", ans
def find_everything(self, seq):
'''finds every possible presence of match or it variations inside the sequence provided'''
ans = {'match': [], 'mismatch': [], 'insertion': [], 'deletion': []};
if(self.match in seq):
ans['match'].append(self.match);
for mismatched in self.mismatched[0]:
if(mismatched.seq in seq):
ans['mismatch'].append(mismatched);
for inserted in self.inserted[0]:
if(inserted.seq in seq):
ans['insertion'].append(inserted);
for deleted in self.deleted[0]:
if(deleted.seq in seq):
ans['deletion'].append(deleted);
return ans;
def get_seeds (mirdict, start=1, end=8):
seeds = {};
for mirid, mirseq in mirdict.items():
seeds[mirid] = Seed(mirseq, mirid, start, end);
seeds[mirid].generate_default_variants();
#seeds[mirid].generate_deletions(upto = 1);
#seeds[mirid].generate_insertions(upto = 1);
return seeds;
if __name__ == "__main__":
seed = Seed("TGAGGTAGTAGGTTGTATAGTT", "cel-let-7")
#seed.generate_mismatches(2);
#seed.generate_deletions(2);
seed.generate_insertions(2);
print seed.match
def mir2seed(mirdict, start = 1, end = 7):
sdict = {};
for k,v in mirdict.items():
sdict[k] = reverse_complement(v[start: end])
return sdict;
def seed2mirs(mirdict, start = 1, end = 7):
sdict = defaultdict(list);
for k,v in mirdict.items():
sdict[reverse_complement(v[start: end])].append(k);
return sdict;
def mm28(seq, mir):
#if(len(mir)> 7):
s27 = reverse_complement(mir[1:7])
s38 = reverse_complement(mir[2:8])
a = reverse_complement(mir[1:8])
#elif(len(mir) == 7):
#s27 = reverse_complement(mir[:6])
#s38 = reverse_complement(mir[1:7])
#a = reverse_complement(mir);
mm37 = set();
for i in range(1,6):
for n in "ACTG":
mm37.add(a[:i] + n + a[i+1:]);
order = [s27, s38] + list(mm37);
for el in order:
if(el in seq):
return seq.rfind(el);
return -1;
def modes(seq, mir):
#if(len(mir)> 7):
s27 = reverse_complement(mir[1:7])
s38 = reverse_complement(mir[2:8])
a = reverse_complement(mir[1:8])
#elif(len(mir) == 7):
#s27 = reverse_complement(mir[:6])
#s38 = reverse_complement(mir[1:7])
#a = reverse_complement(mir);
mm28 = set();
for i in range(1,6):
for n in "ACTG":
mm28.add(a[:i] + n + a[i+1:]);
wobble = set()
for i in range(1,6):
if(a[i] == "C"):
wobble.add(a[:i] + "T" + a[i+1:]);
elif(a[i] == "A"):
wobble.add(a[:i] + "G" + a[i+1:]);
ins28 = set();# target bulge
for i in range(1,6):
for n in "ACTG":
ins28.add(a[:i] + n + a[i:]);
del28 = set();# miRNA bulge
for i in range(1,6):
del28.add(a[:i] + a[i+1:]);
order = [s27], [s38] , wobble, mm28, ins28, del28;
for i in range(len(order)):
for s in order[i]:
if(s in seq):
return i;
return -1;
pattern1 = r"\w+-(\w+)-(\d+.*)"
regex1 = re.compile(pattern1);
def longname(mirids):
result = "";
mirs = set();
others = set();
for m in mirids:
temp = regex.search(m).groups()
if(temp[0] == "miR" or temp[0] == "mir"):
mirs.add(temp[1]);
else:
others.add("-".join(temp))
if(others):
result += ",".join(others) + "\\n"
elif(mirs):
result += "miR(" + ",".join(mirs) + ")\\n"
return result
pattern2 = r"\w+-(\w+)-(\d+)"
regex2 = re.compile(pattern2);
def shortname(mirids):
result = "";
mirs = set();
others = set();
for m in mirids:
temp = regex2.search(m).groups()
if(temp[0] == "miR" or temp[0] == "mir"):
mirs.add(temp[1]);
else:
others.add("-".join(temp))
if(others):
return sorted(others)[0] + "\\nfamily"
else:
return "miR-" + str(sorted([int(x) for x in mirs])[0]) + "\\nfamily"
def seeds2name(system):
mirdict = parsing.fasta2dict(gconst.system2mir[system]);
s2m = seed2mirs(mirdict);
s2n = {};
for k, v in s2m.iteritems():
s2n[k] = shortname(v);
return s2n;
def read_families(path):
'''creates fam2mirs dictionary (keys: fam ids, values sets of miRNAs' ids)
path String: path to fam_ids.tsv (left/fam_ids.tsv) file;
'''
fm = defaultdict(set);
f = open(path);
for l in f:
a = l.strip().split("\t");
fm[a[0]].update(a[1].split(","));
f.close();
return fm;
def get_common_part(seqs, fr = 0, tolerate_first_mismatch = -1):
'''gets the longest common onset (5' part of mirna) for all given sequences'''
limit = min([len(x) for x in seqs])
ambiguos = 0;
for i in range(fr, limit):
if(len(set([x[i] for x in seqs])) > 1):
if ((i > tolerate_first_mismatch)):
return 'X'*(fr+ambiguos) + seqs[0][fr+ambiguos:i], i;
else:
ambiguos = i;
return 'X'*(fr+ambiguos) + seqs[0][fr+ambiguos:limit], limit;
|
Java | UTF-8 | 1,662 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2.iosp;
/**
* Uses longs for indexing, otherwise similar to ucar.ma2.Index
*
* @author caron
* @since Jul 30, 2010
*/
public class IndexLong {
private int[] shape;
private long[] stride;
private int rank;
private int offset; // element = offset + stride[0]*current[0] + ...
private int[] current; // current element's index
// shape = int[] {1}
public IndexLong() {
shape = new int[] {1};
stride = new long[] {1};
rank = shape.length;
current = new int[rank];
stride[0] = 1;
offset = 0;
}
public IndexLong(int[] _shape, long[] _stride) {
this.shape = new int[_shape.length]; // optimization over clone
System.arraycopy(_shape, 0, this.shape, 0, _shape.length);
this.stride = new long[_stride.length]; // optimization over clone
System.arraycopy(_stride, 0, this.stride, 0, _stride.length);
rank = shape.length;
current = new int[rank];
offset = 0;
}
public static long computeSize(int[] shape) {
long product = 1;
for (int ii = shape.length - 1; ii >= 0; ii--)
product *= shape[ii];
return product;
}
public long incr() {
int digit = rank - 1;
while (digit >= 0) {
current[digit]++;
if (current[digit] < shape[digit])
break;
current[digit] = 0;
digit--;
}
return currentElement();
}
public long currentElement() {
long value = offset;
for (int ii = 0; ii < rank; ii++)
value += current[ii] * stride[ii];
return value;
}
}
|
Java | UTF-8 | 44,666 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | package com.gh.mygreen.xlsmapper.cellconverter;
import static com.gh.mygreen.xlsmapper.TestUtils.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.gh.mygreen.xlsmapper.XlsMapper;
import com.gh.mygreen.xlsmapper.annotation.RecordTerminal;
import com.gh.mygreen.xlsmapper.annotation.XlsArrayConverter;
import com.gh.mygreen.xlsmapper.annotation.XlsColumn;
import com.gh.mygreen.xlsmapper.annotation.XlsDefaultValue;
import com.gh.mygreen.xlsmapper.annotation.XlsFormula;
import com.gh.mygreen.xlsmapper.annotation.XlsHorizontalRecords;
import com.gh.mygreen.xlsmapper.annotation.XlsIgnorable;
import com.gh.mygreen.xlsmapper.annotation.XlsOrder;
import com.gh.mygreen.xlsmapper.annotation.XlsRecordOption;
import com.gh.mygreen.xlsmapper.annotation.XlsRecordOption.OverOperation;
import com.gh.mygreen.xlsmapper.annotation.XlsSheet;
import com.gh.mygreen.xlsmapper.annotation.XlsTrim;
import com.gh.mygreen.xlsmapper.util.IsEmptyBuilder;
import com.gh.mygreen.xlsmapper.validation.FieldError;
import com.gh.mygreen.xlsmapper.validation.SheetBindingErrors;
import com.gh.mygreen.xlsmapper.validation.SheetErrorFormatter;
/**
* リスト/集合/配列型のコンバータのテスト
*
* @version 2.0
* @since 0.5
* @author T.TSUCHIE
*
*/
public class CollectionCellConveterTest {
/**
* テスト結果ファイルの出力ディレクトリ
*/
private static File OUT_DIR;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
OUT_DIR = createOutDir();
}
/**
* エラーメッセージのコンバーター
*/
private SheetErrorFormatter errorFormatter;
@Before
public void setUp() throws Exception {
this.errorFormatter = new SheetErrorFormatter();
}
/**
* リスト、集合、配列型の読み込みテスト
*/
@Test
public void test_load_collection() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream("src/test/data/convert.xlsx")) {
SheetBindingErrors<CollectionSheet> errors = mapper.loadDetail(in, CollectionSheet.class);
CollectionSheet sheet = errors.getTarget();
if(sheet.simpleRecords != null) {
for(SimpleRecord record : sheet.simpleRecords) {
assertRecord(record, errors);
}
}
if(sheet.formattedRecords != null) {
for(FormattedRecord record : sheet.formattedRecords) {
assertRecord(record, errors);
}
}
if(sheet.customRecords != null) {
for(CustomRecord record : sheet.customRecords) {
assertRecord(record, errors);
}
}
if(sheet.formulaRecords != null) {
for(FormulaRecord record : sheet.formulaRecords) {
assertRecord(record, errors);
}
}
}
}
private void assertRecord(final SimpleRecord record, final SheetBindingErrors<?> errors) {
if(record.no == 1) {
// 空文字
assertThat(record.listText, empty());
assertThat(record.listInteger, empty());
assertThat(record.arrayText, emptyArray());
assertThat(record.arrayInteger, emptyArray());
assertThat(record.setText, empty());
assertThat(record.setInteger, empty());
} else if(record.no == 2) {
// 項目が1つ
assertThat(record.listText, contains("abc"));
assertThat(record.listInteger, contains(123));
assertThat(record.arrayText, arrayContaining("abc"));
assertThat(record.arrayInteger, arrayContaining(123));
assertThat(record.setText, contains("abc"));
assertThat(record.setInteger, contains(123));
} else if(record.no == 3) {
// 項目が2つ
assertThat(record.listText, contains("abc", "def"));
assertThat(record.listInteger, contains(123, 456));
assertThat(record.arrayText, arrayContaining("abc", "def"));
assertThat(record.arrayInteger, arrayContaining(123, 456));
assertThat(record.setText, contains("abc", "def"));
assertThat(record.setInteger, contains(123, 456));
} else if(record.no == 4) {
// 区切り文字のみ
assertThat(record.listText, empty());
assertThat(record.listInteger, empty());
assertThat(record.arrayText, emptyArray());
assertThat(record.arrayInteger, emptyArray());
assertThat(record.setText, empty());
assertThat(record.setInteger, empty());
} else if(record.no == 5) {
// 空の項目がある
assertThat(record.listText, contains("abc", null, "def"));
assertThat(record.listInteger, contains(123, null, 456));
assertThat(record.arrayText, arrayContaining("abc", null, "def"));
assertThat(record.arrayInteger, arrayContaining(123,null, 456));
assertThat(record.setText, contains("abc", null, "def"));
assertThat(record.setInteger, contains(123, null, 456));
} else if(record.no == 6) {
// 空の項目がある
assertThat(record.listText, contains(" abc", " def "));
{
FieldError fieldError = cellFieldError(errors, cellAddress(record.positions.get("listInteger")));
assertThat(fieldError.isConversionFailure(), is(true));
String message = errorFormatter.format(fieldError);
assertThat(message, is("[リスト型]:List(数値) - セル(C10)の値'123, 456 'は、配列の形式に変換できません。"));
}
assertThat(record.arrayText, arrayContaining(" abc", " def "));
{
FieldError fieldError = cellFieldError(errors, cellAddress(record.positions.get("arrayInteger")));
assertThat(fieldError.isConversionFailure(), is(true));
String message = errorFormatter.format(fieldError);
assertThat(message, is("[リスト型]:Array(数値) - セル(E10)の値'123, 456 'は、配列の形式に変換できません。"));
}
assertThat(record.setText, contains(" abc", " def "));
{
FieldError fieldError = cellFieldError(errors, cellAddress(record.positions.get("setInteger")));
assertThat(fieldError.isConversionFailure(), is(true));
String message = errorFormatter.format(fieldError);
assertThat(message, is("[リスト型]:Set(数値) - セル(G10)の値'123, 456 'は、配列の形式に変換できません。"));
}
} else {
fail(String.format("not support test case. No=%d.", record.no));
}
}
private void assertRecord(final FormattedRecord record, final SheetBindingErrors<?> errors) {
if(record.no == 1) {
// 空文字
assertThat(record.listText, empty());
assertThat(record.listInteger, contains(0));
assertThat(record.arrayText, emptyArray());
assertThat(record.arrayInteger, arrayContaining(0));
assertThat(record.setText, empty());
assertThat(record.setInteger, contains(0));
} else if(record.no == 2) {
// 項目が1つ
assertThat(record.listText, contains("abc"));
assertThat(record.listInteger, contains(123));
assertThat(record.arrayText, arrayContaining("abc"));
assertThat(record.arrayInteger, arrayContaining(123));
assertThat(record.setText, contains("abc"));
assertThat(record.setInteger, contains(123));
} else if(record.no == 3) {
// 項目が2つ
assertThat(record.listText, contains("abc", "def"));
assertThat(record.listInteger, contains(123, 456));
assertThat(record.arrayText, arrayContaining("abc", "def"));
assertThat(record.arrayInteger, arrayContaining(123, 456));
assertThat(record.setText, contains("abc", "def"));
assertThat(record.setInteger, contains(123, 456));
} else if(record.no == 4) {
// 区切り文字のみ
assertThat(record.listText, empty());
assertThat(record.listInteger, empty());
assertThat(record.arrayText, emptyArray());
assertThat(record.arrayInteger, emptyArray());
assertThat(record.setText, empty());
assertThat(record.setInteger, empty());
} else if(record.no == 5) {
// 区切り文字、空白
assertThat(record.listText, contains("abc", "def"));
assertThat(record.listInteger, contains(123, 456));
assertThat(record.arrayText, arrayContaining("abc", "def"));
assertThat(record.arrayInteger, arrayContaining(123, 456));
assertThat(record.setText, contains("abc", "def"));
assertThat(record.setInteger, contains(123, 456));
} else if(record.no == 6) {
// 空白がある
assertThat(record.listText, contains("abc", "def"));
assertThat(record.listInteger, contains(123, 456));
assertThat(record.arrayText, arrayContaining("abc", "def"));
assertThat(record.arrayInteger, arrayContaining(123, 456));
assertThat(record.setText, contains("abc", "def"));
assertThat(record.setInteger, contains(123, 456));
} else {
fail(String.format("not support test case. No=%d.", record.no));
}
}
private void assertRecord(final CustomRecord record, final SheetBindingErrors<?> errors) {
if(record.no == 1) {
// 空文字
assertThat(record.listDate, empty());
assertThat(record.arrayDate, emptyArray());
assertThat(record.setDate, empty());
} else if(record.no == 2) {
// 項目が1つ
Date date1 = toUtilDate(toTimestamp("2016-03-15 00:00:00.000"));
assertThat(record.listDate, contains(date1));
assertThat(record.arrayDate, arrayContaining(date1));
assertThat(record.setDate, contains(date1));
} else if(record.no == 3) {
// 項目が2つ
Date date1 = toUtilDate(toTimestamp("2016-03-15 00:00:00.000"));
Date date2 = toUtilDate(toTimestamp("2016-03-16 00:00:00.000"));
assertThat(record.listDate, contains(date1, date2));
assertThat(record.arrayDate, arrayContaining(date1, date2));
assertThat(record.setDate, contains(date1, date2));
} else if(record.no == 4) {
// 区切り文字のみ
assertThat(record.listDate, empty());
assertThat(record.arrayDate, emptyArray());
assertThat(record.setDate, empty());
} else if(record.no == 5) {
// 区切り文字、空白
Date date1 = toUtilDate(toTimestamp("2016-03-15 00:00:00.000"));
Date date2 = toUtilDate(toTimestamp("2016-03-16 00:00:00.000"));
assertThat(record.listDate, contains(date1, date2));
assertThat(record.arrayDate, arrayContaining(date1, date2));
assertThat(record.setDate, contains(date1, date2));
} else if(record.no == 6) {
// 空白がある
Date date1 = toUtilDate(toTimestamp("2016-03-15 00:00:00.000"));
Date date2 = toUtilDate(toTimestamp("2016-03-16 00:00:00.000"));
assertThat(record.listDate, contains(date1, date2));
assertThat(record.arrayDate, arrayContaining(date1, date2));
assertThat(record.setDate, contains(date1, date2));
} else {
fail(String.format("not support test case. No=%d.", record.no));
}
}
private void assertRecord(final FormulaRecord record, final SheetBindingErrors<?> errors) {
if(record.no == 1) {
// 空文字
assertThat(record.listStr, empty());
assertThat(record.arrayStr, emptyArray());
assertThat(record.setStr, empty());
} else if(record.no == 2) {
// 項目が1つ
assertThat(record.listStr, contains("/dir1/index.html", "/dir2/sample.html"));
assertThat(record.arrayStr, arrayContaining("/dir1/index.html", "/dir2/sample.html"));
assertThat(record.setStr, contains("/dir1/index.html", "/dir2/sample.html"));
} else {
fail(String.format("not support test case. No=%d.", record.no));
}
}
/**
* リスト、集合、配列型の書き込みテスト
*/
@Test
public void test_save_collection() throws Exception {
// テストデータの作成
final CollectionSheet outSheet = new CollectionSheet();
// アノテーションなしのデータ作成
outSheet.add(new SimpleRecord()
.comment("空文字"));
outSheet.add(new SimpleRecord()
.listText(toList("abc"))
.listInteger(toList(123))
.arrayText(toArray("abc"))
.arrayInteger(toArray(123))
.setText(toSet("abc"))
.setInteger(toSet(123))
.comment("項目が1つ"));
outSheet.add(new SimpleRecord()
.listText(toList("abc", "def"))
.listInteger(toList(123, 456))
.arrayText(toArray("abc", "def"))
.arrayInteger(toArray(123, 456))
.setText(toSet("abc", "def"))
.setInteger(toSet(123, 456))
.comment("項目が2つ"));
outSheet.add(new SimpleRecord()
.listText(toList("", null, ""))
.listInteger(toList(0, null, null))
.arrayText(toArray("", null, ""))
.arrayInteger(toArray(0, null, null))
.setText(toSet("", null, ""))
.setInteger(toSet(0, null, null))
.comment("空の項目のみ"));
outSheet.add(new SimpleRecord()
.listText(toList("abc", "", "def"))
.listInteger(toList(123, null, 456))
.arrayText(toArray("abc", "", "def"))
.arrayInteger(toArray(123, null, 456))
.setText(toSet("abc", "", "def"))
.setInteger(toSet(123, null, 456))
.comment("空の項目がある"));
outSheet.add(new SimpleRecord()
.listText(toList(" abc", " def "))
.listInteger(toList(123, 456))
.arrayText(toArray(" abc", " def "))
.arrayInteger(toArray(123, 456))
.setText(toSet(" abc", " def "))
.setInteger(toSet(123, 456))
.comment("空白がある"));
// アノテーションありのデータ作成
outSheet.add(new FormattedRecord()
.comment("空文字"));
outSheet.add(new FormattedRecord()
.listText(toList("abc"))
.listInteger(toList(123))
.arrayText(toArray("abc"))
.arrayInteger(toArray(123))
.setText(toSet("abc"))
.setInteger(toSet(123))
.comment("項目が1つ"));
outSheet.add(new FormattedRecord()
.listText(toList("abc", "def"))
.listInteger(toList(123, 456))
.arrayText(toArray("abc", "def"))
.arrayInteger(toArray(123, 456))
.setText(toSet("abc", "def"))
.setInteger(toSet(123, 456))
.comment("項目が2つ"));
outSheet.add(new FormattedRecord()
.listText(toList("", null, ""))
.listInteger(toList(0, null, null))
.arrayText(toArray("", null, ""))
.arrayInteger(toArray(0, null, null))
.setText(toSet("", null, ""))
.setInteger(toSet(0, null, null))
.comment("空の項目のみ"));
outSheet.add(new FormattedRecord()
.listText(toList("abc", "", "def"))
.listInteger(toList(123, null, 456))
.arrayText(toArray("abc", "", "def"))
.arrayInteger(toArray(123, null, 456))
.setText(toSet("abc", "", "def"))
.setInteger(toSet(123, null, 456))
.comment("空の項目がある"));
outSheet.add(new FormattedRecord()
.listText(toList(" abc", " def "))
.listInteger(toList(123, 456))
.arrayText(toArray(" abc", " def "))
.arrayInteger(toArray(123, 456))
.setText(toSet(" abc", " def "))
.setInteger(toSet(123, 456))
.comment("空白がある"));
// リスト型(任意の型)
Date date1 = toUtilDate(toTimestamp("2016-03-15 00:00:00.000"));
Date date2 = toUtilDate(toTimestamp("2016-03-16 00:00:00.000"));
Date nullDate = null;
outSheet.add(new CustomRecord()
.comment("空文字"));
outSheet.add(new CustomRecord()
.listDate(toList(date1))
.arrayDate(toArray(date1))
.setDate(toSet(date1))
.comment("項目が1つ"));
outSheet.add(new CustomRecord()
.listDate(toList(date1, date2))
.arrayDate(toArray(date1, date2))
.setDate(toSet(date1, date2))
.comment("項目が2つ"));
outSheet.add(new CustomRecord()
.listDate(toList(nullDate, nullDate, nullDate))
.arrayDate(toArray(nullDate, nullDate, nullDate))
.setDate(toSet(nullDate, nullDate, nullDate))
.comment("空の項目のみ"));
outSheet.add(new CustomRecord()
.listDate(toList(date1, nullDate, date2))
.arrayDate(toArray(date1, nullDate, date2))
.setDate(toSet(date1, nullDate, date2))
.comment("空の項目がある"));
outSheet.add(new CustomRecord()
.listDate(toList(date1, date2))
.arrayDate(toArray(date1, date2))
.setDate(toSet(date1, date2))
.comment("空白がある(※テスト不可)"));
// 数式のデータ
outSheet.add(new FormulaRecord().comment(";"));
outSheet.add(new FormulaRecord().comment("/dir1/index.html;/dir2/sample.html"));
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, "convert_collection.xlsx");
try(InputStream template = new FileInputStream("src/test/data/convert_template.xlsx");
OutputStream out = new FileOutputStream(outFile)) {
mapper.save(template, out, outSheet);
}
// 書き込んだファイルを読み込み値の検証を行う。
try(InputStream in = new FileInputStream(outFile)) {
SheetBindingErrors<CollectionSheet> errors = mapper.loadDetail(in, CollectionSheet.class);
CollectionSheet sheet = errors.getTarget();
if(sheet.simpleRecords != null) {
assertThat(sheet.simpleRecords, hasSize(outSheet.simpleRecords.size()));
for(int i=0; i < sheet.simpleRecords.size(); i++) {
assertRecord(sheet.simpleRecords.get(i), outSheet.simpleRecords.get(i), errors);
}
}
if(sheet.formattedRecords != null) {
assertThat(sheet.formattedRecords, hasSize(outSheet.formattedRecords.size()));
for(int i=0; i < sheet.formattedRecords.size(); i++) {
assertRecord(sheet.formattedRecords.get(i), outSheet.formattedRecords.get(i), errors);
}
}
if(sheet.customRecords != null) {
assertThat(sheet.customRecords, hasSize(outSheet.customRecords.size()));
for(int i=0; i < sheet.customRecords.size(); i++) {
assertRecord(sheet.customRecords.get(i), outSheet.customRecords.get(i), errors);
}
}
if(sheet.formulaRecords != null) {
assertThat(sheet.formulaRecords, hasSize(outSheet.formulaRecords.size()));
for(int i=0; i < sheet.formulaRecords.size(); i++) {
assertRecord(sheet.formulaRecords.get(i), outSheet.formulaRecords.get(i), errors);
}
}
}
}
/**
* 書き込んだレコードを検証するための
* @param inRecord
* @param outRecord
* @param errors
*/
private void assertRecord(final SimpleRecord inRecord, final SimpleRecord outRecord, final SheetBindingErrors<?> errors) {
System.out.printf("%s - assertRecord::%s no=%d, comment=%s\n",
this.getClass().getSimpleName(), inRecord.getClass().getSimpleName(), inRecord.no, inRecord.comment);
if(inRecord.no == 1) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(hasSize(0)));
assertThat(inRecord.listInteger, is(hasSize(0)));
assertThat(inRecord.arrayText, is(arrayWithSize(0)));
assertThat(inRecord.arrayInteger, is(arrayWithSize(0)));
assertThat(inRecord.setText, is(hasSize(0)));
assertThat(inRecord.setInteger, is(hasSize(0)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 4) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(hasSize(0)));
assertThat(inRecord.listInteger, is(contains(0)));
assertThat(inRecord.arrayText, is(arrayWithSize(0)));
assertThat(inRecord.arrayInteger, is(arrayContaining(0)));
assertThat(inRecord.setText, is(hasSize(0)));
assertThat(inRecord.setInteger, is(containsInAnyOrder(0)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 5) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(contains("abc", null, "def")));
assertThat(inRecord.listInteger, is(contains(123, 456)));
assertThat(inRecord.arrayText, is(arrayContaining("abc", null, "def")));
assertThat(inRecord.arrayInteger, is(arrayContaining(123, 456)));
assertThat(inRecord.setText, is(containsInAnyOrder("abc", null, "def")));
assertThat(inRecord.setInteger, is(containsInAnyOrder(123, 456)));
assertThat(inRecord.comment, is(outRecord.comment));
} else {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(outRecord.listText));
assertThat(inRecord.listInteger, is(outRecord.listInteger));
assertThat(inRecord.arrayText, is(outRecord.arrayText));
assertThat(inRecord.arrayInteger, is(outRecord.arrayInteger));
assertThat(inRecord.setText, is(outRecord.setText));
assertThat(inRecord.setInteger, is(outRecord.setInteger));
assertThat(inRecord.comment, is(outRecord.comment));
}
}
/**
* 書き込んだレコードを検証するための
* @param inRecord
* @param outRecord
* @param errors
*/
private void assertRecord(final FormattedRecord inRecord, final FormattedRecord outRecord, final SheetBindingErrors<?> errors) {
System.out.printf("%s - assertRecord::%s no=%d, comment=%s\n",
this.getClass().getSimpleName(), inRecord.getClass().getSimpleName(), inRecord.no, inRecord.comment);
if(inRecord.no == 1) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(hasSize(0)));
assertThat(inRecord.listInteger, is(contains(0)));
assertThat(inRecord.arrayText, is(arrayWithSize(0)));
assertThat(inRecord.arrayInteger, is(arrayContaining(0)));
assertThat(inRecord.setText, is(hasSize(0)));
assertThat(inRecord.setInteger, is(containsInAnyOrder(0)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 4) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(hasSize(0)));
assertThat(inRecord.listInteger, is(contains(0)));
assertThat(inRecord.arrayText, is(arrayWithSize(0)));
assertThat(inRecord.arrayInteger, is(arrayContaining(0)));
assertThat(inRecord.setText, is(hasSize(0)));
assertThat(inRecord.setInteger, is(containsInAnyOrder(0)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 5) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(contains("abc", "def")));
assertThat(inRecord.listInteger, is(contains(123, 456)));
assertThat(inRecord.arrayText, is(arrayContaining("abc", "def")));
assertThat(inRecord.arrayInteger, is(arrayContaining(123, 456)));
assertThat(inRecord.setText, is(containsInAnyOrder("abc", "def")));
assertThat(inRecord.setInteger, is(containsInAnyOrder(123, 456)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 6) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(contains("abc", "def")));
assertThat(inRecord.listInteger, is(contains(123, 456)));
assertThat(inRecord.arrayText, is(arrayContaining("abc", "def")));
assertThat(inRecord.arrayInteger, is(arrayContaining(123, 456)));
assertThat(inRecord.setText, is(containsInAnyOrder("abc", "def")));
assertThat(inRecord.setInteger, is(containsInAnyOrder(123, 456)));
assertThat(inRecord.comment, is(outRecord.comment));
} else {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listText, is(outRecord.listText));
assertThat(inRecord.listInteger, is(outRecord.listInteger));
assertThat(inRecord.arrayText, is(outRecord.arrayText));
assertThat(inRecord.arrayInteger, is(outRecord.arrayInteger));
assertThat(inRecord.setText, is(outRecord.setText));
assertThat(inRecord.setInteger, is(outRecord.setInteger));
assertThat(inRecord.comment, is(outRecord.comment));
}
}
/**
* 書き込んだレコードを検証するための
* @param inRecord
* @param outRecord
* @param errors
*/
private void assertRecord(final CustomRecord inRecord, final CustomRecord outRecord, final SheetBindingErrors<?> errors) {
System.out.printf("%s - assertRecord::%s no=%d, comment=%s\n",
this.getClass().getSimpleName(), inRecord.getClass().getSimpleName(), inRecord.no, inRecord.comment);
if(inRecord.no == 1) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listDate, is(hasSize(0)));
assertThat(inRecord.arrayDate, is(arrayWithSize(0)));
assertThat(inRecord.setDate, is(hasSize(0)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 4) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listDate, is(hasSize(0)));
assertThat(inRecord.arrayDate, is(arrayWithSize(0)));
assertThat(inRecord.setDate, is(hasSize(0)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 5) {
Date date1 = toUtilDate(toTimestamp("2016-03-15 00:00:00.000"));
Date date2 = toUtilDate(toTimestamp("2016-03-16 00:00:00.000"));
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listDate, contains(date1, date2));
assertThat(inRecord.arrayDate, arrayContaining(date1, date2));
assertThat(inRecord.setDate, contains(date1, date2));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 6) {
Date date1 = toUtilDate(toTimestamp("2016-03-15 00:00:00.000"));
Date date2 = toUtilDate(toTimestamp("2016-03-16 00:00:00.000"));
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listDate, contains(date1, date2));
assertThat(inRecord.arrayDate, arrayContaining(date1, date2));
assertThat(inRecord.setDate, contains(date1, date2));
assertThat(inRecord.comment, is(outRecord.comment));
} else {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listDate, is(outRecord.listDate));
assertThat(inRecord.arrayDate, is(outRecord.arrayDate));
assertThat(inRecord.setDate, is(outRecord.setDate));
assertThat(inRecord.comment, is(outRecord.comment));
}
}
/**
* 書き込んだレコードを検証するための
* @param inRecord
* @param outRecord
* @param errors
*/
private void assertRecord(final FormulaRecord inRecord, final FormulaRecord outRecord, final SheetBindingErrors<?> errors) {
System.out.printf("%s - assertRecord::%s no=%d, comment=%s\n",
this.getClass().getSimpleName(), inRecord.getClass().getSimpleName(), inRecord.no, inRecord.comment);
if(inRecord.no == 1) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listStr, is(hasSize(0)));
assertThat(inRecord.arrayStr, is(arrayWithSize(0)));
assertThat(inRecord.setStr, is(hasSize(0)));
assertThat(inRecord.comment, is(outRecord.comment));
} else if(inRecord.no == 2) {
assertThat(inRecord.no, is(outRecord.no));
assertThat(inRecord.listStr, is(contains("/dir1/index.html", "/dir2/sample.html")));
assertThat(inRecord.arrayStr, is(arrayContaining("/dir1/index.html", "/dir2/sample.html")));
assertThat(inRecord.setStr, is(contains("/dir1/index.html", "/dir2/sample.html")));
assertThat(inRecord.comment, is(outRecord.comment));
}
}
@XlsSheet(name="リスト型")
private static class CollectionSheet {
@XlsOrder(1)
@XlsHorizontalRecords(tableLabel="リスト型(アノテーションなし)", terminal=RecordTerminal.Border)
@XlsRecordOption(overOperation=OverOperation.Insert)
private List<SimpleRecord> simpleRecords;
@XlsOrder(2)
@XlsHorizontalRecords(tableLabel="リスト型(初期値、書式)", terminal=RecordTerminal.Border)
@XlsRecordOption(overOperation=OverOperation.Insert)
private List<FormattedRecord> formattedRecords;
@XlsOrder(3)
@XlsHorizontalRecords(tableLabel="リスト型(任意の型)", terminal=RecordTerminal.Border)
@XlsRecordOption(overOperation=OverOperation.Insert)
private List<CustomRecord> customRecords;
@XlsOrder(4)
@XlsHorizontalRecords(tableLabel="リスト型(数式)", terminal=RecordTerminal.Border)
@XlsRecordOption(overOperation=OverOperation.Insert)
private List<FormulaRecord> formulaRecords;
/**
* レコードを追加する。noを自動的に付与する。
* @param record
* @return
*/
public CollectionSheet add(SimpleRecord record) {
if(simpleRecords == null) {
this.simpleRecords = new ArrayList<>();
}
this.simpleRecords.add(record);
record.no(simpleRecords.size());
return this;
}
/**
* レコードを追加する。noを自動的に付与する。
* @param record
* @return
*/
public CollectionSheet add(FormattedRecord record) {
if(formattedRecords == null) {
this.formattedRecords = new ArrayList<>();
}
this.formattedRecords.add(record);
record.no(formattedRecords.size());
return this;
}
/**
* レコードを追加する。noを自動的に付与する。
* @param record
* @return
*/
public CollectionSheet add(CustomRecord record) {
if(customRecords == null) {
this.customRecords = new ArrayList<>();
}
this.customRecords.add(record);
record.no(customRecords.size());
return this;
}
/**
* レコードを追加する。noを自動的に付与する。
* @param record
* @return
*/
public CollectionSheet add(FormulaRecord record) {
if(formulaRecords == null) {
this.formulaRecords = new ArrayList<>();
}
this.formulaRecords.add(record);
record.no(formulaRecords.size());
return this;
}
}
/**
* リスト型 - アノテーションなし。
*
*/
private static class SimpleRecord {
private Map<String, Point> positions;
private Map<String, String> labels;
@XlsColumn(columnName="No.")
private int no;
@XlsColumn(columnName="List(文字列)")
private List<String> listText;
@XlsColumn(columnName="List(数値)")
private List<Integer> listInteger;
@XlsColumn(columnName="Array(文字列)")
private String[] arrayText;
@XlsColumn(columnName="Array(数値)")
private Integer[] arrayInteger;
@XlsColumn(columnName="Set(文字列)")
private Set<String> setText;
@XlsColumn(columnName="Set(数値)")
private Set<Integer> setInteger;
@XlsColumn(columnName="備考")
private String comment;
@XlsIgnorable
public boolean isEmpty() {
return IsEmptyBuilder.reflectionIsEmpty(this, "positions", "labels", "no");
}
public SimpleRecord no(int no) {
this.no = no;
return this;
}
public SimpleRecord listText(List<String> listText) {
this.listText = listText;
return this;
}
public SimpleRecord listInteger(List<Integer> listInteger) {
this.listInteger = listInteger;
return this;
}
public SimpleRecord arrayText(String[] arrayText) {
this.arrayText = arrayText;
return this;
}
public SimpleRecord arrayInteger(Integer[] arrayInteger) {
this.arrayInteger = arrayInteger;
return this;
}
public SimpleRecord setText(Set<String> setText) {
this.setText = setText;
return this;
}
public SimpleRecord setInteger(Set<Integer> setInteger) {
this.setInteger = setInteger;
return this;
}
public SimpleRecord comment(String comment) {
this.comment = comment;
return this;
}
}
private static class FormattedRecord {
private Map<String, Point> positions;
private Map<String, String> labels;
@XlsColumn(columnName="No.")
private int no;
@XlsTrim
@XlsArrayConverter(separator="\n", ignoreEmptyElement=true)
@XlsColumn(columnName="List(文字列)")
private List<String> listText;
@XlsDefaultValue("0")
@XlsTrim
@XlsArrayConverter(separator=";", ignoreEmptyElement=true)
@XlsColumn(columnName="List(数値)")
private List<Integer> listInteger;
@XlsTrim
@XlsArrayConverter(separator="\n", ignoreEmptyElement=true)
@XlsColumn(columnName="Array(文字列)")
private String[] arrayText;
@XlsDefaultValue("0")
@XlsTrim
@XlsArrayConverter(separator=";", ignoreEmptyElement=true)
@XlsColumn(columnName="Array(数値)")
private Integer[] arrayInteger;
@XlsTrim
@XlsArrayConverter(separator="\n", ignoreEmptyElement=true)
@XlsColumn(columnName="Set(文字列)")
private Set<String> setText;
@XlsDefaultValue("0")
@XlsTrim
@XlsArrayConverter(separator=";", ignoreEmptyElement=true)
@XlsColumn(columnName="Set(数値)")
private Set<Integer> setInteger;
@XlsColumn(columnName="備考")
private String comment;
@XlsIgnorable
public boolean isEmpty() {
return IsEmptyBuilder.reflectionIsEmpty(this, "positions", "labels", "no");
}
public FormattedRecord no(int no) {
this.no = no;
return this;
}
public FormattedRecord listText(List<String> listText) {
this.listText = listText;
return this;
}
public FormattedRecord listInteger(List<Integer> listInteger) {
this.listInteger = listInteger;
return this;
}
public FormattedRecord arrayText(String[] arrayText) {
this.arrayText = arrayText;
return this;
}
public FormattedRecord arrayInteger(Integer[] arrayInteger) {
this.arrayInteger = arrayInteger;
return this;
}
public FormattedRecord setText(Set<String> setText) {
this.setText = setText;
return this;
}
public FormattedRecord setInteger(Set<Integer> setInteger) {
this.setInteger = setInteger;
return this;
}
public FormattedRecord comment(String comment) {
this.comment = comment;
return this;
}
}
private static class CustomRecord {
private Map<String, Point> positions;
private Map<String, String> labels;
@XlsColumn(columnName="No.")
private int no;
@XlsTrim
@XlsArrayConverter(separator="\n", ignoreEmptyElement=true, elementConverter=DateElementConverter.class)
@XlsColumn(columnName="List(Date型)")
private List<Date> listDate;
@XlsTrim
@XlsArrayConverter(separator=";", ignoreEmptyElement=true, elementConverter=DateElementConverter.class)
@XlsColumn(columnName="Array(Date型)")
private Date[] arrayDate;
@XlsTrim
@XlsArrayConverter(separator=",", ignoreEmptyElement=true, elementConverter=DateElementConverter.class)
@XlsColumn(columnName="Set(Date型)")
private Set<Date> setDate;
@XlsColumn(columnName="備考")
private String comment;
@XlsIgnorable
public boolean isEmpty() {
return IsEmptyBuilder.reflectionIsEmpty(this, "positions", "labels", "no");
}
public CustomRecord no(int no) {
this.no = no;
return this;
}
public CustomRecord listDate(List<Date> listDate) {
this.listDate = listDate;
return this;
}
public CustomRecord arrayDate(Date[] arrayDate) {
this.arrayDate = arrayDate;
return this;
}
public CustomRecord setDate(Set<Date> setDate) {
this.setDate = setDate;
return this;
}
public CustomRecord comment(String comment) {
this.comment = comment;
return this;
}
private static class DateElementConverter implements ElementConverter<Date> {
@Override
public Date convertToObject(final String text, final Class<Date> targetClass) throws ConversionException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
try {
return formatter.parse(text);
} catch (ParseException e) {
String message = String.format("fail parse '%s' to java.util.Date", text);
throw new ConversionException(message, e, targetClass);
}
}
@Override
public String convertToString(final Date value) {
if(value == null) {
return "";
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
return formatter.format(value);
}
}
}
private static class FormulaRecord {
private Map<String, Point> positions;
private Map<String, String> labels;
@XlsColumn(columnName="No.")
private int no;
@XlsTrim
@XlsArrayConverter(separator=";", ignoreEmptyElement=true)
@XlsColumn(columnName="List(数式)")
@XlsFormula("E{rowNumber}")
private List<String> listStr;
@XlsTrim
@XlsArrayConverter(separator=";", ignoreEmptyElement=true)
@XlsColumn(columnName="Array(数式)")
@XlsFormula("E{rowNumber}")
private String[] arrayStr;
@XlsTrim
@XlsArrayConverter(separator=";", ignoreEmptyElement=true)
@XlsColumn(columnName="Set(数式)")
@XlsFormula("E{rowNumber}")
private Set<String> setStr;
@XlsColumn(columnName="備考")
private String comment;
@XlsIgnorable
public boolean isEmpty() {
return IsEmptyBuilder.reflectionIsEmpty(this, "positions", "labels", "no");
}
public FormulaRecord no(int no) {
this.no = no;
return this;
}
public FormulaRecord listStre(List<String> listStr) {
this.listStr = listStr;
return this;
}
public FormulaRecord arrayStr(String[] arrayStr) {
this.arrayStr = arrayStr;
return this;
}
public FormulaRecord setStr(Set<String> setStr) {
this.setStr = setStr;
return this;
}
public FormulaRecord comment(String comment) {
this.comment = comment;
return this;
}
}
}
|
Markdown | UTF-8 | 1,261 | 3.1875 | 3 | [] | no_license | # Host_Url-Anomaly-Detection-with-Word-Embedding
This project explores the dataset in the internal system, aiming to accurately spot the potential host_url anomaly with the help
of word embeddings.
# Data
Fetched from elasticsearch with the assigned score to indicate its severity level. Complied in a csv file with roughly 80000 samples
and a bunch of features. The purpose of this project is to conduct a NLP study on detecting anomaly on the host url combination.
# Method
Pre-process the dataset to get the root from text information and standardized the expression. Also created a word dictionary to
assign index to each word in the dataset. Generate a 28000*28000 matrix co-occurrence matrix with row being the word and the blank being
the number of two occurring in the given windows size, which, in this case, equals 4. Transform the giant co-occurrence matrx in 2-D
matrix using truncatedSVD method for faster computation and ease the memory burden.
# Output
Produced a 2-D plot with a test case in which most of them are threat and two others are benign. Since most threats are clusterd together,
it is guaranteed that the word embeddings is capable of detecting the anomaly in the text by using "significant" term to pre-screen
the dataset
|
Java | UTF-8 | 455 | 2.671875 | 3 | [] | no_license | package sample.utils;
import javafx.scene.paint.Color;
import java.util.concurrent.ThreadLocalRandom;
public class ColorSelector {
private static Color[] colors = {
Color.BLUE, Color.BROWN, Color.GREEN, Color.GREY, Color.ORANGE, Color.PINK, Color.PURPLE, Color.RED, Color.WHITE,
Color.YELLOW};
public static Color select() {
int randomNum = ThreadLocalRandom.current().nextInt(0, 10);
return colors[randomNum];
}
}
|
C++ | UTF-8 | 1,296 | 3.140625 | 3 | [] | no_license | /// Emil Hedemalm (base from Fredrik Larsson)
/// 2015-05-20
#include <iostream>
#include "Windows.h"
int main (int argc, char *argv[])
{
int mode = 0;
enum{
BASIC,
BASIC_GL,
MULTI_GL,
MULTI_GL_THREADED
};
for (int i = 0; i < argc; ++i)
{
char * arg = argv[i];
std::cout<<"\nArg "<<i<<": "<<argv[i];
if (i == 1)
{
if (strcmp(arg, "basic") == 0)
mode = 0;
if (strcmp(arg, "gl") == 0)
mode = BASIC_GL;
if (strcmp(arg, "multi-gl") == 0)
mode = MULTI_GL;
if (strcmp(arg, "multi-gl-threaded") == 0)
mode = MULTI_GL_THREADED;
}
}
switch(mode)
{
case BASIC:
std::cout<<"\nCreating basic window";
BasicWindow();
break;
case BASIC_GL:
SingleGLWindow();
break;
case MULTI_GL:
MultiGLWindows();
break;
case MULTI_GL_THREADED:
SeparateRenderThreadMultiGLWindows();
break;
default:
std::cout<<"\nBad mode. Available modes: basic, gl, multi-gl, multi-gl-threaded";
}
std::cout<<"\nExiting";
return 0;
}
|
Markdown | UTF-8 | 3,138 | 3.03125 | 3 | [] | no_license | # TP 102: How to Use Git and GitHub
Git and GitHub are commonly used tools in open source practice. Whether you are considering contribute to an open source project or start your own open source project. This course includes a collection of Git and GitHub related learning materials and will guide you through everything you need to start contributing, from managing notifications to merging pull requests.
***Important note:*** ***How to Use Git and GitHub is in an alpha
state.*** Its scope is limited. If you are taking it now you
are brave, but you are also an early tester and your feedback is greatly
appreciated. You are encouraged to reporting bugs, suggest changes, update the contents, etc. **See [Contributing Guide](../CONTRIBUTING.md) for more details.**
## Who this is for
New GitHub users, users new to Git
## What you will learn?
* what GitHub is
* how to use GitHub
* how to create a branch and a commit
* how to review a pull request
* how to manage merge conflicts
* how to communicate using Markdown
### Prerequisites:
None. This course is a great introduction for your first day on GitHub.
## Course details
### Chapter 1: Introduction to GitHub
**Learning Material(s):**
* [Introduction to GitHub](https://lab.github.com/githubtraining/introduction-to-github), an open source course created by [The GitHub Training Team](https://lab.github.com/githubtraining)
**Suggested Assignments: **
* Finish the lab.
### Chapter 2: Reviewing pull requests
**Learning Material(s):**
* [Reviewing pull requests](https://lab.github.com/githubtraining/reviewing-pull-requests), an open source course created by [The GitHub Training Team](https://lab.github.com/githubtraining)
**Suggested Assignments:**
* Finish the lab.
### Chapter 3: Managing merge conflicts
**Learning Material(s):**
* [Managing merge conflicts](https://lab.github.com/githubtraining/managing-merge-conflicts), an open source course created by [The GitHub Training Team](https://lab.github.com/githubtraining)
**Suggested Assignments:**
* Finish the lab.
### Chapter 4: Communicating using Markdown
**Learning Material(s):**
* [Communicating using Markdown](https://lab.github.com/githubtraining/communicating-using-markdown), an open source course created by [The GitHub Training Team](https://lab.github.com/githubtraining)
**Suggested Assignments:**
* Finish the lab.
### Chapter 5: Git Handbook
* [Git Handbook](https://guides.github.com/introduction/git-handbook/), the official learning material provided by [GitHub Guides](https://guides.github.com/)
**Suggested Assignments:**
No assignments, the git skill will be tested all the time you participate in an open source project.
## Users who took this course also took
* [TP 101: Introduction to Open Source Software](tp101-intro-to-oss.md)
* [TP 103: Build A Welcoming Open Source Community](tp103-open-source-community.md)
## Acknowledgement
Special Thanks to:
* `Producer Wen`, `Qinyao Yang`, and `Jason Zhangg`for testing this course and updating the materials.
* [The GitHub Training Team](https://lab.github.com/githubtraining) for creating open source courses above.
|
Python | UTF-8 | 1,725 | 3.015625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from six.moves import range
import numpy as np
__all__ = [
'effective_sample_size',
'effective_sample_size_1d',
]
def effective_sample_size_1d(samples):
"""
Compute the effective sample size of a chain of scalar samples.
:param samples: A 1-D numpy array. The chain of samples.
:return: A float. The effective sample size.
"""
n = samples.shape[0]
mu_hat = np.mean(samples)
var = np.var(samples) * n / (n - 1)
var_plus = var * (n - 1) / n
def auto_covariance(lag):
return np.mean((samples[:n - lag] - mu_hat) * (samples[lag:] - mu_hat))
sum_rho = 0
for t in range(0, n):
rho = 1 - (var - auto_covariance(t)) / var_plus
if rho < 0:
break
sum_rho += rho
ess = n / (1 + 2 * sum_rho)
return ess
def effective_sample_size(samples, burn_in=100):
"""
Compute the effective sample size of a chain of vector samples, using the
algorithm in Stan. Users should flatten their samples as vectors if not so.
:param samples: A 2-D numpy array of shape ``(M, D)``, where ``M`` is the
number of samples, and ``D`` is the number of dimensions of each
sample.
:param burn_in: The number of discarded samples.
:return: A 1-D numpy array. The effective sample size.
"""
current_ess = np.inf
esses = []
for d in range(samples.shape[1]):
ess = effective_sample_size_1d(np.squeeze(samples[burn_in:, d]))
assert ess >= 0
if ess > 0:
current_ess = min(current_ess, ess)
esses.append(ess)
return current_ess
|
Python | UTF-8 | 2,132 | 3.546875 | 4 | [] | no_license | from sqlalchemy import create_engine #object relation mapping(store object in relational db)
from sqlalchemy.ext.declarative import declarative_base;
from sqlalchemy import Column, Integer, String;
from sqlalchemy.orm import sessionmaker;
Base = declarative_base() #global var, base class provided by SqlAlchemy to ORM compatiable/capable
class Customer(Base): #Base here is to make my class ORM compatiable/capable.
#constructor
def __init__(self, name, address, creditCardNum, licensePlate):
self.name = name
self.address = address
self.creditCardNum = creditCardNum
self.licensePlate = licensePlate
#name of the table, for objects of this to be stored in.
__tablename__ = "customer"
#column defining in db
id = Column(Integer, primary_key = True); #unique identifier of table
name = Column(String);
address = Column(String);
creditCardNum = Column(Integer);
licensePlate = Column(String);
def __repr__(self): #printable representational of the object
return "<customer(name= {0}, address= {1}, creditcard Number= {2}, license Plate= {3} )>".format(self.name, self.address, self.creditCardNum, self.licensePlate);
def main():
engine = create_engine('sqlite:///:memory:', echo=False) # uses system memory, display sql on screen false = no.
Base.metadata.create_all(engine); #knows what engine to use to store objects.
Session = sessionmaker(bind=engine); #creates session opens connection.
session = Session(); #instantiates object from Session
#add content to the database.
session.add_all([
Customer('Boy Guy', '2209 Fresh Road', 987654321123, 'BLAH56'),
Customer('Curious George', '1 Tree Top Lane', 888888888888, 'NANNAS'),
Customer("Frank White", "555 Place Lane Dr.", 4444543223547894, "L8ER5") ])
session.commit(); #commits the info
for row in session.query(Customer).all(): #Loops through the db.
print(row.name, ", ", row.address); #prints out the name and address of customers
main()
|
Shell | UTF-8 | 93 | 2.8125 | 3 | [] | no_license | #!/bin/bash
for c in $@
{
make -C $c $FOCP_SECTION
if [ "$?" != "0" ]
then
break
fi
}
|
Java | UTF-8 | 228 | 3.015625 | 3 | [] | no_license | package com.company;
public class Storage {
public double availableCash(double cash, double price) {
System.out.println("Your available balance is £" + (cash - price) + ".");
return cash - price;
}
}
|
Markdown | UTF-8 | 3,261 | 2.859375 | 3 | [] | no_license | # ID3 Decision Tree
This is an implementation of ID3 decision tree algorithm.
## Structure
```ID3/dtree.py``` is the main file to be executed
```ID3/DT_Model.py``` is the model class file that builds a ID3 decision tree
## Usage
```shell
python3 ID3/dtree.py [data_folder_path] use_full_sample max_depth use_gain_ratio
```
where ```use_full_sample``` takes value in {0, 1}, with 0 meaning do a k-fold cross validation (defaulted to 5) and 1 meaning train the model on all datapoints.
```max_depth``` takes value in non-negative integers with 0 representing "grow a full tree".
```use_gain_ratio``` takes value in {0, 1}
# Naive Bayes Net
The first part of `stats_models` is the implementation of the naive Bayes algorithm.
## Structure
```stats_models/nbayes.py``` is the main file to be executed to run naive Bayes algorithm
## Usage
```shell
python3 stats_models/nbayes.py [data_folder_path] use_full_sample max_depth use_gain_ratio
```
```use_full_sample``` takes value in {0, 1}, with 0 meaning do a k-fold cross validation (defaulted to 5) and 1 meaning train the model on all datapoints.
```n_bins``` takes value in non-negative integers greater than 2.
```m_estimate``` takes value in {0, 1}.
# Logistic Regression
The second part of `stats_models` is the implementation of logistic regression algorithm.
## Structure
```stats_models/logreg.py``` is the main file to be executed to run logistic regression.
## Usage
```shell
python3 stats_models/logreg.py [data_folder_path] use_full_sample lambda
```
```use_full_sample``` takes value in {0, 1}, with 0 meaning do a k-fold cross validation (defaulted to 5) and 1 meaning train the model on all datapoints.
```lambda``` is a non-negative real number that sets value for required constant lambda.
# Bagging
The first part of `ensemble_models` is the implementation of bagging algorithm.
## Structure
```ensemble_models/bag.py``` is the main file to be executed to run bagging algorithm
## Usage
```shell
python3 ensemble_models/bag.py [data_folder_path] use_full_sample learning_algo n_iter
```
```use_full_sample``` takes value in {0, 1}, with 0 meaning do a k-fold cross validation (defaulted to 5) and 1 meaning train the model on all datapoints.
```learning_algo``` takes a string among "dtree", "nbayes" and "logreg", representing creating an ensemble of which learning algorithm.
```n_iter``` takes a positive integer, representing the number of iterations to perform bagging.
# Boosting
The second part of `ensemble_models` is the implementation of boosting algorithm.
## Structure
```ensemble_models/boost.py``` is the main file to be executed to run boosting algorithm
## Usage
```shell
python3 ensemble_models/boost.py [data_folder_path] use_full_sample learning_algo n_iter
```
```use_full_sample``` takes value in {0, 1}, with 0 meaning do a k-fold cross validation (defaulted to 5) and 1 meaning train the model on all datapoints.
```learning_algo``` takes a string among "dtree", "nbayes" and "logreg", representing creating an ensemble of which learning algorithm.
```n_iter``` takes a positive integer, representing the number of iterations to perform boosting. |
JavaScript | UTF-8 | 2,339 | 3.296875 | 3 | [] | no_license | // var salary = document.getElementById("salary").value;
// let salaryContent = Number(salary);
// console.log(salary);
function CalcDeductions() {
alert ("Hello we are in the Quebec tax calculator");
let salary1 = document.getElementById("salary").value;
let salary = parseInt(salary1);
if (salary>=42705 && salary<85405) {
deductions = salary*.2;
console.log(deductions);
document.getElementById("deductions").innerHTML = deductions +" "+ "CAD";
addDeductions = 0;
addDeductions2 = 0;
total = salary - deductions-addDeductions-addDeductions2;
document.getElementById("netSalary").innerHTML = total + " "+"CAD";
}
// else if (salary==85405 && salary==103915) {
// deductions = salary*.24;
// console.log(deductions);
// document.getElementById("deductions").innerHTML = deductions +" "+ "CAD";
// addDeductions = 0;
// addDeductions2 = 0;
// }
else if (salary>=85405 && salary<103915) {
deductions = 85405*.2;
addDeductions = (salary-85405)*.24;
document.getElementById("deductions").innerHTML = deductions +" "+ "CAD";
document.getElementById("addDeductions").innerHTML = "After 85405 CAD: " + addDeductions +" "+ "CAD";
addDeductions2 = 0;
total = salary - deductions-addDeductions-addDeductions2;
document.getElementById("netSalary").innerHTML = total + " "+"CAD";
}
else if (salary>=103915) {
deductions = 85405*.2;
addDeductions = (salary-85405)*.24;
document.getElementById("addDeductions").innerHTML = "After 85405 CAD: " + addDeductions +" "+ "CAD";
addDeductions2 = (salary-103915)*.2575;
document.getElementById("deductions").innerHTML = deductions +" "+ "CAD";
document.getElementById("addDeductions2").innerHTML ="After 103915 CAD: "+ addDeductions2 +" "+ "CAD";
console.log(addDeductions2);
total = salary - deductions-addDeductions-addDeductions2;
document.getElementById("netSalary").innerHTML = total + " "+"CAD";
}
else if (salary<42705) {
window.alert("You should work BETTER, Dude!!!!");
deductionsLess = salary*.15;
total = salary - deductionsLess;
document.getElementById("deductionsLess").innerHTML = total + " "+"CAD";
}
// total = salary - deductions-addDeductions+addDeductions2;
// document.getElementById("netSalary").innerHTML = total + " "+"CAD";
console.log(total);
}
function ReloadPage(){
location.reload();
}
|
Java | UTF-8 | 850 | 2.3125 | 2 | [] | no_license | package com.byted.chapter5;
import com.google.gson.annotations.SerializedName;
import java.util.List;
class ArticleResponse {
@SerializedName("errorCode")
public int errorCode;
@SerializedName("errorMsg")
public String errorMsg;
@SerializedName("data")
List<Article> articles;
public static class Article {
// id: 409,
// name: "..",
// order: 190001
@SerializedName("id")
public int id;
@SerializedName("name")
public String name;
@SerializedName("order")
public int order;
@Override
public String toString() {
return "Article{" +
"id=" + id +
", name='" + name + '\'' +
", order=" + order +
'}';
}
}
}
|
Shell | UTF-8 | 2,525 | 3.953125 | 4 | [] | no_license | #!/bin/sh
#
# Kernel NET hotplug params include:
#
# ACTION=%s [register or unregister]
# INTERFACE=%s
. /lib/rc-scripts/functions.network
mesg() {
/usr/bin/logger -t $(basename $0)"[$$]" "$@"
}
debug_mesg() {
:
}
# returns true if device is either wireless, usbnet or is named eth* and supports ethtool
ethernet_check() {
[ -d /sys/class/net/$1/wireless/ ] && return 0
[[ "$1" == bnep* ]] && return 0
# eagle-usb/firewire create a fake ethX interface
if [ -x /usr/sbin/ethtool ] && ! /usr/sbin/ethtool $1 > /dev/null 2>&1;
then return 1;
fi
return 0;
}
if [ "$INTERFACE" = "" ]; then
mesg Bad NET invocation: \$INTERFACE is not set
exit 1
fi
export IN_HOTPLUG=1
case $ACTION in
add|register)
case $INTERFACE in
# interfaces that are registered after being "up" (?)
ppp*|ippp*|isdn*|plip*|lo*|irda*|dummy*|ipsec*|tun*|tap*)
debug_mesg assuming $INTERFACE is already up
exit 0
;;
# interfaces that are registered then brought up
*)
# NOTE: network configuration relies on administered state,
# we can't do much here without distro-specific knowledge
# such as whether/how to invoke DHCP, set up bridging, etc.
# conform to network service (AUTOMATIC_IFCFG)
[ -r /etc/sysconfig/network ] && . /etc/sysconfig/network
# don't do anything for non ethernet devices
ethernet_check $INTERFACE || exit 0;
# automatically create an interface file
CFG=/etc/sysconfig/interfaces/ifcfg-$INTERFACE
if [ "$AUTOMATIC_IFCFG" != no -a ! -r $CFG ]; then
debug_mesg creating config file for $INTERFACE
cat > $CFG <<EOF
DEVICE=$INTERFACE
BOOTPROTO=dhcp
ONBOOT=no
EOF
fi
if [ ! -f /var/lock/subsys/network ] || [ ! -r $CFG ]; then
# Don't do anything if the network is stopped or interface isn't configured
exit 0
fi
if [ -x /sbin/ifup ]; then
debug_mesg invoke ifup $INTERFACE
exec /sbin/ifup $INTERFACE hotplug
fi
;;
esac
mesg $1 $ACTION event not handled
;;
remove|unregister)
case $INTERFACE in
# interfaces that are unregistered after being "down" (?)
ppp*|ippp*|isdn*|plip*|lo*|irda*|dummy*|ipsec*|tun*|tap*)
debug_mesg assuming $INTERFACE is already down
exit 0
;;
*)
if [ -x /sbin/ifdown ]; then
debug_mesg invoke ifdown $INTERFACE
exec /sbin/ifdown $INTERFACE hotplug
fi
;;
esac
mesg $1 $ACTION event not handled
;;
*)
debug_mesg NET $ACTION event for $INTERFACE not supported
exit 1 ;;
esac
|
Java | UTF-8 | 1,601 | 2.5625 | 3 | [] | no_license | package com.detection.UtilLs;
import com.sun.imageio.plugins.common.InputStreamAdapter;
import com.sun.javafx.image.IntPixelGetter;
import javafx.util.Pair;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;
public class readPropertyFile {
public static Properties propertiesFactory(String filename)
{
try {
Properties properties = new Properties();
InputStreamReader ir = new InputStreamReader(new FileInputStream(new File(filename)));
properties.load(ir);
return properties;
}catch (Throwable e)
{
return null;
}
}
public static HashMap<String, String> propertiesFile2HashMap(String filename)
{
HashMap<String ,String> result = new HashMap<>();
Properties properties = propertiesFactory(filename);
if(properties != null)
{
for (String key : properties.stringPropertyNames())
{
String value = properties.getProperty(key);
result.put(key, value);
}
}
return result;
}
public static HashMap<String, String> malware2Name = propertiesFile2HashMap("./malware.properties");
public static void main(String[] args) {
Properties properties = propertiesFactory("./malware.properties");
for(String key: malware2Name.keySet())
{
String value = malware2Name.get(key);
System.out.println(key +" " + value);
}
}
}
|
PHP | UTF-8 | 98,756 | 2.53125 | 3 | [] | no_license | <?php
// ************************************************************************************//
// * WoltLab Burning Board 2
// ************************************************************************************//
// * Copyright (c) 2001-2004 WoltLab GmbH
// * Web http://www.woltlab.de/
// * License http://www.woltlab.de/products/burning_board/license_en.php
// * http://www.woltlab.de/products/burning_board/license.php
// ************************************************************************************//
// * WoltLab Burning Board 2 is NOT free software.
// * You may not redistribute this package or any of it's files.
// ************************************************************************************//
// * $Date: 2005-05-02 15:31:29 +0200 (Mon, 02 May 2005) $
// * $Author: Burntime $
// * $Rev: 1601 $
// ************************************************************************************//
/**
* use stripslashes on all array elements
*
* @param array array to which stripslashes should be applied
* @return array new array
*/
function stripslashes_array(&$array) {
reset($array);
while (list($key, $val) = each($array)) {
if (is_string($val)) $array[$key] = stripslashes($val);
elseif (is_array($val)) $array[$key] = stripslashes_array($val);
}
return $array;
}
/**
* use wbb_trim on all array elements
*
* @param array array to which wbb_trim should be applied
* @return array new array
*/
function trim_array(&$array) {
reset($array);
while (list($key, $val) = each($array)) {
if (is_array($val)) $array[$key] = trim_array($val);
elseif (is_string($val)) $array[$key] = wbb_trim($val);
}
return $array;
}
/**
* use intval on all array elements
*
* @param array array to which intval should be applied
* @return array new array
*/
function intval_array(&$array) {
reset($array);
while (list($key, $val) = each($array)) {
if (is_array($val)) $array[$key] = intval_array($val);
else $array[$key] = intval($val);
}
return $array;
}
/**
* setcookie function
*
* @param string name
* @param strinv value
* @param integer time
*
* @return void
*/
function bbcookie($name, $value, $time) {
global $cookiepath, $cookiedomain, $cookieprefix, $_SERVER;
if ($_SERVER['SERVER_PORT'] == '443') $ssl = 1;
else $ssl = 0;
setcookie($cookieprefix.$name, $value, $time, $cookiepath, $cookiedomain, $ssl);
}
/**
* sendmail function
*
* @param string email
* @param string subject
* @param string text
* @param string sender
* @param string other
*
* @return boolean mail
*/
function mailer($email, $subject, $text, $sender = '', $other = '') {
global $frommail, $master_board_name, $smtp, $socket, $mailer_use_f_param;
if ($socket && function_exists('fsockopen')) {
global $mail_container;
if (!isset($mail_container)) $mail_container = &new smtp_socket;
return $mail_container->mail($email, $subject, $text, $sender, $other);
}
if ($smtp && ini_get('SMTP') != $smtp) {
@ini_set('SMTP', $smtp);
$smtp = '';
}
if ($mailer_use_f_param) return @wbb_mail($email, $subject, $text, "From: ".($sender ? $sender : $frommail).$other, "-f $frommail");
else return @wbb_mail($email, $subject, $text, "From: ".($sender ? $sender : $frommail).$other);
}
/**
* generate an a href tag
*
* @param string url
* @param string name
* @param string target
*
* @return string a tag
*/
function makehreftag($url, $name, $target = '') {
return "<a href=\"".$url."\"".(($target != '') ? (" target=\"".$target."\"") : ("")).">".$name."</a>";
}
/**
* generate a img tag
*
* @param string path
* @param string alt
* @param integer usehtmlconverter
*
* @return string img tag
*/
function makeimgtag($path, $alt = '', $usehtmlconverter = 1) {
if ($alt != '' && $usehtmlconverter == 1) $alt = htmlconverter($alt);
$path = replaceImagefolder($path);
return "<img src=\"".$path."\" border=\"0\" alt=\"".$alt."\" title=\"".$alt."\" />";
}
/**
* format an unix timestamp
*
* @param string timeformat
* @param integer timestamp
* @param integer replacetoday
*
* @return string date
*/
function formatdate($timeformat, $timestamp, $replacetoday = 0) {
global $wbbuserdata, $lang;
$summertime = date('I', $timestamp) * 3600;
$timestamp += 3600 * intval($wbbuserdata['timezoneoffset']) + $summertime;
if ($replacetoday == 1) {
if (gmdate('Ymd', $timestamp) == gmdate('Ymd', time() + 3600 * intval($wbbuserdata['timezoneoffset']) + $summertime)) {
return $lang->get('LANG_GLOBAL_TODAY');
}
elseif (gmdate('Ymd', $timestamp) == gmdate('Ymd', time() - 86400 + 3600 * intval($wbbuserdata['timezoneoffset']) + $summertime)) {
return $lang->get('LANG_GLOBAL_YESTERDAY');
}
}
return htmlconverter(gmdate($timeformat, $timestamp));
}
/**
* get the subboardlist fo a boardid
*
* @param integer boardid
*
* @return string subboardlist
*/
function getSubboards($boardid) {
global $boardcache, $session, $SID_ARG_1ST, $SID_ARG_2ND, $SID_ARG_2ND_UN, $tpl, $permissioncache, $lang, $wbbuserdata;
if (!isset($boardcache[$boardid])) return;
$subboardbit = '';
while (list($key1, $val1) = each($boardcache[$boardid])) {
while (list($key2, $boards) = each($val1)) {
if (!isset($permissioncache[$boards['boardid']]['can_view_board']) || $permissioncache[$boards['boardid']]['can_view_board'] == -1) $permissioncache[$boards['boardid']]['can_view_board'] = $wbbuserdata['can_view_board'];
if ($boards['invisible'] == 2 || !$permissioncache[$boards['boardid']]['can_view_board']) continue;
$boards['title'] = getlangvar($boards['title'], $lang);
eval("\$subboardbit .= \"".$tpl->get("index_subboardbit")."\";");
$subboardbit .= getSubboards($boards['boardid']);
}
}
return $subboardbit;
}
/**
* make the boardlist for indexpage
*
* @param integer boardid
* @param integer depth
*
* @return string boardbit
*/
function makeboardbit($boardid, $depth = 1) {
global $db, $style, $lang, $n, $tpl, $boardcache, $boardvisit, $visitcache, $permissioncache, $modcache, $wbbuserdata, $session, $hidecats, $index_depth, $show_subboards, $showlastposttitle, $dateformat, $timeformat, $showuseronlineinboard, $filename, $temp_boardid, $hide_modcell, $SID_ARG_1ST, $SID_ARG_2ND, $SID_ARG_2ND_UN;
if (!isset($boardcache[$boardid])) return;
reset($boardcache[$boardid]);
$boardbit = '';
while (list($key1, $val1) = each($boardcache[$boardid])) {
while (list($key2, $boards) = each($val1)) {
if (!isset($permissioncache[$boards['boardid']]['can_view_board']) || $permissioncache[$boards['boardid']]['can_view_board'] == -1) $permissioncache[$boards['boardid']]['can_view_board'] = $wbbuserdata['can_view_board'];
if (!isset($permissioncache[$boards['boardid']]['can_enter_board']) || $permissioncache[$boards['boardid']]['can_enter_board'] == -1) $permissioncache[$boards['boardid']]['can_enter_board'] = $wbbuserdata['can_enter_board'];
if ($boards['invisible'] == 2 || !$permissioncache[$boards['boardid']]['can_view_board']) continue;
$boards['title'] = getlangvar($boards['title'], $lang);
$boards['description'] = getlangvar($boards['description'], $lang, 0);
$subboardbit = '';
$subboards = '';
if ($show_subboards == 1 && (($boards['isboard'] == 1 && $depth == $index_depth) || (isset($hidecats[$boards['boardid']]) && $hidecats[$boards['boardid']] == 1) || ($depth == $index_depth && !isset($hidecats[$boards['boardid']])))) {
$subboardbit = getSubboards($boards['boardid']);
if ($subboardbit) $subboardbit = wbb_substr($subboardbit, 0, -2);
}
if ($wbbuserdata['lastvisit'] > $boards['lastposttime'] || $boards['lastvisit'] > $boards['lastposttime']) $onoff = 'off';
else {
$onoff = 'off';
$tempids = explode(',', "$boards[boardid],$boards[childlist]");
$tempids_count = count($tempids);
for ($j = 0; $j < $tempids_count; $j++) {
if ($tempids[$j] == 0) continue;
if (is_array($visitcache[$tempids[$j]]) && count($visitcache[$tempids[$j]])) {
reset($visitcache[$tempids[$j]]);
while (list($threadid, $lastposttime) = each($visitcache[$tempids[$j]])) {
if ($lastposttime > $boardvisit[$tempids[$j]]) {
$onoff = 'on';
break 2;
} // end if
} // end while
} // end if
} // end for
} // end else
if ($boards['isboard']) {
if ($boards['externalurl'] != '') $onoff = 'link';
elseif ($boards['closed'] == 1 || !$permissioncache[$boards['boardid']]['can_enter_board']) $onoff .= 'closed';
$useronlinebit = '';
$guestcount = 0;
if ($showuseronlineinboard == 2 && $boards['externalurl'] == '') {
global $userinboard, $online;
if (isset($userinboard[$boards['boardid']]) && count($userinboard[$boards['boardid']])) {
while (list($key, $row) = each($userinboard[$boards['boardid']])) {
if ($row['userid'] == 0) $guestcount++;
else $online->user($row['userid'], htmlconverter($row['username']), $row['useronlinemarking'], $row['invisible']);
}
$useronlinebit = $online->useronlinebit;
if ($guestcount == 1) $useronline_GUEST = $lang->items['LANG_START_USERONLINE_GUEST_ONE'];
elseif ($guestcount > 1) $useronline_GUEST = $lang->items['LANG_START_USERONLINE_GUEST'];
else $useronline_GUEST = '';
if ($guestcount > 0 && $useronlinebit != '') $useronline_AND = $lang->items['LANG_START_USERONLINE_AND'];
else $useronline_AND = '';
if ($guestcount > 0 || $useronlinebit != '') {
if ($guestcount == 0) $guestcount = '';
$boards['useronline'] = $lang->get("LANG_START_USERACTIVE", array('$useronlinebit' => $useronlinebit, '$useronline_AND' => $useronline_AND, '$guestcount' => $guestcount, '$useronline_GUEST' => $useronline_GUEST));
$boards['useronline'] = wbb_trim($boards['useronline']);
}
$online->useronlinebit = '';
}
}
if ($showuseronlineinboard == 1 && $boards['externalurl'] == '') {
$guestcount = '';
$useronline_GUEST = '';
$useronline_AND = '';
$useronlinebit = $boards['useronline'];
$boards['useronline'] = $lang->get("LANG_START_USERACTIVE", array('$useronlinebit' => $useronlinebit, '$useronline_AND' => $useronline_AND, '$guestcount' => $guestcount, '$useronline_GUEST' => $useronline_GUEST));
$boards['useronline'] = wbb_trim($boards['useronline']);
}
if ($boards['threadcount']) {
$boards['lastposter'] = htmlconverter($boards['lastposter']);
$lastpostdate = formatdate($wbbuserdata['dateformat'], $boards['lastposttime'], 1);
$lastposttime = formatdate($wbbuserdata['timeformat'], $boards['lastposttime']);
if ($showlastposttitle == 1) {
if ($permissioncache[$boards['boardid']]['can_enter_board']) {
if (wbb_strlen($boards['topic']) > 30) $topic = wbb_substr($boards['topic'], 0, 30).'...';
else $topic = $boards['topic'];
$topic = htmlconverter($topic);
$boards['topic'] = htmlconverter($boards['topic']);
}
if (isset($boards['iconid'])) $ViewPosticon = makeimgtag($boards['iconpath'], getlangvar($boards['icontitle'], $lang), 0);
else $ViewPosticon = makeimgtag($style['imagefolder'].'/icons/icon14.gif');
}
}
$moderatorbit = '';
if (isset($modcache[$boards['boardid']])) {
while (list($mkey, $moderator) = each($modcache[$boards['boardid']])) {
$moderator['username'] = htmlconverter($moderator['username']);
eval("\$moderatorbit .= \"".$tpl->get("index_moderatorbit")."\";");
}
}
if ($boards['postcount'] >= 1000) $boards['postcount'] = number_format($boards['postcount'], 0, "", $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
if ($boards['threadcount'] >= 1000) $boards['threadcount'] = number_format($boards['threadcount'], 0, "", $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
eval("\$boardbit .= \"".$tpl->get("index_boardbit")."\";");
}
else {
$show_hide = 0;
if ($boards['childlist'] != '0') {
if ((isset($hidecats[$boards['boardid']]) && $hidecats[$boards['boardid']] == 0) || ($depth < $index_depth && (!isset($hidecats[$boards['boardid']]) || $hidecats[$boards['boardid']] != 1))) {
$show_hide = 1;
if ($filename == 'index.php') $current_url = "index.php?hidecat=".$boards['boardid']. $SID_ARG_2ND;
else $current_url = "board.php?boardid=$temp_boardid&hidecat=".$boards['boardid']. $SID_ARG_2ND;
$LANG_START_DEACTIVATE_CAT = $lang->get("LANG_START_DEACTIVATE_CAT", array('$title' => $boards['title']));
}
else {
$show_hide = 2;
if ($filename == 'index.php') $current_url = "index.php?showcat=".$boards['boardid']. $SID_ARG_2ND;
else $current_url = "board.php?boardid=$temp_boardid&showcat=".$boards['boardid']. $SID_ARG_2ND;
$LANG_START_SHOWCAT = $lang->get("LANG_START_SHOWCAT", array('$title' => $boards['title']));
}
}
eval("\$boardbit .= \"".$tpl->get("index_catbit")."\";");
}
if ((isset($hidecats[$boards['boardid']]) && $hidecats[$boards['boardid']] == 0) || ($depth < $index_depth && (!isset($hidecats[$boards['boardid']]) || $hidecats[$boards['boardid']] != 1))) $boardbit .= makeboardbit($boards['boardid'], $depth + 1);
}
}
unset($boardcache[$boardid]);
return $boardbit;
}
/**
* generate the board navigationbar
*
* @param string parentlist
* @param string template
*
* @return string navbar
*/
function getNavbar($parentlist, $template = 'navbar_board') {
global $db, $n, $session, $url2board, $lines, $tpl, $boardnavcache, $lang, $SID_ARG_1ST, $SID_ARG_2ND, $SID_ARG_2ND_UN;
if ($parentlist == '0') return;
else {
$navbar = '';
if (!isset($boardnavcache) || !is_array($boardnavcache) || !count($boardnavcache)) {
$result = $db->unbuffered_query("SELECT boardid, title FROM bb".$n."_boards WHERE boardid IN ($parentlist)");
while ($row = $db->fetch_array($result)) {
$boardnavcache[$row['boardid']] = $row;
}
}
$parentids = explode(',', $parentlist);
$parentids_count = count($parentids);
for ($i = 1; $i < $parentids_count; $i++) {
if ($template == 'print_navbar') $lines .= str_repeat('-', $i);
$board = $boardnavcache[$parentids[$i]];
$board['title'] = getlangvar($board['title'], $lang);
eval("\$navbar .= \"".$tpl->get($template)."\";");
}
return $navbar;
}
}
/**
* generate the codebuttons for the message forms
*
* @return string bbcode_buttons
*/
function getcodebuttons() {
global $_COOKIE, $tpl, $style, $lang, $session, $SID_ARG_1ST, $SID_ARG_2ND, $SID_ARG_2ND_UN;
$modechecked = array('', '');
if ($_COOKIE['bbcodemode'] == 1) $modechecked[1] = "checked=\"checked\"";
else $modechecked[0] = "checked=\"checked\"";
eval("\$bbcode_sizebits = \"".$tpl->get("bbcode_sizebits")."\";");
eval("\$bbcode_fontbits = \"".$tpl->get("bbcode_fontbits")."\";");
eval("\$bbcode_colorbits = \"".$tpl->get("bbcode_colorbits")."\";");
eval("\$bbcode_buttons = \"".$tpl->get("bbcode_buttons")."\";");
return $bbcode_buttons;
}
/**
* generate the smilielist for message forms
*
* @param integer tableColumns
* @param integer maxSmilies
*
* @return string bbcode_smilies
*/
function getclickysmilies($tableColumns = 3, $maxSmilies = -1) {
global $db, $n, $tpl, $showsmiliesrandom, $style, $lang, $session, $SID_ARG_1ST, $SID_ARG_2ND, $SID_ARG_2ND_UN;
if ($showsmiliesrandom == 1) $result = $db->query("SELECT smiliepath, smilietitle, smiliecode FROM bb".$n."_smilies ORDER BY RAND()");
else $result = $db->query("SELECT smiliepath, smilietitle, smiliecode FROM bb".$n."_smilies ORDER BY smilieorder ASC");
$totalSmilies = $db->num_rows($result);
if (($maxSmilies == -1) || ($maxSmilies >= $totalSmilies)) $maxSmilies = $totalSmilies;
elseif ($maxSmilies < $totalSmilies) eval("\$bbcode_smilies_getmore = \"".$tpl->get("bbcode_smilies_getmore")."\";");
$i = 0;
while ($row = $db->fetch_array($result)) {
$row['smilietitle'] = getlangvar($row['smilietitle'], $lang);
$row['smiliepath'] = replaceImagefolder($row['smiliepath']);
$row['smiliecode'] = addcslashes($row['smiliecode'], "'\\");
eval("\$smilieArray[\"".$i."\"] = \"".$tpl->get("bbcode_smiliebit")."\";");
$i++;
}
$tableRows = ceil($maxSmilies / $tableColumns);
$count = 0;
$smiliebits = '';
for ($i = 0; $i < $tableRows; $i++) {
$smiliebits .= "\t<tr>\n";
for ($j = 0; $j < $tableColumns; $j++) {
$smiliebits .= $smilieArray[$count];
$count++;
if ($count >= $maxSmilies) {
$repeat = $tableColumns - ($j + 1);
if ($repeat > 0) $smiliebits .= str_repeat('<td class="tableb"></td>', $repeat);
break;
}
}
$smiliebits .= "\t</tr>\n";
}
$lang->items['LANG_POSTINGS_SMILIE_COUNT'] = $lang->get("LANG_POSTINGS_SMILIE_COUNT", array('$maxSmilies' => $maxSmilies, '$totalSmilies' => $totalSmilies));
eval("\$bbcode_smilies = \"".$tpl->get("bbcode_smilies")."\";");
return $bbcode_smilies;
}
function getAppletSmilies() {
static $splitString = '^@~|';
global $db, $n, $lang, $url2board;
$smilies = '';
$result = $db->query("SELECT smiliepath, smilietitle, smiliecode FROM bb".$n."_smilies ORDER BY smilieorder ASC");
while ($row = $db->fetch_array($result)) {
if ($smilies != '') $smilies .= $splitString;
$row['smilietitle'] = getlangvar($row['smilietitle'], $lang);
$row['smiliepath'] = replaceImagefolder($row['smiliepath']);
if (!preg_match("!^http://!", $row['smiliepath'])) $row['smiliepath'] = $url2board . "/" . $row['smiliepath'];
$row['smiliecode'] = addcslashes($row['smiliecode'], "\"\\");
$smilies .= $row['smiliecode'] . $splitString . $row['smilietitle'] . $splitString . $row['smiliepath'];
}
return $smilies;
}
/**
* if number is odd get element one otherweise element two
*
* @param integer number
* @param mixed one
* @param mixed two
*
* @return mixed element
*/
function getone($number, $one, $two) {
if ($number & 1) return $one;
else return $two;
}
/**
* generate the boardlist for boardjump
*
* @param integer current boardid
*
* @return string boardjump
*/
function makeboardjump($current) {
global $wbbuserdata, $boardcache, $permissioncache, $useuseraccess, $tpl, $session, $boardnavcache, $style, $lang, $SID_ARG_1ST, $SID_ARG_2ND, $SID_ARG_2ND_UN;
if (!isset($boardcache) || !isset($permissioncache)) {
global $db, $n, $wbbuserdata, $boardordermode;
switch ($boardordermode) {
case 1: $boardorder = 'title ASC'; break;
case 2: $boardorder = 'title DESC'; break;
case 3: $boardorder = 'lastposttime DESC'; break;
default: $boardorder = 'boardorder ASC'; break;
}
$result = $db->unbuffered_query("SELECT boardid, parentid, boardorder, title, invisible FROM bb".$n."_boards ORDER by parentid ASC, $boardorder");
while ($row = $db->fetch_array($result)) {
$boardcache[$row['parentid']][$row['boardorder']][$row['boardid']] = $row;
$boardnavcache[$row['boardid']] = $row;
}
$permissioncache = getPermissions();
}
if (is_array($boardcache) && count($boardcache)) {
reset($boardcache);
$boardoptions = makeboardselect(0, 1, $current);
}
eval("\$boardjump = \"".$tpl->get("boardjump")."\";");
return $boardjump;
}
/**
* generate a general boardlist
*
* @param integer boardid
* @param integer depth
* @param integer current
* @param string catmarking
*
* @return string boardlist
*/
function makeboardselect($boardid, $depth = 1, $current = 0, $catmarking = '%s') {
global $boardcache, $permissioncache, $accesscache, $wbbuserdata, $lang;
if (!isset($boardcache[$boardid])) return;
$boardbit = '';
while (list($key1, $val1) = each($boardcache[$boardid])) {
while (list($key2, $boards) = each($val1)) {
if (!isset($permissioncache[$boards['boardid']]['can_view_board']) || $permissioncache[$boards['boardid']]['can_view_board'] == -1) $permissioncache[$boards['boardid']]['can_view_board'] = $wbbuserdata['can_view_board'];
if ($boards['invisible'] == 2 || !$permissioncache[$boards['boardid']]['can_view_board']) continue;
if ($depth > 1) $prefix = str_repeat('--', $depth - 1).' ';
else $prefix = '';
$boards['title'] = getlangvar($boards['title'], $lang);
if (((isset($boards['externalurl']) && $boards['externalurl'] != '') || (isset($boards['isboard']) && !$boards['isboard'])) && $catmarking != '%s') $boards['title'] = sprintf($catmarking, $boards['title']);
$boardbit .= makeoption($boards['boardid'], $prefix.$boards['title'], $current, 1);
$boardbit .= makeboardselect($boards['boardid'], $depth + 1, $current, $catmarking);
}
}
unset($boardcache[$boardid]);
return $boardbit;
}
/**
* format rank images
*
* @param string images
*
* @return string images
*/
function formatRI($images) {
if (!$images) return;
$imgArray = explode(';', $images);
$RI = '';
$imgArray_count = count($imgArray);
for ($i = 0; $i < $imgArray_count; $i++) $RI .= makeimgtag($imgArray[$i]);
return $RI;
}
/**
* build URLs for parseURL
*
* @param string url
* @param integer id
* @param integer ispost
*
* @return string locallink
*/
function makeLocalLink($url, $id, $ispost = 0) {
global $threadcache, $postidcache;
$threadid = 0;
if ($ispost == 1 && isset($postidcache[$id])) $threadid = $postidcache[$id];
else $threadid = $id;
if ($threadid != 0 && isset($threadcache[$threadid])) return "[url=".$url."]".$threadcache[$threadid]."[/url]";
else return "[url]".$url."[/url]";
}
/**
* parse URLs in post
*
* @param string message
*
* @return string message
*/
function parseURL($message) {
global $db, $n, $threadcache, $postidcache, $usecode, $url2board, $boardurls;
static $idnList = array(224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 240, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 248, 254, 249, 250, 251, 252, 253, 255);
$idnChars = '';
for ($i = 0, $j = count($idnList); $i < $j; $i++) {
$idnChars .= chr($idnList[$i]);
}
$boardURL = str_replace("\n", "|", preg_quote(wbb_trim($url2board . "\n" . dos2unix($boardurls)), "%"));
$threadid_pattern = "((".$boardURL.")/thread\.php.*threadid=([0-9]+)(&.*)?)";
$postid_pattern = "((".$boardURL.")/thread\.php.*postid=([0-9]+)(&.*)?(#.*)?)";
// before parsing urls replace code tags with hash values
// to avoid URLs within code tags to be altered
if ($usecode == 1) {
$parsecode = &new parsecode;
$message = $parsecode->doparse($message);
}
$urlsearch[] = "/([^]@_a-z0-9-=\"'\/])((https?|ftp):\/\/|www\.)([^ \r\n\(\)\^\$!`\"'\|\[\]\{\}<>]*)/si";
$urlsearch[] = "/^((https?|ftp):\/\/|www\.)([^ \r\n\(\)\^\$!`\"'\|\[\]\{\}<>]*)/si";
$urlreplace[] = "\\1[URL]\\2\\4[/URL]";
$urlreplace[] = "[URL]\\1\\3[/URL]";
$emailsearch[] = "/([\s])([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z" . $idnChars . "0-9-]+(\.[a-zA-Z" . $idnChars . "0-9-]+)*(\.[a-zA-Z]{2,}))/si";
$emailsearch[] = "/^([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z" . $idnChars . "0-9-]+(\.[a-zA-Z" . $idnChars . "0-9-]+)*(\.[a-zA-Z]{2,}))/si";
$emailreplace[] = "\\1[EMAIL]\\2[/EMAIL]";
$emailreplace[] = "[EMAIL]\\0[/EMAIL]";
$message = preg_replace($urlsearch, $urlreplace, $message);
if (wbb_strpos($message, '@')) $message = preg_replace($emailsearch, $emailreplace, $message);
// cache vars
$threadcache = array();
$postidcache = array();
// get threadids & postids
$catched_threadids = array();
$catched_postids = array();
preg_replace("%\[url\]".$threadid_pattern."\[/url\]%ieU", "\$catched_threadids[]=\\3;", $message);
preg_replace("%\[url\]".$postid_pattern."\[/url\]%ieU", "\$catched_postids[]=\\3;", $message);
if (count($catched_threadids) || count($catched_postids)) {
// get visible boards
$result = $db->query("SELECT boardid,boardorder,parentid,parentlist FROM bb".$n."_boards WHERE password='' ORDER BY parentid ASC, boardorder ASC");
while ($row = $db->fetch_array($result)) $boardcache[$row['parentid']][$row['boardorder']][$row['boardid']] = $row;
$boardpermissions = getPermissions();
$boardids = '';
foreach ($boardcache as $key => $val) {
foreach ($val as $key2 => $val2) {
foreach ($val2 as $row) if (!isset($boardpermissions[$row['boardid']]['can_enter_board']) || $boardpermissions[$row['boardid']]['can_enter_board'] != 0) $boardids .= ','.$row['boardid'];
}
}
// get threadids
if (count($catched_postids)) {
$result = $db->query("SELECT postid, threadid FROM bb".$n."_posts WHERE postid IN (".implode(",", $catched_postids).")");
while ($row = $db->fetch_array($result)) {
$postidcache[$row['postid']] = $row['threadid'];
$catched_threadids[] = $row['threadid'];
}
}
// get topics
if (count($catched_threadids)) {
$catched_threadids = array_unique($catched_threadids);
$result = $db->query("SELECT threadid, topic FROM bb".$n."_threads WHERE threadid IN (".implode(",", $catched_threadids).") AND boardid IN (0".$boardids.")");
while ($row = $db->fetch_array($result)) $threadcache[$row['threadid']] = $row['topic'];
}
if (count($threadcache)) {
// insert topics
$message = preg_replace("%\[url\]".$threadid_pattern."\[/url\]%ieU", "makeLocalLink('\\1',\\3)", $message);
$message = preg_replace("%\[url\]".$postid_pattern."\[/url\]%ieU", "makeLocalLink('\\1',\\3,1)", $message);
}
}
// reinsert code
if ($usecode == 1) {
$message = $parsecode->replacecode($message);
}
return $message;
}
/**
* generates ACP pagelinks
*
* @param string link
* @param integer page
* @param integer pages
* @param integer number
*
* @return string pagelinks
*/
function makePageLink($link, $page, $pages, $number) {
global $tpl, $lang;
$f_pages = number_format($pages, 0, '', $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
eval("\$pagelink = \"".$tpl->get("pagelink")."\";");
if ($page - $number > 1) eval("\$pagelink .= \"".$tpl->get("pagelink_first")."\";");
if ($page > 1) {
$temppage = $page - 1;
eval("\$pagelink .= \"".$tpl->get("pagelink_left")."\";");
}
$count = (($page + $number >= $pages) ? ($pages) : ($page + $number));
for ($i = $page - $number; $i <= $count; $i++) {
if ($i < 1) $i = 1;
$f_i = $i;
if ($f_i > 1000) $f_i = number_format($f_i, 0, '', $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
if ($i == $page) eval("\$pagelink .= \"".$tpl->get("pagelink_current")."\";");
else eval("\$pagelink .= \"".$tpl->get("pagelink_nocurrent")."\";");
}
if ($page < $pages) {
$temppage = $page + 1;
eval("\$pagelink .= \"".$tpl->get("pagelink_right")."\";");
}
if ($page + $number < $pages) eval("\$pagelink .= \"".$tpl->get("pagelink_last")."\";");
return $pagelink;
}
/**
* generate a option tag
* @param string value
* @param string text
* @param string selected value
* @param integer selected
* @param string style
*
* @return string option tag
*/
function makeoption($value, $text, $selected_value = '', $selected = 1, $style = '') {
$option_selected = '';
if ($selected == 1) {
if (is_array($selected_value)) {
if (in_array($value, $selected_value)) $option_selected = " selected=\"selected\"";
}
elseif ($selected_value == $value) $option_selected = " selected=\"selected\"";
}
return "<option value=\"$value\"".(($style != '') ? (" style=\"color:$style\"") : ("")).$option_selected.">$text</option>";
}
/**
* get name of a month
*
* @param integer number
*
* @return string month
*/
function getmonth($number) {
global $months, $lang;
if (!isset($months)) $months = explode('|', $lang->get("LANG_GLOBAL_MONTHS"));
return $months[$number - 1];
}
/**
* get name of a day
*
* @param integer number
*
* @return string day
*/
function getday($number) {
global $days, $lang;
if (!isset($days)) $days = explode('|', $lang->get("LANG_GLOBAL_DAYS"));
return $days[$number];
}
/**
* show access error page and die
*
* @param integer isacp
*
* @return void
*/
function access_error($isacp = 0)
{
if ($isacp == 0)
{
global $db, $n, $wbbuserdata, $header, $footer, $headinclude, $session, $sid, $master_board_name, $REQUEST_URI, $tpl, $style, $lang, $usercbar_username, $allowloginencryption, $SID_ARG_1ST, $SID_ARG_2ND, $SID_ARG_2ND_UN;
$update_session = false;
if (!$wbbuserdata['userid'] && $allowloginencryption == 1)
{
// force authentificationcode
$authentificationcode = makeAuthentificationcode(0);
if ($authentificationcode != $session['authentificationcode'])
{
$update_session = true;
$session['authentificationcode'] = $authentificationcode;
$db->unbuffered_query("UPDATE bb".$n."_sessions SET authentificationcode = '".addslashes($session['authentificationcode'])."', request_uri='', boardid=0, threadid=0 WHERE sessionhash = '$sid'", 1);
}
}
if (!$update_session) $db->unbuffered_query("UPDATE bb".$n."_sessions SET request_uri='', boardid=0, threadid=0 WHERE sessionhash = '$sid'", 1);
$REQUEST_URI = htmlconverter($REQUEST_URI);
$lang->items['LANG_GLOBAL_ACCESS_ERROR_DESC'] = $lang->get("LANG_GLOBAL_ACCESS_ERROR_DESC", array('$SID_ARG_1ST' => $SID_ARG_1ST));
eval("\$tpl->output(\"".$tpl->get("access_error")."\");");
exit();
}
else
{
global $tpl, $lang, $master_board_name;
eval("\$tpl->output(\"".$tpl->get("access_error", 1)."\",1);");
exit;
}
}
/**
* verify an username
*
* @param string username
*
* @return boolean is_valid
*/
function verify_username($username) {
global $db, $n, $minusernamelength, $maxusernamelength, $ban_name;
if (wbb_strlen($username) < $minusernamelength || wbb_strlen($username) > $maxusernamelength) return false;
$ban_name = explode("\n", preg_replace("/\s*\n\s*/", "\n", wbb_strtolower(wbb_trim($ban_name))));
$ban_name_count = count($ban_name);
for ($i = 0; $i < $ban_name_count; $i++) {
$ban_name[$i] = wbb_trim($ban_name[$i]);
if (!$ban_name[$i]) continue;
if (strstr($ban_name[$i], '*')) {
$ban_name[$i] = str_replace("*", ".*", preg_quote($ban_name[$i], "/"));
if (preg_match("/$ban_name[$i]/i", $username)) return false;
}
elseif (wbb_strtolower($username) == $ban_name[$i]) return false;
}
$result = $db->query_first("SELECT COUNT(*) FROM bb".$n."_users WHERE username = '".addslashes($username)."'");
if ($result[0] != 0) return false;
else return true;
}
/**
* verify a email
*
* @param string email
*
* @return boolean is_valid
*/
function verify_email($email) {
global $db, $n, $multipleemailuse, $ban_email;
static $idnList = array(224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 240, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 248, 254, 249, 250, 251, 252, 253, 255);
$idnChars = '';
for ($i = 0, $j = count($idnList); $i < $j; $i++) {
$idnChars .= chr($idnList[$i]);
}
$email = wbb_strtolower($email);
if (!preg_match("/^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z" . $idnChars . "0-9-]+(\.[a-z" . $idnChars . "0-9-]+)*(\.[a-z]{2,}))$/si", $email)) return false;
$ban_email = explode("\n", preg_replace("/\s*\n\s*/", "\n", wbb_strtolower(wbb_trim($ban_email))));
$ban_email_count = count($ban_email);
for ($i = 0; $i < $ban_email_count; $i++) {
$ban_email[$i] = wbb_trim($ban_email[$i]);
if (!$ban_email[$i]) continue;
if (strstr($ban_email[$i], '*')) {
$ban_email[$i] = str_replace("*", ".*", preg_quote($ban_email[$i], "/"));
if (preg_match("/$ban_email[$i]/i", $email)) return false;
}
elseif ($email == $ban_email[$i]) return false;
}
if ($multipleemailuse == 1) return true;
else {
$result = $db->query_first("SELECT COUNT(*) FROM bb".$n."_users WHERE email = '".$email."'");
if ($result[0] != 0) return false;
else return true;
}
}
/**
* verify an ip address
*
* @param string ip
*
* @return void
*/
function verify_ip($ip, $throwAccessError = true) {
global $ban_ip;
$valid = true;
if ($ban_ip) {
$ban_ip = explode("\n", preg_replace("/\s*\n\s*/", "\n", wbb_strtolower(wbb_trim($ban_ip))));
$ban_ip_count = count($ban_ip);
for ($i = 0; $i < $ban_ip_count; $i++) {
$ban_ip[$i] = wbb_trim($ban_ip[$i]);
if (!$ban_ip[$i]) continue;
if (strstr($ban_ip[$i], '*')) {
$ban_ip[$i] = str_replace("*", ".*", preg_quote($ban_ip[$i], "/"));
if (preg_match("/$ban_ip[$i]/i", $ip)) $valid = false;
}
else if ($ip == $ban_ip[$i]) $valid = false;
}
}
if (!$valid && $throwAccessError) access_error();
return $valid;
}
/**
* verify an usertitle
*
* @param string usertitle
*
* @return boolean is_valid
*/
function verify_usertitle($usertitle) {
global $db, $n, $wbbuserdata, $ban_usertitle;
if ($wbbuserdata['can_avoid_ban_usertitle'] == 1) return true;
else
{
if (!is_array($ban_usertitle)) $ban_usertitle = explode("\n", preg_replace("/\s*\n\s*/", "\n", wbb_strtolower(wbb_trim($ban_usertitle))));
$ban_usertitle_count = count($ban_usertitle);
for ($i = 0; $i < $ban_usertitle_count; $i++) {
$ban_usertitle[$i] = wbb_trim($ban_usertitle[$i]);
if (!$ban_usertitle[$i]) continue;
if (strstr($ban_usertitle[$i], '*')) {
$ban_usertitle[$i] = str_replace("*", ".*", preg_quote($ban_usertitle[$i], "/"));
if (preg_match("/$ban_usertitle[$i]/i", $usertitle)) return false;
}
elseif (wbb_strtolower($usertitle) == $ban_usertitle[$i]) return false;
}
return true;
}
}
/**
* verify posttime for flood control
*
* @param integer userid
* @param string ipaddress
* @param integer avoid_fc
*
* @return boolean
*/
function flood_control($userid, $ipaddress, $avoid_fc) {
if ($avoid_fc == 1) return false;
global $db, $n, $fctime;
if ($userid) $result = $db->query_first("SELECT postid FROM bb".$n."_posts WHERE userid='$userid' AND posttime>='".(time() - $fctime)."'", 1);
else $result = $db->query_first("SELECT postid FROM bb".$n."_posts WHERE ipaddress='$ipaddress' AND posttime>='".(time() - $fctime)."'", 1);
if ($result['postid']) return true;
else return false;
}
/**
* generate a new random password
*
* @param integer number
* @param integer length
*
* @return string new password
*/
function password_generate($numbers = 2, $length = 8) {
$time = intval(wbb_substr(microtime(), 2, 8));
mt_srand($time);
$numberchain = '1234567890';
for ($i = 0; $i < $numbers; $i++) {
$random = mt_rand(0, wbb_strlen($numberchain) - 1);
$number[intval($numberchain[$random])] = mt_rand(1, 9);
$numberchain = str_replace($random, '' , $numberchain);
}
$chain = 'abcdefghijklmnopqrstuvwxyz';
for ($i = 0; $i < $length; $i++) {
if ($number[$i]) $password .= $number[$i];
else $password .= $chain[mt_rand(0, wbb_strlen($chain) - 1)];
}
return $password;
}
/**
* generate a new activation code
*
* @return string activation code
*/
function code_generate() {
$time = intval(wbb_substr(microtime(), 2, 8));
mt_srand($time);
return mt_rand(1000000, 10000000);
}
/**
* show an error page and die
*
* @param string error_msg
*
* @return void
*/
function error($error_msg) {
global $headinclude, $master_board_name, $tpl, $lang;
eval("\$tpl->output(\"".$tpl->get("error")."\");");
exit();
}
/**
* show a redirect page and die
*
* @param string msg
* @param string url
* @param integer waittime
*
* @return void
*/
function redirect($msg, $url, $waittime = 5) {
global $headinclude, $master_board_name, $tpl, $lang;
eval("\$tpl->output(\"".$tpl->get("redirect")."\");");
exit();
}
/**
* stop shooting in topic
*
* @param string topic
*
* @return string topic
*/
function stopShooting($topic) {
if ($topic == wbb_strtoupper($topic)) return wbb_ucwords(wbb_strtolower($topic));
return $topic;
}
/**
* add an element to a list
*
* @param string list
* @param string add
*
* @return string new list
*/
function add2list($list, $add) {
if ($list == '') return $add;
else {
$listelements = explode(' ', $list);
if (!in_array($add, $listelements)) {
$listelements[] = $add;
return implode(' ', $listelements);
}
else return - 1;
}
}
/**
* wordmatch function
*
* @param integer postid
* @param string message
* @param string topic
*
* @return void
*/
function wordmatch($postid, $message, $topic) {
global $db, $n, $minwordlength, $maxwordlength, $badsearchwords, $goodsearchwords;
$topicwords = '';
$topicwordarray = array();
$wordcache = array();
if ($topic) {
$topicwords = preg_replace("/(\.+)($| |\n|\t)/s", " ", $topic);
$topicwords = str_replace("[", " [", $topicwords);
$topicwords = str_replace("]", "] ", $topicwords);
$topicwords = preg_replace("/[<>\/,\.:;\(\)\[\]?!#{}%_\-+=\\\\]/s", " ", $topicwords);
$topicwords = preg_replace("/['\"]/s", "", $topicwords);
$topicwords = preg_replace("/[\s,]+/s", " ", $topicwords);
$topicwords = wbb_strtolower(wbb_trim(str_replace(" ", " ", $topicwords)));
$temparray = explode(" ", $topicwords);
while (list($key, $val) = each($temparray)) $topicwordarray[$val] = 1;
}
$words = preg_replace("/\[quote](.+)\[\/quote\]/siU", "", $message); // remove quotes
$words = preg_replace("/(\.+)($| |\n|\t)/s", " ", $words);
$words = str_replace("[", " [", $words);
$words = str_replace("]", "] ", $words);
$words = preg_replace("/[<>\/,\.:;\(\)\[\]?!#{}%_\-+=\\\\]/s", " ", $words);
$words = preg_replace("/['\"]/s", "", $words);
$words = preg_replace("/[\s,]+/s", " ", $words);
$words = wbb_strtolower(wbb_trim(str_replace(" ", " ", $words)));
if ($topicwords) $words .= " ".$topicwords;
$wordarray = explode(" ", $words);
$result = $db->unbuffered_query("SELECT wordid, word FROM bb".$n."_wordlist WHERE word IN ('".str_replace(" ", "','", $words)."')");
while ($row = $db->fetch_array($result)) $wordcache[$row['word']] = $row['wordid'];
$badwords = array();
if ($badsearchwords) {
$temp = explode("\n", wbb_strtolower($badsearchwords));
while (list($key, $val) = each($temp)) $badwords[wbb_trim($val)] = 1;
}
$goodwords = array();
if ($goodsearchwords) {
$temp = explode("\n", wbb_strtolower($goodsearchwords));
while (list($key, $val) = each($temp)) {
unset($badwords[wbb_trim($val)]);
$goodwords[wbb_trim($val)] = 1;
}
}
$alreadyadd = array();
$wordmatch_sql = '';
$newtopicwords = '';
$newwords = '';
while (list($key, $val) = each($wordarray)) {
if ((!isset($goodwords[$val]) && !$goodwords[$val]) && ((isset($badwords[$val]) && $badwords[$val] == 1) || wbb_strlen($val) < $minwordlength || wbb_strlen($val) > $maxwordlength)) {
unset($wordarray[$key]);
continue;
}
if ($val && !isset($alreadyadd[$val])) {
if (isset($wordcache[$val])) $wordmatch_sql .= ",($wordcache[$val],$postid,".(($topicwordarray[$val] == 1) ? (1) : (0)).")";
else {
if (isset($topicwordarray[$val]) && $topicwordarray[$val] == 1) $newtopicwords .= $val." ";
else $newwords .= $val." ";
}
$alreadyadd[$val] = 1;
}
}
if ($wordmatch_sql) $db->query("REPLACE INTO bb".$n."_wordmatch (wordid,postid,intopic) VALUES ".wbb_substr($wordmatch_sql, 1));
if ($newwords) {
$newwords = wbb_trim($newwords);
$insertwords = "(NULL,'".str_replace(" ", "'),(NULL,'", addslashes($newwords))."')";
$db->query("INSERT IGNORE INTO bb".$n."_wordlist (wordid,word) VALUES $insertwords");
$selectwords = "word IN('".str_replace(" ", "','", addslashes($newwords))."')";
$db->query("INSERT IGNORE INTO bb".$n."_wordmatch (wordid,postid) SELECT DISTINCT wordid,$postid FROM bb".$n."_wordlist WHERE $selectwords");
}
if ($newtopicwords) {
$newtopicwords = wbb_trim($newtopicwords);
$insertwords = "(NULL,'".str_replace(" ", "'),(NULL,'", addslashes($newtopicwords))."')";
$db->query("INSERT IGNORE INTO bb".$n."_wordlist (wordid,word) VALUES $insertwords");
$selectwords = "word IN('".str_replace(" ", "','", addslashes($newtopicwords))."')";
$db->query("REPLACE INTO bb".$n."_wordmatch (wordid,postid,intopic) SELECT DISTINCT wordid,$postid,1 FROM bb".$n."_wordlist WHERE $selectwords");
}
}
/**
* update board information
*
* @param string boardidlist
* @param integer lastposttime
* @param integer lastthreadid
*
* @return void
*/
function updateBoardInfo($boardidlist, $lastposttime = -1, $lastthreadid = -1) {
global $db, $n;
if ($lastthreadid != -1) $result = $db->query("SELECT boardid, childlist FROM bb".$n."_boards WHERE boardid IN ($boardidlist) AND lastthreadid='$lastthreadid'");
elseif ($lastposttime != -1) $result = $db->query("SELECT boardid, childlist FROM bb".$n."_boards WHERE boardid IN ($boardidlist) AND lastposttime<='$lastposttime'");
else $result = $db->query("SELECT boardid, childlist FROM bb".$n."_boards WHERE boardid IN ($boardidlist)");
while ($row = $db->fetch_array($result)) {
$lastthread = $db->query_first("SELECT threadid, lastposttime, lastposterid, lastposter FROM bb".$n."_threads WHERE boardid IN ($row[boardid],$row[childlist]) AND visible=1 AND closed<>3 ORDER BY lastposttime DESC", 1);
$db->unbuffered_query("UPDATE bb".$n."_boards SET lastthreadid='$lastthread[threadid]', lastposttime='$lastthread[lastposttime]', lastposterid='$lastthread[lastposterid]', lastposter='".addslashes($lastthread['lastposter'])."' WHERE boardid='$row[boardid]'", 1);
}
}
/**
* generate userration result
*
* @param integer count
* @param integer points
* @param integer userid
*
* @return string userrating
*/
function userrating($count, $points, $userid) {
global $tpl, $lang, $style;
if ($count != 0) {
$doubletemp = $points / $count;
$temp = number_format($doubletemp, 1);
$rating = number_format($doubletemp, 2, $lang->get("LANG_GLOBAL_DEC_POINT"), $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
$width = $temp * 10;
$LANG_MEMBERS_RATING_RATINGS = $lang->get("LANG_MEMBERS_RATING_RATINGS", array('$count' => $count, '$rating' => $rating));
}
eval("\$userrating = \"".$tpl->get("userrating")."\";");
return $userrating;
}
/**
* converts dos - newlines to unix - newlines
*
* @param string text
*
* @return string text
*/
function dos2unix($text) {
if ($text != '') {
$text = preg_replace("#(\r\n)|(\r)#", "\n", $text);
}
return $text;
}
/**
* strip crap from posts (i.e. sessionhash
*
* @param string post
*
* @return string post
*/
function stripcrap($post) {
if ($post) {
$post = preg_replace("/(\?|\&){1}sid=[a-z0-9]{32}/", "\\1sid=", $post);
$post = preg_replace("/(&#)(\d+)(;)/e", "chr(intval('\\2'))", $post);
$post = dos2unix($post);
}
return $post;
}
/**
* decode cookie data
*
* @param string serialized data
*
* @return array data
*/
function decode_cookie($data) {
return unserialize($data);
}
/**
* encode cookie data
*
* @param string name
* @param integer time
*
* @return void
*/
function encode_cookie($name, $time = 0) {
global $$name, $wbbuserdata;
bbcookie($name, serialize($$name), $time);
}
/**
* generate userlevel view
*
* @param integer userposts
* @param integer regdata
*
* @return string userlevel
*/
function userlevel($userposts, $regdate) {
global $tpl, $lang, $style;
$regdate = (time() - $regdate) / 86400;
$exp = ceil($userposts * $regdate);
if ($exp != 0) $level = pow(log10($exp), 2);
else $level = 0;
$showlevel = floor($level) + 1;
$nextexp = ceil(pow(10, pow($showlevel, 0.5)));
if ($showlevel == 1) $prevexp = 0;
else $prevexp = ceil(pow(10, pow($showlevel - 1, 0.5)));
$width = ceil((($exp - $prevexp) / ($nextexp - $prevexp)) * 100);
$needexp = number_format($nextexp - $exp, 0, '', $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
$exp = number_format($exp, 0, '', $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
$nextexp = number_format($nextexp, 0 , '', $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
$LANG_MEMBERS_USERLEVEL_NEEDEXP = $lang->get("LANG_MEMBERS_USERLEVEL_NEEDEXP", array('$needexp' => $needexp));
eval("\$userlevel = \"".$tpl->get("userlevel")."\";");
return $userlevel;
}
/**
* format a filesize
*
* @param integer byte
*
* @return string filesize
*/
function formatFilesize($byte) {
global $lang;
$string = 'Byte';
if ($byte > 1024) {
$byte /= 1024;
$string = 'KB';
}
if ($byte > 1024) {
$byte /= 1024;
$string = 'MB';
}
if ($byte > 1024) {
$byte /= 1024;
$string = 'GB';
}
if ($byte - number_format($byte, 0) >= 0.005) $byte = number_format($byte, 2, $lang->get("LANG_GLOBAL_DEC_POINT"), $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
else $byte = number_format($byte, 0, '', $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
return $byte.' '.$string;
}
/**
* get the client ip address
*
* @return string ip address
*/
function getIpAddress() {
global $_SERVER;
$REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $HTTP_X_FORWARDED_FOR = $_SERVER['HTTP_X_FORWARDED_FOR'];
else $HTTP_X_FORWARDED_FOR = '';
if ($HTTP_X_FORWARDED_FOR != '') {
if (preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $HTTP_X_FORWARDED_FOR, $ip_match)) {
$private_ip_list = array("/^0\./", "/^127\.0\.0\.1/", "/^192\.168\..*/", "/^172\.16\..*/", "/^10..*/", "/^224..*/", "/^240..*/");
$REMOTE_ADDR = preg_replace($private_ip_list, $REMOTE_ADDR, $ip_match[1]);
}
}
if (wbb_strlen($REMOTE_ADDR) > 16) $REMOTE_ADDR = wbb_substr($REMOTE_ADDR, 0, 16);
return $REMOTE_ADDR;
}
/**
* returns an array with user - and groupsettings
*
* @param mixed id
* @param string bywhat
* @param integer issession
*
* @return array data
*/
function getwbbuserdata($id, $bywhat = 'userid', $issession = 0) {
global $db, $n;
$wbbuserdata = array();
$variables = array();
$groupids = array();
if ($bywhat == 'userid') {
if ($issession == 0) $wbbuserdata = $db->query_first("SELECT uf.*,u.*,gc.groupids,gc.data FROM bb".$n."_users u LEFT JOIN bb".$n."_groupcombinations gc USING(groupcombinationid) LEFT JOIN bb".$n."_userfields uf ON (uf.userid=u.userid) WHERE u.userid='$id'");
else {
global $styleid, $langid;
$wbbuserdata = $db->query_first("SELECT u.*,gc.groupids,gc.data, s.styleid, s.templatepackid, s.designpackid, l.languagepackid, tp.templatestructure FROM bb".$n."_users u ".
"LEFT JOIN bb".$n."_groupcombinations gc USING(groupcombinationid) ".
"LEFT JOIN bb".$n."_styles s ON(s.styleid=".(($issession == 1 && isset($styleid)) ? ("'".intval($styleid)."'") : ("u.styleid")).") ".
"LEFT JOIN bb".$n."_templatepacks tp ON(tp.templatepackid=s.templatepackid) ".
"LEFT JOIN bb".$n."_languagepacks l ON(l.languagepackid=".(($issession == 1 && isset($langid)) ? ("'".intval($langid)."'") : ("u.langid")).") ".
"WHERE u.userid='$id'");
if (!isset($wbbuserdata['styleid'])) {
$default_style = $db->query_first("SELECT s.templatepackid, s.designpackid, tp.templatestructure FROM bb".$n."_styles s LEFT JOIN bb".$n."_templatepacks tp ON(tp.templatepackid=s.templatepackid) WHERE s.styleid=0");
$wbbuserdata['styleid'] = 0;
$wbbuserdata['templatepackid'] = $default_style['templatepackid'];
$wbbuserdata['designpackid'] = $default_style['designpackid'];
$wbbuserdata['templatestructure'] = $default_style['templatestructure'];
}
if (!isset($wbbuserdata['languagepackid'])) $wbbuserdata['languagepackid'] = 0;
}
$groupids = explode(',', $wbbuserdata['groupids']);
}
elseif ($bywhat == 'groupid') {
$wbbuserdata = $db->query_first("SELECT data FROM bb".$n."_groupcombinations WHERE groupids='$id'");
$groupids[] = $id;
}
elseif ($bywhat == 'grouptype') {
if ($issession == 0) $wbbuserdata = $db->query_first("SELECT g.groupid,gc.data FROM bb".$n."_groups g LEFT JOIN bb".$n."_groupcombinations gc ON gc.groupids=g.groupid WHERE g.grouptype='$id'");
else {
global $styleid, $langid;
$wbbuserdata = $db->query_first("SELECT g.groupid,gc.data, s.styleid, s.templatepackid, s.designpackid, l.languagepackid, tp.templatestructure FROM bb".$n."_groups g ".
"LEFT JOIN bb".$n."_groupcombinations gc ON gc.groupids=g.groupid ".
"LEFT JOIN bb".$n."_styles s ON(s.styleid='".intval($styleid)."') ".
"LEFT JOIN bb".$n."_templatepacks tp ON(tp.templatepackid=s.templatepackid) ".
"LEFT JOIN bb".$n."_languagepacks l ON(l.languagepackid='".intval($langid)."') ".
"WHERE g.grouptype='$id'");
if (!isset($wbbuserdata['styleid'])) {
$default_style = $db->query_first("SELECT s.templatepackid, s.designpackid, tp.templatestructure FROM bb".$n."_styles s LEFT JOIN bb".$n."_templatepacks tp ON(tp.templatepackid=s.templatepackid) WHERE s.styleid=0");
$wbbuserdata['styleid'] = 0;
$wbbuserdata['templatepackid'] = $default_style['templatepackid'];
$wbbuserdata['designpackid'] = $default_style['designpackid'];
$wbbuserdata['templatestructure'] = $default_style['templatestructure'];
}
if (!isset($wbbuserdata['languagepackid'])) $wbbuserdata['languagepackid'] = 0;
}
$groupids[] = $wbbuserdata['groupid'];
}
elseif ($bywhat == 'username') {
$wbbuserdata = $db->query_first("SELECT u.*, gc.groupids, gc.data, l.languagepackid FROM bb".$n."_users u LEFT JOIN bb".$n."_groupcombinations gc USING(groupcombinationid) LEFT JOIN bb".$n."_languagepacks l ON (l.languagepackid=u.langid) WHERE u.username='".addslashes($id)."'");
$groupids = explode(',', $wbbuserdata['groupids']);
}
$variables = unserialize($wbbuserdata['data']);
unset($wbbuserdata['data']);
if (is_array($variables) && count($variables)) {
while (list($key, $val) = each($variables)) {
$wbbuserdata[$key] = $val;
}
}
$wbbuserdata['groupids'] = $groupids;
return $wbbuserdata;
}
/**
* returns an array of arrays with user- and groupsettings
*
* @param string usernames
*
* @return array userdatas
*/
function getwbbuserdatas($usernames) {
global $db, $n;
static $groupcombinationCache;
if (!isset($groupcombinationCache)) $groupcombinationCache = array();
$wbbuserdata = array();
$usernames = explode("\n", $usernames);
foreach ($usernames as $key => $val) {
$usernames[$key] = addslashes(wbb_trim($val));
}
$result = $db->unbuffered_query("SELECT u.*, gc.groupids, gc.data, l.languagepackid FROM bb".$n."_users u LEFT JOIN bb".$n."_groupcombinations gc USING(groupcombinationid) LEFT JOIN bb".$n."_languagepacks l ON (l.languagepackid=u.langid) WHERE u.username IN ('".implode("','", $usernames)."')");
while ($row = $db->fetch_array($result)) {
$wbbuserdata[wbb_strtolower($row['username'])] = $row;
$wbbuserdata[wbb_strtolower($row['username'])]['groupids'] = explode(',', $wbbuserdata[wbb_strtolower($row['username'])]['groupids']);
if (!isset($groupcombinationCache[$row['groupcombinationid']])) {
$groupcombinationCache[$row['groupcombinationid']] = unserialize($row['data']);
}
unset($wbbuserdata[$row['username']]['data']);
if (is_array($groupcombinationCache[$row['groupcombinationid']])) {
$wbbuserdata[wbb_strtolower($row['username'])] = $wbbuserdata[wbb_strtolower($row['username'])] + $groupcombinationCache[$row['groupcombinationid']];
}
}
return $wbbuserdata;
}
/**
* returns true if the current user is moderator and has got the permission to perform this action.
*
* @param string function
*
* @return boolean permission
*/
function checkmodpermissions($function = '', $boarddata = '') {
global $wbbuserdata;
if ($boarddata != '') $board = $boarddata;
else {
global $board;
}
if ($function) {
if (isset($board[$function]) && $board[$function] != -1) return $board[$function];
elseif ($wbbuserdata['m_is_supermod'] == 1 || (isset($board['moderatorid']) && $board['moderatorid'] == $wbbuserdata['userid'] && $wbbuserdata['userid'])) return $wbbuserdata[$function];
else return false;
}
elseif ($wbbuserdata['m_is_supermod'] == 1 || (isset($board['moderatorid']) && $board['moderatorid'] == $wbbuserdata['userid'] && $wbbuserdata['userid'])) return true;
else return false;
}
/**
* get the permission for all boards
*
* @return array permissions
*/
function getPermissions() {
global $db, $n, $wbbuserdata;
// read in useraccess
if ($wbbuserdata['userid'] && $wbbuserdata['useuseraccess'] == 1) {
$useraccesscache = array();
$result = $db->query("SELECT * FROM bb".$n."_access WHERE userid = '$wbbuserdata[userid]'");
while ($row = $db->fetch_array($result)) $useraccesscache[$row['boardid']] = $row;
if (count($useraccesscache)) {
inheritpermissions(0, $useraccesscache, 'useraccess');
foreach ($useraccesscache as $row) {
reset($row);
while (list($key, $val) = each($row)) if ($val != -1) $wbbuserdata['permissions'][$row['boardid']][$key] = $val;
}
}
}
return $wbbuserdata['permissions'];
}
/**
* check the permissions for the current board
*
* @param string permission
* @param array boarddata
*
* @return boolean permission
*/
function checkpermissions($permission, $boarddata = '') {
global $wbbuserdata;
if ($boarddata != '') $board = $boarddata;
else {
global $board;
}
if (!isset($board[$permission]) || $board[$permission] == -1) return $wbbuserdata[$permission];
else return $board[$permission];
}
/**
* generate an iconlist
*
* @param integer iconid
*
* @return string iconlist
*/
function getIcons($iconid = 0) {
global $tpl, $lang, $db, $n, $filename;
$ICONselected[0] = '';
$ICONselected[$iconid] = "checked=\"checked\"";
$result = $db->query("SELECT * FROM bb".$n."_icons ORDER BY iconorder ASC");
$iconcount = 0;
$choice_posticons = '';
while ($row = $db->fetch_array($result)) {
$row_iconid = $row['iconid'];
if (!isset($ICONselected[$row_iconid])) $ICONselected[$row_iconid] = '';
$row['icontitle'] = getlangvar($row['icontitle'], $lang);
$row['iconpath'] = replaceImagefolder($row['iconpath']);
eval("\$choice_posticons .= \"".$tpl->get("newthread_iconbit")."\";");
if ($iconcount == 6) {
$choice_posticons .= '<br />';
$iconcount = 0;
}
else $iconcount++;
}
eval("\$icons = \"".$tpl->get("newthread_icons")."\";");
return $icons;
}
/**
* generate a mysql where tag
*
* @param string add
*
* @return string where
*/
function add2where($add) {
global $where;
if ($where) $where .= ' AND '.$add;
else $where = $add;
}
/**
* format allowed extensions for output
*
* @param string extensions
*
* @return string extensions
*/
function getAllowedExtensions($extensions) {
$extensions = dos2unix($extensions);
$a_extensions = explode("\n", $extensions);
$a_extensions = array_unique($a_extensions);
$a_temp = $a_extensions;
while (list($key, $val) = each($a_temp)) {
if (strstr($val, '*')) {
reset($a_extensions);
while (list($key2, $val2) = each($a_extensions)) {
if ($val != $val2 && preg_match("/".str_replace('*', '[a-z0-9]*', $val).'/', $val2)) unset($a_extensions[$key2]);
}
}
}
return implode(' ', $a_extensions);
}
/**
* htmlconverter function
*
* @param string text
*
* @return string encoded text
*/
function htmlconverter($text) {
global $phpversion;
$charsets = array('ISO-8859-1', 'ISO-8859-15', 'UTF-8', 'CP1252', 'WINDOWS-1252', 'KOI8-R', 'BIG5', 'GB2312', 'BIG5-HKSCS', 'SHIFT_JIS', 'EUC-JP');
if (version_compare($phpversion, '4.3.0') >= 0 && in_array(wbb_strtoupper(ENCODING), $charsets)) return @htmlentities($text, ENT_COMPAT, ENCODING);
elseif (in_array(wbb_strtoupper(ENCODING), array('ISO-8859-1', 'WINDOWS-1252'))) return htmlentities($text);
else return htmlspecialchars($text);
}
/**
* rehtmlconverter function
*
* @param string text
*
* @return string text
*/
function rehtmlconverter($text) {
global $phpversion;
$charsets = array('ISO-8859-1', 'ISO-8859-15', 'UTF-8', 'CP1252', 'WINDOWS-1252', 'KOI8-R', 'BIG5', 'GB2312', 'BIG5-HKSCS', 'SHIFT_JIS', 'EUC-JP');
if (version_compare($phpversion, '4.3.0') >= 0 && in_array(wbb_strtoupper(ENCODING), $charsets)) return @html_entity_decode($text, ENT_COMPAT, ENCODING);
elseif (in_array(wbb_strtoupper(ENCODING), array('ISO-8859-1', 'WINDOWS-1252'))) $trans_tbl = get_html_translation_table(HTML_ENTITIES);
else $trans_tbl = get_html_translation_table(HTML_SPECIALCHARS);
$trans_tbl = array_flip($trans_tbl);
return strtr($text, $trans_tbl);
}
/**
* generate the threadrating view
*
* @param integer votepoints
* @param integer voted
*
* @return string threadrating
*/
function threadrating($votepoints, $voted) {
global $tpl, $lang, $style;
$avarage = $votepoints / $voted;
$rating = round($avarage);
$avarage = number_format($avarage, 2, $lang->get("LANG_GLOBAL_DEC_POINT"), $lang->get("LANG_GLOBAL_THOUSANDS_SEP"));
$LANG_GLOBAL_THREAD_RATING = $lang->get("LANG_GLOBAL_THREAD_RATING", array('$voted' => $voted, '$avarage' => $avarage));
if ($rating < 6) {
$rating = 6 - $rating;
$img = makeimgtag($style['imagefolder']."/thumbs_down.gif", $LANG_GLOBAL_THREAD_RATING);
}
else {
$rating -= 5;
$img = makeimgtag($style['imagefolder']."/thumbs_up.gif", $LANG_GLOBAL_THREAD_RATING);
}
return str_repeat($img, $rating);
}
/**
* new textwrap function from class_parse
*
* @param string text
* @param integer wrapwidth
*
* @return string text
*/
function textwrap($text, $wrapwidth = 40) {
if ($text && wbb_strlen($text) > $wrapwidth) {
$text = preg_replace("/([^\n\r -]{".$wrapwidth."})/i", " \\1\n", $text);
return $text;
}
else return $text;
}
/**
* get the boardinfo and permissions for the current board
*
* @param integer boardid
*
* @return array data
*/
function getBoardAccessData($boardid) {
global $wbbuserdata, $db, $n, $filename, $lang;
$select = '';
$join = '';
if ($wbbuserdata['userid'] && ($filename == 'thread.php' || $filename == 'board.php')) {
$select = ", bv.lastvisit, s.emailnotify, s.countemails";
$join = " LEFT JOIN bb".$n."_boardvisit bv ON (bv.boardid=b.boardid AND bv.userid='".$wbbuserdata['userid']."')".
"LEFT JOIN bb".$n."_subscribeboards s ON (s.userid='".$wbbuserdata['userid']."' AND s.boardid=b.boardid)";
}
$board = $db->query_first("SELECT m.*, m.userid AS moderatorid,b.*".$select." FROM bb".$n."_boards b LEFT JOIN bb".$n."_moderators m ON (m.boardid=b.boardid AND m.userid='".$wbbuserdata['userid']."')".$join." WHERE b.boardid = '$boardid'");
// permissions
if (isset($wbbuserdata['permissions'][$boardid]) && is_array($wbbuserdata['permissions'][$boardid])) {
foreach ($wbbuserdata['permissions'][$boardid] as $key => $val) {
if ($key != 'boardid' && $val != -1) $board[$key] = $val;
}
}
// useraccess (inherited)
if ($wbbuserdata['userid'] && $wbbuserdata['useuseraccess'] == 1) {
$useraccess = $db->query_first("SELECT *, LOCATE(CONCAT(',',boardid,','),',$board[parentlist],$board[boardid],') as parentlocate FROM bb".$n."_access WHERE userid = '$wbbuserdata[userid]' AND boardid".(($board['parentlist']) ? (" IN($board[parentlist],$boardid)") : ("='$boardid'"))." ORDER BY parentlocate DESC", 1);
if (is_array($useraccess) && count($useraccess)) {
while (list($key, $val) = each($useraccess)) if ($key != 'boardid' && $val != -1) $wbbuserdata['permissions'][$boardid][$key] = $board[$key] = $val;
}
}
return $board;
}
/**
* make an authentification code*
*
* @param integer onlyWhenNeeded
*
* @return string authentificationcode
*/
function makeAuthentificationcode($onlyWhenNeeded = 1)
{
if ($onlyWhenNeeded == 1) $make = needNewAuthentificationcode();
else $make = 1;
if ($make == 1) {
srand((double)microtime() * 1000000);
$authentificationcode = md5(uniqid(rand().microtime(), 1));
return $authentificationcode;
}
else {
return '';
}
}
/**
* do we need a new authentification code?
*
* @return integer need
*/
function needNewAuthentificationcode()
{
global $filename, $_POST, $_REQUEST;
if ($filename == 'index.php' || ($filename == 'login.php' && !isSet($_POST['send'])) || ($filename == 'usercp.php' && isSet($_REQUEST['action']) && $_REQUEST['action'] == 'password_change' && !isSet($_POST['send'])) || ($filename == 'usercp.php' && isSet($_REQUEST['action']) && $_REQUEST['action'] == 'email_change' && !isSet($_POST['send']))) {
return 1;
}
elseif (($filename == 'login.php' && isSet($_POST['send'])) || ($filename == 'usercp.php' && isSet($_REQUEST['action']) && $_REQUEST['action'] == 'password_change' && isSet($_POST['send'])) || ($filename == 'usercp.php' && isSet($_REQUEST['action']) && $_REQUEST['action'] == 'email_change' && isSet($_POST['send']))) {
return 2;
}
else {
return 0;
}
}
/**
* str_replace with amount param
*
* @param string needle
* @param string str
* @param string haystack
* @param integer amout
*
* @return string str
*/
function amount_str_replace($needle, $str, $haystack, $amount) {
$start = wbb_strpos($haystack, $needle);
if ($start === false) return $haystack;
$end = $start + wbb_strlen($needle);
$new_haystack = wbb_substr($haystack, 0, $start).$str.wbb_substr($haystack, $end);
if ($amount > 1) amount_str_replace($needle, $str, $new_haystack, --$amount);
else return $new_haystack;
}
/**
* split hex values of a colorcode
*
* @param string color
*
* @return array color
*/
function getHexValues($color) {
$color = wbb_substr($color, 1);
return array(hexdec(wbb_substr($color, 0, 2)), hexdec(wbb_substr($color, 2, 2)), hexdec(wbb_substr($color, 4, 2)));
}
/**
* create the gradient for threadrating from
*
* @param string color1
* @param string color2
* @param string color3
*
* @return array colors
*/
function createGradient($color1, $color2, $color3) {
$color1codes = getHexValues($color1);
$color2codes = getHexValues($color2);
$color3codes = getHexValues($color3);
$red = ($color2codes[0] - $color1codes[0]) / 4;
$green = ($color2codes[1] - $color1codes[1]) / 4;
$blue = ($color2codes[2] - $color1codes[2]) / 4;
$newcolor = array();
for ($i = 0; $i < 5; $i++) {
$newred = dechex($color1codes[0] + round($i * $red));
if (wbb_strlen($newred) < 2) $newred = '0'.$newred;
$newgreen = dechex($color1codes[1] + round($i * $green));
if (wbb_strlen($newgreen) < 2) $newgreen = '0'.$newgreen;
$newblue = dechex($color1codes[2] + round($i * $blue));
if (wbb_strlen($newblue) < 2) $newblue = '0'.$newblue;
$newcolor[$i] = '#'.$newred.$newgreen.$newblue;
}
$red = ($color3codes[0] - $color2codes[0]) / 5;
$green = ($color3codes[1] - $color2codes[1]) / 5;
$blue = ($color3codes[2] - $color2codes[2]) / 5;
for ($i = 1; $i < 6; $i++) {
$newred = dechex($color2codes[0] + round($i * $red));
if (wbb_strlen($newred) < 2) $newred = '0'.$newred;
$newgreen = dechex($color2codes[1] + round($i * $green));
if (wbb_strlen($newgreen) < 2) $newgreen = '0'.$newgreen;
$newblue = dechex($color2codes[2] + round($i * $blue));
if (wbb_strlen($newblue) < 2) $newblue = '0'.$newblue;
$newcolor[(4 + $i)] = '#'.$newred.$newgreen.$newblue;
}
return $newcolor;
}
/**
* session update stuff
*
* @return void
*/
function sessionupdate() {
global $wbbuserdata, $days4AI, $db, $n;
if ($days4AI != '') {
$days4AI = unserialize($days4AI);
if (is_array($days4AI) && count($days4AI)) {
$regdays = (time() - $wbbuserdata['regdate']) / 86400;
$updateuser = 0;
while (list($key, $val) = each($days4AI)) {
if ($val <= $regdays && !in_array($key, $wbbuserdata['groupids'])) {
$db->unbuffered_query("INSERT IGNORE INTO bb".$n."_user2groups (userid,groupid) VALUES ('".$wbbuserdata['userid']."','$key')", 1);
$wbbuserdata['groupids'][] = $key;
$updateuser = 1;
}
}
if ($updateuser == 1) {
sort($wbbuserdata['groupids']);
updateMemberships($wbbuserdata['userid'], $wbbuserdata['userposts'], $wbbuserdata['gender'], implode(',', $wbbuserdata['groupids']));
}
}
}
$db->unbuffered_query("DELETE FROM bb".$n."_threadvisit WHERE userid = '".$wbbuserdata['userid']."' AND lastvisit<='".time()."' ", 1);
$db->unbuffered_query("DELETE FROM bb".$n."_boardvisit WHERE userid = '".$wbbuserdata['userid']."' AND lastvisit<='".time()."' ", 1);
}
/**
* update membership (groupcombination, rank and useronlinemarking)
*
* @param integer userid
* @param integer userposts
* @param integer gender
* @param string groupids
*
* @return void
*/
function updateMemberships($userid, $userposts, $gender, $groupids) {
global $db, $n;
list($groupid) = $db->query_first("SELECT groupid FROM bb".$n."_groups WHERE groupid IN ($groupids) ORDER BY showorder ASC", 1);
list($rankid) = $db->query_first("SELECT rankid FROM bb".$n."_ranks WHERE groupid IN ('0','".$groupid."') AND needposts<='".$userposts."' AND gender IN ('0','".$gender."') ORDER BY needposts DESC, gender DESC", 1);
$db->unbuffered_query("UPDATE bb".$n."_users SET groupcombinationid='".cachegroupcombinationdata($groupids , 0)."', rankid='".$rankid."', rankgroupid='".$groupid."', useronlinegroupid='".$groupid."' WHERE userid='".$userid."'", 1);
}
/**
* check posts for automatic group inserts
*
* @return void
*/
function checkPosts4AI() {
global $posts4AI, $wbbuserdata, $db, $n;
if ($posts4AI != '') {
$posts4AI = unserialize($posts4AI);
if (is_array($posts4AI) && count($posts4AI)) {
$updateuser = 0;
while (list($key, $val) = each($posts4AI)) {
if ($val <= $wbbuserdata['userposts'] && !in_array($key, $wbbuserdata['groupids'])) {
$db->unbuffered_query("INSERT IGNORE INTO bb".$n."_user2groups (userid,groupid) VALUES ('".$wbbuserdata['userid']."','$key')", 1);
$wbbuserdata['groupids'][] = $key;
$updateuser = 1;
}
}
if ($updateuser == 1) {
sort($wbbuserdata['groupids']);
updateMemberships($wbbuserdata['userid'], $wbbuserdata['userposts'], $wbbuserdata['gender'], implode(',', $wbbuserdata['groupids']));
}
}
}
}
/**
* get groupcombination data
*
* @param string groupids
* @param integer mode
* @param array data
*
* @return string serialized data
*/
function getgroupcombinationdata($groupids, $mode = 3, $data = array()) {
global $db, $n;
if ($mode == 1 || $mode == 3) {
// read in groupvariables
$variables = array();
$result = $db->unbuffered_query("SELECT g.groupid, g.grouptype, g.priority, var.variablename, var.type, vl.value FROM bb".$n."_groups g LEFT JOIN bb".$n."_groupvalues vl USING(groupid) LEFT JOIN bb".$n."_groupvariables var USING(variableid) WHERE g.groupid IN($groupids) ORDER BY priority ASC, grouptype DESC");
while ($row = $db->fetch_array($result)) {
switch ($row['type']) {
case 'truefalse': if (!isset($variables[$row['variablename']]) || $row['value'] || $row['priority']) $variables[$row['variablename']] = $row['value']; break;
case 'integer': if (!isset($variables[$row['variablename']]) || ($row['value'] > $variables[$row['variablename']] && $variables[$row['variablename']] != -1) || $row['priority'] || $row['value'] == -1) $variables[$row['variablename']] = $row['value']; break;
case 'string': $variables[$row['variablename']] = (($row['priority'] == 0 && isset($variables[$row['variablename']])) ? ($variables[$row['variablename']]."\n") : ("")).$row['value']; break;
case 'inverse_integer':
if (!isset($variables[$row['variablename']]) || ($row['value'] < $variables[$row['variablename']] && $row['value'] != -1) || $row['priority'] || $variables[$row['variablename']] == -1) $variables[$row['variablename']] = $row['value'];
break;
}
}
while (list($key, $val) = each($variables)) $data[$key] = $val;
}
if ($mode == 2 || $mode == 3) {
// read in forum permissions
$result = $db->query_first("SELECT groupid FROM bb".$n."_groups WHERE groupid IN ($groupids) AND priority <> 0 ORDER BY priority DESC");
if (isset($result['groupid'])) $groupids = $result['groupid'];
$data['permissions'] = array();
$permissioncache = array();
$result = $db->query("SELECT p.*,g.priority,g.grouptype FROM bb".$n."_permissions p LEFT JOIN bb".$n."_groups g USING(groupid) WHERE p.groupid IN ($groupids) ORDER BY g.priority ASC, g.grouptype DESC");
while ($row = $db->fetch_array($result, MYSQL_ASSOC)) $permissioncache[$row['boardid']][$row['groupid']] = $row;
// inherit forum permissions
inheritpermissions(0, $permissioncache);
// go through forum permissions
foreach ($permissioncache as $boardid => $val) {
foreach ($val as $row) {
if (isset($data['permissions'][$row['boardid']])) $tmp = $data['permissions'][$row['boardid']];
else $tmp = array();
reset($row);
while (list($key, $val) = each($row)) {
if ($val == -1 || $key == 'groupid') continue;
if (!isset($tmp[$key])) $tmp[$key] = $val;
if ($row['priority'] || $val == 1 || ($val == 0 && $tmp[$key] != 1)) $tmp[$key] = $val;
}
$data['permissions'][$row['boardid']] = $tmp;
}
}
}
return serialize($data);
}
/**
* cache a groupcombination
*
* @param string groupids
* @param integer update
* @param integer mode
* @param array data
*
* @return integer groupcombinationid
*/
function cachegroupcombinationdata($groupids, $update = 1, $mode = 3, $data = array()) {
global $db, $n;
list($groupcombinationid) = $db->query_first("SELECT groupcombinationid FROM bb".$n."_groupcombinations WHERE groupids='$groupids'");
if ($groupcombinationid > 0) {
if ($update == 1) $db->unbuffered_query("UPDATE bb".$n."_groupcombinations SET data='".addslashes(getgroupcombinationdata($groupids, $mode, $data))."' WHERE groupcombinationid='$groupcombinationid'", 1);
}
else {
$db->query("INSERT INTO bb".$n."_groupcombinations (groupids,data) VALUES ('$groupids', '".addslashes(getgroupcombinationdata($groupids))."')");
$groupcombinationid = $db->insert_id();
}
return $groupcombinationid;
}
/**
* check if a forum inherited permissions from its parent board
*
* @param integer boardid
* @param integer parentlist
* @param integer boardparentid
* @param integer parentid
* @param array permissioncache
*
* @return array groupids
*/
function checkforinheritance($boardid, $parentlist = 0, $boardparentid = '', $parentid = 0, $permissioncache = '') {
global $db, $n, $boardcache;
$groupids = array();
if (!$parentlist) return $groupids;
$parents = explode(',', $parentlist);
if (!in_array($parentid, $parents)) return $groupids;
// get board structure if not already loaded
//if (!isset($boardcache) || !is_array($boardcache) || !count($boardcache)) { // perhaps its better to check if the array is totally emtpy ?
if (!isset($boardcache) || !is_array($boardcache)) {
$boardcache = array();
$result = $db->query("SELECT boardid,boardorder,parentid,parentlist,childlist FROM bb".$n."_boards WHERE boardid IN ($boardid,$parentlist) ORDER BY parentid ASC, boardorder ASC");
while ($row = $db->fetch_array($result)) {
if ($boardid == $row['boardid'] && $boardparentid != '') $row['parentid'] = $boardparentid;
$boardcache[$row['parentid']][$row['boardorder']][$row['boardid']] = $row;
}
}
// get permissioncache if not already loaded
if (!is_array($permissioncache)) {
$permissioncache = array();
$result = $db->query("SELECT p.*,g.priority,g.grouptype FROM bb".$n."_permissions p LEFT JOIN bb".$n."_groups g USING(groupid) WHERE p.boardid IN ($boardid,$parentlist) ORDER BY g.priority ASC, g.grouptype DESC");
while ($row = $db->fetch_array($result)) $permissioncache[$row['boardid']][$row['groupid']] = $row;
}
if (isset($boardcache[$parentid]) && is_array($boardcache[$parentid])) {
foreach ($boardcache[$parentid] as $key => $val) {
foreach ($val as $key2 => $boards) {
// skip forums that are not relevant
if (!in_array($boards['boardid'], $parents) && $boards['boardid'] != $boardid) continue;
// inherit permissions from parent board
if ($boards['parentid']) {
// forum permissions
if (isset($permissioncache[$boards['parentid']]) && is_array($permissioncache[$boards['parentid']])) {
foreach ($permissioncache[$boards['parentid']] as $groupid => $row) {
if (!isset($permissioncache[$boards['boardid']][$groupid])) {
$permissioncache[$boards['boardid']][$groupid] = $row;
$permissioncache[$boards['boardid']][$groupid]['boardid'] = $boards['boardid'];
if ($boards['boardid'] == $boardid) $groupids[] = $groupid;
}
}
// return results..
if ($boards['boardid'] == $boardid ) {
return $groupids;
}
}
}
if (!isset($boards['childlist']) || $boards['childlist']) return checkforinheritance($boardid, $parentlist, $boardparentid, $boards['boardid'], $permissioncache);
}
}
reset($boardcache[$parentid]);
}
}
/**
* inherit forum permissions (permissions & useraccess)
*
* @param integer parentid
* @param array permissioncache
* @param string type
*
* @return void
*/
function inheritpermissions($parentid = 0, &$permissioncache, $type = 'forumpermissions') {
global $db, $n, $boardcache;
// get board structure if not already loaded
//if (!isset($boardcache) || !is_array($boardcache) || !count($boardcache)) { // perhaps its better to check if the array is totally emtpy ?
if (!isset($boardcache) || !is_array($boardcache)) {
$boardcache = array();
$result = $db->query("SELECT boardid,boardorder,parentid,parentlist,childlist FROM bb".$n."_boards ORDER BY parentid ASC, boardorder ASC");
while ($row = $db->fetch_array($result)) {
$boardcache[$row['parentid']][$row['boardorder']][$row['boardid']] = $row;
}
}
if (isset($boardcache[$parentid]) && is_array($boardcache[$parentid])) {
foreach ($boardcache[$parentid] as $key => $val) {
foreach ($val as $key2 => $boards) {
// inherit permissions from parent board
if ($boards['parentid']) {
// forum permissions
if ($type == 'forumpermissions' && isset($permissioncache[$boards['parentid']]) && is_array($permissioncache[$boards['parentid']])) {
$resort = false;
foreach ($permissioncache[$boards['parentid']] as $groupid => $row) {
if (!isset($permissioncache[$boards['boardid']][$groupid])) {
$permissioncache[$boards['boardid']][$groupid] = $row;
$permissioncache[$boards['boardid']][$groupid]['boardid'] = $boards['boardid'];
$permissioncache[$boards['boardid']][$groupid]['permissionsinherited'] = 1; // mark inheritance for permissions overview in admin panel
$resort = true;
}
}
// if permissions were inherited, we have to resort the array by grouppriority and grouptype
// unfortenately, array_multisort resets numeric array keys..
if ($resort) {
$sortarray1 = array();
$sortarray2 = array();
foreach ($permissioncache[$boards['boardid']] as $val) {
$sortarray1[] = $val['priority'];
$sortarray2[] = $val['grouptype'];
}
array_multisort($sortarray1, SORT_ASC, SORT_NUMERIC, $sortarray2, SORT_DESC, SORT_NUMERIC, $permissioncache[$boards['boardid']]);
unset($sortarray1);
unset($sortarray2);
$newarray = array();
foreach ($permissioncache[$boards['boardid']] as $key => $val) $newarray[$val['groupid']] = $val;
$permissioncache[$boards['boardid']] = $newarray;
unset($newarray);
}
}
// user access
elseif ($type == 'useraccess' && isset($permissioncache[$boards['parentid']]) && is_array($permissioncache[$boards['parentid']]) && !isset($permissioncache[$boards['boardid']])) {
$permissioncache[$boards['boardid']] = $permissioncache[$boards['parentid']];
$permissioncache[$boards['boardid']]['boardid'] = $boards['boardid'];
}
}
if (!isset($boards['childlist']) || $boards['childlist']) inheritpermissions($boards['boardid'], $permissioncache, $type);
}
}
reset($boardcache[$parentid]);
}
}
/**
* own trim function for wbb
*
* @param string text
*
* @return string text
*/
function wbb_trim($text) {
if ($text != '') {
// removing whitespace may not work with some charsets (like utf - 8, gb2312, etc)
global $removewhitespace;
if ($removewhitespace == 1) {
$text = str_replace(chr(160), " ", $text); // remove alt + 0160
$text = str_replace(chr(173), " ", $text); // remove alt + 0173
$text = str_replace(chr(240), " ", $text); // remove alt + 0240
$text = str_replace("\0", " ", $text); // remove whitespace
}
$text = trim($text);
}
return $text;
}
/**
* replace the key with a langvar
*
* @param string key
* @param object lang
* @param integer userhtmlconverter
*
* @return string langvar
*/
function getlangvar($key, &$lang, $usehtmlconverter = 1) {
if (isset($lang->items['LANG_OWN_'.$key])) return $lang->items['LANG_OWN_'.$key];
else return (($usehtmlconverter == 1) ? (htmlconverter($key)) : ($key));
}
/**
* get search fieldname for memberssearch
*
* @param string field
*
* @return string fieldname
*/
function getSearchFieldname($field) {
if (strstr($field, 'profilefield')) return 'field'.wbb_substr($field, 12);
else {
if (in_array($field, array('pm', 'search', 'buddy', 'rankimage'))) return '';
elseif ($field == 'avatar') return 'u.avatarid';
else return $field;
}
}
/**
* generate a dynamic link
*
* @param string varname
* @param string value
* @param integer isacp
*
* @return void
*/
function linkGenerator($varname, $value) {
global $link;
$link .= urlencode($varname).'='.urlencode($value).'&';
}
/**
* anti spam roboter e - mail generator
*
* @param string text
*
* @return string text
*/
function getASCIICodeString($text) {
if ($text != '') {
$newtext = '';
$length = wbb_strlen($text);
for ($i = 0; $i < $length; $i++) {
$newtext .= '&#'.ord($text[$i]).';';
}
$text = $newtext;
}
return $text;
}
/**
* function version_compare for php < 4.1.0
*
* @param string vercurrent
* @param string vercheck
*
* @param integer check
*/
if (!function_exists('version_compare')) {
function version_compare($vercurrent, $vercheck) {
$minver = explode('.', $vercheck);
$curver = explode('.', $vercurrent);
if (($curver[0] < $minver[0]) || (($curver[0] == $minver[0]) && ($curver[1] < $minver[1])) || (($curver[0] == $minver[0]) && ($curver[1] == $minver[1]) && ($curver[2][0] < $minver[2][0])))
return - 1;
elseif ($curver[0] == $minver[0] && $curver[1] == $minver[1] && $curver[2] == $minver[2])
return 0;
else
return 1;
}
}
/**
* search for users with a certain groupcombination
*
* @param array variables
* @param string operator
*
* @return string groupcombinations
*/
function getUserByGroupcombination($variables, $operator = 'AND')
{
global $db, $n;
$groupcombinations = '';
$result = $db->query("SELECT groupcombinationid,data FROM bb".$n."_groupcombinations");
while ($row = $db->fetch_array($result)) {
$row['data'] = unserialize($row['data']);
if ($operator == 'AND') {
$goodcombination = true;
foreach ($variables as $variablename => $value) {
if ($row['data'][$variablename] != $value) $goodcombination = false;
}
}
else {
$goodcombination = false;
foreach ($variables as $variablename => $value) {
if ($row['data'][$variablename] == $value) $goodcombination = true;
}
}
if ($goodcombination) $groupcombinations .= ','.$row['groupcombinationid'];
}
return $groupcombinations;
}
/**
* replace "{imagefolder}" with "$style['imagefolder']"
*
* @param string text
*
* @return string text
*/
function replaceImagefolder($text) {
if ($text != '' && strstr($text, '{imagefolder}')) {
global $style;
$text = str_replace('{imagefolder}', $style['imagefolder'], $text);
}
return $text;
}
/**
* check the admin permission for a function
*
* @param string permission
* @param integer access_error
*
* @return boolean permission
*/
function checkAdminPermissions($permission, $access_error = 0) {
global $wbbuserdata;
if ($access_error == 0) {
if ($wbbuserdata['a_can_use_acp'] == 1 && isSet($wbbuserdata[$permission]) && $wbbuserdata[$permission]) return true;
else return false;
}
elseif ($access_error != 0 && (!$wbbuserdata['a_can_use_acp'] || !isSet($wbbuserdata[$permission]) || !$wbbuserdata[$permission])) {
access_error(1);
}
}
/**
* extracts the embedded thumbnail picture of a jpeg or tiff image
*
* @param string filename
* @param string type
* @param integer maxWidth
* @param integer maxHeight
*
* @return string thumbnail
*/
function extractEmbeddedThumbnail($filename, &$thumbnail_type, $maxWidth = 160, $maxHeight = 160) {
if (version_compare(phpversion(), '4.3.0') < 0 || !function_exists('exif_thumbnail')) {
return false;
}
$width = $height = $type = 0;
$thumbnail = @exif_thumbnail($filename, $width, $height, $type);
if ($thumbnail && $type) {
// resize the extracted thumbnail again if necessary
// (normally the thumbnail size is set to 160px
// which is recommended in EXIF >2.1 and DCF
if (($width > $maxWidth || $height > $maxHeight) || ($width < $maxWidth && $height < $maxHeight)) {
if (file_exists('./acp/temp/')) $tempFilename = './acp/temp/';
else $tempFilename = './temp/';
$tempFilename .= md5(uniqid(rand()));
$fp = @fopen($tempFilename, 'wb');
@fwrite($fp, $thumbnail);
@fclose($fp);
@chmod($tempFilename, 0777);
if ($width > $maxWidth || $height > $maxHeight) {
$thumbnail = makeThumbnailImage($tempFilename, $type, $maxWidth, $maxHeight);
}
else {
if ($width > $height) {
$newWidth = $maxWidth;
$newHeight = round($height * ($newWidth / $width));
}
else {
$newHeight = $maxHeight;
$newWidth = round($width * ($newHeight / $height));
}
$thumbnail = resizeImageTo($tempFilename, $type, $newWidth, $newHeight, $width, $height, $type);
}
@unlink($tempFilename);
if (!$thumbnail) {
return false;
}
}
else {
switch ($type) {
case 1: $type = 'gif'; break;
case 2: $type = 'jpg'; break;
case 3: $type = 'png'; break;
}
}
$thumbnail_type = $type;
return $thumbnail;
}
}
/**
* create a thumbnail picture (jpg) of a big image
*
* @param string filename
* @param string type
* @param integer maxWidth
* @param integer maxHeight
*
* @return string thumbnail
*/
function makeThumbnailImage($filename, &$thumbnail_type, $maxWidth = 160, $maxHeight = 160) {
global $makethumbnails;
list($width, $height, $type) = @getimagesize($filename);
// no need to resize this image => cancel
if ($width <= $maxWidth && $height <= $maxHeight) {
return false;
}
// try to extract the embedded thumbnail first (faster)
if ($makethumbnails == 2) {
$thumbnail = extractEmbeddedThumbnail($filename, $thumbnail_type, $maxWidth, $maxHeight);
if ($thumbnail != '') {
return $thumbnail;
}
}
// calculate uncompressed filesize
// and cancel to avoid a memory_limit error
$memory_limit = ini_get('memory_limit');
if ($memory_limit != '') {
$memory_limit = wbb_substr($memory_limit, 0, -1) * 1024 * 1024;
$filesize = $width * $height * 3;
if (($filesize * 2) > ($memory_limit - 1024 * 1024)) {
if ($makethumbnails == 1) {
$thumbnail = extractEmbeddedThumbnail($filename, $thumbnail_type, $maxWidth, $maxHeight);
if ($thumbnail != '') {
return $thumbnail;
}
}
return false;
}
}
if ($width > $height) {
$newWidth = $maxWidth;
$newHeight = round($height * ($newWidth / $width));
}
else {
$newHeight = $maxHeight;
$newWidth = round($width * ($newHeight / $height));
}
$thumbnail = resizeImageTo($filename, $thumbnail_type, $newWidth, $newHeight, $width, $height, $type);
return $thumbnail;
}
/**
* resize image to given width and height
*
* @param string filename
* @param string type
* @param integer maxWidth
* @param integer maxHeight
* @param integer oldWidth
* @param integer oldHeight
* @param integer oldType
*
* @return string imageNew
*/
function resizeImageTo($filename, &$type, $newWidth, $newHeight, $oldWidth, $oldHeight, $oldType) {
// jpeg image
if ($oldType == 2 && function_exists('imagecreatefromjpeg')) {
$imageResource = @imagecreatefromjpeg($filename);
}
// gif image
if ($oldType == 1 && function_exists('imagecreatefromgif')) {
$imageResource = @imagecreatefromgif($filename);
}
// png image
if ($oldType == 3 && function_exists('imagecreatefrompng')) {
$imageResource = @imagecreatefrompng($filename);
}
// could not create image
$type = '';
if (!isset($imageResource) || !$imageResource) {
return false;
}
// resize image
if (function_exists('imagecreatetruecolor') && function_exists('imagecopyresampled')) {
$imageNew = @imagecreatetruecolor($newWidth, $newHeight);
@imagecopyresampled($imageNew, $imageResource, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);
}
elseif (function_exists('imagecreate') && function_exists('imagecopyresized')) {
$imageNew = @imagecreate($newWidth, $newHeight);
@imagecopyresized($imageNew, $imageResource, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);
}
else return false;
$imageNew = createImage($imageNew, $type);
// return new image
if ($imageNew != '') {
return $imageNew;
}
else {
return false;
}
}
/**
* creates a final image from an image resource
*
* @param resource imageResource
*
* @return string image
*/
function createImage(&$imageResource, &$type) {
ob_start();
if (function_exists('imagejpeg')) {
@imagejpeg($imageResource);
$type = 'jpg';
}
elseif (function_exists('imagepng')) {
@imagepng($imageResource);
$type = 'png';
}
else {
return false;
}
@imagedestroy($imageResource);
$image = ob_get_contents();
ob_end_clean();
return $image;
}
/**
* sends a private message
*
* @param array recipientlist
* @param array recipientlist_bcc
* @param string subject
* @param string message
* @param integer senderid
* @param integer savecopy
* @param integer allowsmilies
* @param integer allowhtml
* @param integer allowbbcode
* @param integer allowimages
* @param integer showsignature
* @param integer iconid
* @param integer tracking
* @param integer attachments
* @param integer doublecheck
*
* @return integer pmid
*/
function sendPrivateMessage($recipientlist, $recipientlist_bcc, $subject, $message, $senderid = 0, $savecopy = 0, $allowsmilies = 1, $allowhtml = 0, $allowbbcode = 1, $allowimages = 1, $showsignature = 1, $iconid = 0, $tracking = 0, $attachments = 0, $doublecheck = 0) {
global $db, $n, $pmmaxrecipientlistsize, $dpvtime;
if (!isset($pmmaxrecipientlistsize)) $pmmaxrecipientlistsize = 10;
// validate input
$senderid = intval($senderid);
$savecopy = intval($savecopy);
$allowsmilies = intval($allowsmilies);
$allowhtml = intval($allowhtml);
$allowbbcode = intval($allowbbcode);
$alloimages = intval($alloimages);
$showsignature = intval($showsignature);
$iconid = intval($iconid);
$tracking = intval($tracking);
$attachments = intval($attachments);
// serialize recipientlist
$recipientlistSerialized = $recipientlist + $recipientlist_bcc;
$recipientcount = count($recipientlistSerialized);
if ($recipientcount > $pmmaxrecipientlistsize) {
for ($j = 0, $jmax = count($recipientlistSerialized) - $pmmaxrecipientlistsize; $j < $jmax; $j++) array_pop($recipientlistSerialized);
}
$recipientlistSerialized = serialize($recipientlistSerialized);
// check wheater this private message already exists or not
$pmhash = md5($senderid."\n".$recipientcount."\n".$recipientlistSerialized."\n".$subject."\n".$message);
if ($doublecheck == 1) {
$check = $db->query_first("SELECT privatemessageid FROM bb".$n."_privatemessage WHERE pmhash='".addslashes($pmhash)."' AND sendtime>='".(time() - $dpvtime)."'");
if ($check['privatemessageid']) {
return false;
}
}
// insert pm
$db->unbuffered_query("INSERT INTO bb".$n."_privatemessage (senderid,recipientlist,recipientcount,subject,message,sendtime,allowsmilies,allowhtml,allowbbcode,allowimages,showsignature,iconid,inoutbox,tracking,attachments,pmhash) VALUES ('$senderid','".addslashes($recipientlistSerialized)."','".$recipientcount."','".addslashes($subject)."','".addslashes($message)."','".time()."','$allowsmilies','$allowhtml','$allowbbcode','$allowimages','$showsignature','$iconid','$savecopy','$tracking', '$attachments', '".addslashes($pmhash)."')", 1);
$pmid = $db->insert_id();
$recipientInsertStr = '';
foreach ($recipientlist as $recipientid => $recipient) {
$recipientid = intval($recipientid);
$recipientInsertStr .= ",('$pmid', '$recipientid', '".addslashes($recipient)."', '0')";
}
foreach ($recipientlist_bcc as $recipientid => $recipient) {
$recipientid = intval($recipientid);
$recipientInsertStr .= ",('$pmid', '$recipientid', '".addslashes($recipient)."', '1')";
}
$db->unbuffered_query("INSERT INTO bb".$n."_privatemessagereceipts (privatemessageid, recipientid, recipient, blindcopy) VALUES ".wbb_substr($recipientInsertStr, 1), 1);
// update pmcounter for recipients && sender
$recipientUpdateList = implode(',', array_merge(array_keys($recipientlist), array_keys($recipientlist_bcc)));
$db->unbuffered_query("UPDATE bb".$n."_users SET pmtotalcount=pmtotalcount+1,pminboxcount=pminboxcount+1,pmnewcount=pmnewcount+1,pmunreadcount=pmunreadcount+1 WHERE userid IN (".$recipientUpdateList.")", 1);
if ($savecopy == 1 && $senderid > 0) $db->unbuffered_query("UPDATE bb".$n."_users SET pmtotalcount=pmtotalcount+1 WHERE userid='$senderid'", 1);
// set popup for recipients
$db->unbuffered_query("UPDATE bb".$n."_users SET pmpopup=2 WHERE userid IN (".$recipientUpdateList.") AND pmpopup=1", 1);
return $pmid;
}
/** wrapper functions for mb_functions **/
function wbb_mail($to, $subject, $message, $headers = null, $params = null) {
if (USE_MBSTRING === true) {
if (!is_null($params)) return mb_send_mail($to, $subject, $message, $headers, $params);
elseif (!is_null($headers)) return mb_send_mail($to, $subject, $message, $headers);
else return mb_send_mail($to, $subject, $message);
}
else {
if (!is_null($params)) return mail($to, $subject, $message, $headers, $params);
elseif (!is_null($headers)) return mail($to, $subject, $message, $headers);
else return mail($to, $subject, $message);
}
}
function wbb_split($pattern, $string, $limit = null) {
if (USE_MBSTRING === true) {
if (!is_null($limit)) return mb_split($pattern, $string, $limit);
else return mb_split($pattern, $string);
}
else {
if (!is_null($limit)) return split($pattern, $string, $limit);
else return split($pattern, $string);
}
}
function wbb_strlen($string, $encoding = null) {
if (USE_MBSTRING === true) {
if ($encoding) return mb_strlen($string, $encoding);
elseif (defined('ENCODING')) return mb_strlen($string, ENCODING);
else return mb_strlen($string);
}
else {
return strlen($string);
}
}
function wbb_strpos($haystack, $needle, $offset = 0, $encoding = null) {
if (USE_MBSTRING === true) {
if ($encoding) return mb_strpos($haystack, $needle, $offset, $encoding);
elseif (defined('ENCODING')) return mb_strpos($haystack, $needle, $offset, ENCODING);
else return mb_strpos($haystack, $needle, $offset);
}
else {
return strpos($haystack, $needle, $offset);
}
}
function wbb_strrpos($haystack, $needle, $encoding = null) {
if (USE_MBSTRING === true) {
if ($encoding) return mb_strrpos($haystack, $needle, $encoding);
elseif (defined('ENCODING')) return mb_strrpos($haystack, $needle, ENCODING);
else return mb_strrpos($haystack, $needle);
}
else {
return strrpos($haystack, $needle);
}
}
function wbb_strtolower($string, $encoding = null) {
if (USE_MBSTRING === true) {
if ($encoding) return mb_strtolower($string, $encoding);
elseif (defined('ENCODING')) return mb_strtolower($string, ENCODING);
else return mb_strtolower($string);
}
else {
return strtolower($string);
}
}
function wbb_strtoupper($string, $encoding = null) {
if (USE_MBSTRING === true) {
if ($encoding) return mb_strtoupper($string, $encoding);
elseif (defined('ENCODING')) return mb_strtoupper($string, ENCODING);
else return mb_strtoupper($string);
}
else {
return strtoupper($string);
}
}
function wbb_substr_count($haystack, $needle, $encoding = null) {
if (USE_MBSTRING === true) {
if ($encoding) return mb_substr_count($haystack, $needle, $encoding);
elseif (defined('ENCODING')) return mb_substr_count($haystack, $needle, ENCODING);
else return mb_substr_count($haystack, $needle);
}
else {
return substr_count($haystack, $needle);
}
}
function wbb_substr($string, $start, $length = null, $encoding = null) {
if (USE_MBSTRING === true) {
if ($encoding) return mb_substr($string, $start, $length, $encoding);
elseif (defined('ENCODING')) {
if (!is_null($length)) return mb_substr($string, $start, $length, ENCODING);
else return mb_substr($string, $start, wbb_strlen($string, $encoding), ENCODING);
}
else {
if (!is_null($length)) return mb_substr($string, $start, $length);
else return mb_substr($string, $start);
}
}
else {
if (!is_null($length)) return substr($string, $start, $length);
else return substr($string, $start);
}
}
/** wrapper functions for other string functions **/
function wbb_ucfirst($string, $encoding = null) {
if (USE_MBSTRING == true) {
return wbb_strtoupper(wbb_substr($string, 0, 1, $encoding), $encoding).wbb_substr($string, 1, $encoding);
}
else {
return ucfirst($string);
}
}
function wbb_ucwords($string, $encoding = null) {
if (USE_MBSTRING == true) {
if ($encoding) return mb_convert_case($string, MB_CASE_TITLE, $encoding);
elseif (defined('ENCODING')) return mb_convert_case($string, MB_CASE_TITLE, ENCODING);
else return mb_convert_case($string, MB_CASE_TITLE);
}
else {
return ucwords($string);
}
}
/**
* function sha1 for php < 4.3.0
*
* @param string string
*
* @return string hash
*/
if (!function_exists('sha1')) {
function sha1($string) {
if (extension_loaded('mhash') && function_exists('mhash')) {
return bin2hex(mhash(MHASH_SHA1, $str));
}
else {
$x = sha1_str2blks($string);
$w = Array(80);
$a = 1732584193;
$b = -271733879;
$c = -1732584194;
$d = 271733878;
$e = -1009589776;
for ($i = 0, $end = count($x); $i < $end; $i += 16) {
$olda = $a;
$oldb = $b;
$oldc = $c;
$oldd = $d;
$olde = $e;
for ($j = 0; $j < 80; $j++) {
if ($j < 16) $w[$j] = $x[($i + $j)];
else $w[$j] = sha1_rol(($w[($j - 3)] ^ $w[($j - 8)] ^ $w[($j - 14)] ^ $w[($j - 16)]), 1);
$t = sha1_add(sha1_add(sha1_rol($a, 5), sha1_ft($j, $b, $c, $d)), sha1_add(sha1_add($e, $w[$j]), sha1_kt($j)));
$e = $d;
$d = $c;
$c = sha1_rol($b, 30);
$b = $a;
$a = $t;
}
$a = sha1_add($a, $olda);
$b = sha1_add($b, $oldb);
$c = sha1_add($c, $oldc);
$d = sha1_add($d, $oldd);
$e = sha1_add($e, $olde);
}
return sha1_hex($a).sha1_hex($b).sha1_hex($c).sha1_hex($d).sha1_hex($e);
}
}
/**
* @desc alternative to the zero fill shift right operator
*/
function sha1_zeroFill($a, $b) {
$z = hexdec(80000000);
if ($z & $a) {
$a >>= 1;
$a &= (~ $z);
$a |= 0x40000000;
$a >>= ($b - 1);
}
else {
$a >>= $b;
}
return $a;
}
/**
* @desc conversion decimal to hexadecimal
* @param decnum integer
* @return hexstr string
*/
function sha1_hex($decnum) {
$hexstr = dechex($decnum);
if (wbb_strlen($hexstr) < 8) $hexstr = str_repeat('0', 8 - wbb_strlen($hexstr)).$hexstr;
return $hexstr;
}
/**
* @desc divides a string into 16 - word blocks
* @param str string
* @return blocks array
*/
function sha1_str2blks($str) {
$nblk = ((wbb_strlen($str) + 8) >> 6) + 1;
$blks = array($nblk * 16);
for ($i = 0; $i < $nblk * 16; $i++) $blks[$i] = 0;
for ($i = 0, $end = wbb_strlen($str); $i < $end; $i++) $blks[($i >> 2)] |= ord(wbb_substr($str, $i, 1)) << (24 - ($i % 4) * 8);
$blks[($i >> 2)] |= 0x80 << (24 - ($i % 4) * 8);
$blks[($nblk * 16 - 1)] = wbb_strlen($str) * 8;
return $blks;
}
/**
* @desc add integers, wrapping at 2^32. This uses 16 - bit operations internally
*/
function sha1_add($x, $y) {
$lsw = ($x & 0xFFFF) + ($y & 0xFFFF);
$msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);
return ($msw << 16) | ($lsw & 0xFFFF);
}
/**
* @desc Bitwise rotate a 32 - bit number to the left
*/
function sha1_rol($num, $cnt) {
return ($num << $cnt) | sha1_zeroFill($num, (32 - $cnt));
}
/**
* @desc Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft($t, $b, $c, $d) {
if ($t < 20) return ($b & $c) | ((~$b) & $d);
elseif ($t < 40) return $b ^ $c ^ $d;
elseif ($t < 60) return ($b & $c) | ($b & $d) | ($c & $d);
else return $b ^ $c ^ $d;
}
/**
* @desc Determine the appropriate additive constant for the current iteration
*/
function sha1_kt($t) {
if ($t < 20) return 1518500249;
elseif ($t < 40) return 1859775393;
elseif ($t < 60) return - 1894007588;
else return - 899497514;
}
}
?> |
Java | UTF-8 | 167 | 1.90625 | 2 | [] | no_license | package com.testtask.exception;
public class MazeBuildException extends AppException{
public MazeBuildException(String message) {
super(message);
}
}
|
C++ | UTF-8 | 2,192 | 3.296875 | 3 | [] | no_license | #include "List.h"
#include <cstdio>
#include <cstddef>
using namespace std;
List::List()
: _len(0)
{}
List::List(unsigned int _length)
: Array(_length), _len(_length)
{}
List::List(const List &other){
_len = other._len;
if (_len>0) {
_Array = new long [_len];
for (int i=0; i < _len; i++) _Array[i] = other._Array[i];
}
else _Array = NULL;
}
List::~List() {
_len = 0;
}
int List::setLength(unsigned int _length){
if (!_len) {
_Array = reCreate(_length);
_len = _length;
return 1;
}
else return 0;
}
int List::setElement(unsigned int pos, long val){
if (pos<_len) {
_Array[pos] = val;
return 1;
}
else {
printf("pos is illegal.\n");
return 0;
}
}
List& List::operator=(const List &list){
this -> setLength(list._len);
for (int i = 0; i < list._len; i++)
this -> _Array[i] = list._Array[i];
return *this;
}
List List::operator+(const List &other){
unsigned int min_len = (_len < other._len) ? _len : other._len;
List result(min_len);
for (int i = 0; i < min_len; i++)
result._Array[i] = _Array[i] + other._Array[i];
return result;
}
List& List::operator+=(const List &other){
unsigned int min_len = (_len < other._len) ? _len : other._len;
for (int i = 0; i < min_len; i++){
this->_Array[i] += other._Array[i];
}
return *this;
}
List& List::operator++(){
for (int i = 0; i < _len; i++) {
++_Array[i];
}
return *this;
}
List& List::operator++(int){
for (int i = 0; i < _len; i++)
_Array[i]++; // postfix++
return *this;
}
List& List::operator--(){
for (int i = 0; i < _len; i++) {
--_Array[i];
}
return *this;
}
List& List::operator--(int){
for (int i = 0; i < _len; i++) {
_Array[i]--;
}
return *this;
}
ostream& operator<<(ostream &out, List &list){
for (int i = 0; i < list._len; i++)
out << list._Array[i] << " ";
out << endl;
return out;
}
istream& operator>>(istream &in, List &list){
for (int i = 0; i < list._len; i++)
in >> list._Array[i];
return in;
}
|
JavaScript | UTF-8 | 2,136 | 3.046875 | 3 | [
"MIT"
] | permissive | 'use strict';
const client = require('./client.js');
var checkNotInsideDatabase = true;
var signinChecking = {
signinFunction: function (obj, res) {
let userName = obj.user;
let password = obj.pass;
let confirmPassword = obj.confirm;
client.query(`SELECT username FROM users;`)
.then(data => {
data.rows.forEach(v => {
if (v.username === userName) {
checkNotInsideDatabase = false;
let usernameError = `${userName} is alredy exist`;
res.render('pages/signupPages/signupError', { errorMessage: usernameError });
}
})
})
.then(() => {
if (password !== confirmPassword) {
// // Incorrect password!
let confirmError = `You should use same password`;
res.render('pages/signupPages/signupError', { errorMessage: confirmError });
}
if (password === confirmPassword && checkNotInsideDatabase===true) {
console.log('hello');
let SQL = `INSERT INTO users(username, password) VALUES ($1, $2);`;
let value = [userName, password];
return client.query(SQL, value).then(() => {
res.render('pages/signinPages/signin');
})
}
})
}
}
module.exports = signinChecking;
// /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.(com||net||org)$/g
// one word, or two words separated by dash or underscore , before the @ symbol
// - can contain numbers
// - can have any of the following top-level domains: .net, .com, or .org
// - no other special characters
// - no subdomains, ports, etc: must be of the form name@place.com, not name@sub.place.com:3000
// /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/g
//To check a password between 8 to 15 characters which contain at least one lowercase letter,
// one uppercase letter, one numeric digit, and one special character |
Java | UTF-8 | 460 | 2.15625 | 2 | [] | no_license | package org.pih.hivmigration.common.code;
import java.util.Arrays;
import java.util.List;
/**
* This corresponds to the hiv_exam_system_status.system values
*/
public enum PartnerReferralStatus implements CodedValue {
REFERRED("t"),
NOT_REFERRED("f"),
NO_PARTNER_IDENTIFIED("9");
private String value;
PartnerReferralStatus(String value) {
this.value = value;
}
@Override
public List<String> getValues() {
return Arrays.asList(value);
}
}
|
Java | UTF-8 | 1,075 | 3.15625 | 3 | [] | no_license | package Multiplayer.Sudoku.Protocol;
public class MovePacket extends Packet {
private int value;
private int row;
private int col;
public MovePacket(int value, int row, int col) {
super(PacketTypes.MOVE);
this.value = value;
this.row = row;
this.col = col;
super.setMessage(createMessage(value, row, col));
}
public MovePacket(byte[] encoded_message) {
super(encoded_message);
byte[] decoded_message = super.getMessage();
this.setValuesFromMessage(decoded_message);
}
public int getValue() {
return this.value;
}
public int getRow() {
return this.row;
}
public int getCol() {
return this.col;
}
private byte[] createMessage(int value, int row, int col) {
return new byte[]{
(byte) value, (byte) row, (byte) col
};
}
private void setValuesFromMessage(byte[] message) {
this.value = message[0];
this.row = message[1];
this.col = message[2];
}
} |
PHP | UTF-8 | 986 | 2.5625 | 3 | [] | no_license | <?php
namespace CaptchaRefresher\Service;
use Zend\Captcha\AbstractAdapter;
/**
* Description of CaptchaRefreshService
*
* @author David Contavalli <mauipipe@gmail.com>
* @copyright M.V. Labs 2013 - All Rights Reserved -
* You may execute and modify the contents of this file, but only within the scope of this project.
* Any other use shall be considered forbidden, unless otherwise specified.
* @link http://www.mvassociates.it
*/
class CaptchaService {
private $captcha;
public function __construct(AbstractAdapter $captcha) {
$this->captcha = $captcha;
}
public function generate(){
$captchaData = array();
$captchaData['id'] = $this->captcha->generate();
$captchaData['href'] = $this->captcha->getImgUrl().
$this->captcha->getId().
$this->captcha->getSuffix();
return $captchaData;
}
}
|
Markdown | UTF-8 | 4,719 | 4.25 | 4 | [
"MIT"
] | permissive | # [Medium][950. Reveal Cards In Increasing Order](https://leetcode.com/problems/reveal-cards-in-increasing-order/)
In a deck of cards, every card has a unique integer. You can order the deck in any order you want.
Initially, all the cards start face down (unrevealed) in one deck.
Now, you do the following steps repeatedly, until all cards are revealed:
1. Take the top card of the deck, reveal it, and take it out of the deck.
2. If there are still cards in the deck, put the next top card of the deck at the bottom of the deck.
3. If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.
The first entry in the answer is considered to be the top of the deck.
Example 1:
```text
Input: [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order doesn't matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal **2**, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].
We reveal **3**, and move 11 to the bottom. The deck is now [5,17,7,13,11].
We reveal **5**, and move 17 to the bottom. The deck is now [7,13,11,17].
We reveal **7**, and move 13 to the bottom. The deck is now [11,17,13].
We reveal **11**, and move 17 to the bottom. The deck is now [13,17].
We reveal **13**, and move 17 to the bottom. The deck is now [17].
We reveal **17**.
Since all the cards revealed are in increasing order, the answer is correct.
```
Note:
1. 1 <= A.length <= 1000
2. 1 <= A[i] <= 10^6
3. A[i] != A[j] for all i != j
## 思路
这是一个翻牌的有些。先把第一张拿掉,然后把第二张放到队尾,再拿掉第三张,第四张翻到队尾。以此类推。直到倒数第二张被拿掉,直接拿掉最后一张。这样翻过之后,拿掉的牌按照大小排列是有序的。
例如上面的抽调牌的顺序依次是[2,3,5,7,11,13,17] 是有序的。输出的数组是能够得到这个结果的数组。
由于输入的数组顺序是不定的,所有要先将输入数组进行排序。例如将[17,13,11,2,3,5,7],排序为[2,3,5,7,11,13,17],使其有序。
利用一个辅助数组,模拟这个翻牌的过程,用来构造所需要的一个数组。
观察这个翻牌的过程可以发现,第一次输出的顺序是可以预见的。分别是A[0], A[1],A[3],...,A[2n-1].可以排定这些数字。有序数组A按照顺序先将第一个元素放在待输出数组B的第一个位置上。接下来A移到下一个元素,而数组B则需要先跳过第二个元素,然后停再第三个元素上,将A的元素放入。这个行为持续到排满一半的元素以后,B已经来到了数组的末尾。

这个时候开始第二轮的输出。第一轮的时候,当2被拿掉的时候,被移到队尾的[13]这个时候已经重新回到了队列的前方,将要被拿掉。这个时候把B想象成一个环形链表。移动到队尾之后,重新回到0的位置,先判断一下是否没有被占用。如果被占用,挪到下一个元素,直到第一个没有被占用的元素,再重复上述的过程。判断是否要跳过一个元素,还是要对这个位置赋值。

然后再次重复这个过程,直到分配到倒数第二个元素完成。这个时候只剩下一个空余的位置,没有填满,这个时候可以直接填充这个位置即可。

## 代码
```csharp
public class Solution {
public int[] DeckRevealedIncreasing(int[] deck) {
if(deck.Length == 0 || deck.Length == 1) return deck;
int len = deck.Length;
int[] reveal = InitArray(len);
Array.Sort(deck);
bool skip = false;
int pos = 0;
for(int i = 0; i < len - 1; i++)
{
while(skip)
{
pos = MoveToNext(reveal, pos);
skip = false;
}
reveal[pos] = deck[i];
skip = true;
pos = MoveToNext(reveal, pos);
}
reveal[pos] = deck[len - 1];
return reveal;
}
private int[] InitArray(int len)
{
int[] reveal = new int[len];
for(int i = 0; i < len; i++)
{
reveal[i] = Int32.MinValue;
}
return reveal;
}
private int MoveToNext(int[] reveal, int pos)
{
while(true)
{
if(pos == reveal.Length - 1)
pos = 0;
else
pos += 1;
if(reveal[pos] == int.MinValue) break;
}
return pos;
}
}
```
|
Java | UTF-8 | 362 | 1.8125 | 2 | [] | no_license | package com.itheima.plugins_test.dao;
import com.itheima.plugins_test.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserXmlMapper {
@Select("select * from `user`")
List<User> findAll();
}
|
Python | UTF-8 | 321 | 2.84375 | 3 | [] | no_license | #Build-In Functions
#print()
#input()
#len()
#modules has to be inported first
import random, sys, os, math
random.randint(1, 10)
#oprionally not to print "random." each time infront function (but not recommended
import random
from random import *
randint(1, 10)
#to terminate running program
import sys
sys.exit()
|
Markdown | UTF-8 | 12,859 | 2.96875 | 3 | [
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | ---
layout: post
title: "茅于轼:以人为本,还是以国为本?"
date: 2010-05-11
author: 茅于轼
from: http://unirule.cloud/index.php?c=article&id=1121
tags: [ 天则观点 ]
categories: [ 天则观点 ]
---
<div class="article">
<div class="body-text">
<p align="left">
</p>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
俄罗斯小孩"阿尔捷姆&bull;萨韦利耶"在他六岁时被美国人,女护士托利&bull;汉森,从海参葳的儿童福利院收养,七岁时又被他的养母送回莫斯科,声称这孩子神经有毛病,所以不愿再养他了。这样的事原本是一件家庭纠纷,类似的各式各样的事多得很,比这更严重的事,酿出人身伤害的都不是没有。可是因为牵涉到两个国家的老百姓,就变成了国家之间的事,两国的外交官都出面说话,连总统都发了话了。媒体也推波助澜,变了一件国际大新闻。如果这事不涉及两个国家,实在是一件很普通的事,只能上当地新闻。这样的比较可以看出政治家和老百姓都愿意从国家的角度看问题,把简单的事弄复杂。人与人之间的事变成了国与国之间的事。究竟哪种看法对,哪种看法错。其分界点就在于"以人为本"还是"以国为本"。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
如果是"以人为本"就应该考虑当事人的利害,从人民的利益出发,找出最有利的解决办法。就萨韦利耶的案子来说,首先要考虑的是这孩子的前途,也应照顾他养母的要求。这里根本涉及不到国家的事。可如果是"以国为本",情况就非常不同。首先要考虑的是国家的利益,领土的完整等等。就算扯不上国家的利害,也得照顾国家的尊严。说到尊严,总是有文章可做的。俄罗斯的外长已经表示,要暂停美国家庭收养俄罗斯儿童的业务。俄罗斯总统从国家尊严的立场发话,严厉批评了那个美国养母。俄国政府已经决定暂停两国间的收养办法。这一来,本来高高兴兴可以完成收养手续的美国父母,只好等俄罗斯外长哪天发善心,批准继续这项业务。他们发动签名运动,征集了两万人的响应,要求尽快恢复收养业务。如果这样的事发生在一国内部,绝不会波及这么大,这么远。可为了贯彻"以国为本",就会有成千上万的人参与进来。这些热心人参与的结果不大会是使收养业务更完善,更容易,多半是手续更繁复,麻烦更多。最后老百姓就得做点牺牲。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
这确实是非常奇怪的事。当强调"以国为本"时,各种事物变得越来越复杂。本来是极简单的事,或者连简单都谈不上,完全是无中生有的事,也会吵得轰轰烈烈,酿成激烈的冲突。比如讲,钓鱼台的领土冲突,就是一例。这个地方既没有居民,又没有资源。如果是"以人为本",谁也不会去注意它。可是因为"以国为本",就变成双方寸土不让的国家事务。事实上就有人为此而牺牲。他的牺牲显然不是为了某个人,而是为了国家。"以人为本"和"以国为本"的区分就在这里。还好,钓鱼台的冲突死的人不多。还有别的一些类似的冲突,也是为了争夺没有多少价值的领土,双方都不惜兴师动众,大打出手,牺牲的人就不是几个几十,而是成百上千,甚至几十万。这些人的死亡到底是为了什么。现在好像还有些理由可说,但是随着历史的发展,这些理由越来越淡去了。再过一二百年,恐怕就觉得实在无法理解。朝鲜战争,珍宝岛之战,中印之战,抗越自卫之战,还有支援越南之战等等。死掉人恐怕远远不止是十万,二十万。我们从来没有为死去的人想一想,他们年轻的一生就此被毁灭了。死去的人不会说话了。我们现在还活着,还有机会说话。是不是应该为死去的人想一想?他们是为国捐躯,值得大家敬佩。但是捐躯的理由何在,很少人会去追究。将来再有类似的事大家是不是还准备牺牲。如果是你,你愿意为此而死吗?发动战争的人一般自己是不上前线的,死人是死别人,所以叫得很响。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
如果是因为"以人为本"而为国捐躯,那是完全应该的。比如日本人侵略中国,要把中国人当亡国奴,我们坚决不干。因为我们的人受到了伤害。我们要誓死捍卫祖国。这不是国家的尊严,而是百姓的死活。如果只是国家的尊严,与百姓的利益无关,我们要不要关心就是值得讨论的问题。这样的看法恐怕很难为大多数人接受。因为"以国为本"的思想已经根深蒂固,很难扭转。这个思想已经贯彻了几千年,谁也不会去想一想这里有什么问题。由于以国为本的误导,枉死了成亿的人口。他们的死没有任何价值。可是因为国家的观念太强烈了,以至于连性命都显得不重要了。其实这完全是本末倒置。人的生命才是最最重要的,以人为本是对的。今天是我们重新考虑事物的主次问题的时候了。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
今年是越南战争结束
</span>
<span style="font-size: 9pt">
35
</span>
<span style="font-size: 9pt">
周年。美国再一次举行纪念会,吊念越战中死去的五万多美国人。今天看来这些人死得太冤了。美国参与越战打了败仗,并没有防止越南成为共产主义国家。更没想到改革后的越南,越来越走上资本主义的道路。早知今日何必当初。也许越南也在吊念越战牺牲的人。越南不会吊念越战中死的美国人,美国也不会吊念越战中死的越南人,因为"以国为本",各自有各自的政治目的。但是如果"以人为本",越战中死的人都是人,死得都很冤枉。最近(
</span>
<span style="font-size: 9pt">
2010
</span>
<span style="font-size: 9pt">
年
</span>
<span style="font-size: 9pt">
4
</span>
<span style="font-size: 9pt">
月
</span>
<span style="font-size: 9pt">
30
</span>
<span style="font-size: 9pt">
日
</span>
<span style="font-size: 9pt">
)海南岛建成了海南解放的烈士纪念碑,纪念海南解放战争中死去的烈士。当然,其中不包括国民党军队里死的人。战争的双方都有各自的理由,都说对方是错的,是反动的,是违反人们利益的。到底谁说得对,并不是几句话就能说得清的。但是就战死的人来说,他们都是平民百姓,对他们而言最重要的不是谁对谁错的问题,而是自己个人的死活问题。政府把他们动员来到战场上,面对敌方的武装,已经不容选择。唯一的一条路就是杀死对方。因为你不杀死对方,对方就会杀死你。他们被迫去杀一个和自己相仿佛的一个年轻人。他也有父母妻子,有温暖的家庭,有个人的抱负。但是到了战场上,这一切都被抛到脑后。杀戮是唯一的出路。因为这里是"以国为本"。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
如果摊开每天的报纸看,一大堆的新闻,轰轰烈烈,热热闹。,大家关注的事情中有多少是"以人为本"作为出发点的?又有多少是"以国为本"作为出发点的?你仔细想一想一定会发现大多数的热点新闻都是政治家制造出来的,和老百姓根本无关。拿今天(
</span>
<span style="font-size: 9pt">
2010.5.8.
</span>
<span style="font-size: 9pt">
)的参考消息为例,日中两国东海调查船对峙(互相跟踪),土耳其出口军火,俄国重振黑海舰队,天安号被击沉的责任,美俄核能纠纷,欧盟
</span>
<span style="font-size: 9pt">
-
</span>
<span style="font-size: 9pt">
拉美峰会危机,金正日访华,没有一件是从百姓利益出发的,大多数是政治家挑起的事端,没事找事。有一些和百姓的利益间接相关,但是解决的方法却是南辕北撤,把事情越搞越复杂,越困难。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
今天最使人担忧的恐怕还不是战争,而是恐怖主义,一些人身上绑了炸弹去炸另外一些无辜的人。损人损己,对任何人都不利。这些行为用最简单的理性去分析就能看出其荒谬性。然而确实有人为这种极端荒谬的目的而牺牲。幸亏这样的人为数不多,大家还能勉强活着。可是类似于恐怖分子的行为,稍微改变一点形式,以一种隐蔽的方式进行,就很容易蒙骗群众。一个最近的例子就是我国以文化革命为代表的阶级斗争。为了让无产阶级的政权永不变色,叫大家斗大家。全国人民都上当受骗。居然在一个十亿人口的大国中畅通无阻,搞得几十万人自杀,几百万人妻离子散,还有几十万人搞武斗,动用机枪大炮,互相残杀。其理论依据就是"以国为本"。如果大家都明白"以人为本",就绝不至于闹到如此荒谬的地步。现在文革已经过去,大家也不会自己斗自己。但是"以国为本"的思想并没有根除,它随时随地能够反扑,叫老百姓遭殃。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
大家会问,何以"以国为本"的思想如此根深蒂固?原因很复杂。但是归根结底,责任在政治家身上。是他们不断宣传这种思想,强化这种思想,要求百姓为国牺牲。其实是为他们这些人去牺牲,使"以国为本"固化在百姓的脑袋里。以便他们容易动员群众为他们所用,达到他们个人的目的。在独裁国家,政治家的首要目的就是继续统治这个国家,在民主国家里政治家的目的就是强调政治的重要性,给他们花更多的钱,更多的风光。表面上都是为了老百姓,其实是为了他们自己。只有慢慢地用"以人为本"取代了"以国为本"的想法时这种关系才能够改变。政治家不能再用"以国为本"欺骗百姓,做任何一件事必须符合百姓的利益,哪怕未必符合国家的利益。如果国家利益和百姓利益相矛盾时,只有牺牲国家利益为人民,而不许可牺牲人民利益为国家。到最后国家的观念越来越消退,人民和社区组织将取代国家。到那时候战争绝不会发生,更没有谁能够制造原子弹,也不会制造航母,连机关枪也没有用处,在武器方面有手枪就足够对付强盗小偷。那时候兵工厂,军事要地,国防要塞,军校,军事科研,兵营,阅兵都成为过去。这时候世界和平才有最后的保障。当然,这样的目标距离我们很远很远。但如果人类还能生存一二百年,没有被核战争消灭掉,最后的世界必然是这样的一种结构。这才能保障世界的持久和平。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
<span style="font-size: 9pt">
说了一大套大道理,让我们回到萨韦利耶的案子上来看。为什么外交家,总统都对这样的小事那么感兴趣?他们日理万机,还用得着为此小事而操心吗?是的,对他们而言这事并不小,它关系到由他们代表的国家尊严。我估计为此事将会召开一系列的会议,会有几十个人坐头等舱飞机,飞来飞去,住高级宾馆,花纳税人的钱,各自用"以国为本"的精神辩论是非曲直。最后得出的结果不大会是从百姓的利益出发的,而是国家尊严超过了一切。倒霉的是老百姓。他们想自由从事的事因此做不成了。还好,这终究是一件小事。如果是战争与和平的大事,其规律也一样。这就值得我们担心了。
</span>
</div>
<div style="text-indent: 18pt">
</div>
<div style="text-indent: 18pt">
</div>
</div>
</div>
|
Markdown | UTF-8 | 262 | 2.765625 | 3 | [
"MIT"
] | permissive | # century-club
A quick 5 minute app that tracks drinks for a century club game on new year's eve.
A countdown timer tells you when you need to take your next drink.
## Installation
```bower install ```
Then, open the index.html file in your browser. Simple.
|
Java | UTF-8 | 477 | 2.015625 | 2 | [] | no_license | package com.gavinandre.androidherosamples.chaptersix.canvaspaintbase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.gavinandre.androidherosamples.R;
/**
* Created by gavinandre on 17-5-6.
*/
public class CanvasPaintActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_canvas_paint);
}
}
|
C# | UTF-8 | 1,800 | 2.515625 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PrefabPreview : MonoBehaviour {
public Transform prefabContainer;
public Text currentPrefabName;
private Transform[] prefabs;
private Transform activePrefab;
private int prefabIndex = 0;
// Use this for initialization
void Start () {
prefabs = new Transform[prefabContainer.childCount];
prefabs = GetComponentsInDirectChildren<Transform> (prefabContainer);
activePrefab = prefabs [prefabIndex];
activePrefab.gameObject.SetActive (true);
currentPrefabName.text = activePrefab.name;
}
public void NextPrefab () {
activePrefab.gameObject.SetActive (false);
prefabIndex++;
if (prefabIndex > prefabs.Length - 1) {
prefabIndex = 0;
}
activePrefab = prefabs [prefabIndex];
activePrefab.gameObject.SetActive (true);
currentPrefabName.text = activePrefab.name;
}
public void PrevPrefab () {
activePrefab.gameObject.SetActive (false);
prefabIndex--;
if (prefabIndex < 0) {
prefabIndex = prefabs.Length - 1;
}
activePrefab = prefabs [prefabIndex];
activePrefab.gameObject.SetActive (true);
currentPrefabName.text = activePrefab.name;
}
// Get content pages / returns only 1st level components
private static T[] GetComponentsInDirectChildren<T>(Transform t) {
int index = 0;
foreach (Transform t2 in t) {
if (t2.GetComponent<T>() != null) {
index++;
}
}
T[] returnArray = new T[index];
index = 0;
foreach (Transform t2 in t) {
if (t2.GetComponent<T>() != null) {
returnArray[index++] = t2.GetComponent<T>();
}
}
return returnArray;
}
void Update () {
if(Input.GetKeyDown(KeyCode.RightArrow)) {
NextPrefab ();
}
if(Input.GetKeyDown(KeyCode.LeftArrow)) {
PrevPrefab ();
}
}
}
|
C# | UTF-8 | 2,993 | 2.65625 | 3 | [] | no_license | using collegeWebSite.App_Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace collegeWebSite
{
public partial class Home : System.Web.UI.Page
{
public string NewsTicker = string.Empty;
public string ImportantLinks = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String sNews = string.Empty;
String sLinks = string.Empty;
using (DataTable dt = GetAllatestNews())
{
foreach (DataRow dr in dt.Rows)
{
if (dr["nNewsPriority"].ToString() == "4")
sNews = sNews + string.Format("<li><a href='{0}' target='_blank' style='font-size: 16px; color: #0ba9f5;'><strong><em>{1}</em></strong></a></li>", dr["sNewsDescription"].ToString(), dr["sNewsTitle"].ToString());
else
sNews = sNews + string.Format("<li><a href='{0}' target='_blank'>{1}</a></li>", dr["sNewsDescription"].ToString(), dr["sNewsTitle"].ToString());
}
}
using (DataTable dt = GetImportantLinks())
{
foreach (DataRow dr in dt.Rows)
{
sLinks = sLinks + string.Format("<li><i class='fa-li fa fa-check-square'></i><a href='{0}' target='_blank'>{1}</a></li>", dr["sLinkURL"].ToString(), dr["sLinkDescripation"].ToString());
}
}
//Assign fetched result to global variable 'NewsTicker'
NewsTicker = sNews.ToString();
ImportantLinks = sLinks.ToString();
}
}
private DataTable GetAllatestNews()
{
DataTable _dt = null;
DataAccess _DataAccess = new DataAccess();
StudentInformation _Student = new StudentInformation();
try
{
_dt = _Student.GetLatestNEWS(0);
}
catch (Exception)
{
if (_DataAccess != null) { _DataAccess.RollBack(); _DataAccess.CloseConnection(false); }
}
finally
{
}
return _dt;
}
private DataTable GetImportantLinks()
{
DataTable _dt = null;
DataAccess _DataAccess = new DataAccess();
StudentInformation _Student = new StudentInformation();
try
{
_dt = _Student.GetImportantLinks();
}
catch (Exception)
{
if (_DataAccess != null) { _DataAccess.RollBack(); _DataAccess.CloseConnection(false); }
}
finally
{
}
return _dt;
}
}
} |
Swift | UTF-8 | 2,322 | 2.625 | 3 | [] | no_license | //
// LaunchViewModel.swift
// ShellHacks NASA
//
// Created by Peter Khouly on 9/25/21.
//
import Foundation
import SwiftUI
import SwiftyJSON
import Alamofire
class LaunchViewModel: ObservableObject {
@Published var rockets: [Rocket] = []
let dateFormatter = DateFormatter()
@Published var failed = false
init() {
load()
}
func load() {
self.failed = false
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
rockets.removeAll()
AF.request("http://ll.thespacedevs.com/2.2.0/launch/upcoming/?format=json", method: .get, encoding: JSONEncoding.default, headers: nil).validate(statusCode: 200 ..< 299).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let ships = json["results"]
// print(ships)
for (_, subJson):(String, JSON) in ships {
let shipName = subJson["name"].stringValue
let date = subJson["net"].stringValue //2021-09-27T06:20:00Z format date
let owner = subJson["launch_service_provider"]["name"].stringValue
let typeOfOwner = subJson["launch_service_provider"]["type"].stringValue
let missionName = subJson["mission"]["name"].stringValue
let missionDesc = subJson["mission"]["description"].stringValue
let launchPad = subJson["pad"]["name"].stringValue
let image = subJson["image"].stringValue
self.rockets.append(Rocket(name: shipName, date: self.dateFormatter.date(from: date), owner: owner, typeOfOwner: typeOfOwner, missionName: missionName, missionDesc: missionDesc, launchPad: launchPad, image: image))
}
case .failure(_):
self.failed = true
print("failed")
break
}
}
}
}
struct Rocket: Identifiable {
let id = UUID()
var name: String
var date: Date?
var owner: String
var typeOfOwner: String
var missionName: String
var missionDesc: String
var launchPad: String
var image: String
}
|
Java | UTF-8 | 9,168 | 1.929688 | 2 | [] | no_license | import org.restlet.data.Form;
import gr.gradle.demo.conf.Configuration;
import gr.gradle.demo.data.DataAccess;
import gr.gradle.demo.data.model.Product;
import gr.gradle.demo.data.model.Price;
import gr.gradle.demo.data.model.Result;
import gr.gradle.demo.data.Limits;
import com.google.gson.Gson;
import gr.gradle.demo.data.model.Product;
import org.restlet.data.MediaType;
import org.restlet.representation.WriterRepresentation;
import org.restlet.data.Status;
import org.restlet.engine.adapter.HttpRequest;
import org.restlet.representation.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;
import java.util.Map;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import org.restlet.util.*;
import org.restlet.data.Header;
import org.restlet.data.Form;
import gr.gradle.demo.conf.Configuration;
import gr.gradle.demo.data.DataAccess;
import gr.gradle.demo.data.model.Product;
import org.restlet.data.Status;
import org.restlet.engine.adapter.HttpRequest;
import org.restlet.representation.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.restlet.engine.header.*;
import java.util.HashMap;
import java.util.Optional;
import java.util.Map;
import java.util.*;
import org.restlet.util.*;
import java.lang.Object;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.restlet.data.Header;
public class WTF extends HttpServlet{
private final DataAccess dataAccess = Configuration.getInstance().getDataAccess();
public String get(String str_dateFrom,String str_dateTo,String str_products,String str_shops) throws ResourceException {
int start,count,i,j;
String str_count = null;
String str_start = null;
String status = null;
String str_geodist = null;
String str_Lng = null;
String str_Lat = null;
String sort = null;
String str_tags = null;
String inner_sort="price|ASC";
try{
//count check
if (str_count == null)
count = 20;
else
count = Integer.parseInt(str_count);
}catch(Exception e){
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Wrong count value");
}
try{
//start check
if (str_start==null)
start = 0;
else
start = Integer.parseInt(str_start);
}catch(Exception e){
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Wrong start value");
}
//sort check
String[] sort_list;
if (sort==null){
sort_list = new String[1];
sort_list[0] = "price|ASC";
}
else{
String[] parts = sort.split(",");
sort_list = new String[parts.length];
System.out.println(parts.length);
for (i=0;i<parts.length;i++){
sort = parts[i];
if (!(sort!="geo.dist|ASC" && sort!="geo.dist|DESC" && sort!="price|ASC" && sort!="price|DESC"
&& sort!="date|ASC" && sort!="date|DESC"))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Wrong sort value");
if ((sort.equals("geo.dist|ASC") || sort.equals("geo.dist|DESC"))
&& (str_Lng==null || str_Lat==null || str_geodist==null))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Wrong sort value");
if (sort.equals("price|DESC"))
inner_sort=sort;
System.out.println("ftasame");
sort_list[i]=sort;
}
}
System.out.println("ftanw1");
//check geo infos
int geoDist; Double Lng=null,Lat=null;
geoDist=0;
System.out.println(str_Lng);
if (!((str_Lng==null && str_Lat==null && str_geodist==null) || (str_Lng!=null && str_Lat!=null && str_geodist!=null)))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Need all of geo infos or none");
else if(str_Lng!=null){
try{
System.out.println("gamwwwwww");
geoDist = Integer.parseInt(str_geodist);
Lng = Double.parseDouble(str_Lng);
Lat = Double.parseDouble(str_Lat);
}catch(Exception e){
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Wrong geo values");
}
}
else
System.out.println("hellooo");
System.out.println("ftanw2");
//check dates
Date date1=null;
Date date2=null;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
if (!((str_dateFrom==null && str_dateTo==null) || (str_dateFrom!=null && str_dateTo!=null)))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Need all of date infos or none");
else if(str_dateFrom!=null){
if(!isValidDate(str_dateFrom) || !isValidDate(str_dateTo))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid date values");
try{
date1=format.parse(str_dateFrom);
date2=format.parse(str_dateTo);
if (date2.before(date1))
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Date from < Date to");
}catch(Exception e){
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid dates");
}
}
else{
Calendar calendar = Calendar.getInstance();
str_dateFrom = format.format(calendar.getTime());
str_dateTo = format.format(calendar.getTime());
}
System.out.println("ftanw3");
//check shops
Long[] shopsids=null;
if (str_shops!=null){
String[] parts = str_shops.split(",");
shopsids = new Long[parts.length];
for(i=0;i<parts.length;i++){
shopsids[i] = Long.parseLong(parts[i]);
}
}
System.out.println("ftanw4");
//check products
Long[] productids = null;
if (str_products!=null){
String[] parts = str_products.split(",");
productids = new Long[parts.length];
for(i=0;i<parts.length;i++){
productids[i] = Long.parseLong(parts[i]);
}
}
System.out.println("ftanw5");
//check tags
String[] tags = null;
if (str_tags!=null){
String[] parts = str_tags.split(",");
tags = new String[parts.length];
for(i=0;i<parts.length;i++){
tags[i] = parts[i];
}
}
//bazw ta tags se hashmap
HashMap<String,Integer> tags_map = new HashMap<String,Integer>();
if (tags!=null){
for(i=0;i<tags.length;i++){
tags_map.put(tags[i],1);
}
}
System.out.println("ftanw6");
System.out.println(geoDist);
List<Result> results = dataAccess.getResults(new Limits(start, count),sort_list,geoDist,Lng,Lat,shopsids,productids,tags,str_dateFrom,str_dateTo);
Map<String, Object> map = new HashMap<>();
//elegxos gia tags
List<Result> results_aftertags = new ArrayList<Result>(); Result curr; String[] tags_array;
if (tags!=null){
System.out.println("brhka tags");
for(i=0;i<results.size();i++){
curr = results.get(i);
tags_array = curr.gettags().split(",");
for(j=0;j<tags_array.length;j++){
if(tags_map.containsKey(tags_array[j])){
results_aftertags.add(curr);
break;
}
}
}
}
else
results_aftertags = results;
results = results_aftertags;
if (results.size()==0){
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "Not found");
}
try{
HashMap<Double, List<Result>> price_map = new HashMap<>();
Double price_help; List<Result> help_list;
ArrayList<Double> arlist_prices = new ArrayList<Double>();
for(i = 0;i <results.size();i++){
price_help = results.get(i).getprice();
if (price_map.containsKey(price_help))
help_list = price_map.get(price_help);
else{
arlist_prices.add(price_help);
help_list = new ArrayList<Result>();
price_map.put(price_help,help_list);
}
help_list.add(results.get(i));
}
//sorting prices right
LinkedHashMap<Double, List<Result>> final_hmap = new LinkedHashMap<>();
if (inner_sort.equals("price|ASC"))
Collections.sort(arlist_prices);
else
Collections.sort(arlist_prices, Collections.reverseOrder());
for(i=0;i<arlist_prices.size();i++){
final_hmap.put(arlist_prices.get(i),price_map.get(arlist_prices.get(i)));
}
map.put("start", start);
map.put("count", count);
map.put("total", final_hmap.size());
map.put("prices",final_hmap);
//return null;
Gson gson = new Gson();
String json = gson.toJson(map);
return json;
}catch(Exception e){
System.out.println(e);
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid values eksoterika");
}
}
boolean isValidDate(String input) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
try {
System.out.println(format.parse(input));
return true;
}
catch(ParseException e){
return false;
}
}
} |
PHP | UTF-8 | 411 | 2.90625 | 3 | [] | no_license | <html>
<head>
<title> User Count </title>
</head>
<body>
<?php
$counterfile = "./counter.txt";
$f = fopen($counterfile, "r+");
$counter = fgets($counterfile);
$counter++;
fwrite($counterfile, $counter);
fclose($f);
echo "You are visitor number $counter to this site";
?>
</body>
</html> |
C | UTF-8 | 4,582 | 3.28125 | 3 | [] | no_license | //
// day07.c
// day07
//
// Created by Brandon Holland on 2018-12-03.
// Copyright © 2018 Brandon Holland. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
typedef struct step step;
struct step
{
char id;
int working;
int completed;
int seconds;
step *dependencies[26];
};
step *createNewStep(char id)
{
step *newStep = malloc(sizeof(step));
newStep->id = id;
newStep->working = 0;
newStep->completed = 0;
newStep->seconds = id - 4;
memset(newStep->dependencies, 0, sizeof(step *) * 26);
return newStep;
}
int countStepIncompleteDependencies(step *s)
{
int c = 0;
for(int i = 0; i < 26; i++)
{
step *d = s->dependencies[i];
if(d && !d->completed)
{ c++; }
}
return c;
}
int main(int argc, char *argv[])
{
//Argument check
if (argc < 2)
{
printf("usage: day07 <INPUT>\n");
exit(0);
}
//Initialize steps
step *steps[26];
memset(steps, 0, sizeof(step *) * 26);
//Parse steps and build dependency graph
FILE *file = fopen(argv[1], "r");
char contextStepId;
char dependencyStepId;
while(fscanf(file, "Step %c must be finished before step %c can begin. ", &dependencyStepId, &contextStepId) == 2)
{
//Get dependency step and if it doesn't exist...
step *dependencyStep = steps[dependencyStepId - 65];
if(!dependencyStep)
{
//Create new step and add it to steps
dependencyStep = createNewStep(dependencyStepId);
steps[dependencyStepId - 65] = dependencyStep;
}
//Get context step and if it doesn't exist...
step *contextStep = steps[contextStepId - 65];
if(!contextStep)
{
//Create new step and add it to steps
contextStep = createNewStep(contextStepId);
steps[contextStepId - 65] = contextStep;
}
//Add dependency to context step
contextStep->dependencies[dependencyStepId - 65] = dependencyStep;
}
fclose(file);
//Find order of steps
printf("part1: order of steps = ");
for(int i = 0; i < 26; i++)
{
step *s = steps[i];
if(s && !s->completed && countStepIncompleteDependencies(s) == 0)
{
s->completed = 1;
i = -1;
printf("%c", s->id);
}
}
printf("\n");
//Reset step completion
for(int i = 0; i < 26; i++)
{
step *s = steps[i];
if(s)
{ s->completed = 0; }
}
//Initialize workers
step *workers[5];
memset(workers, 0, sizeof(step *) * 5);
//Find total number of seconds to complete steps
int secondsTotal = 0;
for(;;)
{
//Iterate through each worker
int working = 0;
for(int i = 0; i < 5; i++)
{
//Attempt to get worker
step *w = workers[i];
//If worker is working and has completed
if(w && w->seconds == 0)
{
//Mark as completed and release worker
w->completed = 1;
w = workers[i] = NULL;
}
//If worker is available
if(!w)
{
//Iterate through each step
for(int j = 0; j < 26; j++)
{
//Get step and if it exists, is not completed, not being worked on, and has no outstanding dependencies...
step *s = steps[j];
if(s && !s->completed && !s->working && countStepIncompleteDependencies(s) == 0)
{
//Assign worker step and mark it as being worked on
w = s;
w->working = 1;
workers[i] = s;
break;
}
}
}
//If worker has been assigned a step
if(w)
{
//Do work
w->seconds--;
working = 1;
}
}
//If no workers are working, we are done!
if(!working)
{
secondsTotal--;
break;
}
//Increment number of seconds passed
secondsTotal++;
}
printf("part2: total seconds to assemble = %d\n", secondsTotal);
//Cleanup
for(int i = 0; i < 26; i++)
{ free(steps[i]); }
return 0;
}
|
Java | UTF-8 | 1,960 | 3.421875 | 3 | [] | no_license | package com.playground;
import java.util.HashSet;
import java.util.Set;
//rate limiting using token bucket filter. this algorithm is used for shaping network traffic flow. It is also known as leaky bucket algorithm
//implementing rate limiting using a naive token bucket filter algorithm
public class TokenBucketFilter {
private int MAX_TOKEN;
private long lastRequestTime = System.currentTimeMillis();
long possibleToken = 0;
public TokenBucketFilter(int maxSize){
this.MAX_TOKEN=maxSize;
}
synchronized void getToken() throws InterruptedException{
// Divide by a 1000 to get granularity at the second level.
possibleToken+= (System.currentTimeMillis()-lastRequestTime)/1000;
if(possibleToken>MAX_TOKEN){
possibleToken=MAX_TOKEN;
}
if(possibleToken==0){
Thread.sleep(1000);
}else{
possibleToken--;
}
lastRequestTime=System.currentTimeMillis();
System.out.println("Granted " +Thread.currentThread().getName()+ "token at " + System.currentTimeMillis()/1000);
}
public static void runTestMaxTokenIs1() throws InterruptedException{
Set<Thread> allThreads = new HashSet<>();
final TokenBucketFilter tokenBucketFilter = new TokenBucketFilter(1);
for(int i=0; i<10; i++){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try{
tokenBucketFilter.getToken();
}catch (InterruptedException ie) {
System.out.println("We have a problem");
}
}
});
thread.setName("Thread_" + (i+1));
allThreads.add(thread);
}
for(Thread t: allThreads){
t.start();
}
for(Thread t: allThreads){
t.join();
}
}
}
|
Rust | UTF-8 | 137 | 2.640625 | 3 | [] | no_license | fn main() {
let a=[-1,-1,3];
let b=a.into_iter().skip_while(|x| **x<0).cloned().collect::<Vec<i32>>();
println!("{:?}",b);
}
|
Java | UTF-8 | 3,111 | 2.703125 | 3 | [] | no_license | package com.yesway.wechat.platform.message;
import java.util.ArrayList;
import java.util.List;
public class NewsMessage extends BaseMessage {
// 图文消息列表
private List<Article> articles = new ArrayList<Article>();
public NewsMessage() {
msgType = "news";
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
public int getArticleCount() {
return articles.size();
}
public String buildXmlMessage() {
StringBuilder result = new StringBuilder();
result.append("<xml>");
result.append("<ToUserName><![CDATA[" + toUserName + "]]></ToUserName>");
result.append("<FromUserName><![CDATA[" + fromUserName + "]]></FromUserName>");
result.append("<CreateTime>" + createTime + "</CreateTime>");
result.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");
result.append("<ArticleCount>" + getArticleCount() + "</ArticleCount>");
result.append("<Articles>");
for (Article article : articles) {
result.append("<item>");
result.append("<Title><![CDATA[" + article.getTitle() + "]]></Title>");
result.append("<Description><![CDATA[" + article.getDescription() + "]]></Description>");
result.append("<PicUrl><![CDATA[" + article.getPicUrl() + "]]></PicUrl>");
result.append("<Url><![CDATA[" + article.getUrl() + "]]></Url>");
result.append("</item>");
}
result.append("</Articles>");
result.append("</xml>");
return result.toString();
}
public String buildJsonMessage() {
StringBuilder result = new StringBuilder();
result.append("{");
result.append("\"touser\":\"" + toUserName + "\",");
result.append("\"msgtype\":\"" + msgType + "\",");
result.append("\"news\":{\"articles\":[");
for (int i = 0; i < articles.size(); i++) {
Article article = articles.get(i);
result.append("{");
result.append("\"title\":\"" + article.getTitle() + "\",");
result.append("\"description\":\"" + article.getDescription() + "\",");
result.append("\"url\":\"" + article.getUrl() + "\",");
result.append("\"picurl\":\"" + article.getPicUrl() + "\"");
result.append("}");
if (i < articles.size() - 1) {
result.append(",");
}
}
result.append("]}");
result.append("}");
return result.toString();
}
public static void main(String[] args) {
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName("toUser");
newsMessage.setFromUserName("fromUser");
newsMessage.setCreateTime("12345678");
newsMessage.setMsgType("news");
Article article1 = new Article();
article1.setTitle("title1");
article1.setDescription("description1");
article1.setPicUrl("picurl");
article1.setUrl("url");
newsMessage.getArticles().add(article1);
Article article2 = new Article();
article2.setTitle("title");
article2.setDescription("description");
article2.setPicUrl("picurl");
article2.setUrl("url");
newsMessage.getArticles().add(article2);
// 被动响应消息
System.out.println(newsMessage.buildXmlMessage());
// 发送客服消息
System.out.println(newsMessage.buildJsonMessage());
}
}
|
TypeScript | UTF-8 | 766 | 2.59375 | 3 | [
"MIT"
] | permissive | import IBaseRequest from "../../IBaseRequest";
import convroute from "../convroute";
interface IRequest extends IBaseRequest {
params: {
appId: string;
};
}
export default convroute({
path: "/apps/:appId",
method: "get",
description: "Get app",
tags: ["apps"],
parameters: [
{
name: "appId",
in: "path",
required: true,
type: "string"
}
],
responses: {
"200": { description: "Returns the app" },
"404": { description: "App not found" }
},
handler: async (req: IRequest, res) => {
const getApp = req.makeUsecase("getApp");
const app = await getApp.exec(req.params.appId);
res.status(200).send(app);
}
});
|
Markdown | UTF-8 | 9,479 | 2.78125 | 3 | [
"MIT"
] | permissive |
## 十三經
##### 孟子
`公孫丑下`
* * *
孟子曰:「天時不如地利,地利不如人和。三里之城,七里之郭,環而攻之而不勝;夫環而攻之,必有得天時者矣,然而不勝者,是天時不如地利也。城非不高也,池非不深也,兵革非不堅利也,米粟非不多也,委而去之,是地利不如人和也。故曰:域民不以封疆之界,固國不以山谿之險,威天下不以兵革之利。得道者多助,失道者寡助。寡助之至,親戚畔之;多助之至,天下順之。以天下之所順,攻親戚之所畔,故君子有不戰,戰必勝矣。」
孟子將朝王。王使人來曰:「寡人如就見者也,有寒疾,不可以風;朝將視朝,不識可使寡人得見乎?」
對曰:「不幸而有疾,不能造朝。」
明日出弔於東郭氏。公孫丑曰:「昔者辭以病,今日弔,或者不可乎?」
曰:「昔者疾,今日愈,如之何不弔?」
王使人問疾,醫來。孟仲子對曰:「昔者有王命,有采薪之憂,不能造朝。今病小愈,趨造於朝;我不識能至否乎?」
使數人要於路曰:「請必無歸,而造於朝。」
不得已而之景丑氏宿焉。
景子曰:「內則父子,外則君臣,人之大倫也。父子主恩,君臣主敬。丑見王之敬子也,未見所以敬王也。」
曰:「惡!是何言也!齊人無以仁義與王言者,豈以仁義為不美也?其心曰『是何足與言仁義也』云爾,則不敬莫大乎是。我非堯舜之道不敢以陳於王前,故齊人莫如我敬王也。」
景子曰:「否,非此之謂也。《禮》曰:『父召無諾;君命召,不俟駕。』固將朝也,聞王命而遂不果,宜與夫禮若不相似然。」
曰:「豈謂是與?曾子曰:『晉楚之富,不可及也。彼以其富,我以吾仁;彼以其爵,我以吾義,吾何慊乎哉?』夫豈不義而曾子言之?是或一道也。天下有達尊三:爵一,齒一,德一。朝廷莫如爵,鄉黨莫如齒,輔世長民莫如德。惡得有其一,以慢其二哉?故將大有為之君,必有所不召之臣;欲有謀焉則就之。其尊德樂道,不如是不足以有為也。故湯之於伊尹,學焉而後臣之,故不勞而王;桓公之於管仲,學焉而後臣之,故不勞而霸;今天下地醜德齊,莫能相尚。無他,好臣其所教,而不好臣其所受教。湯之於伊尹,桓公之於管仲,則不敢召;管仲且猶不可召,而況不為管仲者乎?」
陳臻問曰:「前日於齊,王餽兼金一百而不受;於宋,餽七十鎰而受;於薛,餽五十鎰而受。前日之不受是,則今日之受非也;今日之受是,則前日之不受非也;夫子必居一於此矣!」
孟子曰:「皆是也。當在宋也,予將有逺行;行者必以贐,辭曰『餽贐』,予何為不受?當在薛也,予有戒心,辭曰『聞戒故為兵餽之』,予何為不受?若於齊則未有處也。無處而餽之,是貨之也;焉有君子而可以貨取乎?」
孟子之平陸,謂其大夫曰:「子之持戟之士,一日而三失伍,則去之否乎?」
曰:「不待三。」
「然則子之失伍也亦多矣。凶年饑歲,子之民老羸轉於溝壑,壯者散而之四方者幾千人矣。」
曰:「此非距心之所得為也。」
曰:「今有受人之牛羊而為之牧之者,則必為之求牧與芻矣。求牧與芻而不得,則反諸其人乎?抑亦立而視其死與?」
曰:「此則距心之罪也。」
他日,見於王曰:「王之為都者,臣知五人焉。知其罪者,惟孔距心。」為王誦之。
王曰:「此則寡人之罪也。」
孟子謂蚔鼃曰:「子之辭靈丘而請士師,似也,為其可以言也。今既數月矣,未可以言與?」
蚔鼃諫於王而不用,致為臣而去。
齊人曰:「所以為蚔鼃,則善矣;所以自為,則吾不知也。」
公都子以告。
曰:「吾聞之也:有官守者,不得其職則去;有言責者,不得其言則去。我無官守,我無言責也,則吾進退豈不綽綽然有餘裕哉?」
孟子為卿於齊,出弔於滕,王使蓋大夫王驩為輔行。王驩朝暮見,反齊、滕之路,未甞與之言行事也。
公孫丑曰:「齊卿之位,不為小矣;齊、滕之路,不為近矣。反之而未甞與言行事,何也?」
曰:「夫既或治之,予何言哉?」
孟子自齊葬於魯。反於齊,止於嬴。
充虞請曰:「前日不知虞之不肖,使虞敦匠事;嚴,虞不敢請。今願竊有請也:木若以美然。」
曰:「古者棺槨無度,中古棺七寸、椁稱之,自天子達於庶人。非直為觀美也,然後盡於人心。不得,不可以為悅;無財,不可以為悅。得之為有財。古之人皆用之,吾何為獨不然?且比化者,無使土親膚,於人心獨無恔乎?吾聞之君子:不以天下儉其親。」
沈同以其私問曰:「燕可伐與?」
孟子曰:「可。子噲不得與人燕,子之不得受燕於子噲。有仕於此,而子悅之,不告於王,而私與之吾子之祿爵;夫士也,亦無王命而私受之於子,則可乎?何以異於是?」
齊人伐燕。
或問曰:「勸齊伐燕,有諸?」
曰:「未也。沈同問:『燕可伐與?』吾應之曰:『可。』彼然而伐之也。彼如曰:『孰可以伐之?』則將應之曰:『為天吏則可以伐之。』今有殺人者,或問之曰:『人可殺與?』則將應之曰:『可。』彼如曰:『孰可以殺之?』則將應之曰:『為士師則可以殺之。』今以燕伐燕,何為勸之哉?」
燕人畔。王曰:「吾甚慚於孟子。」
陳賈曰:「王無患焉,王自以為與周公,孰仁且智?」
王曰:「惡!是何言也!」
曰:「周公使管叔監殷,管叔以殷畔。知而使之,是不仁也;不知而使之,是不智也。仁智,周公未之盡也,而況於王乎?賈請見而解之。」
見孟子問曰:「周公何人也?」
曰:「古聖人也。」
曰:「使管叔監殷,管叔以殷畔也,有諸?」
曰:「然。」
曰:「周公知其將畔而使之與?」
曰:「不知也。」
「然則聖人且有過與?」
曰:「周公,弟也;管叔,兄也。周公之過,不亦宜乎?且古之君子,過則改之;今之君子,過則順之。古之君子,其過也如日月之食,民皆見之;及其更也,民皆仰之。今之君子,豈徒順之?又從為之辭。」
孟子致為臣而歸,王就見孟子曰:「前日愿見而不可得,得侍同朝甚喜。今又棄寡人而歸,不識可以繼此而得見乎?」
對曰:「不敢請耳,固所願也。」
他日王謂時子曰:「我欲中國而授孟子室,養弟子以萬鐘,使諸大夫國人皆有所矜式。子盍為我言之?」
時子因陳子而以告孟子。
陳子以時子之言告孟子。孟子曰:「然。夫時子惡知其不可也?如使予欲富,辭十萬而受萬,是為欲富乎?季孫曰:『異哉子叔疑!使己為政,不用,則亦已矣,又使其子弟為卿。人亦孰不欲富貴?而獨於富貴之中有私龍斷焉。』古之為市也,以其所有易其所無者,有司者治之耳。有賤丈夫焉,必求龍斷而登之,以左右望而罔市利。人皆以為賤,故從而征之。征商,自此賤丈夫始矣。」
孟子去齊,宿於晝。有欲為王留行者,坐而言。不應,隱几而臥。
客不悅曰:「弟子齊宿而後敢言;夫子臥而不聽;請勿復敢見矣。」
曰:「坐。我明語子:昔者魯繆公無人乎子思之側,則不能安子思;泄柳、申詳無人乎繆公之側,則不能安其身。子為長者慮,而不及子思。子絕長者乎?長者絕子乎?」
孟子去齊,尹士語人曰:「不識王之不可以為湯、武,則是不明也;識其不可然且至,則是干澤也。千里而見王,不遇故去;三宿而後出晝,是何濡滯也!士則茲不悅。」
高子以告。
曰:「夫尹士惡知予哉?千里而見王,是予所欲也。不遇故去,豈予所欲哉?予不得已也。予三宿而出晝,於予心猶以為速。王庶幾改之!王如改諸,則必反予。夫出晝而王不予追也,予然後浩然有歸志。予雖然,豈舍王哉?王由足用為善;王如用予,則豈徒齊民安?天下之民舉安。王庶幾改之!予日望之!予豈若是小丈夫然哉!諫於其君而不受,則怒,悻悻然見於其面,去則窮日之力而後宿哉?」
尹士聞之,曰:「士誠小人也。」
孟子去齊,充虞路問曰:「夫子若有不豫色然。前日虞聞諸夫子曰:『君子不怨天,不尤人。』」
曰:「彼一時,此一時也。五百年必有王者興,其間必有名世者。由周而來,七百有餘歲矣;以其數則過矣,以其時考之則可矣。夫天,未欲平治天下也,如欲平治天下,當今之世,舍我其誰也?吾何為不豫哉?」
孟子去齊居休。公孫丑問曰:「仕而不受祿,古之道乎?」
曰:「非也。於崇,吾得見王;退而有去志,不欲變,故不受也。繼而有師命,不可以請。久於齊,非我志也。」
* * *
|
C | UTF-8 | 2,247 | 3.734375 | 4 | [
"MIT"
] | permissive | //
// main.c
// MasteringAlgorithms
// Illustrates using a heap (see Chapter 10).
//
// Created by YourtionGuo on 05/05/2017.
// Copyright © 2017 Yourtion. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
static void print_heap(Heap *heap)
{
int i;
/// 打印堆结构
fprintf(stdout, "-> Heap size is %d\n", heap_size(heap));
for (i = 0; i < heap_size(heap); i++) {
fprintf(stdout, "--> Node=%03d\n", *(int *)heap->tree[i]);
}
return;
}
static int compare_int(const void *int1, const void *int2)
{
/// 比较两个整数
if (*(const int *)int1 > *(const int *)int2) return 1;
if (*(const int *)int1 < *(const int *)int2) return -1;
return 0;
}
int main(int argc, char **argv)
{
Heap heap;
void *data;
int intval[30], i;
/// 初始化堆
heap_init(&heap, compare_int, NULL);
/// 执行堆操作
i = 0;
intval[i] = 5;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (heap_insert(&heap, &intval[i]) != 0) return 1;
print_heap(&heap);
i++;
intval[i] = 10;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (heap_insert(&heap, &intval[i]) != 0) return 1;
print_heap(&heap);
i++;
intval[i] = 20;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (heap_insert(&heap, &intval[i]) != 0) return 1;
print_heap(&heap);
i++;
intval[i] = 1;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (heap_insert(&heap, &intval[i]) != 0) return 1;
print_heap(&heap);
i++;
intval[i] = 25;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (heap_insert(&heap, &intval[i]) != 0) return 1;
print_heap(&heap);
i++;
intval[i] = 22;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (heap_insert(&heap, &intval[i]) != 0) return 1;
print_heap(&heap);
i++;
intval[i] = 9;
fprintf(stdout, "Inserting %03d\n", intval[i]);
if (heap_insert(&heap, &intval[i]) != 0) return 1;
print_heap(&heap);
i++;
while (heap_size(&heap) > 0) {
if (heap_extract(&heap, (void **)&data) != 0) return 1;
fprintf(stdout, "Extracting %03d\n", *(int *)data);
print_heap(&heap);
}
/// 销毁堆
fprintf(stdout, "Destroying the heap\n");
heap_destroy(&heap);
return 0;
}
|
Java | UTF-8 | 3,496 | 2.390625 | 2 | [] | no_license | package com.brennan.deviget.redditposts.domain;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Objects;
public class RedditNewsDataResponse implements Serializable {
@SerializedName("author_fullname")
@Expose
private String authorFullname;
@SerializedName("title")
@Expose
private String title;
@SerializedName("created")
@Expose
private long created;
@SerializedName("thumbnail")
@Expose
private String thumbnail;
@SerializedName("thumbnail_width")
@Expose
private long thumbnailWidth;
@SerializedName("thumbnail_height")
@Expose
private long thumbnailHeight;
@SerializedName("num_comments")
@Expose
private long numComments;
private String authorLegibleName;
public String getAuthorLegibleName() {
return authorLegibleName;
}
public void setAuthorLegibleName(String authorLegibleName) {
this.authorLegibleName = authorLegibleName;
}
public String getAuthorFullname() {
return authorFullname;
}
public void setAuthorFullname(String authorFullname) {
this.authorFullname = authorFullname;
}
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public long getThumbnailWidth() {
return thumbnailWidth;
}
public void setThumbnailWidth(long thumbnailWidth) {
this.thumbnailWidth = thumbnailWidth;
}
public long getThumbnailHeight() {
return thumbnailHeight;
}
public void setThumbnailHeight(long thumbnailHeight) {
this.thumbnailHeight = thumbnailHeight;
}
public long getNumComments() {
return numComments;
}
public void setNumComments(long numComments) {
this.numComments = numComments;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RedditNewsDataResponse that = (RedditNewsDataResponse) o;
return created == that.created &&
thumbnailWidth == that.thumbnailWidth &&
thumbnailHeight == that.thumbnailHeight &&
numComments == that.numComments &&
Objects.equals(authorFullname, that.authorFullname) &&
Objects.equals(title, that.title) &&
Objects.equals(thumbnail, that.thumbnail);
}
@Override
public int hashCode() {
return Objects.hash(authorFullname, title, created, thumbnail, thumbnailWidth, thumbnailHeight, numComments);
}
@Override
public String toString() {
return "RedditNewsDataResponse{" +
"authorFullname='" + authorFullname + '\'' +
", title='" + title + '\'' +
", created=" + created +
", thumbnail='" + thumbnail + '\'' +
", thumbnailWidth=" + thumbnailWidth +
", thumbnailHeight=" + thumbnailHeight +
", numComments=" + numComments +
'}';
}
}
|
TypeScript | UTF-8 | 657 | 3.234375 | 3 | [] | no_license | /**
* interface para el modelo de los comentarios
*/
export interface IComment {
id: string;
name: string;
email: string;
body: string;
}
export class Comment {
private _id: string;
private _name: string;
private _email: string;
private _body: string;
constructor(comment: IComment) {
this._id = comment.id || '';
this._name = comment.name || '';
this._email = comment.email || '';
this._body = comment.body || '';
}
public get id() {
return this._id;
}
public get name() {
return this._name;
}
public get email() {
return this._email;
}
public get body() {
return this._body;
}
}
|
Python | UTF-8 | 734 | 3 | 3 | [] | no_license |
def solve(word):
result = [word[0]]
for w in word[1:]:
if w >= result[0]:
result.insert(0, w)
else:
result.append(w)
return "".join(result)
def main(source, dest):
with open(source, 'r') as fd, open(dest, 'w') as fo:
T = int(fd.readline())
for i in range(1,T+1):
word = fd.readline().rstrip()
result = solve(word)
print 'Case #' + str(i) + ': ' + result + '\n',
fo.write('Case #' + str(i) + ': ' + result + '\n')
if __name__ == "__main__":
filename = os.path.basename(sys.argv[1])
source = sys.argv[1]
dest = os.path.join(sys.argv[2], filename.replace(".in.txt",".out.txt"))
main(source, dest) |
C# | UTF-8 | 3,861 | 2.546875 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.IO;
using System;
namespace CodeSampleOne
{
[CustomEditor(typeof(AnimalDataHandler))]
public class AnimalDataEditor : Editor
{
public bool makeJSONPretty = default;
private SerializedProperty animalListProperty = default;
private static GUIStyle titleStyle = default;
private const string kFilePath = "Assets/Resources/AnimalData.json";
private const string infoString = "This tool is used to help update AnimalData.json in the Resources folder. It is recommended that you do not update that file directly. Any changes you make will be overwritten by this tool.";
private GUILayoutOption[] buttonOptions = new GUILayoutOption[] {
GUILayout.Height(24)
};
void OnEnable()
{
titleStyle = new GUIStyle();
titleStyle.fontSize = 24;
titleStyle.richText = true;
SetupAnimalList();
}
private void SetupAnimalList()
{
animalListProperty = serializedObject.FindProperty("data");
}
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField("<color=white>Animal Data</color>", titleStyle);
EditorGUILayout.Space();
GUILayout.Space(20);
makeJSONPretty = EditorGUILayout.Toggle("Format JSON", makeJSONPretty);
if (GUILayout.Button("Preview JSON In Console", buttonOptions))
{
OnPreviewJSON();
}
if (GUILayout.Button("Validate Data", buttonOptions))
{
OnValidateData();
}
if (GUILayout.Button("Update Animal Data File", buttonOptions))
{
OnUpdateData();
}
GUILayout.Space(20);
EditorGUILayout.HelpBox(infoString, MessageType.Info);
GUILayout.Space(20);
serializedObject.Update();
base.OnInspectorGUI();
serializedObject.ApplyModifiedProperties();
}
private void OnUpdateData()
{
var animalListData = (AnimalDataHandler)animalListProperty.serializedObject.targetObject;
var jsonData = animalListData.CreateJsonStringFromData(makeJSONPretty: makeJSONPretty);
StreamWriter sw = new StreamWriter(kFilePath);
sw.Write(jsonData);
sw.Close();
EditorUtility.DisplayDialog(
"Done!",
"Data has been updated in AnimalData.json file",
"OK"
);
AssetDatabase.Refresh();
}
private void OnValidateData()
{
var animalListData = (AnimalDataHandler)animalListProperty.serializedObject.targetObject;
var totalErrors = animalListData.ValidateData();
if (totalErrors > 0)
{
EditorUtility.DisplayDialog(
"Errors found!",
$"There are some errors found in the data. Check the console for more information.\n Number of errors found: {totalErrors}",
"OK"
);
return;
}
EditorUtility.DisplayDialog(
"Data is valid!",
$"Data is good to go. No errors found!",
"OK"
);
}
// Prints the JSON string to the console
private void OnPreviewJSON()
{
var animalListData = (AnimalDataHandler)animalListProperty.serializedObject.targetObject;
var jsonData = animalListData.CreateJsonStringFromData(makeJSONPretty: makeJSONPretty);
Debug.Log($"{jsonData}");
}
}
} |
Java | UTF-8 | 2,669 | 2.34375 | 2 | [] | no_license | package com.iba.kozlov.web.writers;
import com.iba.kozlov.db.dto.WriterDto;
import com.iba.kozlov.web.application.WriterBean;
import com.iba.kozlov.web.writers.view.AddBean;
import com.iba.kozlov.web.writers.view.EditorBean;
import com.iba.kozlov.web.writers.view.SearchBean;
import com.iba.kozlov.web.writers.view.TableRowBean;
public class Mapper {
public TableRowBean writerDtoToTableRowBean(WriterDto writer) {
TableRowBean tableRowBean = new TableRowBean();
tableRowBean.setId(writer.getId());
tableRowBean.setName(writer.getName());
tableRowBean.setSurname(writer.getSurname());
tableRowBean.setCountry(writer.getCountry());
return tableRowBean;
}
public WriterDto tableRowBeanToWriterDto(TableRowBean addBean) {
WriterDto writerDto = new WriterDto();
writerDto.setId(addBean.getId());
writerDto.setName(addBean.getName());
writerDto.setSurname(addBean.getSurname());
writerDto.setCountry(addBean.getCountry());
return writerDto;
}
public WriterDto addBeanToWriterDto(AddBean addBean) {
WriterDto writerDto = new WriterDto();
writerDto.setId(addBean.getId());
writerDto.setName(addBean.getName());
writerDto.setSurname(addBean.getSurname());
writerDto.setCountry(addBean.getCountry());
return writerDto;
}
public WriterDto editBeanToWriterDto(EditorBean editorBean) {
WriterDto writerDto = new WriterDto();
writerDto.setId(editorBean.getId());
writerDto.setName(editorBean.getName());
writerDto.setSurname(editorBean.getSurname());
writerDto.setCountry(editorBean.getCountry());
return writerDto;
}
public EditorBean writerDtoToEditBean(WriterDto writerDto) {
EditorBean editorBean = new EditorBean();
editorBean.setId(writerDto.getId());
editorBean.setName(writerDto.getName());
editorBean.setSurname(writerDto.getSurname());
editorBean.setCountry(writerDto.getCountry());
return editorBean;
}
public WriterDto writerBeanToDto(WriterBean writerBean){
WriterDto writerDto=new WriterDto();
writerDto.setId(writerBean.getId());
writerDto.setName(writerBean.getName());
writerDto.setSurname(writerBean.getSurname());
return writerDto;
}
public SearchBean writerDtoToSearchBean(WriterDto writerDto) {
SearchBean searchBean=new SearchBean();
searchBean.setId(writerDto.getId());
searchBean.setName(writerDto.getName());
searchBean.setSurname(writerDto.getSurname());
return searchBean;
}
public WriterDto searchBeanToWriterDto(SearchBean writerSearch) {
WriterDto writerDto=new WriterDto();
writerDto.setId(writerSearch.getId());
writerDto.setName(writerSearch.getName());
writerDto.setSurname(writerSearch.getSurname());
return writerDto;
}
}
|
Java | UTF-8 | 396 | 1.578125 | 2 | [] | no_license | package com.fancv;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author hamish-wu
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.run();
}
}
|
PHP | UTF-8 | 757 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace Stark\Daemon\Consumer;
class Callback extends Base {
protected $_init = '';
protected $_run = '';
protected $_complete = '';
public function init(\Stark\Daemon\Worker $worker) {
if (function_exists($this->_init)) {
call_user_func_array($this->_init, array($worker));
}
}
public function run(\Stark\Daemon\Worker $worker, $data) {
if (function_exists($this->_run)) {
return call_user_func_array($this->_run, array($worker, $data));
}
return false;
}
public function complete(\Stark\Daemon\Worker $worker) {
if (function_exists($this->_complete)) {
call_user_func_array($this->_complete, array($worker));
}
}
} |
Python | UTF-8 | 814 | 2.921875 | 3 | [
"MIT"
] | permissive | from mltoolkit.mldp.steps.preprocessors import BasePreProcessor
from mltoolkit.mlutils.helpers.paths_and_files import get_file_paths
from numpy import random
class FileShuffler(BasePreProcessor):
"""Reads the paths of files; assigns them to `data_path` in a shuffled
order, and passes them along in the data-source.
"""
def __init__(self, **kwargs):
super(FileShuffler, self).__init__(**kwargs)
def __call__(self, data_path, **kwargs):
file_paths = []
if not isinstance(data_path, list):
data_path = [data_path]
for _data_path in data_path:
file_paths += get_file_paths(_data_path)
random.shuffle(file_paths)
new_data_source = kwargs
new_data_source['data_path'] = file_paths
return new_data_source
|
Python | UTF-8 | 2,994 | 3.453125 | 3 | [] | no_license | import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
:param messages_filepath: messages.csv file path
:param categories_filepath: categories file path
:return: merged message and categories dataset----df
'''
messages = pd.read_csv(messages_filepath)
categories = pd.read_csv(categories_filepath)
# merge datasets
df = pd.merge(messages, categories, on='id')
return df
def clean_data(df):
'''
:param df: the dataset need to be clean
:return: cleaned df
'''
# split categories into separate category columns
categories = df['categories'].str.split(';', expand=True)
categories.index = df.id
row = categories[0:1]
category_colnames = row.apply(lambda x: list(x.str.split('-'))[0][0])
categories.columns = category_colnames
# Convert category values to just numbers 0 or 1
for column in categories:
# set each value to be the last character of the string
categories[column] = categories[column].str[-1]
# convert column from string to numeric
categories[column] = categories[column].astype(int)
# Replace `categories` column in `df` with new category columns
df.drop(columns=['categories'], index=1, inplace=True)
df.index = df.id
df = pd.merge(df, categories, left_index=True, right_index=True)
df = df.reset_index(drop=True)
# check number of duplicates
if df.duplicated().sum():
# drop duplicates
df = df.drop_duplicates(subset=['id', 'message', 'original', 'genre'], keep='first')
# check number of duplicates
if not df.duplicated().sum():
return df
def save_data(df, database_filename):
'''
:param df: dataset
:param database_filename: database name
:return: None
'''
engine = create_engine(f'sqlite:///{database_filename}')
df.to_sql('DisasterResponse', engine, index=False)
def main():
if len(sys.argv) == 4:
messages_filepath, categories_filepath, database_filepath = sys.argv[1:]
print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}'
.format(messages_filepath, categories_filepath))
df = load_data(messages_filepath, categories_filepath)
print('Cleaning data...')
df = clean_data(df)
print('Saving data...\n DATABASE: {}'.format(database_filepath))
save_data(df, database_filepath)
print('Cleaned data saved to database!')
else:
print('Please provide the filepaths of the messages and categories ' \
'datasets as the first and second argument respectively, as ' \
'well as the filepath of the database to save the cleaned data ' \
'to as the third argument. \n\nExample: python process_data.py ' \
'disaster_messages.csv disaster_categories.csv ' \
'DisasterResponse.db')
if __name__ == '__main__':
main() |
Markdown | UTF-8 | 876 | 3.0625 | 3 | [] | no_license | ##
TF2 runs Eager Execution by default, thus removing the need for Sessions.
If you want to run static graphs, the more proper way is to use tf.function() in TF2.
While Session can still be accessed via tf.compat.v1.Session() in TF2, I would discourage using it.
It may be helpful to demonstrate this difference by comparing the difference in hello worlds:
TF1.x hello world:
```
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))
```
TF2.x hello world:
```
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)
```
## reference
[TensorFlow 2](https://www.tensorflow.org/guide?hl=zh-cn)
[TF1_TF2](https://stackoverflow.com/questions/55142951/tensorflow-2-0-attributeerror-module-tensorflow-has-no-attribute-session)
[TensorFlow教程](http://c.biancheng.net/view/1881.html)
|
PHP | UTF-8 | 88,063 | 2.796875 | 3 | [] | no_license | <?php
/**
* 后台操作的记录
*
* @author ZP 2012-10-25 16:33:17
* @param string $user_name操作人 time $time操作时间 string $act操作文件什么的 string $content操作内容(参数什么的)
* @modify 薛升 2015-6-16 15:04:55 添加判断整数或小数并保留2位
* @tudo 多人追加写引发问题
*/
function mywayec_log_record($user_name = '', $time = '', $ip = '', $act = '', $content = array()){
clearstatcache();
/*
* 通过循环截取数组里每个值的前200个字符
*/
/*foreach ($content as $key=>&$value){
$value=substr($value,0,200);
}*/
$content=print_r($content,true);//把截取后的数组转化成字符串输出
$size = 10000000;//单个文件放数据大小,单位B
if($user_name && $time){
$dir = ROOT_PATH.'/mywayec_log_record/';
$file_name = '';
if (!file_exists($dir)) {
if (!make_dir($dir)) {
$error_msg = sprintf('目录 % 不存在或不可写', $dir);
return false;
}
}
if($dh = opendir($dir)){
while(($file = readdir($dh)) !== false ){
if(preg_match("/\.txt/i",$file)){
$file_name = $file;
break;
}
}
closedir($dh);
}else{
$error_msg = sprintf('目录 % 打不开', $dir);
return false;
}
$file_name = empty($file_name) ? date('YmdHis').'.txt' : $file_name;//文件名
$gz_file_name = substr($file_name, 0 , strlen($file_name)-4);//压缩文件名
if(file_exists($dir.$file_name) && (filesize($dir.$file_name) > $size)){
/*
* 压缩文件
*/
$zip = new ZipArchive;//php>5.2.0 自带的 先要去php.ini打开扩展
if ($zip->open($dir.$gz_file_name.'_'.date('YmdHis').'.zip', ZIPARCHIVE::CREATE) === TRUE) {//压缩成zip
$zip->addFromString($gz_file_name.'.txt', file_get_contents($dir.$file_name));//第一个参数-压缩到里面的文件名,第二个参数-内容
$zip->close();
if(unlink($dir.$file_name)){//删除txt文件
$file_name = date('YmdHis').'.txt';
}
}
}
if($handle = fopen($dir.$file_name,'a+')){
$str_content = $user_name.' (操作人)于:'.$time.'(时间)在:'.$ip.'(IP)操作了:'.$act.' 参数:'.$content;//记录信息组合
$startTime = microtime();
/*
* 超时设置为1ms,如果这里时间内没有获得锁,就反复获得,直接获得到对文件操作权为止.如果超时限制已到,就必需马上退出,让出锁让其它进程来进行操作。
*/
do {
$canWrite = flock($handle, LOCK_EX);
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite) && ((microtime()-$startTime) > 1000));
if($canWrite){
if(!fwrite($handle,$str_content."\r\n")){
$error_msg = sprintf('文件 % 不可写', $dir.$file_name);
return false;
}
flock($handle, LOCK_UN);
}
fclose($handle);
}else{
$error_msg = sprintf('文件 % 打不开或不可建', $dir.$file_name);
return false;
}
}else{
$error_msg = sprintf('数据为空');
return false;
}
}
/**
* 获得用户的真实IP地址
*
* @access public
* @return string
*/
function real_ip() {
static $realip = null;
if ($realip !== null) {
return $realip;
}
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
/**
* 取X-Forwarded-For中第一个非unknown的有效IP字符串
*/
foreach ($arr AS $ip) {
$ip = trim($ip);
if ($ip != 'unknown') {
$realip = $ip;
break;
}
}
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$realip = $_SERVER['HTTP_CLIENT_IP'];
} else {
if (isset($_SERVER['REMOTE_ADDR'])) {
$realip = $_SERVER['REMOTE_ADDR'];
} else {
$realip = '0.0.0.0';
}
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR')) {
$realip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_CLIENT_IP')) {
$realip = getenv('HTTP_CLIENT_IP');
} else {
$realip = getenv('REMOTE_ADDR');
}
}
preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
return $realip;
}
/**
* 检查目标文件夹是否存在,如果不存在则自动创建该目录
*
* @access public
* @param string $ folder 目录路径。不能使用相对于网站根目录的URL
* @return bool
*/
function make_dir($folder) {
$reval = false;
if (!file_exists($folder)) {
/**
* 如果目录不存在则尝试创建该目录
*/
@umask(0);
/**
* 将目录路径拆分成数组
*/
preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
/**
* 如果第一个字符为/则当作物理路径处理
*/
$base = ($atmp[0][0] == '/') ? '/' : '';
/**
* 遍历包含路径信息的数组
*/
foreach ($atmp[1] AS $val) {
if ('' != $val) {
$base .= $val;
if ('..' == $val || '.' == $val) {
/**
* 如果目录为.或者..则直接补/继续下一个循环
*/
$base .= '/';
continue;
}
} else {
continue;
}
$base .= '/';
if (!file_exists($base)) {
/**
* 尝试创建目录,如果创建失败则继续循环
*/
if (@mkdir($base, 0777)) {
@chmod($base, 0777);
$reval = true;
}
}
}
} else {
/**
* 路径已经存在。返回该路径是不是一个目录
*/
$reval = is_dir($folder);
}
clearstatcache();
return $reval;
}
/**
* 页面上调用的js文件
*
* @access public
* @param string $files
* @return void
*/
function smarty_insert_scripts($args) {
static $scripts = array();
$arr = explode(',', str_replace(' ', '', $args['files']));
$str = '';
foreach ($arr AS $val) {
if (in_array($val, $scripts) == false) {
$scripts[] = $val;
$str .= '<script type="text/javascript" src="'.__ROOT__.'/Public/Js/' . $val . '"></script>';
}
}
return $str;
}
/**
* 页面上调用的css文件
*
* @access public
* @param string $files
* @return void
*/
function smarty_insert_css($args) {
static $css = array();
$arr = explode(',', str_replace(' ', '', $args['files']));
$str = '';
foreach ($arr AS $val) {
if (in_array($val, $css) == false) {
$css[] = $val;
$str .= '<link href="'.__ROOT__.'/Public/Css/'.$val.'" rel="stylesheet" type="text/css" />';
}
}
return $str;
}
/**
* 创建分页的列表
*
* @access public
* @param integer $count
* @return string
*/
function smarty_create_pages($params) {
extract($params);
$str = '';
$len = 10;
if (empty($page)) {
$page = 1;
}
if (!empty($count)) {
$step = 1;
$str .= "<option value='1'>1</option>";
for ($i = 2; $i < $count; $i += $step) {
$step = ($i >= $page + $len - 1 || $i <= $page - $len + 1) ? $len : 1;
$str .= "<option value='$i'";
$str .= $page == $i ? " selected='true'" : '';
$str .= ">$i</option>";
}
if ($count > 1) {
$str .= "<option value='$count'";
$str .= $page == $count ? " selected='true'" : '';
$str .= ">$count</option>";
}
}
return $str;
}
/**
* 分页的信息加入条件的数组
*
* @access public
* @return array
* @modify XM 2013-12-6 10:05:06 每页最大显示数量改为2000
*/
function page_and_size($filter)
{
$filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
{
$filter['page_size'] = intval($_REQUEST['page_size']);
}
elseif (isset($_COOKIE['SITE']['page_size']) && intval($_COOKIE['SITE']['page_size']) > 0)
{
$filter['page_size'] = intval($_COOKIE['SITE']['page_size']);
}
else
{
$filter['page_size'] = 30;
}
if($filter['page_size']>10000){//判断每页的显示数量,如果超过2000,则显示2000条
$filter['page_size']=10000;
}
return $filter;
}
/**
* 根据过滤条件获得排序的标记
*
* @access public
* @param array $filter
* @return array
*/
function sort_flag($filter)
{
$flag['tag'] = 'sort_' . preg_replace('/^.*\./', '', $filter['sort_by']);
$flag['img'] = '<img src="'.__ROOT__.'/Public/Images/' . ($filter['sort_order'] == "DESC" ? 'sort_desc.gif' : 'sort_asc.gif') . '"/>';
return $flag;
}
/**
*
*
* @access public
* @param
* @return void
*/
function make_json_result($content, $message='', $append=array())
{
make_json_response($content, 0, $message, $append);
}
/**
* 创建一个JSON格式的错误信息
*
* @access public
* @param string $msg
* @return void
*/
function make_json_error($msg)
{
make_json_response('', 1, $msg);
}
/**
* 创建一个JSON格式的数据
*
* @access public
* @param string $content
* @param integer $error
* @param string $message
* @param array $append
* @return void
*/
function make_json_response($content='', $error="0", $message='', $append=array())
{
include_once(COMMON_PATH.'Util/Json.class.php');
$json = new JSON;
$res = array('error' => $error, 'message' => $message, 'content' => $content);
if (!empty($append))
{
foreach ($append AS $key => $val)
{
$res[$key] = $val;
}
}
$val = $json->encode($res);
exit(print($val));
}
/**
* LIKE过滤
*/
function mysql_like_quote($str) {
return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%'));
}
/**
* soap通信
* @access public
* @param mixed $method 方法名
* @param mixed $param
* @return array
* @author 李健 2014-12-17 15:59:04
* @modidy 钟宏亮 2016-5-20 11:02:40 增加emmacloth站soap地址
*/
function soap($method,$param=array(),$type=1){
$soapConfig = array(
'trace' => false,
'connection_timeout' => 180,
);
try{
if($type==1){
$soap = new SoapClient(C('SOAP_WSDL_URL'));
}elseif($type==2){
$soap = new SoapClient(C('SOAP_WSDL_URL_RW'));
}elseif($type==3){
$soap = new SoapClient(C('SOAP_WSDL_URL_EM'),$soapConfig);
}elseif($type==4){
$soap = new SoapClient(C('SOAP_WSDL_URL_EC'));
}
if($method != 'get_order'){
$request = array('token' => C('SOAP_TOKEN_LOCAL'),'validation' => md5(serialize($param)),'param' => $param);
}else{
$request = array('token' => C('SOAP_TOKEN_LOCAL'), 'billno' => $param['billno'], 'number' => $param['number'], 'type'=> $param['type']);
}
$result = $soap->$method($request);
return $result;
}catch (SoapFault $fault){
return array('status' => 'fail', 'message' => "Error: ".$fault->faultcode.", string: ".$fault->faultstring);
}
}
/**
* 生成MYSQL语句的条件语句
* @access public
* @param array $data_arr 查询条件
* @example
* $data_arr = array(
* 'where' => array("user_id IN (236,244)","b.role='总管理员'"), //WHERE user_id IN (236,244) AND b.role = '总管理员'
* 'group' => array('a.role_list', 'a.role'), //GROUP BY a.role_list, a.role
* 'order' => array(array('user_id','DESC'),array('b.role')), //ORDER BY user_id DESC, b.role ASC
* 'limit' => array(0,2), // LIMIT 1,2
* );
* @return string;
* @author 翁晨 2014-12-16 16:56:27
*/
function get_mysql_condition($data_arr = array()){
$res = '';
$where = '';
$group = '';
$order = '';
$limit = '';
if(!empty($data_arr)){
//WHERE
if($data_arr['where']){
$where = ' WHERE 1 ';
foreach($data_arr['where'] as $value){
$where .= ' AND '.$value.' ';
}
}
//GROUP BY
if($data_arr['group']){
$group = ' GROUP BY ';
foreach($data_arr['group'] as $value){
$group .= ' '.$value.',';
}
$group = rtrim($group, ',');
}
//ORDER BY
if($data_arr['order']){
$order = ' ORDER BY ';
foreach($data_arr['order'] as $value){
if(isset($value[1])){
$order .= ' '.$value[0].' '.$value[1];
}else{//默认正序
$order .= ' '.$value[0].' ASC ';
}
$order .= ',';
}
$order = rtrim($order, ',');
}
//LIMIT
if($data_arr['limit']){
$limit = ' LIMIT '.$data_arr['limit'][0];
if(isset($data_arr['limit'][1])){
$limit .= ', '.$data_arr['limit'][1];
}
}
$res = $where.$group.$order.$limit;
}
return $res;
}
/**
* 生成MYSQL批量更新语句
* @access public
* @param array $data_arr 数据数组
* @example
* $data_arr = array(
* 'table' => 'rs_inventory', //表名
* 'case' => 'inventory_id', //根据哪个字段进行更新
* 'set' => array('order_goods_id'=>array(array(1[inventory_id],11[order_goods_id]),array(2,12)),'status'=>array(array(1[inventory_id],11[status]),array(2,12))), //需要更新的字段和更新内容
* );
* @return string;
* @author 翁晨 2015-7-15 09:59:09
*/
function get_mysql_update_batch($data_arr = array()){
$sql = '';
if($data_arr){
$i = 0;
$case_arr = array();
$sql = "UPDATE {$data_arr['table']} SET ".key($data_arr['set'])." = CASE {$data_arr['case']}";
foreach($data_arr['set'] as $key => $value_arr){
if($i>0){
$sql .= " END , {$key} = CASE {$data_arr['case']} ";
}
foreach($value_arr as $value){
$sql .= " WHEN '{$value[0]}' THEN '{$value[1]}' ";
$case_arr[] = $value[0];
}
$i++;
}
$case_str = "'".implode("','",array_unique($case_arr))."'";
$sql .= " END WHERE {$data_arr['case']} IN ({$case_str}) ";
}
return $sql;
}
/**
* 判断表中某字段是否无重复
* @access public
* @param string $table 表名
* @param string $field 字段名
* @param string $value 字段值
* @param array $id_arr 主键的字段名和值
* @return boolean 无重复返回true ,有重复false
* @author 翁晨 2014-12-18 12:10:50
*/
function is_only($table, $field, $value, $id_arr=array('field'=>'', 'value'=>''), $where='')
{
$sql = "SELECT COUNT(*) FROM ".C('DB_PREFIX')."" .$table. " WHERE $field = '$value'";
if($id_arr['field'] && $id_arr['value']){
$sql .= " AND {$id_arr['field']} <> {$id_arr['value']}";
}
$sql .= empty($where) ? '' : ' AND ' .$where;
return (M()->getOne($sql) == 0);
}
/**
* 异步发送邮件
* @access public
* @param string $url 地址
* @param array $data_arr 字段名
* string $name 发送人
* string $email 接收邮箱
* string $from 发送邮箱
* string $subject 主题
* string $content 内容
* string $site_from 来自站点
* tinyint $mail_type 什么类型发送邮件,1是263发送邮件,0是思齐发邮件
* string $billno 账单号
* tinyint $status 订单商品状态
* string $admin_name 操作人
* int $id 重发邮件ID
* string $yanzheng 验证码
* @param string $errno 错误号
* @param array $errstr 错误内容
* @return mix
* @author 翁晨 2014-12-23 15:00:01
* @modify 何洋 2015-7-31 17:45:48 修改bug
*/
function send_mail_async($data_arr, $url, $errno='', $errstr=''){
//访问地址
$url = $url ? $url : C('MAIL_HOST').':'.C('MAIL_PORT');
//初始化参数
$data_arr = array(
'name' => $data_arr['name'],
'email' => $data_arr['email'],
'from' => $data_arr['from'],
'subject' => $data_arr['subject'],
'content' => $data_arr['content'],
'type' => isset($data_arr['type']) ? $data_arr['type'] : 0,
'is_html' => isset($data_arr['is_html']) ? $data_arr['is_html'] : 1,
'site_from' => $data_arr['site_from'],
'mail_type' => isset($data_arr['mail_type']) ? $data_arr['mail_type'] : 0,
'billno' => $data_arr['billno'],
'status' => isset($data_arr['status']) ? $data_arr['status'] : 0,
'admin_name' => $data_arr['admin_name'],
'is_insert' => isset($data_arr['is_insert']) ? $data_arr['is_insert'] : 0,
'id' => isset($data_arr['id']) ? $data_arr['id'] : 0,
'yanzheng' => $data_arr['yanzheng'],
);
//组建内容字符串
$post_data = '';
$post_data .= "name=".$data_arr['name'];
$post_data .= "&email=".$data_arr['email'];
$post_data .= "&from=".$data_arr['from'];
$post_data .= "&subject=".$data_arr['subject'];
$post_data .= "&content=".urlencode($data_arr['content']);
$post_data .= "&type=".$data_arr['type'];
$post_data .= "&is_html=".$data_arr['is_html'];
$post_data .= "&site_from=".$data_arr['site_from'];
$post_data .= "&mail_type=".$data_arr['mail_type'];
$post_data .= "&billno=".$data_arr['billno'];
$post_data .= "&status=".$data_arr['status'];
$post_data .= "&admin_name=".$data_arr['admin_name'];
$post_data .= "&is_insert=".$data_arr['is_insert'];
$post_data .= "&id=".$data_arr['id'];
$post_data .= "&yanzheng=".$data_arr['yanzheng'];
//POST url
$fp = fsockopen($url,80,$errno,$errstr,30);
if($fp){
$out = "POST http://".$url.__APP__."/Home/MailSendAsync HTTP/1.0\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Content-Length: " . strlen ( $post_data ) . "\r\n\r\n";
fputs($fp, $out.$post_data);
$send_status = false;
if($data_arr['is_insert'] != 1){
while (!feof($fp)) {
$receive = fgets($fp, 128);
if (strcmp ( $receive, "SEND_MAIL_TRUE" ) == 0) {
$send_status = true;
}
}
}
fclose($fp);
return $send_status;
}
}
/*
* 邮件发送
* @param string $name 发送人
* @param string $email 接收邮箱
* @param string $from 发送邮箱
* @param string $subject 主题
* @param string $content 内容
* @return boolean
* @author 翁晨 2014-12-23 15:00:01
* @modify 林祯 2016-10-24 11:45:10 站点从配置读取
*/
function send_mail_graphic($name,$email,$from,$subject,$content,$site_from){
/*
*获取邮件id,组id
*/
$site_config = C('SITE_CONFIG');
$site_rw_arr = array_flip($site_config[2]['CHILD_SITES']);
$site_em_arr = array_flip($site_config[3]['CHILD_SITES']);
$site_ec_arr = array_flip($site_config[4]['CHILD_SITES']);
if(in_array($site_from,$site_rw_arr)){
$name="romwe.com";
$sys_tag = 'supply_romwe';//CRM标记
}elseif(in_array($site_from,$site_em_arr)){//思齐发邮件
$name = 'MakeMeChic';
$sys_tag = 'supply_mmc';//CRM标记
}else{
if($site_from == 'sid'){
$name = "sisde.com";
}else if(in_array($site_from,$site_ec_arr)){
$name = "emmacloth";
}
$sys_tag = 'supply_shein';//CRM标记
}
if(!C('MAIL_IS_SEND')){
return true;
}
import('Vendor.SysEmail.SysEmail',LIB_PATH,'.php');
$direct_param = array(
'key' => C('CRM_MAIL_KEY'),
"temp_mail" => 0,
"send_params" => array
(
"from_email" => $from,
"from_name" => $name,
"to_email" => $email,
"to_name" => '',
"subject" => $subject,
"content" => $content,
"from_site" => $site_from,
"dept" => "supply",
"sys_tag" => $sys_tag,
"mail_plantform" => "mandrill"
)
);
$request_log = array(
"to_email" => $email,
"from_site" => $site_from,
"sys_tag" => $sys_tag
);
@file_put_contents(ROOT_PATH.'/Logs/shein_mail_log/'.date('Ymd').'.txt',date('Y-m-d H:i:s').' request:'.json_encode($request_log)."\r\n",FILE_APPEND);
$email = new SysEmail();
$res = $email->call($direct_param);
@file_put_contents(ROOT_PATH.'/Logs/shein_mail_log/'.date('Ymd').'.txt',date('Y-m-d H:i:s').' response:'.json_encode($res)."\r\n-----------------------------------------\r\n",FILE_APPEND);
if($res['status'] == 1 && $res['code'] == 200){
return true;
}else{
$GLOBALS['mail_error'] = $res['info'];
return false;
}
}
/**
* 生成编辑器,创建fckeditor的html
* @param string input_name 输入框名称
* @param string input_value 输入框值
* @author 游佳 2014-12-25 17:53:01
*/
function create_html_editor($input_name, $input_value = '')
{
vendor("fckeditor.fckeditor");
$editor = new FCKeditor($input_name);
$editor->BasePath = __ROOT__.'/ThinkPHP/Library/Vendor/fckeditor/';
$editor->ToolbarSet = 'Normal';
$editor->Width = '100%';
$editor->Height = '320';
$editor->Value = $input_value;
$FCKeditor = $editor->CreateHtml();
return $FCKeditor;
}
/**
* 更新项目的属性
* @access public
* @author 戴鑫 2014-12-25 10:47:41
* @modify 田靖 2016-09-27 16:16:14 修改接口方法
* @return sting
*/
function get_goods_info($goods_sn = '',$goods_type,$return_beihuo_attr=false){
if($return_beihuo_attr===false){
$good_info = S('common_goods_attr_' . $goods_sn);//根据商品sn获取该商品信息
}else{
$good_info = S('common_goods_attr_and_beihuo_attr' . $goods_sn);//根据商品sn获取该商品信息
}
if($goods_type) //区分sheinside 1,romwe 2
$type = $goods_type;
else
$type = 1; //默认为 1
if(empty($good_info)){//获取缓存值
$param = array();
$param['goods_sn'] = array($goods_sn);
$param['return_beihuo_attr'] = $return_beihuo_attr;
$param['action']='getGoodsInfo';
$uri=C('CURL_URI_GET_GOODS_ATTR');
$result=website_api($type,$uri,$param);
if($result['success']){
if($return_beihuo_attr===false){
S('common_goods_attr_' . $goods_sn, $result['content'][$goods_sn]);//加入缓存
}else{
S('common_goods_attr_and_beihuo_attr' . $goods_sn, $result['content'][$goods_sn]);//加入缓存
}
$good_info = $result['content'][$goods_sn];
}
}
return $good_info;
}
/*
* 数组 排序
* @access public
* @author 游佳 2014-1-6 18:47:41
*/
function arr_sort($sort_by,$sort_order,&$row,$page = 0,$page_size = 50){
foreach($row as $k=>$v){
$temp1[$k]=$v[$sort_by];
}
if(strtolower($sort_order)=='desc'){
array_multisort($temp1,SORT_DESC,$row);
}else{
array_multisort($temp1,SORT_ASC,$row);
}
$row = array_slice($row,$page,$page_size);
}
/*
* code39校验字符串是否正确
* @access public
* @author 何洋 2015-1-16 19:35:31
*/
function jiaoyan_code39($arr){
$str = strtoupper($arr);//转换成大写
$allow_word = array('0'=>'0','1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5','6'=>'6','7'=>'7','8'=>'8','9'=>'9','A'=>'10','B'=>'11','C'=>'12','D'=>'13','E'=>'14','F'=>'15','G'=>'16','H'=>'17','I'=>'18','J'=>'19','K'=>'20','L'=>'21','M'=>'22','N'=>'23','O'=>'24','P'=>'25','Q'=>'26','R'=>'27','S'=>'28','T'=>'29','U'=>'30','V'=>'31','W'=>'32','X'=>'33','Y'=>'34','Z'=>'35','-'=>'36','.'=>'37',' '=>'38','$'=>'39','/'=>'40','+'=>'41','%'=>'42');
$out = array();
preg_match_all ( "/^(.+)(.){1}$/i", $str, $out, PREG_PATTERN_ORDER );//分隔字符串和校验位
$jiaoyan_arr = str_split($out[1][0]);//字符串转换成数组
$jiaoyan_num = 0;
foreach($jiaoyan_arr as $key => $val){
$jiaoyan_num += $allow_word[$val];
}
$check_word_arr = array_flip($allow_word);
$check_word = $check_word_arr[($jiaoyan_num%43)];//校验位
if(strcmp($check_word, $out[2][0]) == 0) {//校验位比对
return true;
}else{
return false;
}
}
/**
* 将ip转化成对应的地区
* @access public
* @param $ip ip地址
* @int $num 参数
* @return string
* @author 游佳 2015-1-26 14:51:40
*/
function convertip($ip,$num=1) {
if($num==2){
$dat_path = ROOT_PATH.'/Public/File/ip/ip_all.dat';
}else{
$dat_path = ROOT_PATH.'/Public/File/ip/ip_simple.dat';
}
//打开IP数据文件
if(!$fd = @fopen($dat_path, 'rb')){
return 'IP date file not exists or access denied';
}
//分解IP进行运算,得出整形数
$ip = explode('.', $ip);
$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
//获取IP数据索引开始和结束位置
$DataBegin = fread($fd, 4);
$DataEnd = fread($fd, 4);
$ipbegin = implode('', unpack('L', $DataBegin));
if($ipbegin < 0) $ipbegin += pow(2, 32);
$ipend = implode('', unpack('L', $DataEnd));
if($ipend < 0) $ipend += pow(2, 32);
$ipAllNum = ($ipend - $ipbegin) / 7 + 1;
$BeginNum = 0;
$EndNum = $ipAllNum;
//使用二分查找法从索引记录中搜索匹配的IP记录
while($ip1num>$ipNum || $ip2num<$ipNum) {
$Middle= intval(($EndNum + $BeginNum) / 2);
//偏移指针到索引位置读取4个字节
fseek($fd, $ipbegin + 7 * $Middle);
$ipData1 = fread($fd, 4);
if(strlen($ipData1) < 4) {
fclose($fd);
return 'System Error1';
}
//提取出来的数据转换成长整形,如果数据是负数则加上2的32次幂
$ip1num = implode('', unpack('L', $ipData1));
if($ip1num < 0) $ip1num += pow(2, 32);
//提取的长整型数大于我们IP地址则修改结束位置进行下一次循环
if($ip1num > $ipNum) {
$EndNum = $Middle;
continue;
}
//取完上一个索引后取下一个索引
$DataSeek = fread($fd, 3);
if(strlen($DataSeek) < 3) {
fclose($fd);
return 'System Error2';
}
$DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
fseek($fd, $DataSeek);
$ipData2 = fread($fd, 4);
if(strlen($ipData2) < 4) {
fclose($fd);
return 'System Error3';
}
$ip2num = implode('', unpack('L', $ipData2));
if($ip2num < 0) $ip2num += pow(2, 32);
//没找到提示未知
if($ip2num < $ipNum) {
if($Middle == $BeginNum) {
fclose($fd);
return 'Unknown';
}
$BeginNum = $Middle;
}
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(1)) {
$ipSeek = fread($fd, 3);
if(strlen($ipSeek) < 3) {
fclose($fd);
return 'System Error4';
}
$ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
fseek($fd, $ipSeek);
$ipFlag = fread($fd, 1);
}
if($ipFlag == chr(2)) {
$AddrSeek = fread($fd, 3);
if(strlen($AddrSeek) < 3) {
fclose($fd);
return 'System Error5';
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return 'System Error6';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0))
$ipAddr2 .= $char;
$AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
fseek($fd, $AddrSeek);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
} else {
fseek($fd, -1, SEEK_CUR);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return 'System Error7';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0)){
$ipAddr2 .= $char;
}
}
fclose($fd);
//最后做相应的替换操作后返回结果
if(preg_match('/http/i', $ipAddr2)) {
$ipAddr2 = '';
}
$ipaddr = "$ipAddr1 $ipAddr2";
$ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);
$ipaddr = preg_replace('/^s*/is', '', $ipaddr);
$ipaddr = preg_replace('/s*$/is', '', $ipaddr);
if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {
$ipaddr = 'Unknown';
}
$ipaddr = iconv('gbk', 'utf-8//IGNORE', $ipaddr); //转换编码,如果网页的gbk可以删除此行
return $ipaddr;
}
/**
* 将ip转化成对应的国家
*
* @author 何洋 2015-12-9 17:59:06
*/
function convertips($ip){
vendor("geoip2.autoload");//引入初始文件
try {
$reader = new GeoIp2\Database\Reader(ROOT_PATH.'/Public/File/ip/GeoIP2-Country.mmdb');//创建对象
$record = $reader->country($ip);
return $record->country->names['zh-CN'];
} catch (Exception $e) {
return '本机地址或局域网';
}
}
/**
* 将匹配/[^a-zA-Z0-9']+/的项替换为-
* @access public
* @param $filename 产品名称
* @return string
* @author 游佳 2015-1-29 14:51:40
* @modify 胡林霄 2016-09-09 17:33:34 转义单双引号
*/
function profilename($filename) {
$filename = preg_replace("/[^a-zA-Z0-9']+/", '-', $filename);
$filename = addslashes($filename);
return $filename;
}
/**
* 将数据以json格式写入文件
* @access public
* @param string $filepath 文件路径
* @param string $key 数组的key
* @param string|array $value 数组的key对应的值
* @param boolean $is_replace 是否执行替换,默认false(追加)
* @author 翁晨 2014-9-4 16:34:03
* @modify 何洋 2015-10-19 16:17:32 日志文件存储位置修改
*/
function write_json_to_file($filepath, $key, $value, $is_replace = false){
if($filepath && $key && $value){
$arr = array();
$todaydate = date("Ymd",time());
if(!file_exists($filepath)){
@mkdir($filepath,0777);
}
$json = @file_get_contents($filepath."/$todaydate.txt");
if($json){
$arr = json_decode($json, true);
}
if($is_replace == true){
$arr[$key][$todaydate] = $value; //替换
}else{
$arr[$key][$todaydate][] = $value; //追加
}
$json = json_encode($arr);
return file_put_contents($filepath."/$todaydate.txt",$json);
}
}
/**
* 将存储着json格式的文件以数组形式读出
* @access public
* @param string $filepath 文件路径
* @param string $key 数组的key
* @param string $date 日期 格式如 20140904
* @return array
* @author 翁晨 2014-9-4 16:34:03
*/
function get_file_to_array($filepath, $key = '', $date = ''){
$res_arr = array();
if($filepath){
$json = @file_get_contents($filepath);
if($json){
$arr = json_decode($json, true);
$res_arr = $arr;
//筛选key
if(!empty($key)){
if(isset($arr[$key])){
$res_arr = $arr[$key];
//筛选日期
if(!empty($date)){
if(isset($arr[$key][$date])){
$res_arr = $arr[$key][$date];
}else{
$res_arr = array();
}
}
}else{
$res_arr = array();
}
}
}
}
return $res_arr;
}
/**
* 实例化RedisQ
* @author 翁晨 2015-2-15 13:25:38
* @modify 陈东 2015-11-25 12:59:01 redis实例化修改
*/
function redises(){
import("Common.Util.Redisrs");
$redis = new \RedisR();
$options = array (
'host' => C('REDIS_HOST') ? C('REDIS_HOST') : '127.0.0.1',
'port' => C('REDIS_PORT') ? C('REDIS_PORT') : 6379,
);
$redis->addserver($options['host'],$options['port']);
return $redis;
}
/**
* 实例化图像类
* @author 翁晨 2015-8-5 09:41:05
*/
function image(){
import("Common.Util.Image");
return new \image();
}
/**
* 实例化验证码类
* @author 翁晨 2015-8-5 09:41:05
*/
function captcha(){
import("Common.Util.Captcha");
return new \captcha('Public/Images/Captcha/');
}
/**
* 实例化session类
* @author 翁晨 2015-8-5 17:43:45
*/
function session_memcache(){
import("Common.Util.Session");
return new \cls_session(M(), 'rs_sessions', 'SITE_ID');;
}
/**
* 事务提交
* @access public
* @param mixed $db 数据库对象
* @param mixed $arr 事务中的执行结果
* @return bool
*/
function db_commit($arr,$db=''){
$rollback = false;
if(!is_object($db)){ //如果没传数据库对象,则用M实例对象。
$db = M();
}
if(empty($arr)){
$db->rollback(); //回滚
return false; //没验证数据就不执行提交,进行回滚。
}
foreach($arr as $val){
if($val === false){ //事务中只要一个不成功,则回滚。
$rollback = true;
break;
}
}
if($rollback){
$db->rollback(); //回滚
return false;
}else{
$db->commit(); //事务提交
return true;
}
}
/**
* 清除指定后缀的模板缓存或编译文件
* @access public
* @param bool $is_cache 是否清除缓存还是清出编译文件
* @param string $ext 文件后缀
* @return int 返回清除的文件个数
* @author 翁晨 2015-3-23 14:12:54
*/
function clear_tpl_files($is_cache = true, $ext = '') {
$dirs = array();
if ($is_cache) {
$dirs[] = ROOT_PATH .''. APP_PATH . 'Runtime/Temp/';
} else {
$dirs[] = ROOT_PATH .''. APP_PATH . 'Runtime/Cache/Home/';
}
$str_len = strlen($ext);
$count = 0;
foreach ($dirs AS $dir) {
$folder = @opendir($dir);
if ($folder == false) {
continue;
} while ($file = readdir($folder)) {
if ($file == '.' || $file == '..') {
continue;
}
if (is_file($dir . $file)) {
/**
* 如果有后缀判断后缀是否匹配
*/
if ($str_len > 0) {
$ext_str = substr($file, - $str_len);
if ($ext_str == $ext) {
if (@unlink($dir . $file)) {
$count++;
}
}
} else {
if (@unlink($dir . $file)) {
$count++;
}
}
}
}
closedir($folder);
}
return $count;
}
/**
* 清除模版编译文件
* @access public
* @param mix $ext 模版文件名后缀
* @return void
* @author 翁晨 2015-3-23 14:12:54
*/
function clear_compiled_files($ext = null) {
return clear_tpl_files(false, $ext);
}
/**
* 清除缓存文件
* @access public
* @param mix $ext 模版文件名后缀
* @return void
* @author 翁晨 2015-3-23 14:12:54
*/
function clear_cache_files($ext = null) {
return clear_tpl_files(true, $ext);
}
/**
* 清除模版编译和缓存文件
* @access public
* @param mix $ext 模版文件名后缀
* @return void
* @author 翁晨 2015-3-23 14:12:54
*/
function clear_all_files($ext = null) {
$count = clear_tpl_files(false, $ext);
$count += clear_tpl_files(true, $ext);
return $count;
}
/**
* 过滤若干特殊字符 ( 除了 , - _ )
* @return string
* @author 何洋 2015-5-15 17:43:38
*/
function str_filter($str){
if($str){
$str = str_replace("\n", " ", $str);
$str = str_replace("\r", " ", $str);
$str = str_replace("\t", " ", $str);
$regex = "/\/|\~|\!|\@|\\$|\%|\^|\&|\*|\(|\)|\+|\{|\}|\:|\<|\>|\?|\[|\]|\.|\/|\;|\'|\"|\`|\=|\\\|\|/";
$str = preg_replace($regex," ",$str);
}
return $str;
}
/**
* 过滤非英文数字
* @return string
* @author 何洋 2015-5-20 14:58:08
*/
function str_noengnum_filter($str){
if($str){
$regex = "/[^a-zA-Z0-9]/";
$str = preg_replace($regex," ",$str);
}
return $str;
}
/**
* 是否包含对于sql危险的符号
* @return bool
* @author 翁晨 2015-6-5 17:51:26
*/
function is_sql_injection_str($str){
return preg_match("/,|'|\"|;|\!|\*|\\\|\(|\)|\{|\}/", $str);
}
/**
* 检查客户是否在办公室登陆
* @return bool
* @author 韦俞丞 2015-5-25 15:53:57
* @modify 薛升 2016-11-7 16:23:15 增加新的ip
*/
function is_office_ip($ip){
$office_ip_list = array("58.62.236.114","103.206.189.141","218.94.92.98","218.94.92.99","218.94.92.100","218.94.92.101", "58.213.139.99", "71.187.224.61", "58.62.236.115", "58.62.236.116", "58.62.236.117", "58.62.236.118","103.206.188.13", "96.57.190.164","71.187.224.69","91.183.223.210","106.75.143.219","221.226.90.226","58.213.139.102");
if(in_array($ip, $office_ip_list)){
return true;
}else{
return false;
}
}
/**
* 检查是否是整数或小数精确到2位
* @return mixed 如果满足条件返回true,如果不满足条件,返回该值
* @author 薛升 2015-6-15 14:09:10
*/
function check_num_type($num){
if(is_array($num)){
foreach($num as $v){
if(! preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $v)){
return false;
}
}
return true;
}else{
return preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $num) ? true : false;
}
}
/**
* 获取汉字的拼音首字母
*
* @param string $word 汉字
* @return string
* @author 周少峰 2015-6-10 14:49:54
*/
function get_first_char($word){
$first_char = ord($word{0});
if($first_char >= ord("A") and $first_char <= ord("z") )return strtoupper($word{0});
$word_gb = iconv("UTF-8","gb2312", $word);
$word_utf = iconv("gb2312","UTF-8", $word_gb);
if($word_utf == $word){$s = $word_gb;}else{$s = $word;}
$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
if($asc >= -20319 and $asc <= -20284) return "A";
if($asc >= -20283 and $asc <= -19776) return "B";
if($asc >= -19775 and $asc <= -19219) return "C";
if($asc >= -19218 and $asc <= -18711) return "D";
if($asc >= -18710 and $asc <= -18527) return "E";
if($asc >= -18526 and $asc <= -18240) return "F";
if($asc >= -18239 and $asc <= -17923) return "G";
if($asc >= -17922 and $asc <= -17418) return "H";
if($asc >= -17417 and $asc <= -16475) return "J";
if($asc >= -16474 and $asc <= -16213) return "K";
if($asc >= -16212 and $asc <= -15641) return "L";
if($asc >= -15640 and $asc <= -15166) return "M";
if($asc >= -15165 and $asc <= -14923) return "N";
if($asc >= -14922 and $asc <= -14915) return "O";
if($asc >= -14914 and $asc <= -14631) return "P";
if($asc >= -14630 and $asc <= -14150) return "Q";
if($asc >= -14149 and $asc <= -14091) return "R";
if($asc >= -14090 and $asc <= -13319) return "S";
if($asc >= -13318 and $asc <= -12839) return "T";
if($asc >= -12838 and $asc <= -12557) return "W";
if($asc >= -12556 and $asc <= -11848) return "X";
if($asc >= -11847 and $asc <= -11056) return "Y";
if($asc >= -11055 and $asc <= -10247) return "Z";
return null;
}
/**
* 汉字字符串转换成以拼音首字母组成的字符串
*
* @param string $zh 汉字字符串
* @return string
* @author 周少峰 2015-6-10 15:00:28
*/
function pinyin($zh){
$ret = "";
$word_gb = iconv("UTF-8","gb2312", $zh);
$word_utf = iconv("gb2312","UTF-8", $word_gb);
if($word_utf == $zh){$zh = $word_gb;}
for($i = 0; $i < strlen($zh); $i++){
$word_gb = substr($zh,$i,1);
$p = ord($word_gb);
if($p > 160){
$word_utf = substr($zh,$i++,2);
$ret .= get_first_char($word_utf);
}else{
$ret .= $word_gb;
}
}
return $ret;
}
/**
* 二位数组指定键值排序
* @param array $multi_array 待排序数组
* @param string $sort_key 键值
* @param string $sort 排序方式
* @return array
* @author 周少峰 2015-6-10 15:00:28
*/
function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
$new = array();
if(is_array($multi_array)){
foreach ($multi_array as $k=> $row_array){
if(is_array($row_array)){
$key_array[$k] = $row_array[$sort_key];
}else{
return false;
}
}
}else{
return false;
}
asort($key_array);
foreach($key_array as $key =>$val){
$new[] = $multi_array[$key];
}
return $new;
}
/**
* 读取Excel
* @param array $field_arr 字段列表
* @param string $_FILES ['file'] ['tmp_name']
* @return array
* @author 翁晨 2015-6-29 11:28:43
* @modify 何洋 2015-9-11 15:41:30 修改bug
*/
function read_excel($excel_tmp_name,$field_arr=array()){
$res_arr = array ();
if($excel_tmp_name){
import('Vendor.PHPExcel174.excel_class',LIB_PATH,'.php');
//将文件按行读入数组,逐行进行解析
$add_time = time();
$data = new \Spreadsheet_Excel_Reader ();
$data->setOutputEncoding ( 'UTF-8' );
$data->read($excel_tmp_name);
if($field_arr){
//数据存入数组
for($i = 1; $i <= $data->sheets[0]['numRows']; $i ++) {
reset($field_arr);//将数组的内部指针指向第一个单元
for($j = 1; $j <= $data->sheets[0]['numCols']; $j ++) {
if (! empty ( $data->sheets[0]['cells'][$i][$j])) {
if($field_arr){
$res_arr[$i][current($field_arr)] = $data->sheets[0]['cells'][$i][$j];
next($field_arr);
}
}
}
}
}else{
$res_arr = $data->sheets [0] ['cells'];
}
}
return $res_arr;
}
/**
* 生成带校验位的字符串
* @return string
* @author 何洋 2015-7-15 15:43:53
*/
function get_jiaoyan_code39($str){
$str = strtoupper($str.' ');//转换成大写
$allow_word = array('0'=>'0','1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5','6'=>'6','7'=>'7','8'=>'8','9'=>'9','A'=>'10','B'=>'11','C'=>'12','D'=>'13','E'=>'14','F'=>'15','G'=>'16','H'=>'17','I'=>'18','J'=>'19','K'=>'20','L'=>'21','M'=>'22','N'=>'23','O'=>'24','P'=>'25','Q'=>'26','R'=>'27','S'=>'28','T'=>'29','U'=>'30','V'=>'31','W'=>'32','X'=>'33','Y'=>'34','Z'=>'35','-'=>'36','.'=>'37',' '=>'38','$'=>'39','/'=>'40','+'=>'41','%'=>'42');
$out = array();
preg_match_all ( "/^(.+)(.){1}$/i", $str, $out, PREG_PATTERN_ORDER );//分隔字符串和校验位
$jiaoyan_arr = str_split($out[1][0]);//字符串转换成数组
$jiaoyan_num = 0;
foreach($jiaoyan_arr as $key => $val){
$jiaoyan_num += $allow_word[$val];
}
$check_word_arr = array_flip($allow_word);
$check_word = $check_word_arr[($jiaoyan_num%43)];//校验位
return $out[1][0].$check_word;
}
/**
* 异步提交gls、tms数据
*
* @author 何洋 2015-7-27 15:01:26
* @modify 钟宏亮 2016-10-10 11:40:22 增加参数
*/
function curl_post($data,$url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_TIMEOUT,1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000);
$output =curl_exec($ch);
curl_close($ch);
return true;
}
/**
* PHP 模拟POST提交
*
* @author 何洋 2015-8-11 09:54:17
*/
function actionPost($url,$data){ // 模拟提交数据函数
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookie.txt'); // 读取上面所储存的Cookie信息
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)){
echo 'Errno'.curl_error($curl);
}
curl_close($curl); // 关键CURL会话
return $tmpInfo; // 返回数据
}
/**
* 获取csv文件
*
* @author 何洋 2015-8-11 09:54:17
*/
function get_csv($file){
$handle = fopen($file,"r");
while($row = fgetcsv($handle)){
$data[] = $row;
}
fclose($handle);
return $data;
}
/**
* 将数组转为csv字符串
*
* @author 何洋 2015-8-11 09:54:17
*/
function make_csv_str($data , $title = array()){
$res = '';
if(!empty($title))
$res = implode(',' , $title)."\r\n";
if(empty($data))
return $res;
foreach($data as $row){
$row_str = '';
foreach($row as $col){
$row_str .= str_replace(',' , ',' , $col).',';
}
$res .= rtrim($row_str , ',')."\r\n";
}
return $res;
}
/**
* 转为order表city_same字段
*
* @author 何洋 2015-8-11 09:54:17
*/
function city_same($shipping_country_id,$shipping_city,$shipping_province){
// 判断美国和澳大利亚的城市能否和4px的相匹配 city_same 1=相同 2-不同
if ($shipping_country_id == 226 || $shipping_country_id == 13) {
if ($shipping_country_id == 226) { // 不同的国家存于不同的txt
$citys = file_get_contents(ROOT_PATH.'/Public/File/text/United_states.txt');
} else
if ($shipping_country_id == 13) {
$citys = (file_get_contents(ROOT_PATH.'/Public/File/text/Australia.txt'));
}
$citys = json_decode($citys, true);
$temp_city = 2;
$city_name = ucwords(strtolower($shipping_city));
$states_name = strtoupper($shipping_province);
if (isset($citys[$states_name])) { // 获取州下的城市
$city_info = array(
'city_name' => $city_name,
'states_name' => $states_name,
'country_id' => $shipping_country_id
);
if (in_array($city_info, $citys[$states_name])) {
$temp_city = 1;
}
}
return $temp_city;
}
}
/**
* 对数组中的所有元素进行转义
* @param array 需要转义的数组
* @author 林祯 2015-9-21 17:34:15
*/
function addslashes_array($array){
foreach($array as $key => $val){
if(is_array($val)){
$array[$key] = addslashes_array($array[$key]);
}else{
$array[$key] = addslashes($val);
}
}
return $array;
}
/*
* 建立socket连接
* @return array
* @author 林祯 2015-10-9 10:57:52
* @modify 林祯 2016-1-31 11:38:19 修改超时时间
*/
function get_socket($ip,$port){
//创建socket句柄
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($socket < 0){
return array('success'=>0,'msg'=>"Error:socket_create() failed");
}
//尝试进行连接
$result = socket_connect($socket,$ip,$port);
if(!$result){
return array('success'=>0,'msg'=>"Error:socket_connect() failed");
}
socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,array("sec"=>30, "usec"=>0 ) ); // 发送超时30秒
socket_set_option($socket,SOL_SOCKET,SO_SNDTIMEO,array("sec"=>60, "usec"=>0 ) ); // 接收超时60秒
return array('success'=>1,'socket'=>$socket);
}
/*
* 异步发送curl请求
* @return mix
* @param string $url 请求的链接
* @param array $data_multi 发送的数据
* @param boolean $need_return 是否需要返回数据,默认false
* @author 林祯 2015-10-22 09:00:49
* @modify 林祯 2015-11-4 17:18:38 修改变量名bug
*/
function asynch_curl($url,$data_multi,$need_return=false){
//创建curl批处理句柄
$mh = curl_multi_init();
foreach($data_multi as $data){
//创建单个curl资源
$ch = curl_init();
$mch[] = $ch;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
if(!$need_return){
curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//将单个curl资源添加到批处理句柄中
curl_multi_add_handle($mh,$ch);
}
$running = null;
//执行批处理句柄
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active and $mrc == CURLM_OK) {
if(curl_multi_select($mh) === -1){
usleep(100);
}
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
$result = array();
//关闭全部句柄
foreach($mch as $ch){
if($need_return){
//返回的数据
$result[] = curl_multi_getcontent($ch);
}
curl_multi_remove_handle($mh,$ch);
}
curl_multi_close($mh);
return $need_return ? $result : null;
}
/*
* 任务监控邮箱管理
* @param string $type 类型,确定要发送的邮箱
* @param array $mail_arr 邮件内容数组
* @author 林祯 2015-11-17 17:50:14
* @modify 薛升 2017-2-6 15:38:49 增加接收人
*/
function mail_manage($type,$mail_arr){
//管理员邮箱
$manager = array(
0=>'xuming@dotfashion.cn',//徐明
1=>'heyang@dotfashion.cn',//何洋
2=>'linzhen@dotfashion.cn',//林祯
3=>'yangshangru@dotfashion.cn',//杨尚儒
4=>'zhangquan@dotfashion.cn',//张权
5=>'only@dotfashion.cn',//申楚
6=>'stefanie@mywayec.com',
7=>'82542563@qq.com',//许浩
8=>'wendysun@dotfashion.cn',
9=>'mia@dotfashion.cn',
10=>'ywbao@dotfashion.cn',//严武保
12=>'namexiaoping@gmail.com',//夏小平
13=>'liansen.tan@163.com',//谭连森
14=>'luozhidong@dotfashion.cn',//骆志东
15=>'zhuwenfang@dotfashion.cn',//朱文方
16=>'yanyuwu@dotfashion.cn',//颜宇武
17=>'lijieyi@dotfashion.cn',//亚马逊失败
18=>'yuxin@dotfashion.cn',//亚马逊失败
19=>'hulinxiao@dotfashion.cn',//亚马逊自动抓单二次失败
20=>'suhui@dotfashion.cn',//亚马逊自动抓单二次失败
21=>'zhonghongliang@dotfashion.cn',//钟宏亮
22=>'xuesheng@dotfashion.cn',//薛升
23=>'hulinxiao@dotfashion.cn',//胡林霄
24=>'lianyingqun@dotfashion.cn',//连英群
25=>'gezhen@dotfashion.cn'//葛振
);
//$type使用要发邮件的函数名
switch($type){
case 'inventoryBatchOccupy': //库存占用
$addressee = array(0,4,10,3,22);
break;
case 'MonitorMail': //邮件监控
$addressee = array(0,1,2);
break;
case 'yunTuResendAuto': //云图失败列表重发
$addressee = array(0,2,5);
break;
case 'getOrder': //自动抓单
$addressee = array(0,1);
break;
case 'stockEnough': //同步充足库存(全尺码)
$addressee = array(0,1,3);
break;
case 'getTmsApiPrintLabelSingle'://纵腾打标
$addressee = array(1,2);
break;
case 'getTmsApiPrintReturnLabel'://纵腾退货
$addressee = array(0,1,2);
break;
case 'monitorInventoryOccupy': //库存占用监控
$addressee = array(0,1,3,4,5,7,22);
break;
case 'stockEnoughSimple': //同步充足库存(简单)
$addressee = array(6);
break;
case 'checkFbaOrderInventory': //批量核验fba库存数量
$addressee = array(8,9);
break;
case 'qianhuoSyn':
$addressee = array(0,1,3,4,5); //欠货同步操作
break;
case 'stocktakeHuowei': //库存盘点未盘货位
$addressee = array(0,4,5,12,13,14);
break;
case 'FinanceAuto': //财务用友对接
$addressee = array(4,25);
break;
case 'mailErrorMonitor':
$addressee = array(0,1,2); //邮件发送失败数量监控
break;
case 'InventoryScanAuto': //自动库存扫描(订单加队列)
$addressee = array(0,1,2,3,4,5,16);
break;
case 'amazonSynchro': //亚马逊订单数据数据同步失败
$addressee = array(4,17,18);
break;
case 'amazonAutoDown': //亚马逊自动抓单请求接口二次失败
$addressee = array(4,17,18,19,20);
break;
case 'synGoodsStatus': //商品状态同步失败提醒
$addressee = array(0,1,21);
break;
case 'codTrackError': //COD状态追踪失败
$addressee = array(0,1,19);
break;
case 'synShippingNo' : //发货号同步失败提醒
$addressee = array(0,1,23);
break;
case 'FinanceCodAuto':
$addressee = array(0,1,23);
break;
case 'smsErrorMonitor':
$addressee = array(0,1); //短信发送失败数量监控
break;
}
foreach($addressee as $val){
//发送邮件
$data_arr = array(
'name' => 'monitor',
'email' => $manager[$val],
'from' => 'monitor@shein.com',
'subject' => $mail_arr['subject'],
'content' => $mail_arr['content'],
'type' => '',
'is_html' => '',
'site_from' => 'www',
'mail_type' => '',
'billno' => '',
'status' => '',
'admin_name' => 'root',
'is_insert' => 1,
'id' => '',
'yanzheng' => 'qingrenzheng'
);
send_mail_async($data_arr);
}
}
/**
* 发送短信
*
* @author 何洋 2016-4-11 09:54:30
* @modify 薛升 新增短信触发类型
*/
function sms_manage($type,$msg){
$phone_number = array(
0 => '15195805313',//徐明
1 => '13291260805',//何洋
2 => '18352863204',//林祯
3 => '18351933671',//杨尚儒
4 => '15521221277',//张权
5 => '18928725952',//申楚
6 => 'stefanie@mywayec.com',
7 => '18913040526',//许浩
8 => 'wendysun@dotfashion.cn',
9 => 'mia@dotfashion.cn',
10=> 'ywbao@dotfashion.cn',
12=> 'namexiaoping@gmail.com',
13=> 'liansen.tan@163.com',
14=> 'luozhidong@dotfashion.cn',
15=> '15521221376',//颜宇武
16=> '18069151585',//胡林霄
17=> '18336159234',//杜佳彬
18=> '18608178285',//雷杰
19=> '15856313969',//钟宏亮
20=> '13013962752',//李杰
21=> '17625922569',//薛升
);
switch($type){
case 'getOrder': //自动抓单
$phone = array(0,1);
break;
case 'monitorInventoryOccupy': //库存占用监控
$phone = array(0,1,3,4,5,7,21);
break;
case 'InventoryScanAuto': //自动库存扫描(订单加队列)
$phone = array(0,1,2,4,5,15);
break;
case 'yunTuResendAuto': //云图失败列表重发
$phone = array(0,2,5);
break;
case 'mailErrorMonitor':
$phone = array(0,1,2); //邮件发送失败数量监控
break;
case 'stockEnough': // 同步充足库存--库存未变化监控
$phone = array(0, 1, 3);
break;
case 'amazonSynchro': // 同步亚马逊订单运单号 没有批次号监控
$phone = array(0,1,4,16);
break;
case 'codTrackError': // cod已签收、派件异常监控
$phone = array(0,1,16);
break;
case 'orderDataOperate':
$phone = array(1,2,15,17); //打包机无重量报警
break;
case 'synGoodsStatus':
$phone = array(0,1,19); //商品状态同步失败提醒
break;
case 'mailSendMonitor': //邮件发送失败提醒
$phone = array(0,1,2);
break;
case 'logisticsApiError': //物流接口失败提醒
$phone = array(0,1,20);
break;
case 'synShippingNo': //发货号同步失败提醒
$phone = array(0,1,16);
break;
case 'synIsReplace'://换货同步失败提醒
$phone = array(0,1,16);
break;
case 'stockEnoughSimple': //同步充足库存(简单)
$phone = array(0,3,21);
break;
case 'orderCheckBatchOccupy': //批量审核的占用库存
$phone = array(0,3,21);
break;
case 'OccupyInventory': //库存占用
$phone = array(3,21);
break;
case 'getOnSellingProductIds': //获取速卖通上架商品
$phone = array(3,21);
break;
}
foreach($phone as $v){//重组手机号
$mobile[]=$phone_number[$v];
}
$mobile = implode(',',$mobile);//发送手机号
if($msg&&$mobile){
send_sms($mobile,$msg);//发短信
}
}
/**
* 发送短信接口
*
* @author 何洋 2016-4-11 09:54:30
*/
function send_sms($mobile,$msg){
if(C('SMS_IS_SEND')){//允许发送短信
if($msg&&$mobile){
$key = C('SMS_KEY');//key
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, C('SMS_URL'));//批量
curl_setopt($ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_0 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD , 'api:key-'.$key);//KEY
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile_list' => $mobile,'message' => '提醒:'.$msg.'【供应链】'));
$res = curl_exec( $ch );
curl_close( $ch );
@file_put_contents(ROOT_PATH.'/Logs/sms_log/'.date('Ymd').'.txt',date('Y-m-d H:i:s').' '.$mobile.' '.$msg.' '.$res."\r\n",FILE_APPEND);
//$res = curl_error( $ch );
$res = json_decode($res,true);//json强制转数组
if($res['error'] == 0){//error=0成功、其他失败
return true;
}else{//失败
return false;
}
}
}else{
return false;
}
}
/**
* 将对象转换成数组
*
* @author 林祯 2016-3-9 13:17:49
*/
function object_array($obj){
//强制转换成数组
$arr = (array)$obj;
//兼容多维数组
foreach($arr as $key => $val){
if(is_object($val) ||is_array($val)){
$arr[$key] = object_array($val);
}
}
return $arr;
}
/**
* 获取pdf对象
*
* @author 林祯 2016-3-23 17:03:37
*/
function pdf($dire = 'P',$unit = 'mm',$size = array(99,150)){
vendor('tcpdf.pdf');
$pdf = new \PDF($dire,$unit,$size);
return $pdf;
}
/**
* 导出数据到excel文件
*
* @author 林祯 2016-04-28 12:02:200
*/
function export_excel($head = array(),$data = array(),$file = ''){
$file = $file ? $file : "excel-".date("Y-m-d-H-i-s");//文件名
//输出头
header("Content-type:application/vnd.ms-excel" );
header("Content-Type: application/download" );
header("Content-Disposition:filename=".$file.".xls" );
if(!empty($head)){//输出表头
foreach($head as $h){
echo $h."\t";
}
echo "\n";
}
if(!empty($data)){
foreach($data as $row){//行数据
foreach($row as $col){//列数据
echo $col."\t";
}
echo "\n";
}
}
}
/**
* 多维数组去重
*
* @author 林祯 2016-05-03 15:02:31
*/
function unique($array){
$new_arr = array();
foreach($array as $arr){
$new_arr[] = json_encode($arr);//转换成一维数组
}
$new_arr = array_unique($new_arr);//去掉重复
foreach($new_arr as $key => $arr){
$new_arr[$key] = json_decode($arr,true);//恢复数据
}
return $new_arr;
}
/**
* 建立ftp连接
*
* @author林祯 2015-12-03 09:53:21
*/
function get_ftp_connection($ip,$user,$pwd,$port=21){
//数据初始化
$is_success = 0;
$conn = '';
$msg = '';
//连接ftp服务器
$conn = ftp_connect($ip,$port);
if(!$conn){
$msg = 'ftp服务器连接失败';
}else{
//登陆ftp服务器
$login = ftp_login($conn,$user,$pwd);
if(!$login){
$msg = 'ftp服务器登陆失败';
}else{
$is_success = 1;
}
}
return array('is_success'=>$is_success,'conn'=>$conn,'msg'=>$msg);
}
/**
* XML转化为数组
*
* @author 何洋 2016-3-17 14:37:20
*/
function xml_to_array($xml){
$reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
if(preg_match_all($reg, $xml, $matches)){
$count = count($matches[0]);
$arr = array();
for($i = 0; $i < $count; $i++){
$key= $matches[1][$i];
$val = xml_to_array( $matches[2][$i] ); // 递归
if(array_key_exists($key, $arr)){
if(is_array($arr[$key])){
if(!array_key_exists(0,$arr[$key])){
$arr[$key] = array($arr[$key]);
}
}else{
$arr[$key] = array($arr[$key]);
}
$arr[$key][] = $val;
}else{
$arr[$key] = $val;
}
}
return $arr;
}else{
return $xml;
}
}
/**
* 105后台通过curl请求93后台API
*
* @param int $site 站点 1shein 2rw 3mmc
* @param string $uri 方法相对路径
* @param array $param 请求信息数组
* @return array
* @author 韦俞丞 2016-06-14 16:42:52
* @modify 薛升 2017-2-23 09:26:13 认证接口动态获取
*/
function website_api($site, $uri, $param = array()) {
if (!$verification_config = parse_ini_file(C('VERIFICATION_ACCESS'), true)) {
return array('success' => 0, 'message' => '未能获取安全认证账户配置');
}
switch ($site) {// 读取站点url、账户、密码
case 1:
$name = 'shein';
$config = $verification_config['admin_shein'];
break;
case 2:
$name = 'rw';
$config = $verification_config['admin_romwe'];
break;
case 3:
$name = 'mmc';
$config = $verification_config['admin_mmc'];
break;
case 4:
$name = 'ec';
$config = $verification_config['admin_emc'];
break;
}
if (isset($config['host']) && $config['host'] && $uri) { //拼接最终访问的url
$prefix = sprintf(
"http://%s{$config['host']}",
isset($config['user']) && $config['user'] ? $config['user'] . ':' . $config['password'] . '@' : ''
);
$url = $prefix . $uri;
} else {
return array('success' => 0, 'message' => '未能获取站点url或方法路径');
}
$header = array(
'Content-type: application/json',
'SiteUID: all',
'ClientId: 105',
'Accept: application/json'
);
$ch = curl_init();// 初始化会话
$options = array(
CURLOPT_URL => $url,// 要访问的url
CURLOPT_RETURNTRANSFER => true,// 获取的信息以字符串返回
CURLOPT_HTTPHEADER => $header,// 设置HTTP header
CURLOPT_POST => true,// 全部数据使用HTTP协议中的 "POST" 操作来发送
CURLOPT_POSTFIELDS => json_encode($param),// 将数据转成json
CURLOPT_CONNECTTIMEOUT => 30,// 在尝试连接时等待的秒数
CURLOPT_TIMEOUT => 60,// 允许 cURL 函数执行的最长秒数
);
if(cookie("xujiajia")=='api'){
print_r($options);
exit;
}
curl_setopt_array($ch, $options);// 批量设置选项
$res_json = curl_exec($ch);// 执行会话
// var_dump($res_json);
// var_dump($url);
// var_dump($param);
if (curl_errno($ch)) {
$error = curl_error($ch);// curl错误信息
}
$res = json_decode($res_json, true);// 返回关联数组
curl_close($ch);// 关闭句柄
$data = array(
'curl_error' => $error,
'name' => $name,
'uri' => $uri,
'param' => $param,
'res' => $res
);
if ($res['code'] === 0) {// code为0表示93没报错
if ($res['info']) {// 返回数据不为空,不写日志
return array('success' => 1, 'content' => $res['info']);
} else {// 返回数据为空,异常,写日志
$msg = website_api_log($data);
return array('success' => 1, 'content' => $res['info'], 'message' => $msg);
}
} else {// code不为0,表示93报错,写日志
$msg = website_api_log($data);
return array('success' => 0, 'content' => $res['info'], 'message' => $msg);
}
}
/**
* api写日志
* @param array $data 数据集合,减少参数个数
* @return string $log 错误信息
* @author 韦俞丞 2016-06-14 16:42:52
* @modify 陈东 2016-8-25 12:13:11 修改目录
*/
function website_api_log($data) {
$curl_error = $data['curl_error'];// curl报错信息
$name = $data['name'];// 站点缩写
$uri = $data['uri'];// 方法地址
$param = $data['param'];// 参数
$res = $data['res']; // curl返回信息
if ($curl_error) {// curl报错
$log = 'cURL报错:' . $curl_error;
} elseif ($res['code']) {// 接口请求成功返回错误信息
$log = '返回错误信息:' . $res['msg'];
} elseif ($res['code'] == 0 && !$res['info']) {// 请求成功但未返回数据
$log = '返回数据为空';
} else {
$log = '返回信息不符合规范,无法解析';
}
$str = date('Y-m-d H:i:s') . " 站点:$name 相对路径:$uri 参数:" . json_encode($param) . ' 错误类型:' . $log . "\r\n";
if (strpos($uri, 'get_supplier')) {
$dir = 'supplier';
}elseif(strpos($uri, 'update_goods_cost_log')){
$dir = 'update_goods_cost';
}elseif(strpos($uri, 'Stock')){
$dir = 'Stock';
}
write_log_to_file(ROOT_PATH.'/Logs/website_api/' . $dir, $str);
return $log;
}
/**
* 将信息追加写入日志文件
*
* @param string $filepath 文件路径
* @param string $str 追加写入的文本信息
* @author 韦俞丞 2016-06-24 14:44:59
*/
function write_log_to_file($filepath, $str) {
if ($filepath && $str) {
$todaydate = date("Ymd", time());
if (!file_exists($filepath)) {
@mkdir($filepath, 0777);
}
file_put_contents($filepath."/$todaydate.txt", $str, FILE_APPEND);
}
}
/**
*
* 缓存管理(Redis key=>value)
* @param mixed $name 缓存名称
* @param mixed $value 缓存值
* @param mixed $options 缓存参数/过期时间
* @return mixed
* @author 杨尚儒 2016-6-22 14:09:05
* @modify 田靖 2016-07-04 14:14:48 key加上前缀supplychain
*/
function redis_cache($name,$value='',$options=null) {
$redis_obj = redises();//获取系统封装的reids的类
$redis = $redis_obj->redis();//获取redis的原生类
$name = 'supplychain'.$name;//加前缀
if(''=== $value){ // 获取缓存
return $redis->get($name);
}elseif(is_null($value)) { // 删除缓存
return $redis->delete($name);
}else { // 缓存数据
if(is_array($options)) {
$expire = isset($options['expire'])?$options['expire']:NULL;
}else{
$expire = is_numeric($options)?$options:NULL;
}
if(empty($expire)){
$expire = 3600;//默认缓存一小时
}
return $redis->setex($name, $expire,$value);//带有时间的写入
}
}
/**
* 将字符串'S:5<br/>M:5<br/>L:5<br/>' 转成 数组['S'=>5,'M'=>5,'L'=>5]
* @param string 尺码数量字符串
* @return array 尺码数量数组
* @author 薛升 2016-6-27 13:46:49
*/
function attr_num_convert($attr_num)
{
$attr_num = explode('<br/>', rtrim($attr_num, '<br/>'));
$attr_num_arr = array();
foreach ($attr_num as $value){
if($value){
$cuu_arr = explode(":", $value);
$attr_num_arr[$cuu_arr[0]] = intval($cuu_arr[1]);
}
}
return $attr_num_arr;
}
/**
* 读取Excel 并返回多个sheet信息
* @param array $field_arr 字段列表
* @param string $_FILES ['file'] ['tmp_name']
* @return array
* @author 田靖 2016-08-03 09:51:04
* @modify 田靖 2016-09-13 17:26:18 处理float数据
*/
function read_excel_form($excel_tmp_name){
import('Vendor.PHPExcel174.PHPExcel.IOFactory',LIB_PATH,'.php');
$objPHPExcel = PHPExcel_IOFactory::load($excel_tmp_name);
$sheetCount = $objPHPExcel->getSheetCount();
$data = array();
for ( $k = 0; $k < $sheetCount; $k++ ) {
$sheet = $objPHPExcel->getSheet($k);
//获取行数与列数,注意列数需要转换
$highestRowNum = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnNum = PHPExcel_Cell::columnIndexFromString($highestColumn);
//开始取出数据并存入数组
for($i=1;$i<=$highestRowNum;$i++){
$row = array();
for($j=0; $j<$highestColumnNum;$j++){
$cellName = PHPExcel_Cell::stringFromColumnIndex($j).$i;
$cellVal = $sheet->getCell($cellName)->getValue();
if(is_numeric($cellVal)){
if(!preg_match("/^[0-9]+(.[0-9]{1,10})?$/", $cellVal)){
$cellVal = sprintf("%.10f",$cellVal);
$cell_float = explode('.',$cellVal);
$jiequ = 0;
for ($p=9; $p >=0 ; $p--) {
if($cell_float[1][$p]==0){
continue;
}
$jiequ = ($p-9);
break;
}
if($jiequ!==0){
$cellVal = substr($cellVal,0,$jiequ);
}
}
}
$row[ $j ] = strval($cellVal);
}
$data [$k][]= $row;
}
}
return $data;
}
/**
* 返回数组中指定的一列
* @param array $input 需要取出数组列的多维数组(或结果集)
* @param mixed $column_key 需要返回值的列,它可以是索引数组的列索引,或者是关联数组的列的键。
* @param mixed $index_key 作为返回数组的索引/键的列,它可以是该列的整数索引,或者字符串键值。
* @return array
* @author 薛升 2016-6-27 13:46:49
*/
if (!function_exists('array_column')) {
function array_column($input, $column_key, $index_key = null)
{
$result = array();
foreach ($input as $subArray) {
if (!is_array($subArray)) {
continue;
} elseif (is_null($index_key) && array_key_exists($column_key, $subArray)) {
$result[] = $subArray[$column_key];
} elseif (array_key_exists($index_key, $subArray)) {
if (is_null($column_key)) {
$result[$subArray[$index_key]] = $subArray;
} elseif (array_key_exists($column_key, $subArray)) {
$result[$subArray[$index_key]] = $subArray[$column_key];
}
} elseif(is_null($column_key)) {
$result[] = $subArray;
}
}
return $result;
}
}
/**
* CRM发短信
*
* @author 林祯 2016-9-12 18:49:38
* @modify 许佳佳 2017-02-27 11:35:01 更换接口为splio平台
*/
function crm_sms($mobile,$msg,$plat = 'splio')
{
import('Vendor.SysSms.SysSms',LIB_PATH,'.php');
$plat = 'splio';
//直接短信发送参数
$param = array(
'key' => 'RiESa1Lez5wDRQy0tW',
'customerNum' => '00'.$mobile,
'sendNum' => '85259259059',
'content' => $msg,
'lang' => 'en',
'site' => 'shein',
'sys_tag' => 'supply_shein',
'sms_platform' => $plat
);
$log = date('Y-m-d H:i:s')."\r\n";
$log .= 'request:'.json_encode($param)."\r\n";
$sms = new SysSms();
$response = $sms->call($param);
//记录日志
$log .= 'response:'.json_encode($response)."\r\n-------------------------------------------------\r\n";
@file_put_contents(ROOT_PATH.'/Logs/crm_sms/'.date('Ymd').'.txt',$log,FILE_APPEND);
if($response['status'] == 1){
return true;
}else{
$GLOBALS['sms_error'] = $response['info'];
return false;
}
}
/**
* 105后台通过curl请求105本地后方法
* @param string $uri 方法相对路径
* @param array $param 请求信息数组
* @return array
* @author 葛振 2016-10-24 16:08:26
*/
function website_api_self($uri,$param=array()){
$prefix=C('CURL_API_SELF');
$url=$prefix.$uri;
$ch = curl_init();// 初始化会话
$options = array(
CURLOPT_URL => (string)$url,// 要访问的url
CURLOPT_RETURNTRANSFER => true,// 获取的信息以字符串返回
CURLOPT_POST => true,// 全部数据使用HTTP协议中的 "POST" 操作来发送
CURLOPT_POSTFIELDS => json_encode($param),// 将数据转成json
CURLOPT_CONNECTTIMEOUT => 30,// 在尝试连接时等待的秒数
CURLOPT_TIMEOUT => 60,// 允许 cURL 函数执行的最长秒数
CURLOPT_HTTPHEADER=>array("ClientId:105")//头信息
);
curl_setopt_array($ch, $options);// 批量设置选项
$res_json = curl_exec($ch);// 执行会话
return $res_json;
}
/**
* 异步发送短信
* @author 李杰 2016-11-02 10:18:07
* @modify 许佳佳 2017-02-28 14:31:24 短信接口全部对接为splio平台
*/
function send_sms_async($data_arr, $url, $errno='', $errstr=''){
//访问地址
$url = $url ? $url : C('MAIL_HOST').':'.C('MAIL_PORT');
//初始化参数
$data_arr = array(
'billno' => $data_arr['billno'],
'phone' => $data_arr['phone'],
'content' => $data_arr['content'],
'admin_name' => $data_arr['admin_name'],
'is_insert' => $data_arr['is_insert'],
'id' => $data_arr['id'],
'plat'=>$data_arr['plat'],
);
//组建内容字符串
$post_data = '';
$post_data .= "billno=".$data_arr['billno'];
$post_data .= "&phone=".$data_arr['phone'];
$post_data .= "&content=".urlencode($data_arr['content']);
$post_data .= "&admin_name=".$data_arr['admin_name'];
$post_data .= "&is_insert=".$data_arr['is_insert'];
$post_data .= "&id=".$data_arr['id'];
$post_data .= "&plat=".$data_arr['plat'];
//POST url
$fp = fsockopen($url,80,$errno,$errstr,30);
if($fp){
$out = "POST http://".$url.__APP__."/Home/SmsSendAsync HTTP/1.0\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Content-Length: " . strlen ( $post_data ) . "\r\n\r\n";
fputs($fp, $out.$post_data);
$send_status = false;
if($data_arr['is_insert'] != 1){
while (!feof($fp)) {
$receive = fgets($fp, 128);
if (strcmp ( $receive, "SEND_SMS_TRUE" ) == 0) {
$send_status = true;
}
}
}
fclose($fp);
return $send_status;
}
}
/**
* redis hash操作
*
* @author 林祯 2016-08-29 11:17:23
*/
function redis_hash($hash_key,$field = '',$data = '')
{
$redis = redises();
if(empty($hash_key)){
return false;
}
if($data === ''){//获取数据
if($field == ''){
$data = $redis->hGetAll($hash_key);
foreach($data as $key => $val){//逐个判断是否为json
$json = json_decode($val,true);
if(is_array($json)){
$data[$key] = $json;
}
}
}else{
$data = $redis->hGet($hash_key,$field);
$json = json_decode($data,true);//判断是否为json
if(is_array($json)){
$data = $json;
}
}
return $data;
}elseif(is_null($data)){//删除数据
if($field){//删除单个域
return $redis->hDel($hash_key,$field);
}
//删除所有域
$keys = $redis->hKeys($hash_key);//获取这个键的所有域
$redis->multi();//事务
foreach($keys as $val){//遍历进行删除
$redis = $redis->hDel($hash_key,$val);
}
$res = $redis->exec();//执行事务
foreach($res as $val){
if(!$val) return false;
}
return true;
}else{//存储数据
if($field == ''){//批量存储
foreach($data as $key => $val){
if(is_array($val)){
$data[$key] = json_encode($val);
}
}
return $redis->hMset($hash_key,$data);
}else{//单个键值存储
if(is_array($data)){
$data = json_encode($data);
}
return $redis->hSet($hash_key,$field,$data);
}
}
}
/**
* 导出excel(只一个sheet情况下,扩展名为xls)
* @param array $header 列头,列值
* @param array $data 数据值
* @param string $excel_name 文件名
* @author 卞钉 2017-1-12 11:22:07
*/
function down_excel($header = array() ,$data=array() , $excel_name=''){
//引入PHPExcel
vendor("PHPExcel174.PHPExcel");
$objPHPExcel = new \PHPExcel();
// 设置excel文档的属性
$objPHPExcel->getProperties()->setCreator("ctos")
->setLastModifiedBy("ctos")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
/*
* 开始操作excel表
*/
// 操作第一个工作表
$objPHPExcel->setActiveSheetIndex(0);
// 设置默认字体和大小
$objPHPExcel->getDefaultStyle()->getFont()->setName(iconv('gbk', 'utf-8', '微软雅黑'));
$objPHPExcel->getDefaultStyle()->getFont()->setSize(12);
$objPHPExcel->getActiveSheet()->getRowDimension()->setRowHeight(40);
foreach($header as $k=>$v){
$objPHPExcel->getActiveSheet()->setCellValue($k."1", $v['name']);
}
$count = count($data);
for ($i = 2; $i <= $count+1; $i++) {
foreach ($header as $k=>$v) {
$objPHPExcel->getActiveSheet()->setCellValueExplicit($k. $i, $data[$i-2][$v['value']],\PHPExcel_Cell_DataType::TYPE_STRING);
}
}
// 设置输出EXCEL格式
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// 从浏览器直接输出$filename
$filename = $excel_name.'.xls';
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type: application/vnd.ms-excel;");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
header("Content-Disposition:attachment;filename=".$filename);
header("Content-Transfer-Encoding:binary");
$objWriter->save("php://output");
}
/**
* 调试信息输出到控制台
*
* @param $data
* @author Alex&陈超 2017-01-24 16:51
*/
function debug($data, $title = 'Alex')
{
$dbt = current(debug_backtrace());
$fileArr = explode('\\', $dbt['file']);
$fileTitle = $title . ':' . end($fileArr) . ':' . $dbt['line'] . '\n';
echo("<script>console.info('$fileTitle', ".json_encode($data).");</script>");
}
/**
* curl file obj
* @param $file 为了兼容代码中的$_FILE , $_FILE['tmp_name'] , 相对路径 不做特殊限制
* @ new CURLFile php > 5.5
* @author 许佳佳 2017-01-23 11:49:25
*/
function curl_file_create_obj($file){
if( is_array($file) && isset($file['tmp_name']) ){
$file = realpath($file['tmp_name']);
}elseif( is_string($file) && strpos($file , '..') === false ){
$file = realpath($file);
}elseif( strpos($file, '..') !== false ){
$file = str_replace("../" , ROOT_PATH , $file);
}
if(version_compare( PHP_VERSION,'5.5') == '-1'){
$file_tmp = "@".$file;
}else{
$file_tmp = new CURLFile($file);
}
return $file_tmp;
}
/**
* 判断数组是否为索引数组
*
* @param $arr
* @return bool|mixed
* @author Alex&陈超 2017-03-04 上午11:02
*/
function is_list($arr)
{
if (!is_array($arr)) {
return false;
} else if (empty($arr)) {
return true;
} else {
$isKeyNum = array_map('is_numeric', array_keys($arr));
return !in_array(false, $isKeyNum);
}
}
/**
* 以goods_sn为入参请求bi数据接口
*
* @param $key 指定key
* @param $arr 入参
* @author 卞钉 2017-03-13 10:15:11
* $param=array(
'token'=>'7KsJzMlRwEwIVO88KPRLGg==',
'key'=>$key,
'goods_sn'=>array(),
)
);
*/
function data_shein_api($key='',$params = array()){
$remote = C('DATA_SHEIN_URL');
$data = array(
'token'=>'7KsJzMlRwEwIVO88KPRLGg==',
'key' =>$key,
'goods_sn' => $params,);
$_param = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote);
//关闭证书校验
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT,600);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_param);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$http_info = curl_getinfo($ch);
$curl_no = curl_errno($ch);
curl_close($ch);
if($http_info['http_code'] != '200'){
return array('success'=>0,'message'=>'http请求失败,status:'.$http_info['http_code'],',机器ip:'.$http_info['local_ip'].'=>'.$http_info['primary_ip']);
}
if($curl_no){
return array('success'=>0,'message'=>'curl error:'.curl_error($ch));
}
$res_arr = json_decode($res,true);
$json_error = json_last_error();
if($json_error == 0){
if($res_arr['code']!='200'){
return array('success'=>0,'message'=>"对方返回业务错误码:".$res_arr['code'].','.$res_arr['msg']);
}else{
return array('success'=>1,'content'=>$res_arr);
}
}else{
return array('success'=>0,'message'=>'解析对方JSON错误,错误码:'.$json_error);
}
} |
Java | UTF-8 | 3,786 | 3.28125 | 3 | [] | no_license | package batch_processing.batch_insert;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
/**
* Insert Batch operation using PreparedStatement Interface
* @author Ramesh Fadatare
*
*/
public class BatchInsertExample {
public static void main(String[] args) {
parameterizedBatchUpdate();
}
public static void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
private static void parameterizedBatchUpdate() {
String INSERT_USERS_SQL = "INSERT INTO users" + " (id, name, email, country, password) VALUES " +
" (?, ?, ?, ?, ?);";
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test1?useSSL=false", "root", "");
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
connection.setAutoCommit(false);
preparedStatement.setInt(1, 20);
preparedStatement.setString(2, "a");
preparedStatement.setString(3, "a@gmail.com");
preparedStatement.setString(4, "India");
preparedStatement.setString(5, "secret");
preparedStatement.addBatch();
preparedStatement.setInt(1, 21);
preparedStatement.setString(2, "b");
preparedStatement.setString(3, "b@gmail.com");
preparedStatement.setString(4, "India");
preparedStatement.setString(5, "secret");
preparedStatement.addBatch();
preparedStatement.setInt(1, 22);
preparedStatement.setString(2, "c");
preparedStatement.setString(3, "c@gmail.com");
preparedStatement.setString(4, "India");
preparedStatement.setString(5, "secret");
preparedStatement.addBatch();
preparedStatement.setInt(1, 23);
preparedStatement.setString(2, "d");
preparedStatement.setString(3, "d@gmail.com");
preparedStatement.setString(4, "India");
preparedStatement.setString(5, "secret");
preparedStatement.addBatch();
int[] updateCounts = preparedStatement.executeBatch();
System.out.println(Arrays.toString(updateCounts));
connection.commit();
connection.setAutoCommit(true);
} catch (BatchUpdateException batchUpdateException) {
printBatchUpdateException(batchUpdateException);
} catch (SQLException e) {
printSQLException(e);
}
}
public static void printBatchUpdateException(BatchUpdateException b) {
System.err.println("----BatchUpdateException----");
System.err.println("SQLState: " + b.getSQLState());
System.err.println("Message: " + b.getMessage());
System.err.println("Vendor: " + b.getErrorCode());
System.err.print("Update counts: ");
int[] updateCounts = b.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
System.err.print(updateCounts[i] + " ");
}
}
}
|
Go | UTF-8 | 2,825 | 3.4375 | 3 | [] | no_license | package main
import (
"bufio"
"fmt"
"log"
"net"
"time"
)
type client struct {
c chan<- string
name string
}
var (
entering = make(chan client)
leaving = make(chan client)
messages = make(chan string) // all incoming client messages
)
func main() {
listener, err := net.Listen("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
go broadcaster()
for {
conn, err := listener.Accept()
if err != nil {
log.Print(err)
continue
}
go handleConn(conn)
}
}
func broadcaster() {
clients := make(map[client]bool) // all connected clients
for {
select {
case msg := <-messages:
// Broadcast incoming message to all
// clients' outgoing message channels.
for cli := range clients {
cli.c <- msg
}
case cli := <-entering:
sendParticipants(cli.c, clients)
clients[cli] = true
case cli := <-leaving:
delete(clients, cli)
close(cli.c)
}
}
}
func sendParticipants(c chan<- string, clients map[client]bool) {
allClients := ""
for currentCli := range clients {
allClients += fmt.Sprintf("%q, ", currentCli.name)
}
if len(clients) == 0 {
allClients = "You are the only one in the chat."
}
if len(clients) == 1 {
allClients += "is in the chat."
} else if len(clients) >= 2 {
allClients += "are in the chat."
}
c <- allClients
}
func handleConn(conn net.Conn) {
ch := make(chan string) // outgoing client messages
go clientWriter(conn, ch)
input := bufio.NewScanner(conn)
cli := createClient(ch, input)
messages <- cli.name + " has arrived"
entering <- cli
finishCh := make(chan bool)
continueCh := make(chan bool)
connClosedCh := make(chan bool)
go clientTimeout(finishCh, continueCh)
go readMessages(input, cli.name, messages, continueCh, connClosedCh)
select {
case <-finishCh:
fmt.Printf("timeout: %s\n", cli.name)
conn.Close()
case <-connClosedCh:
fmt.Printf("connection closed: %s\n", cli.name)
}
leaving <- cli
messages <- cli.name + " has left"
}
func clientWriter(conn net.Conn, ch <-chan string) {
for msg := range ch {
fmt.Fprintln(conn, msg) // NOTE: ingnoring network errors
}
}
func createClient(ch chan string, input *bufio.Scanner) client {
ch <- "Please enter your name: "
input.Scan()
who := input.Text()
ch <- "Welcome, " + who
return client{c: ch, name: who}
}
func clientTimeout(finishCh chan bool, continueCh chan bool) {
for {
select {
case cont := <-continueCh:
if !cont {
return
}
case <-time.After(20 * time.Second):
finishCh <- true
}
}
}
func readMessages(input *bufio.Scanner, who string, messages chan string, continueCh chan bool, connClosedCh chan bool) {
for input.Scan() {
continueCh <- true
messages <- who + ": " + input.Text()
}
// NOTE: ignoring potential errors from input.Err()
// The connection is closed
connClosedCh <- true
}
|
Java | UTF-8 | 1,011 | 2.140625 | 2 | [] | no_license | package com.liang.lagou.mail.config;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
* smtp配置类
*
* 项目中可能有多邮箱配置,
* neuabc,dam和neupals可能都有自己的邮箱配置,因为发送人不一样
*/
@Component
@ConfigurationProperties(prefix = "smtp-mail")
public class SmtpEmailProperties {
private final Lagou lagou = new Lagou();
public Lagou getLagou() {
return lagou;
}
@Getter
@Setter
@ToString
public static class Lagou{
private String host;
private int port;
private String defaultEncoding;
private String protocol;
private String username;
private String password;
private String fromAlias;
private boolean testConnection;
private Properties properties;
}
}
|
JavaScript | UTF-8 | 2,068 | 2.625 | 3 | [
"MIT"
] | permissive | import React, {Component} from 'react';
import { Panel,Form,FormGroup,FormControl,ControlLabel } from 'react-bootstrap';
class Report extends Component {
constructor(props) {
super(props);
this.state = {
report: [],
item:'',
value:'',
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handlePrev = this.handlePrev.bind(this);
this.handleNext = this.handleNext.bind(this);
}
handleChange(event) {
if (event.target.name === 'item') {
this.setState({item: event.target.value});
} else {
this.setState({password: event.target.value});
}
}
handleSubmit(event) {
event.preventDefault();
}
handlePrev(event) {
event.preventDefault();
this.setState({isAuthenticated: false});
}
handleNext(event) {
event.preventDefault();
this.setState({isAuthenticated: false});
}
displayForm() {
return (
<Form onSubmit={this.handleSubmit}>
<FormGroup controlId="formItem">
<ControlLabel>Item</ControlLabel>
<FormControl type="text"
name="item"
placeholder="Item" value={this.state.item} onChange={this.handleChange} />
</FormGroup>
<FormGroup controlId="formItem">
<ControlLabel>cost</ControlLabel>
<FormControl type="text"
name="cost"
placeholder="ammount" value={this.state.cost} onChange={this.handleChange} />
</FormGroup>
</Form>
)
}
displayItem() {
return (
<Panel>
<Panel.Heading>
<Panel.Title componentClass="h3">Reports</Panel.Title>
</Panel.Heading>
<Panel.Body>
{this.displayForm()}
</Panel.Body>
</Panel>
)
}
displayReport() {
return (
<Panel>
<Panel.Heading>
<Panel.Title componentClass="h3">Report</Panel.Title>
</Panel.Heading>
<Panel.Body>
<p>Items: {this.state.report.length}</p>
<p>Target: {this.state.target}</p>
</Panel.Body>
</Panel>
)
}
render() {
return (
<div className="App-container">
{this.displayReport()}
{this.displayItem()}
</div>
)
}
}
export default Report; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.