language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 699
| 2.515625
| 3
|
[] |
no_license
|
# Article R731-16
Les cotisations dues pour les membres de la famille de l'exploitant assurés obligatoires (ascendants, descendants, frères,
soeurs, alliés au même degré) incombent à l'exploitant pour la totalité, sauf le cas où l'assuré perçoit la rémunération
normale en espèces des travailleurs de sa catégorie.
**Liens relatifs à cet article**
_Anciens textes_:
- Décret n°50-444 1950-04-20 art. 15, par. 1
- Décret n°50-444 du 20 avril 1950 - art. 15 (Ab)
_Codifié par_:
- Décret n°2005-368 2005-04-19
_Créé par_:
- Décret n°2005-368 2005-04-19 art. 1, annexe JORF 22 avril 2005
- Décret n°2005-368 du 19 avril 2005 - art. 1 (V) JORF 22 avril 2005
|
Java
|
UTF-8
| 1,126
| 2.203125
| 2
|
[] |
no_license
|
package com.miller.o2o.dao;
import com.miller.o2o.BaseTest;
import com.miller.o2o.entity.ProductCategory;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by miller on 2019/3/16
*
* @author Miller
*/
public class ProductCategoryDaoTest extends BaseTest {
@Autowired
private ProductCategoryDao categoryDao;
@Test
public void selectByShopId() {
List<ProductCategory> productCategories = categoryDao.selectList(4);
assertEquals(5,productCategories.size());
}
@Test
public void batchInsert() {
List<ProductCategory> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add(ProductCategory.builder().name("分类" + i).priority(i).shopId(4l).build());
}
int i = categoryDao.batchInsert(list);
assertTrue(i > 0);
}
@Test
@Ignore
public void delete() {
int delete = categoryDao.delete(4, 4);
assertEquals(1, delete);
}
}
|
C#
|
UTF-8
| 729
| 4.0625
| 4
|
[] |
no_license
|
// Ex.118 - Nested counters, goto
// Create a program with two nested loops:
//
// In the outer loop, "i" must go from 1 to 10
// In the inner loop, "j" must go from 20 to 30
// with a step of 2
// Display the values of "i" and "j"
// You must interrupt the loop when "i"
// becomes 3 and "j" is greater than 25.
// Jose Vilaplana
using System;
public class GoTo2
{
public static void Main()
{
for (int i = 1; i <= 10; i++)
{
for (int j = 20; j <= 30; j +=2)
{
if ((i == 3) && (j > 25))
goto end;
Console.Write("{0} {1} ; ", i, j);
}
}
end:
Console.WriteLine();
}
}
|
JavaScript
|
UTF-8
| 453
| 2.875
| 3
|
[] |
no_license
|
// Takes in a token, if it's there, puts it in the headers, if not deletes from headers
// If we have a token, we'll send it with every request
import axios from "axios";
// Function that takes in token as a parameter, then checks for it
const setAuthToken = (token) => {
if (token) {
axios.defaults.headers.common["x-auth-token"] = token;
} else {
delete axios.defaults.headers.common["x-auth-token"];
}
};
export default setAuthToken;
|
JavaScript
|
UTF-8
| 2,805
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
var canvas = document.createElement('canvas');
$(document).ready(function () {
//test if URL contains passed ID - if so we want to use it
//var id = getURLParameters("ID");
var id = "1";
GetAllEventItems(id);
}); // End of Document Ready function
function GetAllEventItems(id) {
/*******************************************************************
* GetAllEventItem - Go get the event data for a particular item
*******************************************************************/
var uri = "api/frogforce/GetAllEventItems/";
$.getJSON(uri, function (data) {
var htext = "";
var parseDate = d3.timeParse("%Y-%m-%dT%H:%M:%S");
var formatDate = d3.timeFormat("%B %d, %Y");
var formatdd = d3.timeFormat("%d");
var formattt = d3.timeFormat("%H:%M %p");
var formatmm = d3.timeFormat("%B");
$.each(data, function (key, item) {
var sd = parseDate(item.Start_Date);
htext = htext + "<div style='height: 300px;' class='col-xs-6 col-sm-4'><div class='related_post_sec single_post'><span class='date-wrapper'>";
htext = htext + "<span class='date'><span>" + formatdd(sd) + "</span>" + formatmm(sd) + "</span></span>";
htext = htext + "<div class='rel_right'><h4><a href='page-single-event.html?ID=" + item.ID + "'>" + item.Title_text + "</a></h4>";
htext = htext + "<div class='meta'><span class='place'><i class='fa fa-map-marker'></i>" + item.Location_text + "</span>";
htext = htext + "<span class='event-time'><i class='fa fa-clock-o'></i>" + formattt(sd) + "</span></div>";
htext = htext + "<p>" + shrinktext(item.Body_text) + "</p>";
htext = htext + "<a href='page-single-event.html?ID=" + item.ID + "' class='btn btn-default commonBtn'>view Detals</a></div></div></div>";
}); // End each
$('#ffthumb').html(htext);
}) // End Json Call
.error(function (jqXHR, textStatus, errorThrown) {
ErrorMsgBox("Error GetAllEventItems()!", jqXHR.responseJSON, jqXHR.status);
});
} // End getEventItem
function shrinktext(intext) {
// function to reduce a line of text to a maximum of 150 characters
var st = "";
var sx = "";
var l = 0;
var n;
//if length of text is less than limit than return input string to caller
if (intext.length < 150) {
return intext;
}
//get the first 150 characters of string
sx = intext.substring(0, 150);
//find the last blank in the string
n = sx.lastIndexOf(" ");
//only move part of string from start to first blank less than 150
st = intext.substring(0, n);
st = st + "...";
return st;
}
|
Java
|
UTF-8
| 5,186
| 2.53125
| 3
|
[] |
no_license
|
package me.zhouxi.iot.client;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import me.zhouxi.iot.IoTApplication;
/**
* Created by zhouxi on 6/10/2017.
*/
public class APIList {
/**
* a remote server address
*/
public static String address = "192.168.1.52";// for test
/**
* a port connect to remote server
*/
public static int port = 20000;
/**
* udp port
*/
public static int udp_port = port + 1;
public static int udp_receive_port = udp_port + 1;
/**
* udp broad cast address
*/
public static String broadcast_address = "224.0.0.1";
/**
* time out
*/
public static int timeout = 3000;
/**
* receive data from server
*/
public interface APIListListener{
/**
* received data
* @param type
* @param data
*/
void apiListListenerOnDataReceived(APIs type ,String data);
/**
* handle error
* @param type
* @param e
*/
void apiListListenerOnError(APIs type ,Exception e);
}
/**
* use this variable to find request name
*/
private HashMap<String,String> apiDictionary;
// static single instance
private static APIList apiList;
/**
* get instance for this class
* @return
*/
public static APIList getInstance(){
if(apiList == null){
apiList = new APIList();
}
return apiList;
}
/**
* hidden constructor
*/
private APIList(){
super();
readJSON();
}
private void readJSON(){
if(apiDictionary == null)
apiDictionary = new HashMap<>();
apiDictionary.clear();
IoTApplication application = IoTApplication.getInstance();
try {
InputStream inputStream = application.getAssets().open("api.json");
StringBuilder stringBuilder = new StringBuilder();
byte[] buffer = new byte[2048];
int readBytes;
while((readBytes = inputStream.read(buffer)) > 0){
stringBuilder.append(new String(buffer, 0, readBytes));
}
JSONArray jsonArray = new JSONArray(stringBuilder.toString());
for(int i = 0 ; i < jsonArray.length() ; i ++ ){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String key = jsonObject.getString("key");
String value = jsonObject.getString("value");
apiDictionary.put(key,value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void commonShortRequest(APIListListener listener,APIs type,String param){
Set<String> keySet = apiDictionary.keySet();
Iterator<String> iterator = keySet.iterator();
String apiName = null;
while (iterator.hasNext()){
String key = iterator.next();
String value = apiDictionary.get(key);
if(value.equals(String.valueOf(type))){
apiName = key;
break;
}
}
if(apiName != null){
String requestString = generateARequestString(apiName,param);
SocketThread socketThread = new SocketThread(requestString,type,listener);
socketThread.startRequest();
}
}
private String generateARequestString(String api,String param){
if(param == null)
param = "";
return String.format("%s:%s\0",api,param);
}
/**
* get all devices
* @param listener
*/
public void getAllDevices(APIListListener listener){
commonShortRequest(listener,APIs.GetAllDevicesList,null);
}
/**
* check server is have password
* @param listListener
*/
public void IsServerHavePassword(APIListListener listListener){
commonShortRequest(listListener,APIs.IsServerHavePassword,null);
}
/**
* set pwd
* @param listListener
* @param params
*/
public void SetServersPassword(APIListListener listListener,String params){
commonShortRequest(listListener,APIs.SetServersPassword,params);
}
/**
* check pwd
* @param listListener
* @param params
*/
public void PasswordAuthentication(APIListListener listListener,String params){
commonShortRequest(listListener,APIs.PasswordAuthentication,params);
}
/**
* get a new nfc card
* @param listListener
* @param pwd
* @param time
*/
public void GetNFCCard(APIListListener listListener,String pwd ,long time){
String req = pwd + "," + String.valueOf(time / 1000);
commonShortRequest(listListener,APIs.GetNFCCard,req);
}
/**
* get all open door data
* @param listListener
*/
public void GetAllNFCAuthOKData(APIListListener listListener){
commonShortRequest(listListener,APIs.GetAllNFCAuthOKData,null);
}
}
|
Python
|
UTF-8
| 10,850
| 2.96875
| 3
|
[] |
no_license
|
import subprocess
import re
import os
def memedata_prep( filename_in, filename_out ):
"""
Notes:
Preparatory formatting of meme input data that was generated from the updownstream.py script:
- duplicate sample sequences must be dealt with to prevent MEME from biasing motifs from them
- these duplicates arise in two main ways:
1) Pulley samples: genes with exactly the same 5' start share the upstream promoter => delete one of the duplicates, the other gene gets nothing
2) Tug'o'war samples: a shared sample lies between opposite facing genes (+/-) => half goes to one gene, half goes to the other
Args:
"""
# Need to ensure data is ready for MEME
file_in = open(filename_in) # Read file in order to establish filters that will later format the data ready for MEME
file_out = open(filename_out,'w')
headers = {}
print '\tEstablishing filters...'
while True:
header = file_in.readline()
sequence= file_in.readline()
if header == '': # break when finished
break
# tabs of the fi
header_split = header.split('\t')
geneId = header_split[0].replace('>','')
utrCoord = header_split[1].replace('UtrCoord:','').split(':')
utrLength = header_split[2].replace('UtrLength:','')
utrType = header_split[3].replace('UtrType:','').rstrip()
chromosome = utrCoord[0]
# sub-properties of chromosome
startEnd = utrCoord[1].rpartition('-') # rpartition ensures: (-800-20) -> '-800','-','20'
start = startEnd[0]
end = startEnd[2]
strand = utrCoord[2]
# dictionary storeage of all headers
headers[geneId] = {'utrCoord':{'chromosome':chromosome,'start':start,'end':end,'strand':strand},'utrLength':utrLength,'utrType':utrType}
file_in.close()
# Pulley samples: shared samples with genes in the same direction
#
# ---S--- + ---G-------->
# ---S--- + ---G--->
# ---S--- + ---G------------> ...only one of these samples are kept, rest are thrown...
#
# dealt with by making a dictionary that ensures a 1 to 1 key-value relationshipof sample-to-geneId
#
# during the next .readline() loop utrcoord-to-geneid value will be checked against the current geneId in current iteration
#
geneIds = headers.keys()
one_coord_per_geneId = {}
for geneId in geneIds:
utrCoord = headers[geneId]['utrCoord']['chromosome']+':'+headers[geneId]['utrCoord']['start']+'-'+headers[geneId]['utrCoord']['end']+':'+headers[geneId]['utrCoord']['strand']
one_coord_per_geneId[utrCoord] = geneId # To ensure only one geneId = one utrCoord, I purposefully allow values to be overidden for a given key
# Tug'o'war samples: shared samples with genes in the opposite direction
#
# s1 <-------G--- + ---S---
# s2 ---S--- + ---S------->
#
# dealt with by making a set of unique utrcoords stripped of their strand property. Now upon encountering a match, forward samples and reverse samples take their half of the tug-o-war sequence
#
coords = [ ':'.join(i.split(':')[0:-1]) for i in one_coord_per_geneId.keys() ] # remove strand property
coords_shared = set([i for i in coords if coords.count(i)>1])
print '\tGenerating meme-ready data...'
file_in = open(filename_in) # Open file for formatted parsing
collection = []
coords_shared_geneIds = []
print ('\t\tFiltering shared samples...')
while True:
header = file_in.readline()
sequence= file_in.readline().rstrip()
if header == "": # break when finished
break
# MEME filter: => Is this sample seq too short for meme?
# YES:
if len(sequence)<10:
if sequence=='\n':
collection.append(header)
continue
# NO:
else:
geneId = header.split('\t')[0].replace('>','')
utrCoord= header.split('\t')[1].replace('UtrCoord:','').split(':')
# PULLEY filter: => Is this GeneId unique? or permitted as a winning pulley sample?
if one_coord_per_geneId[':'.join(utrCoord)] == geneId:
utrCoord_noStrand = ':'.join(utrCoord[0:1+1])
# TUG'O'WAR filter: => Is this sample in a tug'o'war?
if utrCoord_noStrand in coords_shared:
coords_shared_geneIds.append(header.split('\t')[0].replace('>',''))
sequence = sequence[(len(sequence)/2):] # this works, since the rightermost end of the seq = gene, so we must sample from the end inwards
# OKAY: => then upon passing the filters, we can write the sample :)
file_out.write(header+sequence+'\n')
file_in.close()
file_out.close()
def memedata_dust( filename_in, cutoff=2 ):
"""
Notes:
DUSTMASKER: low complexity region masker, commandline program installed on vb-dev
Args:
cutoff = 5 <= the -level argument proportional to how strict the masking is, 20 is default for the native program, lower => more masking
"""
file_dust_tmp_name = filename_in.split('.')[0]+'_dusted_tmp'+'.'+filename_in.split('.')[1]
file_dust_name = filename_in.split('.')[0]+'_dusted'+'.'+filename_in.split('.')[1]
print('\t\tMasking low complexity regions: DUST...')
file_dust_tmp = open(file_dust_tmp_name,'w')
subprocess.call([ 'dust', filename_in, str(cutoff)],stdout=file_dust_tmp) # TODO: what value do I use for 'cut-off', here given as 10
file_dust_tmp.close()
file_dust_tmp = open(file_dust_tmp_name)
file_dust = open(file_dust_name,'w') # Concatenating consective lines of sequence...
seq_united = 'start'
while True:
line = file_dust_tmp.readline()
if line == '':
file_dust.write(seq_united)
break
if '>' in line:
if seq_united == 'start':
file_dust.write(line)
seq_united = ''
else:
file_dust.write(seq_united+'\n'+line)
seq_united = ''
else:
seq_united += line.rstrip()
file_dust_tmp.close()
file_dust.close()
subprocess.call([ 'rm', file_dust_tmp_name]) # Deletes the temporary dust file
def memedata_simpleMask( filename_in ):
"""
Notes:
BOB's SIMPLE MASKER: low complexity region masker, masks di-nucleotide repeats if >=8bp or tri nucletides repeats if >=9bp long
Args:
"""
print('\t\tMasking low complexity regions: SIMPLE...')
file_in = open(filename_in)
file_out = open('..'+filename_in.split('..')[1].split('.')[0]+'_simpleMasked'+'.'+filename_in.split('..')[1].split('.')[1],'w')
def maskChars(matchobj):
return len(matchobj.group(0))*'N'
while True:
line = file_in.readline()
if line == "": # break when finished
break
di_nucleotides = re.compile(r'(..)\1{4,}') # Mask where DI NUCLEOTIDE repeats are 8bp long or more
mask = di_nucleotides.sub(maskChars,line)
tri_nucleotides = re.compile(r'(...)\1{3,}') # Mask where TRI NUCLEOTIDE repeats are 9bp long or more
mask = tri_nucleotides.sub(maskChars,mask)
file_out.write(mask)
file_in.close()
file_out.close()
def allSpecies( speciesFile='./species_list.txt', dataPath_in='../data/sample_seqs/fasta/', dataPath_out = '../data/meme_data/in/', LCR_masking='simple' ):
"""
Notes:
prepares the 2kb upstream data for MEME to start processing for every species
Args:
species_list = ['Anopheles gambiae', 'Aedes aegypti'] #list: species names to sample from
"""
import speciesManage # species.generate_list() method creates a python list with names of species corresponding to MySQL EnsEMBL databases
species_list = speciesManage.generate_list(speciesFile) # generates a list of species names corresponding to EnsEMBl MySQL db names
for species in species_list:
print(species)
print(dataPath_in)
filename_in = dataPath_in + species + '_upstream.fasta'
filename_out= dataPath_out+ species + '_upstream_memeready_all.fasta'
memedata_prep(filename_in,filename_out)
if LCR_masking=='dust':
memedata_dust(filename_out)
elif LCR_masking=='simple':
memedata_simpleMask(filename_out)
#-------------------------------------------------------------------------------------------------------------------------------------
# RUN
#-------------------------------------------------------------------------------------------------------------------------------------
""" NOTICE
- dataPath_in = .../masking/test/...
- dataPath_out = .../meme_data/in/test...
"""
if __name__ == "__main__":
import sys
# Deal with MISSING ARGS:
try:
speciesFile = sys.argv[1]
except IndexError:
speciesFile = './species_list.txt', # to alter the list of species to iterate through look in: scripts/species_list.txt
try:
dataPath_in = sys.argv[2]
except IndexError:
dataPath_in = '../data/sample_seqs/fasta/masking/',
try:
dataPath_out = sys.argv[3]
except IndexError:
dataPath_out = '../data/meme_data/in/'
try:
LCR_masking = sys.argv[4]
except IndexError:
LCR_masking = 'simple' # other options: 'dust', 'none'
# RUN MAIN:
allSpecies( speciesFile, dataPath_in, dataPath_out, LCR_masking )
print('COMPLETE!')
# # PRODUCTION:
# allSpecies( speciesFile = './species_list.txt', # to alter the list of species to iterate through look in: scripts/species_list.txt
# dataPath_in = 'home/ab108/0VB/2kb/data/sample_seqs/fasta/masking/',
# dataPath_out = 'home/ab108/0VB/2kb/data/meme_data/in/'
# )
# TG repeat story:
# allSpecies( speciesFile = './species_list.txt', # to alter the list of species to iterate through look in: scripts/species_list.txt
# dataPath_in = 'home/ab108/0VB/2kb/data/sample_seqs/fasta/bob/',
# dataPath_out = 'home/ab108/0VB/2kb/data/meme_data/in/',
# dust=False
# )
# # DEBUGGING:
# allSpecies( species_list,
# dataPath_in = 'home/ab108/0VB/2kb/data/sample_seqs/fasta/masking/test/',
# dataPath_out = 'home/ab108/0VB/2kb/data/meme_data/test/'
# )
|
Python
|
UTF-8
| 478
| 2.8125
| 3
|
[] |
no_license
|
# This file implements the IPA class, which is the entry point of the application
# author: Timothy Mason
import os
import IPAController
import IPAModel
class IPA:
"""
This is the main program class of IPA: Image Processing Application.
"""
def __init__(self):
self.model = IPAModel.IPAModel()
self.controller = IPAController.IPAController(self.model)
self.controller.start()
if __name__ == '__main__':
IPA() # This call doesn't return until the application terminates
|
JavaScript
|
UTF-8
| 1,720
| 3.390625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
var cart = [];
function getCart() {
return cart;
}
function setCart(c) {
cart = c;
return cart;
}
function addToCart(item) {
var keyvalue = {itemName : item, itemPrice : Math.floor(Math.random() * 100)};
cart.push(keyvalue)
return `${item} has been added to your cart.`;
}
function viewCart() {
// write your code here
if (cart.length === 0) {
returnString = "Your shopping cart is empty.";
} else {
var returnString = "In your cart, you have ";
for (var i = 0; i < cart.length; i++){
if (i === cart.length - 1 && cart.length !== 1){
returnString = returnString + `and ${cart[i].itemName} at $${cart[i].itemPrice}, `;
} else {
returnString = returnString + `${cart[i].itemName} at $${cart[i].itemPrice}, `;
}
}
returnString = returnString.substr(0, returnString.length -2) + ".";
}
return returnString;
}
function total() {
var cartTotal = 0;
for (var i = 0; i < cart.length; i++){
cartTotal += cart[i].itemPrice
}
return cartTotal;
}
function removeFromCart(item) {
var found = false;
for (var i = 0; i < cart.length; i++){
if (item == cart[i].itemName){
console.log(i)
cart.splice(i,1)
found = true;
}
}
if (found === false) {
return "That item is not in your cart."
} else {
return cart;
}
}
function placeOrder(cardNumber) {
if (cardNumber === null || cardNumber === undefined) {
return "Sorry, we don't have a credit card on file for you."
} else {
var cartTotal = total();
cart = [];
return `Your total cost is $${cartTotal}, which will be charged to the card ${cardNumber}.`
}
}
|
Markdown
|
UTF-8
| 367
| 2.578125
| 3
|
[] |
no_license
|
#学习Markdown语法练习
##二级标题
###三级标题
####四级标题
#####五级标题
######六级标题
**粗体测试**
*斜体测试*
***
* 标号一
+ 标号二
- 标号三
1、 序号1
2、 序号2
3、 序号3
* * *
>区块引用测试
>23
>232
3432
>3432
>34355
>fedadfd
---
```java
public static void main(String[] args){
println("hello world");
}
|
Markdown
|
UTF-8
| 1,736
| 2.96875
| 3
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
s2gen: Static Site Generator
-----------------------------------
This static site generator is tailored for my use case and I'm not sure how
useful it will be for others. It is essentially a python script that you copy
into the directory you want to generate your static site from. It automatically
creates an Atom feed for the site as well.
## Prequisites and Assumptions
You must have npm installed in order for s2gen to function. You also need to
install the libraries s2gen uses internally. I recommend doing this with pip in
a virtual environment as follows:
python3 -m venv venv
source venv/bin/activate
pip install wheel
pip install -r requirements.txt
s2gen assumes you are using tailwindcss, since this is the css framework I use.
When generating the release version it automatically minimizes the css
(including removing unnused css rules).
## Commands
- `s2gen.py help` show help message listing available commands
- `s2gen.py init` initialize site directory (does nothing if already initialized)
- `s2gen.py release` generate release version of site
- `s2gen.py generate` generate site
- `s2gen.py serve` serve site files locally to preview site
## Complementary Libaries
- [Footnotes.js](https://github.com/jeffreyrogers/Footnotes.js). This is a simple library
I wrote to make footnotes and sidenotes easy to add to static sites.
## Contributing
I do not have the time to work on open source projects at this point in my life,
so I will not be accepting any PRs (except bug fixes) or implementing any
requested features. However, s2gen is in the public domain, so feel free to
modify, fork, or otherwise do whatever you want with this code.
|
Python
|
UTF-8
| 4,919
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
import json
import sys
import testdata
import unittest
SUFFIX = False
class Flattener:
# obj : json object to be flattened
# indices : combination of indices used to identify current subobject
# depth : tuple of names traversed in original object to reach subobject
def _flatten_list(self, obj, indices, depth):
cur_string = '_'.join(depth)
if not self._data.get(cur_string):
self._data[cur_string] = []
current_obj = []
# Return list as is, if it entirely consists of non-dict/non-list contents
if not any(isinstance(i, (list, dict)) for i in obj):
return obj
for index, subobj in enumerate(obj):
tmp = None
# Accomodate mixed arrays and indexing
try:
id = subobj.get(self._index)
if id:
tmp = self._flatten(subobj, indices + [(self._index, str(id))], depth)
else:
tmp = self._flatten(subobj, indices + [(self._default_index, str(index))], depth)
# AttributeError implies the list contains non-dict contents
# They are not ignored here, to allow reconstruction of original from subfiles.
except AttributeError:
tmp = self._flatten(subobj, indices, depth)
if tmp:
current_obj.append(tmp)
self._data[cur_string] += current_obj
def _flatten_dict(self, obj, indices, depth):
cur_string = '_'.join(depth)
current_obj = {}
# Handle nested "id"/"__index" fields
for name, id in indices:
if not current_obj.get(name):
current_obj[name] = id
else:
if not isinstance(current_obj[name], list):
current_obj[name] = [current_obj[name]]
current_obj[name].append(id)
if not self._data.get(cur_string):
self._data[cur_string] = []
for field, subobj in obj.items():
if field in [self._index, self._default_index]:
continue
temp_field = field
# truncate trailing character if current subobject is a list
# stopgap measure:
# Use "__l" suffix for lesser chance of overlapping field names.
if isinstance(subobj, list) and len(field) > 1 and field[-1] == 's':
if not SUFFIX:
temp_field = field[:-1]
else:
temp_field += '__l'
# Flatten all child content
tmp = self._flatten(subobj, indices, depth + (temp_field,))
# Ignore non-trivial children
if tmp:
current_obj[temp_field] = tmp
self._data[cur_string].append(current_obj)
# Recursive function to flatten object
def _flatten(self, obj, indices = [], depth = ()):
if not isinstance(obj, (list, dict)):
return obj
if isinstance(obj, list):
return self._flatten_list(obj, indices, depth)
if isinstance(obj, dict):
return self._flatten_dict(obj, indices, depth)
def get_flattened(self, json_obj):
self._data = {'':None}
self._flatten(json_obj)
self._data.pop('')
return self._data
# allows specifying name used for index fields
def __init__(self, primary_index = 'id', unnamed_index = 'index'):
self._index = primary_index
self._default_index = '__{}'.format(unnamed_index)
def split_to_file(sol):
for field, subobj in sol.items():
cur_file = "{}.json".format(field)
try:
outfile = open(cur_file,'x')
json.dump(subobj, outfile)
print("Generated {}".format(cur_file))
except Exception as e:
print(e)
def flatten_json(filename):
obj = None
try:
with open(filename) as jsonfile:
obj = json.loads(jsonfile.read())
except Exception as e:
print(e)
f = Flattener()
sol = f.get_flattened(obj)
split_to_file(sol)
class TestUM(unittest.TestCase):
def setUp(self):
self.maxDiff = None
def test_1(self):
f = Flattener()
self.assertEqual( f.get_flattened(testdata.test1), testdata.sol1)
def test_2(self):
f = Flattener()
self.assertEqual( f.get_flattened(testdata.test2), testdata.sol2)
def test_3(self):
f = Flattener()
self.assertEqual( f.get_flattened(testdata.test3), testdata.sol3)
if __name__ == '__main__':
# argparse is overkill for 2 arguments
if len(sys.argv) > 1:
try:
if sys.argv[2] == '-suffix':
SUFFIX = True
except:
pass
try:
flatten_json(sys.argv[1])
except Exception as e:
print(e)
else:
if not SUFFIX:
unittest.main()
|
Java
|
UTF-8
| 410
| 2.0625
| 2
|
[] |
no_license
|
package com.hwt.service.impl;
import com.hwt.entity.User;
import com.hwt.service.UserService;
import org.springframework.stereotype.Service;
/**
* @author 黄雯婷
* @version 1.0
* @description: TODO
* @date 2020-08-24 14:21:40
**/
@Service
public class UserServiceImpl implements UserService {
@Override
public void addUser(User user) {
System.out.println("==========="+user);
}
}
|
Markdown
|
UTF-8
| 1,372
| 3.046875
| 3
|
[] |
no_license
|
## What is accessibility?
> Accessibility is the practice of making your websites
> usable by as many people as possible. We traditionally
> think of this as being about people with disabilities,
> but the practice of making sites accessible also
> benefits other groups such as those using mobile
> devices, or those with slow network connections.
Quote from MDN's page ["What is
accessibility?"](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility)
When making technology design decisions, we should
consider how our products can be interacted with by:
- blind people, colour blind people
- D/deaf people, people that are hard of hearing
- people with motor disabilities
- people with various cognitive disabilities
- According to WebAIM, about 20% of people are disabled
- It's common to think of disability as a medical
condition, but disability is often limiting only when
diverse bodies and minds interact with inacessible
technology design
- Designing web experiences that are as accessible as
possible for disabled people also benefit everyone else
- For example, designing technology that can be used with
only one arm/hand benefits:
- amputees
- people with broken fingers, wrists, arms, etc.
- someone holding a phone in one hand and a dog leash
in the other
|
Java
|
UTF-8
| 1,280
| 3.203125
| 3
|
[] |
no_license
|
package com.dnd;
import com.dnd.dto.Actor;
import com.dnd.dto.playerCharacter.PlayerCharacter;
import com.dnd.dto.monster.Goblin;
import com.dnd.dto.monster.Monster;
import com.dnd.util.SetupCharacter;
import java.util.ArrayList;
public class DndApplication
{
private static PlayerCharacter getStartingCharacter()
{
PlayerCharacter playerCharacter;
while(true)
{
System.out.println(
"Greetings Adventurer! What Character would you like to be?\n\n" +
"Your choices are:\n" +
"\tfighter\n\n" +
"Type in one of the above choices and press enter."
);
playerCharacter = SetupCharacter.setupCharacterByClass("fighter");//Input.readInput());
if (playerCharacter == null)
System.out.println("Option unavailable... Please try again.");
else
return playerCharacter;
}
}
public static void main(String[] args)
{
System.out.println("hello world!");
ArrayList<Actor> playerCharacters = new ArrayList<>();
playerCharacters.add(getStartingCharacter());
ArrayList<Actor> monsters = new ArrayList<>();
monsters.add(new Goblin("goblin1"));
monsters.add(new Goblin("goblin2"));
Game game = new Game(playerCharacters, monsters);
//combat
game.marchingOrder();
game.rollForInitiative();
game.combat();
}
}
|
Java
|
UTF-8
| 290
| 1.890625
| 2
|
[] |
no_license
|
package com.egg.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.egg.model.Buyer;
@Repository
public interface BuyerRepository extends JpaRepository<Buyer, Long> {
Buyer findByUsername(String username);
}
|
Python
|
UTF-8
| 163
| 2.875
| 3
|
[] |
no_license
|
from json import load
file = open("characters.json")
content = load(file)
characters = content["characters"]
for c in characters:
print(c["characterName"])
|
Markdown
|
UTF-8
| 1,382
| 3.15625
| 3
|
[] |
no_license
|
Suppose the number of ways to climb a section of <img src="http://latex.codecogs.com/gif.latex?n"/> stairs is <img src="http://latex.codecogs.com/gif.latex?s_n"/>. We have <img src="http://latex.codecogs.com/gif.latex?s_0=1,s_1=1,s_2=2"/> and <img src="http://latex.codecogs.com/gif.latex?s_n=s_{n-1}+s_{n-2}+s_{n-3}"/>. The official solution uses dynamic programming to calculate them one by one, which has a complexity of <img src="http://latex.codecogs.com/gif.latex?O(n)"/>. My algorithm has time complexity of <img src="http://latex.codecogs.com/gif.latex?O(\log{n})"/> but requires a memory 9 times as large as that solution.
We can write the recursive relation as
<img src="http://latex.codecogs.com/gif.latex?s_n=s_n"/>
<img src="http://latex.codecogs.com/gif.latex?s_{n+1}=s_{n+1}"/>
<img src="http://latex.codecogs.com/gif.latex?s_{n+2}=s_{n+1}+s_n+s_{n-1}"/>
which is equivalent to the matrix relation <img src="http://latex.codecogs.com/gif.latex?S_{n}=A{\cdot}S_{n-1}"/> where
<img src="http://latex.codecogs.com/gif.latex?S_{n}=\left(\begin{array}{c}a_{n}\\a_{n+1}\\a_{n+2}\end{array}\right),A=\left(\begin{array}{ccc}0&1&0\\0&0&1\\1&1&1\end{array}\right)"/>
By induction, <img src="http://latex.codecogs.com/gif.latex?S_{n}=A^n{\cdot}S_0"/>, where can be calculated using [Exponentiation by squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring).
|
Java
|
UTF-8
| 978
| 2.203125
| 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 com.unw.crypto.loader;
import com.unw.crypto.Config;
import com.unw.crypto.loader.CSVAdapter;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import org.springframework.stereotype.Component;
import org.ta4j.core.TimeSeries;
/**
*
* @author UNGERW
*/
@Component
public class DataLoader {
public TimeSeries loadData() {
LocalDate df = LocalDate.parse(Config.fromDate);
LocalDate du = LocalDate.parse(Config.untilDate);
Instant instantFrom = df.atStartOfDay(ZoneId.of("Europe/Berlin")).toInstant();
Instant instantUntil = du.atStartOfDay(ZoneId.of("Europe/Berlin")).toInstant();
TimeSeries series = CSVAdapter.loadBitstampSeries(Config.csv_file,instantFrom, instantUntil);
return series;
}
}
|
Java
|
UTF-8
| 5,077
| 2.53125
| 3
|
[] |
no_license
|
package com.seekting.killer.model;
import android.content.Context;
import android.util.Log;
import com.seekting.killer.App;
import com.seekting.utils.IOUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;
import java.util.concurrent.CountDownLatch;
public class ScoreItemManager {
private CountDownLatch mCountDownLatch = new CountDownLatch(1);
private ScoreItem mScoreItem;
private static class Holder {
private static final ScoreItemManager instance = new ScoreItemManager();
}
public static ScoreItemManager getInstance() {
return Holder.instance;
}
private ScoreItemManager() {
}
public void init(Context context) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Stack<ScoreItem> scoreItems = new Stack<>();
// String[] array = new String[]{"", "\\t", "\\t\\t", "\\t\\t\\t"};
String[] array = new String[]{"", " ", " ", " "};
InputStream inputStream = context.getAssets().open("score.txt");
IOUtil.eachLine(inputStream, new IOUtil.Callback() {
@Override
public boolean onRead(String line) {
if (line.startsWith("all")) {
scoreItems.push(new ScoreItem("0", "all", 0));
} else {
out:
for (int i = 3; i > 0; i--) {
if (line.startsWith(array[i])) {
int index = 0;
while (!scoreItems.isEmpty()) {
ScoreItem scoreItem = scoreItems.pop();
index++;
if (scoreItem.level == i - 1) {//它的上一级
scoreItems.push(scoreItem);
ScoreItem child = new ScoreItem("", line.trim(), i);
scoreItems.push(child);
scoreItem.mItems.add(child);
child.parent = scoreItem;
setItemId(scoreItem, child);
break out;
}
}
}
}
}
return true;
}
});
mScoreItem = scoreItems.firstElement();
// print(mScoreItem);
// Log.d("seekting", "ScoreItemManager.run()" + mScoreItem);
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}).start();
}
private void setItemId(ScoreItem parent, ScoreItem child) {
StringBuilder stringBuilder = new StringBuilder();
String mId = String.valueOf(parent.mItems.size());
if (parent.parent != null) {
stringBuilder.insert(0, parent.id + "-");
}
stringBuilder.append(mId);
child.id = stringBuilder.toString();
}
public ScoreItem getScoreItem() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mScoreItem;
}
private static void print(ScoreItem scoreItem) {
Stack<ScoreItem> scoreItems = new Stack<>();
scoreItems.add(scoreItem);
StringBuilder sb = new StringBuilder();
StringBuilder stringBuilder = new StringBuilder();
while (!scoreItems.isEmpty()) {
ScoreItem scoreItem1 = scoreItems.pop();
stringBuilder.setLength(0);
for (int i = 0; i < scoreItem1.level; i++) {
stringBuilder.append(" ");
}
stringBuilder.append(scoreItem1.name);
stringBuilder.append("\n");
sb.append(stringBuilder.toString());
if (!scoreItem1.mItems.isEmpty()) {
for (int i = scoreItem1.mItems.size() - 1; i >= 0; i--) {
scoreItems.push(scoreItem1.mItems.get(i));
}
}
}
Log.d("seekting", "ScoreItemManager.print()\n" + sb.toString());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
File file = new File(App.context.getDataDir(), "test_score.txt");
IOUtil.write(file, sb.toString());
Log.d("seekting", "ScoreItemManager.print()" + file.getAbsolutePath());
}
}
}
|
Java
|
UTF-8
| 1,515
| 2.078125
| 2
|
[] |
no_license
|
package com.angryBeaver.jackson.configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
@Component
public class Jdk8ObjectMapperInjectionConfig {
@Resource(name = "jdk8ObjectMapper")
private ObjectMapper jdk8ObjectMapper;
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
@Resource
public void setRequestMappingHandlerAdapter(
RequestMappingHandlerAdapter requestMappingHandlerAdapter
) {
this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
}
@PostConstruct
public void injectJdk8ObjectMapperIntoDefaultMappingJacksonHttpMessageConverter() {
List<HttpMessageConverter<?>> converters =
this.requestMappingHandlerAdapter.getMessageConverters();
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter m =
(MappingJackson2HttpMessageConverter) converter;
m.setObjectMapper(this.jdk8ObjectMapper);
}
}
}
}
|
Python
|
UTF-8
| 2,791
| 2.71875
| 3
|
[] |
no_license
|
import dumper
def qdump__NumericalValue(d, value):
iss = value['is'].integer()
val = value['storage']
if iss == 0:
img = val.extractInteger(8, True)
elif iss == 1:
img = val.extractInteger(32, False)
elif iss == 2:
img = val.extractInteger(32, True)
else:
img = val.extractSomething('d', 64)
d.putValue('%s %s' % (["Truthy", "Whole", "Counting", "Floating"][iss], img))
def qdump__Cstr(d, value):
d.putItem(value['ptr'])
d.putBetterType("char *")
def qdump__Text(d, value):
d.putItem(value['ptr'])
d.putBetterType("char *")
def qdump__Index(d, value):
raw = value['raw']
if raw.integer() == 4294967295:
d.putValue("BadIndex")
else:
d.putItem(raw)
d.putBetterType("unsigned")
def qdump__Ordinal(d, value):
d.putValue('%u/%u' % (value['pointer'], value['length']))
def StorableTypeEnum(code):
return ["NotDefined", "Uncertain", "Textual", "Numerical", "Wad"][code]
def StorableQualityEnum(code):
return ["Empty", "Defaulted", "Parsed", "Edited"][code]
def qdump__Storable(d, value):
iss = value['type'].integer()
if iss == 4:
safely__StorableWad(d,value)
return
elif iss == 3:
onion = value['number']
else: #others are all varying degrees of confidence that the image is actually text.
onion = value['text']
d.putItem(onion)
d.putBetterType(onion.type)
def safely__StorableWad(d,storable):
innerType = 'Storable *' #our wad is always mroe of us
value = storable['wad']['v'] #named for what I copied out of stdtypes.py
# the next chunk is pulled from std__vector
(start, finish, alloc) = value.split("ppp")
size = int((finish - start) / innerType.size())
d.check(finish <= alloc)
if size > 0:
d.checkPointer(start)
d.checkPointer(finish)
d.checkPointer(alloc)
d.check(0 <= size and size <= 1000 * 1000 * 1000)
d.putItemCount(size)
#back to piece taken from std_map
if d.isExpanded():
keyType = 'Text' #our text class is used for name members
valueType = 'Storable *' #and this is what the vector is filled with, value.type[0] might be the same thing.
with Children(d, size, maxNumChild=1000):
# node = value["_M_t"]["_M_impl"]["_M_header"]["_M_left"]
# nodeSize = node.dereference().type.size()
# typeCode = "@{%s}@{%s}" % (keyType.name, valueType.name)
for i in d.childRange():
q = start + i * 4 #! sizeof pointer
with SubItem(d, i):
kidstar = d.extractPointer(q)
kid=d.dereference(kidstar)
key=kid['name']
d.putPairItem(i, (key, kid))
|
C#
|
UTF-8
| 4,011
| 2.546875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using APICon.Container;
namespace APICon.Util
{
public class ZipHelper
{
public static byte[] createZipBody(string name, string body, string sign)
{
/**/
string docEntryName = Path.GetFileName(name);
byte[] docBody = Encoding.GetEncoding("windows-1251").GetBytes(Utils.Base64Decode(body, "windows-1251"));
string signEntryName = "6_" + Path.GetFileName(name).Replace(".xml", ".bin");
byte[] signBody = Encoding.UTF8.GetBytes(sign);
/**/
byte[] zipByteArray = null;
MemoryStream outputMemoryStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemoryStream);
zipStream = addZipEntry(zipStream, docEntryName, docBody);
zipStream = addZipEntry(zipStream, signEntryName, signBody);
zipStream.IsStreamOwner = false;
zipStream.Close();
outputMemoryStream.Position = 0;
zipByteArray = outputMemoryStream.ToArray();
return zipByteArray;
}
public static byte[] createCondraZip(string xmlBody, string bodyName, string body, string signName, string sign)
{
byte[] zipByteArray = null;
MemoryStream outputMemoryStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemoryStream);
zipStream = addZipEntry(zipStream, "condra.xml", Encoding.UTF8.GetBytes(Utils.Base64Decode(xmlBody, "UTF-8")));
zipStream = addZipEntry(zipStream, bodyName, Encoding.UTF8.GetBytes(Utils.Base64Decode(body, "UTF-8")));
zipStream = addZipEntry(zipStream, signName, Encoding.UTF8.GetBytes(sign));
zipStream.IsStreamOwner = false;
zipStream.Close();
outputMemoryStream.Position = 0;
zipByteArray = outputMemoryStream.ToArray();
return zipByteArray;
}
public static byte[] zipChainContainer(ChainContainer container)
{
byte[] zipByteArray = null;
MemoryStream outputMemoryStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemoryStream);
foreach (string key in container.containedEntries.Keys)
{
zipStream = addZipEntry(zipStream, key, container.containedEntries[key]);
}
zipStream.IsStreamOwner = false;
zipStream.Close();
outputMemoryStream.Position = 0;
zipByteArray = outputMemoryStream.ToArray();
return zipByteArray;
}
public static Dictionary<string, byte[]> unzip(byte[] zip)
{
Dictionary<string, byte[]> map = new Dictionary<string, byte[]>();
ZipInputStream zis = new ZipInputStream(new MemoryStream(zip));
ZipEntry ze = zis.GetNextEntry();
while (ze != null)
{
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[4096];
StreamUtils.Copy(zis, ms, buffer);
map.Add(ze.Name, ms.ToArray());
ze = zis.GetNextEntry();
}
}
zis.Close();
return map;
}
private static ZipOutputStream addZipEntry(ZipOutputStream zipStream, string name, byte[] body)
{
MemoryStream inputMemoryStream = new MemoryStream(body);
ZipEntry newZipEntry = new ZipEntry(Path.GetFileName(name));
newZipEntry.Size = body.Length;
zipStream.PutNextEntry(newZipEntry);
StreamUtils.Copy(inputMemoryStream, zipStream, new byte[1024]);
return zipStream;
}
}
}
|
Markdown
|
UTF-8
| 23,707
| 3.234375
| 3
|
[] |
no_license
|
---
title: "Nepal - Mardi Himal Trek"
categories: Travel
tags: nepal travel trek trekking hiking walking mardi himal
---
I took a 'career break' from April 2017 to April 2018, to travel, learn new skills, spend more time in bed and do stuff that I used to do before getting a desk job.
This career break started with just under a month in Nepal. This is my account of one of the treks we did called Mardi Himal
# Map for reference

# Mardi Himal Trek
<table>
<tr><td>Planned duration: </td><td> 6 days (16 - 21 April)</td></tr>
<tr><td>Actual duration: </td><td> 4 days (16 - 19 April)</td></tr>
</table>
### Plan Vs Reality
<table>
<tr><td colspan="2">Plan</td></tr>
<tr><td>Day 1</td><td>Taxi from Pokhara to Kande (2 hours). Walk from Kande (1700 m) to Pitam-Deurali (2100 m) (2.5 hours)</td></tr>
<tr><td>Day 2</td><td>Walk Pitam-Deurali (2100 m) to Forest Camp (2550 m) (4 - 5 hours)</td></tr>
<tr><td>Day 3</td><td>Walk Forest Camp (2550 m) to Low Camp (2990 m) (3 hours), then Low Camp to High Camp (3580 m) (3 hours)</td></tr>
<tr><td>Day 4</td><td>Walk High Camp (3580 m) to Mardi Himal base camp (4500m) and return to High Camp (6 - 7 hours)</td></tr>
<tr><td>Day 5</td><td>Walk High Camp (3580 m) to Sidhing (1850 m) (6 hours)</td></tr>
<tr><td>Day 6</td><td>Walk Sidhing (1850m) to Lumre (3 hours). Taxi/Jeep from Lumre to Pokhara (3 hours)</td></tr>
</table>
<table>
<tr><td colspan="4">Reality </td></tr>
<tr><td>Day</td> <td>Elevation change</td> <td>Total times</td> <td>Details</td></tr>
<tr><td>Day 1</td> <td>+750m</td> <td>6:20 walking. 1:15 driving.</td> <td>
<ul>
<li>Taxi from Pokhara (820m) to Kande (1770m). +950m. 1:15 actual.</li>
<li>Walk from Kande (1770m) to Pothana (1840m). +120m. 1:40 actual.</li>
<li>Walk from Pothana (1840m) to Pitam Deurali (2100m). +210m. 0:40 actual. 0:45 suggested.</li>
<li>Walk from Pitam Deurali (2100m) to Forest Camp (2520m). +420m. 4:00 actual. 4:30 suggested.</li>
</ul>
</td></tr>
<tr><td>Day 2</td> <td>+1180m</td> <td>5:25 walking.</td> <td>
<ul>
<li>Walk from Forest Camp (2520m) to Low Camp (2970m). +450m. 2:00 actual. 2:00 suggested.</li>
<li>Walk from Low Camp (2970m) to High Camp (3700m). +730m. 3:25 actual. 3:00 suggested.</li>
</ul>
</td></tr>
<tr><td>Day 3</td> <td>+800m. -1530m</td> <td>5:50 walking.</td> <td>
<ul>
<li>Walk from High Camp (3700m) to View Point (4300m). +600m. 1:10 actual. 2:45 suggested.</li>
<li>Walk from View Point (4300m) to Mardi Himal Base Camp (4500m). +200m. 1:15 actual. 3:00 suggested.</li>
<li>Walk from Mardi Himal Base Camp (4500m) to View Point (4300m). -200m. 0:45 actual. 2:00 suggested.</li>
<li>Walk from View Point (4300m) to High Camp (3700m). -600m. 1:20 actual. 1:45 suggested.</li>
<li>Walk from High Camp (3700m) to Low Camp (2970m). -730m. 1:20 actual. 2:00 suggested.</li>
</ul>
</td></tr>
<tr><td>Day 4</td> <td>-1270m</td> <td>2:10 walking. 2-3 hours driving.</td> <td>
<ul>
<li>Walk from Low Camp (2970m) to Sidhing (1700m). -1270m. 2:10 actual. 3:30 suggested.</li>
<li>Jeep from Sidhing (1700m) to Pokhara (820m). 2-3 hours approx.</li>
</ul>
</td></tr>
</table>
### Detailed Reality
#### Day 1: 16 April
08:00 - 09:15 (1 hr 15 min) - Taxi from Pokhara to Kande (2500rs Tourist 6 seater mini van). Organised from our hotel the night before - Hotel Mountain View.
09:15 - 09:30 (15 min) - Ate bananas in Kande. Warded off Tibetan lucky charm sellers. Looked at our map, and realised some of the place names were different, and some didnt exist. 'Camps' also weren't shown on the map. Gave up with map and asked for directions.
09:30 - 10:30 (1 hr) - After being pointed in the right direction down a small stair case, around a building to the left and onto a well trodden path, we set off on our way to Australian Camp. Supposedly an hour and a half away, we took an hour. Lots of stone steps.

*One of the first sign posts we saw on the trek. Sign post quality deteriorated very quickly after this one*
10.30 - 11.10 (40 mins) - After a short water and photography break, walked from Australian Camp to Pothana (1890m), the next village along.
11.10 - 11.30 (20 mins) - Got our Annapurna Conservation Area permits (ACAP) checked at the tourist checkpoint in Pothana. Took photos of the useful sign boards and information they had in the building. One of our group had yet to buy a TIMS card as the tourist office TIMS desk was shut when we went to get it. Luckily he managed to get the ACAP and was told at the tourist office he could get a TIMS card on route. At the checkpoint the man behind the counter only checked out ACAP and didn't want to see TIMS. When we asked about getting a TIMS card he said they couldnt do it there, and he didn't think you needed a TIMS for Mardi Himal anyway. So we continued, slightly annoyed that we forked out $20 each for a TIMS we apparently didn't need. (TIMS cards were never checked throughout the whole trek)

*A useful board showing the expected trek times*
11:30 - 12:10 (40 mins) - After buying some snacks and water, we set off to Pitam Deurali which was supposed to be our first sleep stop. However since it was only just past mid-day we decided to get some food and carry onwards. We had our first mountain meal, fried rice, chow mein and dal bhat which would soon become our staple foods.
13:30 - 17:30 (4 hours) - Walked from Pitam Deurali (2100m) to Forest Camp (2520m). Elevation gain of 420m overall. Following our new best friend: the blue and white flag, painted on rocks and trees to mark the way, and the odd sign post giving us confidence we were going in the right direction. This was a beautiful walk through the forest along a very long ridge. Passing a temple along the way offering stunning views.

*This type of sign was relatively common along the way, however the blue and white flag was painted on rocks, trees and the ground even more frequently*

*The entrance to forest camp, we were glad to see this, it had been a long day*
We arrived at Forest Camp relatively late, being slightly worried that there would be no beds. The woman who served us food at Pitam Deurali recommended the place we stayed at Forest Camp, saying the food is good and room is free if we had dinner and breakfast. She muttered the last part under her breath as if it were top secret. I had heard the same from other travellers we chatted to in Pokhara and Kathmandu, so we assumed this was true and stayed there. Unfortunately the name of the place we stayed escapes me and I didn't record it, but it was the second place you get to as you enter the forest camp area (it has a fenced perimeter that is closed after dark). As we got there late, all that was left was a single triple room, and there were five of us in the group. We didn't mind initially as this was our first mountain sleep and we were optimistic and full of energy and excitement. However cramming 5 average to tall guys on 3 small single beds pushed together, ended up with none of us getting much decent sleep. Blankets were supplied but it was warm so I didn't use one. I used my sleeping bag liner and during the night I pulled my Ethihad airplane blanket onto myself as it was a bit chilly. The others used the blankets and were fine, however only 3 were supplied so 2 of the group had to share.

*This was our bed for the night. Not quite enough space for the 5 of us.*
The food was good, although we didn't have much choice. There seems to be a standard set menu by the Nepalese government that sets the prices of meals based on the distance from civilisation. Basically this means everything gets more expensive as you go up the mountain, and you're also not supposed to barter. Also prices are set by the government and changing printed prices by hand is a punishable offence, but we saw this frequently at lots of the tea houses we stayed at. Anyway, this set menu was available and we all decided what we wanted, but the old lady who ran the tea house had other ideas. In broken English and with a huge grin on her face she pointed to each one of us and said 'Dal Bhat'. So we all looked at each other and came to the conclusion we would be having Dal Bhat that evening. After some time food arrived and it was good. A large plate of plain white rice served with a small dish of Dal. I just poured the Dal onto the rice and wolfed it down. Dal Bhat is commonly unlimited, and once your plate is nearly empty, the host will offer you more Dal and more rice if you so wish to take it. I often had two to three helpings, it's amazing how hungry hiking makes you. Other meals such as fried rice, chow mein and momos don't offer this.
It was a good thing Dal Bhat was unlimited, as Dan tried to lightly salt his meal, and in doing so managed to tip the entire contents of the salt shaker onto his plate when the lid came off. After the laughter died down, and the majority of the salt had been scraped off the surface, the meal was still too salty to handle. Dan decided to 'dilute' the salty mess on his plate with a second helping of dal and rice. This worked to a certain extent, but he still ate that meal with a grimace on his face.
We awoke the next morning just before 6, as we had ordered our breakfast the previous night for that time. 3 Tibetan bread, one Chapatti and one bowl of museli. The bread stuff was a help yourself to honey, and jam type affair. The museli came with warm fresh milk from what we assume was either a cow, buffalo or yak. I was a little concerned about drinking milk as it's straight from the animal with no pasteurising but I think heating it goes some way to kill nasties? Need to check up on this. Nothing bad happened to my stomach anyway, and it was a good breakfast. The others Tibetan bread looked good but not as substantial as my museli. I think I made the right choice.

*The view in the morning*
When it came to paying, we totalled up the food (3425rs) and then noticed the standard room charge pricings on the menu. This contradicted with what the woman in Pitam Deurali had told us. I asked the woman whether the room was free because we had breakfast and dinner, and was met with a huge laugh, a slap on the back (friendly) and the phrase 'hahaha it's not free, it's not free'. So we stuck an extra 415 rs on the bill, payed up and left.

*The beds weren't free*
#### Day 2: 17 April
07:30 - 09:30 (2 hours) - Walked from Forest Camp to Low Camp via Rest Camp (08:00). This is where we got our first proper glimpse of the snow covered mountains. We took a break and had some food and tea at a very friendly tea house at the top of low camp. They were in the process of building a middle tea house and Hotel Machapachure was at the bottom of the perimeter. The man at Hotel Laligurans, which is the teahouse at the top of Low Camp, showed us a proper map, which I took a picture of for future reference (which was our most useful map for the entre journey). He gave us lots of useful advice and was always smiling.

*The view from Low Camp, and our first proper glimpse of the mountains ahead.*
11:45 - 13:20 (1 hr 45 min) - Walked from Low Camp (2970m) to Mid Camp. Mid Camp is a small camp with two tea houses, where we only stopped for water and picture taking.
13:30 - 15:10 ( 1 hr 40 min) - Walked from Mid Camp to High Camp. High camp would be the highest sleep on the trek at 3700m. It was noticeably colder at this altitude, and we had all been noticing a shortness of breath when climbing up wards, however interestingly it didn't take long at all after stopping for breathing to return to normal. Walking down hill was comparatively easy, with little to no shortness of breath.

*Walking to High Camp*
High Camp is also where I experienced my first 'Mars Roll' which is a Snickers bar wrapped in some sort of bread like pastry and shaped like a Cornish pasty. It came with custard on top and was absolutely amazing. Considering I hadn't had anything sweet since I got to Nepal, this really hit the spot. We called these Mars Rolls ironically because I asked for a mars roll and it turned out to be a snickers, and the second time I got one the same happened. So we joked that I should buy a mars bar and ask them to make one with an actual mars bar. Sadly the only place I found above high camp that sold mars bars would be the next day at View Point, where the price made me cringe. Also Hotel Machapachure at Low Camp where we would stay the next day didn't have Mars Roll on the menu. It was a short but sweet affair.

*The legend-dairy Mars roll*
The food here was good too, despite another mishap with condiments. As you know the previous day, Dan had over-salted his meal when the salt shaker lid fell off. Well now it was Toms turn. Tom likes chili sauce, and wanted to add some to his plate of Dal Bhat. When he tipped the bottle over his food, the lid came off and the entire contents of the bottle was emptied onto his plate. That was one spicy meal. From that point on, none of us trusted anything with a lid.
We explored High Camp where the view was an improvement on the already amazing views of Low Camp. We went exploring as the sun was setting and there was a lake of cloud below us. We took some photos of both the beautiful scenery and our bad outfit choices and then went to bed.

*Cloud lake, just one of the stunning views*
I awoke the next day unusually early at 5.15 and went out to the toilet. It was just getting light and the stars and the moon were on show. The sky looked beautiful so I grabbed my photographer roommate and we wandered around taking photos until breakfast time at 06:00.

*Early morning stars. Credit <a href="https://www.instagram.com/mr_daniel_longley/">@mr_daniel_longley</a>*
#### Day 3: 18 April
07:30 - 08:40 - Walked from High Camp (3700m) to View Point (4300m). We set off for Mardi Himal Basecamp at around 7.30 after a fair amount of faffing. We decided to leave our heavy bags at High Camp as we would be returning back after visiting Base Camp and there was no point carrying a load of dirty washing and sleeping stuff up to the top. This was a welcome treat after 2 long days of trekking with full weight sacks. It was also a good thing as there were some seriously steep sections, where using your hands to scramble up the rocky path was nessecary. There were some scary cliff-like drops and hills that if you started rolling down, you wouldn't stop until you got to the bottom of the mountain.

*Proper mountaineering*
08:45 - 10:00 (1 hr 15 min) - Walked from View Point (4300m) to Mardi Himal Base Camp (4500m) which was the top of the trek. This was an exciting but tiring journey with some snowy ice patches to make things even more interesting. There were multiple view points along the way, marked by flag poles and stone platforms.

*Panorama from one of the many view points along the last stretch*

*Arriving at Upper View Point*
Despite the snow, we trekked up in tshirts as it was still hot from the blinding sun. Factor 50 at the ready was a must. We found base camp from the Nepalese flag and stone with 'Mardi B.C. 4500' written on it. There was also a stone with 'Vegan <3' etched into it - clearly some enthusiastic vegans had been here previously. We took some photos, selfies, had a lye down and ate some snacks whilst taking in the amazing views.

*Arriving at the top, Mardi Himal Base Camp. Credit <a href="https://www.instagram.com/tom.sinclair/">@tom.sinclair</a>*

*Group photo at the top of Mardi Himal Base Camp. Credit <a href="https://www.instagram.com/mr_daniel_longley/">@mr_daniel_longley</a>*
10:45 - 11:30 (45 mins) - Walked down from the Mardi Himal Base Camp to View Point. Cloud rose quickly as we descended and if we had got to Base Camp any later, we wouldn't have had any view of anything. We were lucky that we sped up the journey. By the time we reached View Point, we were inside a thick cloud.

*Descending into a thick cloud on the way down from Mardi Himal Base Camp. Credit <a href="https://www.instagram.com/tom.sinclair/">@tom.sinclair</a>*
11:30 - 12:50 (1 hour 20 mins) - We descended from View Point down to High Camp. However due to the misty cloud, visibility was around 10-20 meters. We took a wrong turn at a steep junction and ended up scrambling along a precarious slope, with lethal looking drops to our left. We clearly weren't on the path, and I was fearing the worst so I asked the group to turn around, find the path and wait it out a while until either the visibility improved or people came along who knew the path. We couldn't even remember where we had come from, so more precarious scrambling one at a time, very slowly and cautiously we climbed back up the slope to the big rock with the blue and white flag on it. Safe in the knowledge we were on the path, we rested and drank while we re thought the situation. Luckily, after around 5 minutes, an American family caught up with us, and they had two porters and a guide. So we followed them for a while until the path was clear enough for us to continue alone. The visibility was constantly bad and we had to stay close so that we could see the next member along. Eventually High Camp emerged out of the mist and we were greeted with food and tea. I had a Mars (Snickers) Roll to celebrate being alive still. We settled the bill (over 10,000 rs) and headed on down the mountain.

*High camp bill*
14:40 - 15:30 (50 mins) - Walked from High Camp to Mid Camp. Short DEET (insect repellant) and water break, not much point in photography due to poor visibility.
15:30 - 16:00 (30 mins) - Walked from Mid Camp to Low Camp. We would sleep here for the night. At High Camp, the cook of Hotel Fishtail called down to his brother at Hotel Machapachure at Low Camp to book a couple of rooms for us as it was apparently very busy. I thought that Hotel Machapachure was the nice smiley man's teahouse (which turned out to be Hotel Laligurans), so I was happy with that. However when we arrived and said we were staying at Hotel Machapachure he looked dissapointed and pointed us towards the lower teahouse. I felt a bit guilty because he had been to helpful to us, but we did buy food and tea from him, so it wasn't all bad. We made our way to Hotel Machapachure and spoke to the owner, who after some confusion gave us three double rooms for the price of a double and a triple. Clearly something got lost in translation. We put our stuff away, and some of the group went to sit in the communal dining area that all teahouses have. A few minutes into cleaning my soaking wet, wrinkly feet, a member of our group suggested trying to get a room at nice smiley man's teahouse because there were lots of people in bed sleeping in the communal area and we didn't want to disturb them. Also it would be nice to speak to smiley man again and ask his advice on some things, as the owner of Hotel Machapachure wasn't very talkative or helpful, or even around. Smiley man had rooms available but wanted us to speak to Machapachue man before moving to check its ok. I did that, and at first he said no problem, move if we like. So I went to get my things. However a few seconds later he came back complaining that it was not a good move as we had rung ahead to book the rooms and he had turned customers away as we had reserved the rooms. Fair enough, we apologised and said we would stay here. He also mentioned that we should use the communal area as we wanted, and if anyone complained they should go to sleep in their own rooms and he would deal with it. Awkward drama over, we went to get some food - which wasn't amazing, but maybe that's because we ordered a pizza. The pizza was not good. The curry and rice dishes were fine though.

*Things to do in the evenings - build a house of cards. The locals were amazed - can you see the guy taking a photo in the background?*
We awoke at the usual time of 6am, had breakfast and packed up.
#### Day 4: 19 April
07:30 - 09:40 (2 hours 10 minutes) - Walked from Low Camp (2970m) down to Sidhing (1700m) which is down 1270m. By this time the path was very muddy due to light rain and wet conditions. We took things slow and there was only one minor slip in the mud with no injuries. At Sidhing, the weather was still rubbish and the group didn't seem to be enjoying the conditions. The wife of the owner of Hotel Lalingurans had a lodge in Sidhing called Guatam Cottage. It's on the left of the fancy looking hotel as you pass the buffalo sign. They have jeep facilities and the general group feeling was that we should get a jeep back to Pokhara. We had tea with the owner and waited it out as the heavens opened. We were glad we decided to get the jeep down because the rain was so heavy, there were rivers forming on the hills. Eventually the jeep got there, and after helping the two young guys unload some bags of cement we headed down the mountain.
The jeep ride from Sidhing to Pokhara was an exciting and scary experience. The road was rocky, narrow, and deadly drops were common. The rain didn't help, neither did the steamy windows. After driving through winding mountain tracks, rivers and small towns, we arrived at Hotel Mountain View after approx 2-3 hours.
### Altitudes
These sometimes differ between the photo of the map I took from smiley man, and the photo of the sign I took at the Pothana Tourist Checkpoint.
- Kande 1770 (map)
- Pothana 1950 (sign), 1890 (map)
- Pitam Deurali 2100 (sign and map)
- Forest camp 2420 (sign), 2520 (map)
- Low camp 2995 (sign), 2970 (map)
- High camp 3550 (sign), 3700 (map)
- View Point 4300 (map)
- Mardi Himal BC West 4500 (sign and map)
### Suggested times
These are from the sign board at Pothana Tourist Checkpoint.
Up:
- Pothana - Pitam Deurali 0:45
- Pitam Deurali - Forest Camp 4:30
- Forest Camp - Low Camp 2:00
- Low Camp - High Camp 3:00
- High Camp - View Point 2:45
- View Point - Base Camp 3:00
Down:
- Base Camp - View Point 2:00
- View Point - High Camp 1:45
- High Camp - Low Camp 2:00
- Low Camp - Sidhing 3:30
<script src="//storage.googleapis.com/vrview/2.0/build/vrview.min.js"></script>
|
Python
|
UTF-8
| 3,665
| 2.84375
| 3
|
[] |
no_license
|
import gym
from gym import spaces
import numpy as np
from collections import namedtuple
MINIMUM_SKEW = -1.0
MAXIMUM_SKEW = 1.0
BID_OFFER_WIDTH = 2.0
MINIMUM_PRICE = 0.0
MINIMUM_INVENTORY = -10
MAXIMUM_INVENTORY = 10
INVENTORY_STEP_SIZE = 1.0
ALPHA_PENALTY = 0.05
Observation = namedtuple('Observation', ['inventory', 'tradeLost'])
class DealerEnvironment(gym.Env):
"""
Environment which a single dealer agent interacts with
action_space : skew value in [-1, 1]
observation_space : (currentInventory, currentMid, tradeWon)
"""
def __init__(self, dealerId, exchange):
super(DealerEnvironment, self).__init__()
self.action_space = spaces.Box(low=np.array([MINIMUM_SKEW]), high=np.array([MAXIMUM_SKEW]), dtype=np.float32)
self.observation_space = spaces.Box(low=np.array([MINIMUM_INVENTORY, MINIMUM_PRICE]), high=np.array([MAXIMUM_INVENTORY, np.inf]), dtype=np.float32)
self._dealerId = dealerId
self._exchange = exchange
def submitPricesToExchange(self, bid, ask):
self._exchange.submitDealerOrder(bid, ask, self._dealerId)
def submitSkewToExchange(self, skew):
latestMid = self._previousMid
bid = latestMid - BID_OFFER_WIDTH * ( 1 - skew ) / 2.0
ask = bid + BID_OFFER_WIDTH
# Limit to inventory - Have to be super competitive other side if too high
if self._inventory >= MAXIMUM_INVENTORY:
ask = latestMid - BID_OFFER_WIDTH
if self._inventory <= MINIMUM_INVENTORY:
bid = latestMid + BID_OFFER_WIDTH
self.submitPricesToExchange(bid, ask)
def step(self):
exchangeObservation = self._exchange.getPostTradeInformation(self._dealerId)
mid = exchangeObservation.mid
clientDirection = exchangeObservation.clientDirection
winningPrice = exchangeObservation.winningPrice
wonTrade = exchangeObservation.tradeWon
done = exchangeObservation.episodeFinished
tradeLost = int(exchangeObservation.tradeLost)
reward = self._getInventoryPnl(mid)
inventoryPnl = reward
#Penalising money made by holding inventory
reward -= ALPHA_PENALTY * np.min(inventoryPnl, 0)
if wonTrade:
self._updateInventory(clientDirection)
reward += self._getNewBusinessPnl(mid, winningPrice, clientDirection)
self._updatePreviousMid(mid)
observation = Observation(self._inventory, tradeLost)
return observation, reward, done, {}
def reset(self):
self._inventory = 0.0
self._previousMid = self._exchange.getInitialPrice()
tradeLost = int(False)
initialObservation = Observation(self._inventory, tradeLost)
return initialObservation
def render(self):
pass
def _getInventoryPnl(self, mid):
priceMove = mid - self._previousMid
return self._inventory * priceMove
def _getNewBusinessPnl(self, mid, winningPrice, clientDirection):
if clientDirection == 'clientBuys':
return INVENTORY_STEP_SIZE * (winningPrice - mid)
elif clientDirection == 'clientSells':
return INVENTORY_STEP_SIZE * (mid - winningPrice)
else:
raise KeyError("Invalid clientDirection")
def _updateInventory(self, clientDirection):
if clientDirection == 'clientBuys':
self._inventory -= INVENTORY_STEP_SIZE
elif clientDirection == 'clientSells':
self._inventory += INVENTORY_STEP_SIZE
else:
raise KeyError("invalid clientDirection")
def _updatePreviousMid(self, newMid):
self._previousMid = newMid
|
C++
|
UHC
| 3,155
| 2.5625
| 3
|
[] |
no_license
|
#pragma once
#include <cocos2d.h>
#include "UI_Def.h"
#include "../SoundManager.h"
USING_NS_CC;
class UIComponent : public cocos2d::CCLayer
{
public:
UIComponent(void);
virtual ~UIComponent(void);
public:
virtual void Init(void* packet) = 0;
virtual bool get_UIActive() = 0;
virtual void set_UIActive(bool isActive) = 0;
virtual void Update() = 0;
virtual void setTouchEvent(TouchEvent t_event, cocos2d::CCPoint t_pt) = 0;
virtual void Destroy() = 0;
public:
// UI ü Լ
virtual void* send_message_main() = 0;
// UI ü Ʒ Լ
virtual void* send_message_lua() = 0;
// UI ü κ ޱ Լ
virtual void recv_message_main(void* src_msg) = 0;
// UI ü Ʒκ ޱ Լ
virtual void recv_message_lua(void* src_msg) = 0;
public:
void set_ID(unsigned int id) { this->id |= id; }
void set_Sort(unsigned int sort) { id &= ~UI_TYPE_FIELD; id |= (sort << UI_TYPE_SHIFT); }
void set_Message(unsigned int message) { id &= ~UI_MESSAGE_FIELD; id |= (message << UI_MESSAGE_SHIFT); }
void set_UIStatus(unsigned int ui_stat) { id &= ~UI_TOUCH_EVENT_FIELD; id |= (ui_stat << UI_TOUCH_EVENT_SHIFT); }
unsigned int get_ID() { return id; }
unsigned int get_PureID() { return (id & (UI_TYPE_FIELD | UI_ID_FIELD)); }
unsigned int get_Sort() { return (id & UI_TYPE_FIELD) >> UI_TYPE_SHIFT; }
unsigned int get_Message() { return (id & UI_MESSAGE_FIELD) >> UI_MESSAGE_SHIFT; }
unsigned int get_UIStatus() { return (id & UI_TOUCH_EVENT_FIELD) >> UI_TOUCH_EVENT_SHIFT; }
public:
void setProgressTimer(cocos2d::CCProgressTimer* progress_timer) { this->progress_timer = progress_timer; this->progress_timer->setZOrder(2); }
void setProgressTimerPercentage(float current_percent)
{
if (progress_timer != nullptr)
progress_timer->setPercentage(current_percent);
}
void setIsSwipeMode(bool isSwipe) { isSwipeMode = isSwipe; }
bool getIsSwipeMode() { return isSwipeMode; }
bool is_UITouched(cocos2d::CCPoint& touched_Pt)
{
bool ui_active = get_UIActive();
cocos2d::CCPoint ui_pos = getPosition();
cocos2d::CCSize contents_size = getContentSize();
if(ui_active)
{
cocos2d::CCRect contents_Rect = cocos2d::CCRect(ui_pos.x, ui_pos.y, contents_size.width, contents_size.height);
if(contents_Rect.containsPoint(touched_Pt))
return true;
else
return false;
}
else
return false;
}
protected:
virtual void setResource(void* packet) = 0;
protected:
cocos2d::CCRect ui_rect;
cocos2d::CCProgressTimer* progress_timer;
unsigned int id; // UI ĺ UI .(enum )
// ȣ intڷ 4byte LSBκ 12bit ID ̸, 4bit UI Ʈ̸,
// 4bit UI ¸ Ÿ, 12bit UI شѴ.
// UI Check_Box , üũ , Slide_Control ġ شȴ.
void* recv_message_by_main;
bool isUISelected, isSwipeMode;
};
|
Markdown
|
UTF-8
| 2,774
| 2.796875
| 3
|
[] |
no_license
|
# tcpcopy的工作原理
TCPCopy 是一种请求复制(复制基于 TCP 的 packets)工具 ,通过复制在线数据包,修改 TCP/IP 头部信息,发送给测试服务器,达到欺骗测试服务器的TCP 程序的目的,从而为欺骗上层应用打下坚实基础。
tcpcopy 不是基于应用层的复制,而是基于底层数据包的请求复制,这么做的好处是:可以做到无需穿透整个协议栈,路程最短的,可以从数据链路层抓请求包,从数据链路层发包,路程一般的,可以在IP层抓请求包,从IP层发出去,不管怎么走,只要不走TCP,对在线的影响就会小得多。
tcpcopy 经历了三次架构调整,这三次架构的基本原理都一样,本质是利用在线数据包信息,模拟tcp客户端协议栈,欺骗测试服务器的上层应用服务。由于tcp交互是相互的,一般情况下需要知道测试服务器的响应数据包信息,才能利用在线请求数据包,构造出适合测试服务器的请求数据包,因此只要基于数据包的方式,无论怎么实现(除非是tcp协议改的面目全非),都需要返回响应包的相关信息。
三种架构的差别就在于在什么地方截获响应包。
具体这三种架构的差别请看上面文章,简单差别如下:
方案一:tcpcopy是从数据链路层\(pcap接口\)抓请求数据包,发包是从IP层发出去
方案二:tcpcopy默认从IP层抓包,从IP层发包
方案三:跟方案一一样,不过引入了独立的 intercept\(assistant server\)
tcpcopy 架构
tcpcopy运行需要intercept的支持,tcpcopy负责抓包和发包工作,而intercept负责截获应答包
它的数据流转和部署架构如下图:

具体的生产环境和镜像环境数据传递流程图如下:

TCPcopy 从数据链路层 copy 端口请求,然后更改目的 ip 和目的端口。
将修改过的数据包传送给数据链路层,并且保持 tcp 连接请求。
通过数据链路层从 online server 发送到 test server。
在数据链路层解封装后到达 nginx 响应的服务端口。
等用户请求的数据返回结果后,回包走数据链路层。
通过数据链路层将返回的结果从 test server 发送到 assistant server。注:test server 只有一条默认路由指向 assistant server。
数据到达 assistant server 后被 intercept 进程截获。
过滤相关信息将请求状态发送给 online server 的 tcpcopy,关闭 tcp 连接。
对于tcpcopy,configure的时候加上--offline
--offline replay TCP streams from the pcap file
执行的时候,加上-i参数,用来指定pcap文件地址
对于intercept,不用变化
|
PHP
|
UTF-8
| 548
| 3.234375
| 3
|
[] |
no_license
|
<?php
function solution($S) {
// write your code in PHP7.0
$len = strlen($S);
$St = [];
$closes = [']', '}', ')'];
$opens = [
']' => '[',
')' => '(',
'}' => '{',
];
for ($i = 0; $i < $len; $i++) {
$c = $S[$i];
if (in_array($c, $closes)) {
$pop = array_pop($St);
if (strlen($pop) == 0 || $pop != $opens[$c]) return 0;
} else {
array_push($St, $c);
}
}
return count($St) == 0 ? 1 : 0;
}
var_dump(solution("{[()()]}"));
|
TypeScript
|
UTF-8
| 2,668
| 2.609375
| 3
|
[] |
no_license
|
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-part10-angular-form-control-value-changes',
templateUrl: './part10-angular-form-control-value-changes.component.html',
styleUrls: ['./part10-angular-form-control-value-changes.component.css']
})
export class Part10AngularFormControlValueChangesComponent implements OnInit {
employeeForm: FormGroup;
fullNameLength = 0;
constructor(private fb:FormBuilder) { }
ngOnInit(): void {
this.employeeForm = this.fb.group({
fullName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(10)]],
email: ['', Validators.required],
skills: this.fb.group({
skillName: [''],
experienceInYear: [''],
proficiency: ['beginner']
})
});
this.employeeForm.get('fullName').valueChanges.subscribe((value: string) => {
this.fullNameLength = value.length;
});
this.employeeForm.valueChanges.subscribe((value: any) => {
console.log(JSON.stringify(value));
});
}
onSubmit():void {
console.log(this.employeeForm);
console.log(this.employeeForm.value);
console.log('==========FormGroup method to access form values=========');
console.log('FullName:', this.employeeForm.value.fullName);
console.log('Email:', this.employeeForm.value.email);
console.log('Control:', this.employeeForm.controls.fullName);
console.log('Control:', this.employeeForm.controls.email);
console.log('Control with value:', this.employeeForm.controls.fullName.value);
console.log('Control with value:', this.employeeForm.controls.email.value);
console.log('Touched:', this.employeeForm.controls.fullName.touched);
console.log('Touched:', this.employeeForm.controls.email.touched);
console.log('==========get() method to access form values=========');
console.log('FullName:', this.employeeForm.get('fullName').value);
console.log('Email:', this.employeeForm.get('email').value);
}
onLoadDataClick(): void {
//Use setValue to update all form controls
this.employeeForm.setValue({
fullName: 'Randhir Singh',
email: 'randhir.ges@gmail.com',
skills: {
skillName: 'C#',
experienceInYear: 3,
proficiency: 'intermediate'
}
});
//Use patchValue to update subset of form controls
// this.employeeForm.patchValue({
// fullName: 'Randhir Singh',
// email: 'randhir.ges@gmail.com',
// // skills: {
// // skillName: 'C#',
// // experienceInYear: 3,
// // proficiency: 'intermediate'
// // }
// });
}
}
|
Python
|
UTF-8
| 1,858
| 2.953125
| 3
|
[] |
no_license
|
import pika
import json
from enum import Enum
from typing import Any, List
from dataclasses import dataclass
from pika.connection import Connection
from pika.channel import Channel
from loguru import logger
class MessageType(Enum):
TEXT = 1
JSON = 2
@dataclass
class RMQConfig(object):
host: str
port: int
exchange: str
topic: str
queues: List[str]
messageType: MessageType
class SimpleRMQTopicConnection(object):
def __init__(self, config: RMQConfig):
self._connector: Connection = pika.BlockingConnection(
pika.ConnectionParameters(host = config.host, port = config.port)
)
self._channel: Channel = self._connector.channel()
self._channel.exchange_declare(
config.exchange,
exchange_type = "topic",
durable = True
)
for q in config.queues:
self._channel.queue_declare(q, durable = True)
self._channel.queue_bind(q, config.exchange)
self._exchange: str = config.exchange
self._topic: str = config.topic
self._messageType: MessageType = config.messageType
def __getJsonString(self, message: Any) -> str:
return json.dumps(message)
def send(self, message: Any):
messStr = ""
if self._messageType == MessageType.JSON:
messStr = self.__getJsonString(message)
elif self._messageType == MessageType.TEXT:
messStr = str(message)
try:
self._channel.basic_publish(
self._exchange,
self._topic,
messStr,
mandatory = True,
)
except pika.exceptions.UnroutableError:
logger.error("Message was returned")
def close(self):
if self._connector is not None:
self._connector.close()
|
Python
|
UTF-8
| 16,850
| 3.1875
| 3
|
[] |
no_license
|
import ika
import engine
#### Inventory System ############################################################################################
class Inventory(object):
def __init__(self):
#None = empty
#DummyItem = filled box, points to the item object that fills it
#Item object = obvious :P
self.items = [None] * 32
self.left = 247
self.top = 6
self.AddItem(1, 1, Shells(16))
self.AddItem(0, 1, Shells(10))
self.AddItem(0, 0, Medkit(1))
self.AddItem(0, 2, Food(2))
#self.AddItem(3, 0, Shotgun(6) )
#self.AddItem(0, 5, Armor1())
self.AddItem(2, 6, Clip(40))
self.AddItem(2, 7, Clip(60))
self.AddItem(3, 7, Clip())
self.AddItem(1, 7, Clip(42))
self.block = ika.Image("Img/ui/block.png")
self.grabbeditem = None
def Draw(self):
for i, item in enumerate(self.items):
if item is not None:
if isinstance(item, Item):
#for w in range(item.w):
# for h in range(item.h):
#ika.Video.TintBlit(self.block, int(self.left+16*(i%4)+16*w), int(self.top+16*(i/4)+16*h),
# ika.RGB(0,0,128,100))
#ika.Video.DrawRect(int(self.left+16*(i%4) - 1), int(self.top+16*(i/4) - 1),
# int(self.left+16*(i%4)+16*item.w - 1), int(self.top+16*(i/4)+16*item.h - 1),
#ika.RGB(0,0,255,128))
# engine.engine.color)
item.Draw(int(self.left+16*(i%4)), int(self.top+16*(i/4)))
#tries to add an item to the inventory. Returns true if an item is grabbed as a result of this, false if not
def AddItem(self, x, y, item):
if x+item.w>4 or y+item.h>8: return False #can't place an item if doing so would put it ouf of bounds
g_item=None
grab = False
itemlist = self.CheckItems(x, y, item.w, item.h)
if len(itemlist) < 2: #only try to place the item if there is one or no items underneath it
if len(itemlist) == 1: #only one item, try to grab it
g_item=self.TakeItem(itemlist[0][0], itemlist[0][1]) #Takes the item at the x / y location of first (only) item in the itemlist
if isinstance(g_item, Stackable) and item.countable == True and type(g_item) == type(item) : #same type of item, try to stack them
needed = item.max_count - item.count
if needed >= g_item.count: #has room for the entire grabbed item to stack into it
item.count += g_item.count
g_item = None
elif needed > 0: #only set to the maximum amount allowed by the item, rest is reduced from original item
item.count = item.max_count
g_item.count -= needed
else: #normal item, so grab it instead of stacking it
grab = True
if (item.h > 1 or item.w > 1): #item < 1 tile in some direction, so place dummy items first
d = DummyItem(x,y) #dummy items that point to the real item (only used for items larger than 1x1)
for h in range(item.h):
for w in range(item.w):
self.items[self.GetIndex(x+w,y+h)] = d
self.items[self.GetIndex(x, y)] = item #place the real item at the top left location
self.grabbeditem=g_item
else: grab = False #too many items underneath
return grab
#returns a list of x, y locations
def CheckItems(self, x, y, w, h):
itemList = []
for a in range(w):
for b in range(h):
i = self.items[self.GetIndex(x+a,y+b)]
if isinstance(i, Item):
itemList.append((x+a, y+b))
elif isinstance(i, DummyItem):
if not (i.x, i.y) in itemList: #add original item, not the dummy
itemList.append((i.x, i.y))
return itemList
def TakeItem(self, x, y): #picks up an item from inventory and returns it
item = self.items[self.GetIndex(x,y)]
if isinstance(item, Item):
self.RemoveItem(x,y, item.w, item.h)
elif isinstance(item, DummyItem):
i = self.items[self.GetIndex(item.x, item.y)] #find the original index pointed to by the dummy
self.RemoveItem(item.x, item.y, i.w, i.h)
item = i
else: return None
return item
def DeleteItem(self, item):
x, y = self.GetXY(self.items.index(item))
self.RemoveItem(x, y, item.w, item.h)
def RemoveItem(self, x, y, w, h):
for i in range(h):
for j in range(w):
self.items[self.GetIndex(x+j,y+i)] = None
def GetIndex(self, x, y): #square coordinates
return int((y*4)+x)
def GetXY(self, index):
return index%4, index/4
#### Public functions (The only ones the mouse system should access :P) ########################################
#### x and y are mouse positions for these functions
def UseItem(self, x, y):
x -= self.left
y -= self.top
item = self.items[self.GetIndex(int(x/16),int(y/16))]
if isinstance(item, Item): #make doubly sure it's an item before trying to use it..
item.Use()
if isinstance(item, Stackable) and item.count == 0:
self.RemoveItem(int(x/16), int(y/16), item.w, item.h)
def PlaceItem(self, x, y):
x -= self.left
y -= self.top
if isinstance(self.AddItem(int(x/16), int(y/16), self.grabbeditem), Item):
engine.engine.messages.AddMessage(self.grabbeditem.name)
def GrabItem(self, x, y): #picks up an item from inventory and assigns it to be the item in your hand
x -= self.left
y -= self.top
item = self.TakeItem(int(x/16), int(y/16))
if item is not None:
self.grabbeditem = item
engine.engine.messages.AddMessage(self.grabbeditem.name)
#### Equipment System ##############################################################################################
class Equip(object):
def __init__(self):
self.righthand = Rifle(60)
self.lefthand = None
self.armor = Armor2()
self.belt = Belt2()
#self.righthand = None
#self.lefthand = None
#self.armor = Clothing()
#self.belt = None
def Draw(self):
if self.righthand: self.righthand.Draw(253, 178)
if self.lefthand: self.lefthand.Draw(253, 210)
if self.armor: self.armor.Draw(272, 178)
if self.belt: self.belt.Draw(272, 210)
def AddItem(self, item, slot):
if engine.engine.attacking or engine.engine.reloading: return #BAD! :P
g_item = None
if slot == 0: #right hand
if isinstance(item, Weapon):
if item.h == 2: #only takes one slot, do as normal
g_item = self.righthand
self.righthand = item
if g_item:
engine.engine.messages.AddMessage(g_item.name)
else: #two handed weapon
if self.righthand and self.lefthand: return #both slots full
if self.righthand: #only right hand full
g_item = self.righthand
engine.engine.messages.AddMessage(g_item.name)
self.righthand = None
self.righthand = item
elif self.lefthand: #only left hand full
g_item = self.lefthand
engine.engine.messages.AddMessage(g_item.name)
self.lefthand = None
self.righthand = item
else: #no hands full
self.righthand = item
else: return
elif slot == 1: #left hand
if item.w == 1 and item.h == 1:
if self.righthand and self.righthand.h == 3: #two handed weapon already equipped
g_item = self.righthand
engine.engine.messages.AddMessage(g_item.name)
self.righthand = None
self.lefthand = item
else: #just a simple place
g_item = self.lefthand
self.lefthand = item
else: return
elif slot == 2: #armor
if isinstance(item, Armor):
g_item = self.armor
if g_item: engine.engine.messages.AddMessage(g_item.name)
self.armor = item
else: return
elif slot == 3: #belt
if isinstance(item, Belt):
g_item = self.belt
if g_item: engine.engine.messages.AddMessage(g_item.name)
self.belt = item
else: return
engine.engine.inv.grabbeditem = g_item
def TakeItem(self, slot):
r = None
if slot == 0:
r = self.righthand
self.righthand = None
elif slot == 1:
r = self.lefthand
self.lefthand = None
elif slot == 2:
r = self.armor
self.armor = None
elif slot == 3:
r = self.belt
self.belt = None
if r: engine.engine.messages.AddMessage(r.name)
return r
def UseItem(self, slot):
item = None
if slot == 0: item = self.righthand
elif slot == 1: item = self.lefthand
elif slot == 2: item = self.armor
elif slot == 3: item = self.belt
if isinstance(item, Item):
item.Use()
if isinstance(item, Stackable) and item.count == 0:
self.TakeItem(slot)
#### Generic Item Objects ###########################################################################################
class Item(object):
def __init__(self, img, w, h, name, count=1, countable=False, imgused=None):
self.img = img
self.w = w
self.h = h
self.count = count
self.countable = countable
self.name = name
if imgused is not None:
self.imgused = imgused
def Draw(self, x, y):
ika.Video.Blit(self.img, x, y)
if self.countable:
if self.count > 0: #print in white if at least 1 left. Works up to 99, no ammo/stacks higher than this
engine.engine.itemfont.Print(x + 16*self.w - 6*len(str(self.count))+1, y + 16*self.h - 7, str(self.count))
else: engine.engine.itemfontgrey.Print(x + 16*self.w - 6, y + 16*self.h - 7, "0")
def Use(self): #specific items must override this if they are to be used
pass
class DummyItem(object):
def __init__(self, x, y):
self.x = x
self.y = y
#### Specific Item Objects #########################################################################################
#Weapons
class Weapon(Item):
def __init__(self, img, w, h, name, count=1, countable=False):
super(Weapon, self).__init__(img, w, h, name, count, countable)
self.attack = 0 #attack power
self.reloadtime = 0 #ticks per reload
class Pipe(Weapon):
img = ika.Image("Img/items/pipe.png")
def __init__(self, count=0):
super(type(self), self).__init__(type(self).img, 1, 2, "Lead Pipe")
self.attack = 4
self.reloadtime = 35
class Pistol(Weapon):
img = ika.Image("Img/items/pistol.png")
def __init__(self, count=0):
super(type(self), self).__init__(type(self).img, 1, 2, "Pistol", count, True)
self.attack = 3
self.reloadtime = 35
class Shotgun(Weapon):
img = ika.Image("Img/items/shotgun.png")
def __init__(self, count=0):
super(type(self), self).__init__(type(self).img, 1, 3, "Shotgun", count, True)
self.attack = 10
self.reloadtime = 70
class Rifle(Weapon):
img = ika.Image("Img/items/rifle.png")
def __init__(self, count=0):
super(type(self), self).__init__(type(self).img, 1, 3, "Assault Rifle", count, True)
self.attack = 2
self.reloadtime = 200
#Armor
class Armor(Item):
def __init__(self, img, w, h, name, count=1, countable=False):
super(Armor, self).__init__(img, w, h, name, count, countable)
class Clothing(Armor):
img = ika.Image("Img/items/clothing1.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 2, 2, "Clothes")
self.defense = 1
class Armor1(Armor):
img = ika.Image("Img/items/armor1.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 2, 2, "Light Armor")
self.defense = 2
class Armor2(Armor):
img = ika.Image("Img/items/armor2.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 2, 2, "Medium Armor")
self.defense = 3
class Armor3(Armor):
img = ika.Image("Img/items/armor3.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 2, 2, "Heavy Armor")
self.defense = 4
#Belts
class Belt(Item):
def __init__(self, img, w, h, name, count=1, countable=False):
super(Belt, self).__init__(img, w, h, name, count, countable)
class Belt1(Belt):
img = ika.Image("Img/items/belt1.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 2, 1, "Belt #1")
self.defense = 2
class Belt2(Belt):
img = ika.Image("Img/items/belt2.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 2, 1, "Belt #2")
self.defense = 5
#Keys
class Key(Item):
def __init__(self, img, w, h, name, count=1, countable=False):
super(Key, self).__init__(img, w, h, name, count, countable)
class BlueKey(Key):
img = ika.Image("Img/items/key_blue.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 1, 1, "Blue Keycard")
self.access = 1
class GreenKey(Key):
img = ika.Image("Img/items/key_green.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 1, 1, "Green Keycard")
self.access = 2
class RedKey(Key):
img = ika.Image("Img/items/key_red.png")
def __init__(self):
super(type(self), self).__init__(type(self).img, 1, 1, "Red Keycard")
self.access = 3
#General Items
class Recorder(Item):
img = ika.Image("Img/items/recorder.png")
imgused = ika.Image("Img/items/recorder_used.png")
def __init__(self, lognumber):
super(type(self), self).__init__(type(self).img, 1, 1, "Log Recorder", type(self).imgused)
self.lognumber = lognumber
self.used = False
def Use(self):
if not self.used:
engine.engine.pda.ReadLog(self.lognumber)
engine.engine.messages.AddMessage("Log Uploaded to PDA")
engine.engine.sound.Play("beep1.wav")
self.used = True
self.img = self.imgused
#Stackable Items
class Stackable(Item):
def __init__(self, img, w, h, name, count=1, countable=True):
super(Stackable, self).__init__(img, w, h, name, count, countable)
self.max_count = 0 #override per item
#Ammo
class Clip(Stackable):
img = ika.Image("Img/items/clip.png")
def __init__(self, count=16):
super(type(self), self).__init__(type(self).img, 1, 1, "Clip", count, True)
self.max_count = 60
def Use(self):
pass
#engine.engine.Reload(Clip)
class Shells(Stackable):
img = ika.Image("Img/items/shells.png")
def __init__(self, count=12):
super(type(self), self).__init__(type(self).img, 1, 1, "Shells", count, True)
self.max_count = 24
def Use(self):
pass
#engine.engine.Reload(Shells)
class Cells(Stackable):
img = ika.Image("Img/items/powercell.png")
def __init__(self, count=30):
super(type(self), self).__init__(type(self).img, 1, 1, "Power Cells", count, True)
self.max_count = 90
def Use(self):
pass
#Healing items
class Hypo(Stackable):
img = ika.Image("Img/items/hypo.png")
def __init__(self, count=1):
super(type(self), self).__init__(type(self).img, 1, 1, "Health hypo", count, True)
self.max_count=5
def Use(self):
engine.engine.Heal(20)
self.count -= 1
class Medkit(Stackable):
img = ika.Image("Img/items/medkit.png")
def __init__(self, count=1):
super(type(self), self).__init__(type(self).img, 1, 1, "Medical kit", count, True)
self.max_count=5
def Use(self):
engine.engine.Heal(50)
self.count -= 1
class Food(Stackable):
img = ika.Image("Img/items/foodcan.png")
def __init__(self, count=1):
super(type(self), self).__init__(type(self).img, 1, 1, "Canned food", count, True)
self.max_count=5
def Use(self):
engine.engine.Heal(10)
self.count -= 1
|
PHP
|
UTF-8
| 9,835
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* DocumentStore
* Copyright 2020-2021 Jamiel Sharief.
*
* Licensed under The MIT License
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* @copyright Copyright (c) Jamiel Sharief
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types = 1);
namespace DocumentStore\Test;
use DocumentStore\Assert;
use PHPUnit\Framework\TestCase;
use DocumentStore\DocumentStore;
use DocumentStore\Exception\DocumentStoreException;
class AssertTest extends TestCase
{
public function testEquals()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'name' => 'Tony'
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
}
public function testNotEquals()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'name !=' => 'Tony'
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
}
public function testEqualsIn()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'name' => ['Foo','Tony']
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
}
public function testNotEqualsIn()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'name !=' => ['Foo','Tony']
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
}
public function testEqualsDeep()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'emails' => 'cbear@hotmail.com'
]);
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
}
public function testEqualsInDeep()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'emails' => ['foo','cbear@hotmail.com']
]);
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
}
public function testNotEqualsDeep()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'emails !=' => 'cbear@hotmail.com'
]);
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
}
public function testNotEqualsInDeep()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'emails !=' => ['foo','cbear@hotmail.com']
]);
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
}
public function testEqualsDeepArray()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'addreses.street' => '25 corp road'
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
}
public function testEqualsInDeepArray()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'addreses.street' => ['foo','25 corp road']
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
}
public function testNotEqualsDeepArray()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'addreses.street !=' => '25 corp road'
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
}
public function testNotEqualsInDeepArray()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'addreses.street !=' => ['foo','25 corp road']
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
}
public function testLike()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'name LIKE' => '%o_y'
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
}
public function testNotLike()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'name NOT LIKE' => 'T_n%'
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
}
public function testGreaterThan()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'age >' => 30
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
// check invalid value
$assert = new Assert([
'age >' => 'a'
]);
$this->assertFalse($assert->conditions($document));
}
public function testGreaterThanEquals()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'age >=' => 32
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertTrue($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertFalse($assert->conditions($document));
// check invalid value
$assert = new Assert([
'age >=' => 'a'
]);
$this->assertFalse($assert->conditions($document));
}
public function testLessThan()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'age <' => 32
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
// check invalid value
$assert = new Assert([
'age <' => 'a'
]);
$this->assertFalse($assert->conditions($document));
}
public function testLessThanEquals()
{
$store = new DocumentStore($this->fixture_path('contacts'));
$assert = new Assert([
'age <=' => 25
]);
$document = $store->get('5f731f1345b65d076150a7b6');
$this->assertFalse($assert->conditions($document));
$document = $store->get('5f7320135e9d29aebacd4f97');
$this->assertTrue($assert->conditions($document));
// check invalid value
$assert = new Assert([
'age <=' => 'a'
]);
$this->assertFalse($assert->conditions($document));
}
public function testParseConditionsInvalidOperator()
{
$this->expectException(DocumentStoreException ::class);
$assert = new Assert([
'name <-o->' => 'darthy'
]);
}
public function testParseConditionsInvalidLikeString()
{
$this->expectException(DocumentStoreException ::class);
$assert = new Assert([
'name LIKE' => ['%foo']
]);
}
private function fixture_path(string $path): string
{
return __DIR__ .'/Fixture/' . $path;
}
}
|
Shell
|
UTF-8
| 397
| 3.859375
| 4
|
[] |
no_license
|
#!/bin/bash
# put a trailing slash on the source dir to indicate *contents of* that directory
SOURCE_DIR=$1
DEST_DIR=$2
if [ ! -d "${SOURCE_DIR}" ]; then
echo "Error: source dir not specified or not a directory"
exit 1
fi
if [ ! -d "${DEST_DIR}" ]; then
echo "Error: dest dir not specified or not a directory"
exit 1
fi
rsync -n -v -raP --delete "${SOURCE_DIR}" "${DEST_DIR}"
|
JavaScript
|
UTF-8
| 768
| 2.5625
| 3
|
[] |
no_license
|
const express=require('express');
const bodyParser=require('body-parser')
const {randomBytes}=require('crypto');
const cors=require('cors');
const axios=require('axios')
const app=express();
app.use(bodyParser.json());
app.use(cors())
const posts={};
app.get('/posts',(req,res)=>{
res.send(posts);
});
app.post('/posts/create',async (req,res)=>{
const id= randomBytes(4).toString('hex');
const {title}=req.body;
posts[id]={
id,title
};
await axios.post('http://event-bus-srv:4005/events',{
type:'PostCreated',
data:{
id,title
}
})
res.status(201).send(posts[id]);
});
app.post('/events',(req,res)=>{
console.log('Received Event:',req.body.type);
res.send({});
})
app.listen(4000,()=>{
console.log("Listening on 4000");
});
|
Python
|
UTF-8
| 2,661
| 3.546875
| 4
|
[] |
no_license
|
import numpy as np
from matplotlib import pyplot
import math
# Dati della tabella
data = np.array([[833. , 37. ],
[987. , 41.6],
[883. , 37.2],
[378. , 15.2],
[ 84. , 3.4],
[483. , 19.6],
[835. , 35.1],
[646. , 28.9],
[508. , 22.6],
[ 90. , 3.7]])
#------------------------
# definizione del modello
#------------------------
class LinearModel:
def __init__(self):
self.angular_coeff =None
self.intercept=None
self.train_data=None
def fit(self,train_data):
# controllo che train_data sia della forma giusta
try:
assert(len(train_data.shape)==2)
assert(train_data.shape[1]==2)
assert(len(train_data[:,0]) == len(train_data[:,1]))
except:
raise Exception("Bad train_data shape! {} should be (*,2)".format(train_data.shape))
# ricavo le x e le y da train_data
x = train_data[:,0]
y = train_data[:,1]
#calcolo la media delle x e delle y
avg_x = sum(x)/len(x)
avg_y = sum(y)/len(y)
#calcolo il coefficiente di correlazione (calcolo prima le tre sommatorie)
sum_diff_xy = np.sum((x - avg_x) * (y - avg_y))
sum_pow_x = np.sum((x-avg_x)**2)
sum_pow_y = np.sum((y-avg_y)**2)
coeff_P = sum_diff_xy / math.sqrt(sum_pow_x * sum_pow_y)
dev_std_x = math.sqrt(sum_pow_x /(len(x)-1))
dev_std_y = math.sqrt(sum_pow_y /(len(y)-1))
#coefficiente angolare:
self.angular_coeff = coeff_P * (dev_std_y / dev_std_x)
self.intercept = avg_y - self.angular_coeff * avg_x
self.train_data =train_data
def predict(self,xs):
if self.angular_coeff is None or self.intercept is None:
raise Exception ("coefficiente angolare e/o intercetta non calcolati ")
return xs*self.angular_coeff + self.intercept
#-------------------------
# applicazione del modello
#-------------------------
def plot_regression(model):
xs= np.array([0,100,200,2000,2500])
ys = model.predict(xs)
pyplot.plot(xs,ys, "blue")
try:
linMod = LinearModel()
linMod.fit(data)
plot_regression(linMod)
km_tragitto = 2500
litri_tragitto = linMod.predict(km_tragitto)
prezzo_benzina = 1.4
tot_costo = litri_tragitto*prezzo_benzina
quota_individuale = tot_costo/3
#Stampa i risultati a schermo
print("Litri di benzina totali:{}lt\nQuota individuale:{}€".format(litri_tragitto,quota_individuale))
pyplot.plot(data[:,0],data[:,1],'go')
pyplot.plot(km_tragitto, litri_tragitto, 'ro')
pyplot.show()
except Exception as e:
print(e)
|
Go
|
UTF-8
| 148
| 3.125
| 3
|
[] |
no_license
|
package main
import "fmt"
func main(){
x := []int{1,2}
i:=append(x, 3)
fmt.Printf("%v\n", x) //1,2
fmt.Printf("%v\n", i) //1,2,3
}
|
Java
|
UTF-8
| 3,643
| 2.046875
| 2
|
[] |
no_license
|
package com.mavericks.checkin.holders;
import android.os.Parcel;
import android.os.Parcelable;
public class HCHistoryHolder extends HCBaseHolder implements Parcelable {
String transaction_id;
String user_name;
String dob;
String gender;
String address;
String fname;
String hnumber;
String email;
String mobile;
String special;
String name;
String visit_date;
String dname;
String totalamount;
boolean priorpass = false;
public String getTransaction_id() {
return transaction_id;
}
public boolean isPriorpass() {
return priorpass;
}
public void setPriorpass(boolean priorpass) {
this.priorpass = priorpass;
}
public void setTransaction_id(String transaction_id) {
this.transaction_id = transaction_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public HCHistoryHolder() {
}
public HCHistoryHolder(Parcel in) {
readFromParcel(in);
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getHnumber() {
return hnumber;
}
public void setHnumber(String hnumber) {
this.hnumber = hnumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getSpecial() {
return special;
}
public void setSpecial(String special) {
this.special = special;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVisit_date() {
return visit_date;
}
public void setVisit_date(String visit_date) {
this.visit_date = visit_date;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getTotalamount() {
return totalamount;
}
public void setTotalamount(String totalamount) {
this.totalamount = totalamount;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(transaction_id);
dest.writeString(user_name);
dest.writeString(name);
dest.writeString(special);
dest.writeString(address);
dest.writeString(visit_date);
dest.writeString(totalamount);
dest.writeString(visit_date);
dest.writeString(dob);
// dest.writeLong(favTime);
}
public void readFromParcel(Parcel in) {
transaction_id = in.readString();
user_name = in.readString();
name = in.readString();
special = in.readString();
address = in.readString();
visit_date = in.readString();
totalamount = in.readString();
visit_date = in.readString();
dob = in.readString();
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
@Override
public HCHistoryHolder createFromParcel(Parcel in) {
return new HCHistoryHolder(in);
}
@Override
public Object[] newArray(int size) {
return new HCHistoryHolder[size];
}
};
}
|
Java
|
UTF-8
| 6,738
| 2.625
| 3
|
[] |
no_license
|
package benchmark;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.function.BiFunction;
import java.util.function.Function;
import static java.lang.Double.NaN;
import static java.time.temporal.ChronoUnit.NANOS;
public class AvgTimeBenchmark<ITER_IN, ITER_OUT> implements Benchmark {
private static final Random rn = new Random();
private final int warmUpIterations;
private final int testCaseIterations;
private final BiFunction<ITER_IN, IterationContext, ITER_OUT> testCase;
private final Function<Integer, ITER_IN> dataProvider;
private final Runnable beforeTestCallback;
private final Runnable afterWarmupCallback;
private final List<Duration> times;
private AvgTimeBenchmark(int warmUpIterations,
int testCaseIterations,
BiFunction<ITER_IN, IterationContext, ITER_OUT> testCase,
Function<Integer, ITER_IN> dataProvider,
Runnable beforeTestCallback,
Runnable afterWarmupCallback) {
Objects.requireNonNull(testCase);
this.warmUpIterations = warmUpIterations;
this.testCaseIterations = testCaseIterations;
this.testCase = testCase;
this.dataProvider = dataProvider;
this.beforeTestCallback = beforeTestCallback;
this.afterWarmupCallback = afterWarmupCallback;
this.times = new ArrayList<>();
}
@Override
public Duration run() {
for (int i = 0; i < warmUpIterations; i++) {
beforeTestCallback.run();
warmUpIteration(i);
}
afterWarmupCallback.run();
for (int i = 0; i < testCaseIterations; i++) {
beforeTestCallback.run();
iteration(i);
}
double avg = times.stream()
.mapToLong(duration -> duration.get(NANOS))
.average()
.orElse(NaN);
return Duration.ofNanos(Math.round(avg));
}
private void iteration(Integer iteration) {
IterationContext context = new IterationContext();
ITER_IN input = dataProvider.apply(iteration);
System.gc();
long start = System.nanoTime();
Object result = testCase.apply(input, context);
long time = System.nanoTime() - start - context.getTotalPauseNanos();
if (!context.excludeResult) {
times.add(Duration.ofNanos(time));
}
context.jitAssertNoPause(result);
}
private void warmUpIteration(Integer iteration) {
IterationContext context = new IterationContext();
context.isWarmup = true;
Object result = testCase.apply(dataProvider.apply(iteration), context);
context.jitAssertNoPause(result);
}
public static class IterationContext {
private final List<Duration> pauseDurations;
private boolean isWarmup;
private boolean excludeResult;
public IterationContext() {
this.pauseDurations = new ArrayList<>();
}
public void pause(Runnable runnable) {
if (!isWarmup) {
long start = System.nanoTime();
runnable.run();
long time = System.nanoTime() - start;
pauseDurations.add(Duration.ofNanos(time));
}
}
public void jitAssert(Object result) {
long start = System.nanoTime();
consume(result);
long time = System.nanoTime() - start;
pauseDurations.add(Duration.ofNanos(time));
}
public void jitAssertNoPause(Object result) {
consume(result);
}
/**
* Do some operations on tested objects so it will prevent JIT from eliminating
* useless computations.
*
* @param result object to prevent JIT optimizations
*/
private void consume(Object result) {
if (result == null) {
System.out.println("[DEBUG] Null result from test");
} else {
if (result instanceof Collection &&
result.hashCode() - ((Collection) result).size() == rn.nextInt(200000)) {
System.out.println("[DEBUG] JIT assertion for collection");
} else {
if ((result.hashCode() == rn.nextInt(200000))) {
System.out.println("[DEBUG] JIT assertion for object");
}
}
}
}
public long getTotalPauseNanos() {
double pauseSum = pauseDurations.stream()
.mapToLong(duration -> duration.get(NANOS))
.sum();
return Math.round(pauseSum);
}
public boolean isWarmup() {
return isWarmup;
}
public void exclueResult() {
this.excludeResult = true;
}
}
public static class Builder<I, O> {
private int warmUpIterations;
private int testCaseIterations;
private BiFunction<I, IterationContext, O> testCase;
private Function<Integer, I> dataProvider;
private Runnable beforeTestCallback;
private Runnable afterWarmupCallback;
public Builder() {
this.beforeTestCallback = () -> { };
this.afterWarmupCallback = () -> { };
this.dataProvider = i -> null;
}
public Builder<I, O> warmUpIterations(int warmUpIterations) {
this.warmUpIterations = warmUpIterations;
return this;
}
public Builder<I, O> testCaseIterations(int testCaseIterations) {
this.testCaseIterations = testCaseIterations;
return this;
}
public Builder<I, O> testCase(BiFunction<I, IterationContext, O> testCase) {
this.testCase = testCase;
return this;
}
public Builder<I, O> dataProvider(Function<Integer, I> dataProvider) {
this.dataProvider = dataProvider;
return this;
}
public Builder<I, O> beforeTestCallback(Runnable beforeTestCallback) {
this.beforeTestCallback = beforeTestCallback;
return this;
}
public Builder<I, O> afterWarmupCallback(Runnable afterWarmupCallback) {
this.afterWarmupCallback = afterWarmupCallback;
return this;
}
public AvgTimeBenchmark<I, O> build() {
return new AvgTimeBenchmark<>(warmUpIterations,
testCaseIterations,
testCase,
dataProvider,
beforeTestCallback,
afterWarmupCallback);
}
}
}
|
PHP
|
UTF-8
| 900
| 2.8125
| 3
|
[] |
no_license
|
<?php
namespace MyStore2\Attributes;
class Street implements \MyStore2\Interfaces\AttributeInterface
{
public function getAttributeValue($params)
{
return $params['visit']->street;
}
public function getAttributeParams(): array
{
return [
"meta" => [
"href" => $_ENV['MYSTORE_API_URL']."customerorder/metadata/attributes/".$_ENV['ATTR_STREET'],
"type" => "attributemetadata",
"mediaType" => "application/json"
],
"id" => $_ENV['ATTR_STREET'],
"name" => "Улица",
"type" => "text"
];
}
public static function getAttribute(array $params): array
{
$street = new self;
$attribute = $street->getAttributeParams();
$attribute['value'] = $street->getAttributeValue($params);
return $attribute;
}
}
|
Java
|
GB18030
| 5,494
| 1.90625
| 2
|
[] |
no_license
|
package com.straw.friend.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.WindowFeature;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.AuthFailureError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.straw.friend.R;
import com.straw.friend.bean.User;
import com.straw.friend.bean.User_;
import com.straw.friend.tools.ConntentResource;
import com.straw.friend.tools.PhoneTools;
import com.straw.friend.tools.SingletonRequestQueue;
import com.straw.friend.tools.SystemBarTintManager;
@WindowFeature({ Window.FEATURE_NO_TITLE, Window.FEATURE_INDETERMINATE_PROGRESS })
@EActivity(R.layout.register)
public class RegisterActivity extends BaseActivity {
SystemBarTintManager tintManager;
@ViewById
EditText name;
String miem;
@ViewById
ImageView imageView;
@AfterViews
void initView() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// ״̬ ҪڴSystemBarTintManager ֮ǰá
super.setTranslucentStatus(true);
}
miem = PhoneTools.getuniqueId(getApplicationContext());
tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.actionbar_4);
tintManager.setStatusBarDarkMode(false, this);
isRegister(miem);
}
public void commit(View v) {
String nameString = name.getText().toString();
// ύ
commitData(nameString, miem);
}
private void isRegister(final String miem) {
StringRequest request = new StringRequest(Method.POST,
ConntentResource.FINDUSERBYID, new Listener<String>() {
public void onResponse(String arg0) {
parseData(arg0);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// POST
HashMap<String, String> map = new HashMap<String, String>();
map.put("deviceId", miem);
return map;
}
};
SingletonRequestQueue.getRequestQueue(getApplicationContext()).add(
request);
}
private void parseData(String arg0) {
if (arg0 != null) {
User_ user = new Gson().fromJson(arg0, User_.class);
if (user != null) {
name.setText(user.getName());
}
}
}
private void commitData(final String nameString, final String miem) {
StringRequest request = new StringRequest(Method.POST,
ConntentResource.USER_ADD, new Listener<String>() {
public void onResponse(String arg0) {
finish();
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// POST
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", nameString);
map.put("deviceid", miem);
return map;
}
};
SingletonRequestQueue.getRequestQueue(getApplicationContext()).add(
request);
}
public void addImage(View v) {
StringRequest request = new StringRequest(Method.POST,
ConntentResource.USER_IMAGE_ADD, new Listener<String>() {
public void onResponse(String arg0) {
//finish();
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// POST
HashMap<String, String> map = new HashMap<String, String>();
map.put("deviceid", miem);
return map;
}
};
SingletonRequestQueue.getRequestQueue(getApplicationContext()).add(
request);
}
public void selectImage(View v) {
// Intent intent = new Intent(MediaStore.ACTION_GET_CONTENT);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri));
// ImageView imageView = (ImageView) findViewById(R.id.iv01);
/* Bitmap趨ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
|
Markdown
|
UTF-8
| 1,884
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: NEATOs
subtitle: A robot programmed to drive along a parametric curve, climb a mountain, and navigate its surroundings
image: /img/projects/qea/neato-square.jpg
share-img: /img/projects/qea/neato-square.jpg
tags: [Quantitative-Engineering-Analysis]
---
In QEA, we programmed NEATOs (robot vacuums) to complete a series of tasks while also learning the math behind the code. This project was split into a series of three smaller projects, including:
+ "The Bridge of Death" - have the robot drive along a parametric curve (Project Partner: Khang Vu)
+ "Mount Doom" - have the robot reach the top of a "mountain" using gradient ascent (Project Partner: Mark Goldwater)
+ "The Gauntlet" - have the robot use a lidar to detect and avoid obstacles while searching for a round target with RANSAC (Project Partner: Sherrie Shen)
At the end of the project, we attempted the ultimate challenge - to complete all three in a row!
<style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class='embed-container'><iframe src='https://www.youtube.com/embed/4bkSMio2Isw' frameborder='0' allowfullscreen></iframe></div>
Deliverables:
+ [Source code](https://github.com/AmyPhung/QEA-Final-Robo-Module)
+ ["The Bridge of Death" Summary](https://drive.google.com/open?id=1i_323PIKnWDFjGWYD3hyWexNj4EzgfE8)
+ ["Mount Doom" Summary](https://drive.google.com/open?id=11zRsVgRyRmD1Wi9bcW69h6P102_lkpzP)
+ ["The Gauntlet" Summary](https://drive.google.com/open?id=1CQp8nRaTRIm3vYceTcVGgrhNSVqzlWmn)
+ [Demo](https://youtu.be/4bkSMio2Isw)
Tools used:
- **MATLAB** - used for determining wheel velocity commands based on parametric curve, imu readings, or lidar readings from NEATO
|
Ruby
|
UTF-8
| 332
| 4.5
| 4
|
[] |
no_license
|
# What will the following code print? Why?
def count_sheep
5.times do |sheep|
puts sheep
end
10
end
puts count_sheep
# prints "0 1 2 3 4 10" because the times method inside the "count_sheep" method prints the numbers
# 0 to 4. After that the last line executed is returned from the method, which is integer literal 10.
|
Java
|
UTF-8
| 35,051
| 2.96875
| 3
|
[] |
no_license
|
package interpreteur.as.Objets;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.lang.model.type.NullType;
import interpreteur.as.modules.ASModule;
import interpreteur.ast.buildingBlocs.expressions.Type;
import interpreteur.ast.buildingBlocs.programmes.Boucle;
import interpreteur.executeur.Coordonnee;
import interpreteur.executeur.Executeur;
import interpreteur.tokens.Token;
import interpreteur.as.erreurs.ASErreur.*;
/**
* Les explications vont être rajouté quand j'aurai la motivation de les écrire XD
*
* @author Mathis Laroche
*/
public interface ASObjet<T> {
T getValue();
boolean boolValue();
String obtenirNomType();
interface Nombre extends ASObjet<Number> {
@Override
default String obtenirNomType() {
return "Nombre";
}
}
interface Iterable extends ASObjet<Object> {
boolean contient(ASObjet<?> element);
Iterable sousSection(int debut, int fin);
ASObjet<?> get(int index);
int taille();
Iterator<ASObjet<?>> iter();
default int idxRelatif(List<?> valeur, int idx) {
if (Math.abs(idx) > valeur.size()) {
throw new ErreurIndex("l'index est trop grand");
}
idx = (idx < 0) ? valeur.size() + idx : idx;
return idx;
}
@Override
default String obtenirNomType() {
return "it\u00E9rable";
}
}
class VariableManager {
public static final String scopeParDefaut = "main";
public static Hashtable<String, Hashtable<String, Variable>> varDict = new Hashtable<>();
public static Hashtable<String, Variable> constDict = new Hashtable<>();
public static String currentScope = scopeParDefaut;
public static void ajouterVariable(Variable variable) {
String nom = FonctionManager.ajouterDansStructure(variable.nom);
Variable nouv = VariableManager.varDict.get(VariableManager.currentScope).put(nom, variable);
// if (nouv != null) {
// throw new ErreurAssignement("La variable '" + nom + "' a deja ete initialisee");
// }
}
public static void ajouterVariable(Variable variable, String scope) {
String nom = FonctionManager.ajouterDansStructure(variable.nom);
varDict.putIfAbsent(scope, new Hashtable<>());
Variable nouv = VariableManager.varDict.get(scope).put(nom, variable);
// if (nouv != null) {
// throw new ErreurAssignement("La variable '" + nom + "' a deja ete initialisee");
// }
}
public static void ajouterConstante(Constante constante) {
String nom = FonctionManager.ajouterDansStructure(constante.obtenirNom());
VariableManager.constDict.put(nom, constante);
VariableManager.varDict.get(VariableManager.currentScope).put(nom, constante);
}
public static void ajouterConstante(Constante constante, String scope) {
String nom = FonctionManager.ajouterDansStructure(constante.obtenirNom());
VariableManager.constDict.put(nom, constante);
varDict.putIfAbsent(scope, new Hashtable<>());
VariableManager.varDict.get(scope).put(nom, constante);
}
public static void initScope(String nomDuScope) {
varDict.putIfAbsent(nomDuScope, new Hashtable<>());
varDict.get(nomDuScope).putAll(constDict);
}
public static void initScope(String scope, String fromScope) {
varDict.putIfAbsent(scope, new Hashtable<>());
Hashtable<String, ASObjet.Variable> varFromScope = new Hashtable<>(varDict.get(fromScope));
varFromScope.replaceAll((name, var) -> new Variable(var.obtenirNom(), var.getValeur(), var.type).setReadOnly());
varDict.get(scope).putAll(varFromScope);
}
public static void changerScope(String nomDuScope) {
VariableManager.currentScope = Objects.requireNonNullElse(nomDuScope, scopeParDefaut);
}
public static String getCurrentScope() {
return currentScope;
}
public static Variable obtenirVariable(String nom) {
return VariableManager.varDict.get(VariableManager.currentScope).get(nom);
}
public static Variable obtenirVariable(String nom, String nomScope) {
varDict.putIfAbsent(nomScope, new Hashtable<>());
return VariableManager.varDict.get(nomScope).get(nom);
}
public static boolean estConstante(Variable var) {
return constDict.containsValue(var);
}
public static boolean estConstante(String nom) {
return constDict.keySet().stream().anyMatch(varName -> varName.equals(nom));
}
public static boolean laVariableExiste(String nom) {
return VariableManager.varDict.get(VariableManager.currentScope).containsKey(nom);
}
public static boolean nouvelleValeurValide(String nom, ASObjet<?> nouvelleValeur) {
Variable var = VariableManager.varDict.get(VariableManager.currentScope).get(nom);
if (var.getType().noMatch(nouvelleValeur.obtenirNomType())) {
throw new ErreurAssignement("La variable '" +
nom +
"' est de type *" +
var.obtenirNomType() +
"*. Elle ne peut pas prendre une valeur de type *" +
nouvelleValeur.obtenirNomType() +
"*.");
}
return true;
}
public static void retirerVariable(String nom) {
VariableManager.varDict.get(VariableManager.currentScope).remove(nom);
}
public static void clearCurrentScope() {
for (String varNom : VariableManager.varDict.get(VariableManager.currentScope).keySet()) {
if (!(estConstante(varNom)) && !varDict.get(currentScope).get(varNom).isReadOnly())
VariableManager.varDict.get(VariableManager.currentScope).get(varNom).valeur = null;
}
}
public static void reset() {
VariableManager.varDict = new Hashtable<>();
VariableManager.constDict = new Hashtable<>();
VariableManager.currentScope = VariableManager.scopeParDefaut;
VariableManager.varDict.putIfAbsent(scopeParDefaut, new Hashtable<>());
}
public static Hashtable<String, Hashtable<String, Variable>> getVarDict() {
return varDict;
}
public static Hashtable<String, Variable> getConstDict() {
return constDict;
}
}
class Variable implements ASObjet<Object> {
private final String nom;
private final Type type;
private ASObjet<?> valeur;
private boolean readOnly = false;
private Function<ASObjet<?>, ASObjet<?>> getter = null;
private Function<ASObjet<?>, ASObjet<?>> setter = null;
public Variable(String nom, ASObjet<?> valeur, Type type) {
this.type = type;
this.nom = nom;
this.valeur = valeur instanceof Variable ? ((Variable) valeur).getValeurApresGetter() : valeur;
}
public static void creerOuChangerValeur(String nom, ASObjet<?> valeur, Type type) {
Variable var = VariableManager.obtenirVariable(nom);
if (var != null) {
var.changerValeur(valeur);
} else {
VariableManager.ajouterVariable(new Variable(nom, valeur, type));
}
}
public void changerValeur(ASObjet<?> valeur) {
if (VariableManager.nouvelleValeurValide(this.nom, valeur)) {
if (this.setter != null) {
this.valeur = this.setter.apply(valeur);
} else {
this.valeur = valeur;
}
VariableManager.varDict.get(VariableManager.currentScope).put(nom, this);
}
}
public String obtenirNom() {
return this.nom;
}
public Type getType() {
return type;
}
public boolean pasInitialisee() {
return this.valeur == null;
}
public Variable setGetter(Function<ASObjet<?>, ASObjet<?>> getter) {
this.getter = getter;
return this;
}
public Variable setSetter(Function<ASObjet<?>, ASObjet<?>> setter) {
this.setter = setter;
return this;
}
public Variable setReadOnly() {
this.setter = (valeur) -> {
throw new ErreurAssignement("Cette variable est en lecture seule: elle ne peut pas \u00EAtre modifi\u00E9");
};
this.readOnly = true;
return this;
}
public boolean isReadOnly() {
return readOnly;
}
@Override
public String toString() {
return "Variable{" +
"nom='" + nom + '\'' +
", type='" + type + '\'' +
", valeur=" + valeur +
", getter=" + getter +
", setter=" + setter +
'}';
}
/* différentes manières de get la valeur stockée dans la variable */
public ASObjet<?> getValeur() {
return this.valeur;
}
public ASObjet<?> getValeurApresGetter() {
if (this.valeur == null) {
throw new ErreurAssignement("la variable " + this.nom + " est initialis\u00E9e, mais pas d\u00E9finie");
}
if (this.getter != null) {
return this.getter.apply(this.valeur);
}
return this.valeur;
}
@Override
public Object getValue() {
if (this.valeur == null) {
throw new ErreurAssignement("la variable " + this.nom + " est initialis\u00E9e, mais pas d\u00E9finie");
}
if (this.getter != null) {
return this.getter.apply(this.valeur).getValue();
}
return this.valeur.getValue();
}
@Override
public boolean boolValue() {
return this.valeur.boolValue();
}
@Override
public String obtenirNomType() {
return this.type.getNom();
}
}
class Constante extends Variable {
public Constante(String nom, ASObjet<?> valeur) {
super(nom, valeur, new Type("tout"));
}
@Override
public Variable setSetter(Function<ASObjet<?>, ASObjet<?>> setter) {
throw new ErreurAssignement("Impossible d'attribuer un setter \u00E0 une constante");
}
@Override
public Variable setGetter(Function<ASObjet<?>, ASObjet<?>> getter) {
throw new ErreurAssignement("Impossible d'attribuer un getter \u00E0 une constante");
}
@Override
public void changerValeur(ASObjet<?> valeur) {
if (this.getValeur() != null)
throw new ErreurAssignement("Il est impossible de changer la valeur d'une constante");
super.changerValeur(valeur);
}
}
class FonctionManager {
private static String structure = "";
// met la fonction dans le dictionnaire de fonction et cree enregistre la fonction dans une Variable
// pour que le code puisse la retrouver plus tard
public static void ajouterFonction(Fonction fonction) {
VariableManager.ajouterConstante(new Constante(fonction.getNom(), fonction));
//fonction.nom = ajouterDansStructure(fonction.getNom());
}
public static String obtenirStructure() {
return structure;
}
public static String ajouterDansStructure(String element) {
return (structure.isBlank() ? "" : structure + ".") + element;
}
public static void ajouterStructure(String nomStruct) {
structure += (structure.isBlank() ? "" : ".") + nomStruct;
}
public static void retirerStructure() {
structure = structure.contains(".") ? structure.substring(0, structure.lastIndexOf(".")) : "";
}
public static void reset() {
FonctionManager.structure = "";
for (Fonction fonction : ASModule.getModuleBuiltins().getFonctions()) ajouterFonction(fonction);
for (Variable variable : ASModule.getModuleBuiltins().getVariables()) {
if (variable instanceof Constante) VariableManager.ajouterConstante((Constante) variable);
else VariableManager.ajouterVariable(variable);
}
}
}
class Fonction implements ASObjet<Object> {
private final Type typeRetour;
private final Parametre[] parametres; //String[] de forme {nomDuParam�tre, typeDuParam�tre (ou null s'il n'en poss�de pas)}
private final String nom;
private Hashtable<String, ASObjet<?>> parametres_appel = new Hashtable<>(); // Object[][] de forme {{nom_param, valeur}, {nom_param2, valeur2}}
private Coordonnee coordReprise = null;
private String scopeName;
/**
* @param nom <li>
* Nom de la fonction
* </li>
* @param typeRetour <li>
* Nom du type de retour de la fonction (ex: <i>entier</i>, <i>texte</i>, <i>liste</i>, ect.)
* </li>
* <li>
* le type du retour peut avoir plusieurs types
* -> separer chaque type par un <b>|</b> (les espaces sont ignores)
* <br> (ex: <i>texte | liste</i>, <i>entier | decimal</i>)
* </li>
* <li>
* Mettre <b>null</b> si le type du retour n'a pas de type forcee
* </li>
*/
public Fonction(String nom, Type typeRetour) {
this.nom = nom;
this.scopeName = "fonc_";
this.typeRetour = typeRetour;
this.parametres = new Parametre[0];
}
/**
* @param nom <li>
* Nom de la fonction
* </li>
* @param parametres
* @param typeRetour <li>
* Nom du type de retour de la fonction (ex: <i>entier</i>, <i>texte</i>, <i>liste</i>, ect.)
* </li>
* <li>
* le type du retour peut avoir plusieurs types
* -> separer chaque type par un <b>|</b> (les espaces sont ignores)
* <br> (ex: <i>texte | liste</i>, <i>entier | decimal</i>)
* </li>
* <li>
* Mettre <b>null</b> si le type du retour n'a pas de type forcee
* </li>
*/
public Fonction(String nom, Parametre[] parametres, Type typeRetour) {
this.nom = nom;
this.scopeName = "fonc_";
this.parametres = parametres;
this.typeRetour = typeRetour;
}
public String getNom() {
return nom;
}
public Type getTypeRetour() {
return this.typeRetour;
}
public Parametre[] getParams() {
return this.parametres;
}
public Hashtable<String, ASObjet<?>> getParamsValeursDict() {
return this.parametres_appel;
}
public ASObjet<?> getValeurParam(String nomParametre) {
return this.parametres_appel.get(nomParametre);
}
/**
* @return true -> si les parametres sont initialisees <br> false -> s'il n'y a pas de parametres
* @throws Error une erreur si un des tests n'est pas passe
*/
public boolean testParams(ArrayList<?> paramsValeurs) {
if (this.parametres.length == 0 && paramsValeurs.size() == 0) return false;
int nonDefaultParams = (int) Arrays.stream(parametres).filter(param -> param.getValeurParDefaut() == null).count();
if (paramsValeurs.size() < nonDefaultParams || paramsValeurs.size() > this.parametres.length) {
if (nonDefaultParams == this.parametres.length) {
throw new ErreurAppelFonction(this.nom, "Le nombre de param\u00E8tres donn\u00E9s est '" + paramsValeurs.size() +
"' alors que la fonction en prend '" + this.parametres.length + "'");
} else {
throw new ErreurAppelFonction(this.nom, "Le nombre de param\u00E8tres donn\u00E9s est '" + paramsValeurs.size() +
"' alors que la fonction en prend entre '" + nonDefaultParams + "' et '" + this.parametres.length + "'");
}
}
for (int i = 0; i < paramsValeurs.size(); i++) {
Parametre parametre = this.parametres[i];
if (parametre.getType().noMatch(((ASObjet<?>) paramsValeurs.get(i)).obtenirNomType())) {
throw new ErreurType("Le param\u00E8tres '" + parametre.getNom() + "' est de type '" + parametre.getType().nom() +
"', mais l'argument pass\u00E9 est de type '" + ((ASObjet<?>) paramsValeurs.get(i)).obtenirNomType() + "'.");
}
}
return true;
/*
* grandement am�liorer les tests ici
* test � ajouter:
* 1. tous les param = valeur sont apr�s les params sans val_defaut
*
*/
}
// public void afficherParams() {
// System.out.println("Fonction: " + this.nom);
// for (Object[] param: this.parametres) {
// String message = "Param�tre " + param[0] + ": {";
// for (String m : param) {
// message += ((m == null || m.equals("null")) ? "tout" : m) + ", ";
// }
// System.out.println(message.substring(0, message.length()-2) + "}");
// };
// }
public ASObjet<?> setParamPuisExecute(ArrayList<ASObjet<?>> paramsValeurs) {
this.parametres_appel = new Hashtable<>();
if (testParams(paramsValeurs)) {
/*
* Défini la valeur de chaque argument passé explicitement par nom dans l'appel de la fonction
* ex: foo(param1=vrai)
*/
for (ASObjet<?> param : paramsValeurs) {
if (param instanceof Parametre) {
if (Arrays.stream(parametres).noneMatch(p -> p.getNom().equals(((Parametre) param).getNom()))) {
throw new ErreurAppelFonction("l'argument: " + ((Parametre) param).getNom() + " pass\u00E9 en param\u00E8tre" +
" ne correspond \u00E0 aucun param\u00E8tre d\u00E9fini dans la fonction '" + this.nom + "'");
}
this.parametres_appel.put(((Parametre) param).getNom(), ((Parametre) param).getValeurParDefaut());
}
}
for (int i = 0; i < this.parametres.length; i++) {
Parametre param = this.parametres[i];
if (i < paramsValeurs.size()) {
this.parametres_appel.putIfAbsent(param.getNom(), paramsValeurs.get(i));
} else {
if (param.getValeurParDefaut() == null) {
throw new ErreurAppelFonction(this.nom, "l'argument: " + param.getNom() + " n'a pas reçu de valeur" +
"et ne poss\u00E8de aucune valeur par d\u00E9faut");
}
this.parametres_appel.putIfAbsent(param.getNom(), param.getValeurParDefaut());
}
}
for (Parametre param : this.parametres) {
this.parametres_appel.computeIfAbsent(param.getNom(), (val) -> {
if (param.getValeurParDefaut() == null) {
throw new ErreurAppelFonction(this.nom, "l'argument: " + param.getNom() + " n'a pas reçu de valeur" +
"et ne poss\u00E8de aucune valeur par d\u00E9faut");
}
return param.getValeurParDefaut();
});
}
}
return this.executer();
}
public ASObjet<?> executer() {
Object valeur;
ASObjet<?> asValeur;
String ancienScope = VariableManager.currentScope;
VariableManager.changerScope(this.scopeName + this.nom);
VariableManager.initScope(this.scopeName + this.nom, ancienScope);
for (String param : this.parametres_appel.keySet()) {
VariableManager.ajouterVariable(new Variable(param, this.parametres_appel.get(param), new Type("tout")));
}
Coordonnee ancienneCoord = Executeur.obtenirCoordRunTime().copy();
valeur = Executeur.executerScope(VariableManager.currentScope, null, coordReprise == null ? null : coordReprise.getCoordAsString());
if (valeur instanceof String) {
//System.out.println("valeur: " + valeur);
coordReprise = Executeur.obtenirCoordRunTime().copy();
Executeur.setCoordRunTime(ancienneCoord.getCoordAsString());
VariableManager.changerScope(ancienScope);
throw new StopSendData((String) valeur);
} else {
asValeur = (ASObjet<?>) valeur;
}
coordReprise = null;
Boucle.sortirScope(VariableManager.getCurrentScope());
Executeur.setCoordRunTime(ancienneCoord.getCoordAsString());
VariableManager.clearCurrentScope();
VariableManager.changerScope(ancienScope);
//System.out.println(this.typeRetour);
//System.out.println(valeur);
if (asValeur == null || this.typeRetour.noMatch(asValeur.obtenirNomType())) {
throw new ErreurType("Le type retourner ' " + (asValeur == null ? "vide" : asValeur.obtenirNomType()) + " ' ne correspond pas "
+ "au type de retour pr\u00E9cis\u00E9 dans la d\u00E9claration de la fonction ' " + this.typeRetour.nom() + " '.");
}
return asValeur;
}
public void setScopeName(String scopeName) {
this.scopeName = scopeName;
}
@Override
public String toString() {
return this.nom + "(" +
String.join(", ", Arrays.stream(this.parametres).map(p -> p.getNom() + ": " + p.obtenirNomType())
.toArray(String[]::new)) +
") " +
"\u2192 " + this.typeRetour.nom();
}
@Override
public Object getValue() {
return this;
}
@Override
public boolean boolValue() {
return true;
}
@Override
public String obtenirNomType() {
return "fonctionType";
}
/**
* Classe responsable de definir les proprietes des parametres des fonctions
*/
public static class Parametre implements ASObjet<Object> {
private final String nom;
private final Type type;
private final ASObjet<?> valeurParDefaut;
/**
* @param type <li>
* Nom du type du parametre (ex: <i>entier</i>, <i>texte</i>, <i>liste</i>, ect.)
* </li>
* <li>
* le parametre peut avoir plusieurs types
* -> separer chaque type par un <b>|</b> (les espaces sont ignores)
* <br> (ex: <i>texte | liste</i>, <i>entier | decimal</i>)
* </li>
* <li>
* Mettre <b>null</b> si le parametre n'a pas de type forcee
* </li>
* @param nom <li>
* Nom du parametre
* </li>
* @param valeurParDefaut <li>
* Valeur de type ASObjet qui sera assigne au parametre s'il ne recoit aucune valeur lors de l'appel de la fonction
* </li>
* <li>
* Mettre <b>null</b> pour rendre ce parametre obligatoire lors de l'appel de la fonction
* </li>
*/
public Parametre(Type type, String nom, ASObjet<?> valeurParDefaut) {
this.nom = nom;
this.type = type == null ? new Type("tout"): type;
this.valeurParDefaut = valeurParDefaut;
}
public String getNom() {
return nom;
}
public Type getType() {
return type;
}
public ASObjet<?> getValeurParDefaut() {
return valeurParDefaut;
}
@Override
public Object getValue() {
return null;
}
@Override
public boolean boolValue() {
return false;
}
@Override
public String obtenirNomType() {
return this.type.nom();
}
@Override
public String toString() {
return "Parametre{" +
"nom='" + nom + '\'' +
", type=" + type +
", valeurParDefaut=" + valeurParDefaut +
'}';
}
}
}
class Entier implements Nombre {
private final int valeur;
public Entier(Token valeur) {
try {
this.valeur = Integer.parseInt(valeur.obtenirValeur());
} catch (NumberFormatException e) {
throw new ErreurEntierInvalide("Les nombres entiers doivent avoir une valeur entre "
+ Integer.MIN_VALUE + " et " + Integer.MAX_VALUE);
}
}
public Entier(Number valeur) {
try {
this.valeur = valeur.intValue();
} catch (NumberFormatException e) {
throw new ErreurEntierInvalide("Les nombres entiers doivent avoir une valeur entre "
+ Integer.MIN_VALUE + " et " + Integer.MAX_VALUE);
}
}
@Override
public String toString() {
return this.getValue().toString();
}
@Override
public Integer getValue() {
return valeur;
}
@Override
public boolean boolValue() {
return this.valeur != 0;
}
@Override
public String obtenirNomType() {
return "entier";
}
}
class Decimal implements Nombre {
private final double valeur;
public Decimal(Token valeur) {
String val = valeur.obtenirValeur();
if (val.startsWith(".")) val = "0" + val;
else if (val.endsWith(".")) val += "0";
this.valeur = Double.parseDouble(val);
}
public Decimal(Number valeur) {
this.valeur = valeur.doubleValue();
}
@Override
public String toString() {
return this.getValue().toString();
}
@Override
public Double getValue() {
return valeur;
}
@Override
public boolean boolValue() {
return this.valeur != 0;
}
@Override
public String obtenirNomType() {
return "decimal";
}
}
class Booleen implements ASObjet<Boolean> {
private final boolean valeur;
public Booleen(Token valeur) {
this.valeur = valeur.obtenirValeur().equals("vrai");
}
public Booleen(ASObjet<?> valeur) {
this.valeur = Boolean.parseBoolean(valeur.getValue().toString());
}
public Booleen(Boolean valeur) {
this.valeur = valeur;
}
@Override
public String toString() {
return valeur ? "vrai" : "faux";
}
@Override
public Boolean getValue() {
return valeur;
}
@Override
public boolean boolValue() {
return this.getValue();
}
@Override
public String obtenirNomType() {
return "booleen";
}
}
class Nul implements ASObjet<NullType> {
public Nul() {
}
@Override
public String toString() {
return "nul";
}
@Override
public NullType getValue() {
return null;
}
@Override
public boolean boolValue() {
return false;
}
@Override
public String obtenirNomType() {
return "nulType";
}
}
class Texte implements Iterable {
private final String valeur;
public Texte(Token valeur) {
this.valeur = valeur.obtenirValeur().substring(1, valeur.obtenirValeur().length() - 1);
}
public Texte(Object valeur) {
this.valeur = String.valueOf(valeur);
}
public Texte[] arrayDeLettres() {
Texte[] array = new Texte[this.getValue().length()];
int i = 0;
for (char lettre : this.getValue().toCharArray()) {
array[i] = new Texte(lettre);
i++;
}
return array;
}
@Override
public String toString() {
return this.getValue();
}
@Override
public String getValue() {
return valeur;
}
@Override
public boolean boolValue() {
return !this.valeur.isEmpty();
}
@Override
public boolean contient(ASObjet<?> element) {
if (element.getValue() instanceof String) {
return this.valeur.contains((String) element.getValue());
} else {
return false;
}
}
@Override
public Iterable sousSection(int debut, int fin) {
return new Texte(this.valeur.substring(debut, idxRelatif(Arrays.asList(this.arrayDeLettres()), fin)));
}
@Override
public ASObjet<?> get(int index) {
return new Texte(this.valeur.charAt(idxRelatif(Arrays.asList(this.arrayDeLettres()), index)));
}
@Override
public int taille() {
return this.valeur.length();
}
@Override
public Iterator<ASObjet<?>> iter() {
return Arrays.asList((ASObjet<?>[]) this.arrayDeLettres()).iterator();
}
@Override
public String obtenirNomType() {
return "texte";
}
}
class Liste implements Iterable {
private ArrayList<ASObjet<?>> valeur = new ArrayList<>();
public Liste() {
}
public Liste(ASObjet<?>[] valeurs) {
this.valeur = new ArrayList<>(Arrays.asList(valeurs));
}
public void ajouterElement(ASObjet<?> element) {
this.valeur.add(element);
}
public Liste ajouterTout(Liste elements) {
this.valeur.addAll(elements.getValue());
return this;
}
public void retirerElement(int idx) {
this.valeur.remove(idxRelatif(this.valeur, idx));
}
public Liste remplacer(int idx, ASObjet<?> valeur) {
this.valeur.set(idxRelatif(this.valeur, idx), valeur);
return this;
}
public Liste remplacer(ASObjet<?> valeur, ASObjet<?> remplacement) {
this.valeur.replaceAll(v -> v.equals(valeur) ? remplacement : v);
return this;
}
public Liste remplacerRange(int debut, int fin, Liste remplacement) {
debut = idxRelatif(valeur, debut);
fin = idxRelatif(valeur, fin);
this.valeur = this.sousSection(0, debut).ajouterTout(remplacement).ajouterTout(this.sousSection(fin, this.taille())).getValue();
return this;
}
public ArrayList<?> map(Function<ASObjet<?>, ?> mappingFunction) {
return this.valeur.stream().map(mappingFunction).collect(Collectors.toCollection(ArrayList::new));
}
@Override
public ASObjet<?> get(int idx) {
return this.valeur.get(idxRelatif(this.valeur, idx));
}
@Override
public int taille() {
return this.valeur.size();
}
@Override
public Iterator<ASObjet<?>> iter() {
return this.valeur.iterator();
}
@Override
public boolean contient(ASObjet<?> element) {
return this.valeur.contains(element);
}
@Override
public SousListe sousSection(int debut, int fin) {
return new SousListe(this, debut, idxRelatif(this.valeur, fin));
}
@Override
public String toString() {
return "{" +
String.join(", ", this.valeur
.stream()
.map(e -> e instanceof Texte ? '"' + e.toString() + '"' : e.toString())
.toArray(String[]::new))
+ "}";
}
@Override
public ArrayList<ASObjet<?>> getValue() {
return this.valeur;
}
@Override
public boolean boolValue() {
return !this.valeur.isEmpty();
}
@Override
public String obtenirNomType() {
return "liste";
}
public static class SousListe extends Liste {
private final Liste parent;
SousListe(Liste parent, int debut, int fin) {
super(parent.valeur.subList(debut, fin).toArray(ASObjet<?>[]::new));
this.parent = parent;
}
public Liste getParent() {
return parent;
}
}
}
}
|
C#
|
UTF-8
| 1,951
| 2.84375
| 3
|
[] |
no_license
|
using BLL.Validation;
using System;
using System.Collections.Generic;
using System.Text;
namespace BLL
{
public static class Maker
{
//Check validation of package. If correct, processing them and display a response.
//Else only get non-acceptance response
public static string IsValidProcessingData(string inputData, out bool statusAboutSuccessProcessing)
{
statusAboutSuccessProcessing = false;
if (!StartIndexPackageValidator.IsExistStartSymbol(inputData.ToCharArray()))
return Messager.GetNonAcceptanceMessage();
int indexStartPackage = PackageIdentifier.GetStartIndexPackage(inputData);
if (!PackagePayloadVerifier.IsValidPackage(inputData, indexStartPackage))
return Messager.GetNonAcceptanceMessage();
string package = PackageIdentifier.GetDataPackage(inputData, indexStartPackage);
char command = PackagePayloadVerifier.GetCommand(package);
List<int> indexCharacterColon = ParametersExtractor.GetIndexCharacterColon(package);
if (!ParameterValidator.IsValidIndexCharacterColon(indexCharacterColon))
return Messager.GetNonAcceptanceMessage();
statusAboutSuccessProcessing = GetCommandResult(command, package, indexCharacterColon, out string result);
return result;
}
public static string GetResponseAboutSuccessProcessing(bool status)
=> status.Equals(true) ? Messager.GetAcceptanceMessage() : Messager.GetNonAcceptanceMessage();
// processing command
private static bool GetCommandResult(char command, string package, List<int> indexCharacterColon, out string result)
{
string parameters = ParametersExtractor.GetDataPackage(package, indexCharacterColon);
return PackagePayloadVerifier.DoCommand(command, parameters, out result);
}
}
}
|
C
|
UHC
| 3,025
| 3.703125
| 4
|
[] |
no_license
|
//Hashing
//
//ڿ ε Ư ڿ ã ó ؾߵȴ.
// ִ ʴ.
//, Hashing ѹ ã ִ.
//迭 ƿ ؼ 迭 ִ´.
//ڰ ϱ ̴.
//ڼ ش ε ִ.
//ĺ ڸ οؼ ε ִ.
//߸ 2 .
//chaining.
//ߵǸ ĭ 1:1 Ī Ұϴ.
// ĭ ִµ
//װ óϱ =>SLL.
//ó ׳ ְ ġ Ǹ SLL.
//Ž chain ã´.
//hashing hashing function ־ Ѵ.
//chaining SLL .
//bucket(index ǹ)
//collision Ѱ 2 . -> chaining.
//lineaer probing collision , ĭ äִ´.
//, collision->chainig or linear probing.
//loading density ä /ü .
//loading density collision .
// collision Ȯ ȿ ̿ ̴.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int stno;
unsigned short age;
struct student *next;
};
typedef struct student STUDENT;
#define HASHTABLE_SZ 30
STUDENT *hashTable[HASHTABLE_SZ];
int hashFunction(char *str) {
//ڰ Ѵ.
int sum = 0;
int len = strlen(str);
int i;
for (i = 0;i < len;i++) {
sum += str[i];
}
//%HASHTABLE_SZ
return (sum%HASHTABLE_SZ);
}
void addToHashTable(char *name, int stno, unsigned short age) {
STUDENT *cur = (STUDENT*)malloc(sizeof(STUDENT));
int idx;
strcpy_s(cur->name, sizeof(name)*3 , name);
cur->stno = stno;
cur->age = age;
cur->next = 0;
idx = hashFunction(name); // ε
if (hashTable[idx] == 0) {
hashTable[idx] = cur;
return;
}
else { //collision
STUDENT *temp = hashTable[idx];
while (temp->next != 0) {
temp = temp->next;
}
temp->next = cur;
return;
}
}
void searchInTheHash(char *name) {
STUDENT *cur;
//ã
int idx;
idx = hashFunction(name);
cur = hashTable[idx];
if (cur == 0) {
return;
}
else {
while (strcmp(cur->name, name) != 0) {
cur = cur->next;
if (cur == 0) {
return;
}
}
}
//
printf("%s %d %d\n", cur->name, cur->stno, cur->age);
}
void main(void) {
addToHashTable((char*)"ö", 200, 19);
addToHashTable((char*)"ö", 201, 20);
addToHashTable((char*)"ö", 202, 19);
addToHashTable((char*)"ö", 203, 18);
addToHashTable((char*)"ö", 204, 19);
searchInTheHash((char*)"ö");
searchInTheHash((char*)"ö");
}
|
TypeScript
|
UTF-8
| 1,814
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
import { Edge, WeightedEdge } from "../src/lib/Graph";
import { displayMatrix, toMatrix, transposeMatrix, fromJSON } from "../src/lib/Graph-Utils";
import { dfsAnalysis } from "../src/lib/Graph-Search";
import { DirectedEdgeAnalizer, ToposortAnalizer, DirectedComponentAnalizer } from "../src/lib/Graph-Directed-Analizers";
//independent run
// node --require ts-node/register --trace-uncaught test/topo.ts
//or
//in this case it's itself in Run Task as "Graph create"
//remember to change the name in launch.json
const g = fromJSON({
name: "Topological Sort of a DiGraph",
directed: true,
weighted: false,
nodes: 13,
edges: [
{ from: 0, to: 5 },
{ from: 0, to: 6 },
{ from: 0, to: 2 },
{ from: 0, to: 3 },
{ from: 0, to: 1 },
{ from: 2, to: 3 },
{ from: 3, to: 5 },
{ from: 3, to: 4 },
{ from: 4, to: 9 },
{ from: 6, to: 9 },
{ from: 6, to: 4 },
{ from: 7, to: 6 },
{ from: 8, to: 7 },
{ from: 9, to: 11 },
{ from: 9, to: 10 },
{ from: 9, to: 12 },
{ from: 11, to: 12 },
]
});
console.log('name: ', g.name);
console.log('nodes: ', g.size);
console.log('g.directed: ', g.directed);
console.log('g.edgeCount: ', g.edgeCount());
console.log('Edges');
g.nodeList().forEach(n => {
console.log((g.nodeEdges(n.id) as Edge[]).map(e => {
return `(${e.v}>${e.w}${g.weighted ? ` @${(e as WeightedEdge).weight}` : ''})`
}).join(' '))
});
let
start = 0,
analizers = [
new DirectedEdgeAnalizer(true, true, true),
new ToposortAnalizer(),
new DirectedComponentAnalizer(),
];
console.log('Degree or Source');
console.log(g.degrees().join(" "));
console.log('InDegree or Sink');
console.log(g.indegrees().join(" "));
dfsAnalysis(g, start, analizers);
console.log('Matrix');
displayMatrix(toMatrix(g));
console.log('Transpose');
displayMatrix(transposeMatrix(g));
|
Java
|
UTF-8
| 1,250
| 2.28125
| 2
|
[] |
no_license
|
package com.company.springcrud.controller;
import com.company.springcrud.entity.Company;
import com.company.springcrud.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class CompanyController {
@Autowired
private CompanyService companyService;
@GetMapping("/companys")
public List<Company> findAllCompany() {
return companyService.getAllCompanys();
}
@GetMapping("/company/{id}")
public Company getCompanyByID(@PathVariable Long id) {
return companyService.getCompanyById(id);
}
@PostMapping("/addcompany")
public Company addCompany(@RequestBody Company company) {
return companyService.saveCompany(company);
}
@DeleteMapping("/company/{id}")
public String deleteCompany(@PathVariable long id) {
return companyService.deleteCompany(id);
}
@PutMapping("/updates/{id}")
public Company updateCompany(@PathVariable long id,@Validated @RequestBody Company company) {
return companyService.updateCompany(id,company);
}
}
|
Python
|
UTF-8
| 387
| 4.25
| 4
|
[] |
no_license
|
def getUserInput():
name_ = input("Name: ")
age_ = int(input("Age: "))
add_ = input("Address:")
return name_, age_, add_
def display(name_, age_, add_):
print(f"Hi, My name is {name_} I am {age_} years old and I live in {add_}.")
#steps
#1. ask my name, age and address
name, age, add = getUserInput()
#2. display my name, age and address
display(name, age, add)
|
Ruby
|
UTF-8
| 515
| 3.1875
| 3
|
[] |
no_license
|
#Final Project: Design Patterns Quiz App
# Date: 23-November-2017
# Authors:
# A01168958 Francisco Geada Rodríguez
# A01373179 María Fernanda Cruz González
#Class for each individual multiple question
class Question
#Class is initialized
attr_accessor :question, :answerA, :answerB, :answerC, :correct
#Initializing the class
def initialize q, a, b, c, corr
#Question text
@question=q
#Answer a
@answerA=a
#Answer b
@answerB=b
#Answer c
@answerC=c
#Correct answer
@correct=corr
end
end
|
C#
|
UTF-8
| 1,510
| 2.6875
| 3
|
[] |
no_license
|
using System;
using System.Data;
namespace SimpleDAL.UnitOfWork.Linq2Sql
{
public class LinqToSqlTransaction : ITransaction
{
#region fields
private bool _disposed;
private readonly IDbTransaction _internalTransaction;
#endregion
#region ctor
public LinqToSqlTransaction( IDbTransaction transaction )
{
if ( transaction == null ) throw new ArgumentNullException( "transaction" );
_internalTransaction = transaction;
}
#endregion
#region Implementation of IDisposable
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
private void Dispose( bool disposing )
{
if ( disposing )
{
if ( !_disposed )
{
_internalTransaction.Dispose();
_disposed = true;
}
}
}
#endregion
#region Implementation of ITransaction
public event EventHandler TransactionCommitted;
public event EventHandler TransactionRolledback;
public void Commit()
{
if ( _disposed ) throw new ObjectDisposedException( "LinqToSqlTransaction", "Cannot commit a disposed transaction." );
_internalTransaction.Commit();
if ( TransactionCommitted != null )
TransactionCommitted( this, EventArgs.Empty );
}
public void Rollback()
{
if ( _disposed ) throw new ObjectDisposedException( "LinqToSqlTransaction", "Cannot rollback a disposed transaction." );
_internalTransaction.Rollback();
if ( TransactionRolledback != null )
TransactionRolledback( this, EventArgs.Empty );
}
#endregion
}
}
|
Java
|
ISO-8859-2
| 555
| 3.46875
| 3
|
[] |
no_license
|
package stackx;
import java.util.Scanner;
public class Ex_002 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*Criar um programa que calcule a mdia de 2 notas e mostrar essa mdia na tela.*/
Scanner ler = new Scanner(System.in);
float not1, not2, media;
System.out.println("Digite a primeira nota: ");
not1 = ler.nextFloat();
System.out.println("Digite a primeira nota: ");
not2 = ler.nextFloat();
media = (not1 + not2) / 2;
System.out.println("A nota do aluno eh "+ media);
}
}
|
C++
|
UTF-8
| 1,601
| 3.03125
| 3
|
[] |
no_license
|
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#define PI 4.0*atan(1.0)
#define eps 1e-8
using namespace std;
struct point{double x,y;point(double x=0,double y=0):x(x),y(y){}};
typedef point vec;
vec operator - (vec a,vec b){return vec(a.x-b.x,a.y-b.y);}
vec operator + (vec a,vec b){return vec(a.x+b.x,a.y+b.y);}
vec operator * (vec a,double b){return vec(a.x*b,a.y*b);}
int dcmp(double a){if (fabs(a)<eps)return 0;return a<0?-1:1;}
double cross(vec a,vec b){return a.x*b.y-a.y*b.x;}
vec rotate(vec a,double b){return vec(a.x*cos(b)-a.y*sin(b),a.x*sin(b)+a.y*cos(b));}
double dot(vec a,vec b){return a.x*b.x+a.y*b.y;}
double length(vec a){return sqrt(dot(a,a));}
point llcross(point a,vec v,point b,vec w)
{
vec u=a-b;
return a+v*(cross(w,u)/cross(v,w));
}
int main()
{
freopen("1329.in","r",stdin);
freopen("1329.out","w",stdout);
point a,b,c;
while(scanf("%lf%lf%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y,&c.x,&c.y)==6)
{
point ab=vec((a.x+b.x)/2.0,(a.y+b.y)/2.0);
vec u=rotate(b-a,PI/2.0);
point bc=vec((b.x+c.x)/2.0,(b.y+c.y)/2.0);
vec v=rotate(c-b,PI/2.0);
point o=llcross(ab,u,bc,v);
double r=length(o-a);
char c1,c2;
if (o.x>0) c1='-';
else c1='+';
if (o.y>0) c2='-';
else c2='+';
char c3;
double z=o.x*o.x+o.y*o.y-r*r;
if (z>0) c3='+';
else c3='-';
printf("(x %c %.3lf)^2 + (y %c %.3lf)^2 = %.3lf^2\n",c1,fabs(o.x),c2,fabs(o.y),fabs(r));
printf("x^2 + y^2 %c %.3lfx %c %.3lfy %c %.3lf = 0\n",c1,2*fabs(o.x),c2,2*fabs(o.y),c3,fabs(z));
printf("\n");
}
return 0;
}
|
Markdown
|
UTF-8
| 4,275
| 2.609375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
## xView Baselines and Scoring
### Code
This repository contains the pre-trained xView baseline models (see our [blog post](https://medium.com/@dariusl/object-detection-baselines-in-overhead-imagery-with-diux-xview-c39b1852f24f)) as well as code for inference and scoring. Class ID to name mappings are in the 'xview_class_labels.txt' file
Inference and scoring code are under the 'inference/' and 'scoring/' folders, respectively. Inside 'inference/' we provide a python script 'create_detections.py' for exporting detections from a single xView TIF image, given a frozen model. There is also a script 'create_detections.sh' for exporting detections from multiple xView TIF images. Exported detections are in format
|X min|Y min|X max|Y max|Class ID|Confidence|
|---|---|---|---|---|---|
which is the proper format for submitting to the xView challenge portal. You can use the given pre-trained baseline models for the '-c' checkpoint parameter.
The 'scoring/' folder contains code for evaluating a set of predictions (exported from 'create_detections.py' or 'create_detections.sh') given a ground truth label geojson. The script 'score.py' calculates scores: total mean average precision (mAP), per-class mAP, mAP for small/med/large classes, mAP for rare/common classes, F1 score, mean precision, and mean recall. We use the PASCAL VOC method for computing mean average precision and calculate mean precision and mean recall using the formulas:
Precision = (True Positives) / (True Positives + False Positives)
Recall = (True Positives) / (True Positives + False Negatives)
averaged over all classes and files. Class splits are shown at the bottom of this README.
Pre-trained baseline models can be found in a zip file under the 'releases' tab. There are three models: vanilla, multires, and multires_aug which are described [here](https://medium.com/@dariusl/object-detection-baselines-in-overhead-imagery-with-diux-xview-c39b1852f24f). Inside the zip file are three folders and three pb files. The pb files are frozen models: they can be plugged into the detection scripts right away. Inside each respective folder are the tensorflow checkpoint files that can be used for fine-tuning.
### Class Splits
Small:
['Passenger Vehicle', 'Small car', 'Bus', 'Pickup Truck', 'Utility Truck', 'Truck', 'Cargo Truck', 'Truck Tractor', 'Trailer', 'Truck Tractor w/ Flatbed Trailer', 'Crane Truck', 'Motorboat', 'Dump truck', 'Tractor', 'Front loader/Bulldozer', 'Excavator', 'Cement mixer', 'Ground grader', 'Shipping container']
Medium:
['Fixed-wing aircraft', 'Small aircraft', 'Helicopter', 'Truck Tractor w/ Box Trailer', 'Truck Tractor w/ Liquid Tank', 'Railway vehicle', 'Passenger car', 'Cargo/container car', 'Flat car', 'Tank car', 'Locomotive', 'Sailboat', 'Tugboat', 'Fishing vessel', 'Yacht', 'Engineering vehicle', 'Reach stacker', 'Mobile crane', 'Haul truck', 'Hut/Tent', 'Shed', 'Building', 'Damaged/demolished building', 'Helipad', 'Storage Tank', 'Pylon', 'Tower']
Large:
['Passenger/cargo plane', 'Maritime vessel', 'Barge', 'Ferry', 'Container ship', 'Oil Tanker', 'Tower crane', 'Container crane', 'Straddle carrier', 'Aircraft Hangar', 'Facility', 'Construction site', 'Vehicle Lot', 'Shipping container lot']
---
Common:
['Passenger/cargo plane', 'Passenger Vehicle', 'Small car', 'Bus', 'Pickup Truck', 'Utility Truck', 'Truck', 'Cargo Truck', 'Truck Tractor w/ Box Trailer', 'Truck Tractor', 'Trailer', 'Truck Tractor w/ Flatbed Trailer', 'Passenger car', 'Cargo/container car', 'Motorboat', 'Fishing vessel', 'Dump truck', 'Front loader/Bulldozer', 'Excavator', 'Hut/Tent', 'Shed', 'Building', 'Damaged/demolished building', 'Facility', 'Construction site', 'Vehicle Lot', 'Storage Tank', 'Shipping container lot', 'Shipping container']
Rare:
['Fixed-wing aircraft', 'Small aircraft', 'Helicopter', 'Truck Tractor w/ Liquid Tank', 'Crane Truck', 'Railway vehicle', 'Flat car', 'Tank car', 'Locomotive', 'Maritime vessel', 'Sailboat', 'Tugboat', 'Barge', 'Ferry', 'Yacht', 'Container ship', 'Oil Tanker', 'Engineering vehicle', 'Tower crane', 'Container crane', 'Reach stacker', 'Straddle carrier', 'Mobile crane', 'Haul truck', 'Tractor', 'Cement mixer', 'Ground grader', 'Aircraft Hangar', 'Helipad', 'Pylon', 'Tower']
|
JavaScript
|
UTF-8
| 702
| 2.84375
| 3
|
[] |
no_license
|
class ParticleText extends Particle {
constructor(text, x, y, dx, dy, height, fill, stroke, fade) {
super();
this.text = text;
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.height = height;
this.fill = fill;
this.stroke = stroke;
this.alpha = 1;
this.fade = fade;
}
draw(ctx) {
ctx.globalAlpha = this.alpha;
ctx.font = "bold " + this.height + "px "+settings.font;
ctx.strokeStyle = this.stroke;
ctx.lineWidth = 2;
ctx.strokeText(this.text, this.x - (ctx.measureText(this.text).width / 2), this.y - this.height/2);
ctx.fillStyle = this.fill;
ctx.fillText(this.text, this.x - (ctx.measureText(this.text).width / 2), this.y - this.height/2);
}
}
|
Python
|
UTF-8
| 5,438
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example updates an existing sitelinks feed.
Specifically, it does the following:
* Adds FeedItemAttributes for line 1 and line 2 descriptions to the Feed
* Populates the new FeedItemAttributes on FeedItems in the Feed
* Replaces the Feed's existing FeedMapping with one that contains the new
set of FeedItemAttributes
The end result of this is that any campaign or ad group whose CampaignFeed
or AdGroupFeed points to the Feed's ID will now serve line 1 and line 2
descriptions in its sitelinks.
Tags: FeedItemService.mutate
Tags: FeedMappingService.mutate, FeedService.mutate
"""
__author__ = 'Joseph DiLallo'
from googleads import adwords
FEED_ID = 'FEED_ID'
FEED_ITEM_DESCRIPTIONS = {
'INSERT_FEED_ITEM_A_ID_HERE': [
'INSERT_FEED_ITEM_A_LINE1_DESC_HERE',
'INSERT_FEED_ITEM_A_LINE2_DESC_HERE'
],
'INSERT_FEED_ITEM_B_ID_HERE': [
'INSERT_FEED_ITEM_B_LINE1_DESC_HERE',
'INSERT_FEED_ITEM_B_LINE2_DESC_HERE'
]
}
# See the Placeholder reference page for a list of all the placeholder types
# and fields:
# https://developers.google.com/adwords/api/docs/appendix/placeholders
PLACEHOLDER_FIELD_LINE_1_TEXT = 3
PLACEHOLDER_FIELD_LINE_2_TEXT = 4
def main(client, feed_id, feed_item_descriptions):
feed_service = client.GetService('FeedService', 'v201309')
feed_item_service = client.GetService('FeedItemService', 'v201309')
feed_mapping_service = client.GetService('FeedMappingService', 'v201309')
feed_selector = {
'fields': ['Id', 'Attributes'],
'predicates': [
{'field': 'Id', 'operator': 'EQUALS', 'values': [feed_id]}
]
}
feed = feed_service.get(feed_selector)['entries'][0]
# Add new line1 and line2 feed attributes.
next_attribute_index = len(feed['attributes'])
feed['attributes'] = [
{'type': 'STRING', 'name': 'Line 1 Description'},
{'type': 'STRING', 'name': 'Line 2 Description'}
]
mutated_feed_result = feed_service.mutate([
{'operator': 'SET', 'operand': feed}
])
mutated_feed = mutated_feed_result['value'][0]
line_1_attribute = mutated_feed['attributes'][next_attribute_index]
line_2_attribute = mutated_feed['attributes'][next_attribute_index + 1]
# Update feed items.
feed_item_ids = feed_item_descriptions.keys()
item_selector = {
'fields': ['FeedId', 'FeedItemId', 'AttributeValues'],
'predicates': [
{'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed_id]},
{'field': 'FeedItemId', 'operator': 'IN', 'values': feed_item_ids}
]
}
feed_items = feed_item_service.get(item_selector)['entries']
item_operations = []
for feed_item in feed_items:
feed_item['attributeValues'] = [
{
'feedAttributeId': line_1_attribute['id'],
'stringValue': feed_item_descriptions[feed_item['feedItemId']][0]
},
{
'feedAttributeId': line_2_attribute['id'],
'stringValue': feed_item_descriptions[feed_item['feedItemId']][1]
}
]
item_operations.append({'operator': 'SET', 'operand': feed_item})
items_update_result = feed_item_service.mutate(item_operations)
print 'Updated %d items' % len(items_update_result['value'])
# Update feed mapping.
mapping_selector = {
'fields': [
'FeedId',
'FeedMappingId',
'PlaceholderType',
'AttributeFieldMappings'
],
'predicates': [
{'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed_id]}
]
}
feed_mapping_results = feed_mapping_service.get(mapping_selector)
feed_mapping = feed_mapping_results['entries'][0]
# Feed mappings are immutable, so we have to delete it and re-add
# it with modifications.
feed_mapping = feed_mapping_service.mutate([
{'operator': 'REMOVE', 'operand': feed_mapping}
])['value'][0]
feed_mapping['attributeFieldMappings'].push(
{
'feedAttributeId': line_1_attribute['id'],
'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT
},
{
'feedAttributeId': line_2_attribute['id'],
'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT
}
)
mapping_update_result = feed_mapping_service.mutate([
{'operator': 'ADD', 'operand': feed_mapping}
])
mutated_mapping = mapping_update_result['value'][0]
print ('Updated field mappings for feedId %d and feedMappingId %d to:' %
(mutated_mapping['feedId'], mutated_mapping['feedMappingId']))
for field_mapping in mutated_mapping['attributeFieldMappings']:
print ('\tfeedAttributeId %d --> fieldId %d' %
(field_mapping['feedAttributeId'], field_mapping['fieldId']))
if __name__ == '__main__':
# Initialize client object.
adwords_client = adwords.AdWordsClient.LoadFromStorage()
main(adwords_client, FEED_ID, FEED_ITEM_DESCRIPTIONS)
|
Markdown
|
UTF-8
| 72,701
| 2.796875
| 3
|
[] |
no_license
|
---
layout: default
Lastmod: 2020-02-15T15:56:52.325397+00:00
date: 2020-02-11T00:00:00.000Z
title: "粵 國 構 想"
author: "cansinlej"
tags: [粵國,粵獨]
---
(剛剛寫了一篇簡介廣東社會,裡面提及我對粵國的構想,為免在那個關於現實世界的貼大談未來,趕緊寫這一篇。
[https://pincong.rocks/article/14363](https://pincong.rocks/article/14363 "https://pincong.rocks/article/14363"))
我的政治觀點受香港、英國Westminster議會制、新加坡、以色列這些國家政治制度的啟發較大。
首先是我的廣東自治粵人治粵的基本原則
1. 自由、民主
2. 粵國內政,尤其是徵稅和財政,由粵國議會和政府全權處理。
3. 粵國擁有自己的軍隊。粵國男女全民服役。粵軍聽命於粵國議會。
4. 外國軍隊絕不可以入粵。粵國議會授權也不可以。來粵國演習也不可以。
5. 粵國自行處理外交事務。向外國派駐使節,為海外粵人提供領事服務……
6. 司法獨立
7. 粵國實施邊境管制,控制人員出入境。
只要滿足這幾條實現自治就可以,做支那底下一個廣東省,支那聯邦其中一個邦,獨立……都無所謂。
我_理想_中的粵國
0 支那各地和平分手,好聚好散。
1 粵國聯邦制,族群自治。
最粗的分法,大概是分成六個邦:廣州(首都,類似德國柏林邦)、深圳、廣府、潮汕、客家、海陸豐。
如果分得細一點,可能是:廣州、深圳、東莞惠州、海陸豐、潮汕、客家、粵北(韶關清遠)、粵西(肇慶雲浮)、雷州半島(湛江)、粵西南(茂名陽江)、四邑、佛山、中山、珠海。
具體分法取決於各地人喜歡和誰靠攏。
廣西可以加入。海南可以加入。贛南客家人地區可以加入。
所以我的假想國家名字就叫粵國,也可以叫嶺南。不必叫_南_粵。也不叫廣東,為了留下一點曖昧,方便別人加入。
不支持香港加入粵國。他們自己獨立,保持自己獨立地位更好。避免粵國干涉香港政治,造成兩地關係緊張。澳門就隨便吧。
2 國民、國籍法
主要按照居留、血統兩種途徑定義。
(通常居住的定義參考香港法例。)
下列人可以申請粵國國籍:
1. 在粵國獨立日,從出生起一直在粵國通常居住的年滿12周歲的人。
2. 粵獨日前,已在粵國通常居住累計20年以上,並在粵獨日前5年內有1年通常居住以上。
3. 願意效忠粵國,參加粵軍,服役滿5年的外國人。
4. 在粵獨日前出生,出生時父母一方為粵國國民,本人通曉粵國本土語言的申請人。(保證所有粵人後裔都可以申請,除了粵人和外族通婚而子女並未粵化的,所以血統這一條加入語言要求。)
5. 於粵獨日,父母皆已亡故,但假如父母仍然健在,其中一方可按前述條款獲得粵國國籍或由出生至亡故均在粵國通常居住或通常居住累計20年以上,而且申請人通曉粵國本土語言,那麼這個人也可以獲得粵國國籍。
6. 所有香港永久居民、澳門永久居民。
獨立之初,不承認雙重國籍。也就是效忠別國的,就不能獲得粵國國籍。如果獨立穩定下來了(三五十年後吧),可以改。
粵國本土語言指粵國疆域內任何一個鄉鎮的本土語言,比如廣州話潮州話客家話,廣東西北山區裡的瑤族苗族會講自己的語言也算。普通話就不算。
這樣設定呢,就讓所有保持了本族文化的粵人都獲得粵籍,也讓在粵國已經住了很久的「外省人」也可以獲得粵籍。盡量避免社會動盪種族衝突吧。
3 國家政府與地方自治
實行類似英國的議會制。一院制或兩院制無所謂,取決於獨立後各黨決定。我個人是傾向於一院制,像英國下議院、德國聯邦議會總管一切的玩法。議會至上parliamentary sovereignty。不立成文憲法。
各邦有自己的邦議會。各邦自治類似於美國/德國吧,比蘇格蘭和北愛的自治程度要更高。所有事務沒有規定屬於國家政府的都屬於邦決定。
國家政府負責處理軍事、情報、外交、國際貿易、關稅、跨邦的治安(FBI)。
邦以下只設一級政府,市。不要縣/鎮了。基本上現在縣規模的地區全部可以改成市。也就是說比如現在的佛山市,在廣府邦底下直接細分成佛山市、南海市、順德市、高明市諸如此類。市由市議會管理市政,這一級類似於英美的county。比香港區議會權力更大一些,像以前的市政局。
4 司法制度
實行普通法。剛獨立的時候全盤照抄香港成文法例。讓香港終審法院當粵國的終審法院。普通法制度習慣之後,再成立粵國最高法院,但也模仿香港現在的制度,請一些洋人/香港人來做非常任法官。
5 軍事
男女強制兵役。獨立初期不設替代役。獨立穩定之後可以和歐美看齊。
粵國軍隊聽命於國會。任何外國軍隊不得入粵。
支持全支那棄核。但是如果有任何一國不棄核,粵國必須擁核。
核武器和南海是兩大麻煩問題,另外開一個貼討論。
6 貨幣
獨立初期可能改用港元/美元吧。貨幣問題很麻煩,和軍事問題一樣會在另一個貼講。貨幣和財政要是處理不好,獨立政府很容易崩。
7 邊境與工作簽證問題
不設開放邊境,必須控制出入境。
在和平過渡的前提下,粵國向前支那其它地區提供簽證優惠。所有其它地區國籍的人50歲以前可以獲得一生一次為期一年的入境找工作簽證,沒有學歷/年齡/工種限制(無犯罪記錄那些常規當然要)。找到工作可以留下來一直做,連續工作納稅2年後可以享有居民福利(醫療、教育、房屋津貼之類),連續通常居留10年以上並學會其中一種粵國本土語言,可以申請入籍歸化。
8 語言政策
不設國家語言。
工作語言是各邦本土語言+普通話+英語。國會開會可以用任何一種發言,類似香港立法會。(粵國國會議長會很高難度,因為他/她應該要盡量同時通曉粵語潮州話客家話三種語言。)
總的來說,是希望(1)按著現有疆域(2)全體居民 順利過渡到粵國,盡量減少大幅政策變動,尤其是避免族群衝突。現實是,**廣東現在已經有很多「外省人」安身立命,以及不少粵人撈化**。如果新國家政策歧視這批人,搞到這些人大規模離開廣東,甚至出現流血衝突,那是沒有用的。我認為最有效的獨立國策是**盡量維持現狀,把握支那分裂過程其它地區互相交戰/內亂/社會動盪的機會,維持國內穩定,並全力發展粵國經濟**,有錢就能有兵有人,把其它地區甩掉。有的人強求民族純潔,要搞大粵主義,排斥「外省人」,或者想兼併香港、廣西、海南,一點益處也沒有。要是造成人口大幅外流/傷亡,經濟直接萎縮了。獨立是為了甩掉共匪貪腐高壓統治,快速追上韓國台灣,進入發達國家之列。**英法六千萬人,德國八千萬人,日本一億人,他們的經濟、工業能做到的,廣東一億人也可以。**
然而現實是,我這套主張當然過於理想。自由民主,內政自治,這兩條可能比較容易實現。建粵軍就有難度了。不排斥外省人,鄉民更是很可能做不到。因為大中華主義、大漢族主義者,他們主張一國一族一種語言一種文化的社會,不能面對現實,不能接納其他人,變成粵獨分子,只不過把中華換成廣東,漢族換成粵族罷了。所以網上很多粵獨分子(其實是廣府人居多)都提什麼大粵(吞併香港廣西的調調),卻無視廣東本來的多元社會,廣府人和潮汕人客家人還未必合得來。我提出的那一套,客家人願不願意接受,抑或和江西福建客家自成一國,我都完全無法預料。(潮州人我倒是信心大一點。他們應該不會跟閩南人一塊。閩南人本身結構也很複雜。而且我印象中,閩南人做事太黑了。比如香港反送中運動裡,廣府/潮汕社團替政府做打手的很少。唯獨是福建人社團特別親支親政府。讓潮汕人選,是和泉漳廈一起好,還是和珠三角一起好?)
如果客家人、潮汕人選擇自己建國,或與別的人建國,或者留在支那,我也無所謂。畢竟沒辦法強行撮合。剩下廣府人自己的話,還可以省掉各種聯邦結構,直接模仿英格蘭/香港單一制完事。
另外司法制度,未必能移植普通法。那就大陸法吧。這樣一來我對司法獨立、司法公正很擔心。廣東本土沒啥司法精英。
我的想法受香港、英美影響較大,認為凡事應順其自然,不要強求某些政治目標。軍事、外交、國籍、語言政策,應以務實為上。鼓勵使用本土語言是對的,但為了各族平衡,維繫脆弱的聯盟,用普通話做工作語言不成問題,因為這的確是現在每個廣府人/潮汕人/客家人/外省人都懂的語言,而我一個珠三角廣府人可不懂潮州話和客家話。反過來他們也未必懂粵語。如果他們自己肯說粵語,那是他們自願,但政策上不能獨尊一種語言而壓制其它。如果那些大粵分子學會潮州話/客家話,那我這個懶癌無話可說,給你親自點贊。要么你支持僅粵語地區獨立建國,不與其它地區聯邦也行。聯邦用一種別國語言也沒啥好自卑的,畢竟現在粵語地位已經輸給普通話了,就像歐盟現在只剩愛爾蘭馬耳他塞浦路斯三國講英文,德國佬法國佬工作語言不還是以英語為主,哈哈。支那地區lingua franca就是官話,只不過100年前廣東通行的是西南官話,現在一水的北京話罷了。(汪精衛錄音[https://upload.wikimedia.org/wikipedia/commons/9/90/兩種懷疑心理之解釋\_汪精衛\_西南官話.mp3]( "https://upload.wikimedia.org/wikipedia/commons/9/90/兩種懷疑心理之解釋_汪精衛_西南官話.mp3"))
### 品葱用户 **伯格涅夫** 评论于 2020-02-12
邓大平你好。,你就是那个在中国的南海边画了一个圈的老人么。。。。
\---------------------------------------------------------------------------------
不得不说你真的很认真(无贬义)这个要点赞
### 品葱用户 **yvshin** 评论于 2020-02-11
像这样的论述在品葱真的不缺啊,听着想是钢铁雄心出的什么dlc。没有贬义,很cool,但是太脱离现实了吧。
### 品葱用户 **cansinlej yvshin** 评论于 2020-02-11
> 像这样的论述在品葱真的不缺啊,听着想是钢铁雄心出的什么dlc。没有贬义,很cool,但是太脱离现实了...
是啊,是很理想化。我最擔心的是貨幣和財政。人民幣超發、巨額政府債務的問題對於民主化/獨立威脅很大。我改天再開一貼討論那個。
### 品葱用户 **破壁** 评论于 2020-02-11
每当看到这种独立建国的帖,我都会入来点下赞。
### 品葱用户 **飛躍瘋人院** 评论于 2020-02-12
~已删除~
### 品葱用户 **決不再做奴隸** 评论于 2020-02-12
> 工作語言是各邦本土語言+普通話+英語。國會開會可以用任何一種發言,類似香港立法會。
我很讚賞這個作法。非常西方化。(祇是我們需要煲冬瓜麽?內地人聽不明就返鄉下啦。)
> 所以我的假想國家名字就叫粵國,也可以叫嶺南。
劉老把英文名也替我們想好了:Cantonia.
總體來說想法很好。劉仲敬說過,香港抗爭勝利的途徑在於把革命輸出到廣東、華南。這樣可以與中共逼和,實現香港獨立。
如果是抗爭方向,粵獨運動需要有攻有守。不祇在境內抗爭,而是把革命輸出到內地,爭取逼和。
### 品葱用户 **決不再做奴隸** 评论于 2020-02-11
民間力量很重要。廣東一向重視「兄弟義氣」。在此基礎上,如果能夠把地下教會更好地組織起來,實現宗教派別、軍事派別、和社會服務派別的有效運作,那麼應該能在組織度上達到中共無法滲透的程度。深挖洞,廣積糧,緩稱王(不要急於宣告獨立),在農村籌備、積累三十年,粵人將成為相當強的有組織力量。
歸根結蒂,大粵民族的正途是融入美國、日本的世界文明秩序,實現「脫支入美」。繼續在支國大一統的黑暗秩序下苟活,祇能成為豬圈裡生產力較強的肉豬,養肥吃豬人,苦了大粵國。
### 品葱用户 **飛躍瘋人院** 评论于 2020-02-12
我認為廣東如果一旦失去香港會走很多冤枉路走少很多捷徑 不要太看得起廣府人。我認為廣東應該納入香港 跟香港制度管治教育 用土地互補還可以利用香港多年來在國際上的聲譽去經營 用1代人左右的時間融合 洗翻乾淨個种培養人權公民意識 普世價值觀大家雙贏 。廣東有很多小粉紅 支化的一代。政權如果一旦落入他們手中 後果不堪設想。 最好還是請英美過來管治執政也行 反正我是不看好 這代大多毫無公民人權意識的人 建立的制度執政。
獨立之後第一件事當然是邊境建立圍牆 廢除奴隸儒家文化教育 防止偷渡等 太多事要變革了
英語當之無愧肯定為母語 官方語言。(廣東話就民間私用吧 )走國際化路線 建交 越南 台 日 韓 上海 朝鮮等 最好就打造個類似歐盟的 亞洲聯盟 經濟圈 共用貨幣 免簽證 簽訂自由貿易協議 抵抗東北俄 共勢力等等
經過1 2代人努力 趕超 日 韓 成為歐洲二線國家級別 或 至少成為東南亞一哥 絕對真的不難。 這條路我認為能走少很多民主冤枉路 或者說是最快的捷徑吧 其實中國最適合獨立的地區就是上海和廣東。 當年習仲勳自己都覺得廣東是應該獨立的 。只要有錢賺 公民權益福利得到保障 誰的國並不重要 我相信是會得到認可的。其實廣東和上海這兩個地方擺脫北京中央剝削 全面開放 會過的比現在好幾十倍。 現在的廣東根本沒將百分百的實力打出來。簡單的來講 自己想象一下 如果成功 人均收入2000 3000美元 一個放大版的香港 在亞洲的經濟影響力會有几恐怖 是甚麼概念吧
### 品葱用户 **cansinlej 飛躍瘋人院** 评论于 2020-02-11
> 你太看得起廣東人了。我認為廣東納入香港 跟香港制度管治 用土地互補等最好還可以利用香港國際聲譽去經營...
做得到無所謂啊,全盤照抄香港政治制度(小改動,不要行政長官負責政府的制度,直接改成英式議會制),讓香港終審法院當廣東終審法院。問題是廣東人能不能接受呢?喜歡念叨虛無縹緲的尊嚴、主權的人會是主流呢。他們怎麼會同意被香港管理。妹仔大過主人婆噉。
不需要建圍牆。有軍隊巡邏邊境即捕即解就不會有人來的啦。但要是出現難民潮的話,那倒可能需要物理隔離。
### 品葱用户 **cansinlej 決不再做奴隸** 评论于 2020-02-13
> 我很讚賞這個作法。非常西方化。(祇是我們需要煲冬瓜麽?內地人聽不明就返鄉下啦。)劉老把英文名也替我們...
都說了普通話是為了平衡三大土著+外省人。可以用普通話。廣東撈化速度非常快。不講本土語言而講普通話的人每一天都在增加。這是和平過渡的設想。如果流血過渡外省人大逃亡的話,那就無所謂咯。但那樣粵獨這個國家前途更渺茫。
不要Cantonia。Kwangtung就可以了。或者換一個粵字的羅馬化,比如Yuet。
### 品葱用户 **民小一个** 评论于 2020-02-12
为何要男女强制服兵役?有点太军事化了吧。维持那么大数量的军队,如果没有武力威胁邻邦的计划,个人认为完全没有必要。但是粤国经济可能发展高度依赖海洋,保有一支现代化的以护航和巡逻反潜为主要任务的海军力量还是有必要的。
还有入境政策也有点让人一言难尽…
### 品葱用户 **決不再做奴隸 飛躍瘋人院** 评论于 2020-02-12
> 你太看得起廣東人了。我認為廣東應該納入香港 跟香港制度管治教育 用土地互補還可以利用香港多年來在國際...
自從1842年香港成為英國殖民地,與廣東分離已經近180年。雖然兩地粵語還可以互相聽明白,但是文化差異已經像朝鮮和韓國一樣大了。
### 品葱用户 **破壁 飛躍瘋人院** 评论于 2020-02-13
> 你太看得起廣東人了。我認為廣東納入香港 跟香港制度管治 用土地互補等最好還可以利用香港國際聲譽去經營...
这个是事实
### 品葱用户 **cansinlej 決不再做奴隸** 评论于 2020-02-12
> 自從1842年香港成為英國殖民地,與廣東分離已經近180年。雖然兩地粵語還可以互相聽明白,但是文化差...
我不知道你是廣東人還是香港人。看你的敘述恐怕是香港人,對於廣東現況、廣東歷史一概不知,對於香港歷史也不清楚。
廣東的基督教各派信仰都很少。香港本身也不多。
廣東農村也沒有實力,均已大幅度城鎮化。如果民主化/獨立,農村人只是主力一部分。更多的應該是珠三角人,包括很多基層外省人。支那其它地區經濟太差,這些人跑到廣東安家,承擔了許多基層工作,就像西歐的非洲中東非法移民。
廣東與香港的隔閡是從1950年代才開始形成的。
### 品葱用户 **決不再做奴隸 cansinlej** 评论于 2020-02-12
> 我不知道你是廣東人還是香港人。看你的敘述恐怕是香港人,對於廣東現況、廣東歷史一概不知,對於香港歷史也...
城市抗爭和在農村挖地道、發展革命根據地可以同時進行。如果沒有充分的積累就試圖奪取共產黨控制的城市,分分鐘被鎮壓。
### 品葱用户 **cansinlej 決不再做奴隸** 评论于 2020-02-12
> 城市抗爭和在農村挖地道、發展革命根據地可以同時進行。如果沒有充分的積累就試圖奪取共產黨控制的城市,分...
共產黨鎮壓不到農村嗎?還上井岡山打游擊?
### 品葱用户 **飛躍瘋人院 cansinlej** 评论于 2020-02-13
只要有錢賺 公民權益福利得到保障 誰的國 何種制度並不重要。其實廣東這個地方擺脫北京中央剝削 全面開放 會過的比現在好幾十倍。 現在的廣東根本沒將百分百的實力打出來。 自己想象一下如果成功 。一個人均2000 3000美元收入 一個放大版的香港在亞洲的經濟和影響力會有几恐怖 是甚麼概念吧
### 品葱用户 **決不再做奴隸 cansinlej** 评论于 2020-02-13
> 共產黨鎮壓不到農村嗎?還上井岡山打游擊?
農村的半地下自組織已經發展得很好了。你不知道而已。中共鄉官是可以買通的,而且中共的農村官僚體系很容易滲透。
農村居民成分比較穩定,這種半地下的組織可以發展成員、挖地道、屯糧,而長期不被中共發現。就好像新疆的維吾爾人用維語教授民族思想,幾十年都沒被中共發現。
大城市裡面投資辦公司,人員流動太太,藏不住呀。
### 品葱用户 **随心123** 评论于 2020-02-13
土共独裁执政两大法宝:
一,民主就会四分五裂,分裂就会军阀割据,就会乱,就会穷,就会水深火热。
二,美帝亡我之心不死,只有共党才能救人民。阴谋论是万能挡箭牌。
—————题主宣扬民主即分裂,勾勒分解画面切合土共法宝,煞有介事,振振有词,让人啼笑皆非。
从好的方面看,这是理念先进,从不好的方面看,这是土共卧底,强化土共执政基础。
### 品葱用户 **cansinlej 随心123** 评论于 2020-02-13
> 土共独裁执政两大法宝:一,民主就会四分五裂,分裂就会军阀割据,就会乱,就会穷,就会水深火热。二,美帝...
民主即分裂有可能,但分裂即軍閥割據則未必。各地獨立,總有善治、經濟好的吧。各地自治得好,根據自己的意願再合組美國/歐盟形式的聯邦,也很好啊。非要說支那人民主就分裂,分裂就內亂,實則是歧視支那人,認為支那人不如歐美白人,不能做到自由民主自治。
### 品葱用户 **随心123 cansinlej** 评论于 2020-02-12
> 民主即分裂有可能,但分裂即軍閥割據則未必。各地獨立,總有善治、經濟好的吧。各地自治得好,根據自己的意...
题主宣扬民主即分裂,勾勒分解画面切合土共法宝,煞有介事,振振有词,让人啼笑皆非。
从好的方面看,这是理念先进,从不好的方面看,这是土共卧底,强化土共执政基础。
另外用土共维护独裁法宝三来回复你:中国文化和素质不适合民主。
你所回答的,恰巧是土共强化的执政基础,想不到吧?不可思议吧?这就是现实。
### 品葱用户 **cansinlej 民小一个** 评论于 2020-02-13
> 为何要男女强制服兵役?有点太军事化了吧。维持那么大数量的军队,如果没有武力威胁邻邦的计划,个人认为完...
強制兵役制度一為保持軍力,二為塑造國民認同。新加坡、以色列、瑞士、芬蘭都是這樣幹(有的國家女人不用服役)。讓每一個人都參與保家衛國。
如果能成為正常國家如美英法,不應該搞徵兵制。但是剛獨立的國家不會是正常國家,需要提防強敵軍事入侵,或者政治上的統一。
### 品葱用户 **cansinlej 随心123** 评论于 2020-02-13
> 题主宣扬民主即分裂,勾勒分解画面切合土共法宝,煞有介事,振振有词,让人啼笑皆非。从好的方面看,这是理...
支共歧視支那人文化和素質,支那人欣然接受,那我只能表示尊重。
### 品葱用户 **silverball** 评论于 2020-02-13
反对把香港和澳门纳入粤国,这样经济发展必然不均衡
尤其是货币,港币太强势,几乎已经把澳门币灭了
粤国印钞权如果交给香港,主权会沦为被金融精英遥控的傀儡
### 品葱用户 **cansinlej silverball** 评论于 2020-02-12
> 反对把香港和澳门纳入粤国,这样经济发展必然不均衡尤其是货币,港币太强势,几乎已经把澳门币灭了粤国印钞...
香港實施聯繫匯率,港元等於美元。新政府有3種選擇,人民幣、美元、自行發行貨幣。這事很麻煩。不只是粵獨會面對,只要支共倒台,無論是否邁向民主化,都要面對人民幣超發和巨額政府債這個大炸彈。經濟學我只懂皮毛。
### 品葱用户 **飛躍瘋人院 silverball** 评论于 2020-02-12
> 反对把香港和澳门纳入粤国,这样经济发展必然不均衡尤其是货币,港币太强势,几乎已经把澳门币灭了粤国印钞...
如果廣東全面開放 你認為香港價值還會很大嗎 別忘記香港當年的成功是建立于 中國的封閉之上。 廣東隨便拿塊地出來開賭場 澳門就更不用講 明天就可以宣佈 打回原形了。不是嗎。 當然我是主張廣東納入香港的。 如果廣東是個自由民主國家 和你共用港幣 美金 請問你還會願意在香港擠那點地方買房生存????
### 品葱用户 **cansinlej 飛躍瘋人院** 评论于 2020-02-12
> 如果廣東全面開放 你認為香港價值還會很大嗎 別忘記香港當年的成功是建立于 中國的封閉之上。 廣東隨...
香港可以走瑞士、新加坡模式。廣東做不到的。
澳門倒真是無所謂,自己獨立/加入香港/加入廣東都沒什麼區別。60萬人,經濟全靠賭業、旅遊業。可能自己獨立做離岸公司天堂,前途最好。
### 品葱用户 **Virosa** 评论于 2020-02-13
基本支持 少數細節有異議
個人認為認為父母至少一方自三代前定居的給國籍,其餘給永居並按照正常程序申請加入。條件主要包括對應區域語言測試(粵/潮/客/...)
### 品葱用户 **雜種書記親衛隊** 评论于 2020-02-12
作爲一個聯邦+粵獨主義者支持。
國籍認定方面,我覺得應該從一開始就認可雙重國籍以獲得海外粵人的支持。
就我本人而言,如果爆發革命,我會立即以出生地恢復粵國國籍並自帶錢和武器加入革命軍,如果要不認可雙重國籍的話歸屬感會下降(因爲革命時期的粵國國籍是幾乎沒有實際價值的,應該沒有人會選擇放棄除中國藉以外的國籍)。
個人認爲國籍認同可以簡化,除了最基本的繼承法理上原本領土內的常住居民以及出生地認定,可以參考以色列對猶太人回歸故土的政策,對於本土以外申請歸化的粵人,採用血統(如果族譜之類的資料遺失可以由兩個以上的本土粵人擔保)+本土語言認證(廣州話、潮州話、台山話、客家話等各邦本土語言的其中一種,申請海外粵國護照後獲得對應該邦的居留權)。 實際操作上可以要求居住六個月以上才能享有福利(以及兵役、納稅等義務)。
至於香港、澳門永久居民可以入籍我覺得有點多餘,而且香港永久居民中有不少是拒絕融入的新移民以及中共高官子弟,如果是真香港、澳門人通過海外途徑申請入籍完全沒有任何障礙。
關於普通話,我支持不進行激進的文化清洗,認可其現有的通用語地位,但認爲應該設立官方語言(可以包括各邦的官方語言,但應該將普通話排除再外)。如果光復之後(假設我幸運地沒有戰死),在官方場合我寧可用英文與非粵語區的聯邦公民交流也不會使用普通話(不過到時應該到時直接說自己的本土語言,議會之類的地方應該會有一堆同聲傳譯?)。
### 品葱用户 **随心123 cansinlej** 评论于 2020-02-12
> 支共歧視支那人文化和素質,支那人欣然接受,那我只能表示尊重。
我揭示的只是现实,兄台可能未被墙过,也可能未从婴儿时期就开始不间断的被土共洗脑过,觉得不可思议甚至恨铁不成钢,可以理解。
很多人不可理解,土共如此残暴,为什么不倒?其实说起来道理很简单,无非就是几大法宝。
作为反共人士,尊重只是一种无奈,重要的是对土共法宝进行分析和破解。
只有在尊重的基础上,合力破解土共的独裁法宝,墙奴才会不断的觉醒。
而题主所作的这些假设,是毫无意思的,甚至是助纣为虐的。所以,请宽恕我使用一个比较激烈的词:鄙视。
### 品葱用户 **Alicia** 评论于 2020-02-12
大粤国应该还有海南和广西东边+广西南部入海口
### 品葱用户 **亡黨復興中華** 评论于 2020-02-13
支持。可以直接放棄官方語普通話吧,不等於還說普通話犯法,民間還是可說的,但長遠而言下一代就必須要學粵語,慢慢洗掉普通話就行。
我是香港人,堅決拒絕納入粵國的,但不納入不等於敵對的,我更希望是香港與粵國是多方面的伙伴或同盟關係,無論經濟,教育,醫療,軍事等等,只要是提升或保障兩國人民生活都可合作。
### 品葱用户 **cansinlej 雜種書記親衛隊** 评论于 2020-02-12
> 作爲一個聯邦+粵獨主義者支持。國籍認定方面,我覺得應該從一開始就認可雙重國籍以獲得海外粵人的支持。就...
同時回答@Virosa
給永居/雙重國籍這個問題我有考慮過。這個有點麻煩。正如雜種書記親衛隊所說,剛獨立的國籍(永居也一樣)很不值錢。給外省人永居而不是國籍的話,會不會造成信心崩潰大批逃亡?難說。
雙重國籍也是一個做法。海外粵人/港人當然是革命主力。雙重國籍有利於召喚他們加入。但是法治國家,國籍法不能搞歧視,也就是不能說我對支那故地不承認雙重國籍,對全世界都承認。那這樣搞,支那故地其它國家也有他們的國籍法,這幫外省人做兩面人,或者對粵國認同淡薄,也不利。
一些海外粵人的悲慘遭遇,也是我獨立思想的一大啟發。越戰、赤柬、印尼、古巴等地針對華人的屠殺,實際上大部分是粵人。如果廣東是一個獨立自由的國家,肯定不會像共匪那樣置之不理。以色列猶太人、德國針對東歐德裔,這些回歸故土的國籍法一定會考慮。應該只要能證明祖先來自粵國疆域、本人能操土著語言,就應該給予簽證便利,方便他們歸化。
剛獨立的時候可能講普通話比較方便一點。但是時間久了應該直接學會講對方語言。星馬1980年代以前出生的華人很多都能講幾種語言。像這個印度人都可以講很不錯的國語、粵語、閩南話、客家話…… https://youtu.be/sxqY2Ahf-fk 🤣
強制兵役制度中,應該混編各族。這樣有助於學習對方語言,增進民族交流,塑造粵人身份。
### 品葱用户 **frances** 评论于 2020-02-13
我初中時仲未有墻,就見過粵獨論壇,可惜咁多年過去,我地失去好多自己嘅文化同年青人,到今時今日連香港都自身難保...
### 品葱用户 **elsaanna** 评论于 2020-02-13
三大民系应该各自立国,旧的省份划分本来目的就在于牵制
### 品葱用户 **cansinlej elsaanna** 评论于 2020-02-13
> 三大民系应该各自立国,旧的省份划分本来目的就在于牵制
也可以。這樣還可以省掉一級政府,直接國家政府>市政府。
但是這種方法有不好的地方,在於國界難定,容易扯皮,危及各國。像前南斯拉夫內戰,各族搶地盤。能像捷克斯洛伐克那樣和平分手,以談判解決問題,當然最理想。
### 品葱用户 **Schter** 评论于 2020-02-13
本人支持粵國采用大陸法系。
沒有經過英國統治、沒有普通法傳統的地方,强行采用普通法,效果未必好。
民國時期的立法是典型的德日大陸法系立法,采用大陸法系有利于新舊法統銜接。當下南粵法律人也熟習大陸法。
大陸法系不等于無司法獨立,德國的聯邦憲法法院+行政法院+普通法院+勞動法院+各邦法院的司法體制,一樣高度司法獨立,可强力保障人權。
最後,司法體制雖然重要,但在現階段,相較于建國立邦,都只屬技術層面的問題,可以在建國後慢慢傾,唔掂傾到掂嘅。
### 品葱用户 **cansinlej Schter** 评论于 2020-02-12
> 本人支持粵國采用大陸法系。沒有經過英國統治、沒有普通法傳統的地方,强行采用普通法,效果未必好。民國時...
我提出改行普通法,是因為普通法可以直接抄香港英美加澳紐幾百年歷史傳統,無需自己重新建立司法體系。當然弊端在於難以預料移植陌生系統能否有效運作。所以我個人的理想是用普通法,但沿用大陸法也可以,不過那會有迫切需要大幅修訂PRC法例。
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-13
> 同時回答給永居/雙重國籍這個問題我有考慮過。這個有點麻煩。正如雜種書記親衛隊所說,剛獨立的國籍(永居...
對於外省人,其實可以分兩種情況。對於已經取得戶籍的,獨立後的粵國沒有理由剝奪他們的公民權。其實我主張直接將各市的戶籍身份直接轉化爲粵國國籍。對於未取得戶籍的外省人,可以對比參考歐洲那些非移民民族國家對待外國人的方式,已經連續合法工作一定年限(參考歐盟十年永居?)的發放永居資格。不過事實上據我了解,入廣東戶籍要求其實不算高,連續工作的外省人大部分都有廣東籍。只要未達永居資格的,可以給予一定緩衝期(一年~兩年?),緩衝期過後需申請工作簽證才能繼續留粵。
雙重國籍中有一種特殊情況,就是持有中國國籍者申請粵國籍之前應該聲明放棄中國國籍。至於理由,粵獨之後中國必然是頭號敵國。
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-13
> 同時回答給永居/雙重國籍這個問題我有考慮過。這個有點麻煩。正如雜種書記親衛隊所說,剛獨立的國籍(永居...
其實關於普通話這個問題,有一個折中的方式。因爲如果領土包括廣西全境,屬於西南官話的桂柳話也會屬於本土語言的一種。不過似乎有種歐盟在英國脫歐後還要用英文作工作語言的感覺。
### 品葱用户 **反韃復華** 评论于 2020-02-13
在香港打杀的黑警基本上是广东人 说明你粤还是粉红多 既然是粉红又怎么可能支持独立呢 如果是民众要独立那对不起只能是聊天扯淡 要么渗透改造土匪的军队要么自行组建粤民的军队 似乎你都没想过怎么做这个问题
### 品葱用户 **cansinlej 反韃復華** 评论于 2020-02-13
> 在香港打杀的黑警基本上是广东人 说明你粤还是粉红多 既然是粉红又怎么可能支持独立呢 如果是民众要独立...
我估計是只能自行建軍,因為我總覺得廣東人當兵的很少。也不能指望駐紮廣東的解放軍能倒戈,因為他們都是不知道哪個省的人。所以我提出來要實行強制兵役制度,全廣東適齡男女均需服役。兵役制度立起來,三五年就可以有一支軍隊了。這個辦法參考了新加坡和以色列。軍隊初建請台灣國軍和新加坡軍人來做教官,甚至軍官都可以,另外希望吸引在北美當過兵的粵人/華人來參與。
### 品葱用户 **electricalzz** 评论于 2020-02-13
我睇到深圳兩個字就覺得天方夜譚了...
深圳而家全部都係撈佬,你試下係深圳講廣東話,人家會哈?返你轉頭,覺得你係咪痴咗線講廣東話。
### 品葱用户 **雷枫** 评论于 2020-02-13
广州以人口密集型产业为主,真独立出去建国了,谁来发展经济?深圳会理你?
### 品葱用户 **Giangs Schter** 评论于 2020-02-12
> 本人支持粵國采用大陸法系。沒有經過英國統治、沒有普通法傳統的地方,强行采用普通法,效果未必好。民國時...
广州在清代作为通商口岸的时候有没有在一定区域内用过英国法呢?
### 品葱用户 **Zazulovemyworm Giangs** 评论于 2020-02-13
這個真沒有 僅限廣州本地 不過廣州是粵地收監和斬首的地方啦
### 品葱用户 **反韃復華
cansinlej** 评论于 2020-02-13
> 我估計是只能自行建軍,因為我總覺得廣東人當兵的很少。也不能指望駐紮廣東的解放軍能倒戈,因為他們都是不...
鞑警会乖乖等你三五年?陈胜吴广花了三五年?
### 品葱用户 **cansinlej 反韃復華** 评论于 2020-02-12
> 鞑警会乖乖等你三五年?陈胜吴广花了三五年?
不一定是 粵獨->共匪倒台
也可以是 共匪倒台->各地各自為政,混沌狀態->(半年/一年/幾年/十幾年)->粵獨
或者 共匪統治能力減弱,持續混沌狀態->粵獨->共匪倒台
現階段提倡粵獨,處於討論階段,希望增加支持獨立的人。等人多了,進入實際鬥爭階段,過程與東南亞/非洲反殖獨立相似吧。
### 品葱用户 **反韃復華
cansinlej** 评论于 2020-02-13
> 不一定是 粵獨->共匪倒台也可以是 共匪倒台->各地各自為政,混沌狀態->(半年/一年/幾年/十幾年...
那我明确的表示反对 脱离朝廷的广东就跟越南差不多 四分五裂于大局不利 早晚被美国消灭被美国统一全球 独立只是一时爽 没有考虑到长远利益 误以为被美国人统治就会幸福 更是不稳定不确定 你只能看到现在的美国人是怎么样的 推测不出未来的美国人是怎么样的 要把命运交到异族手里 我只想告诉你一句老祖宗的话 非我族类 其心必异 鞑共为什么残暴至极 本质上也是因为他们是异族 他们是鞑子的后代 包括鞑化的所谓汉人也不是华夏一族的人
### 品葱用户 **cansinlej 反韃復華** 评论于 2020-02-12
> 那我明确的表示反对 脱离朝廷的广东就跟越南差不多 四分五裂于大局不利 早晚被美国消灭被美国统一全球 ...
粵族非華夏一族。粵族非你族類,其心必異,對你必殘暴至極。粵族就是不要把命運交到你們這些異族手裡。
### 品葱用户 **rockman 決不再做奴隸** 评论于 2020-02-13
> 民間力量很重要。廣東一向重視「兄弟義氣」。在此基礎上,如果能夠把地下教會更好地組織起來,實現宗教派別...
赞成。支持。
### 品葱用户 **恶过华秀只狗 反韃復華** 评论于 2020-02-12
> 在香港打杀的黑警基本上是广东人 说明你粤还是粉红多 既然是粉红又怎么可能支持独立呢 如果是民众要独立...
你所说的好像没有实质的证据证明,基本都是理论上的推测,如果将来有机会公审我相信会知道真相。
### 品葱用户 **hkgusa** 评论于 2020-02-12
香港人也支持粵獨
再怎樣說也比與北方共產政權為鄰要好
### 品葱用户 **血染长安街** 评论于 2020-02-12
我建議在粵獨成立之際優先與香港商定結盟、加入聯邦甚至合併,然後全盤使用香港現有法律,使用港幣作為通用貨幣,可以降低粵獨重建的時間。
雖說不一定香港願意加入,但風險與優勢並存。
香港經濟高度發達,但土地資源缺乏,水資源被赤共扼製,價高質平。結盟/聯邦/合併的好處在於調和香港土地資源和廣東經濟的差異,達到良好的互補狀態。
文化上,香港老一輩人多數因不滿政治、生活從廣東遷移入香港,若廣東實行了與理想狀態下的香港高度一致的民主制度,那麼兩個文化淵源非常深刻的土地為何不能商議結盟/聯邦/合併大計?
從個人願望上,亦可滿足大中華膠,畢竟大中華膠的祖上多源自廣東,有了廣東的土地資源,來去自由,文化認同度高了,大中華膠自然會轉化為大南粵膠,有助於淡化黃藍派別歷史爭議,讓真正的爭議放在有用的地方而不是意識形態的鬥爭上。
至於香港現有部分低質的新移民,管他們幹什麼?粵獨就是保留民主自由,保證言論自由,當我們制度優越的時候,無論是誰都容易轉化、接受。
另外本人認為粵港澳大灣區其實不是不能搞,只是背後的搞手不可以是赤共。
祝:南粵聯邦早日建立
### 品葱用户 **aisicong** 评论于 2020-02-13
真有人敢这样做广东人马上就造他的反了。。。没有了便宜的人力资源 没有了便宜的矿产资源 没有了庞大的市场 广东还剩下什么?
就拿广东TOP1的城市深圳来说,纳税前几的企业平安(全大陆范围内的保险业务)、华为(大陆三大运营商主要设备供应商)、正威国际(矿产资源)、恒大集团(全大陆范围内的房地产业务)、招商银行(全大陆范围内的零售银行业务)、腾讯(全大陆范围内的互联网业务)。。。。怕是你刚想喊造反就被这些大佬以及他们的员工打死了吧。。。。
看得出来贴主是有花点时间写得一篇帖子,有兴趣应该更仔细调查下。
### 品葱用户 **cansinlej aisicong** 评论于 2020-02-13
> 真有人敢这样做广东人马上就造他的反了。。。没有了便宜的人力资源 没有了便宜的矿产资源 没有了庞大的市...
我沒有把邊境徹底關上哦。50歲以前一生一次的一年期無條件找工作簽證。工作兩年可享福利。這個條件比現在戶口制度更優惠哦。比如現在沒有深圳戶籍的小孩讀書可要交很高的費用。這是一生都在省外的普通人的工作機會。另外還可以有正常國家的各種吸引人才的工作簽證哦。
獨立了也不代表我一定喪失市場哦。跨省企業變成跨國企業罷了。
經濟方面,短期目標可以是東南亞龍頭。假如今天突然獨立了,廣東的競爭力起碼比越南強多了,把外資吸引回來。中期目標人均生產力和生活質量追上台灣韓國。(珠三角還差十幾年的樣子吧。珠三角以外就差遠了。然而貿易戰+國進民退,那十幾年的差距還要拉開。)中短期內,務求工業品生產水平成為世界二流,追上韓國之流吧。長遠希望增加科研投資,追上荷蘭北歐的水平。德日水平不敢奢望。
今天同屬一個國家,生產原材料是否便宜?我看未必。物價很貴超英趕美倒是真的。事實上珠三角經濟、生產力已接近台灣韓國,但是錢都貪了/浪費在面子工程/輸送到中央……以至於珠三角平民生活水平還不如馬來西亞。
### 品葱用户 **反韃復華
cansinlej** 评论于 2020-02-12
> 粵族非華夏一族。粵族非你族類,其心必異,對你必殘暴至極。粵族就是不要把命運交到你們這些異族手裡。
小鞑子别冒充啦 就你还粤人 查过历史吗 是个民族吗 你们鞑子内部政策早就路人皆知啦 到处抹黑华夏血统分化华夏派系
### 品葱用户 **Virosa cansinlej** 评论于 2020-02-13
> 同時回答給永居/雙重國籍這個問題我有考慮過。這個有點麻煩。正如雜種書記親衛隊所說,剛獨立的國籍(永居...
個人認為大量為赤化塞進廣東的外省人如果擁有投票權會對本土文化復興產生巨大阻力,反而沖淡身份認同
### 品葱用户 **cansinlej Virosa** 评论于 2020-02-14
> 個人認為大量為赤化塞進廣東的外省人如果擁有投票權會對本土文化復興產生巨大阻力,反而沖淡身份認同
班友有D似以色列嘅阿拉伯人……
投票權要畀掛,唔畀D人危機感咪會重咯,走晒啦,除非外省戰亂嘎啫。
唔計深圳。其實冇粵化嘅外省人+撈化嘅粵人,有幾多呢?我估呢種人主要都係喺廣州、東莞、珠海、佛山、中山呢5個城市。佛山中山可能都好D。
我估廣州大概有800萬土著,800萬外來人?其中應該有至少600萬係非粵潮客?600萬應該通婚+同化嘅有100萬?所以大概有500萬未化嘅撈頭?所以成個珠三角除咗深圳可能有800至1000萬呢班人?即係佔人口兩三成。
不過呢。如果湖南同廣東關係友善,呢班人起碼有三四成係湖南頭,噉威脅都細D。
無論點都好,我始終都認為盡量留住呢班人,好過一腳踢走。畢竟唔能夠大屠殺嘎?趕走班人,唔單止經濟萎縮,仲嚴重嘅係送幾百萬滿懷怨恨嘅人畀鄰國。赤化分子捉到直接遞解出境另一回事。
### 品葱用户 **达拉鸡 反韃復華** 评论于 2020-02-14
> 那我明确的表示反对 脱离朝廷的广东就跟越南差不多 四分五裂于大局不利 早晚被美国消灭被美国统一全球 ...
是的我突然想起明末那群人怎么鼓吹满清君主结果到最后才发现人家根本不把你们这群文人当人看。
### 品葱用户 **他出發找最愛 決不再做奴隸** 评论于 2020-02-14
> 民間力量很重要。廣東一向重視「兄弟義氣」。在此基礎上,如果能夠把地下教會更好地組織起來,實現宗教派別...
冇錯 擁抱海洋政權的那一邊先可以實現自由民主
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-14
> 班友有D似以色列嘅阿拉伯人……投票權要畀掛,唔畀D人危機感咪會重咯,走晒啦,除非外省戰亂嘎啫。唔計深...
我有一個設想,就是設定領土範圍中國籍公民放棄中國籍申請粵國籍的時間,比如可以是新政府成立後的1年。到時候,出於對激進本土派種族歧視的擔憂,相信有不少的外省人會選擇移民回祖籍地。而留下選擇粵國籍的部分,會是已經融入或者同樣支持中國解體的同路人。待政局穩定後,之前選擇保留中國籍的外省人想要回粵就要參照一般外國人的標準。在和平過渡的前提下這應該是進行人口篩選最溫和的方式(雖然我覺得獨立戰爭無可避免)。
### 品葱用户 **cansinlej 雜種書記親衛隊** 评论于 2020-02-13
> 我有一個設想,就是設定領土範圍中國籍公民放棄中國籍申請粵國籍的時間,比如可以是新政府成立後的1年。到...
我想了一下,有一個邪惡的想法,可以合法屠殺。
在戶籍換國籍的前提下。立法要這些沒有戶籍的18到40歲的男人,參軍服役2年來換國籍。這就逼人選邊了。所有事業家產都在廣東,不捨得放棄的話,就算不支持獨立,為了保住財產,還是會去當兵。不肯當兵的沒有國籍只能離開了。編成輕步兵師。
一旦開戰,送上前線……
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-13
> 我想了一下,有一個邪惡的想法,可以合法屠殺。在戶籍換國籍的前提下。立法要這些沒有戶籍的18到40歲的...
感覺這個方案只適合整個東亞陷入混戰的情況。如果戰亂沒有達到一定程度,這種充軍的行爲其實很不人道,有礙國際聲譽(除非廣東以北變成軍閥混戰的地獄,他們無路可選)。逼得太緊,還有原地暴動,做中國內應的風險。其實不能取得戶籍或者達到永居條件的外地人一般都是低端產業工人,與其讓他們參軍不如發福利受限、移民較爲不友好的一種「工廠工人簽證」(簽證費包含強制本土文化課程的費用),用多幾年廉價勞動力。
關於語言政策的問題,其實只要廢除普通話現時的獨尊地位(可以暫時作爲實際上的通用語,但因非本土語言之一而不具有官方語言地位),粵語作爲現時除官話以外最有影響力的中文語言,依靠珠三角的經濟優勢以及香港作爲外援,自然發展,到粵獨之後的下一代人應該就會成爲事實上的區域通用語。至於深圳這座移民城市,其實粵獨之後失去北京作爲後援,只會倒向香港,普通話影響力逐漸減弱。所以我一直認爲廣府地區的熱愛母語人士其實不必強調粵語的官方地位,只要壓制普通話,靜待自然發展便可。
教育上,聯邦可以規定基礎教育階段需學會三種本土語言,其中一種作爲授課語言,另外兩種學到參照CEFR B1水平就可以(具體是那三種由各邦自行規定),普通話/國語可以作爲除英語外可選修的一門外語,與西班牙語、法語、德語、日語等並列。另外建議至少從高中開始,所有科目(除語文、本土史之類)採用英文授課,重建大學體系期間在學術上脫離對中文(中國)的依賴和便於學生海外升學。政府每年可以提供一定名額資助海外升學。
### 品葱用户 **cansinlej 雜種書記親衛隊** 评论于 2020-02-13
> 感覺這個方案只適合整個東亞陷入混戰的情況。如果戰亂沒有達到一定程度,這種充軍的行爲其實很不人道,有礙...
我這篇的主要考慮是剛獨立的瞬間,怎麼去保持穩定減少衝突平穩過渡。
至於獨立確立後嘛。我可能另外寫一篇文講。簡單來說,原則是模仿英美加澳紐這些英式國家,盡量自由的經濟、開放市場、簡單及低的企業稅、簡單的利得稅制、自由的社會、自由的傳媒。
教育制度,全部科目母語教學。英文科難度提高就可以啦,不需要英文教學,具體辦學方法也是很自由的,取決於學校,學校有錢請得起老師開英語教學是他們自己的事。考試模式參考英國/香港,A Level或DSE的模式。必考科目就是四科:1 書面中文及母語口語 2 數學 3 英語 4邏輯、公民社會及基本科學。其它科目根據自己需要選修。中一或中三開始資優生可以學第二外語,日法西德俄阿拉伯東南亞各國語言這些。應試語言可以是書面中文或英文。
小學開聯邦語言課,一個禮拜三小時這樣,學非母語的另兩種聯邦語言。另外也要學普通話。兩年學一種。比如小一二學潮州話,小三四客家話,小五六普通話這樣,順序因人而異。正如你所說,學到B1水平,能夠日常交流就夠了。而且因為傳媒自由,多了其它語言的節目,很容易學會的啦。有志從政的自己會學好一點。
普通話其實就是中文換個發音嘛,不需要像第二外語那樣那麼多功夫去學。至於用詞、語法方面,發展出一種粵式普通話,也無所謂嘛。反正北方人能聽懂就行。比如 我吃飯先 這種理論上普通話錯誤的結構,管他呢,對於多數人來說,比崔世安好能溝通交流就行。普通話還是有必要學學的,畢竟能夠溝通能有十億人口龐大市場,也便於知己知彼,別搞得像現在的香港人那樣對北支社會文化一概不知。
在辦學自由的情況下,大學理工醫科很大概率自行加重英語授課比例,甚至轉成英語教學。
### 品葱用户 **aisicong cansinlej** 评论于 2020-02-13
> 我沒有把邊境徹底關上哦。50歲以前一生一次的一年期無條件找工作簽證。工作兩年可享福利。這個條件比現在...
你真当别人傻吗?你都搞独立了 还给你市场?还给你大量人才?你见过哪个外资银行外资保险外资互联网公司在大陆混得很好?
你震认为东南亚有什么市场吗?语言习惯经济法律什么完全不一样的如果真的那么容易搞定 大陆这些企业就不用拼死拼活了 而是去东南亚扩展业务了
还有把广东跟越南比 你真的是太看不起广东了 可能你印象中的广东是十几年前的完全靠密集劳动产业的。
资源是否便宜不是取决你看的 是基于现实情况的。。。。
### 品葱用户 **Philadelphia** 评论于 2020-02-14
我覺得工作語言一定不能用普通話,普通話僅限於日常生活交流,工作語言可以英語+本土各族群語。如果法國德國或者日本對粵國擺脫北屬獨立出了大力,不妨增加這個國家的語言為工作語言。但無論何種本土語,都必須擺脫漢字,全面拉丁化。
語言習慣的框架必須一開始就定好,否則習慣養成後想改變會困難重重。粵國人既然有力量完成獨立,也就不用擔心境內的外省人。斬斷語言鏈接後,第一代還需要擔心,外省二代三代後就會變成真正的粵人。
### 品葱用户 **cansinlej aisicong** 评论于 2020-02-13
> 你真当别人傻吗?你都搞独立了 还给你市场?还给你大量人才?你见过哪个外资银行外资保险外资互联网公司在...
沒有關係啊。拒絕廣東企業,那廣東也可以加關稅。不買廣東產品,不准廣東企業經營,那你去買美國貨日本貨韓國貨唄。限制人口出境那是你們的選擇。
東南亞市場比中國市場好做多了,最重要的就是自由,人家不抗拒外資企業,沒有共匪的條條框框。而且未來50年東南亞人口比中國年輕多了。他們的文化也更願意消費。日韓台港企業早跑東南亞佔地盤了。
未來50年工業自動化程度會快速提高。像日企還把工廠往日本遷。所以工廠從中國遷走根本不是工資問題,而是營商環境太差。實行低企業稅、裁減政府冗員、不用再往北方輸血,廣東已經建立的商業環境和市場比東南亞任何一國都好多了。現實就是處於一國以內不見得資源就會更便宜。澳洲天然氣比狗屁西氣東輸還要便宜。
### 品葱用户 **Virosa cansinlej** 评论于 2020-02-14
> 班友有D似以色列嘅阿拉伯人……投票權要畀掛,唔畀D人危機感咪會重咯,走晒啦,除非外省戰亂嘎啫。唔計深...
撈化粵人 說的就是我喇
你講哩D確實有道理。其實只要保證教育同政府嘅白話地位我就冇乜意見。
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-14
> 我這篇的主要考慮是剛獨立的瞬間,怎麼去保持穩定減少衝突平穩過渡。至於獨立確立後嘛。我可能另外寫一篇文...
我建議將普通話列入選修外語之一主要是考慮國族認同上的去中國化,參考新加坡對待華語的態度。而且過渡期由於教師資源的限制,除了少數精英名校,大部分學校一開始只能開始普通話作爲選修外語。你都提到媒體自由,到時大中華區的電視、網絡節目很普遍,就算小學不專門單列普通話相信也不會失去與北方人交流的能力。
第二是考慮未來激進本土派的情緒,參照現在香港的情況,未來衝突升級,支持粵獨的群體中有相當一部分會在情感上反感普通話。將普通話列入選修外語,他們真心不願意學選學西班牙語、日語都是可以的。而且粵獨後的新優勢是經濟上可以選擇南向,更多與東南亞進行地區整合而不是原本是只服務於大中華。
### 品葱用户 **cansinlej 雜種書記親衛隊** 评论于 2020-02-13
> 我建議將普通話列入選修外語之一主要是考慮國族認同上的去中國化,參考新加坡對待華語的態度。而且過渡期由...
噉索性唔柒教啦。好似我哋老豆老母呢代人讀書教嘅普通話好少嘎咋嘛,咪又一早識聽,而家識講。屌那媽北方電視、頭條app呢D真係毒瘤來。
### 品葱用户 **cansinlej 雜種書記親衛隊** 评论于 2020-02-14
星加坡係教普通話而扼殺閩南話潮州話粵語。反例來嘎。
我只係想講,普通話唔使好似外語噉學,稍為有一個禮拜一堂已經學得識。或者小學可以噉,都係我上邊嗰種建議,不過聯邦語言必修,普通話就選修(實大把人慌死執輸揀,睇下D港爸港媽,哈哈)。
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-13
> 噉索性唔柒教啦。好似我哋老豆老母呢代人讀書教嘅普通話好少嘎咋嘛,咪又一早識聽,而家識講。屌那媽北方電...
不過到時如果北方都脫支解體埋傳媒質素應該會高唔少。睇返你上一個評論講到崔屎安,搞到我都想去重溫佢卸任澳門特首最後嘅演講😂😂😂😂
### 品葱用户 **cansinlej 雜種書記親衛隊** 评论于 2020-02-14
經濟我係希望,廣東做個巨型荷蘭、南韓。要發展高科技工業,面向全世界,唔好再搞埋晒D cheap嘢。以廣東嘅地利同人才,起碼做到荷蘭北歐八成水平啦。只不過支那市場有得食嘅話梗係唔好嘥。
### 品葱用户 **苏维埃督战队 cansinlej** 评论于 2020-02-13
> 是啊,是很理想化。我最擔心的是貨幣和財政。人民幣超發、巨額政府債務的問題對於民主化/獨立威脅很大。我...
广东省银行了解一下?我们只不过是试图恢复她往日的辉煌而已。
廣東省銀行(The Kwangtung Provincial Bank),原稱中央銀行,在民國十三年(1924年)8月,由孫中山小舅宋子文領頭籌辦成立,孫中山當時也曾經在開幕儀式上發表演說。廣東中央銀行是中華民國第一間以中央銀行為名,在中國金融歷史上有一重要的角色。廣州中央銀行成立後負責發行紙幣。後由於各軍閥間混戰,廣東紙幣信用趨於下降。1920年代尾開始,港幣重新取得在廣東金融市場的壟斷地位。
至民國十八年(1929)三月,兩廣政治分會令飭中央銀行改名為廣東中央銀行,以區別南京中央銀行,並在香港開設分行。到1931年9月,廣東中央銀行改組為廣東省銀行。總行位於廣州市長堤西濠口,該處同時是廣東省省庫(Treasury of The Kwangtung Provincial Government)的所在地。省府規定不再發行銀質硬幣,改以毫洋為本位發行紙鈔,即毫洋券,又叫做銀毫券。1935年11月6日廣東省財政廳出臺廣東管理貨幣辦法,指定廣東省銀行所發鈔票,以及廣州市立銀行所發鈔票,為廣東法定貨幣,抗衡中央法幣入粵流通。
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-13
> 星加坡係教普通話而扼殺閩南話潮州話粵語。反例來嘎。我只係想講,普通話唔使好似外語噉學,稍為有一個禮拜...
同感,不過如果並列選修嘅話,我諗修日文嘅都多過修普通話啦,起碼大學入東亞研究係加分項。普通話大把人識應該冇咩人會浪費公立學校嘅免費資源去學。
### 品葱用户 **cansinlej 苏维埃督战队** 评论于 2020-02-13
> 广东省银行了解一下?我们只不过是试图恢复她往日的辉煌而已。廣東省銀行(The Kwangtung P...
大佬,30年代都未發達,中意點印銀紙都得啦。
問題係而家廣東人草咗四十幾年錢,冚唪冷都係死人頭啊。成立新政府印新銀紙,死人頭跳水嗰下,幾十年財富dum落海啦。
個難題就係,點樣可以最快速度喺死人頭變廢紙之前,等廣東人將資產變成黃金/美元/港元/世界貨幣。
### 品葱用户 **苏维埃督战队 cansinlej** 评论于 2020-02-13
> 大佬,30年代都未發達,中意點印銀紙都得啦。問題係而家廣東人草咗四十幾年錢,冚唪冷都係死人頭啊。成立... 個難題就係,點樣可以最快速度喺死人頭變廢紙之前,等廣東人將資產變成黃金/美元/港元/世界貨幣。
采用甚么货币只不过是一纸行政命令强制推行而已。当初人仔取代银元,咪唔系人地老共摞住枪杆硬销?
心心念念挂住保值,咁咪学习人地厄瓜多、巴拿马、辛巴威搅Dollarization?(辛巴威最多曾宣布十余种货币为法定货币)
### 品葱用户 **cansinlej 苏维埃督战队** 评论于 2020-02-14
> 咁咪学习人地厄瓜多、巴拿马搅Dollarization?
我係噉諗啊。初初建國嗰下直接用美金,美金唔夠就攞港紙來用。局勢穩定經濟平穩之後再發行粵國貨幣。但係個問題在於,個政府改貨幣嗰下,或者有風聲洩漏出來,D人一定會爭住去唱外幣,加速質冧人民幣。
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-13
> 我係噉諗啊。初初建國嗰下直接用美金,美金唔夠就攞港紙來用。局勢穩定經濟平穩之後再發行粵國貨幣。但係個...
用美金應該算係建國之後嘅自然過渡?因爲到時嘅地下革命組織買軍火接受捐助都係用美金、Bitcoin。成立新政府穩定經濟之前應該都係會直接繼續用。防止被人仔貶值波及可以試下加印粵國印章,然後限制粵國版人仔與北方嘅流通?噉做應該情況會好少少。
### 品葱用户 **cansinlej 苏维埃督战队** 评论于 2020-02-14
> 采用甚么货币只不过是一纸行政命令强制推行而已。当初人仔取代银元,咪唔系人地老共摞住枪杆硬销?心心念念...
唔係咁兒戲嘎兄台。你銀紙印出來有冇人要,唔係你話幾多就幾多嘎。銀紙可以視作一種貨物。當D人冇信心嗰陣,個個都賣冇人肯買,就會快速貶值。每個人肯以某個價接一種貨幣,係因為佢有合理期望,用呢種貨幣可以換得返等值嘅其它嘢。
共匪發行人民幣,係由「解放區」開始。佔領到邊度,通用範圍就擴展到邊度。D人用銀元換人民幣,因為佢個政府穩定咗,並規定咗國內交易全部用人民幣。
初初獨立嗰陣,D人會唔會覺得呢個政府可以持久呢?如果唔能夠持久,邊有人夠膽用佢嘅貨幣。
即使係政權穩定,發行貨幣都要面對俾人狙擊嘅風險。因為我設想嘅國家係自由市場開放經濟,貨幣應該可以畀人自由兌換。但係粵國政府要發行新貨幣嘅話,諗住用咩方法提供backing呢?而家冇乜人會去狙擊人民幣,因為冇人有人民銀行咁多美元,冇辦法對撼,冇辦法平倉。但係粵國初立嗰陣充其量係香港兩倍。
所以我估計呢,要用一兩年美金/港紙,之後發行新貨幣,亦要學香港噉實施聯繫匯率一段時間,將新貨幣peg美金/一籃子。等到真係政權穩定、經濟正常,先自由浮動。
### 品葱用户 **中国有蜥蛤** 评论于 2020-02-13
没机会了,粤地以后再无粤人了,外省人滚出广东!
### 品葱用户 **cansinlej 雜種書記親衛隊** 评论于 2020-02-13
> 用美金應該算係建國之後嘅自然過渡?因爲到時嘅地下革命組織買軍火接受捐助都係用美金、Bitcoin。成...
我都有噉諗。即使係民主化唔係分裂,我估計各地會自己印人民幣加印XX省。初時係等值嘅。但係慢慢就有一D省嘅人民幣值錢D。我尋日寫咗喺 https://pincong.rocks/article/14384 。
### 品葱用户 **aslohk** 评论于 2020-02-13
因為香港賽馬會太黑,而且澳門豬排包很好吃,所以澳門就跟香港組隊吧。
### 品葱用户 **Suvi 破壁** 评论于 2020-02-14
> 每当看到这种独立建国的帖,我都会入来点下赞。
### 品葱用户 **cansinlej** 评论于 2020-02-14
我覺得還是能吹一波粵人。覺醒的粵人很自然地就支持粵獨或很高程度的聯邦自治。咱這貼都聊到建國方略了,別的人還在吵民國好還是聯邦好還是獨立好。
### 品葱用户 **雜種書記親衛隊 cansinlej** 评论于 2020-02-15
> 我都有噉諗。即使係民主化唔係分裂,我估計各地會自己印人民幣加印XX省。初時係等值嘅。但係慢慢就有一D...
重有一個思路係中國經濟開始逐步崩盤嘅時候,粵獨的地下組織開始涉足黑市貿易。黑市用嘅自然係國際硬通貨美金。同時借黑市呢個平臺喺各地發展商會、工會,最終架空中國政府。
### 品葱用户 **静心斋主** 评论于 2020-02-15
我觉得这种理想只有可能在中国本身四分五裂,其他各省也独立建国的情况下发生,否则中央直接干涉独立省区的各项事务,甚至可能封锁各种资源和劳动力,那就直接崩掉了。
### 品葱用户 **GeeAcc** 评论于 2020-02-14
是很好的理想,但语言文字只能是普通话+粤语+英语,毕竟推普很久了,很难改变习惯.网络也是问题.
### 品葱用户 **drdoom_2009 決不再做奴隸** 评论于 2020-02-14
> 劉老把英文名也替我們想好了:Cantonia.
Cantonia 是2009年“粵嚟粵掂”在粵語協會提出的,要在廣州Canton之上再造一個代表南粵的英文。經過多番討論後粵獨群體妥協使用。你看大粵民國的論壇網址就知道創建時是用namyuekok南越國的。2010年廣州撐粵語行動失敗後粵語協會就把所有粵獨人賬號屏蔽,所有人都轉移到大粵民國的論壇和後來的Facebook page。
不過我也一直有一個懷疑。當時所有我認識的粵獨人都是在粵語協會的一個隱藏子論壇聚集,大粵民國不是我們這群人創建的,因為沒有達成建國共識。而大粵民國臨時政府創建者把damin的權限交給了我和粵嚟粵掂之後就消失了。同期在freeforums.org上還有大吳越國臨時政府,齊洲國臨時政府,回斯坦共和國臨時政府,福建共和國臨時政府現在都無人打理。可不可能在2008年的時候劉仲敬已經在創造諸夏,他好像說過“如果你不代表你自己,就會有人幫你來代表”之類的話。劉創造了很多空殼臨時政府網站,看有沒有人來接。最後唯有大粵民國臨時政府真的給我和“粵嚟粵掂”接了盤,而且創造了英文名稱,國旗和國徽,也有凖國歌,一直堅持運行到現在。多年之後要收成了,諸夏自由同盟就拿著Cantonia名字和旗幟來代表大粵民國。
不過真是如此也無妨,我確實使用了這個殼在粵獨歷史上打了卡,認識了不少志同道合的粵人。
### 品葱用户 **凉拌螃蟹 中国有蜥蛤** 评论于 2020-02-15
> 没机会了,粤地以后再无粤人了,外省人滚出广东!
你要深圳东莞这些怎么做啊,少了那么多外省人,经济都崩溃了,学校都没人教书啦
### 品葱用户 **決不再做奴隸 凉拌螃蟹** 评论于 2020-02-14
> 你要深圳东莞这些怎么做啊,少了那么多外省人,经济都崩溃了,学校都没人教书啦
跟西方國家移民規則一樣。粵國獨立以後,官方語言粵語(或者粵英雙語)。願意學粵語、通過考試的外國人可以申請歸化。不願意學的遞解出境。以後移民署也是這樣處理。願意學粵語的可以申請移民。不願意學粵語的不簽發移民簽證。
### 品葱用户 **尼德兰防化兵** 评论于 2020-02-14
我反对,我希望粤国是一个Sharia law国家,严格执行伊斯兰教法,而不是和基督教徒混在一起。
其实伊斯兰不一定反对诸夏,伊斯兰也有特殊的埃米尔政治,和诸夏相似
### 品葱用户 **尼德兰防化兵 決不再做奴隸** 评论于 2020-02-14
> 跟西方國家移民規則一樣。粵國獨立以後,官方語言粵語(或者粵英雙語)。願意學粵語、通過考試的外國人可以...
为什么不以粤语和阿拉伯语为官方语言呢
### 品葱用户 **凉拌螃蟹 決不再做奴隸** 评论于 2020-02-16
> 跟西方國家移民規則一樣。粵國獨立以後,官方語言粵語(或者粵英雙語)。願意學粵語、通過考試的外國人可以...
其实我感觉实施难度有点大,不过如果教育机构做得好,应该效果不错的。
之前和一个在东莞的外省人聊天,和她讲广东文化,她居然问我广东有什么文化。怪不得出门都不敢说粤语······
小时候外省老师都能学几句粤语,长大之后居然要听那些老师讲那种带着浓厚口音的普通话,课都快听不懂了。
### 品葱用户 **決不再做奴隸 凉拌螃蟹** 评论于 2020-02-15
> 其实我感觉实施难度有点大,不过如果教育机构做得好,应该效果不错的。之前和一个在东莞的外省人聊天,和她...
廣東文化在香港還是保存(隱藏)得比較好的。可以說如同希伯來傳統在歐洲中世紀處於沉睡的狀態。未來有一天中國光復了,廣東文化將會復甦,再次成為中國工業化和資本主義的驅動力。
### 品葱用户 **凉拌螃蟹 決不再做奴隸** 评论于 2020-02-16
> 廣東文化在香港還是保存(隱藏)得比較好的。可以說如同希伯來傳統在歐洲中世紀處於沉睡的狀態。未來有一天...
真心希望如此
### 品葱用户 **鲁提辖拳打习近平 決不再做奴隸** 评论于 2020-02-15
> 跟西方國家移民規則一樣。粵國獨立以後,官方語言粵語(或者粵英雙語)。願意學粵語、通過考試的外國人可以...
恕我直言。你这种想法和二百年前的英国殖民者一样野蛮。这并不是民主政治,而是法西斯主义。负责任预测,如果你这种想法能够获得一定支持并最终成为政策(民众的短视可能会导致种族主义、帝国主义以及法西斯注意,这也是民主的缺陷之一),那么其后果将会是毁灭性的战争。
### 品葱用户 **雜種書記親衛隊 鲁提辖拳打习近平** 评论于 2020-02-15
> 恕我直言。你这种想法和二百年前的英国殖民者一样野蛮。这并不是民主政治,而是法西斯主义。负责任预测,如...
我個人認爲二百年前英國殖民者的民主素養要遠高於現在的中國人。如果廣東光復後成爲一個以色列式的國家其實也是最好的選擇之一。
> [点击品葱原文参与讨论](https://pincong.rocks/article/14376)
|
Java
|
UTF-8
| 4,329
| 1.640625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.greengrass.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.greengrass.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* CreateSoftwareUpdateJobRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateSoftwareUpdateJobRequestMarshaller {
private static final MarshallingInfo<String> AMZNCLIENTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.HEADER).marshallLocationName("X-Amzn-Client-Token").build();
private static final MarshallingInfo<String> S3URLSIGNERROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("S3UrlSignerRole").build();
private static final MarshallingInfo<String> SOFTWARETOUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SoftwareToUpdate").build();
private static final MarshallingInfo<String> UPDATEAGENTLOGLEVEL_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UpdateAgentLogLevel").build();
private static final MarshallingInfo<List> UPDATETARGETS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("UpdateTargets").build();
private static final MarshallingInfo<String> UPDATETARGETSARCHITECTURE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UpdateTargetsArchitecture").build();
private static final MarshallingInfo<String> UPDATETARGETSOPERATINGSYSTEM_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UpdateTargetsOperatingSystem").build();
private static final CreateSoftwareUpdateJobRequestMarshaller instance = new CreateSoftwareUpdateJobRequestMarshaller();
public static CreateSoftwareUpdateJobRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(CreateSoftwareUpdateJobRequest createSoftwareUpdateJobRequest, ProtocolMarshaller protocolMarshaller) {
if (createSoftwareUpdateJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createSoftwareUpdateJobRequest.getAmznClientToken(), AMZNCLIENTTOKEN_BINDING);
protocolMarshaller.marshall(createSoftwareUpdateJobRequest.getS3UrlSignerRole(), S3URLSIGNERROLE_BINDING);
protocolMarshaller.marshall(createSoftwareUpdateJobRequest.getSoftwareToUpdate(), SOFTWARETOUPDATE_BINDING);
protocolMarshaller.marshall(createSoftwareUpdateJobRequest.getUpdateAgentLogLevel(), UPDATEAGENTLOGLEVEL_BINDING);
protocolMarshaller.marshall(createSoftwareUpdateJobRequest.getUpdateTargets(), UPDATETARGETS_BINDING);
protocolMarshaller.marshall(createSoftwareUpdateJobRequest.getUpdateTargetsArchitecture(), UPDATETARGETSARCHITECTURE_BINDING);
protocolMarshaller.marshall(createSoftwareUpdateJobRequest.getUpdateTargetsOperatingSystem(), UPDATETARGETSOPERATINGSYSTEM_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
Markdown
|
UTF-8
| 24,739
| 2.59375
| 3
|
[] |
no_license
|
---
title: '기본적 서버 보안 프로그램, Fail2Ban 사용법 기초부터 실전 사용법까지 알아 보기'
layout: post
author: 안형우
tags:
- serverside
- linux
description: ssh와 apache 무작위 대입 공격(brute forece)을 방어하는 프로그램
image: /uploads/2022/fail2ban-logo.jpg
---
## Fail2Ban이란?
Fail2Ban은 무작위 대입 공격을 방어하는 프로그램이다. ssh라면 비밀번호를 마구 집어 넣어 보는 공격이 해당할 것이고, apache 같은 웹서버라면 `/phpMyAdmin-5/index.php?lang=en` 같은 식으로 찔러 보는 경로에 대한 요청을 검토해 IP를 차단할 수 있다. 다만 웹서버에 대한 공격은 추가 필터를 만들어야 한다. 예컨대 방금 예로 든 phpMyAdmin 폴더를 찔러보는 경우, 실제로 같은 경로에 phpMyAdmin이 있다면 IP를 차단해서는 안 되니까 말이다.
아래는 [Fail2Ban 사이트](https://www.fail2ban.org/wiki/index.php/Main_Page)의 소개다.
> Fail2Ban은 로그 파일을 검사해서 (예컨대 /var/log/apache/error_log) 악의적 징후를 보여 주는 IP를 차단합니다(너무 많은 로그인 실패, 취약점을 찾는 요청 등). 따라서 일반적으로 Fail2Ban은 특정 시간동안 IP 주소를 차단하도록 방화벽 규칙을 업데이트하는 데 사용됩니다. 다른 많은 동작을 설정할 수도 있지만 말입니다(예컨대 이메일 보내기 같은 것). 기본적으로 Fail2Ban은 다양한 서비스를 위한 필터를 포함하고 있습니다(아파치, courier, ssh 등).
>
> Fail2Ban은 잘못된 인증 시도의 비율을 줄일 수 있지만 취약한 인증 방법을 사용하는 데 따르는 위험을 완전히 없애지는 못합니다. 진정으로 서비스를 보호하려면 반드시 2단계 인증이나 공개키/개인키 인증 매커니즘 둘 중 하나를 사용하도록 설정하십시오.
## 기본 설치
우분투라면 아래 명령을 쓴다. 이하 설명은 기본적으로 우툰부(혹은 데비안 계열)에 대한 설명이다. 레드햇 계열이라면 설정 파일 경로나 명령어 같은 게 다를 수 있다.
```
sudo apt install fail2ban
```
설치 직후에 작동을 바로 할 것이다. 그렇지 않다면 맨 밑에 에러 확인 방법을 써 놨으니 확인하라.
## 버전에 대한 이해
Fail2Ban은 `0.9.0` 버전 때 많은 것이 변했다. 이 설명은 `0.9.0` 이후 버전에 대한 설명을 주로 다룬다. 따라서 자신의 버전을 확인해 보자.
```
fail2ban-client --version
# 결과: Fail2Ban v0.11.1
```
내 경우 `0.11.1`이었다.
## 설정 파일 - 기본
설정에 대해 자세히 알고 싶으면 `/etc/fail2ban/jail.conf` 파일의 설정 예시와 설명을 보거나 `man jail.conf` 명령어로 매뉴얼을 연다.
설정 파일 경로는 두 가지 방법으로 만든다. `jail.conf`의 맨 앞부분에 이런 설명이 씌어 있다.
> 대부분의 경우 이 파일을 수정할 필요가 없습니다. 하지만 `jail.local` 파일이나, `jail.d/` 폴더 밑에 각각의 `.conf`로 사용자 설정을 제공합니다.
1. 기본적인 설정은 `jail.conf`에 돼 있다.
2. 설정 내용을 덮어쓰려면 `jail.local`을 만들거나 `jail.d/` 폴더에 `.conf` 확장자로 설정 파일을 만들어서 저장한다.
`jail.d/` 폴더에는 이미 파일이 하나 있다. `sudo cat /etc/fail2ban/jail.d/defaults-debian.conf` 명령으로 파일의 내용을 살펴 보자.
```
[sshd]
enabled = true
```
우리는 여기서 한 가지 문법을 유추할 수 있는데, `[sshd]`는 감시할 필터 규칙을 의미하는 것이고, `enabled = true` 설정으로 이 필터를 활성화한다는 것이다.
### 상태 확인
자, Fail2Ban을 설치한 것만으로 서버는 시작된 것이다. Fail2Ban이 제대로 실행중인지는 아래 명령으로 확인해 보자.
```
sudo fail2ban-client status
```
결과는 아래와 같은 식이다.
```
Status
|- Number of jail: 1
`- Jail list: sshd
```
이로써 우리는 ssh에 대한 무작위 대입 공격을 막을 수 있게 됐다.
만약 실행중이라는 결과가 나오지 않는다면 맨 아래 에러 대응 방법을 써 놨으니 그걸 참고하라.
## 설정 파일 - 한 발짝 더
한 발짝 더 나가보자. `jail.conf`에 있는 설정들을 `jail.local` 파일을 만들어서 덮어쓸 수 있다.
`jail.local` 파일을 만들고 몇 가지 기본 설정을 수정할 생각이다. 선호하는 에디터로 `jail.local` 파일을 열고 아래 설정을 넣는다.
```
[DEFAULT]
# 차단하지 않을 IP
ignoreip = 127.0.0.1/8 ::1 8.8.8.8
# IP 차단을 얼마동안 할지. 기본값은 10m
bantime = 31536000m
```
맨 앞에 우선 차단하지 않을 IP를 설정했다(`ignoreip`). 띄어쓰기로 IP를 여러 개 넣을 수 있다. 우선 로컬 접속 IP가 기본으로 들어가 있고(`127.0.0.1/8`와 `::1`), 내 IP를 `8.8.8.8`이라고 가정했다(`8.8.8.8`은 실제로는 구글이 사용하는 DNS 서버의 IP다). 자신의 IP를 알고 싶다면 구글에서 [what is my ip로 검색](https://www.google.com/search?q=what+is+my+ip)해 본다. 구글이 바로 알려 준다.
두 번째 설정으로, 차단 시간은 기본 10분인데 1년으로 늘렸다.
아래는 차단에 관여하는 설정인데, 기본값을 그대로 뒀지만 복사해서 `[DEFAULT]` 밑에 넣어 두자. 나중에 수정하기 쉽게 하려는 조처다.
```
# findtime 동안 maxretry에 설정된 수만큼 문제가 발견되면 IP를 차단한다.
# 기본값은 10m
findtime = 10m
# IP를 차단할 때까지 최대 실패 횟수. 기본값은 5
maxretry = 5
```
## 추가 필터 활성화
`/etc/fail2ban/filter.d/` 폴더를 보면 여러 필터가 있다. `jail.conf`를 봐도 여러 필터가 있는 것을 확인할 수 있다.
`jail.local`을 열고 Fail2Ban이 기본으로 제공하는 아파치 필터를 넣어 보자. 아까 입력한 `[DEFAULT]` 섹션의 밑에 넣는다.
```
[apache-badbots]
# Ban hosts which agent identifies spammer robots crawling the web
# for email addresses. The mail outputs are buffered.
enabled = true
port = http,https
logpath = %(apache_access_log)s
bantime = 48h
maxretry = 1
```
설정을 보면 `bantime`과 `maxretry`를 필터별로 정의할 수 있다는 것을 알 수 있다.
### logpath 설정 방법
`logpath`라는 새로운 설정값이 나타났는데, `%(apache_access_log)s`라는 모양을 볼 때 `apache_access_log`라는 변수를 사용한다는 것을 유추할 수 있다. 이 변수는 `/etc/fail2ban/paths-common.conf` 파일에 정의돼 있는데, `apache_access_log = /var/log/apache2/*access.log`라고 돼 있다.
그런데 만약 `/var/log/apache2/` 폴더 밑에 여러 가상 호스트별로 폴더를 만들고 로그를 저장하는 경우라면 경로 설정을 어떻게 해야 할까? 아래처럼 하면 된다.
```
logpath = /var/log/apache2/*/*.log
```
로그패스가 제대로 들어갔는지 확인하려면, `fail2ban-client status 필터명` 명령을 사용하면 된다. 아래 설명하고 있으니 계속 따라가 보자.
### 현재까지 `jail.local`의 모습
이로써 지금까지 넣은 `jail.local` 파일은 아래와 같은 모양이 됐다.
```
[DEFAULT]
# 차단하지 않을 IP
ignoreip = 127.0.0.1/8 ::1 8.8.8.8
# IP 차단을 얼마동안 할지. 기본값은 10m
bantime = 31536000m
# findtime 동안 maxretry에 설정된 수만큼 문제가 발견되면 IP를 차단한다.
# 기본값은 10m
findtime = 10m
# IP를 차단할 때까지 최대 실패 횟수. 기본값은 5
maxretry = 5
[apache-badbots]
# 이메일 주소를 크롤링하는 스팸 로봇의 에이전트 문자열을 식별해 IP를 차단한다.
enabled = true
port = http,https
logpath = %(apache_access_log)s
bantime = 48h
maxretry = 1
```
## 설정 적용하기
설정을 변경했으면 다시 읽어야 한다. 아래 명령으로 한다.
```
sudo systemctl reload fail2ban
```
혹은 아래 명령으로 할 수도 있다.
```
sudo fail2ban-server reload
```
이제 필터가 제대로 적용됐는지 확인해 보자.
```
sudo fail2ban-client status
```
아래처럼 Jail list에 `apache-badbots`가 추가됐으면 성공한 것이다.
```
$ sudo fail2ban-client status
Status
|- Number of jail: 2
`- Jail list: apache-badbots, sshd
```
### 개별 필터 확인하기
각 필터의 상태를 따로 확인할 수도 있다. 예컨대 sshd 필터의 상태만 보려면 뒤에 sshd를 붙인다. 그러면 해당 필터가 차단한 IP와 감시하고 있는 로그파일 정보를 볼 수 있다.
```
$ sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
| |- Currently failed: 3
| |- Total failed: 765
| `- File list: /var/log/auth.log
`- Actions
|- Currently banned: 26
|- Total banned: 26
`- Banned IP list: (생략)
```
현재 필터에 걸리는 게 3개, 지금까지 누적해서 걸린 게 765개, 감시하는 파일 경로가 나온다. 그리고 차단한 아이피 개수가 그 밑에 나온다. 차단한 IP의 목록도 나오는 것을 볼 수 있다.
## 사용자 설정 필터 만들어 넣기
Fail2Ban의 필터는 `/etc/fail2ban/filter.d/` 폴더에 있다. 예컨대 `apache-badbots`의 설정은 `/etc/fail2ban/filter.d/apache-badbots.conf`에 있다. 내용은 다음과 같다.
```
# Fail2Ban configuration file
#
# Regexp to catch known spambots and software alike. Please verify
# that it is your intent to block IPs which were driven by
# above mentioned bots.
[Definition]
badbotscustom = EmailCollector|WebEMailExtrac|TrackBack/1\.02|sogou music spider|(?:Mozilla/\d+\.\d+ )?Jorgee
badbots = Atomic_Email_Hunter/4\.0|atSpider/1\.0|autoemailspider|bwh3_user_agent|China Local Browse 2\.6|ContactBot/0\.2|ContentSmartz|DataCha0s/2\.0|DBrowse 1\.4b|DBrowse 1\.4d|Demo Bot DOT 16b|Demo Bot Z 16b|DSurf15a 01|DSurf15a 71|DSurf15a 81|DSurf15a VA|EBrowse 1\.4b|Educate Search VxB|EmailSiphon|EmailSpider|EmailWolf 1\.00|ESurf15a 15|ExtractorPro|Franklin Locator 1\.8|FSurf15a 01|Full Web Bot 0416B|Full Web Bot 0516B|Full Web Bot 2816B|Guestbook Auto Submitter|Industry Program 1\.0\.x|ISC Systems iRc Search 2\.1|IUPUI Research Bot v 1\.9a|LARBIN-EXPERIMENTAL \(efp@gmx\.net\)|LetsCrawl\.com/1\.0 \+http\://letscrawl\.com/|Lincoln State Web Browser|LMQueueBot/0\.2|LWP\:\:Simple/5\.803|Mac Finder 1\.0\.xx|MFC Foundation Class Library 4\.0|Microsoft URL Control - 6\.00\.8xxx|Missauga Locate 1\.0\.0|Missigua Locator 1\.9|Missouri College Browse|Mizzu Labs 2\.2|Mo College 1\.9|MVAClient|Mozilla/2\.0 \(compatible; NEWT ActiveX; Win32\)|Mozilla/3\.0 \(compatible; Indy Library\)|Mozilla/3\.0 \(compatible; scan4mail \(advanced version\) http\://www\.peterspages\.net/?scan4mail\)|Mozilla/4\.0 \(compatible; Advanced Email Extractor v2\.xx\)|Mozilla/4\.0 \(compatible; Iplexx Spider/1\.0 http\://www\.iplexx\.at\)|Mozilla/4\.0 \(compatible; MSIE 5\.0; Windows NT; DigExt; DTS Agent|Mozilla/4\.0 efp@gmx\.net|Mozilla/5\.0 \(Version\: xxxx Type\:xx\)|NameOfAgent \(CMS Spider\)|NASA Search 1\.0|Nsauditor/1\.x|PBrowse 1\.4b|PEval 1\.4b|Poirot|Port Huron Labs|Production Bot 0116B|Production Bot 2016B|Production Bot DOT 3016B|Program Shareware 1\.0\.2|PSurf15a 11|PSurf15a 51|PSurf15a VA|psycheclone|RSurf15a 41|RSurf15a 51|RSurf15a 81|searchbot admin@google\.com|ShablastBot 1\.0|snap\.com beta crawler v0|Snapbot/1\.0|Snapbot/1\.0 \(Snap Shots, \+http\://www\.snap\.com\)|sogou develop spider|Sogou Orion spider/3\.0\(\+http\://www\.sogou\.com/docs/help/webmasters\.htm#07\)|sogou spider|Sogou web spider/3\.0\(\+http\://www\.sogou\.com/docs/help/webmasters\.htm#07\)|sohu agent|SSurf15a 11 |TSurf15a 11|Under the Rainbow 2\.2|User-Agent\: Mozilla/4\.0 \(compatible; MSIE 6\.0; Windows NT 5\.1\)|VadixBot|WebVulnCrawl\.unknown/1\.0 libwww-perl/5\.803|Wells Search II|WEP Search 00
failregex = ^<HOST> -.*"(GET|POST|HEAD).*HTTP.*"(?:%(badbots)s|%(badbotscustom)s)"$
ignoreregex =
datepattern = ^[^\[]*\[({DATE})
{^LN-BEG}
# DEV Notes:
# List of bad bots fetched from http://www.user-agents.org
# Generated on Thu Nov 7 14:23:35 PST 2013 by files/gen_badbots.
#
# Author: Yaroslav Halchenko
```
그런데 apache-badbots 필터는 너무 낡았다. 거의 걸리는 놈이 없다. User Agent String은 쉽게 속일 수 있기 때문이다. 따라서 URL 요청에 따른 악의적 공격을 가려내는 것이 필요할 텐데, 자신의 서버에 따라서 악의적 공격을 가려내야 한다.
내 경우 phpMyAdmin을 사용하지 않으므로 phpMyAdmin 폴더를 요청하는 IP는 악의적 의도를 가졌다고 생각할 수 있다. (다시 말하지만, 서버 상황에 따라 악의적 요청이 무엇인지 서버 관리자가 가려야 한다.)
필터 설정을 모아 두는 폴더에 파일을 만들자. `/etc/fail2ban/filter.d/apache-custom.conf` 파일을 만들고 선호하는 에디터로 연다. (**주의!**: 필터명은 24자를 넘으면 안 된다.)
필터 파일의 규칙은 맨 위에 `[Definition]`이라고 적고, `failregex` 변수와 `ignoreregex` 변수를 설정해 주는 것이다. 설정을 위해 변수도 사용할 수 있다.
나는 `phpmyadmin`이나 `phpMyAdmin`이 들어간 URL을 요청하는 경우 차단할 생각이다. 그러면 아래처럼 쓰면 된다.
```
[Definition]
failregex = failregex = ^<HOST> -.*"(GET|POST|HEAD) /[^ ]*?(?:phpmyadmin|phpMyAdmin)[^ ]*? HTTP.*".*$
ignoreregex =
```
아파치 로그 규칙에 맞춰서 정규식을 썼고, 핵심부는 `phpmyadmin|phpMyAdmin` 부분이다. `|`가 "또는"이라는 뜻이다.
자, 차단할 문자열이 늘어날수록 복잡하니까 `phpmyadmin|phpMyAdmin` 부분을 변수화하자. 아래처럼 하면 된다.
```
[Definition]
badrequests = phpmyadmin|phpMyAdmin
failregex = failregex = ^<HOST> -.*"(GET|POST|HEAD) /[^ ]*?(?:%(badrequest)s)[^ ]*? HTTP.*".*$
ignoreregex =
```
이제 차단하고 싶은 URL 호출이 생길 때마다 `badrequests`에 추가해 주면 된다. 예컨대 `arm63.php`라는 파일은 내 서버에 없는 파일인데, 해커가 설치해서 사용하는 파일이다. `arm63.php`가 포함된 URL을 호출하는 IP를 차단하려면 아래처럼 갱신한다.
```
[Definition]
badrequests = phpmyadmin|phpMyAdmin|arm63\.php
failregex = failregex = ^<HOST> -.*"(GET|POST|HEAD) /[^ ]*?(?:%(badrequests)s)[^ ]*? HTTP.*".*$
ignoreregex =
```
자, 주의할 점이 하나 나왔는데, 정규식에서 `.`은 "한 글자"를 가리키는 뜻을 가진다. 따라서 이스케이핑(`\`)을 해 줘야 실제 `.`이라는 문자를 가리키게 된다. 그래서 `\.`이라고 쓴 것이다.
### 필터 테스트
필터가 제대로 작성됐는지 테스트해 볼 차례다. `fail2ban-regex`라는 프로그램을 사용한다. 아래가 명령을 내리는 방법 설명이다.
```
sudo fail2ban-regex [옵션] <로그> <정규식>
```
로그와 정규식은 파일 경로를 넣어도 되고 문자열을 넣어도 된다. 우리는 파일을 만들었으니 파일 경로를 넣어 주자.
```
sudo fail2ban-regex /var/log/apache2/access.log /etc/fail2ban/filter.d/apache-custom.conf
```
제대로 됐다면 아래처럼 출력될 것이다.
```
Running tests
=============
Use failregex filter file : apache-custom, basedir: /etc/fail2ban
Use log file : /var/log/apache2/access.log
Use encoding : UTF-8
Results
=======
Failregex: 0 total
Ignoreregex: 0 total
Date template hits:
|- [# of hits] date format
| [200] Day(?P<_sep>[-/])MON(?P=_sep)ExYear[ :]?24hour:Minute:Second(?:\.Microseconds)?(?: Zone offset)?
`-
Lines: 200 lines, 0 ignored, 0 matched, 200 missed
[processed in 0.05 sec]
Missed line(s): too many to print. Use --print-all-missed to print all 200 lines
```
로그에 200줄이 있었는데, 무시된 건 0개고, 필터에 걸린 것도 0개라고 한다. 200개는 필터에 걸리지 않은 로그 줄이라고 한다. 필터에 걸리지 않은 로그 줄을 다 보고 싶다면 `--print-all-missed`를 옵션으로 주라고 한다. 만약, 필터에 걸린 놈들만 다 보고 싶다면 `--print-all-matched` 옵션을 넣어 주면 된다.
### Fail2Ban에 커스텀 필터 등록하기
이제 테스트도 통과했으니 커스텀 필터를 등록하자.
선호하는 에디터로 `/etc/fail2ban/jail.local` 파일을 열고 맨 밑에 아래 내용을 추가해 주면 된다.
```
[apache-custom]
enabled = true
port = http,https
logpath = %(apache_access_log)s
maxretry = 2
findtime = 60
```
나는 60초 동안 2번 동안 이 필터에 걸리는 URL 호출을 하면 IP를 차단하게 한 것이다.
Fail2Ban 서버 설정을 리로드하고 상태를 보자.
```
sudo systemctl reload fail2ban
sudo fail2ban-client status
```
아래처럼 등록된 필터로 `apache-custom`이 등장하면 성공한 것이다.
```
Status
|- Number of jail: 3
`- Jail list: apache-badbots, apache-custom, sshd
```
## 완료된 `jail.local` 모습
```
[DEFAULT]
# IP 차단을 얼마동안 할지. 기본값은 10m
bantime = 31536000m
# findtime 동안 maxretry에 설정된 수만큼 문제가 발견되면 IP를 차단한다.
# 기본값은 10m
findtime = 10m
# IP를 차단할 때까지 최대 실패 횟수. 기본값은 5
maxretry = 5
[apache-badbots]
# 이메일 주소를 크롤링하는 스팸 로봇의 에이전트 문자열을 식별해 IP를 차단한다.
enabled = true
port = http,https
logpath = %(apache_access_log)s
bantime = 48h
maxretry = 1
[apache-custom]
enabled = true
port = http,https
logpath = %(apache_access_log)s
maxretry = 2
findtime = 60
```
## 필터로 차단한 IP 목록 보기
어떤 필터가 어떤 IP를 차단하고 있는지 확인하고 싶을 때 아래 명령어를 사용한다.
```
sudo fail2ban-client status <필터이름>
```
`apache-custom`이 차단한 IP 목록을 보고 싶다면 아래처럼 명령을 내린다.
```
sudo fail2ban-client status apache-custom
```
## 아이피 차단 풀기
실수로 차단된 IP가 있다면 두 방법으로 풀 수 있다. 하나는 `jail.local`에 `ignoreip`로 등록하는 것이고, 다른 하나는 명령으로 하는 것이다.
명령어로 차단을 풀려면 아래와 같이 한다. `0.9.0` 이전과 이후가 다른데, 여기서는 `0.9.0` 이후 버전의 명령만 다룬다.
```
sudo fail2ban-client set <filter이름> unbanip <IP주소>
```
그래서 `apache-custom`이 차단한 아이피 `1.1.1.1`을 풀고 싶다면 아래처럼 쓴다.
```
sudo fail2ban-client set apache-custom unbanip 1.1.1.1
```
## 여러 IP 차단 풀기
필터에 상관없이 여러 IP에 대한 차단을 풀 수 있다. 아래 명령을 사용한다.
```
sudo fail2ban-client unban <IP> ... <IP>
```
그러니까, 실제 명령은 이렇게 될 것이다. `1.1.1.1`부터 `1.1.1.4`까지 IP 4개를 차단해제하는 것이다.
```
sudo fail2ban-client unban 1.1.1.1 1.1.1.2 1.1.1.3 1.1.1.4
```
그냥 모든 IP의 차단을 풀어 버리려면 아래 명령을 사용한다.
```
sudo fail2ban-client unban --all
```
## 특정 필터가 차단한 IP 전부 풀기
어떤 경우에는 필터에 심각한 결함이 발견돼, 해당 필터가 차단한 IP를 전부 풀어야 할 수 있다. 그런 경우 우선 해당 필터가 차단하고 있는 IP를 전부 복사한 다음에 여러 IP 차단 풀기 명령을 사용하면 된다. 아래는 `apache-custom` 필터가 차단한 IP를 전부 차단해제하는 예시를 보여 준다. (예시에서 `$`는 프롬프트라는 것을 가리키는 뜻으로 사용한 것이다. 명령어의 일부가 아니다. `$` 없이 시작되는 줄은 출력 내용을 의미한다.)
```
$ sudo fail2ban-client status apache-custom
Status for the jail: apache-custom
|- Filter
| |- Currently failed: 0
| |- Total failed: 34
| `- File list: /var/log/apache2/access.log
`- Actions
|- Currently banned: 2
|- Total banned: 223
`- Banned IP list: 1.1.1.1 1.1.1.2
$ sudo fail2ban-client unban 1.1.1.1 1.1.1.2
```
## 수동으로 IP 차단하기
아래와 같은 식으로 IP를 수동으로 차단할 수 있다.
```
sudo fail2ban-client set <필터이름> banip <IP나열>
```
그러니까 아래와 같은 식으로 한다.
```
sudo fail2ban-client set apache-custom banip 1.1.1.1 1.1.1.2 1.1.1.3 1.1.1.4
```
## 차단한 IP 알림 받기
이건 설명하자면 길다. IP를 차단할 때마다 알림을 받으면 좀 피곤하다. 그래서 Fail2Ban의 sqlite 디비에 접속해서 알림을 보내는 PHP 프로그램을 만들었다. GitLab에 [fail2ban-notification 프로그램의 코드](https://gitlab.com/mytory/fail2ban-notification/)를 공개해 놨으니 참고하면 된다.
## Fail2Ban의 log 파일
log 파일 경로는 `/var/log/fail2ban.log`이다. 아래와 같은 형식으로 돼 있다.
```
2022-01-15 18:50:54,899 fail2ban.filter [10249]: INFO [sshd] Found xxx.xxx.154.120 - 2022-01-15 18:50:54
2022-01-15 18:50:55,372 fail2ban.actions [10249]: NOTICE [sshd] Ban xxx.xxx.154.120
```
## 필터 이름을 지을 때 주의 - 이름 글자수 24자 이하
filter 이름은 최대 24자를 넘으면 안 된다. iptable 설정에서 체인 이름(chain name)은 29자를, 대상 이름(target name)은 28자를 넘기면 안 되는데, fail2ban이 이 이름을 구성할 때 filter 이름을 사용하기 때문이다.
Fail2Ban은 filter 이름 앞에 `f2b-` 접두어를 붙여서 이름을 만든다. 내가 필터 이름을 `apache-mytory-bad-requests`로 했더니 체인 이름과 대상 이름이 `f2b-apache-mytory-bad-requests`으로 30자가 돼 아래와 같은 에러가 발생했다.
```
2022-01-09 07:15:17,928 fail2ban.filter [1103]: INFO [apache-mytory-bad-requests] Found xxx.xxx.52.134 - 2022-01-09 07:15:17
2022-01-09 07:15:18,067 fail2ban.actions [1103]: NOTICE [apache-mytory-bad-requests] Ban xxx.xxx.52.134
2022-01-09 07:15:18,081 fail2ban.utils [1103]: Level 39 7fd340459030 -- exec: iptables -w -N f2b-apache-mytory-bad-requests
iptables -w -A f2b-apache-mytory-bad-requests -j RETURN
iptables -w -I INPUT -p tcp -m multiport --dports http,https -j f2b-apache-mytory-bad-requests
2022-01-09 07:15:18,081 fail2ban.utils [1103]: ERROR 7fd340459030 -- stderr: "iptables v1.6.1: chain name `f2b-apache-mytory-bad-requests' too long (must be under 29 chars)"
2022-01-09 07:15:18,081 fail2ban.utils [1103]: ERROR 7fd340459030 -- stderr: "iptables v1.6.1: Invalid target name `f2b-apache-mytory-bad-requests' (28 chars max)"
2022-01-09 07:15:18,082 fail2ban.utils [1103]: ERROR 7fd340459030 -- stderr: "Try `iptables -h' or 'iptables --help' for more information."
2022-01-09 07:15:18,082 fail2ban.utils [1103]: ERROR 7fd340459030 -- returned 2
2022-01-09 07:15:18,082 fail2ban.actions [1103]: ERROR Failed to execute ban jail 'apache-mytory-bad-requests' action 'iptables-multiport' (이하 생략)
```
## 실행이 안 되는 경우 에러 확인
fail2ban이 실행되지 않는다면 아래 명령으로 에러를 확인한다.
```
sudo fail2ban-server start
```
나 같은 경우 아래와 같은 에러를 만난 적이 있다. 오라클 클라우드의 우분투 서버였다.
```
2022-01-16 07:53:39,944 fail2ban [3011039]: ERROR Failed during configuration: Have not found any log file for sshd jail
2022-01-16 07:53:39,945 fail2ban [3011039]: ERROR Async configuration of server failed
# 아래는 번역
2022-01-16 07:53:39,944 fail2ban [3011039]: ERROR 설정 실패: sshd jail에 대한 로그를 찾지 못했습니다.
2022-01-16 07:53:39,945 fail2ban [3011039]: ERROR 비동기적인 서버 설정이 실패했습니다.
```
**검사용 로그 파일이 없으면 Fail2Ban 서버 시작이 안 된다.**
에러 내용은 `/var/log/auth.log` 파일이 없어서 sshd 실패 검사를 할 수 없고, 그래서 Fail2Ban을 시작할 수 없다는 내용이었다.
확인해 보니 오라클 클라우드의 우분투 서버는 `rsyslog` 패키지가 깔려 있지 않아 `syslog` 등 기본적 시스템 로그를 기록하지 않고 있었다.
아래 명령으로 rsyslog 패키지를 설치했다.
```
sudo apt install rsyslog -y
```
그리고 Fail2Ban 서버를 시작해 보니 제대로 시작됐다.
```
$ sudo fail2ban-server start
Server Ready
```
Fail2Ban 상태를 체크하니 정상 출력됐다.
```
$ sudo fail2ban-client status
Status
|- Number of jail: 1
`- Jail list: sshd
```
## 나가며
이정도면 내가 Fail2Ban을 다루며 익힌 노하우는 대충 다 정리한 것 같다.
|
Python
|
UTF-8
| 728
| 2.734375
| 3
|
[
"ISC"
] |
permissive
|
#!/usr/bin/env python
import argparse
from bikes import TrainTestSets
def parse_args():
"""Parse arguments with argparse."""
parser = argparse.ArgumentParser(description="Load a test set into TrainTestSet.")
parser.add_argument('-t', '--inputfile', dest="inputfile",
help="inputfile that contains the data, .mff format")
args = parser.parse_args()
return args
def create_test_set(inputfile):
"""Input file of test set."""
testset = TrainTestSets("-t %s" % inputfile)
return testset
def main():
"""Main function."""
args = parse_args()
testset = create_test_set(args.inputfile)
print("\n")
print(testset)
if __name__ == "__main__":
main()
|
Go
|
UTF-8
| 1,069
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package platforms
import (
"fmt"
"path/filepath"
"github.com/s0nerik/goloc/goloc"
"github.com/s0nerik/goloc/registry"
)
func init() {
registry.RegisterPlatform(&json{})
}
type json struct{}
func (json) Names() []string {
return []string{
"json",
"JSON",
}
}
func (json) LocalizationFilePath(lang goloc.Lang, resDir goloc.ResDir) string {
return filepath.Join(resDir, fmt.Sprintf("%v.json", lang))
}
func (json) Header(args *goloc.HeaderArgs) string {
return "{\n"
}
func (json) LocalizedString(args *goloc.LocalizedStringArgs) string {
if args.IsLast {
return fmt.Sprintf("\t\"%v\": \"%v\"\n", args.Key, args.Value)
}
return fmt.Sprintf("\t\"%v\": \"%v\",\n", args.Key, args.Value)
}
func (json) Footer(args *goloc.FooterArgs) string {
return "}"
}
func (json) ValidateFormat(format string) error {
return nil
}
func (json) FormatString(args *goloc.FormatStringArgs) string {
return args.Format
}
func (json) ReplacementChars() map[string]string {
return map[string]string{
"\n": `\n`,
"\t": `\t`,
`"`: `\"`,
`\`: `\\`,
}
}
|
Java
|
UTF-8
| 12,186
| 2.984375
| 3
|
[] |
no_license
|
import java.util.Random;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class GameManager extends JFrame implements ActionListener, MouseListener{
Board gameboard;
Gamelogic logic;
JPanel boardPanel;
public boolean isPlaying = false;
private Cell[][] piecePanel;
private int player = 1;
private MinimaxLogic minimaxLogic = new MinimaxLogic();
public GameManager(Board board)
{
gameboard = board;
//gameboard = new Board();
logic = new Gamelogic();
}
public class Cell extends JPanel {
public int x;
public int y;
public Cell (BorderLayout b) {
super(b);
}
};
private JPanel initializePanel() {
JPanel panel = new JPanel(new GridLayout(7, 7));
panel.setSize(new Dimension(500,500));
return panel;
}
private void drawBoard() {
piecePanel = new Cell[7][7];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
piecePanel[i][j] = new Cell(new BorderLayout());
piecePanel[i][j].x = i;
piecePanel[i][j].y = j;
boardPanel.add(piecePanel[i][j]);
piecePanel[i][j].setBackground(Color.WHITE);
piecePanel[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
piecePanel[i][j].addMouseListener(this);
}
}
}
public GameManager() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
//silently ignore
}
setTitle("Chess Game");
setSize(500, 500);
boardPanel = initializePanel();
this.setUpMenu(this);
this.setContentPane(boardPanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.drawBoard();
gameboard = new Board();
gameboard.generateFig5();
logic = new Gamelogic();
}
public void showMessage (String s) {
JOptionPane.showMessageDialog(null, s, "Chess Game Information", JOptionPane.INFORMATION_MESSAGE);
}
ActionListener emptyAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
showMessage("This is woring");
}
};
private ActionListener startAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!isPlaying) {
isPlaying = !isPlaying;
showMessage("Start !");
}
}
};
private void setUpMenu(JFrame window) {
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem start = new JMenuItem("Start");
JMenuItem forfeit = new JMenuItem("Forfeit");
JMenuItem restart = new JMenuItem("Restart");
JMenuItem score = new JMenuItem("Score");
score.addActionListener(emptyAction);
start.addActionListener(startAction);
forfeit.addActionListener(emptyAction);
restart.addActionListener(emptyAction);
menu.add(start);
menu.add(forfeit);
menu.add(restart);
menu.add(score);
menubar.add(menu);
menu.addSeparator();
JMenu modeMenu = new JMenu("Mode");
JMenuItem standard = new JMenuItem("Standard");
JMenuItem custom = new JMenuItem("Custom");
custom.addActionListener(emptyAction);
standard.addActionListener(emptyAction);
modeMenu.add(standard);
modeMenu.add(custom);
menu.add(modeMenu);
window.setJMenuBar(menubar);
}
public Board play()
{
int count = 0;
int player = 1;
int opponent = 2;
while(true)
{
count ++;
if (count ==50){
System.out.println("Draw");
return gameboard;
}
if (reflexMove(player, opponent)) return gameboard;
if(player == 1)
{
opponent = 1;
player = 2;
}
else
{
player = 1;
opponent = 2;
}
gameboard.printGameboard();
System.out.println();
}
}
public Board alphabetareflex(int startPlayer){
int count = 0;
int player = startPlayer;
int opponent = 2;
int step_cost = 0;
boolean first = true;
while(true) {
count++;
if (count == 50) {
System.out.println("Draw");
return gameboard;
}
if (player == 1) {
AlphaBeta alphaBeta = new AlphaBeta(gameboard);
alphaBeta.treeTraversal(alphaBeta.root,0);
step_cost += alphaBeta.expanded_node;
Pair sol = alphaBeta.sol;
MinimaxLogic logic_mini = new MinimaxLogic();
Stone stone = new Stone(sol.getRow(), sol.getCol(), player);
gameboard.setStone(stone);
if(logic_mini.winningCase(gameboard,1) == 10000)
{
System.out.println("Winner is : " + player);
System.out.println("Step Cost is :" + step_cost);
return gameboard;
}
opponent = 1;
player = 2;
} else {
if (first && startPlayer == 2) {
Random rand = new Random(System.currentTimeMillis());
int r = rand.nextInt(7);
int c = rand.nextInt(7);
Pair pos = new Pair(r, c);
Stone stone = new Stone(pos.getRow(), pos.getCol(), player);
gameboard.setStone(stone);
first = !first;
}
else if (reflexMove(player, opponent)) return gameboard;
player = 1;
opponent = 2;
}
gameboard.printGameboard();
System.out.println();
}
}
public Board minimaxreflexplay(int startPlayer){
int count = 0;
int player = startPlayer;
int opponent = 2;
int step_cost = 0;
boolean first = true;
while(true) {
count++;
if (count == 50) {
System.out.println("Draw");
return gameboard;
}
if (player == 1) {
Minimax minimax = new Minimax(gameboard);
minimax.treeTraversal(minimax.root);
step_cost += minimax.expanded_node;
Pair sol = minimax.sol;
MinimaxLogic logic_mini = new MinimaxLogic();
Stone stone = new Stone(sol.getRow(), sol.getCol(), player);
gameboard.setStone(stone);
if(logic_mini.winningCase(gameboard,1) == 10000)
{
System.out.println("Winner is : " + player);
System.out.println("Step cost is :" + step_cost);
return gameboard;
}
opponent = 1;
player = 2;
} else {
if (first && startPlayer == 2) {
Random rand = new Random(System.currentTimeMillis());
int r = rand.nextInt(7);
int c = rand.nextInt(7);
Pair pos = new Pair(r, c);
Stone stone = new Stone(pos.getRow(), pos.getCol(), player);
gameboard.setStone(stone);
first = !first;
}
else if (reflexMove(player, opponent)) return gameboard;
player = 1;
opponent = 2;
}
gameboard.printGameboard();
System.out.println();
}
}
private boolean reflexMove(int player, int opponent) {
Pair possible = logic.winngCheck(gameboard, player);
if(possible != null)
{
Stone stone = new Stone(possible.getRow(), possible.getCol(), player);
gameboard.setStone(stone);
System.out.println("Winner is : " + player);
return true;
}
possible = logic.blockWinner(gameboard,player);
if(possible != null)
{
Stone stone = new Stone(possible.getRow(), possible.getCol(), player);
gameboard.setStone(stone);
}
else if((possible = logic.threeCheck(gameboard,opponent)) != null)
{
Stone stone = new Stone(possible.getRow(), possible.getCol(), player);
gameboard.setStone(stone);
}
else if((possible = logic.winningBlock(gameboard,player)) != null)
{
Stone stone = new Stone(possible.getRow(), possible.getCol(), player);
gameboard.setStone(stone);
}
else
{
possible = logic.firstMove(gameboard,player);
if(possible == null)
{
}
Stone stone = new Stone(possible.getRow(), possible.getCol(), player);
gameboard.setStone(stone);
}
return false;
}
@Override
public void actionPerformed(ActionEvent e) {
}
private void reDraw() {
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
piecePanel[i][j].add(getIcon(gameboard.gameboard[i][j]), BorderLayout.CENTER);
piecePanel[i][j].validate();
}
}
}
public void initGame() {
gameboard = new Board();
gameboard.generateFig5();
boardPanel = initializePanel();
this.setUpMenu(this);
this.setContentPane(boardPanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.drawBoard();
}
@Override
public void mouseClicked(MouseEvent e) {
if (isPlaying) {
Object source = e.getSource();
if (source instanceof Cell) {
Cell cell = (Cell) source;
int row = cell.x;
int col = cell.y;
if (gameboard.gameboard[row][col].getPlayer() == -1) {
gameboard.setStone(new Stone(row, col, 1));
reDraw();
if (minimaxLogic.winningCase(gameboard, 1) == 10000) {
showMessage("Winner is Player 1");
initGame();
isPlaying = !isPlaying;
return;
}
if (reflexMove(2, 1)) {
showMessage("Player 2 won");
initGame();
isPlaying = !isPlaying;
return;
}
reDraw();
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
private JLabel getIcon(Stone stone) {
if (stone == null) {
return new JLabel();
}
if (stone.getPlayer() == 1) {
ImageIcon blackStone = new ImageIcon(System.getProperty("user.dir") + "/resources/blackStone.png");
return new JLabel(blackStone);
}
else if (stone.getPlayer() == 2){
ImageIcon whiteStone = new ImageIcon(System.getProperty("user.dir") + "/resources/whiteStone.png");
return new JLabel(whiteStone);
}
return new JLabel();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame game = new GameManager();
game.setVisible(true);
}
});
}
}
|
Java
|
UTF-8
| 2,338
| 2.96875
| 3
|
[] |
no_license
|
package info.rmarcus.horton;
import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.junit.Test;
public class HortonHashTest {
@Test
public void insertTestBucketSize10() {
Map<Integer, Integer> m = new HortonHashMap<>(1, 10);
Map<Integer, Integer> m2 = new HashMap<>();
Random r = new Random(5);
for (int i = 0; i < 800000; i++) {
int k = r.nextInt();
int v = r.nextInt();
m.put(k, v);
m2.put(k, v);
}
checkMapsEqual(m, m2);
}
@Test
public void insertTestBucketSize16() throws FileNotFoundException {
Map<Integer, Integer> m = new HortonHashMap<>(1, 16);
Map<Integer, Integer> m2 = new HashMap<>();
Random r = new Random(5);
for (int i = 0; i < 800000; i++) {
int k = r.nextInt();
int v = r.nextInt();
m.put(k, v);
m2.put(k, v);
}
checkMapsEqual(m, m2);
}
@Test
public void insertTestBucketSize32() throws FileNotFoundException {
Map<Integer, Integer> m = new HortonHashMap<>(1, 32);
Map<Integer, Integer> m2 = new HashMap<>();
Random r = new Random(5);
for (int i = 0; i < 800000; i++) {
int k = r.nextInt();
int v = r.nextInt();
m.put(k, v);
m2.put(k, v);
}
checkMapsEqual(m, m2);
}
@Test
public void insertTestBounded() {
Map<Integer, Integer> m = new HortonHashMap<>(1, 10);
Map<Integer, Integer> m2 = new HashMap<>();
Random r = new Random(5);
for (int i = 0; i < 2000000; i++) {
int k = r.nextInt(100);
int v = r.nextInt();
m.put(k, v);
m2.put(k, v);
}
checkMapsEqual(m, m2);
}
private <K, V> void checkMapsEqual(Map<K, V> m1, Map<K, V> m2) {
for (Entry<K, V> e : m1.entrySet()) {
assertTrue(e.getKey() != null);
assertTrue(e.getValue() != null);
assertTrue(m2.containsKey(e.getKey()));
assertTrue("Key " + e.getKey() + " should have value " + e.getValue() + " in m2", m2.get(e.getKey()).equals(e.getValue()));
}
for (Entry<K, V> e : m2.entrySet()) {
assertTrue(e.getKey() != null);
assertTrue(e.getValue() != null);
assertTrue("m1 should contain key " + e.getKey(), m1.containsKey(e.getKey()));
assertTrue(m1.get(e.getKey()).equals(e.getValue()));
}
}
}
|
Markdown
|
UTF-8
| 166,946
| 3.375
| 3
|
[] |
no_license
|
[toc]
# Go语言学习笔记
**Go 语言中文网站API:https://studygolang.com/pkgdoc**
## 一、GO语言的特点:
> GO 语言既能够达到**静态编译语言的安全与性能**,又能够达到**动态语言开发维护的高效率**。如果使用一句话来表达GO语言的话:GO = C + Python;*它既能够达到C静态语言程序的运行速度,又能够达到P原合同动态语言的快速开发。*
>- 继承了C语言的很多语法,控制结构,基础数据类型,指针等。
>- 引入**包的概念** ,用于组织程序结构,GO语言的一个文件属于一个包,不能单独存在。
>- 垃圾回收机制,内存自动回收,不需要开发人员管理。
>- 天然并发(重要特征)。
> - 语言层面支持并发,实现简单。
> - goroutine,轻量级线程,可实现大并发处理,高效的利用多核。
> - 使用CPS并发模型实现并发。
>- 吸收了管道通信机制,形成Go语言特有的管道之间的通信。
>- 函数能够实现多个返回值。
>- 新的特性:比如切片 slice 、延时执行 defer。
>- Golang中没有构造函数,当需要创建构造器的时候,可以使用 工厂模式 来进行创建。
### 1、简介:
>- 一个程序就是一个世界。
>- 变量是程序的基本组成单位。无论是哪种高级程序语言编写程序,变量都使其程序的基本组成单位。
### 2、变量的介绍:
1)**变量的概念**:变量相当于内存中一个数据存储空间的表示,通过变量名可以来访问到变量值。
2)**变量的使用步骤**(*声明的变量必须要被使用*):
>- 声明变量
>- 给变量赋值
>- 使用变量
### 3、变量的使用:
```Go
package main
import "fmt"
func main(){
//定义了一个int类型的变量i
var i int
var id = 10
var age int = 18
//给变量 i 赋值
i = 10
//输出
fmt.Println(i);
}
```
### 4、变量使用的注意事项
**1)变量表示内存中的一个存储区域,该区域有自己的名称(变量名)与类型(数据类型)。**

**2)Golang变量声明及使用的三种方式:**
>- 指定变量类型,声明以后若不赋值,使用默认值。例如:var num int,int类型的初始值为0,string类型值为null,小数类型值为0。
>- 根据值自行判断变量类型(类型推导)。例如:var num = 10.11
>- 省略 var 关键字,注意::= 左边的变量不应该是已经声明过了的,否则会导致编译错误。例如:name = "tom"
>- 一次性多变量声明:
> - 例1:var n1,n2,n3 int
> - 例2:var id,name = 100,"张世林"
> - 例3:id,name,password := 100,"张世林","123456"
>- 声明全局变量:声明在函数外的变量
> - 在函数外定义单个全局变量: var id = 10;
> - 在函数外定义多个全局变量: var(
text = "啦啦啦"
sum = 0
)
>- 一个变量的数据值可以在同一类型范围内不断变化value。如果将int类型的数据赋值为 12.3类型的话,就会报错。
### 5、变量之间使用 + 连接
>- 两边都是数值类型时,则做加法运算。
>- 两边都是字符串时,则做字符串拼接。
### 6、Go语言基本数据类型

### 7、整数类型基本介绍:
<font color=#D2691E size=5>有符号的整数类型:</font>

<font color=#D2691E size=5>无符号的整数类型:</font>

<font color=#D2691E size=5>int、unit、rune、byte四种类型:</font>

> **注意:**
>- Golang的整数类型分为:有符号与无符号类型,int uint32 类型和操作系统有关。
>- Golang的整型类型默认声明为 int 类型。
>- 查看某个变量的字节大小与数据类型:调用 printf() 方法
> - 查看数据类型: printf("数据类型为 %T",i)
> - 查看数据占用字节数:先引入包unsafe,再调用 printf("字节大小为 %d",unsafe.Sizeof(i))
>- Golang程序中,遵守保小不保大的原则,即:在保证数据正常运行的情况下,使用的空间更小更好。
>- 计算机中最小存储单位为 bit ,byte 则是计算机中基本存储单元。8 bit = 1 byte。
### 8、小数类型/浮点型
<font color=#D2691E size=5>小数类型:float32与float64 </font>

> **注意:**
>- Golang浮点类型有固定的范围与长度,不受操作系统的影响。
>- Golang的浮点型默认声明为float64类型。
>- 通常使用float64类型来更加精确的保证数据的精确性。
>- 浮点数的两种计数方式:
> - 十进制数形式 : 5.123 而 0.123 可以表示为 .123
> - 科学计数法表示 :(5.1234e2)---表示的是(5.1234 * 10的二次方) |||| (5.1234e-2)---表示的是(5.1234 * 10的负二次方)
### 9、字符类型 -- byte
**基本介绍:**
>- Golang中没有专门的字符类型,如果需要存储单个字符,一般使用 byte 来进行存储。
>- Golang中的自妇产室友一串固定长度的字符连接起来的字符序列。也即是说 **Go语言中的字符串是由单个字节** 连接起来的(传统的字符串是由单个字符组成的)。
>**注意:**
>- 如果保存的字符在ASCLL表中,则可以直接使用 byte 数据类型来今夕你保存。
>- 如果保存的字符超出了ASCLL表的范围,则可以使用 int 类型来进行保存。
> - 例如:保存ASCLL表中的单个字符--- var c1 byte = 'a'
> - 例如:保存超出了ASCLL表中的单个字符--- var c2 int = '中'
>- 如果需要输出字符,则:fmt.Printf("%c",c1)
>- Go语言中使用的是UTF-8编码格式。而字符的本质解释一个整数,直接输出的话,就是对应着UTF-8编码的码值。
>- 字符类型是可以进行运算的,它是对应的Unicode码。
>**字符转换流程:**
>- 字符的存储:字符->对应码值->二进制->存储
>- 字符的读取:二进制->对应码值->字符->读取
### 9、布尔类型 -- bool
**基本介绍:**
>- 布尔类型也叫bool类型。bool类型只允许类型的只有 true 与 false 。
>- 布尔类型占用一个字节。
>- 布尔类型适用于逻辑运算,一般用于流程控制等。比如:if条件控制语句、for循环控制语句。
>- 使用方法 : var b bool = false
### 10、字符串类型 -- string
**基本介绍:**
>- **字符串就是一串固定长度的字符连接起来的字符序列。Go语言的字符串是由单个字符组合连接而成的。** Go语言的字符串的自己使用的是UTF-8编码标识Unicode文本。
>**注意:**
>- 使用方式 : var c3 string = "阿瑟东 asdf45a"
>- Go语言中的字符串一旦赋值以后,字符串的value就不能够修改。
>- 字符串的两种表现形式:
> - 双引号,嫩公仔双引号里面识别转义字符。
> - 反引号。以字符串的原生形态来进行输出,避免了安全问题。 例如: c5 := `asd\nadsaas`
>- 字符串的拼接方式:
> - 第一种方式:var c6 = c5 + c3 (将 c3 与 c5 字符串拼接在一起)
> - 第二种方式:c6 += "haha" (意思是在c6字符串后面添加 ‘haha’ 字符串)
>- 添加的字符串太多,需要换行的时候,加号必须放在上一行的末尾。
### 11、Golang中基本数据类型的默认值:
在程序中,数据类型都有一个默认值,在程序员没有赋值的时候,就会保留默认值,又称为**零值**。
数据类型 | 默认值(零值)
---|---
整型 | 0
浮点型 | 0
字符串 | ""
布尔类型 | false
### 12、基本数据类型的相互转换
**1)简介:**
> Golang和java不同,Go语言在不同类型的变量之间赋值的时候需要显示转换。也就是说**Golang中数据类型不能自动转换。**
**2)基本语法:**
> 表达式: T(v) --- 将 v 的数据类型转换为 类型T。
> - 例1:将整型转换为float32类型
>```Go
>var c1 int = 123455
>c2 := float32(c1)
>```
> - 例2:将float32型转换为整型类型
>```Go
>var c1 float32 = 123455
>c2 := int(c1)
>```
> **注意:**
>- 数据类型的转换:小范围--->大范围 大范围--->小范围
>- 被转换的变量不会发生变化,只是将转换后的数据赋值给其他变量。
>- 被转换的数据不能够超出范围转换的类型的数据范围,否则会造成数据溢出,会造成数据的结果的不一致。
### 13、基本数据类型与string类型的转换
**1)简介:**
> 在程序开发中,经常将基本数据类型转换为string类型;或者将string类型转换为基本数据类型。
**2)基本数据类型-->string类型:**
>- <font color=#D2691E>方法一:fmt.Sprintf()方法</font>

>- <font color=#D2691E>方法二:使用 strconv包 里面的四个函数</font>
> - func FormatBool(b bool) string
> - func FormatInt(i int64, base int) string
> - func FormatUint(i uint64, base int) string
> - func FormatFloat(f float64, fmt byte, prec, bitSize int) string

>- <font color=#D2691E>方法三:使用 strconv包 里面的Itoa函数,直接将int类型转换为字符串</font>
> - func Itoa(i int) string 例如:str := Itoa(num)
**3)string类型-->基本数据类型:**
>- <font color=#D2691E>方法一:使用 strconv包 里面的四个函数</font>
> - func ParseBool(str string) (value bool, err error)
> - func ParseInt(s string, base int, bitSize int) (i int64, err error)
> - func ParseUint(s string, base int, bitSize int) (n uint64, err error)
> - func ParseFloat(s string, bitSize int) (f float64, err error)
> **注意:**
>- string转向基本数据类型,必须确定数据的有效性。
### 14、标准输出的 %X 所代表的的意思:
> 通用:
>- %v 值的默认格式表示
>- %+v 类似%v,但输出结构体时会添加字段名
>- %#v 值的Go语法表示
>- %T 值的类型的Go语法表示
>- %% 百分号
> 布尔值:
>- %t 单词true或false
> 整数:
>- %b 表示为二进制
>- %c 该值对应的unicode码值
>- %d 表示为十进制
>- %o 表示为八进制
>- %q 该值对应的单引号括起来的go语法字符字面值,必要时会采用安全的转义表示
>- %x 表示为十六进制,使用a-f
>- %X 表示为十六进制,使用A-F
>- %U 表示为Unicode格式:U+1234,等价于"U+%04X"
> 浮点数与复数的两个组分:
>- %b 无小数部分、二进制指数的科学计数法,如-123456p-78;参见strconv.FormatFloat
>- %e 科学计数法,如-1234.456e+78
>- %E 科学计数法,如-1234.456E+78
>- %f 有小数部分但无指数部分,如123.456
>- %F 等价于%f
>- %g 根据实际情况采用%e或%f格式(以获得更简洁、准确的输出)
>- %G 根据实际情况采用%E或%F格式(以获得更简洁、准确的输出)
> 字符串和[]byte:
>- %s 直接输出字符串或者[]byte
>- %q 该值对应的双引号括起来的go语法字符串字面值,必要时会采用安全的转义表示
>- %x 每个字节用两字符十六进制数表示(使用a-f)
>- %X 每个字节用两字符十六进制数表示(使用A-F)
### 15、指针
**1)简介:**
>- 基本数据类型,变量存的就是指,也叫值类型。
>- 获取变量的地址,使用 & 符号。例如:&num 。下面是变量的内存模型。

>- 指针类型,就是指 **指针变量存的是一个内存地址**,而这个指针也具有一个**一个内存地址**。下面是指针内存图:指针 ptr 的变量值为 变量i的地址,而指针也具有一个内存地址。

>- 指针的使用方式:
> - 创建变量:var num int =12
> - 创建指针: var ptr *int= &num
> - 输出指针所存放的值:fmt.Printf("指针ptr的value为 %v \n",**ptr**)
> - 输出指针对应的内存的地址:fmt.Printf("指针ptr自己的地址为 %v \n",**&ptr**)
> - 输出指针存放的地址对应的value:fmt.Printf("指针ptr存放的地址的那个值为 %v",***ptr**)
> - 使用指针存放的地址对应的value(也就是 *ptr)来改变value的num变量的值。 *ptr--
**2)指针数据类型:**
> 值类型,都有对应的指针类型,形式为 *数据类型。比如int类型的指针为 *int,float32对应的指针为 *float32。
> 值类型包括:基本数据类型 int系列、float系列、bool、string、数组和结构体struct。
### 16、值类型与引用类型
**1)值类型:** 基本数据类型 int系列、float系列、bool、string、数组与结构体struct。
**2)引用类型:** 指针、slice切片、map、管道chan、interface等都是引用类型。
**3)值类型的特点:**
> 在值类型中,变量直接存储值,内存通常在栈中分配。内存中的模型为:

> 在引用类型中,变量存储的是一个地址,这个地址对应的空间才是真正存放的value。内存通常在堆中分配。当没有任何变量引用这个跟地址是,改地址就变成了一堆垃圾,由GC负责回收。

> 堆、栈的模型为:

### 17、标识符
**1)概念:**
>- Golang对各种变量、方法、函数等命名时使用的字符序列称为标识符。
>- 范式自己可以起名字的地方都叫标识符。
**2)标识符命名规则:**
>- 由26个英文字母大小写,0-9,_组成。
>- 数字不可以开头。
>- Golang中严格区分大小写。
>- 标识符不能包含空格。
>- 下划线“_”本身就是Go语言中的一个特殊标识符,称为“空标识符”。可以代表任何其他的标识符,然而它的值会被忽略(比如用作某个不重要的返回值)。所以仅能被作为占位符使用,而不能被作为标识符使用。
>- 不能够一系统**保留关键字**作为标识符。
系统中保留关键字有:

系统中预定义标识符:

**3)注意:**
>- 包名:保持package的名字与目录保持一致。尽量采取有意义的包名,且需要避免与标准库冲突。
>- 变量名、函数名、常量名都采用驼峰命名法。
>- **如果变量名、函数名、常量名首字母大写,则可以被其他的包访问;如果首字母小写,则只能在本包中使用。简单的理解就是:首字母大写就是公开的,首字母小写就是私有的。**
**4、两个包之间的数据引用方法:**
>- 第一步:创建被调用的包里面的数据:创建utils包下的 util.go 文件
```Go
package utils
import (
"fmt"
)
var Num int = 8
func Test(){
fmt.Println("测试成功")
}
```
>- 第二步:创建主包 main 下的 main.go 文件,然后再引入utils包下的资源,最后对utils包中的资源进行调用。
> 注意:
> - ① 是直接使用 包名+变量名/函数名/常量名 来对其他包的资源进行调用。
> - ② import的路径是GOPATH环境变量的src目录后的目录所有路径需要写入到import中。
```Go
package main
import (
"fmt"
"go_code/project01/utils"
)
func main(){
fmt.Println(utils.Num);
utils.Test()
}
```
### 18、常量const
#### 1)语法格式:
格式一: const 常量名 常量类型 = 常量的value
格式二: const 常量名 = 常量的value
例如:
```
const name = "张世林"
const text string = "come to here"
```
#### 2)常量使用细节:
- 常量是使用 const 关键字修饰。
- 常量在初始化的时候,必须附初始值。
- 常量不能够修改。
- 常量只能修饰 bool、string、int、float类型。
- **常量仍然是通过首字母大小写来控制访问的权限。**
#### 3)常量简单写法:
```
const (
a = 1
b = 2
)
//输出结果为: a=1,b=2
const (
a = iota
b
c
)
//输出结果为: a=0,b=1,c=2
```
## 二、Go语言运算符
运算符是一种特殊的符号,用以表示数据的运算、赋值、比较等。运算符的种类为:
>- 算术运算符
>- 赋值运算符
>- 比较运算符/关系运算符
>- 逻辑运算符
>- 位运算符
>- 其他运算符
### 1、算数运算符
**1)简介:** 算术运算符是对数字运算符的变量进行运算的。比如:加减乘除。
**2)算术运算符预览:**

**3)注意:**
>- 对于除号 "/",它除以整数的话,就只保留整数;它除以小数的话,就会保留小数点后面的数据。
>- 对于取模 "%",它的公式为:a % b = **a - a / b * b**
>- Go语言中的自增自减只能够当做一个独立语言使用(也就是只能在单行执行语句 i++ )。例如:i++ 正确;而 a = i++ 错误。
>- Go语言中的 ++ 与 -- 运算符只能够放在变量的后面,不能够写在变量前面。
### 2、关系运算符
**1)简介:**
>- 关系运算符的结果都是bool类型,也就是true或者false。
>- 关系表达式经常用在 if结构 **的条件中** 或者 **循环结构** 中。
**2)关系运算符预览:**

**3)注意:**
>- 关系运算符只有true或者false两个值的类型。
>- 关系运算符组成的表达式称为 关系表达式。
>- 比较运算符 "==" 不能够写成 "="。
### 3、逻辑运算符
**1)简介:** 用于连接多个表达式,最终的结果也是一个true或者false。
**2)逻辑运算符预览:**
>- **&&** ---逻辑与运算,如果两边的操作数都为真,结果为真,否则为false。也称为**短路与**,如果第一个条件为假,后面的条件不会去继续进行判断。
>- **||** ---逻辑或运算,如果两边的操作数有一个为true,则结果为true,否则为false。也称为**多路或**,如果第一个条件为true,则第二个条件不会继续进行判断。
>- **!** ---逻辑非运算,如果条件为真,则值为false,条件为false,则值为true。
### 4、赋值运算符
**1)简介:** 将某个运算后的值,赋值给指定变量。
**2)赋值运算符概览:**


**3)注意:**
>- 运算顺序从左到右,赋值运算符左边只能是变量,右边可以是变量、常量、表达式。
### 5、位运算符
**2)位运算符概览:**

### 6、其他运算符
运算符 | 描述 | 实例
---|---|---
& | 返回变量的存储地址 | &a 返回 a 的存储地址
* | 指针变量 | *a 是一个指针变量
### 7、运算符优先级序列:

### 8、键盘输入语句:
方法一:使用fmt包中的 func Scanln() 方法。
```
package main
import "fmt"
func main(){
var i int
fmt.Scanln(&i)
fmt.Println(i)
}
```
方法二:使用fmt包中的 func Scanf() 来标准的执行输入,根据空格、逗号等方式来进行隔断输入数据。
```
package main
import "fmt"
func main(){
var i int
var j int
var k int
fmt.Scanf("%d,%d,%d",&i,&j,&k)
fmt.Println(i+j+k)
}
```
### 9、位运算
#### Golang中有三个位运算符:
运算符 | 符号 | 运算规则
---|---|---
按位与 | & | 同一为1,否则为0
按位或 | 一个竖线 | 有一为一,否则为0
按位异或 | ^ | 两者必须有一个为1,一个为0才为1,否则为0。
#### 注意:
- 计算机在做位运算的时候,都是**使用补码来进行位运算**的。
- **补码之间的运算,算出来的结果也是补码**,如果需要得到结果,那么可以必须将补码转换为原码。
---
例如:2&3 的结果为 2
> 解析过程:
> 2的补码为:0000 0010
> 3的补码为:0000 0011
> 根据 与 的规则,同一为一,则结果为: 0000 0010 == 2 ,所以结果为2.
---
例如:2|3 的结果为 3
> 解析过程:
> 2的补码为: 0000 0010
> 3的补码为: 0000 0011
> 根据 或 的规则,有一为一,则结果为: 0000 0011 == 3 ,所以结果为3.
---
例如:-2^3 的结果为 -3
> 解析过程:
> -2的补码为: 1111 1110
> 3的补码为: 0000 0011
> 根据 异或 的规则,两个中有一个0与一个1,则为1,否则为0: 1111 1101
> 然后再将补码转换为反码: 1111 1100
> 最后将反码转换为原码: 1000 0011 == -3
#### Golang中两个移位运算符
运算符 | 符号 | 运算规则
---|---|---
右移运算符 | >> | 低位溢出,符号位不变,并用符号位补溢出的高位。
左移运算符 | << | 符号位不变,低位补0.
**注意:**
其实也就是移动数据多少位而已。
### 10、程序流程控制
#### 程序流程控制的分类:
- 顺序控制
- 分支控制
- 循环控制
#### 1)顺序控制
从上到下逐行的执行,中间没有任何判断与跳转。
#### 2)分支控制
##### if单分支控制
执行代码为:
```
if 条件表达式 {
//执行代码块
}
```
##### if双分支控制
执行代码为:
```
if (a > 3) {
fmt.Println(a)
} else {
fmt.Println(a-1)
}
```
##### if多分支控制
执行代码为:
```
if a > 3 {
fmt.Println(1)
} else if a == 3 {
fmt.Println(2)
} else {
fmt.Println(3)
}
```
#### 注意:
- if 后面的条件表达式尽量不使用小括号。
- else 不能够单独占一行,只能够跟在 if 标签的反大括号的后面。
- if 标签与 else 标签都必须添加 大括号。
- if 标签的 条件表达式 中能够申明一个变量,只能够在条件表达式中使用。例如:
```
if age := 20;age > 18 {
}
```
##### switch分支结构
**基本介绍:** switch语句用于基于不同条件执行的不同动作,每一个case分支都是唯一的,从上下文中逐一尝试,直到匹配位置。
**注意:**
- switch的case后面不需要break,默认自带了break。
- 如果switch无匹配到的数据,则执行default中的代码。
- case后面的表达式能够有多个,使用逗号分开。
- default不是必须存在的。
- switch后面可以不带表达式,直接执行case中的代码。
执行结构为:
```
switch 条件表达式 {
case 表达式一,表达式二 :
fmt.Println(1)
case 表达式一,表达式二 :
fmt.Println(2)
default:
fmt.Println(3)
}
```
执行代码为:
```
switch a/2 {
case 1,2 :
fmt.Println(1)
case 3,4 :
fmt.Println(2)
default:
fmt.Println(3)
}
```
#### 循环控制
操作模式一:
```
for 初始化变量/变量; 循环条件表达式 ; 循环变量迭代 {
//中间操作。
}
//例如:
for a = 3;a < 10;a++ {
fmt.Println(a)
}
```
操作模式二:
```
for 循环条件表达式 {
//中间操作
}
//例如:
for a < 10 {
fmt.Println(a)
a++
}
```
操作模式三:
```
for {
//中间操作,相当于无限循环,需要与break结合来停止循环。
}
//例如:
for {
if a < 10 {
fmt.Println(a)
a++
} else{
fmt.Println("循环终止")
break;
}
}
```
#### break的完整使用
##### 1、直接跳出当前循环
使用方式:
```
for i:=1;i<9;i++ {
if i ==7 {
break
}
}
```
##### 2、跳出指定的某个循环
使用方式:
```
a1:
for k:=1;k<5;k++ {
fmt.Printf("k的值为:%d\n",k)
a2:
for j:=1;j<=k;j++ {
fmt.Printf("J的值为:%d\n",j)
if j == 2 {
break a2
}
}
if(k == 4) {
break a1
}
}
```
#### continue 完整使用
##### 1、基本介绍:
continue语句用于结束本次循环,继续执行下一次循环。continue语句出现在多层嵌套的循环语句体中时,可以通过标签指明要跳过哪一层循环。
##### 2、结束本次循环
使用方式为:
```
for o :=0;o<10;o++ {
if o ==2 {
continue;
}
fmt.Println(o)
}
```
##### 3、跳过某一层循环
使用方式为:
```
a1:
for p := 0;p<5;p++ {
fmt.Println(p)
for q := 0;q<=p;q++ {
if q ==2 {
continue a1;
}
fmt.Println(q)
}
}
```
#### goto 完整使用
##### 1、基本介绍:
Go语言中的 goto语句能够实现无条件的转移到程序中指定的标签的位置。
##### 2、注意:
Go语言中不推荐使用 goto语句,以免造成程序混乱。
##### 3、使用方式:
执行代码为:
```
if a<10 {
goto lable;
}
var k int;
lable;
k++;
```
## 三、Go语言的函数、包与错误处理
### 1、Go语言函数
#### 1)函数的基本语法
##### 格式:
```
func 函数名 (形参列表) (返回值列表) {
//中间操作
return 返回值列表
}
```
##### 注意:
- 形参列表能够有多个数据,中间使用逗号隔开。
- 形参的形式是 参数名在前,参数类型在后。
- 返回值列表可以有多个,使用逗号隔开。
- 返回值只需要有参数的类型即可。
##### 简单代码:
```
func main(){
var n1 int
var n2 int
fmt.Println("请输入两个整数:")
fmt.Scanf("%d %d",&n1,&n2 )
n3 := a1(n1,n2)
fmt.Println(n3)
}
func a1 (n1 int,n2 int) int {
return n1+n2
}
```
#### 函数返回多个值
使用多个变量来接收函数的返回值。
```
func main(){
var n1 int
var n2 int
fmt.Println("请输入两个整数:")
fmt.Scanf("%d %d",&n1,&n2 )
n4,n5 := A2(n1,n2)
fmt.Println(n4)
fmt.Println(n5)
}
func A2 (n1 int,n2 int) (int,int) {
return n1+n2,n1-n2
}
```
**注意:** 如果不需要接收那么多的返回值,可以使用 _ 占位。而 _ 占位的那个返回值无任何意义。
```
func main(){
var n1 int
var n2 int
fmt.Println("请输入两个整数:")
fmt.Scanf("%d %d",&n1,&n2 )
n3 := utils.A1(n1,n2)
fmt.Println(n3)
_,n5 := A2(n1,n2)
fmt.Println(n5)
}
func A2 (n1 int,n2 int) (int,int) {
return n1+n2,n1-n2
}
```
### 2、Go语言包
#### 1)简介:
包的概念是将多个 .go 文件进行逻辑的分开,避免集中在一起混乱。
#### 2)操作方式:
第一步:创建一个utils包,包里面创建一个 util1.go 文件,文件中存放一个函数:
```
package utils
func A1 (n1 int,n2 int) int {
return n1+n2
}
```
第二步:创建一个主函数的main包,里面存放的是主函数 main.go 文件。如果需要调用utils包下面的函数,则需要在import中引入这个对应的包的路径。
```
package main
import(
"fmt"
"go_code/chapter03/func1"
)
```
第三步:真正调用函数的时候,需要使用 **包名+函数名** 的方式进行调用。
```
func main(){
var n1 int
var n2 int
fmt.Println("请输入两个整数:")
fmt.Scanf("%d %d",&n1,&n2 )
n3 := func1.A1(n1,n2)
fmt.Println(n3)
}
```
#### 注意:
- 当需要引入外界的函数的时候,外界的函数名必须要大写,否则访问权限不够。
- 当文件进行打包的时候,一个包对应的就是一个文件夹。
- 当使用 import 导入包的时候,路径是从 GOPATH 路径下的 src 路径后面的路径。
- 同一个包名下,不能够有相同的 函数名 以及 全局变量名。
- 可以为包名取别名,当调用的时候直接使用别名即可。例如:
```
import(
"fmt"
utils "go_code/chapter03/func1"
)
```
### 3、Go语言内存结构
#### 栈区:
基本数据类型一般存储在栈区(使用的是编译器的逃逸机制来进行区分的)。
#### 堆区:
引用数据类型一般存储在堆区(也是使用编译器的逃逸机制来进行区分的)。
#### 代码区:
代码存放的位置。
### 4、函数的递归调用
#### 1)基本介绍:
一个函数在函数体内又调用了本身,我们称为递归调用。
### 5、函数的注意事项
- 函数的形参列表与返回值都可以为多个。
- 函数列表和返回值列表的数据类型可以是值类型和引用类型。
- 函数的命名遵循标识符命名规范,首字母不能使数字,注意首字母的大小写的使用场景。
- 函数中的变量是局部变量,函数外面不生效。
- **基本数据类型和数组默认是值传递** 的,即进行值拷贝操作,在函数中对数组进行操作,不会影响原来的数据。
- 如果希望函数内的变量能够修改函数外的变量,可以传入变量的地址&,函数内以指针的方式进行操作变量,效果类似于引用。
- Go语言不支持函数重载
- Go语言中 **函数也是一种数据类型**,可以复制给一个变量,则该变量的数据类型就是一个函数类型的变量。
例如:
```
func getsum(n1 int ,n2 int) int {
return n1 + n2
}
main(){
//这个操作就是将 getsum 的数据类型传递给 变量a。
a := getsum
n3 := a(10,20)
}
```
-Go语言中,函数是一种数据类型,所以可以作为形参传入。
```
func getsum(n1 int ,n2 int) int {
return n1 + n2
}
func orther(sum getsum(int,int) , n1 int , n2 int) {
return n1 + n2
}
```
- Go语言种支持自定义数据类型。
- 基本语法为: type 自定义数据类型名 数据类型。 例如: type myint int
- 函数类型: type mysum func(int , int) int 。意思是 mysum 类型时这个func函数的数据类型。
- Go语言支持可变形参。代码为:
```
func main(){
n1 := A2(1,2,3,4,5)
fmt.Println(n1)
}
func A2 (n1 int,args... int) int {
sum := n1
for i := 0 ; i<len(args); i++ {
sum += args[i]
}
return sum
}
```
### 6、init函数
#### 1)基本介绍:
每一个源文件中都可以包含一个init函数,该函数会在 main 函数执行之前执行,被GO运行框架调用。也就是说init函数会在main函数之前执行。
#### 2)注意事项:
- 当main.go文件中与引入的util.go文件中都有init()函数的时候,会先执行util.go文件中init()函数,再执行main.go文件中的init()函数。
- 完整的执行顺序为: **全局变量的执行--》导入的文件的init()方法的执行--》main.go文件中的init()方法的执行--》main()方法的执行**。
- init()函数最主要的工作就是做一些初始化的工作。
### 7、匿名函数
#### 1)介绍:
Go语言支持匿名函数,匿名函数就是没有名字的函数,如果我们某个函数只是希望使用一次,那么我们就可以考虑使用匿名函数,匿名函数也可以实现多次调用。
#### 2)匿名函数使用方式一:
在定义匿名函数的时候直接调用,在后面添加数据传入匿名函数的值即可。这种方式只能对匿名函数调用一次。
```
n6 := func (n1 int,n2 int) int {
return n1+n2
}(10,20)
```
#### 3)匿名函数的使用方式二:
将匿名函数赋给一个变量,然后使用该变量来调用匿名函数。
```
a := func (n1 int,n2 int) int {
return n1+n2
}
n7 = a(10,20) //调用 变量a 即可对匿名函数的调用。
```
#### 4)全局匿名函数
如果将匿名函数赋值给一个全局变量,那么这个匿名函数既能够称为一个全局匿名函数。
```
var (
Pk = func (n1 int,n2 int) int {
return n1+n2
}
)
//调用方式:
op := Pk(10,20);
```
### 8、闭包
#### 1)基本介绍:
闭包就是**一个函数** 和其**相关的引用环境**组合的一个整体。
### 9、函数defer--延时机制
#### 1)为什么需要defer?
在函数中,程序员经常需要创建资源(比如:数据库的连接、文件句柄、锁等),为了在函数执行完成之后,能够及时释放资源,GO语言设计者提供了defer。
#### 2)使用方式:
使用defer标记的语句,暂时不执行,会将defer后面的语句亚入岛独立的栈中暂存。
待到函数执行完毕以后,再从defer栈中,将栈中的语句按先入后出的顺序进行出栈并执行。
也就是说,defer在函数执行完毕后执行。
```
defer fmt.Println("第一个defer")
defer fmt.Println("第二个defer")
```
#### 3)defer使用细节:
- 当 Go 保存defer的语句的时候,会保存使用到的相关的值也写入到语句中进行保存。
- defer很好的使用场景是用于函数执行完毕以后,及时释放资源。
### 10、函数的参数传递方式
#### 1)值传递:
基本数据类型 int系列、float系列、bool、string、数组与结构体struct。
#### 2)引用传递:
指针、slice切片、map、管道chan、interface等都是引用类型。
#### 3)值传递与引用传递的特点:
- 其实不管是值传递还是引用传递,值传递的都是进行值得拷贝,引用传递是地址的拷贝。
- 值类型默认是值传递,变量直接存储值,内存通常在栈中分配。
- 引用类型默认是引用传递。变量存储的是一个地址,这个地址对应的空间才真正存储数据。没存通常分配在堆上,当没有任何变量引用这个地址时,改地址对应的数据空间就回城为一个垃圾,待GC来进行回收。
- 如果希望函数内的变量拉力修改函数外的变量,可以穿入变量的地址&,函数内以指针的方式操作变量,从效果上看类似引用。
### 11、变量的作用域
- 在函数内部声明的变量就是局部变量,作用域仅限于函数内部;
- 函数外部声明的变量叫做全局变量,作用域在整个包中都有效,如果首字母大写,则用用于在整个程序都有效。
- 如果变量是一个代码块,那么这个变量的作用域就在该代码块中。例如if、for循环定义的变量。
### 12、字符串常用的系统函数
#### 1)统计字符串的长度,按照字节的方式: len(str)
```
//输出字符串的长度。
fmt.Println(len(str))
```
#### 2)字符串的遍历,同时能够处理中文问题:r := []rune(str)
```
r := []rune(str)
for i:=0 ;i<len(r) ;i++ {
fmt.Println(r[i])
}
```
#### 3)字符串转整数
使用 strconv 包的函数。
```
n,err := strconv.Atoi(str)
if err != nil {
fmt.Println("转换错误",err)
} else {
fmt.Println("转换成功",n)
}
```
#### 4)整数转字符串
使用 strconv 包的函数。
```
str = strconv.Itoa(123)
```
#### 5)字符串转 byte[]:
```
var bytes = []byte(str)
```
#### 6)byte[]转换为字符串:
```
var bytes = []byte{12,13,14}
str := string(bytes)
```
#### 7)查看字符串是否在指定的字符串中:
strings.Contains("长串",子串"); 返回值为true或者false。
```
bl = strings.Contains("asdfg","asd")
```
#### 8)统计字符串有几个指定的子串
```
num := strings.Count("adsfaf","as")
```
#### 9)返回字符串中第一次出现的子串的index值,如果不存在,则返回-1:
```
index := strings.Index("asdfdf","af")
```
#### 10)返回字符串中最后一次出现的子串的index值,如果不存在,则返回-1:
```
index := strings.LastIndex("asdfdf","af")
```
#### 11)将一个字符串中的指定的字段替换为其他的字段:
```
//第一个参数:将对哪个字符串进行操作
//第二个参数:字符串中的哪个子串需要被替换
//第三个参数:将字符串中需要被替换的子串替换为这个串
//第四个参数:替换多少次,如果为 -1 的话,就是全部替换
str := strings.Replace("adsfgad","as","qq",-1)
```
#### 12)按照指定的某个字符进行拆分为多个字符串:
```
strArr := strings.Split("sdfaf,tyru,afs",",")
for i := 0;i<len(strArr);i++ {
fmt.Println(strArr[i])
}
```
#### 13)将字符串进行整体的大小写替换:
```
//全部转换为小写
str := strings.ToLower("GofsgT")
//全部转换为大写
str1 := strings.ToUpper("GadTtyY")
```
#### 14)去掉字符串左右两边的空格:
```
str := strings.TrimSpace(" adf法 按时打发 adr ")
```
#### 15)去掉字符串左右两边指定的字符:
```
//去掉两边的字符
str1 := strings.Trim("!adsgf!","!")
//去掉字符串左边指定的字符
str2 != strings.TrimLeft("!adsf!","!")
//去掉字符串右边指定的字符
str2 != strings.TrimRight("!adsf!","!")
```
#### 16)判断字符串以什么开头与以什么结尾:
```
//判断字符串以什么开头,返回值为true/false
str := strings.HasPrefix("!!!afa","!!!") //返回值为真
//判断字符串以什么结束,返回值为true/false
str := strings.HasSuffix("!!!afa","!!!") //返回值为假
```
### 13、时间与日期函数
#### 1)基本介绍:
程序时常用到时间与日期的相关的函数。需要引入 time 包。
#### 2)获取当前时间,以及格式化日期:
```
//获取当前时间
now := time.Now()
fmt.Printf("%v\n",now.Year())
//将月份转换为数字
fmt.Printf("%v\n",int(now.Month()))
fmt.Printf("%v\n",now.Day())
fmt.Printf("%v\n",now.Hour())
fmt.Printf("%v\n",now.Minute())
fmt.Printf("%v\n",now.Second())
//使用time包下的Format()方法来进行格式化时间,
//注意:Format里面的数据不可改变,这即使模板
fmt.Printf(now.Format("2006-01-02 15:04:05"))
```
#### 3)时间的常量:
时间 | 中文 | 差距
---|---|---
Nanosecond | 1纳秒 |
Microsecond | 1微秒 | 1000 纳秒
Millisecond | 1毫秒 | 1000 微秒
Second | 1秒 | 1000 毫秒
Minute | 1分 | 60秒
Hour | 1小时 | 60分钟
##### 常量的作用:
能够得到一个固定的精确的时间段。比如: myTime := 100*time.Millsecond
能够结合 Sleep 来使用时间常量。例如:time.Sleep(100*time.Millsecond)
#### 4)time的Unix和UnixNano方法:
Unix()方法的时间:从1970年到时间点t所经过的时间,以秒为单位。
```
now := time.Now().Unix();
```
UnixNano()方法的时间:从1970年到时间点t所经过的时间,以纳秒为单位。
```
now := time.Now().UnixNano();
```
### 14、内置函数
#### 1)简介:
Go语言中为了编程方便,提供了一些函数,这些函数能够直接使用。称为内置函数。
#### 2)常用的内置函数:
- len() : 用于求长度。比如:string、数组、slice、map、channel
- new() : 从1970年到时间点t所经过的时间,以秒为单位。
- make(): 用来分配内存,主要是用来分配引用类型,比如channel、map、slice等。
### 15、错误处理
#### 1)简介:
Go语言中,默认是发生错误以后,程序就会崩溃。
Go语言中追求简洁优雅,所以,Go语言不支持 try...catch...finally 这种处理方式。
Go语言中引入的处理方式为:defer、panic、recover
**2)使用流程:**
Go语言可以抛出一个panic的异常,然后在defer中通过recover来捕获这个异常,然后进行正常处理。
**3)使用 defer + recover 来进行异常的捕获与处理:**
```
func main(){
//使用 defer + recover 方式来进行异常的捕获与处理
defer func() {
//先使用recover()方法来捕获到异常
err := recover()
if err != nil {
fmt.Println("异常问题为:",err)
}
}()
num1 := 10
num2 := 0
resu := num1/num2
fmt.Println(resu)
}
```
**4)错误处理的好处:**
进行错误处理后,程序不会轻易挂掉,如果加入预警代码,就可以让程序更加的健壮。
##### 自定义错误:
Go 程序中,也支持自定义错误, 使用 errors.New 和 panic 内置函数。
- errors.New("错误说明") , 会返回一个 error 类型的值,表示一个错误
- panic 内置函数 ,接收一个 interface{}类型的值(也就是任何值了)作为参数。可以接收 error 类型的变量,输出错误信息,并退出程序.
**使用方式:**
```
//这个方法是自定义的异常处理方法,可以根据传入的参数来进行异常的控制
func err1(name string) error {
if name == "abc.txt" {
//返回 nil 表示程序没有问题,返回以后程序继续执行
return nil
} else{
//返回自定义异常
return errors.New("出现错误")
}
}
func main(){
//绑定自定义异常
err := err1("ac.txt")
if err != nil {
panic(err)
}
fmt.Println("主函数继续执行")
}
```
## 四、数组与切片与map
### 1、数组
#### 1)简介:
数组可以存放多个同一个类型的数据。数组是一种数据类型,在Go语言中,**数组是值类型**。
#### 2)快速入门:
```
var a [7] int
for i := 0;i<7;i++ {
a[i] = i+5
fmt.Println(a[i])
}
```
#### 3)数组定义:
数组的定义:
> var 数组名 [数组大小] 数据类型
例如:
```
//第一种方式
var a [7] int
//第二种方式
var arr [5]int = [...]int {1,2.3}
```
#### 4)数组的内存布局:
- 数组的地址可以通过数组名来获取 &a
- 数组的第一个元素的地址,就是数组的首地址
- 数组的各个元素的地址间隔是依据数组的类型决定,比如 int64 -> 8 int32->4...
#### 5)数组的使用:
数组的遍历:
- 方式一:使用 for循环
- 方式二:使用 for-range循环
for-range循环遍历数组:
```
//index 存放的是数组的下标
//value 存放的是这个数组下标对应的数组的值
//range 不变的固定单词
//a 需要遍历的数组
for index,value := range a {
fmt.Println("数组的下标:",index)
fmt.Println("数组对应的下标的值:",value)
fmt.Println("数组a[index]的值:",a[index])
}
```
#### 6)数组的使用细节:
- 数组是多个相同类型数据的组合,一个数组一旦声明/定义了,其长度是固定的, 不能动态变化。
- var arr []int 这时 arr 就是一个 slice 切片。
- 数组中的元素可以是任何数据类型,包括值类型和引用类型,但是不能混用。
- 数组创建后,如果没有赋值,有默认值(零值)。
- 数值类型数组:默认值为 0。
- 字符串数组: 默认值为 ""。
- bool 数组: 默认值为 false。
- 数组下标必须在指定范围内使用,否则报 panic。
- Go 的数组属值类型, 在默认情况下是值传递, 因此会进行值拷贝。数组间不会相互影响。
- 长度是数组类型的一部分,在传递函数参数时 需要考虑数组的长度。意思就是:传递的数组的长度必须与形参的长度定义的一致。
- 如想在其它函数中,去修改原来的数组,可以使用引用传递(指针方式)。
```
func test02(arr *[3]int){
(*arr)[0] = 0;
}
```
### 2、切片
#### 1)简介:
- 切片的英文是 slice。
- 切片是数组的一个引用,因为**切片是引用数据类型**,在进行传递的时候,遵守的是引用传递机制。
- 欺骗的使用方式与数组类似,遍历切片、访问切片的元素和求切片长度的方式都是一样的。
- **切片的长度是可以变化的,因此切片是一个可以动态变化的数组。**
#### 2)基本语法:
**切片的定义:** var 切片名 []类型
例如:
```
var a []int
```
#### 3)切片的基本demo:
```
//创建一个数组
var a [6] int = [...]int{1,2,3,4,5,6}
//声明切片
//表示 slice 这个切片 引用到 a 这个数组,
//引用的 a 数组 的起始下标为1,结束下标为3(但是不包括3)
//slice := a[1:3] //创建切片的第一种方式
var slice [] int = a[1:3] //创建切片的第二种方式
fmt.Println("a数组的值为:",a)
fmt.Println("slice切片的元素是:",slice)
fmt.Println("slice的元素个数为:",len(slice))
fmt.Println("slice的容量为:",cap(slice))
//输出结果为:
// a数组的值为: [1 2 3 4 5 6]
// slice切片的元素是: [2 3]
// slice的元素个数为: 2
// slice的容量为: 5
```
#### 3)切片的内存形式:

**对上面的分析图总结:**
1. slice 的确是一个引用类型
2. slice 从底层来说,其实就是一个数据结构(struct 结构体)
```java
type slice struct {
ptr *[2]int
len int
cap int
}
```
#### 4)切片的使用
##### 方式一:
简介:定义一个切片,然后让切片去引用一个已经创建好了的数组。
```
slice := a[1:3] //创建切片的第一种方式
var slice [] int = a[1:3] //创建切片的第二种方式
var slice = a[1:4] //创建切片的第三种方式
```
##### 方式二:
**简介:** 通过make来创建切片。
**基本语法:** var 切片名 []type = make([]type,len,[cap])
**参数介绍:**
> type : 指的是数据类型
> len : 大小
> cap : 指定切片容量,可选。如果你分配了 cap,则要求 cap>=len.
**代码示例为:**
```
var slice []int = make([]int,5,10)
slice[1] = 2;
slice[2] = 3;
fmt.Println("slice的元素个数为:",len(slice))
fmt.Println("slice的容量为:",cap(slice))
```
**总结为:**
- 通过 make 方式创建切片可以指定切片的大小和容量。
- 如果没有给切片的各个元素赋值,那么就会使用默认值[int , float=> 0 string =>”” bool =>
false]
- 通过 make 方式创建的切片对应的数组是由 make 底层维护,对外不可见,即只能通过 slice 去访问各个元素.
##### 方式三
**简介:**
定义一个切片,直接就指定具体数组,使用原理与make类似。
**使用代码:**
```
var slice []int = []int{1,12,3,4,5}
fmt.Println("slice的元素个数为:",len(slice))
fmt.Println("slice的容量为:",cap(slice))
```
#### 5)切片的遍历
##### 方式一:
**简介:**
使用for 循环常规方式遍历。
**代码操作为:**
```
var slice []int = []int{1,12,3,4,5}
for i:=0 ; i <len(slice) ; i++ {
fmt.Println(slice[i])
}
```
##### 方式二:
**简介:**
使用for 循环常规方式遍历。
**代码操作为:**
```
var slice []int = []int{1,12,3,4,5}
for i,v := range slice {
fmt.Println(slice[i])
fmt.Println(v)
}
```
#### 6)切片使用细节
1) 切片初始化时 var slice = arr[startIndex:endIndex]
说明:从 arr 数组下标为 startIndex,取到 下标为 endIndex 的元素(不含 arr[endIndex])。
2) 切片初始化时,仍然不能越界。范围在 [0-len(arr)] 之间,但是可以动态增长.
3) cap 是一个内置函数,用于统计切片的容量,即最大可以存放多少个元素。
4) 切片定义完后,还不能使用,因为本身是一个空的,需要让其引用到一个数组,或者 make 一个空间供切片来使用。
5) 切片可以继续切片,使用方式相同。
6) 用 append 内置函数,可以对切片进行动态追加。代码为:
```
var slice []int = []int{1,12,3,4,5}
slice = append(slice,55,66,88,99)
```
7) 切片的拷贝操作。具体代码为:
```
// copy(需要将数据存入的slice, 需要将数据复制出来的slice)
var slice []int = []int{1,12,3,4,5}
slice = append(slice,55,66,88,99)
var slice1 []int = make([]int,5,10)
copy(slice1,slice)
```
8)切片是引用类型,所以在传递时,遵守引用传递机制。(也就是说传递的是地址)
### 3、string与slice
#### 1)使用细节:
**①** **string底层是一个byte数组**,因此string也可以进行切片处理。其实string也就是一个切片,可以使用切片的方法。
使用代码为:
```
var a string = "ddsfdsaf"
slice1 := a[1:3]
for i,_ := range slice1 {
fmt.Printf("%c\n",slice1[i])
}
```
**②** string 是不可变的,也就说不能通过 str[0] = 'z' 方式来修改字符串。
**③** 如果需要修改字符串,可以先将 string -> []byte / 或者 []rune -> 修改 -> 重写转成 string 。
### 4、二维数组
#### 1)二维数组语法:
var 数组名 [数组的行][数组的列] 数组类型 。 例如: var arr [3][4] int
#### 2)使用demo:
```
var arr[3][4] int
for i :=0;i<3;i++ {
for j := 0 ;j<4;j++ {
arr[i][j] = i + j;
}
}
for i :=0;i<3;i++ {
for j := 0 ;j<4;j++ {
fmt.Print(arr[i][j]," ")
}
fmt.Println()
}
```
#### 3)使用方式:
##### ① 使用方式一:
语法: var 数组名 [大小][大小]类型
比如: var arr [2][3]int , 再赋值。
##### ② 使用方式 2: 直接初始化
声明方式:
- var 数组名 [大小][大小]类型 = [大小][大小]类型{{初值..},{初值..}}
- var 数组名 [大小][大小]类型 = [...][大小]类型{{初值..},{初值..}}
- var 数组名 = [大小][大小]类型{{初值..},{初值..}}
- var 数组名 = [...][大小]类型{{初值..},{初值..}}
例如:
```
var arr [2][3] int = [2][3]int{{1,2,3},{4,5,6}}
var arr1 = [2][3]int{{1,2,3},{4,5,6}}
```
#### 4)二维数组的遍历
##### ① 使用for循环遍历
```
for i :=0;i<3;i++ {
for j := 0 ;j<4;j++ {
fmt.Print(arr[i][j]," ")
}
fmt.Println()
}
```
##### ② 使用for-range遍历
```
for i,value1 := range arr {
for j,value2 := range value1 {
fmt.Printf("下标为%d %d \n",i,j)
fmt.Println(value2)
}
}
```
### 5、map
#### 1)基本介绍:
map就是key-value的数据结构,又称为字段或者关联数组。
#### 2)map的声明:
var 变量名 map[key的类型] value的类型
例如:
```
var a map[string]string
var a map[string]int
var a map[int]string
var a map[string]map[string]string
```
#### 3)map的key与value的类型:
key与value 可以是很多种类型,比如 bool, 数字,string, 指针, channel , 还可以是只包含前面几个类型的 接口, 结构体, 数组
#### 4)map的使用前提:
***当我们声明了map以后*,不能够直接使用这个map,需要使用make方法来分配内存以后才能够对map进行使用。**
使用案例:
```
func main() {
var map1 map[string]string
//在使用map之前,需要使用make方法来分配空间,10表示的是分配的空间大小
map1 = make(map[string]string,10)
map1["1"] = "zsl"
map1["2"] = "tsl"
fmt.Println(map1)
}
```
#### 5)map使用说明:
- map使用之前必须要先 make。
- map的key不能够重复。
- map的value时无序的数据结构。
- map的value恶意是重复的。
#### 6)map的使用方式:
##### ①方法一:
```
var map1 map[string]string
map1 = make(map[string]string,10)
map1["1"] = "zsl"
map1["2"] = "tsl"
```
##### ②方法二(推荐使用):
```
map1 := make(map[string]string)
map1["1"] = "zsl"
map1["2"] = "tsl"
```
##### ③方式三:
```
map1 := map[string]string{
"1":"zsl",
"2":"tsl",
}
```
#### 7)map的增删改查:
##### ① map的增加与更新:
map["key"] = value ;
**当key已经存在的时候,就是执行更新的操作。**
代码为:
```
map1 := make(map[string]string)
map1["1"] = "zsl"
map1["2"] = "tsl"
```
##### ② map的删除:
delete(map,"key")
**delete是一个内置函数,如果key存在,就删除key-value这个键值对,如果不存在,那么就不执行操作,且不会报错。**
代码为:
```
delete(map1,"1")
```
使用细节:
> 如果我们要删除 map 的所有 key ,没有一个专门的方法一次删除,可以遍历一下 key, 逐个删除。
> 或者 map = make(...),make 一个新的,让原来的成为垃圾,被 gc 回收。
##### ③ map的查找
使用方式: val findresult = map1["1"]
注释说明:
- 如果在这个map中存在 "1" 这个key,那么findresult就会返回的结果是true,否则为false。
- val中存的是这个 key 的值。
代码执行:
```
var map1 map[string]string
map1 = make(map[string]string,10)
map1["1"] = "zsl"
map1["2"] = "tsl"
val,findresult := map1["1"]
fmt.Println(val) //结果为 zsl
fmt.Println(findresult) //结果为 true
```
#### 8)map的遍历:
map的遍历是使用的 for-range 来进行遍历的。
简单的map遍历:
```
//最简单的遍历
var map1 map[string]string
map1 = make(map[string]string,10)
map1["1"] = "zsl"
map1["2"] = "tsl"
//遍历
for k,v := range map1 {
fmt.Print(k," ")
fmt.Println(v)
}
```
map中包含map的遍历:
```
//map中包括一个map
map1 := make(map[string]map[string]string)
map1["1"] = make(map[string]string,2)
map1["1"]["name"] = "zsl"
map1["1"]["age"] = "123"
//遍历map中的map
for k1,v1 := range map1 {
fmt.Println("k1=",k1)
for k2,v2 := range v1 {
fmt.Print(k2," ")
fmt.Println(v2)
}
}
```
#### 9)获得map的长度
```
len(map1)
```
#### 10)map排序
##### 基本介绍:
- golang 中没有一个专门的方法针对 map 的 key 进行排序;
- golang 中的 map 默认是无序的,注意也不是按照添加的顺序存放的,你每次遍历,得到的输出可能不一样;
- golang 中 map 的排序,是先将 key 进行排序,然后根据 key 值遍历输出即可。
##### 代码演示:
```
map1 := make(map[int]int)
map1[0] = 88;
map1[1] = 23;
map1[5] = 45;
map1[3] = 21;
map1[4] = 99;
map1[2] = 0;
map1[6] = 534;
map1[7] = 23;
map1[8] = 56;
map1[9] = 12;
fmt.Println(map1)
//将所以的key放入到切片中
var keys []int
for k,_ := range map1 {
keys = append(keys,k)
}
//排序
sort.Ints(keys)
fmt.Println(keys)
//按照key的顺序进行排序输出
for _,k := range keys {
fmt.Println(k," = ",map1[k])
}
```
### 11)map使用细节:
- map是引用类型,遵守引用类型传递机制。也就是说函数接受一个map,修改以后,会直接修改原来的map数据。
- map的容量达到扩容以后,在想map增加元素,会自动扩容,并且不会报错。
- map 的 value 也经常使用 struct 类型,更适合管理复杂的数据(比前面 value 是一个 map 更好)。
### 6、map切片
#### 1)基本介绍:
切片的数据类型如果是map,那么就是称为 map切片。这样子**map也就可以动态变化**了。
#### 2)基本语法:
var 切片名 []map[数据类型]数据类型
例如:var map1 []map[string]string
#### 3)案例演示:
**要求:** 使用一个 map 来记录 妖怪 的信息 name 和 age, 也就是说一个 妖怪 对应一个 map,并且妖怪的个数可以动态的增加。
```
var map1 []map[string]string
map1 = make([]map[string]string, 2)
if map1[0] ==nil {
map1[0] = make(map[string]string,2)
map1[0]["name"] = "zszl"
map1[0]["age"] = "123"
}
if map1[1] ==nil {
map1[1] = make(map[string]string,2)
map1[1]["name"] = "weqer"
map1[1]["age"] = "33"
}
moremap := map[string]string {
"name":"ttt",
"age":"878",
}
//动态的添加map切片
map1 = append(map1,moremap)
fmt.Println(map1)
```
## 五、排序与查找与设计模式
### 1、排序
#### 1)介绍:
排序是将一组数据,依指定的顺序进行排序的过程。
#### 2)排序的分类:
##### 内部排序:
指的是将需要处理的所有数据都加载到内部存储中进行排序。包括(交换式排序法、选择式排序法、插入式排序法等)。
##### 外部排序:
经常用作数据量过大、无法加载全部数据到内存中的场景。需要借助外部存储进行排序。包括(合并排序法、直接合并排序法等)。
#### 3)交换式排序法包括--冒泡排序(Bubble sort)
##### 基本思想:
让前面的数与后面的数相比较,如果根据需求来进行位置的调换操作。
##### 基本操作:

##### 基本概念:
一共会经过数组长度n的(n-1)次;每一轮比较就会确定一个数的位置;每一轮比较的次数再逐渐的减少(第一次是比较n-1次,第二次就是比较到n-2次,一直到最后一次的比较即可)。
##### 代码实现:
```
/**
* 冒泡排序
* @param args
*/
public static void main(String[] args) {
int a[] = {12,95,56,82,73,91,106,22,19,64};
int i = 0;
int j = 0;
int temp = 0;
//第一个for循环,是专门针对于for循环是需要进行多少次循环
for ( i=0;i<a.length-1;i++ ) {
//第二个for循环,是为了让这个冒泡排序进行多少个数的比较
for( j=0;j<a.length-i-1;j++ ) {
if( a[j]>a[j+1] ) {
temp =a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for (int k=0;k<a.length;k++) {
System.out.println(a[k]);
}
}
```
### 2、查找
#### 1)二分法查找
##### 实现原理:
二分法查找是在一个**有序的数组**中进行查询。
##### 实现流程:

##### 代码实现:
```
public static void main(String[] args) {
int[] a = new int[] { 12, 23, 34, 45, 56, 67, 77, 89, 90 };
int aa = rank(3,a);
if(aa == -1) {
System.out.println("没查找到结果");
} else {
System.out.println("结果查找到了");
}
}
/**
* 二分法查找
* @param key
* @param nums
* @return
*/
public static int rank(int key,int nums[])
{
int low=0;
int high=nums.length-1;
int notFind=-1;
while(low<=high)
{
int mid=low+(high-low)/2;
if(nums[mid]>key)
{
high=mid-1;
}else if(nums[mid]<key)
{
low=mid+1;
}
else
{
return mid;
}
}
return notFind;
}
```
### 3、设计模式
#### 1)工厂模式
##### 基本介绍:
在Golang中没有构造函数,当我们需要创建结构体的时候,可以使用工厂模式来创建结构体实例。
创建一个结构体,里面提供一个工厂方法,然后提供变量的Get方法,让外界能够调用这个Get方法来实现对属性的调用。提供Set方法,为这个变量赋值。
##### 代码实现:
先创建一个go文件:
```
//创建一个结构体
type student struct {
name string
age int
}
//使用工厂模式来创建struct实例
func NewStudent(name string,age int) *student {
return &student{name,age}
}
//提供get方法
func (std student) GetName() string {
return std.name
}
func (std student) GetAge() int {
return std.age
}
//提供set方法
func (std *student) SetName(name1 string) {
(*std).name = name1
}
func (std *student) SetAge(age1 int) {
(*std).age = age1
}
```
再创建一个主函数,来实现对其的调用:
```
import (
"go_code/project3/utils"
"fmt"
)
func main() {
var std = utils.NewStudent("zsl",24)
std.SetName("sss")
std.SetAge(555)
fmt.Println(std.GetName())
fmt.Println(std.GetAge())
}
```
## 六、面向对象
### 1、面向对象的特征
>- Go语言中的面向对象,不是类的概念,而是使用 **结构体** 来代替类的概念。
>- Go语言也支持面向对象编程(OOP)。但是和传统的面向对象编程有区别,并不是纯粹的面向对象语言。所以Golang支持面向对象编程特性是比较准确的。
>- Golang面向对象编程是非常简洁的,去掉了传统的OOP语言的继承、方法重载、构造函数和析构函数、隐匿的this指针等。
>- Golang仍然有面向对象的继承、封装、和多态的特性,只是实现的方式和其他OOP语言不一样。
>- Golang面向对象很优雅,OOP本身就是语言类型系统(type system)的一部分,通过接口(interface)关联,耦合降低,非常灵活。Golang中对接口的使用非常重要,非常灵活。
### 2、结构体
#### 1)结构体的特征:
- 将一类事务的特性提取出来,形成一个新的数据类型,就是一个结构体。
- 通过结构体,来创建多个变量(相当于是多个 实例/对象)。
- 这个结构体,可以是猫、person、或者是工具类等。
#### 2)结构体的使用
##### 结构体创建的基本语法
```
//基本语法
type 结构体名称 struct {
field1 type //字段、属性
field2 type //字段、属性
}
```
##### 结构体变量创建的基本语法
**方式一:** 直接声明变量。
```
type Cat struct {
Name string
Age int8
Color string
Hobby string
}
//创建结构体变量
var cat Cat
//为变量赋值
```
**方式二:** 在创建的时候直接赋值。
```
type Cat struct {
Name string
Age int8
Color string
Hobby string
}
//创建结构体变量
var cat Cat = Cat{"白猫",8,"red","asdf"}
//返回值为直接变量
var cat2 = Cat {
Name:"sad",
Age:32,
Color:"ff",
Hobby:"we",
}
cat3 := Cat {
Name:"sad",
Age:32,
Color:"ff",
Hobby:"we",
}
```
**方式三:** 使用指针的方式来创建结构体变量。
```
type Cat struct {
Name string
Age int8
Color string
Hobby string
}
//为指针赋值
//方式一
var cat1 *Cat = new(Cat)
cat1.Name = "苯二八年"
cat1.Age = 23
fmt.Println(cat1.Name)
fmt.Println(cat1.Age)
//方式二
var cat2 *Cat = new(Cat)
(*cat2).Name = "asdf"
(*cat2).Age = 2
fmt.Println(cat2.Name)
fmt.Println(cat2.Age)
var cat3 *Cat = &Cat{"asd",23,"asd","yty"}
cat4 := &Cat{"asd",23,"asd","yty"}
cat5 := &Cat {
Name:"sad",
Age:32,
Color:"ff",
Hobby:"we",
}
```
**方式四:** 使用地址符方式进行赋值。
```
//创建一个猫的结构体
type Cat struct {
Name string
Age int8
}
var cat1 *Cat = &Cat{}
cat1.Name = "asdf"
cat1.Age = 2
fmt.Println(cat1.Name)
fmt.Println(cat1.Age)
```
**注意:**
- 第三种与第四种的方式返回的是 *结构体指针*。
- 结构体指针访问字段的标准方式是 : (*结构体指针).字段名; 例如:(*cat1).Name = "as"
- Go语言也支持另外一种访问结构体指针的方式: 结构体指针.字段名; 例如:cat1.Name = "a"
##### 结构体的创建
```
//创建一个猫的结构体
type Cat struct {
Name string
Age int8
Color string
Hobby string
}
```
##### 结构体的使用
```
//创建一个猫的结构体
type Cat struct {
Name string
Age int8
Color string
Hobby string
}
//创建一个Cat变量
var cat1 Cat
cat1.Name = "小白"
cat1.Age = 2
cat1.Color = "red"
cat1.Hobby = "吃鱼"
fmt.Println(cat1.Name)
fmt.Println(cat1.Age)
fmt.Println(cat1.Color)
fmt.Println(cat1.Hobby)
```
#### 3)结构体与结构体变量的异同
- 结构体是自定义的数据类型,代表的是一类事物。
- 结构体变量(也就是创建的结构体实例)是具体的一个事物的实例。
#### 4)结构体变量(实例)的内存结构

#### 5)结构体中使用结构体
```
//定义一个结构体
type point struct {
x int
y int
}
//在结构体中引用结构体
type rect struct {
leftdown point
rightdown point
}
```
#### 6)trg标签的使用
##### 简介:
struct 的每个字段上,可以写上一个 tag, 该 tag 可以通过反射机制获取,常见的使用场景就是序列化和反序列化。
##### 使用方式:
在 struct结构体 的字段后面添加 **\`json:"别名"\`** 的方式来实现。
例如:
```
//当我们使用结构体的时候,一般是将字段进行大写,否则经常无法访问。
//放我们序列化的时候(也就是转换为json格式的数据的时候),一般是将字段更改为小写
//所以需要使用 tag 来实现相当于是在转换json的时候实现 为字段取别名。
//创建一个猫的结构体,使用 tag标签来进行取别名,专门用于序列化与反序列化
type Cat struct {
Name string `json:"name"`
Age int8 `json:"age"`
}
var cat1 *Cat = &Cat{}
cat1.Name = "asdf"
cat1.Age = 2
fmt.Println(cat1.Name)
fmt.Println(cat1.Age)
//使用json来转换字符串,
//第一个返回值 jsonStr:这个值是一个byte切片
//第二个返回值 err:这个是返回错误信息
byteStr,err := json.Marshal(cat1)
jsonStr := string(byteStr)
if ( err != nil ) {
fmt.Println("err为:",err)
} else {
fmt.Println(jsonStr)
}
```
### 3、字段/属性
#### 1)基本属性
- 从概念上看:**结构体字段 = 属性 = filed** (通常是统一叫做字段)
- 字段是结构体一个组成部分,一般是基本数据类型、数组、也可以是引用类型。
#### 2)注意事项
- 字段的类型可以为:基本数据类型、数组、引用数据类型
- 在创建一个结构体变量以后,如果未给字段赋值,则对应着一个同类型的默认值。
- 布尔值为false,
- 数值为0,
- 字符串为"",
- 数组类型的默认值和它的元素类型相关,
- 指针,slice,和 map 的零值都是 nil ,即还没有分配空间。
- 不同的结构体变量是互不影响的,一个结构体变量字段的更改,不会影响另外一个,**结构体是值类型**。
- 结构体的所有字段在内存中是连续的。
- 结构体是用户单独定义的类型,和其他类型进行转换时需要有完全相同的字段(名字、类型与个数)。
- 结构体进行 type 重新定义(相当于取别名),Golang 认为是新的数据类型,但是相互间可以强转
- struct 的每个字段上,可以写上一个 tag, 该 tag 可以通过反射机制获取,常见的使用场景就是序列化和反序列化。
- **结构体的复制,默认是值拷贝,所以当我们将一个结构体赋值给另外一个结构体的时候,知识将结构体的数据进行拷贝,复制到另外个结构体中。**
- **结构体指针的复制,就是进行的地址的复制。那么对每一个结构体的改变,都会对那个数据做出改变。**
### 4、方法
#### 1)基本介绍:
在某些情况下,我们要需要声明(定义)方法。比如 Person 结构体:除了有一些字段外( 年龄,姓名..),Person 结构体还有一些行为比如:可以说话、跑步..,通过学习,还可以做算术题。这时就要用方法才能完成。
Golang中的方法是作用在指定的数据类型上的(即:和指定的数据类型绑定),因此自定义类型,都可以有方法,而不仅仅是struct。也就是说,方法是与数据类型绑定在一起的。
#### 2)方法与函数的区别
- 函数的调用方式: 函数名(实参列表)
- 方法的调用方式: 变量.方法名(实参列表)
- 对于普通函数,接收者为值类型时,不能将指针类型的数据直接传递,反之亦然
- 对于方法(如 struct 的方法),接收者为值类型时,可以直接用指针类型的变量调用方法,反过来同样也可以。
**函数的声明方式:**
```
func 函数名 (形参列表) (返回值列表) {
//中间操作
return 返回值列表
}
```
**方法的声明方式:**
- 参数列表:表示方法输入
- recevier type : 表示这个方法和 type 这个类型进行绑定,或者说该方法作用于 type 类型
- receiver type : type 可以是结构体,也可以其它的自定义类型
- receiver : 就是 type 类型的一个变量(实例),比如 :Person 结构体 的一个变量(实例)
- 返回值列表:表示返回的值,可以多个
- 方法主体:表示为了实现某一功能代码块
- return 语句不是必须的。
```
func (recevier type) methodName(参数列表) (返回值列表){
方法体
return 返回值
}
```
**注意:**
方法的声明是需要与数据类型相绑定的,而函数却不需要与数据类型进行绑定。
**方法的调用必须要使用 绑定的参数类型的对象 来进行调用。其他不能够调用。**
#### 3)方法的声明与调用demo
```
type Cat struct {
Name string `json:"name"`
Age int8 `json:"age"`
}
func (cat Cat) test(){
fmt.Println(cat.Name)
fmt.Println(cat.Age)
}
func main() {
var cat1 *Cat = &Cat{}
cat1.Name = "asdf"
cat1.Age = 2
//调用绑定了 Cat数据类型 的 test() 方法
cat1.test()
}
```
#### 4)方法的调用和传参机制原理
- 在通过一个变量去调用方法时,其调用机制和函数一样。
- **不一样的地方时,变量调用方法时,该变量本身也会作为一个参数传递到方法(如果变量是值类型,则进行值拷贝,如果变量是引用类型,则进行地质拷贝)**
#### 5)方法的使用细节
- 结构体类型是值类型,在方法调用中,遵守值类型的传递机制,是值拷贝传递方式
- 如程序员希望在方法中,修改结构体变量的值,可以通过结构体指针的方式来处理
- Golang 中的方法作用在指定的数据类型上的(即:和指定的数据类型绑定),因此自定义类型, 都可以有方法,而不仅仅是 struct, 比如 int , float32 等都可以有方法。
- **方法的访问范围控制的规则,和函数一样。方法名首字母小写,只能在本包访问,方法首字母大写,可以在本包和其它包访问。**
- 如果一个类型实现了 String()这个方法,那么 fmt.Println 默认会调用这个变量的 String()进行输出。
### 5、面向对象---抽象
#### 1)抽象简介
把一类事物的共有的属性(字段)和行为(方法)提取出来,形成一个物理模型(结构体),这种研究问题的方法就是**抽象**。
#### 2)银行账号案例
很多银行,很多银行卡,都具有账号,密码、余额等共有的属性,以及存款、取款等行为,将其抽取出来,实现一个结构体,就是实现一个抽象。
```
//账户的结构体
type Account struct {
AccountNum string
Passwd string
Balance float64
}
func main(){
account := Account{"123","123",64.4}
account.Output("123",60)
account.Input("123",66666)
}
//银行取钱
func (account Account) Output(passwd string,money float64) {
if passwd != account.Passwd {
fmt.Println("输入的密码错误")
return
}
//查看银行卡余额是否足够
if money > account.Balance || money <= 0 {
fmt.Println("输入的金额不正确")
return
}
account.Balance = account.Balance - money
fmt.Println("取款成功,余额为:",account.Balance)
}
//银行存钱
func (account Account) Input(passwd string ,money float64) {
if passwd != account.Passwd {
fmt.Println("输入的密码错误")
return
}
//查看输入的金额是否大于0
if money <= 0 {
fmt.Println("输入的金额不正确")
return
}
account.Balance = account.Balance + money
fmt.Println("存款成功,账户余额为:",account.Balance)
}
```
### 6、面向对象---封装(encapsulation)
#### 1)基本介绍:
封装就是把抽象出来的字段和对字段的操作封装在一起,数据被保护在内部,程序的其他包只能通过被授权的操作(也就是方法)来对字段进行操作。也就是说,我们为字段封装到内部,让外界无法访问,然后提供绑定了字段的对外开放的方法,来实现对字段的操作。
#### 2)封装特性:
- 隐藏了细节操作。
- 可以对数据进行校验,保证数据的安全合理。
- 实现了高内聚,低耦合的操作,避免数据之间发生冲突。
#### 3)封装的实现原理:
- 对结构体中的属性进行封装(也即是将结构体中的属性小写,实现本包能够访问,其他包不能访问的操作)。
- 通过 包、方法 来实现封装的效果。
#### 4)封装的实现步骤:
第一步:将结构体、字段(属性)的首字母小写(这样子在其他包中就无法使用了,类似有private)。
第二步:给结构体所在包提供一个工厂模式函数,首字母大写(类似于构造函数)。
第三步:提供一个首字母大写的Set方法(类似于public),用于对属性判断并赋值。
```
func (var 结构体类型名) SetXXX(参数列表)(返回值列表) {
//加入数据验证的业务逻辑
var.属性 = 参数
}
```
第四步:提供一个首字母大写的 Get 方法(类似于public),用于获取属性的值
```
func (var 结构体类型名) GetXxx() {
return var.age;
}
```
#### 5)封装的代码实现:
先创建一个 person.go 文件,里面创建一个 person 类型的结构体,提供这个结构体的工厂方法,以及这个结构体的 Get/Set方法(类似于java中的pojo)。
```
type person struct {
name string
age int8
}
//使用工厂方式创建一个person结构体对象
func NewPerson() *person{
return &person{}
}
func (p *person) SetName(name1 string){
if( len(name1)<10 && len(name1)>3 ) {
p.name = name1
} else {
fmt.Println("姓名的长度只能在3-10之间,请重新输入。")
}
}
func (p *person) SetAge(age1 int8){
if( age1<120 && age1>0 ){
p.age = age1
} else {
fmt.Println("年龄范围不正确")
}
}
func (p *person) GetName() string {
return p.name
}
func (p *person) GetAge() int8 {
return p.age
}
```
在主函数中创建这个 person 对象,调用方法。
```
func main(){
person := model.NewPerson()
person.SetAge(92)
person.SetName("df33")
name := person.GetName()
age := person.GetAge()
fmt.Println("姓名为:",name,"年龄为:",age)
}
```
### 7、面向对象---继承
#### 1)基本介绍:
继承能够解决代码复用,让编程更接近人类思维。
当多个结构体存在相同的属性(字段)和方法的时候,只需要 **嵌套一个通用的结构体** 即可。
#### 2)继承的代码实现:
先创建一个结构体,然后让 Man 与 Woman 来继承 person 这个结构体:
```
package people
type person struct {
Name string
Age int8
}
type Man struct {
//Man继承了 person 的属性
person
LastName string
}
type Woman struct {
//woman 继承了 person 的属性
person
FirstName string
}
```
使用main函数来调用这个具有继承属性的结构体:
```
func main(){
man := people.Man{}
man.Age = 1
man.LastName = "世林"
man.Name = "张世林"
fmt.Println(man)
woman:= people.Woman{}
woman.FirstName = "张"
woman.Name = "张海霞"
woman.Age = 2
fmt.Println(woman)
}
```
#### 3)继承的特点:
- 结构体使用嵌套匿名结构体的所有字段与方法(无论是属性与方法,无论是大写还是小写开头的,都会有对应的继承的效果)。
- 父结构体的方法、属性,子结构体都具有对应的属性以及方法。
- 当操作子结构体的时候,编译器会先去子结构体中寻找对应的属性与方法,如果子类没有就查询其父类,如果父类也不存在,则报错(编译器是就近原则来对其属性进行访问,子类->父类->报错)。
- 当子结构体的多个父类存在相同的字段的时候,对其调用的话,必须指定父结构体的名字来对其属性进行调用。
例如:下创建两个结构体,每个结构体都有name属性,让BigStudent这个结构体嵌套两个结构体;
```
type bigStudent struct {
student
person
zy string
}
func (bigs bigStudent) NewBigStudent() *bigStudent {
bigs.person.name = "zsl"
bigs.student.name = "zsl"
bigs.zy = "计算机科学与技术"
return &bigs
}
```
- 如果struct潜逃了一个**有名结构体**,则使用时必须使用结构体的名字。例如:
- 嵌套匿名结构体在创建变量的时候,可以直接对各个匿名结构体的字段进行赋值。
#### 4)多重继承
##### 基本介绍:
如果一个struct嵌套了多个匿名结构体,那么该结构体可以直接访问嵌套的匿名结构体的字段和方法,从而实现多重继承。
##### 代码演示:
```
type bigStudent struct {
student
person
zy string
}
func (bigs bigStudent) NewBigStudent() *bigStudent {
bigs.person.name = "zsl"
bigs.zy = "计算机科学与技术"
return &bigs
}
```
##### 使用细节:
- 多重继承,在匿名结构体的方式下,如果有相同的字段名或者方法名,必须要指定对应的结构体,否则编译器会报错。
- 通常情况下,为了保证代码的简洁性,尽量少用多重继承。
### 8、面向对象---接口
#### 1)基本介绍:
interface类型可以定义一组方法,但是这些方法不需要实现。并且interface中不可以包含任何变量。待到某个自定义类型(比如结构体)需要使用的时候,可以根据对应的情况将其具体实现。
在Golang中,多态的特性主要是使用接口来实现的。
#### 2)接口的demo
```
/**
定义一个接口
*/
type Usb interface {
//声明两个未实现的方法
Start()
Stop()
}
//定义一个Phone结构体
type Phone struct {
}
//让Phone实现Usb接口的方法
func (p Phone) Start() {
fmt.Println("手机开始工作")
}
func (p Phone) Stop(){
fmt.Println("手机结束工作")
}
//定义一个Camera结构体
type Camera struct {
}
//让Camera实现Usb接口的方法
func (p Camera) Start() {
fmt.Println("Camera开始工作")
}
func (p Camera) Stop(){
fmt.Println("Camera结束工作")
}
//定义了一个Computer
type Computer struct {
}
func (c Computer) Working(usb Usb) {
usb.Start()
usb.Stop()
}
func main() {
computer := Computer{}
camera := Camera{}
computer.Working(camera)
}
```
#### 3)接口的基本语法:
```
type 接口名 interface {
方法名1(参数列表) (返回值列表)
方法名2(参数列表) (返回值列表)
...
}
```
#### 4)接口的特点:
- 接口中的所有方法都没有方法体,即接口中的方法只有方法头,没有方法体。
- 接口主要是在程序中体现了高内聚,低耦合的特点。
- **Golang中的接口,不需要显式的调用,只要一个变量(比如结构体),含有了接口类型中的所有方法,那么这个变量就是实现了这个接口。所以,Golang中没有implements关键字。**
#### 5)接口的注意事项
- **接口本身不能够创建实例,但是可以指向一个实现了该接口的自定义类型的变量(实例)。** 也就是说,接口不能够直接创建变量,但是可以指向含有该接口的结构体的变量。
- 接口中所有的方法都没有方法体,即都是没有实现的方法。
- 在 Golang 中,一个自定义类型需要将某个接口的所有方法都实现,我们说这个自定义类型实现了该接口。
- 一个自定义类型只有实现了某个接口,才能将该自定义类型的实例(变量)赋给接口类型。例如:
```
//先定义一个实现了 A接口 的数据类型的变量
var stud Student
//现在才能够定义一个接口的变量来指向接口的实现类
var a A = stud
```
- 只要是自定义数据类型,就可以实现接口,不仅仅是结构体类型。
- **一个自定义数据类型能够实现多个接口。**
- 接口中一定不能够有变量。
- **一个接口可以多继承多个接口,那么实现这个接口的话,必须要实现这个接口以及父类接口定义的所有方法。**
```
type A interface {
say()
}
type B interface {
hello()
}
//接口来继承多个接口
type C interface {
A
B
}
```
- interface默认是一个指针类型(引用类型),那么如果没有对interface进行初始化就使用的话,会输出 nil。
- 空接口 interface{} 没有任何方法,所以所有数据类型都是实现了空接口,即我们可以将任何一个变量赋给空接口。例如:
```
var student Student
//将任何变量都能够给赋值给一个空接口
var stu interface{} = stu
```
- **接口多继承的多个接口,不允许有相同的方法名。**
#### 6)实现接口来自定义数据类型的排序
```
import (
"fmt"
"math/rand"
)
type Hero struct {
Name string
Age int
}
//创建一个Hero类型的切片数据
type HeroSlice []Hero
func (hs HeroSlice) Len() int {
return len(hs)
}
// Less方法报告索引i的元素是否比索引j的元素小
func (hs HeroSlice) Less(i, j int) bool {
//按照年龄排序
return hs[i].Age < hs[j].Age
}
// Swap方法交换索引i和j的两个元素
func (hs HeroSlice) Swap(i, j int){
//进行元素的交换操作
//temp := hs[i]
//hs[i] = hs[j]
//hs[j] = temp
//上面三句代码相当于下面这一行代码,主要是说明的是将 hs[i]与hs[j]相交换。
hs[i],hs[j] = hs[i],hs[i]
}
func main() {
//创建一个Hero切片
var heros HeroSlice
//为HeroSlice赋值
for i:=0;i<3 ;i++ {
hero := Hero{
//使用Sprintf()方法返回一个值
Name: fmt.Sprintf("英雄|%d", rand.Intn(100)),
Age : rand.Intn(100),
}
heros = append(heros,hero)
}
//使用for_range来进行输出,将按照上面自定义的规则进行排序
fmt.Println("---------------------")
for _,v:=range heros {
fmt.Println(v)
}
fmt.Println("---------------------")
}
```
#### 7)接口与继承的关系
- 当 A 结构体继承了 B 结构体,那么 A 结构就自动的继承了 B 结构体的字段和方法,并且可以直接使用
- 当 A 结构体需要扩展功能,同时不希望去破坏继承关系,则可以去实现某个接口即可,因此我们可以认为:实现接口是对继承机制的补充.
- 实现接口可以看作是对 继承的一种补充。
- 继承的价值主要在于:解决代码的复用性和可维护性。
- 接口的价值主要在于:设计,设计好各种规范(方法),让其它自定义类型去实现这些方法。
- 接口在一定程度上实现代码解耦。
### 9、面向对象---多态
#### 1)基本介绍:
变量(实例)具有多种形态,面向对象的第三大特征。Go语言中的多态主要是使用接口来实现的。**可以按照统一的借口来通过调用不同的接口的实现来实现不同的功能**。
#### 2)多态参数:
##### 基本介绍:
将接口作为形参,然后传入不同的这个接口的实现类来指明需要执行哪个实现类的功能。
##### 案例演示:
Usb结构体作为形参的时候,传入不同的实现了这个接口的对象,就会具体执行不同的功能。
```
/**
定义一个接口
*/
type Usb interface {
//声明两个未实现的方法
Start()
Stop()
}
//定义一个Phone结构体
type Phone struct {
}
//让Phone实现Usb接口的方法
func (p Phone) Start() {
fmt.Println("手机开始工作")
}
func (p Phone) Stop(){
fmt.Println("手机结束工作")
}
//定义一个Camera结构体
type Camera struct {
}
//让Camera实现Usb接口的方法
func (p Camera) Start() {
fmt.Println("Camera开始工作")
}
func (p Camera) Stop(){
fmt.Println("Camera结束工作")
}
//定义了一个Computer
type Computer struct {
}
func (c Computer) Working(usb Usb) {
usb.Start()
usb.Stop()
}
func main() {
computer := Computer{}
camera := Camera{}
computer.Working(camera)
}
```
#### 3)多态数组
##### 基本介绍:
多态数组就是定义一个接口数组,然后多个这个接口的实现类,分别赋值给这个接口数组。
##### 案例演示:
```
/**
定义一个接口
*/
type Usb interface {
//声明两个未实现的方法
Start()
Stop()
}
//定义一个Phone结构体
type Phone struct {
}
//让Phone实现Usb接口的方法
func (p Phone) Start() {
fmt.Println("手机开始工作")
}
func (p Phone) Stop(){
fmt.Println("手机结束工作")
}
//定义一个Camera结构体
type Camera struct {
}
//让Camera实现Usb接口的方法
func (p Camera) Start() {
fmt.Println("Camera开始工作")
}
func (p Camera) Stop(){
fmt.Println("Camera结束工作")
}
func main() {
var usb [2]Usb
usb[0] = Phone{}
usb[1] = Camera{}
}
```
### 10、类型断言
#### 1)基本介绍:
类型断言,由于接口是一般类型,不知道其具体类型,如果需要转换成具体类型,就回去使用到类型断言。
#### 2)基本语法:
```
//类型断言的检测机制语法
if 名称,断言返回值 := 被检测的数据.(数据类型); 断言返回值 {
}
//断言使用方式与一:
//类型断言进行检测机制,如果类型判断正确,那么久执行下面的代码,否则不执行代码
if y,value := x.(float64); value {
fmt.Printf("y的类型为:%T ,值为 %v",y,y)
}
//断言检测使用方式二:
y,value := x.(float64)
if value == true {
fmt.Printf("y的类型为:%T ,值为 %v",y,y)
} else {
fmt.Println("类型不正确")
}
```
#### 3)断言说明:
在进行类型断言的时候,如果类型不匹配。那么就会报错 panic,因此进行类型断言的时候,要确保原来的空接口指向的就是断言的类型。
#### 4)断言检测:
在断言中,使用下面的方式进行数据类型的判断,如果数据类型与断言的数据类型一致的话,就会执行标签中的代码,如果数据类型判断不一致的话,就不会执行标签中的方法,但是程序也不会报错。
```
func main() {
var x interface{}
var k float64
k = 4
//将 k 的值赋值给空接口 x
x = k
//断言使用方式与一:
//类型断言进行检测机制,如果类型判断正确,那么久执行下面的代码,否则不执行代码
if y,value := x.(float64); value {
fmt.Printf("y的类型为:%T ,值为 %v",y,y)
}
//断言检测使用方式二:
y,value := x.(float64)
if value == true {
fmt.Printf("y的类型为:%T ,值为 %v",y,y)
} else {
fmt.Println("类型不正确")
}
}
```
#### 5)断言最佳实践:
##### 最佳实践一:
根据传入的参数的类型来进行断言的验证,确定是否执行代码
```
/**
定义一个接口
*/
type Usb interface {
//声明两个未实现的方法
Start()
Stop()
}
//定义一个Phone结构体
type Phone struct {
}
//让Phone实现Usb接口的方法
func (p Phone) Start() {
fmt.Println("手机开始工作")
}
func (p Phone) Stop(){
fmt.Println("手机结束工作")
}
func (p Phone) Call(){
fmt.Println("手机可以打电话")
}
//定义一个Camera结构体
type Camera struct {
}
//让Camera实现Usb接口的方法
func (p Camera) Start() {
fmt.Println("Camera开始工作")
}
func (p Camera) Stop(){
fmt.Println("Camera结束工作")
}
type Computer struct {
}
func (c Computer) Working(usb Usb){
usb.Start()
usb.Stop()
//根据传入的参数的不同,来确定是否执行标签中的代码
if t,value := usb.(Phone); value {
t.Call()
}
}
func main(){
var usb Usb
var phone Phone
usb = phone
var computer Computer
computer.Working(usb)
}
```
##### 最佳实践二:
```
//先定义一个检测可变参数类型数据的函数
//返回传入的参数的类型
func TypeReturn(items ...interface{}) {
for i,value := range items {
switch value.(type) {
case bool:
fmt.Println("输出的参数为bool类型,值为",value,"下标为:",i)
case int:
fmt.Println("输出的参数为int类型,值为",value,"下标为:",i)
case float64:
fmt.Println("输出的参数为float64类型,值为",value,"下标为:",i)
case string:
fmt.Println("输出的参数为string类型,值为",value,"下标为:",i)
}
}
}
//传入参数,进行判断
func main(){
var n1 float64 = 1.1
var n2 string = "adf"
main3.TypeReturn(n1,n2)
}
```
## 七、Golang文件操作
### 1、文件的基本介绍
#### 1)文件的概念
文件,我们可以理解为数据源(保存数据的地方)的一种,比如大家经常使用的Word文档、txt文件、excel文件等。文件最主要的作用就是保存数据,它即可以保存一张图片,也可以保存视频、声音等。
#### 2)流与输入流与输出流
- 流:数据在数据源(文件)和程序(内存)之间经历的路径。
- 输入流:数据从数据源(文件)到程序(内存)中。
- 输出流:数据从程序(内存)到数据源(文件)中。
```
sequenceDiagram
Go内存->>外部文件: 输出流
外部文件->>Go内存: 输入流
```
#### 3)操作文件的方法一:
os.File 包中封装了Golang语言对文件的相关操作,File是一个结构体。
#### 4)普通的打开文件
##### 基本介绍:
Open打开一个文件用于读取。如果操作成功,返回的文件对象的方法可用于读取数据;对应的文件描述符具有O_RDONLY模式。如果出错,错误底层类型是*PathError。
##### 注意事项:
- 返回的 file,可以称为 file对象/file指针/file文件句柄,但会的实际就是一个指针。
- 判断err是否为空来确定是否打开文件成功。
##### 方法原型:
```
func Open(name string) (file *File, err error)
```
#### 5)关闭文件
##### 基本介绍:
Close关闭文件file,使文件不能用于读写。它返回可能出现的错误。
##### 方法原型:
```
func (f *File) Close() error
```
##### 使用方法:
```
//方法一:直接使用defer来进行文件流的关闭
defer file.Close();
//方法二:在不需要文件流的位置进行文件流的关闭
//比如:在方法的末尾关闭文件流
err := file.Close()
if err == nil {
fmt.Println("文件关闭成功")
} else {
fmt.Println("文件关闭失败",err)
}
```
#### 6)带缓冲的Reader读取文件:
##### 使用步骤:
第一步:先使用 Open()函数打开文件流
第二步:使用 defer 方式来关闭文件流
第三步:创建一个 reader,调用的是 bufio的NewReader()方法
第四步:判断返回的err信息,来查看是否读到了文件的末尾,来循环输出内容。
##### 代码实现:
```
func main() {
//打开文件,调用的是os包下面的Open函数
file, err := os.Open("E:/test.txt")
//如果没有错误信息的话,就可以继续操作 file对象/file指针/file文件句柄
if err == nil {
fmt.Println(file)
} else {
fmt.Println("打开文件失败")
}
//关闭这个文件流
defer file.Close()
//创建一个带缓冲区的 Reader 来读取文件
reader := bufio.NewReader(file)
for {
//调用reader的ReadString函数来实现当遇到换行符的话,一行就结束
str, err1 := reader.ReadString('\n')
//当 err1 == io.EOF 的时候,说明文件读取到了末尾
if err1 ==io.EOF {
break
}
fmt.Println(str)
}
}
```
#### 7)直接将一个文件读入到内存中---小文件
##### 基本介绍:
ReadFile函数 从filename指定的文件中读取数据并返回文件的内容。成功的调用返回的err为nil而非EOF。因为本函数定义为读取整个文件,它不会将读取返回的EOF视为应报告的错误。
##### 方法原型:
```
func ReadFile(filename string) ([]byte, error)
```
##### 代码实现:
```
//使用的是 ioutil 包下面的 ReadFile 函数,实现小文件的直接读取功能
func main() {
filePath := "E:/test.txt"
file, err := ioutil.ReadFile(filePath)
if err == nil{
fmt.Println(string(file))
} else {
fmt.Println("错误,",err)
}
}
```
##### 注意事项:
- ReadFile()函数不需要显式的Open()文件和Close()文件。
- 一次性的将整个文件读取到内存中,所以文件不能过大,多大内存空间不够。
#### 8)直接将一个文件写入到文件中---小文件
##### 基本介绍:
函数向filename指定的文件中写入数据。如果文件不存在将按给出的权限创建文件,否则在写入数据之前清空文件。
##### 代码原型:
```
func WriteFile(filename string, data []byte, perm os.FileMode) error
```
##### 代码实现:
```
err2 := ioutil.WriteFile(file2, "sadfasff", 0666)
if err2 != nil {
fmt.Println("写入到文件失败",err2)
}
```
#### 9)带缓冲区的Writer写入文件
##### 使用步骤:
第一步:打开一个可以写入的文件流
第二步:使用 defer 方式来关闭文件流
第三步:创建一个 writer,调用的是 bufio的NewWriter()方法。
第四步:调用writer的WriteString()方法写入数据到缓冲区。
第五步:调用writer的Flush()方法来实现数据从缓冲区中刷入的文件中。
##### 代码实现:
```
//创建一个带缓存的Writer
writer := bufio.NewWriter(file)
//向writer中写入数据
for i:=0;i<5;i++ {
writer.WriteString("hello World \n")
}
//调用Flush()方法将缓存中数据刷入到文件中
writer.Flush()
```
#### 10)将数据写入文件
##### 基本介绍:
使用OpenFile()函数打开文件,能够进行打开的方式的控制,能够进行文件权限的控制(文件权限的控制在Linux操作系统下才能够实现,Windows操作系统下无效)。
OpenFile是一个更一般性的文件打开函数,大多数调用者都应用Open或Create代替本函数。它会使用指定的选项(如O_RDONLY等)、指定的模式(如0666等)打开指定名称的文件。如果操作成功,返回的文件对象可用于I/O。如果出错,错误底层类型是*PathError。
##### 代码原型:
```
//name string,表示的是文件名
//flag int,表示的是打开的模式,多种模式可以组合在一起
//perm FileMode,表示打开的文件的权限操作。
func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
```
##### 方法参数的选择:
**flag int参数的选择:**
参数名 | 参数对应文件打开的方式
---|---
O_RDONLY int = syscall.O_RDONLY | 只读模式打开文件
O_WRONLY int = syscall.O_WRONLY | 只写模式打开文件(覆盖)
O_RDWR int = syscall.O_RDWR | 读写模式打开文件(覆盖)
O_APPEND int = syscall.O_APPEND | 写操作时将数据附加到文件尾部(追加)
O_CREATE int = syscall.O_CREAT | 如果不存在将创建一个新文件
O_EXCL int = syscall.O_EXCL | 和O_CREATE配合使用,文件必须不存在
O_SYNC int = syscall.O_SYNC | 打开文件用于同步I/O
O_TRUNC int = syscall.O_TRUNC | 如果可能,打开时清空文件
**perm FileMode参数的选择:**
参数 | 参数的解释
---|---
1 | 读r
2 | 写w
4 | 可执行x
##### 代码实现:
```
func main() {
//定义一个文件名
fileName := "E:/test1.txt"
//第一个参数:指定文件的文件名
//第二个参数:组合模式,打开文件的方式是 读写 或者 创建 两种模式
//第三个参数:指定在Linux下这个文件的权限
file, err := os.OpenFile(fileName, os.O_RDWR | os.O_CREATE, 4)
if err != nil {
fmt.Println("open文件失败",err)
}
//关闭这个流
defer file.Close()
//创建一个带缓存的Writer
writer := bufio.NewWriter(file)
//向writer中写入数据
for i:=0;i<5;i++ {
writer.WriteString("hello World \n")
}
//调用Flush()方法将缓存中数据刷入到文件中
writer.Flush()
}
```
#### 11)将一个文件的数据转入到另外一个文件中
```
func main() {
file1 := "E:/test.txt"
file2 := "E:/test1.txt"
//得到这个文件的内容
file1_value, err1 := ioutil.ReadFile(file1)
if err1 != nil {
fmt.Println("文件读取失败",err1)
return
}
err2 := ioutil.WriteFile(file2, file1_value, 0666)
if err2 != nil {
fmt.Println("写入到文件失败",err2)
}
}
```
#### 12)判断文件/文件夹是否存在
##### 基本介绍:
Golang中判断文件或者文件夹是否存在的方法是 os.Stat()函数。
##### 详细介绍:
- 如果返回的错误为 nil,则说明文件或者文件夹存在。
- 如果返回的错误类型使用os.IsNotExists()函数来进行判断为true,则说明文件夹不存在。
- 如果返回其他类型,则不确定文件是否存在。
##### 代码实现:
```
func main() {
file1 := "E:/test1.txt"
b := PathExists(file1)
fmt.Println(b)
}
//返回文件是否存在
func PathExists(path string) (bool){
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
```
#### 13)文件的拷贝
##### 拷贝图片。
**使用方法:**
使用的是 io包下面的 Copy() 方法来实现文件的拷贝操作。
**代码实现:**
```
//拷贝图片
func main() {
file := "E:/照片/周小燕艺术照片/P001.jpg"
file1 := "E:/P001.jpg"
copyfile(file,file1)
}
/**
实现原理是得到一个reader对象与一个writer对象,然后执行copy操作
*/
//srcPath:源文件的路径
//DSTPath:目标文件的路径
func copyfile(srcPath string,dstPath string) (written int64, err error) {
//打开源文件路径
srcFile, err1 := os.Open(srcPath)
if err1 != nil {
fmt.Println("打开源文件失败",err1)
return
}
//拿到Reader对象
reader := bufio.NewReader(srcFile)
//创建或者打开一个文件
dstFile, err2 := os.OpenFile(dstPath, os.O_CREATE|os.O_RDWR, 0666)
//得到这个文件的Writer对象
if err2 != nil {
fmt.Println("创建或者打开目标文件失败",err2)
return
}
writer := bufio.NewWriter(dstFile)
defer srcFile.Close()
defer dstFile.Close()
//执行文件的Copy操作,并且返回
return io.Copy(writer, reader)
}
```
#### 14)统计文件的各类字符数量
##### 案例需求:
统计文件中的英文、数字、空格以及其他字符的个数。
##### 代码实现:
```
//定义这个结构体,来实现文件中数据的统计
type Num struct {
intSize int
charSize int
spaceSize int
ortherSize int
}
func main(){
var num Num
var path string = "E:/test3.txt"
num1 := tongji(path, num)
fmt.Println(num1.intSize)
fmt.Println(num1.charSize)
fmt.Println(num1.spaceSize)
fmt.Println(num1.ortherSize)
}
//统计文件中的各个字段的数据
func tongji(filepath string,num Num) *Num {
file, err1 := os.Open(filepath)
if err1 != nil {
fmt.Println("文件打开失败",err1)
}
defer file.Close()
//得到这个reader对象,让偶能够实现读取功能
reader := bufio.NewReader(file)
for {
//一行一行的读取的意思
str, err2 := reader.ReadString('\n')
if err2 == io.EOF {
fmt.Println("读取文件完成",err2)
break
}
for _,v :=range str {
switch {
case v >= 'a' && v <= 'z': num.charSize++
case v >= 'A' && v <= 'Z': num.charSize++
case v >='0' && v <='9': num.intSize++
case v >=' ' && v <='\t': num.intSize++
default:
num.ortherSize++
}
}
}
return &num
}
```
## 八、Golang命令行参数
### 1、os.Args解析命令行参数:
os.Args 是一个 string 的切片,用来存储所有的命令行参数。
#### 1)简单demo:
查看所有的命令行参数。
```
//查看命令行参数
func main(){
fmt.Println("命令行的参数有:",len(os.Args),"个")
//得到所有的命令行参数
for i,v :=range os.Args {
fmt.Printf("第%个参数,值为%v\n",i+1,v)
}
}
```
### 2、flag包来解析命令行参数
#### 简单demo:
查看所有的命令行参数
```
//flag包查看命令行参数
func main(){
var user string
var pwd string
var host string
var port int
flag.StringVar(&user,"u","root","用户名默认为root")
flag.StringVar(&pwd,"pwd","123456","密码默认为123456")
flag.StringVar(&host,"h","127.0.0.1","主机名默认为本机")
flag.IntVar(&port,"p",3306,"端口号默认为3306")
//必须将flag进行转换
flag.Parse()
fmt.Println(user,pwd,host,port)
}
```
## 九、Go语言Json
### 1、Json简介:
Json全称 JavaScript Object Notation,是一种轻量级的数据交换格式,有利于阅读与编写。
Json基于机器解析与生成,并有效地提升网络传输效率,通常程序在网络传输时先将数据(结构体、数组、切片、map等)序列华为Json字符串;待到接收方收到Json字符串时,在反序列化恢复成原来的数据类型。
### 2、Json格式:
**在JS中,一切皆为对象**,所以任何数据都可以通过Json类型数据来表示。
Json键值对是用来保存数据的一种方式,key/value对组合中的key写在前面并且使用双引号""包裹住,然后使用 : 分隔,最后连接着value。例如:
```
//最简单的json
{"name":"zsl","age":66,"address":"cq"}
//带数组的json
{"name":"zsl","age":66,"address":["cq","sh"]}
//多个数组对象
[
{"name":"zsl","age":66,"address":"cq"}
{"name":"thl","age":67,"address":"wuxi"}
]
```
### 3、Json序列化
#### 1)基本介绍:
Json序列化是指:将 key/value 结构的数据类型(比如结构体、map、切片等)序列化为Json字符串的操作。
#### 2)序列化使用的方法:
```
func Marshal(v interface{}) ([]byte, error)
```
#### 3)注意事项:
Json序列化必**须使用大写的属性(字段)与大写的结构体**,才能够被 json.Marsual()函数使用。
#### 4)代码演示:
```
//定义一个结构体
type Monster struct {
Name string `json:"monster_name"` //反射机制
Age int `json:"monster_age"`
Birthday string //....
Sal float64
Skill string
}
func testStruct() {
//演示
monster := Monster{
Name :"牛魔王",
Age : 500 ,
Birthday : "2011-11-11",
Sal : 8000.0,
Skill : "牛魔拳",
}
//将monster 序列化
data, err := json.Marshal(&monster) //..
if err != nil {
fmt.Printf("序列号错误 err=%v\n", err)
}
//输出序列化后的结果
fmt.Printf("monster序列化后=%v\n", string(data))
}
//将map进行序列化
func testMap() {
//定义一个map
var a map[string]interface{}
//使用map,需要make
a = make(map[string]interface{})
a["name"] = "红孩儿"
a["age"] = 30
a["address"] = "洪崖洞"
//将a这个map进行序列化
//将monster 序列化
data, err := json.Marshal(a)
if err != nil {
fmt.Printf("序列化错误 err=%v\n", err)
}
//输出序列化后的结果
fmt.Printf("a map 序列化后=%v\n", string(data))
}
//演示对切片进行序列化, 我们这个切片 []map[string]interface{}
func testSlice() {
var slice []map[string]interface{}
var m1 map[string]interface{}
//使用map前,需要先make
m1 = make(map[string]interface{})
m1["name"] = "jack"
m1["age"] = "7"
m1["address"] = "北京"
slice = append(slice, m1)
var m2 map[string]interface{}
//使用map前,需要先make
m2 = make(map[string]interface{})
m2["name"] = "tom"
m2["age"] = "20"
m2["address"] = [2]string{"墨西哥","夏威夷"}
slice = append(slice, m2)
//将切片进行序列化操作
data, err := json.Marshal(slice)
if err != nil {
fmt.Printf("序列化错误 err=%v\n", err)
}
//输出序列化后的结果
fmt.Printf("slice 序列化后=%v\n", string(data))
}
//对基本数据类型序列化,对基本数据类型进行序列化意义不大
func testFloat64() {
var num1 float64 = 2345.67
//对num1进行序列化
data, err := json.Marshal(num1)
if err != nil {
fmt.Printf("序列化错误 err=%v\n", err)
}
//输出序列化后的结果
fmt.Printf("num1 序列化后=%v\n", string(data))
}
func main() {
//演示将结构体, map , 切片进行序列号
testStruct()
testMap()
testSlice()//演示对切片的序列化
testFloat64()//演示对基本数据类型的序列化
}
```
### 4、Json使用tag标签
#### 1)基本介绍:
在Json序列化的过程中,如果需要将属性(字段)取别名或者转换为小写字母开头,那么就需要使用tag标签。
#### 2)基本写法:
```
type Person struct {
Name string `json:"name"`
}
```
#### 3)代码演示:
```
//定义一个结构体,使用tag标签取别名
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Birthday string `json:"birthday"`
}
//演示将一个结构体转换为一个字符串
func ser(p Person) (string,error) {
bytes, err := json.Marshal(p)
return string(bytes),err
}
func main() {
per := Person{"zsl",23,"2344"}
str, err := ser(per)
if err != nil {
fmt.Println("序列化失败,",err)
}
fmt.Println(str)
}
//输出结果为:
{"name":"zsl","age":23,"birthday":"2344"}
```
### 5、Json反序列化
#### 1)基本介绍:
Json反序列化是指:将Json字符串反序列化成对应的数据类型(比如:及饿哦固体、map、切片等)的操作。
#### 2)反序列化使用的方法:
```
func Unmarshal(data []byte, v interface{}) error
```
#### 3)代码实现:
```
//定义一个结构体
type Monster struct {
Name string
Age int
Birthday string //....
Sal float64
Skill string
}
//演示将json字符串,反序列化成struct
func unmarshalStruct() {
//说明str 在项目开发中,是通过网络传输获取到.. 或者是读取文件获取到
str := "{\"Name\":\"牛魔王~~~\",\"Age\":500,\"Birthday\":\"2011-11-11\",\"Sal\":8000,\"Skill\":\"牛魔拳\"}"
//定义一个Monster实例
var monster Monster
err := json.Unmarshal([]byte(str), &monster)
if err != nil {
fmt.Printf("unmarshal err=%v\n", err)
}
fmt.Printf("反序列化后 monster=%v monster.Name=%v \n", monster, monster.Name)
}
//将map进行序列化
func testMap() string {
//定义一个map
var a map[string]interface{}
//使用map,需要make
a = make(map[string]interface{})
a["name"] = "红孩儿~~~~~~"
a["age"] = 30
a["address"] = "洪崖洞"
//将a这个map进行序列化
//将monster 序列化
data, err := json.Marshal(a)
if err != nil {
fmt.Printf("序列化错误 err=%v\n", err)
}
//输出序列化后的结果
//fmt.Printf("a map 序列化后=%v\n", string(data))
return string(data)
}
//演示将json字符串,反序列化成map
func unmarshalMap() {
//str := "{\"address\":\"洪崖洞\",\"age\":30,\"name\":\"红孩儿\"}"
str := testMap()
//定义一个map
var a map[string]interface{}
//反序列化
//注意:反序列化map,不需要make,因为make操作被封装到 Unmarshal函数
err := json.Unmarshal([]byte(str), &a)
if err != nil {
fmt.Printf("unmarshal err=%v\n", err)
}
fmt.Printf("反序列化后 a=%v\n", a)
}
//演示将json字符串,反序列化成切片
func unmarshalSlice() {
str := "[{\"address\":\"北京\",\"age\":\"7\",\"name\":\"jack\"}," +
"{\"address\":[\"墨西哥\",\"夏威夷\"],\"age\":\"20\",\"name\":\"tom\"}]"
//定义一个slice
var slice []map[string]interface{}
//反序列化,不需要make,因为make操作被封装到 Unmarshal函数
err := json.Unmarshal([]byte(str), &slice)
if err != nil {
fmt.Printf("unmarshal err=%v\n", err)
}
fmt.Printf("反序列化后 slice=%v\n", slice)
}
func main() {
unmarshalStruct()
unmarshalMap()
unmarshalSlice()
}
```
#### 4)反序列化注意事项:
- 反序列化的 map或者切片不需要进行make操作,因为在UnMarsual()方法能够自动make操作。
## 十、Golang单元测试
### 1、基本介绍
Go 语言中自带有一个轻量级的测试框架 testing 和自带的 go test 命令来实现单元测试和性能测试,testing 框架和其他语言中的测试框架类似,可以基于这个框架写针对相应函数的测试用例,也可以基于该框架写相应的压力测试用例。
### 2、实现功能:
- 确保每个函数都是可运行的,并且结果运行都是正确的。
- 确保写出来的代码性能优秀。
- 单元测试能够及时发现程序设计与实现的逻辑错误,使错误及时暴露,便于问题的定位与解决。
- 性能测试着重点在于发自按程序设计上面的一些问题,能够让程序在高并发的情况下还能够保持稳定运行。
### 3、快速入门:
在utils包下面创建一个 util1.go 文件,里面放置一个函数:
```
func Add(a int,b int) int {
return a+b
}
```
在utils包下面创建一个命名为 test_util1.go 的文件,专门用于测试 util1.go 文件的函数。
```
func TestAdd(t *testing.T){
add := Add(1, 2)
if add != 3 {
t.Fatalf("函数执行错误,立即自动退出")
} else {
fmt.Println("函数执行成功")
}
}
```
### 4、注意事项:
- 测试用例的文件名字必须以 **XXX_test.go** 方式命名。一般这个 XXX 都是使用被测试的那个文件的文件名来代替。例如:需要测试 util.go 文件,那么可以在同一个包中创建一个 util_test.go 文件来实现对util.go文件的测试。
- 测试用例函数必须以 **TestXXX** 方式来命名,一般是使用 Test+被测试的函数名。比如:TestAdd。
- TestAdd(t *testing.T) 的形参必须要是 **t *testing.T**。
- 一个测试用例文件可以同时测试多个用例函数。
- cmd运行命令:go test -v(程序测试用例运行,且打印日志)。
- 当出现错误的时候,可以使用 t.Fatalf(str string) 来输出错误信息,并停止程序运行。
- t.Logf(str string) 可以输出相应的日志。
- 测试用例中,PASS表示测试正确,FAIL表示测试失败。
## 十一、goroutine(协程)
### 1、进程与线程
- 进程就是程序在操作系统中的一次执行过程,是系统进行资源分配和调度的基本单位。
- 线程是进程的一个执行实例,是程序执行的最小单元,它是一个比进程更小的能够独立运行的基本单位。
- 一个进程能够创建多个线程,同一个进程中的多个线程可以并发的执行任务。
- 一个程序至少一个进程,一个进程至少有一个线程。
### 2、并行与并发
#### 1)并行:
多线程程序在多核上同时运行,这就是并行。
并行是在多个CPU上面有多分线程运行,每个CPU在相同的时间上都是能够执行一个线程,所以多个线程能够同时执行。
#### 2)并发:
多线程程序在单核上同时运行,这就是并发。
并发在同一个CPU上面有多个线程运行,其实是多个线程抢占CPU资源,然后进行线程任务的执行。
### 3、Go协程与Go主线程
#### 1)基本介绍:
在一个Golang主线程上面,可以起多个协程,协程是一个轻量级的线程。也就是说,Golang主线程能够开启多个协程。
#### 2)Go协程的特点:
- 有独立的栈空间。
- 共享程序堆空间。
- 调度由用户控制。
- 协程使用一个轻量级的线程。
示意图:
```
graph LR
A[GO主线程] -->B(协程1)
A[Go主线程] -->C(协程2)
A[Go主线程] -->D(协程3)
A[Go主线程] -->E(协程...)
```
### 4、goroutine(协程)快速入门
#### 1)开启协程方式:
开启协程,就是说在Go主程序上开启一个协程,与主线程一起同时执行,相当于java中的多线程执行方式。
#### 2)使用方式:
go 方法名 --- 这样就能够开启协程。
#### 3)代码演示:
```
func syso() {
for i:=0;i<10;i++ {
fmt.Println("hello goroutine!!",i)
//睡眠一秒
time.Sleep(time.Second)
}
}
func main(){
//go 方法名 --- 这样子就是开启了一个协程
go syso()
for i :=0;i<10;i++ {
fmt.Println("hello Goland",i)
time.Sleep(time.Second)
}
}
```
#### 4)注意事项:
- 如果主线程执行完毕退出了以后,则协程即是未完成,也会退出。
- 如果协程可以在主线程未完成之前就完成了,那么也不会对主线程有影响。
- 主线程是一个物理线程,直接作用于CPU上面,是重量级的,非常耗费资源。
- 协程是从主线程开启的,是轻量级的线程,消耗资源非常少。
- Golang的协程机制是重要的特点,可以轻松突破上万个协程,并发能力强悍。
### 5、Golang设置运行的CPU数目
调用函数查看机器的CPU数目,设置使用的CPU数目.
```
func main(){
//查看机器的CPU数目
cpu := runtime.NumCPU()
fmt.Println("cpu数目为:",cpu)
//自定义需要使用的CPU个数
runtime.GOMAXPROCS(6)
}
```
## 十二、channel(管道)
### 1、channel使用原因
在程序的运行过程中,开启了多个协程goroutine同时操作同一个数据,那么可能会导致数据冲突的问题出现。所以需要使用 channel管道 来解决这个问题。也就是说,为了让程序之间能够相互之间进行通信的操作,避免发生资源的抢占。
### 2、channel基本介绍
- channel本质是一个数据结构---队列。
- 数据是先进先出的操作方式。
- 线程安全,多goroutine访问的时候,不需要加锁,也能够保证线程安全。
- channel是有类型的,一个string的channel只能存放string类型的数据。
### 3、channel声明定义
#### 1)声明方式:
```
var 变量名 chan 数据类型
```
#### 2)举例说明:
```
var intChan chan int (定义了一个存放int类型的channel)
var stringChan chan string (定义了一个存放string类型的channel)
var personChan chan Person (定义了一个存放结构体Person类型的channel)
var personChan1 chan *Person (定义了一个存放结构体Person指针类型的channel)
```
#### 3)注意事项:
- **channel是引用类型**。
- **channel必须初始化才能够写入数据,即 make 以后才能够正常使用**。
- 管道是有数据类型的规定的,只能存放对应的数据类型的数据。
- channel数据放满以后,就不能够继续存放数据。
- 在没有协程的情况下,如果管道中没有数据以后,继续取数据,会报出 dead lock。
### 4、channel的初始化与使用
#### 1)channel的初始化:
初始化的时候,可以定义channel可以存放的数据量的大小。
```
//定义一个channel
var intChan chan int
//初始化channel,意思是 创建了一个可以存放3个int数据类型的管道
intChan = make(chan int,3)
```
#### 2)channel写入、读取数据
```
func main() {
//定义一个channel
var intChan chan int
//初始化channel,意思是 创建了一个可以存放3个int数据类型的管道
intChan = make(chan int, 3)
//查看 intChan 是什么
fmt.Printf("intChan的值为 %v,本身的地址为 %p\n", intChan, &intChan)
//向管道中存入数据
intChan <- 10
intChan <- 20
//查看管道定义的长度:
fmt.Println("管道的长度为:",cap(intChan))
//查看管道存入的数据量:
fmt.Println("管道写入的数据有:",len(intChan))
//从管道中读取数据
num0 := <-intChan
fmt.Println("取出的第一个数据为:",num0)
}
```
### 5、channel更多案例:
#### 1)创建map[string]string的channel
```
func main() {
//定义一个channel
var mapChan chan map[string]string
mapChan = make(chan map[string]string,10)
map1 := make(map[string]string,2)
map1["name"]="zsl"
map1["age"]="23"
map1["birth"]="1996-11-22"
mapChan <- map1
//取出数据
map2 := <- mapChan
fmt.Println(map2)
}
```
#### 2)创建一个结构体的channel
```
type person struct {
name string
age int
}
func main() {
var per chan person
per =make(chan person,3)
cat1 := person{
name:"zsl",
age:23,
}
per <- cat1
cat2 := <- per
fmt.Println(cat2)
}
```
### 6、channel的遍历与关闭
#### 1)channel的关闭
调用 close()函数来关闭管道
```
func main() {
var intChan chan int
intChan = make(chan int,10)
intChan <- 100
intChan <- 200
//关闭管道,这个时候不能继续写入数据到管道中,但是能够继续遍历管道中的数据
close(intChan)
}
```
#### 2)channel的遍历
##### 遍历channel的方式:
使用的是 for-range 的方式进行遍历,模式为:
```
for value :=range 遍历的channel {
fmr.Println(value)
}
```
##### 代码演示:
```
func main() {
var intChan chan int
intChan = make(chan int,10)
intChan <- 100
intChan <- 200
//关闭管道,这个时候不能继续写入数据到管道中,但是能够继续遍历管道中的数据
close(intChan)
//调用for-range来进行遍历的操作
//在遍历的时候,如果管道没有关闭,则会出现 deadback错误。
for v :=range intChan {
fmt.Println(v)
}
}
```
#### 3)channel关闭与遍历的关系:
- **遍历之前必须先要关闭管道,否则会报错 deadback错误。**
- 关闭管道以后,就不能够继续向channel中写入数据。
- channe对象的遍历是使用 for-range 来进行遍历。
### 7、goroutine与channel综合案例一
使用协程与管道进行数据的写入,保证了程序的协作性,提高程序效率,又保证了程序的线程按加权问题,也使用 exitChan 来确保协程执行完毕以后,主线程才停止执行。
```
//写数据的函数
func writeData(intChan chan int) {
for i:=0;i<50;i++ {
intChan <- i+1
fmt.Println("写入的数据,",i+1)
}
close(intChan)
}
//读数据的函数
func readData(intChan chan int,exitChan chan bool) {
for value :=range intChan {
fmt.Println("读取的数据,",value)
}
//读的任务完成
exitChan <- true
close(exitChan)
}
func main() {
//用于存储数据
intChan := make(chan int, 50)
//用于来判断是否读取intChan的数据结束,结束的话,才让程序结束
exitChan := make(chan bool, 1)
//开启协程
go writeData(intChan)
go readData(intChan, exitChan)
//如果协程结束,才让程序结束
for v :=range exitChan {
if v == true {
break
}
}
}
```
### 8、channel使用细节
#### 1)channel只读、只写模式
可以声明为只读,或者只写的模式。使用场景为:当我发送消息的话,可以定义一个只写模式的形参,接收消息的时候, 可以定义一个只读的形参。
```
func main(){
//只读channel
var intChan <-chan int
//只写channel
var stringChan chan<- string
}
```
#### 2)select处理管道取数据阻塞
当在程序运行过程中不知道什么时候关闭管道,那么久可以使用select来进行通道的数据的读取等操作。
```
func main(){
//定义一个管道
intChan := make(chan int,10)
for i:=0;i<10;i++ {
intChan <-i
}
//定义一个管道 ,五个数据的string、
stringChan := make(chan string,5)
for i:=0;i<5;i++ {
stringChan <- "hello"+fmt.Sprintf("%d",i)
}
//在实际开发中,如果不知道该什么时候关闭管道的话,需要用select来解决
for {
select {
case v := <-intChan :
fmt.Printf("从intChannel中取得数据:%d\n",v)
case v := <-stringChan:
fmt.Printf("从stringChannel中取得数据:%s\n",v)
default:
time.Sleep(2000)
fmt.Printf("都取不到数据了\n")
}
}
}
```
#### 3)recover在goroutine中的使用
在程序中的多个协程进行工作,如果一个协程出现错误,那么就会报错panic,如果我们不捕获这个panic的话,会造成整个程序的崩溃。如果在goroutine中使用recover来捕获panic的话,就可以进行处理异常问题,而程序不会出现错误,其他协程继续执行。
##### 代码实现:
```
//函数
func sayHello() {
for i := 0; i < 10; i++ { time.Sleep(time.Second) fmt.Println("hello,world")
}
}
//函数
func test() {
//这里我们可以使用 defer + recover
defer func() {
//捕获 test 抛出的 panic
if err := recover(); err != nil {
fmt.Println("test() 发生错误", err)
}
}()
//定义了一个 map
var myMap map[int]string
myMap[0] = "golang" //error
}
func main() {
go sayHello()
go test()
for i := 0; i < 10; i++ {
fmt.Println("main() ok=", i)
time.Sleep(time.Second)
}
}
```
## 十三、Golang反射
### 1、基本介绍:
> reflect包实现了运行时反射,允许程序操作任意类型的对象。典型用法是用静态类型interface{}保存一个值,通过调用TypeOf获取其动态类型信息,该函数返回一个Type类型值。调用ValueOf函数返回一个Value类型值,该值代表运行时的数据。Zero接受一个Type类型参数并返回一个代表该类型零值的Value类型值。
- 反射可以在运行时动态的获取变量的各种信息,比如变量的类型(type)、类别(kind)等。
- 如果是结构体变量的话,还可以获取到结构体本身的信息(结构体的字段、方法等)。
- 通过反射,可以修改变量的值,可以调用与其相关联的方法。
- 使用反射,可以修改变量的值,可以调用关联的方法。
- 反射的使用,需要导入包 reflect。

### 2、反射的使用场景:
- 当不知道调用哪个函数,根据传入的参数在运行时确定调用的具体结构,这种需要对函数或者方法进行反射的操作。
- 当结构体需要使用 tag进行序列化的时候,可以使用反射生成相应的字符串。
### 3、反射的函数与概念:
#### 1)函数---reflect.TypeOf(变量名)
##### 基本介绍:
获取变量的类型,返回的是 reflect.Type 类型。
##### 方法原型:
```
func TypeOf(i interface{}) Type
TypeOf返回接口中保存的值的类型,TypeOf(nil)会返回nil。
```
##### reflect.Type 介绍:
reflect.Type是一个接口类型,而已通过这个Type调用其已经完成了的方法:
```
type Type interface {
// Kind返回该接口的具体分类
Kind() Kind
// Name返回该类型在自身包内的类型名,如果是未命名类型会返回""
Name() string
// PkgPath返回类型的包路径,即明确指定包的import路径,如"encoding/base64"
// 如果类型为内建类型(string, error)或未命名类型(*T, struct{}, []int),会返回""
PkgPath() string
// 返回类型的字符串表示。该字符串可能会使用短包名(如用base64代替"encoding/base64")
// 也不保证每个类型的字符串表示不同。如果要比较两个类型是否相等,请直接用Type类型比较。
String() string
// 返回要保存一个该类型的值需要多少字节;类似unsafe.Sizeof
Size() uintptr
// 返回当从内存中申请一个该类型值时,会对齐的字节数
Align() int
// 返回当该类型作为结构体的字段时,会对齐的字节数
FieldAlign() int
// 如果该类型实现了u代表的接口,会返回真
Implements(u Type) bool
// 如果该类型的值可以直接赋值给u代表的类型,返回真
AssignableTo(u Type) bool
// 如该类型的值可以转换为u代表的类型,返回真
ConvertibleTo(u Type) bool
// 返回该类型的字位数。如果该类型的Kind不是Int、Uint、Float或Complex,会panic
Bits() int
// 返回array类型的长度,如非数组类型将panic
Len() int
// 返回该类型的元素类型,如果该类型的Kind不是Array、Chan、Map、Ptr或Slice,会panic
Elem() Type
// 返回map类型的键的类型。如非映射类型将panic
Key() Type
// 返回一个channel类型的方向,如非通道类型将会panic
ChanDir() ChanDir
// 返回struct类型的字段数(匿名字段算作一个字段),如非结构体类型将panic
NumField() int
// 返回struct类型的第i个字段的类型,如非结构体或者i不在[0, NumField())内将会panic
Field(i int) StructField
// 返回索引序列指定的嵌套字段的类型,
// 等价于用索引中每个值链式调用本方法,如非结构体将会panic
FieldByIndex(index []int) StructField
// 返回该类型名为name的字段(会查找匿名字段及其子字段),
// 布尔值说明是否找到,如非结构体将panic
FieldByName(name string) (StructField, bool)
// 返回该类型第一个字段名满足函数match的字段,布尔值说明是否找到,如非结构体将会panic
FieldByNameFunc(match func(string) bool) (StructField, bool)
// 如果函数类型的最后一个输入参数是"..."形式的参数,IsVariadic返回真
// 如果这样,t.In(t.NumIn() - 1)返回参数的隐式的实际类型(声明类型的切片)
// 如非函数类型将panic
IsVariadic() bool
// 返回func类型的参数个数,如果不是函数,将会panic
NumIn() int
// 返回func类型的第i个参数的类型,如非函数或者i不在[0, NumIn())内将会panic
In(i int) Type
// 返回func类型的返回值个数,如果不是函数,将会panic
NumOut() int
// 返回func类型的第i个返回值的类型,如非函数或者i不在[0, NumOut())内将会panic
Out(i int) Type
// 返回该类型的方法集中方法的数目
// 匿名字段的方法会被计算;主体类型的方法会屏蔽匿名字段的同名方法;
// 匿名字段导致的歧义方法会滤除
NumMethod() int
// 返回该类型方法集中的第i个方法,i不在[0, NumMethod())范围内时,将导致panic
// 对非接口类型T或*T,返回值的Type字段和Func字段描述方法的未绑定函数状态
// 对接口类型,返回值的Type字段描述方法的签名,Func字段为nil
Method(int) Method
// 根据方法名返回该类型方法集中的方法,使用一个布尔值说明是否发现该方法
// 对非接口类型T或*T,返回值的Type字段和Func字段描述方法的未绑定函数状态
// 对接口类型,返回值的Type字段描述方法的签名,Func字段为nil
MethodByName(string) (Method, bool)
// 内含隐藏或非导出方法
}
```
#### 2)函数---reflect.ValueOf(变量名)
##### 基本介绍:
获取变量的值,返回的reflect.Value是一个结构体类型。
##### 方法原型:
```
func ValueOf(i interface{}) Value
ValueOf返回一个初始化为i接口保管的具体值的Value,ValueOf(nil)返回Value零值。
```
##### reflect.Value介绍:
reflect.Value是一个结构体类型,可以用过这个结构体调用其方法:
```
func ValueOf(i interface{}) Value
func Zero(typ Type) Value
func New(typ Type) Value
func NewAt(typ Type, p unsafe.Pointer) Value
func Indirect(v Value) Value
func MakeSlice(typ Type, len, cap int) Value
func MakeMap(typ Type) Value
func MakeChan(typ Type, buffer int) Value
func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value
func Append(s Value, x ...Value) Value
func AppendSlice(s, t Value) Value
func (v Value) IsValid() bool
func (v Value) IsNil() bool
func (v Value) Kind() Kind
func (v Value) Type() Type
func (v Value) Convert(t Type) Value
func (v Value) Elem() Value
func (v Value) Bool() bool
func (v Value) Int() int64
func (v Value) OverflowInt(x int64) bool
func (v Value) Uint() uint64
func (v Value) OverflowUint(x uint64) bool
func (v Value) Float() float64
func (v Value) OverflowFloat(x float64) bool
func (v Value) Complex() complex128
func (v Value) OverflowComplex(x complex128) bool
func (v Value) Bytes() []byte
func (v Value) String() string
func (v Value) Pointer() uintptr
func (v Value) InterfaceData() [2]uintptr
func (v Value) Slice(i, j int) Value
func (v Value) Slice3(i, j, k int) Value
func (v Value) Cap() int
func (v Value) Len() int
func (v Value) Index(i int) Value
func (v Value) MapIndex(key Value) Value
func (v Value) MapKeys() []Value
func (v Value) NumField() int
func (v Value) Field(i int) Value
func (v Value) FieldByIndex(index []int) Value
func (v Value) FieldByName(name string) Value
func (v Value) FieldByNameFunc(match func(string) bool) Value
func (v Value) Recv() (x Value, ok bool)
func (v Value) TryRecv() (x Value, ok bool)
func (v Value) Send(x Value)
func (v Value) TrySend(x Value) bool
func (v Value) Close()
func (v Value) Call(in []Value) []Value
func (v Value) CallSlice(in []Value) []Value
func (v Value) NumMethod() int
func (v Value) Method(i int) Value
func (v Value) MethodByName(name string) Value
func (v Value) CanAddr() bool
func (v Value) Addr() Value
func (v Value) UnsafeAddr() uintptr
func (v Value) CanInterface() bool
func (v Value) Interface() (i interface{})
func (v Value) CanSet() bool
func (v Value) SetBool(x bool)
func (v Value) SetInt(x int64)
func (v Value) SetUint(x uint64)
func (v Value) SetFloat(x float64)
func (v Value) SetComplex(x complex128)
func (v Value) SetBytes(x []byte)
func (v Value) SetString(x string)
func (v Value) SetPointer(x unsafe.Pointer)
func (v Value) SetCap(n int)
func (v Value) SetLen(n int)
func (v Value) SetMapIndex(key, val Value)
func (v Value) Set(x Value)
func Copy(dst, src Value) int
func DeepEqual(a1, a2 interface{}) bool
```
##### 注意事项:
**在程序开发中,变量、interface{}、reflect.Value 是可以相互转换的,在实际的开发场景中常见。**
- interface{} 转换为 reflect.Value,可以使用: reflect.ValueOf(变量名的方式)
- reflect.Value 转换为 interface{},可以使用: 变量名.interface()
- 将数据转换为 特定类型,使用类型断言,方式为: 变量名.(变量类型)
例如:
```
func test(in interfacve{}) {
//将接口类型转换为 reflect.ValueOf(变量名)的方式
rVal := reflect.ValueOf(in)
//将reflect.Value类型转换为空接口interface{}
iVal := rVal.interface()
//使用类型断言进行变量的转换
student := iVal.(Student)
}
```

### 4、反射入门案例:
#### 1)使用案例一:基本数据类型的反射操作
```
func main(){
var i int
i = 5
//获得数据类型的value
valueOf := reflect.ValueOf(i)
fmt.Println(valueOf)
//获取到反射的Type
typeOf := reflect.TypeOf(i)
//调用kind方法,来获得变量的类型
kind := typeOf.Kind()
fmt.Println(kind)
//将reflect.Value转换为interface
i2 := valueOf.Interface()
test(i2)
}
func test(a interface{}) {
fmt.Println("空接口的值:",a)
//将空接口的值进行类型断言,实现类型的转换
i := a.(int)
fmt.Println("转换为int类型的值为:",i+3)
}
```
#### 2)使用案例二:结构体数据类型的反射操作
```
type Person struct {
name string
age int
card string
phone string
}
func (p Person) show(per Person) {
fmt.Println("show方法的输出:",per)
}
//结构体数据类型的反射
func main(){
person := Person{
"zsl",
23,
"19961122",
"123456",
}
test1(person)
}
func test1(a interface{}) {
typeOf := reflect.TypeOf(a)
fmt.Println(typeOf)
valueOf := reflect.ValueOf(a)
//得到结构体的第三个字段
field:= valueOf.Field(2)
fmt.Println(field)
//获取类别---这个返回值为struct
kind := valueOf.Kind()
fmt.Println("类别为:",kind)
//获取类型---返回值为Person
i2 := valueOf.Type()
fmt.Println("类别为:",i2)
//结构体与interface、reflect.Value之间的转换
i := valueOf.Interface()
person := i.(Person)
fmt.Println(person)
}
```
### 5、反射使用细节
- reflect.Value.Kind,获取的是变量的类别,返回的是一个常量。
- Type与Kind的区别:Type 是类型, Kind 是类别, Type 和 Kind 可能是相同的,也可能是不同的.
- 数据的相互转换一定要保证转换的数据类型正确,否则会包panic。
- 通过反射修改变量:获取 reflect.Value的时候,传入变量的地址,
然后再使用 valueOf.Elem().SetInt(200) 进行修改变量的值。例如:
```
func main() {
var i int
i = 5
//获得数据类型的value
valueOf := reflect.ValueOf(&i)
valueOf.Elem().SetInt(200)
fmt.Printf("%v",i)
}
```
### 6、反射最佳实践:
#### 1)反射常用方法:
- valueOf.NumField() ---- 获取结构体总共有多少个字段
- valueOf.Field(num int) ---- 根据下标获取第几个字段,从下标0开始。
- valUeOf.NumMethod() ---- 获取总共有多少个方法
- valueOf.FieldByName(str string) ---- 根据 str来获取struct中的属性
- valueOf.Elum() ---- 将指针类型的reflect.Value地址 转换为 reflect.Value数据,用于反射操作。
- typeOf.Field(1).Tag.Get("json") ---- 获取结构体中第二个字段的tag标签
```
package main
import (
"fmt"
"reflect"
)
//定义了一个Monster结构体
type Monster struct {
Name string `json:"name"`
Age int `json:"monster_age"`
Score float32 `json:"成绩"`
Sex string
}
//方法,返回两个数的和
func (s Monster) GetSum(n1, n2 int) int {
return n1 + n2
}
//方法, 接收四个值,给s赋值
func (s Monster) Set(name string, age int, score float32, sex string) {
s.Name = name
s.Age = age
s.Score = score
s.Sex = sex
}
//方法,显示s的值
func (s Monster) Print() {
fmt.Println("---start~----")
fmt.Println(s)
fmt.Println("---end~----")
}
func TestStruct(a interface{}) {
//获取reflect.Type 类型
typ := reflect.TypeOf(a)
//获取reflect.Value 类型
val := reflect.ValueOf(a)
//获取到a对应的类别
kd := val.Kind()
//如果传入的不是struct,就退出
if kd != reflect.Struct {
fmt.Println("expect struct")
return
}
//获取到该结构体有几个字段
num := val.NumField()
fmt.Printf("struct has %d fields\n", num) //4
//变量结构体的所有字段
for i := 0; i < num; i++ {
fmt.Printf("Field %d: 值为=%v\n", i, val.Field(i))
//获取到struct标签, 注意需要通过reflect.Type来获取tag标签的值
tagVal := typ.Field(i).Tag.Get("json")
//如果该字段于tag标签就显示,否则就不显示
if tagVal != "" {
fmt.Printf("Field %d: tag为=%v\n", i, tagVal)
}
}
//获取到该结构体有多少个方法
numOfMethod := val.NumMethod()
fmt.Printf("struct has %d methods\n", numOfMethod)
//var params []reflect.Value
//方法的排序默认是按照 函数名的排序(ASCII码)
val.Method(1).Call(nil) //获取到第二个方法。调用它
//调用结构体的第1个方法Method(0)
var params []reflect.Value //声明了 []reflect.Value
params = append(params, reflect.ValueOf(10))
params = append(params, reflect.ValueOf(40))
res := val.Method(0).Call(params) //传入的参数是 []reflect.Value, 返回[]reflect.Value
fmt.Println("res=", res[0].Int()) //返回结果, 返回的结果是 []reflect.Value*/
}
func main() {
//创建了一个Monster实例
var a Monster = Monster{
Name: "黄鼠狼精",
Age: 400,
Score: 30.8,
}
//将Monster实例传递给TestStruct函数
TestStruct(a)
}
```
#### 2)使用反射调用数据变量的方法
程序进行反射以后,程序的方法是来给程序进行自动排序。根据ASCLL码来进行排序。
反射使用的是 Method( num int) 来进行选择执行第几个方法。
反射使用 Call() 来进行参数的传递。如果没有参数的话,传入 nil 即可。方法格式为:
```
func (v Value) Call(in []Value) []Value
//传入的必须是 reflect.Value 切片或者reflect.Value数组
```
例如:
```
//调用第三个方法,传入参数为10 。
valueOf.Method(2).Call(10)
//调用第二个方法,传入参数为切片
var params []reflect.Value //声明一个切片
params = append(params, reflect.ValueOf(10)) //向切片中添加参数
params = append(params, reflect.ValueOf(40)) //向切片中添加参数
valueOf.Method(1).Call(params) //传入参数,调用第二个方法
```
## 十四、Golang网络编程
### 1、网络编程基本介绍
Golang的主要设计目标之一就是面向大规后端服务程序,网络通信这块是服务端程序必不可少的一个重要不组成部分。
#### 1)网络编程的两种模式
##### 第一种:TCP socket编程
TCP socket编程,是网络编程的主流。之所以叫TCP socket,是因为底层是基于TCP/ip协议。
##### 第二种:b/s结构的http编程
b/s结构的http编程,我们使用浏览器去访问服务器时,使用的是http协议,而http底层依赖的是tcp socket实现的。
#### 2)网线、网卡、无线网卡
计算机要进行相互之间的通信,需要使用网线、网卡或者是无线网卡。
### 2、TCP/IP协议
TCP/IP(Transmission Control Protocol/Internet Protocol)的简写,中文译名为**传输控制协议/因特网互联协议**,又叫**网络通讯协议**。
这个协议是 Internet 最基本的协议、Internet 国际互联网络的基础,简单地说,就是由网络层的 IP 协议和传输层的 TCP 协议组成的。
### 3、 IP地址与端口
#### 1)IP的地址
##### 基本介绍:
每隔Internet上每台主机和路由器都有一个IP地址,它包括网络号和主机号,ip地址有 IPV4(32位)、IPV6(128位)。
#### 2)端口
##### 基本介绍:
一个IP地址,拥有65536(256*256)个端口。
服务器端监听一个端口,然后进行服务之间的交互,该端口就是其他程序与服务器之间的通信的通道。
一旦一个端口被某个程序监听了以后(也就是端口被占用),其他程序就不能够再次监听该端口。
##### 基本分类:
端口号 | 端口介绍 | 注意事项
---|---|---
0 号端口 | 保留端口 | 程序员不能使用
1-1024 号端口 | 固定端口 | 程序员不能使用
22 号端口 | SSH远程登录协议端口 | 程序员不能使用
23 号端口 | Telnet端口 | 程序员不能使用
21 号端口 | ftp端口 | 程序员不能使用
25 号端口 | smtp服务端口 | 程序员不能使用
80 号端口 | iis服务端口 | 程序员不能使用
1025-65535 号端口 | 动态端口 | 程序员可以使用
##### 注意事项:
- 在计算机中,应该尽量少开启端口。
- 一个端口只能被一个程序监听。
- 使用 netstat -an 可以查看端口那些已经被监听。
- 可以使用 netstat –anb 来查看监听端口的 pid,在结合任务管理器关闭不安全的端口。
### 4、tcp socket 编程的客户端和服务端
#### 1)服务器端处理流程:
第一步:监听端口,比如8888号端口来进行监听。
第二步:接收客户端的tcp连接,建立起客户端与服务器端的连接。
第三步:创建goroutine,处理该链接的请求。
#### 2)客户端处理流程:
第一步:建立起与服务器的连接(首先,先客户端自动为这个程序分配一个端口,然后让这个端口与socket的端口进行交互,形成连接)。
第二步:发送请求数据,接收服务器端返回来的结果数据。
第三步:关闭socket连接。
#### 3)客户端与服务器端的图例:
```
graph TB
H[协程A] --> A(服务器)
F[协程B] --> A(服务器)
G[协程C] --> A(服务器)
I[协程...] --> A(服务器)
A[服务器] -->|连接|B(客户端A)
B -->|连接|A
A[服务器] -->|连接|C(客户端B)
C -->|连接|A
A[服务器] -->|连接|D(客户端C)
D -->|连接|A
A[服务器] -->|连接|E(客户端...)
E -->|连接|A
```
#### 4)服务器端代码实现:
```
func main(){
fmt.Println("服务器开始进行监听了")
//使用的协议是使用 tcp协议,且监听的是本机的 8888 端口
listener, err := net.Listen("tcp", "0.0.0.0:8888")
//判断是否监听成功,未成功的话,直接程序结束
if err != nil {
fmt.Println("端口监听失败")
return
}
//相当于是开启一直监听模式,程序结束才关闭。相当于java中的 io操作
defer listener.Close()
for {
//循环等待客户端来与服务端进行连接,也就是说建立多个连接
conn, err1 := listener.Accept()
if err1 != nil {
fmt.Println("连接失败,请重试",err1)
} else {
fmt.Println("连接成功,",conn)
}
//当连接成功以后,为客户端监理一个协程操作
go process(conn)
}
}
func process(conn net.Conn) {
//用完以后,关闭连接
defer conn.Close()
var bt []byte
bt = make([]byte,512)
//循环读取数据,返回的 n 表示数据的长度
n, err := conn.Read(bt)
if err != nil {
fmt.Println("服务器读取客户端发送来的数据失败,",err)
}
//将客户端发送来的数据接收到
fmt.Println(string(bt[:n]))
}
```
#### 4)客户端代码的实现:
```
func main(){
conn, err := net.Dial("tcp", "127.0.0.1:8888")
if err != nil {
fmt.Println("客户端无法实现连接", err)
return
}
//客户端发送单行数据,然后就退出
//os.Stdin表示标准输入
reader := bufio.NewReader(os.Stdin)
//从终端读取一行用户输入,并准备发送给服务器
readString, err1 := reader.ReadString('\n')
if err1 != nil {
fmt.Println("从终端读取数据失败",err1)
}
//将终端读取到的数据发送到服务器
write, err2 := conn.Write([]byte(readString))
if err2 != nil {
fmt.Println("发送到服务器失败")
}
fmt.Println("客户端发送成功,数据为:",write)
}
```
## 十五、Golang整合redis
### 1、Golang安装Redis第三方库
先进入到GOPATH目录,输入命令:
```
go get github.com/garyburd/redigo/redis
```
然后在GOPATH目录下的src目录下出现了一个专门用于操作Redis的文件。
### 2、Golang连接Redis
直接调用下载的第三方函数来进行redis的连接。
```
func main() {
//通过远程连接到redis数据库
//第一个参数是指定什么方式的连接,
//第二个参数指的是IP地址与端口号
//第一个返回值conn使用一个结构体,主要是用于存放连接信息的
//第二个返回值 err 是返回连接的错误信息
conn, err := redis.Dial("tcp", "192.168.21.133:6379")
if err != nil {
fmt.Println("连接失败,",err)
return
}
//连接成功
fmt.Println("连接成功,",conn)
}
```
### 3、Golang连接Redis的Demo
```
//操作String数据类型
//插入数据
_, err1 := conn.Do("set", "name", "zsl")
if err1 != nil {
fmt.Println("set数据失败",err1)
}
fmt.Println("set数据成功:")
//取出数据,使用redis.String()方法来实现数据的转换
do, err2 := redis.String(conn.Do("Get", "name"))
if err2 != nil{
fmt.Println("获取数据失败")
}
fmt.Println("取出的数据为:",do)
//操作Hash数据类型
//插入数据
_, err1 := conn.Do("HSet", "user2","name2", "zsl2")
if err1 != nil {
fmt.Println("set数据失败",err1)
return
}
fmt.Println("set数据成功:")
//取出数据,使用redis.String()方法来实现数据的转换
do, err2 := redis.String(conn.Do("HGet", "user2","name2"))
if err2 != nil{
fmt.Println("获取数据失败")
}
fmt.Println("取出的数据为:",do)
```
### 4、Golang使用Redis连接池
```
func init(){
pool = &redis.Pool{
//最大空闲连接数,也就是创建8个线程
MaxIdle:8,
//最大空闲时间,表示和数据库的最大连接数,0表示没有限制。
MaxActive:0,
//最大空闲时间,当空闲时间超出以后未使用,就会返回得到连接池
IdleTimeout:100,
//初始化连接池的代码
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp","192.168.21.133:6379")
},
}
//关闭redis连接池
//pool.Close()
}
func main(){
//从数据库中获取一个连接池
conn := pool.Get()
//关闭这个连接,让这个连接返回到连接池
defer conn.Close()
_, err1 := conn.Do("set", "qq", "zsl")
if err1 != nil {
fmt.Println("set数据失败",err1)
}
fmt.Println("set数据成功:")
//取出数据,使用redis.String()方法来实现数据的转换
do, err2 := redis.String(conn.Do("Get", "qq"))
if err2 != nil{
fmt.Println("获取数据失败")
}
fmt.Println("取出的数据为:",do)
}
```
## 十六、数据结构
### 1、数据结构基本介绍
数据结构是一门专门研究算法的学科,自从有了编程语言也就有了数据结构,能够编码成更加优美的编程方式。
程序 = 数据结构 + 算法。
### 2、数据结构与算法的关系
算法是程序的灵魂,算法的基石是数据结构。数据结构能够保证算法更加简单,逻辑更加清晰。使用数据结构的算法能够让程序更加坚如磐石。
### 3、稀疏sparsearray数组
#### 1)基本介绍:
当一个数组中的大部分元素为0,或者同一个值的数组时,可以使用稀疏数组来保存该数组。
#### 2)稀疏数组处理方法:
第一步:记录数组一共有几行几列,有多少个不同的值。
第二步:把具有不同的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模。
#### 3)图像表示:
稀疏矩阵图为:
列行 | 第0列 | 第1列 | 第2列 | 第3列 | 第4列
---|---|---|---|---|---
第0行 | 3 | 0 | 0 | 0 | 0
第1行 | 0 | 0 | 2 | 0 | -9
第2行 | 0 | 0 | 0 | 0 | 0
第3行 | 0 | 7 | 0 | 0 | 0
记录的小规模数组为:
列行 | 行 | 列 | 值
---|---|---|---
(0)| 0 | 0 | 3
(1)| 1 | 2 | 2
(2)| 1 | 4 | -9
(3)| 3 | 1 | 7
#### 4)案例演示
##### 需求情况:
1) 使用稀疏数组,来保留类似前面的二维数组(棋盘、地图等等)
2) 将稀疏矩阵存入到一个结构体中,实现行、列、value的存储。
##### 代码演示:
```
/**
稀疏矩阵的解析与返回
*/
//定义一个专门用于接受稀疏矩阵不为0 的数据的结构体
type Node struct {
//存储行
row int
//存储列
col int
//存储值
val int
}
func main(){
//1、先创建一个原始数组
var arr [11][11]int
arr[1][2] = 1
arr[2][3] = 2
//输出原始数组
for _,v :=range arr{
for _,v2 := range v {
fmt.Printf(" %d ",v2)
}
fmt.Println(" ")
}
//将稀疏矩阵转换为一个 行列值 的切片
var nodes []Node
//初始化节点,也就是需要存储一下这个稀疏矩阵是多少行,多少列
node :=Node{
row:len(arr),
col:len(arr),
val:0,
}
nodes = append(nodes,node)
//遍历系数矩阵将数据存入Node切片中
for i,v :=range arr{
for j,v2 := range v {
if v2 != 0 {
node := Node{
row:i,
col:j,
val:v2,
}
//将数据append到node切片中
nodes = append(nodes, node)
}
}
}
//输出这个nodes
for i,v :=range nodes {
//因为第一个节点是存储的是这个稀疏矩阵的行数与列数
if i == 0 {
fmt.Printf("这个矩阵一共有%d行,一共有%d列\n",v.row,v.col)
continue
}
fmt.Printf("第%d个数:行:%d 列:%d 值:%d\n",i,v.row,v.col,v.val)
}
//恢复这个稀疏矩阵,先创建这个数组
var arr3 [11][11]int
for i,v :=range nodes {
//因为第一个数据存的是这个矩阵的行和列,不应该放入到稀疏矩阵中
if i != 0 {
//将数据提供给定义的这个数组
arr3[v.row][v.col] = v.val
}
}
//输出这个返回了的稀疏矩阵
fmt.Println(" ")
fmt.Println("重组的矩阵为:")
for _,v :=range arr3{
for _,v2 := range v {
fmt.Printf(" %d ",v2)
}
fmt.Println(" ")
}
}
```
### 4、队列(queue)
#### 1)基本介绍:
队列是一个有序列表,可以使用**数组或者链表来实现**。
队列遵循的是 **先入先出** 原则,先存入的数据先取出来,后存入的数据后取出来。
#### 2)使用数组模拟队列
队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下:
- 声明maxSize来表明该队列的最大容量。
- 使用两个变量front与rear分别标记队列前端与后端的下标,front是随着数据输出而改变,rear是随着数据的输入而该表。
第一次:在初始化数组的时候,有一个空的数组,而front与rear均为-1:
队列位置|队列的值
---|---
maxSize-1 |
4 |
3 |
2 |
1 |
0 |
第二次:存入数据的时候,rear会变化为2,而front依然不变:
队列位置|队列的值
---|---
maxSize-1 |
4 |
3 |
2 | 45
1 | 34
0 | 66
注意:这里存入数据的话,是先在0的位置存入66,然后再在1的位置存入34;接着再在2的位置存入45。
第三次:取出数据的时候,先取出的是第一个数据,front的值改变为1,rear的值依然为2:
队列位置|队列的值
---|---
maxSize-1 |
4 |
3 |
2 | 45
1 | 34
0 |
#### 3)非环形数组队列
##### 需求分析:
第一步:创建一个数组arr,作为一个队列的原型。
第二步:使用front表示队列头,初始化front的值为-1。
第三步:使用rear表示队列尾,初始化rear的值为-1。
第四步:完成队列的基本查找。
##### 异常情况:
当队列满了以后,取出数据,但是也无法实现继续在前面添加数据。
##### 代码实现:
```
//使用数组实现 非环形队列
//定义一个常量来规定这个队列的长度
const lens int = 4
//创建一个结构体来进行管理一个队列
type Queue struct {
maxSize int //队列的最大长度
array [lens]int //数组,需要给这个数组添加一个方法与操作,才能够变成队列
front int //指向队列的队头
rear int //执行队列的队尾
}
//向队列中添加数据
func (queue *Queue)addNum(val int)(error){
//先判断队列是否已经满了
if queue.rear == queue.maxSize -1 {
return errors.New("队列已满")
}
//队列没满的话,就会将数据添加到队列中
queue.rear++
queue.array[queue.rear] = val
fmt.Println("添加数据成功")
return nil
}
//从队列中按顺序取出一个数据
func (queue *Queue) getQueue()(int,error) {
//判断队列是否为空
if queue.front == queue.rear {
return -1,errors.New("队列已空")
}
queue.front++
val := queue.array[queue.front]
return val,nil
}
//显示队列
func (queue Queue)showQueue(){
fmt.Println("队列的详细信息微:")
for i:=queue.front+1;i<=queue.rear;i++ {
fmt.Printf("array[%d] = %d\t",i,queue.array[i])
}
fmt.Println(" ")
}
func main(){
queue := Queue{
maxSize:lens,
front:-1,
rear:-1,
}
var key string
var val int
for {
fmt.Println("1、输入add表示添加队列数据")
fmt.Println("2、输入get表示获取队列数据")
fmt.Println("3、输入show表示显示队列数据")
fmt.Println("4、输入exit退出程序")
fmt.Scanln(&key)
switch key {
case "add":
fmt.Println("请输入你需要添加到队列的数据")
fmt.Scanln(&val)
err := queue.addNum(val)
if err != nil {
fmt.Println("添加队列数据失败,",err.Error())
}
case "get":
val, err := queue.getQueue()
if err != nil{
fmt.Println(err.Error())
} else {
fmt.Println("从队列中取出的值为:",val)
}
case "show":
queue.showQueue()
case "exit":
fmt.Println("get")
}
}
}
```
#### 4)环形数组队列
##### 基本介绍:
将数组形成一个环状,实现非环形数组队列的优化。
##### 分析思路:
1) 什么时候表示队列满 (tail + 1) % maxSize = head
2) tail == head 表示空
3) 初始化时, tail = 0 head = 0
4) 怎么统计该队列有多少个元素 (tail + maxSize - head ) % maxSize
##### 代码实现:
```
//使用环形数组实现队列
//定义一个常量,实现设置链表的长度
const lens int = 5
//定义一个结构体,来实现环形队列的管理
type CirclQueue struct {
maxSize int //最大的链表长度
array [lens]int //数组
head int //执行队列队首
tail int //执行队列队尾
}
//入队列
func (queue *CirclQueue) push(val int)(error){
if queue.isFull() {
return errors.New("队列已满")
}
//将这个值放在最后的尾部
queue.array[queue.tail] = val
queue.tail = (queue.tail + 1)%queue.maxSize
return nil
}
//出队列
func (queue *CirclQueue) pop()(val int,err error){
if queue.isEmpty(){
return 0,errors.New("队列已空")
}
//取出数据
val1 := queue.array[queue.head]
queue.head = (queue.head + 1)%queue.maxSize
return val1,nil
}
//显示队列
func (queue *CirclQueue) listQueue(){
size := queue.Size()
if size == 0 {
fmt.Println("队列为空")
return
}
//输出队列
fmt.Println("输出队列")
tempHead := queue.head
for i:=0;i<size;i++ {
fmt.Printf("array[%d]=%d \t",tempHead,queue.array[tempHead])
tempHead = (tempHead + 1) % queue.maxSize
}
fmt.Println(" ")
}
//判断环形队列是否已满
func (queue CirclQueue) isFull() bool{
return (queue.tail+1) % queue.maxSize == queue.head
}
//判断环形队列是否已空
func (queue CirclQueue) isEmpty() bool{
return queue.tail == queue.head
}
//获得环形队列有多少个元素
func (queue CirclQueue) Size() int{
return (queue.tail + queue.maxSize-queue.head) % queue.maxSize
}
func main(){
queue := &CirclQueue{
maxSize:lens,
head:0,
tail:0,
}
var key string
var val int
for {
fmt.Println("1、输入add表示添加队列数据")
fmt.Println("2、输入get表示获取队列数据")
fmt.Println("3、输入show表示显示队列数据")
fmt.Println("4、输入exit退出程序")
fmt.Scanln(&key)
switch key {
case "add":
fmt.Println("请输入你需要添加到队列的数据")
fmt.Scanln(&val)
err := queue.push(val)
if err != nil {
fmt.Println("添加队列数据失败,",err.Error())
}
case "get":
val, err := queue.pop()
if err != nil{
fmt.Println(err.Error())
} else {
fmt.Println("从队列中取出的值为:",val)
}
case "show":
queue.listQueue()
case "exit":
fmt.Println("get")
}
}
}
```
### 5、链表
#### 1)链表基本介绍
链表是一个物理存储单元上**非连续、非顺序的存储结构**,数据元素的逻辑顺序是通过链表中的指针链接顺序来形成的一系列节点。
#### 2)链表的结构
链表的每个节点包括两部分:一部分是用于存储元素的数据的数据域;一部分是用于存储下一个节点的指针域。
#### 3)链表示意图

**注意:** 通常情况下,为了对单链表进行增删改查的操作,我们都会给他设置一个头结点,这个头结点的作用是用于标记链表头,且这个节点不存放数据。
#### 4)链表的应用实例----单向链表
##### 需求分析:
使用带 head 头的单向链表实现 –水浒英雄排行榜管理。完成对英雄人物的增删改查操作, 注: 删除和修改,查找可以考虑学员独立完成
##### 代码演示:
```
import (
"fmt"
)
//定义一个结构体
type HeroNode struct {
no int
name string
nickname string
//指向下一个节点
next *HeroNode
}
//给链表插入一个节点
//方式一:在单链表的最后加入一个节点。
//第一个形参表示的是将节点插入到哪一个头结点的链表中;第二个形参表示的是新插入的这个节点
func InsertHerNode(head *HeroNode,newHeroNode *HeroNode){
//先找到该链表的最后节点
temp := head
for {
//如果 temp.next == nil 的话,就查找到了最后一个节点了
if temp.next == nil {
break
}
//让temp不断的指向下一个节点
temp = temp.next
}
//让新节点加入到链表的结尾
temp.next = newHeroNode
}
//方式二:根据hero的no编号从小到大进行有序插入。
//第一个形参表示的是将节点插入到哪一个头结点的链表中;第二个形参表示的是新插入的这个节点
func InsertHerNodeByNo(head *HeroNode,newHeroNode *HeroNode){
//创建一个辅助节点
temp := head
//添加一个标识符,默认为允许添加数据的意思
flag := true
//让插入的节点的no,与temp的下一个节点的no进行比较
for {
//表明该节点进入到了链表的最后
if temp.next == nil {
break
} else if temp.next.no > newHeroNode.no {
//说明插入的节点应该插入到temp的后面去
break
} else if temp.next.no == newHeroNode.no {
//说明链表中已经存在这个no节点,不能够继续插入
flag = false
break
}
temp = temp.next
}
if flag == false {
fmt.Printf("已经存在这个no节点%d,不能够重新插入",newHeroNode.no)
return
} else {
//进行节点的插入操作
newHeroNode.next = temp.next
temp.next = newHeroNode
}
}
//单链表的节点删除操作
func deleteHeroNode(head *HeroNode,no int){
temp := head
//表示的是没找到这个no
flag := false
//使用比较的方式进行查找到需要删除的no节点
for {
//表明该节点进入到了链表的最后
if temp.next == nil {
break
} else if temp.next.no == no {
//说明链表中已经存在这个no节点,则表示的是找到了这个节点
flag = true
break
}
temp = temp.next
}
//找到了数据,删除这个节点,让这个节点指向下下个数据节点即可
if flag {
temp.next = temp.next.next
} else {
fmt.Println("没查找到这个no为 %d 的节点",no)
}
}
//显示链表的所有信息
func ListHeroNode(head *HeroNode){
temp := head
//判断是否为空链表
if temp.next == nil {
fmt.Println("这个是空链表,请插入数据在遍历。")
return
}
//遍历这个链表
for {
//输出链表,实现遍历的效果
fmt.Printf("[%d ,%s ,%s]\n",temp.next.no,temp.next.name,temp.next.nickname)
temp = temp.next
//判断是否在链表的尾部了,如果已经在链表的尾部,那么就停止遍历
if temp.next == nil {
fmt.Println("\n链表的节点遍历完成")
break
}
}
}
func main() {
//第一步:创建一个链表的头结点
head := &HeroNode{}
//第二步:创建一个新的HerNode节点
hero1 := &HeroNode{
no:1,
name:"宋江",
nickname:"及时雨",
}
hero2 := &HeroNode{
no:2,
name:"卢俊义",
nickname:"玉麒麟",
}
hero3 := &HeroNode{
no:3,
name:"林冲",
nickname:"豹子头",
}
//将 英雄 添加到hero这个链表中
InsertHerNodeByNo(head,hero2)
InsertHerNodeByNo(head,hero1)
InsertHerNodeByNo(head,hero3)
//遍历节点
ListHeroNode(head)
//删除一个节点
deleteHeroNode(head,2)
ListHeroNode(head)
}
```
#### 5)链表的应用实例----双向链表
##### 基本介绍:
双向链表是链表中的一种,它的每一个数据节点都含有两个指针,分别指向的是前一个节点以及后面一个节点。从表的任意节点开始,都能够方便的访问其前区域后继节点。
##### 示例图:

##### 代码实现:
```
package main
import (
"fmt"
)
//单向链表的使用
//定义一个结构体
type HeroNode11 struct {
no int
name string
nickname string
//指向前一个节点
pre *HeroNode11
//指向下一个节点
next *HeroNode11
}
//给双向链表插入一个节点
//方式一:在单链表的最后加入一个节点。
//第一个形参表示的是将节点插入到哪一个头结点的链表中;第二个形参表示的是新插入的这个节点
func InsertHerNode1(head *HeroNode11,newHeroNode11 *HeroNode11){
//先找到该链表的最后节点
temp := head
for {
//如果 temp.next == nil 的话,就查找到了最后一个节点了
if temp.next == nil {
break
}
//让temp不断的指向下一个节点
temp = temp.next
}
//让新节点加入到链表的结尾
temp.next = newHeroNode11
//让这个节点的前驱指向的是前一个节点
newHeroNode11.pre = temp
}
//方式二:根据hero的no编号从小到大进行有序插入。
//第一个形参表示的是将节点插入到哪一个头结点的链表中;第二个形参表示的是新插入的这个节点
func InsertHerNodeByNo1(head *HeroNode11,newHeroNode *HeroNode11){
//创建一个辅助节点
temp := head
//添加一个标识符,默认为允许添加数据的意思
flag := true
//让插入的节点的no,与temp的下一个节点的no进行比较
for {
//表明该节点进入到了链表的最后
if temp.next == nil {
break
} else if temp.next.no > newHeroNode.no {
//说明插入的节点应该插入到temp的后面去
break
} else if temp.next.no == newHeroNode.no {
//说明链表中已经存在这个no节点,不能够继续插入
flag = false
break
}
temp = temp.next
}
if flag == false {
fmt.Printf("已经存在这个no节点%d,不能够重新插入",newHeroNode.no)
return
} else {
//进行节点的插入操作
newHeroNode.next = temp.next
newHeroNode.pre = temp
if temp.next != nil {
temp.next.pre = newHeroNode
}
temp.next = newHeroNode
}
}
//前序遍历显示链表的所有信息
func ListHeroNode11(head *HeroNode11){
temp := head
//判断是否为空链表
if temp.next == nil {
fmt.Println("这个是空链表,请插入数据在遍历。")
return
}
//遍历这个链表
for {
//输出链表,实现遍历的效果
fmt.Printf("[%d ,%s ,%s]\n",temp.next.no,temp.next.name,temp.next.nickname)
temp = temp.next
//判断是否在链表的尾部了,如果已经在链表的尾部,那么就停止遍历
if temp.next == nil {
fmt.Println("\n链表的节点遍历完成")
break
}
}
}
//后序遍历显示链表的所有信息
func ListHeroNode12(head *HeroNode11){
temp := head
if temp.next == nil {
fmt.Println("空空如也。。。。")
return
}
for {
if temp.next == nil {
break
}
temp = temp.next
}
for {
fmt.Printf("[%d ,%s ,%s]\n",temp.no,temp.name,temp.nickname)
//判断是否链表头
temp = temp.pre
if temp.pre == nil {
fmt.Println("\n后序遍历链表的节点遍历完成")
break
}
}
}
//双向链表删除一个节点
func deleteHeroNode1(head *HeroNode11,no int){
temp := head
//表示的是没找到这个no
flag := false
//使用比较的方式进行查找到需要删除的no节点
for {
//表明该节点进入到了链表的最后
if temp.next == nil {
break
} else if temp.next.no == no {
//说明链表中已经存在这个no节点,则表示的是找到了这个节点
flag = true
break
}
temp = temp.next
}
//找到了数据,删除这个节点,让这个节点指向下下个数据节点即可
if flag {
temp.next = temp.next.next
if temp.next != nil{
temp.next.pre = temp
}
} else {
fmt.Println("没查找到这个no为 %d 的节点",no)
}
}
func main() {
//第一步:创建一个链表的头结点
head := &HeroNode11{}
//第二步:创建一个新的HerNode节点
hero1 := &HeroNode11{
no:1,
name:"宋江",
nickname:"及时雨",
}
hero2 := &HeroNode11{
no:2,
name:"卢俊义",
nickname:"玉麒麟",
}
hero3 := &HeroNode11{
no:3,
name:"林冲",
nickname:"豹子头",
}
//将 英雄 添加到hero这个链表中
InsertHerNodeByNo1(head,hero2)
InsertHerNodeByNo1(head,hero1)
InsertHerNodeByNo1(head,hero3)
deleteHeroNode1(head,1)
//遍历节点
ListHeroNode11(head)
ListHeroNode12(head)
}
```
#### 6)链表的应用实例----环形单向链表
##### 示例图:

##### 代码演示:
```
package main
import "fmt"
//环形单向链表
//先定义一个结构体
type CatNode struct {
no int
name string
next *CatNode
}
//插入一个元素
func InsertCatNode(head *CatNode,newCatNode *CatNode){
//判断是不是插入的第一只猫,如果是第一只猫,那么久将这只猫存放在头节点中
if head.next == nil {
head.no = newCatNode.no
head.name = newCatNode.name
//让这个链表形成一个环状
head.next = head
return
}
//如果不是第一只猫,那么久加入到环形队列中
temp := head
//判断什么时候是在了队尾
for {
if temp.next == head {
break
}
temp = temp.next
}
temp.next = newCatNode
newCatNode.next = head
}
//输出环形链表
func ShowCatNodes(head *CatNode){
temp := head
//判断是否是空链表
if temp.next == nil {
fmt.Println("空空如也。。。")
return
}
for {
fmt.Printf("Cat的信息为:%d==%s\n",temp.no,temp.name)
if temp.next == head {
fmt.Println("遍历完成")
break
}
temp = temp.next
}
}
//删除环形队列节点
func deleteCatNode(head *CatNode,no int)(*CatNode){
temp := head
helper := head
//判断是否是空链表
if temp.next == nil {
fmt.Println("这个是一个空链表,不能够删除")
return head
}
//判断是否是一个节点
if temp.next == head {
temp.next = nil
return head
}
//将helper定位到最后
for {
if helper.next == head {
break
}
helper = helper.next
}
//两个及两个以上的节点
flag := true //表示未删除
for {
if temp.next == head {
//如果比较到这里,就说明没找到
break
}
if temp.no == no {
//如果删除了头结点,则需要将头结点放置在下一个元素中
if temp == head {
head = head.next
}
//找到了这个节点
helper.next = temp.next
fmt.Println("删除成功")
flag = false
}
temp = temp.next
helper = helper.next
}
//在比较一次最后一个节点
//如果flag为真,表明上面没有被删除
if flag {
if temp.no == no {
helper.next = temp.next
fmt.Println("删除成功")
} else {
fmt.Println("没查找到这个节点")
}
}
return head
}
func main () {
//县创建一个头结点,并且这个头结点必须要存放数据
head := &CatNode{}
//创建第一只猫
cat1 := &CatNode{
no: 1,
name: "qqq",
}
cat2 := &CatNode{
no: 2,
name: "www",
}
//cat3 := &CatNode{
// no: 3,
// name: "eee",
//}
InsertCatNode(head,cat1)
InsertCatNode(head,cat2)
//InsertCatNode(head,cat3)
head1 := deleteCatNode(head, 1)
ShowCatNodes(head1)
}
```
#### 7)约瑟夫问题
##### 问题介绍:
设编号为 1,2,… n 的 n 个人围坐一圈,约定编号为 k(1<=k<=n)的人从 1 开始报数,数到 m 的那个人出列,它的下一位又从 1 开始报数,数到 m 的那个人又出列,依次类推, 直到所有人出列为止,由此产生一个出队编号的序列。
|
SQL
|
UTF-8
| 856
| 2.78125
| 3
|
[] |
no_license
|
# Host: localhost (Version: 5.5.32)
# Date: 2014-06-23 19:22:35
# Generator: MySQL-Front 5.3 (Build 4.100)
/*!40101 SET NAMES utf8 */;
#
# Structure for table "order"
#
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order` (
`id` int(7) unsigned zerofill NOT NULL AUTO_INCREMENT,
`nama` varchar(255) DEFAULT NULL,
`alamat` varchar(255) DEFAULT NULL,
`telepon` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`tanggal` date NOT NULL DEFAULT '0000-00-00',
`status_bayar` varchar(1) NOT NULL DEFAULT '0' COMMENT '0 = belum , 1 = lunas',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
#
# Data for table "order"
#
INSERT INTO `order` VALUES (0000001,'Ardha Herdianto','Perumahan Surabaya','089677052285','ardha2008@gmail.com','2014-06-23','0'),(0000002,'Budi','asdkjaskldjaklsdj','932472384729834','budi@gmail.com','2014-06-24','0');
|
C++
|
UTF-8
| 5,532
| 2.578125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
// Copyright (c) 2018-2020, Zhirnov Andrey. For more information see 'LICENSE'
#pragma once
#include "stl/Math/Math.h"
#include "stl/Math/Bytes.h"
#include "stl/Memory/UntypedAllocator.h"
namespace FGC
{
template <typename AllocatorType> struct LinearAllocator;
template <typename T, typename AllocatorType> struct StdLinearAllocator;
template <typename AllocatorType> struct UntypedLinearAllocator;
//
// Linear Pool Allocator
//
template <typename AllocatorType = UntypedAlignedAllocator>
struct LinearAllocator final
{
// types
private:
struct Block
{
void * ptr = null;
BytesU size; // used memory size
BytesU capacity; // size of block
};
using Allocator_t = AllocatorType;
using Blocks_t = std::vector< Block >;
// variables
private:
Blocks_t _blocks;
BytesU _blockSize = 1024_b;
Allocator_t _alloc;
static constexpr BytesU _ptrAlign = SizeOf<void *>;
// methods
public:
LinearAllocator () {}
explicit LinearAllocator (const Allocator_t &alloc) : _alloc{alloc}
{
_blocks.reserve( 16 );
}
LinearAllocator (LinearAllocator &&other) :
_blocks{ std::move(other._blocks) },
_blockSize{ other._blockSize },
_alloc{ std::move(other._alloc) }
{}
LinearAllocator (const LinearAllocator &) = delete;
LinearAllocator& operator = (const LinearAllocator &) = delete;
LinearAllocator& operator = (LinearAllocator &&rhs)
{
Release();
_blocks = std::move(rhs._blocks);
_blockSize = rhs._blockSize;
_alloc = std::move(rhs._alloc);
return *this;
}
~LinearAllocator ()
{
Release();
}
void SetBlockSize (BytesU size)
{
_blockSize = size;
}
ND_ FG_ALLOCATOR void* Alloc (const BytesU size, const BytesU align)
{
for (auto& block : _blocks)
{
BytesU offset = AlignToLarger( size_t(block.ptr) + block.size, align ) - size_t(block.ptr);
if ( size <= (block.capacity - offset) )
{
block.size = offset + size;
return block.ptr + offset;
}
}
BytesU block_size = _blockSize * (1 + _blocks.size()/2);
block_size = size*2 < block_size ? block_size : size*2;
auto& block = _blocks.emplace_back(Block{ _alloc.Allocate( block_size, _ptrAlign ), 0_b, block_size }); // TODO: check for null
BytesU offset = AlignToLarger( size_t(block.ptr) + block.size, align ) - size_t(block.ptr);
DEBUG_ONLY( std::memset( block.ptr, 0xCD, size_t(block.capacity) ));
block.size = offset + size;
return block.ptr + offset;
}
template <typename T>
ND_ FG_ALLOCATOR T* Alloc (size_t count = 1)
{
return BitCast<T *>( Alloc( SizeOf<T> * count, AlignOf<T> ));
}
void Discard ()
{
for (auto& block : _blocks) {
block.size = 0_b;
}
}
void Release ()
{
for (auto& block : _blocks) {
_alloc.Deallocate( block.ptr, block.capacity, _ptrAlign );
}
_blocks.clear();
}
ND_ BytesU TotalSize () const
{
BytesU size;
for (auto& block : _blocks) {
size += block.capacity;
}
return size;
}
};
//
// Untyped Linear Pool Allocator
//
template <typename AllocatorType = UntypedAlignedAllocator>
struct UntypedLinearAllocator final
{
// types
public:
using LinearAllocator_t = LinearAllocator< AllocatorType >;
using Allocator_t = AllocatorType;
using Self = UntypedLinearAllocator< AllocatorType >;
template <typename T>
using StdAllocator_t = StdLinearAllocator< T, AllocatorType >;
// variables
private:
LinearAllocator_t& _alloc;
// methods
public:
UntypedLinearAllocator (Self &&other) : _alloc{other._alloc} {}
UntypedLinearAllocator (const Self &other) : _alloc{other._alloc} {}
UntypedLinearAllocator (LinearAllocator_t &alloc) : _alloc{alloc} {}
ND_ FG_ALLOCATOR void* Allocate (BytesU size, BytesU align)
{
return _alloc.Alloc( size, align );
}
void Deallocate (void *, BytesU)
{}
void Deallocate (void *, BytesU, BytesU)
{}
ND_ LinearAllocator_t& GetAllocatorRef () const
{
return _alloc;
}
ND_ bool operator == (const Self &rhs) const
{
return &_alloc == &rhs._alloc;
}
};
//
// Std Linear Pool Allocator
//
template <typename T,
typename AllocatorType = UntypedAlignedAllocator>
struct StdLinearAllocator
{
// types
public:
using value_type = T;
using LinearAllocator_t = LinearAllocator< AllocatorType >;
using Allocator_t = AllocatorType;
using Self = StdLinearAllocator< T, AllocatorType >;
using UntypedAllocator_t = UntypedLinearAllocator< AllocatorType >;
// variables
private:
LinearAllocator_t& _alloc;
// methods
public:
StdLinearAllocator (LinearAllocator_t &alloc) : _alloc{alloc} {}
StdLinearAllocator (const UntypedAllocator_t &alloc) : _alloc{alloc.GetAllocatorRef()} {}
StdLinearAllocator (Self &&other) : _alloc{other._alloc} {}
StdLinearAllocator (const Self &other) : _alloc{other._alloc} {}
template <typename B>
StdLinearAllocator (const StdLinearAllocator<B,Allocator_t>& other) : _alloc{other.GetAllocatorRef()} {}
Self& operator = (const Self &) = delete;
ND_ FG_ALLOCATOR T* allocate (const size_t count)
{
return _alloc.template Alloc<T>( count );
}
void deallocate (T * const, const size_t)
{
}
ND_ Self select_on_container_copy_construction() const
{
return Self{ _alloc };
}
ND_ LinearAllocator_t& GetAllocatorRef () const
{
return _alloc;
}
ND_ bool operator == (const Self &rhs) const
{
return &_alloc == &rhs._alloc;
}
};
} // FGC
|
Java
|
UTF-8
| 798
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package net.anumbrella.sso.service;
import net.anumbrella.sso.dao.UserDao;
import net.anumbrella.sso.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Anumbrella
*/
@Service
public class UserService {
@Autowired
private UserDao userDao;
public List<User> list() {
return (List<User>) userDao.findAll();
}
public User findUserById(Long id){
return userDao.findOne(id);
}
public List<User> findByUsernameAndPassword(String username, String password){
return userDao.findByUsernameAndPassword(username, password);
}
public User findByUsername(String username){
return userDao.findByUsername(username);
}
}
|
JavaScript
|
UTF-8
| 1,917
| 2.59375
| 3
|
[] |
no_license
|
const ApiError = require('../error/ApiError');
const apiErrorNames = require('../error/ApiErrorNames');
module.exports = {
generate: (params) => {
let result = true;
const { tasks } = params;
if (!tasks || !Array.isArray(tasks)) {
result = new ApiError(apiErrorNames.INVALIDATE_PARAMS);
result.setMessage('任务参数tasks必须是数组');
return result;
}
for (let i = 0; i < tasks.length; i++) {
if (!tasks[i].id) {
result = new ApiError(apiErrorNames.INVALIDATE_PARAMS);
result.setMessage('每一个task必须有id');
return result;
}
if (!tasks[i].option) {
result = new ApiError(apiErrorNames.INVALIDATE_PARAMS);
result.setMessage(`task<${tasks[i].id}>必须有option`);
return result;
}
if (!tasks[i].option.type) {
result = new ApiError(apiErrorNames.INVALIDATE_PARAMS);
result.setMessage(`task<${tasks[i].id}>必须有合法type`);
return result;
}
if (!tasks[i].option.xData || !Array.isArray(tasks[i].option.xData)) {
result = new ApiError(apiErrorNames.INVALIDATE_PARAMS);
result.setMessage(`task<${tasks[i].id}>必须有合法xData`);
return result;
}
if (!tasks[i].option.yData || !Array.isArray(tasks[i].option.yData)) {
result = new ApiError(apiErrorNames.INVALIDATE_PARAMS);
result.setMessage(`task<${tasks[i].id}>必须有合法yData`);
return result;
}
if (tasks[i].option.label) {
let label = tasks[i].option.label;
if (label && (!Array.isArray(label) && (!label.data || !Array.isArray(label.data)))) {
result = new ApiError(apiErrorNames.INVALIDATE_PARAMS);
result.setMessage(`task<${tasks[i].id}>必须有合法label(label: [] || label: {data: [], ...})`);
return result;
}
}
}
return result;
}
};
|
Go
|
UTF-8
| 298
| 3.078125
| 3
|
[] |
no_license
|
package five
// SmallestMultiple ...
func SmallestMultiple(upperBound int) int {
for i := 2520; ; i += upperBound {
if isDivisibleByAll(i, upperBound) {
return i
}
}
}
func isDivisibleByAll(n, m int) bool {
for j := m; j > 1; j-- {
if n%j != 0 {
return false
}
}
return true
}
|
TypeScript
|
UTF-8
| 878
| 2.859375
| 3
|
[] |
no_license
|
import products from "./products";
const productName: string = 'fanny pack';
const product = products.filter(product => product.name === productName)[0];
let shipping: number = 0;
let taxPercent: number;
let taxTotal: number;
let total: number;
const shippingAddress: string = "123 Cherry Street, New York, New York";
if (product.preOrder === 'true') {
console.log("We'll send you a message when your item ships.")
}
product.price > '25' ? console.log("You're shipping is free!") : shipping = 5;
shippingAddress.match("New York") ? taxPercent = .1 : taxPercent = .05;
taxTotal = Number(product.price) * taxPercent;
total = taxTotal + Number(product.price) + shipping;
console.log(`
Product: ${product.name}
Address: ${shippingAddress}
Price: $${product.price}
Tax: $${taxTotal.toFixed(2)}
Shipping: $${shipping.toFixed(2)}
Total: $${total.toFixed(2)}
`);
|
Markdown
|
UTF-8
| 45
| 2.53125
| 3
|
[] |
no_license
|
G0 Back N ARQ implementation using simple-FTP
|
Python
|
UTF-8
| 2,290
| 3.015625
| 3
|
[] |
no_license
|
import numpy
from keras.datasets import imdb
from keras.layers.recurrent import GRU
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
class RNN:
'''
RNN classifier
'''
def __init__(self, train_x, train_y, test_x, test_y, dict_size=5000, example_length=500, embedding_length=32, epoches=15, batch_size=128):
'''
initialize RNN model
:param train_x: training data
:param train_y: training label
:param test_x: test data
:param test_y: test label
:param epoches:
:param batch_size:
'''
self.batch_size = batch_size
self.epoches = epoches
self.example_len = example_length
self.dict_size = dict_size
self.embedding_len = embedding_length
# TODO:preprocess training data
self.train_x = sequence.pad_sequences(train_x, maxlen=self.example_len)
self.test_x = sequence.pad_sequences(test_x, maxlen=self.example_len)
self.train_y = train_y
self.test_y = test_y
# TODO:build model
self.model = Sequential()
self.model.add(Embedding(self.dict_size, self.embedding_len))
self.model.add(LSTM(self.batch_size, dropout=0.2, recurrent_dropout=0.2))
#self.model.add(GRU(self.batch_size, dropout=0.2, recurrent_dropout=0.2))
self.model.add(Dense(1, activation='sigmoid'))
self.model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
def train(self):
'''
fit in data and train model
:return:
'''
# TODO: fit in data to train your model
self.model.fit(self.train_x, self.train_y, self.batch_size, self.epoches,
validation_data=(self.test_x, self.test_y))
def evaluate(self):
'''
evaluate trained model
:return:
'''
return self.model.evaluate(self.test_x, self.test_y)
if __name__ == '__main__':
(train_x, train_y), (test_x, test_y) = imdb.load_data(num_words=5000)
rnn = RNN(train_x, train_y, test_x, test_y)
rnn.train()
rnn.evaluate()
|
Java
|
UTF-8
| 291
| 1.6875
| 2
|
[] |
no_license
|
package com.universalstudios.orlandoresort.frommergeneedsrefactor.framedcamera;
import android.hardware.Camera;
/**
* @author jamestimberlake
* @created 12/2/15.
*/
public class CameraUtils {
public static int numberOfCameras(){
return Camera.getNumberOfCameras();
}
}
|
Java
|
UTF-8
| 352
| 1.976563
| 2
|
[] |
no_license
|
package com.jtravan.model;
import com.jtravan.dal.model.Transaction;
import com.jtravan.dal.model.User;
import lombok.Data;
@Data
public class DominancePair {
private DominanceType dominanceType;
private User dominatingUser;
private Transaction dominatingTransaction;
private User weakUser;
private Transaction weakTransaction;
}
|
Java
|
UTF-8
| 16,450
| 1.726563
| 2
|
[
"MIT"
] |
permissive
|
/*
* Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
*
* License for BK-BASE 蓝鲸基础平台:
* --------------------------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tencent.bk.base.datahub.databus.connect.source.jdbc;
import com.tencent.bk.base.datahub.databus.connect.jdbc.util.JdbcUtils;
import com.tencent.bk.base.datahub.databus.commons.utils.LogUtils;
import org.apache.kafka.connect.errors.ConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
/**
* 此类提供历史数据和周期产生数据的mysql数据拉取。继承自{@see TimestampIncrementingTableQuerier}类,沿用timestamp和increment的设计,
* 依旧支持timestampDelay的延时处理。
* 在此基础上增加了{@link HistoryAndPeriodTableQuerier#isHistoryDataCompleted()},让该类加载数据有着历史数据恢复和周期数据加载两种模式
* 老版本的TimestampIncrementingTableQuerier不加载历史数据,但是由于对于批次没有限流处理,以后也会走这个接口.
* 使用时不拉去历史模式,model配置值为: Timestamp和Incrementing
* 使用时拉取历史模式,model模式的配置值为:
* JdbcSourceConnectorConfig.MODE_HISTORY_PERIOD_TIMESTAMP = "historyAndPeriod.timestamp"
* JdbcSourceConnectorConfig.MODE_HISTORY_PERIOD_INCREMENTING = "historyAndPeriod.incrementing"
* 使用时:类似TimestampIncrementingTableQuerier 需要分别指定:timestamp.column.name / incrementing.column.name
* 历史拉取与非历史拉取的区别在于: Collector初始化时,传入的启动offset不同.
* 历史数据恢复模式中,按照批次拉取DEFAULT_BATCH_SIZE大小的数据,直到db内数据不足一个批次。
* 周期拉取模式下,如果一个批次超过DEFAULT_BATCH_SIZE,也会分批处理
* JdbcSourceTask中为历史数据恢复模式/周期拉取模式,增加不同的线程逻辑,若为历史数据恢复模式并不会进入线程的周期性Sleep,直到数据加载完毕
* lastLimitOffset 为 JdbcSourceConnectorConfig.LOAD_HISTORY_END_VALUE时, 代表着增量拉取过程还没结束
* {@see com.tencent.bk.base.datahub.databus.connect.source.jdbc.JdbcSourceTask#pollData()}
*/
public class HistoryAndPeriodTableQuerier extends TimestampIncrementingTableQuerier {
private static final Logger log = LoggerFactory.getLogger(HistoryAndPeriodTableQuerier.class);
private String timestampColumn;
private String incrementingColumn;
private long timestampDelay;
protected JdbcSourceConnectorConfig conf;
protected String historyAndPeriodMode;
private boolean hasPullLastTimestamp;
private Map<Timestamp, Integer> lastStartTimestamp;
public HistoryAndPeriodTableQuerier(QueryMode mode, String name, String topicPrefix, String historyAndPeriodMode,
String timestampColumn, String incrementingColumn,
Map<String, Object> offsetMap, Long timestampDelay, String schemaPattern, JdbcSourceConnectorConfig conf,
String timestampTimeFormat) {
super(mode, name, topicPrefix, timestampColumn, incrementingColumn, offsetMap, timestampDelay, schemaPattern,
timestampTimeFormat);
this.timestampColumn = timestampColumn;
this.incrementingColumn = incrementingColumn;
this.timestampDelay = timestampDelay;
this.conf = conf;
this.historyAndPeriodMode = historyAndPeriodMode;
this.hasPullLastTimestamp = false;
this.lastStartTimestamp = new HashMap<>();
}
@Override
public void createLatestStatement(Connection db) throws SQLException {
super.createLatestStatement(db);
}
/**
* 从DB中拉取第一条数据作为历史拉取的起点
* SELECT * FROM TABLE ORDER BY incrementingColumn/timestampColumn ASC LIMIT 1
*
* @param db db连接
*/
@Override
protected void createEarliestStatement(Connection db) throws SQLException {
String quoteString = JdbcUtils.getIdentifierQuoteString(db);
StringBuilder builder = new StringBuilder();
builder.append("SELECT * FROM ");
builder.append(JdbcUtils.quoteString(name, quoteString));
builder.append(" WHERE ");
if (incrementingColumn != null) {
builder.append(JdbcUtils.quoteString(incrementingColumn, quoteString));
} else {
builder.append(JdbcUtils.quoteString(timestampColumn, quoteString));
}
builder.append(" IS NOT NULL ");
builder.append(" ORDER BY ");
if (incrementingColumn != null) {
builder.append(JdbcUtils.quoteString(incrementingColumn, quoteString));
} else if (timestampColumn != null) {
builder.append(JdbcUtils.quoteString(timestampColumn, quoteString));
}
builder.append(" ASC LIMIT 1");
String queryString = builder.toString();
LogUtils.info(log, "{} prepared SQL query: {}", this, queryString);
stmt = db.prepareStatement(queryString);
}
/**
* 历史数据是否加载完毕, lastLimitOffset等于JdbcSourceConnectorConfig.LOAD_HISTORY_END_VALUE;
* 并且timestamp情况下,时间窗口滑动到当前时间时,代表加载完毕了
* 若加载完毕返回true, 否则返回false
*/
public boolean isHistoryDataCompleted() {
return isBatchFinished() && hasPullLastTimestamp;
}
/**
* 当前时间范围内的记录是否加载完毕
*/
public boolean isBatchFinished() {
return offset.getLastLimitOffset() == JdbcSourceConnectorConfig.LOAD_HISTORY_END_VALUE
|| offset.getNextLimitOffset() == JdbcSourceConnectorConfig.LOAD_HISTORY_END_VALUE;
}
/**
* 获取当前处理到的记录的offset, 要加上 lastLimitOffset, start
* increment类型只需要 offset就行
* Timestamp类型需要: timestamp, startTimestamp, lastLimitOffset三种
*
* @param record record
* @return Map
*/
@Override
public Map<String, Object> extractAndUpdateOffset(Map<String, Object> record, int recordIndex) {
long time = 0;
Timestamp extractedTimestamp = null;
long incrementingColumnValue = 0;
if (timestampColumn != null) {
// 在sql中,可能是datetime、timestamp或者date类型,datetime可以转为timestamp,date不可以
// string 类型的 timestampColumn 需要手动提供转化
if (record.get(timestampColumn) instanceof Date) {
extractedTimestamp = new Timestamp(((Date) record.get(timestampColumn)).getTime());
} else if (record.get(timestampColumn) instanceof Timestamp) {
// datatime 与 timestamp 类型的转化
extractedTimestamp = (Timestamp) record.get(timestampColumn);
} else {
extractedTimestamp = stringTypeTimestampTranform(record.get(timestampColumn).toString());
}
time = extractedTimestamp.getTime();
} else {
// increment类型
incrementingColumnValue = Long.valueOf(record.getOrDefault(incrementingColumn, 0).toString());
}
LogUtils.info(log, "offsets: {}-{}-{} {}-{}", timestampColumn, time, extractedTimestamp, incrementingColumn,
incrementingColumnValue);
offset = offset
.generateNextOffset(extractedTimestamp, incrementingColumnValue, recordIndex, conf.recordPackageSize);
return offset.toMap();
}
/**
* 构建stmt 和 countStmt, 分别用做sql查询/满足sql要求的个数统计
*
* @param db 数据库链接
*/
@Override
protected void createPreparedStatement(Connection db) throws SQLException {
// Default when unspecified uses an autoincrementing column
if (incrementingColumn != null && incrementingColumn.isEmpty()) {
incrementingColumn = JdbcUtils.getAutoincrementColumn(db, schemaPattern, name);
}
String quoteString = JdbcUtils.getIdentifierQuoteString(db);
StringBuilder builder = new StringBuilder();
switch (mode) {
case TABLE:
builder.append("SELECT * FROM ");
builder.append(JdbcUtils.quoteString(name, quoteString));
break;
case QUERY:
builder.append(query);
break;
default:
throw new ConnectException("Unknown mode encountered when preparing query: " + mode.toString());
}
if (JdbcSourceConnectorConfig.MODE_HISTORY_PERIOD_INCREMENTING.contains(historyAndPeriodMode)) {
builder.append(" WHERE ");
builder.append(JdbcUtils.quoteString(incrementingColumn, quoteString));
builder.append(" IS NOT NULL AND ");
builder.append(JdbcUtils.quoteString(incrementingColumn, quoteString));
builder.append(" > ?");
builder.append(" ORDER BY ");
builder.append(JdbcUtils.quoteString(incrementingColumn, quoteString));
builder.append(" ASC");
} else {
builder.append(" WHERE ");
builder.append(JdbcUtils.quoteString(timestampColumn, quoteString));
builder.append(" IS NOT NULL AND ");
builder.append(JdbcUtils.quoteString(timestampColumn, quoteString));
builder.append(" > ? AND ");
builder.append(JdbcUtils.quoteString(timestampColumn, quoteString));
builder.append(" <= ? ORDER BY ");
builder.append(JdbcUtils.quoteString(timestampColumn, quoteString));
builder.append(" ASC");
}
// limit lastLimitOffset, batchSize
builder.append(" LIMIT ? , ?");
String queryString = builder.toString();
LogUtils.debug(log, "{} prepared SQL query: {}", this, queryString);
stmt = db.prepareStatement(queryString);
}
/**
* 执行stmt和countStmt,返回符合要求的stmt,根据符合要求的记录数量更新{@see HistoryAndPeriodTableQuerier#historyDataCompleted}
* 判断历史数据是否拉取完毕, 若是刚好一批次拉完(rowCount == batchSize)无多余数据, 会空跑一次拉取
*
* @return 查询到的ResultSet
*/
@Override
protected ResultSet executeQuery() throws SQLException {
// countStmt插入和stmt相同的参数
Timestamp startTime = isBatchFinished() ? offset.getTimestampOffset() : offset.getStartTimestamp();
if (JdbcSourceConnectorConfig.MODE_HISTORY_PERIOD_INCREMENTING.contains(historyAndPeriodMode)) {
this.hasPullLastTimestamp = true;
long incOffset = offset.getIncrementingOffset();
stmt.setLong(1, incOffset);
stmt.setLong(2, 0L);
stmt.setInt(3, conf.recordPackageSize);
LogUtils.debug(log, "Executing prepared statement with incrementing value {}", incOffset);
} else {
// 没加载完起点为start_timestamp, 若加载完了起点为Timestamp
Timestamp endTime = getEndTime(stmt.getConnection(), startTime);
timestampValueInsert(startTime, endTime);
if (isBatchFinished()) {
stmt.setLong(3, 0L);
} else {
stmt.setLong(3, offset.getLastLimitOffset() < 0 ? 0 : offset.getLastLimitOffset());
}
stmt.setInt(4, conf.recordPackageSize);
}
LogUtils.info(log, "query sql is {}, ts is {}, start_ts is {}, limit is {}, nextLimit is {}", stmt.toString(),
offset.getTimestampOffset(), offset.getStartTimestamp(), offset.getLastLimitOffset(),
offset.getNextLimitOffset());
ResultSet stmtResultSet = stmt.executeQuery();
// 判断是否加载完所有数据
int rowCount = getRowCountFromRs(stmtResultSet);
if (rowCount < conf.recordPackageSize) {
offset.setNextLimitOffset(JdbcSourceConnectorConfig.LOAD_HISTORY_END_VALUE);
} else {
offset.setNextLimitOffset((offset.getLastLimitOffset() <= 0 ? 0 : offset.getLastLimitOffset()) + rowCount);
}
// 清理窗口信息: rowCount=0代表窗口无数据, rowCount=BatchSize代表有数据但是没有加载完毕
if (rowCount == 0 && lastStartTimestamp.containsKey(startTime)) {
lastStartTimestamp.replace(startTime, lastStartTimestamp.getOrDefault(startTime, 0) + 1);
} else if (rowCount != conf.recordPackageSize) {
lastStartTimestamp.clear();
}
// 若是数据不为空, 清除窗口记录, 下次从一个窗口大小开始拉取
if (rowCount != 0) {
LogUtils.info(log,
"get-result-query sql is {}, ts is {}, start_ts is {}, limit is {}, nextLimit is {}, size is {}",
stmt.toString(), offset.getTimestampOffset(), offset.getStartTimestamp(),
offset.getLastLimitOffset(), offset.getNextLimitOffset(), rowCount);
}
LogUtils.debug(log, "{} All remaining data nums : {, the state of historyDataCompleted is {}", this, rowCount,
isHistoryDataCompleted());
return stmtResultSet;
}
/**
* 获取SQL中的endTimestamp
*/
protected Timestamp getEndTime(Connection connection, Timestamp startTimestamp) throws SQLException {
Timestamp maxEndTime = new Timestamp(
JdbcUtils.getCurrentTimeOnDb(connection, new GregorianCalendar(TimeZone.getTimeZone("UTC"))).getTime()
- timestampDelay);
// 若使用上一次的startTimestamp 未能拉取数据,下次需要加倍窗口拉取
int winNums = lastStartTimestamp.getOrDefault(startTimestamp, 1);
lastStartTimestamp.clear();
lastStartTimestamp.put(startTimestamp, winNums);
Timestamp maxAllowEndTime = new Timestamp(startTimestamp.getTime() + conf.pullMaxIntervalMs * winNums);
Timestamp endTime;
// 确定SQL最后执行时的endTime
if (maxAllowEndTime.before(maxEndTime)) {
endTime = maxAllowEndTime;
this.hasPullLastTimestamp = false;
} else {
endTime = maxEndTime;
this.hasPullLastTimestamp = true;
}
return endTime;
}
/**
* 从Resultset中获取当前查询的数量
*/
protected int getRowCountFromRs(ResultSet stmtResultSet) throws SQLException {
// 移动到最后一行,获取rowCount
if (stmtResultSet.last()) {
int rowCount = stmtResultSet.getRow();
// 调整回第一行
stmtResultSet.beforeFirst();
return rowCount;
} else {
LogUtils.info(log, "In this query the ResultSet is null, when sql is {}, stmtResultSet is {}",
stmt.toString(), stmtResultSet.toString());
return 0;
}
}
}
|
C++
|
UTF-8
| 2,269
| 2.6875
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
// Distributed under the BSD 2-Clause License - Copyright 2012-2023 Robin Degen
#include <aeon/vulkan/pipeline_layout.h>
#include <aeon/vulkan/pipeline_layout_description.h>
#include <aeon/vulkan/device.h>
#include <aeon/vulkan/checked_result.h>
namespace aeon::vulkan
{
namespace internal
{
[[nodiscard]] auto create_pipeline_layout(const device &device, const pipeline_layout_description &description)
{
VkPipelineLayoutCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
if (description.has_set_layouts())
{
info.setLayoutCount = description.set_layout_count();
info.pSetLayouts = std::data(description.set_layouts());
}
if (description.has_push_constant_ranges())
{
info.pushConstantRangeCount = description.push_constant_range_count();
info.pPushConstantRanges = std::data(description.push_constant_ranges());
}
VkPipelineLayout handle{};
checked_result{vkCreatePipelineLayout(vulkan::handle(device), &info, nullptr, &handle)};
return handle;
}
} // namespace internal
pipeline_layout::pipeline_layout() noexcept
: device_{nullptr}
, handle_{VK_NULL_HANDLE}
{
}
pipeline_layout::pipeline_layout(const vulkan::device &device, const pipeline_layout_description &description)
: device_{&device}
, handle_{internal::create_pipeline_layout(device, description)}
{
}
pipeline_layout::~pipeline_layout() noexcept
{
destroy();
}
pipeline_layout::pipeline_layout(pipeline_layout &&other) noexcept
: device_{other.device_}
, handle_{other.handle_}
{
other.handle_ = VK_NULL_HANDLE;
}
auto pipeline_layout::operator=(pipeline_layout &&other) noexcept -> pipeline_layout &
{
if (this != &other) [[likely]]
{
destroy();
device_ = other.device_;
handle_ = other.handle_;
other.handle_ = VK_NULL_HANDLE;
}
return *this;
}
auto pipeline_layout::device() const noexcept -> const vulkan::device &
{
return *device_;
}
auto pipeline_layout::handle() const noexcept -> VkPipelineLayout
{
return handle_;
}
void pipeline_layout::destroy() const noexcept
{
if (handle_)
vkDestroyPipelineLayout(vulkan::handle(device_), handle_, nullptr);
}
} // namespace aeon::vulkan
|
Python
|
UTF-8
| 12,546
| 3.234375
| 3
|
[] |
no_license
|
import numbers, math, random
import numpy as np
import torch
from torchvision.transforms import functional as F
from torchvision import transforms
from PIL import Image, ImagePalette
def Denormalize(mean=[.485, .456, .406], std=[.229, .224, .225]):
mx, my, mz = mean
sx, sy, sz = std
inv_normalize = transforms.Normalize(
mean=[-mx/sx, -my/sy, -mz/sz],
std=[1/sx, 1/sy, 1/sz])
return inv_normalize
class RandomRotation(object):
"""Rotate the image by angle.
Args:
degrees (sequence or float or int): Range of degrees to select from.
If degrees is a number instead of sequence like (min, max), the range of degrees
will be (-degrees, +degrees).
center (2-tuple, optional): Optional center of rotation.
Origin is the upper left corner.
Default is the center of the image.
"""
def __init__(self, degrees, center=None):
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError("If degrees is a single number, it must be positive.")
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError("If degrees is a sequence, it must be of len 2.")
self.degrees = degrees
self.center = center
@staticmethod
def get_params(degrees):
"""Get parameters for ``rotate`` for a random rotation.
Returns:
sequence: params to be passed to ``rotate`` for random rotation.
"""
angle = random.uniform(degrees[0], degrees[1])
return angle
def __call__(self, sample):
"""
img (PIL Image): Image to be rotated.
Returns:
PIL Image: Rotated image.
"""
angle = self.get_params(self.degrees)
sample['image'] = F.rotate(sample['image'], angle = angle, resample = Image.BICUBIC, center = self.center)
sample['label'] = F.rotate(sample['label'], angle = angle, resample = Image.NEAREST, center = self.center)
return sample
def __repr__(self):
format_string = self.__class__.__name__ + '(degrees={0}'.format(self.degrees)
if self.center is not None:
format_string += ', center={0}'.format(self.center)
format_string += ')'
return format_string
class RandomResizedCrop(object):
"""Crop the given PIL Image to random size and aspect ratio.
A crop of random size (default: of 0.08 to 1.0) of the original size and a random
aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
is finally resized to given size.
This is popularly used to train the Inception networks.
Args:
size: expected output size of each edge
scale: range of size of the origin size cropped
ratio: range of aspect ratio of the origin aspect ratio cropped
"""
def __init__(self, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.)):
self.scale = scale
self.ratio = ratio
@staticmethod
def get_params(img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (PIL Image): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for a random
sized crop.
"""
for attempt in range(10):
area = img.size[0] * img.size[1]
target_area = random.uniform(*scale) * area
aspect_ratio = random.uniform(*ratio)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= img.size[0] and h <= img.size[1]:
i = random.randint(0, img.size[1] - h)
j = random.randint(0, img.size[0] - w)
return i, j, h, w
# Fallback
w = min(img.size[0], img.size[1])
i = (img.size[1] - w) // 2
j = (img.size[0] - w) // 2
return i, j, w, w
def __call__(self, sample):
"""
Args:
img (PIL Image): Image to be cropped and resized.
Returns:
PIL Image: Randomly cropped and resized image.
"""
i, j, h, w = self.get_params(sample['image'], self.scale, self.ratio)
sample['image'] = F.resized_crop(sample['image'], i, j, h, w, sample['image'].size, Image.BICUBIC)
sample['label'] = F.resized_crop(sample['label'], i, j, h, w, sample['label'].size, Image.NEAREST)
return sample
def __repr__(self):
format_string = self.__class__.__name__ + '(size={0}'.format(self.size)
format_string += ', scale={0}'.format(tuple(round(s, 4) for s in self.scale))
format_string += ', ratio={0})'.format(tuple(round(r, 4) for r in self.ratio))
return format_string
class Resize(object):
"""Resize the image and the ground truth to specified resolution.
Args:
size: expected output size of each image
"""
def __init__(self, size):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
def __call__(self, sample):
sample['image'] = F.resize(sample['image'], self.size, Image.BICUBIC)
sample['label'] = F.resize(sample['label'], self.size, Image.NEAREST)
return sample
def __repr__(self):
return self.__class__.__name__ + '(size={0})'.format(self.size)
class ToTensor(object):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
Converts a PIL Image or numpy.ndarray (H x W x C) in the range
[0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
"""
def __init__(self):
self.labelFilter = LabelFilter()
def __call__(self, sample):
"""
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
sample['image'] = F.to_tensor(sample['image'])
img = torch.ByteTensor(torch.ByteStorage.from_buffer(sample['label'].tobytes())).long()
img = img.view(sample['label'].size[1], sample['label'].size[0]).contiguous()
sample['label'] = self.labelFilter(img)
return sample
def __repr__(self):
return self.__class__.__name__ + '()'
class Normalize(object):
"""Normalize a tensor image with mean and standard deviation.
Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform
will normalize each channel of the input ``torch.*Tensor`` i.e.
``input[channel] = (input[channel] - mean[channel]) / std[channel]``
.. note::
This transform acts in-place, i.e., it mutates the input tensor.
Args:
mean (sequence): Sequence of means for each channel.
std (sequence): Sequence of standard deviations for each channel.
"""
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, sample):
"""
Args:
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
Returns:
Tensor: Normalized Tensor image.
"""
sample['image'] = F.normalize(sample['image'],self.mean, self.std)
return sample
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
class RandomHorizontalFlip(object):
"""Horizontally flip the given torch Image randomly with a given probability.
Args:
p (float): probability of the image being flipped. Default value is 0.5
"""
def __init__(self, p=0.5):
self.p = p
def __call__(self, sample):
"""
Args:
img (tensor Image): Image to be flipped.
Returns:
tensor Image: Randomly flipped image.
"""
if random.random() < self.p:
sample['image'] = torch.flip(sample['image'], [2])
sample['label'] = torch.flip(sample['label'], [1])
return sample
return sample
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
class RandomCrop(object):
"""Crop the given PIL Image at a random location.
Args:
size (sequence or int): Desired output size of the crop. If size is an
int instead of sequence like (h, w), a square crop (size, size) is
made.
"""
def __init__(self, size):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
@staticmethod
def get_params(img, output_size):
"""Get parameters for ``crop`` for a random crop.
Args:
img (PIL Image): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
"""
w, h = img.size
th, tw = output_size
if w == tw and h == th:
return 0, 0, h, w
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
return i, j, th, tw
def __call__(self, sample):
"""
Args:
img (PIL Image): Image to be cropped.
Returns:
PIL Image: Cropped image.
"""
i, j, h, w = self.get_params(sample['image'], self.size)
sample['image'] = F.crop(sample['image'], i, j, h, w)
sample['label'] = F.crop(sample['label'], i, j, h, w)
return sample
def __repr__(self):
return self.__class__.__name__ + '(size={0}, padding={1})'.format(self.size, self.padding)
class LabelFilter(object):
def __init__(self):
self.map = torch.tensor([19, 19, 19, 19, 19, 19, 19, 0, 1, 19,
19, 2, 3, 4, 19, 19, 19, 5, 19, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 19,
19, 16, 17, 18, 19])
def __call__(self, label):
return torch.index_select(self.map, 0, label.view(-1)).view_as(label)
class Colorize(object):
def __init__(self):
self.map = torch.tensor([[128, 64, 128],
[244, 35, 232],
[70, 70, 70],
[102, 102, 156],
[190, 153, 153],
[153, 153, 153],
[250, 170, 30],
[220, 220, 0],
[107, 142, 35],
[152, 251, 152],
[70, 130, 180],
[220, 20, 60],
[255, 0, 0],
[0, 0, 142],
[0, 0, 70],
[0, 60, 100],
[0, 80, 100],
[0, 0, 230],
[119, 11, 32],
[0, 0, 0]])
def __call__(self, label):
return torch.index_select(self.map, 0, label.cpu().view(-1)).view(*label.size(),3)
class Palette():
def __init__(self, palette):
palette = ImagePalette.ImagePalette(palette = palette.tobytes(), size = palette.size)
palette.rawmode = 'RGB'
self.palette = palette
color20 = np.array([
[128,64,128],
[244,35,232],
[70,70,70],
[102,102,156],
[190,153,153],
[153,153,153],
[250,170,30],
[220,220,0],
[107,142,35],
[152,251,152],
[70,130,180],
[220,20,60],
[255,0,0],
[0,0,142],
[0,0,70],
[0,60,100],
[0,80,100],
[0,0,230],
[119,11,32],
[0,0,0]], dtype = np.uint8)
color35 = np.array([
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[128, 64, 128],
[244, 35, 232],
[ 0, 0, 0],
[ 0, 0, 0],
[ 70, 70, 70],
[102, 102, 156],
[190, 153, 153],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[153, 153, 153],
[ 0, 0, 0],
[250, 170, 30],
[220, 220, 0],
[107, 142, 35],
[152, 251, 152],
[ 70, 130, 180],
[220, 20, 60],
[255, 0, 0],
[ 0, 0, 142],
[ 0, 0, 70],
[ 0, 60, 100],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 80, 100],
[ 0, 0, 230],
[119, 11, 32],
[ 0, 0, 0]], dtype = np.uint8)
palette20 = Palette(color20)
palette35 = Palette(color35)
|
C++
|
UTF-8
| 1,173
| 2.90625
| 3
|
[] |
no_license
|
/*************************************************************************
> File Name: example7_13.cpp
> Author: hp
> Mail: hepan@xiyoulinux.org
> Created Time: 2017年01月12日 星期四 17时17分49秒
************************************************************************/
#include <iostream>
#include "Sales_data.h"
using namespace std;
int main(int argc, char *argv[])
{
Sales_data total(cin); // 保存当前求和结果的变量
// 读入一笔交易
if ( cin ) {
Sales_data trans(cin); // 读入下一条交易数据的变量
// 读入剩余的交易
do {
// 检查isbn
if (total.isbn() == trans.isbn()) {
total.combine(trans); // 更新变量total当前的值
} else {
print(cout, total) << endl; // 输出结果
total = trans; // 处理下一本书
}
} while ( read(cin, trans) );
print(cout, total) << endl; // 输出最后一条交易
} else {
cerr << "No data?!" << endl; // 通知用户,未输入任何数据
}
return 0;
}
|
Java
|
UTF-8
| 587
| 1.960938
| 2
|
[] |
no_license
|
package org.microapp.dao.jpa;
import java.util.List;
import org.microapp.dao.base.MembershipDao;
import org.microapp.dao.jpa.base.GenericDaoJpa;
import org.microapp.model.Membership;
import org.springframework.stereotype.Repository;
@Repository("membershipDaoJpa")
public class MembershipDaoJpa extends GenericDaoJpa<Membership, Long> implements
MembershipDao {
public MembershipDaoJpa() {
super(Membership.class);
// TODO Auto-generated constructor stub
}
public List<Membership> getAllForPerson(long personId) {
// TODO Auto-generated method stub
return null;
}
}
|
Python
|
UTF-8
| 1,086
| 2.84375
| 3
|
[] |
no_license
|
import multiprocessing
from time_track import time_track
from volatility_sort_and_print import *
def volatility_count(file_name):
ticker = None
max_price = 0
min_price = 0
with open(file_name, 'r', encoding='utf8') as file:
file.readline()
for line in file:
sec_id, trade_time, price, quantity = line[:-1].split(',')
price = float(price)
if sec_id != ticker:
ticker = sec_id
max_price, min_price = price, price
elif max_price < price:
max_price = price
elif min_price > price:
min_price = price
half_sum = (max_price + min_price) / 2
volatility = round((((max_price - min_price) / half_sum) * 100), 2)
return ticker, volatility
@time_track
def main(path):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
vol_list = pool.map(volatility_count, path_to_file(path=path))
pool.close()
pool.join()
sort(dict(vol_list))
if __name__ == '__main__':
path = 'trades'
main(path=path)
|
JavaScript
|
UTF-8
| 1,208
| 4.375
| 4
|
[] |
no_license
|
/*
// Problem Pattern: Sliding Window
Problem Statement
-----------------
Write a fuction that accepts a list and a number N.
The function should return the maximum sum of N consecutive numbers in the array.
Examples:
1. max_subarray_sum([1], 2) //None
2. max_subarray_sum([1, 3, 4, 2, 12, 3], 1) //12
3. max_subarray_sum([2, 3, 4, 5, 12, 4], 2) //17
4. max_subarray_sum([9, 2, 3, 1, 2, 10], 2) //12
*/
//O(n^2)
function naive_max_subarray_sum(lst, N){
if (lst.length<N){
return NaN
}
let max_sum = 0;
for (let index = 0; index < array.length-N; index++) {
let temp_sum = 0;
for (let j = index; j < index+N; j++) {
temp_sum+=lst[index];
}
if (temp_sum>max_sum){
max_sum=temp_sum;
}
}
return max_sum;
}
//O(n)
function max_subarray_sum(lst,N) {
if (lst.length<N){
return NaN;
}
max_sum=0
for (let index = 0; index < lst.length; index++) {
max_sum += lst[index];
}
temp_sum=max_sum;
for (let index = N; index < array.length; index++) {
temp_sum = (temp_sum-lst[i-N]) + lst[index];
max_sum = Math.max(temp_sum,max_sum);
}
return max_sum
}
|
Java
|
UTF-8
| 1,221
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
package org.frutilla.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Describes a test using sentences in plain text, similar to Cucumber. <br/>
* This description is included in many places:
* <ul>
* <li>the stacktrace of the failed tests</li>
* <li>the javadocs</li>
* <li>the logs in the console</li>
* </ul>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Frutilla {
/**
* Describes the scenario of the use case.
* @return the sentences for the scenario
*/
String[] Scenario() default "";
/**
* Describes the entry point of the use case.
* @return a sentence or group of sentences
*/
String[] Given();
/**
* Describes what the use case does, the main action of the use case.
* @return a sentence or group of sentences
*/
String[] When();
/**
* Describes what is the expected behavior after doing the main action.
* @return a sentence or group of sentences
*/
String[] Then();
}
|
Java
|
UTF-8
| 9,233
| 1.953125
| 2
|
[
"BSD-3-Clause",
"MIT",
"OFL-1.1",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.cep.nfa;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.cep.Event;
import org.apache.flink.cep.SubEvent;
import org.apache.flink.cep.nfa.compiler.NFACompiler;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.util.TestLogger;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public class NFAITCase extends TestLogger {
@Test
public void testSimplePatternNFA() {
List<StreamRecord<Event>> inputEvents = new ArrayList<>();
Event startEvent = new Event(42, "start", 1.0);
SubEvent middleEvent = new SubEvent(42, "foo", 1.0, 10.0);
Event endEvent= new Event(43, "end", 1.0);
inputEvents.add(new StreamRecord<Event>(startEvent, 1));
inputEvents.add(new StreamRecord<Event>(new Event(43, "foobar", 1.0), 2));
inputEvents.add(new StreamRecord<Event>(new SubEvent(41, "barfoo", 1.0, 5.0), 3));
inputEvents.add(new StreamRecord<Event>(middleEvent, 3));
inputEvents.add(new StreamRecord<Event>(new Event(43, "start", 1.0), 4));
inputEvents.add(new StreamRecord<Event>(endEvent, 5));
Pattern<Event, ?> pattern = Pattern.<Event>begin("start").where(new FilterFunction<Event>() {
private static final long serialVersionUID = 5726188262756267490L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("start");
}
})
.followedBy("middle").subtype(SubEvent.class).where(new FilterFunction<SubEvent>() {
private static final long serialVersionUID = 6215754202506583964L;
@Override
public boolean filter(SubEvent value) throws Exception {
return value.getVolume() > 5.0;
}
})
.followedBy("end").where(new FilterFunction<Event>() {
private static final long serialVersionUID = 7056763917392056548L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("end");
}
});
NFA<Event> nfa = NFACompiler.compile(pattern, Event.createTypeSerializer(), false);
List<Map<String, Event>> resultingPatterns = new ArrayList<>();
for (StreamRecord<Event> inputEvent: inputEvents) {
Collection<Map<String, Event>> patterns = nfa.process(
inputEvent.getValue(),
inputEvent.getTimestamp()).f0;
resultingPatterns.addAll(patterns);
}
assertEquals(1, resultingPatterns.size());
Map<String, Event> patternMap = resultingPatterns.get(0);
assertEquals(startEvent, patternMap.get("start"));
assertEquals(middleEvent, patternMap.get("middle"));
assertEquals(endEvent, patternMap.get("end"));
}
/**
* Tests that the NFA successfully filters out expired elements with respect to the window
* length
*/
@Test
public void testSimplePatternWithTimeWindowNFA() {
List<StreamRecord<Event>> events = new ArrayList<>();
List<Map<String, Event>> resultingPatterns = new ArrayList<>();
final Event startEvent;
final Event middleEvent;
final Event endEvent;
events.add(new StreamRecord<Event>(new Event(1, "start", 1.0), 1));
events.add(new StreamRecord<Event>(startEvent = new Event(2, "start", 1.0), 2));
events.add(new StreamRecord<Event>(middleEvent = new Event(3, "middle", 1.0), 3));
events.add(new StreamRecord<Event>(new Event(4, "foobar", 1.0), 4));
events.add(new StreamRecord<Event>(endEvent = new Event(5, "end", 1.0), 11));
events.add(new StreamRecord<Event>(new Event(6, "end", 1.0), 13));
Pattern<Event, ?> pattern = Pattern.<Event>begin("start").where(new FilterFunction<Event>() {
private static final long serialVersionUID = 7907391379273505897L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("start");
}
}).followedBy("middle").where(new FilterFunction<Event>() {
private static final long serialVersionUID = -3268741540234334074L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("middle");
}
}).followedBy("end").where(new FilterFunction<Event>() {
private static final long serialVersionUID = -8995174172182138608L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("end");
}
}).within(Time.milliseconds(10));
NFA<Event> nfa = NFACompiler.compile(pattern, Event.createTypeSerializer(), false);
for (StreamRecord<Event> event: events) {
Collection<Map<String, Event>> patterns = nfa.process(event.getValue(), event.getTimestamp()).f0;
resultingPatterns.addAll(patterns);
}
assertEquals(1, resultingPatterns.size());
Map<String, Event> patternMap = resultingPatterns.get(0);
assertEquals(startEvent, patternMap.get("start"));
assertEquals(middleEvent, patternMap.get("middle"));
assertEquals(endEvent, patternMap.get("end"));
}
/**
* Tests that the NFA successfully returns partially matched event sequences when they've timed
* out.
*/
@Test
public void testSimplePatternWithTimeoutHandling() {
List<StreamRecord<Event>> events = new ArrayList<>();
List<Map<String, Event>> resultingPatterns = new ArrayList<>();
Set<Tuple2<Map<String, Event>, Long>> resultingTimeoutPatterns = new HashSet<>();
Set<Tuple2<Map<String, Event>, Long>> expectedTimeoutPatterns = new HashSet<>();
events.add(new StreamRecord<Event>(new Event(1, "start", 1.0), 1));
events.add(new StreamRecord<Event>(new Event(2, "start", 1.0), 2));
events.add(new StreamRecord<Event>(new Event(3, "middle", 1.0), 3));
events.add(new StreamRecord<Event>(new Event(4, "foobar", 1.0), 4));
events.add(new StreamRecord<Event>(new Event(5, "end", 1.0), 11));
events.add(new StreamRecord<Event>(new Event(6, "end", 1.0), 13));
Map<String, Event> timeoutPattern1 = new HashMap<>();
timeoutPattern1.put("start", new Event(1, "start", 1.0));
timeoutPattern1.put("middle", new Event(3, "middle", 1.0));
Map<String, Event> timeoutPattern2 = new HashMap<>();
timeoutPattern2.put("start", new Event(2, "start", 1.0));
timeoutPattern2.put("middle", new Event(3, "middle", 1.0));
Map<String, Event> timeoutPattern3 = new HashMap<>();
timeoutPattern3.put("start", new Event(1, "start", 1.0));
Map<String, Event> timeoutPattern4 = new HashMap<>();
timeoutPattern4.put("start", new Event(2, "start", 1.0));
expectedTimeoutPatterns.add(Tuple2.of(timeoutPattern1, 11L));
expectedTimeoutPatterns.add(Tuple2.of(timeoutPattern2, 13L));
expectedTimeoutPatterns.add(Tuple2.of(timeoutPattern3, 11L));
expectedTimeoutPatterns.add(Tuple2.of(timeoutPattern4, 13L));
Pattern<Event, ?> pattern = Pattern.<Event>begin("start").where(new FilterFunction<Event>() {
private static final long serialVersionUID = 7907391379273505897L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("start");
}
}).followedBy("middle").where(new FilterFunction<Event>() {
private static final long serialVersionUID = -3268741540234334074L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("middle");
}
}).followedBy("end").where(new FilterFunction<Event>() {
private static final long serialVersionUID = -8995174172182138608L;
@Override
public boolean filter(Event value) throws Exception {
return value.getName().equals("end");
}
}).within(Time.milliseconds(10));
NFA<Event> nfa = NFACompiler.compile(pattern, Event.createTypeSerializer(), true);
for (StreamRecord<Event> event: events) {
Tuple2<Collection<Map<String, Event>>, Collection<Tuple2<Map<String, Event>, Long>>> patterns =
nfa.process(event.getValue(), event.getTimestamp());
Collection<Map<String, Event>> matchedPatterns = patterns.f0;
Collection<Tuple2<Map<String, Event>, Long>> timeoutPatterns = patterns.f1;
resultingPatterns.addAll(matchedPatterns);
resultingTimeoutPatterns.addAll(timeoutPatterns);
}
assertEquals(1, resultingPatterns.size());
assertEquals(expectedTimeoutPatterns.size(), resultingTimeoutPatterns.size());
assertEquals(expectedTimeoutPatterns, resultingTimeoutPatterns);
}
}
|
C++
|
UTF-8
| 2,739
| 3.46875
| 3
|
[] |
no_license
|
/*Chef lives in Chefland. Chefland can be accurately represented by a certain number of intersections and the roads connecting them.
Chefland is a strange place, because all the roads there are one-way. Also, for any two intersections A and B, once you travel from A to B,
you can never return to A again because there is simply no route you can take to get back to A.
Unaware of this, Chef set out to visit his friend, and now he can't return home! So, Chef decides to travel to the townhall and complain
about this ridiculous system. Studying the map of Chefland, Chef wonders about the number of ways in which he can travel to the townhall.
Help him find this number. As the number may be very large, print it modulo 10^9+7.*/
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef long long ll;
const int mod = (int)1e9 + 7;
vi G[100000+5];
ll dp[100000+5];
int d;
ll dfs(int u) {
if(u == d) return 1;
if(dp[u] != -1) return dp[u];
ll ans = 0;
for(int v: G[u])
ans = ((ans % mod) + dfs(v) % mod) % mod;
return dp[u] = ans;
}
int main() {
int N, M, src, dest, a, b;
cin >> N >> M;
cin >> src >> dest;
while(M--) {
cin >> a >> b;
G[a].push_back(b);
}
memset(dp, -1, sizeof(dp));
d = dest;
cout << dfs(src) << endl;
return 0;
}
/*PROBLEM:
Given a DAG (directed acyclic graph) with N nodes and M edges, the problem requires one to find the number of different paths
that exist from a given node P to another node Q.
QUICK EXPLANATION:
The first step is to toposort the given graph. If dp[u] be the number of paths from node u to node Q.
Then dp[u] = summation of dp[v] for all v for each edge directed from u to v. We obtain dp[u] for each node u in the graph
in reverse topological order. Then dp[P] is the required answer.
Thus, our trivial function would look something like
function f(u)
if u equals Q
return 1
sum = 0
for each edge u→v
sum = sum + f(v)
return sum
another approach :
Kahn's algorithm for toposorting a DAG is provided below
L = empty list
D = array of indegrees for each node
S = list of all nodes u with D[u] = 0
while S is not empty repeat
remove a node u from S
append u to the end of L
for each edge u→v
D[v] = D[v] - 1
if D[v] equals 0
add v to S
The next step is to use dynamic programming to calculate our f values. We also need to make sure to store the values modulo 109+7.
dp = array to store f values
set dp[u] = 0 for each node u
dp[Q] = 1
for each node u in revere order of L
for each edge u→v
dp[u] = dp[u] + dp[v]
dp[u] = dp[u] % 1000000007
*/
|
Python
|
UTF-8
| 222
| 3.90625
| 4
|
[] |
no_license
|
dict_of_numbers = dict()
def dict_maked(number):
for i in range(1, number+1):
dict_of_numbers[i] = i*i
print(dict_maked(5))
print(dict_of_numbers)
for numbers in dict_of_numbers.keys():
print(numbers)
|
Java
|
UTF-8
| 224
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package DesignPattern.BehavioralPattern.IteratorPattern;
/**
* author: WentaoKing
* created on: 2020/4/2
* description:
*/
public interface Iterator<E> {
boolean hasNext();
void next();
E currentItem();
}
|
Markdown
|
UTF-8
| 6,898
| 3.078125
| 3
|
[] |
no_license
|
---
title: "人生不是冲着吃苦来的"
date: "2014-08-27"
---
亲爱的连岳:
第一次给你写信,略有忐忑,不过却觉得很亲切,很喜欢你的书和专栏,一个真性情的男人总是会令人感动。
万事总是因果相连,我总是会不断地反省:是因为什么才形成了现在的我,而我,又应该怎样面对自己,怎样才能淡定从容,毕竟,我们都要好好活着。
先说一下背景吧:单亲,随母亲,在校女大学生(女大学生?略略苦涩,这个词好像已经混杂了太多含义,暧昧,混乱),家境一般,需自己打工赚取零用。因此,在学习之余会接触一些社会的边边角角,从而引来了我的烦恼。
自认为自己长得一般,除了皮肤很白很嫩,别无出众之处。额,曾有人告诉我说:“你长得好萌啊,尤其是一双大眼睛,勾人魂魄。”我听了,笑笑,并不认为这是中肯的评价,只不过是逗我开心罢了。父母的婚姻很槽糕,母亲是极其温柔贤淑的女子,逆来顺受,可换来的结果却是父亲娶了小三且对我们母女不管不顾。都说父亲是女儿上辈子的情人,那么,这个情人伤我太深,使我不再轻易相信爱情,婚姻。呵呵,曾经有过这样的想法:快点长大,快点独立,照顾好母亲,就去教堂当一名修女,每日读经祷告静心传道。这样的臆想,使我很开心。
然而,接触社会多了,却发现独善其身好难,总会有老男人骚扰你,让人胆战心惊。比如打工小店的老板,某些常去的顾客,总爱开你的玩笑,且带有颜色。有共事的姑娘巴不得别人开她玩笑,我是巴不得躲得远远的,然而,你越躲他们越追,让人烦。也许是我太敏感了,甚至在这方面有些洁癖。有时会被弄得很恶心,且恶心好久。然而,知道我的家庭背景的人会更过分,也许是知道没有人能保护我,所以更加肆无忌惮。他是父母的朋友且与父母同龄,相互之间认识很久,父母离异后,有时会找他帮忙,而他也是十分热心,我也很是感激。可是,他却在我上大学后莫名的更加关心起来,突然有点忘年交的意思。有一天,他说,我喜欢你,要我做他的小,要包养我,他说可以给我更好的生活条件,似乎还有些救我于水火的优越感。他的儿子只比我小两岁,且他的妻子很依赖他。我既惊讶又愤怒,真想抽他大嘴巴子。然而,母亲真的太温柔软弱,不能为我出头,且还要被他数落。数落我不懂事,冷漠等种种缺点。幸好我在外地上大学,从那以后,我再也不见他。
连岳,我好不安,手足无措,我想知道,我应该怎样看待这样的事情,怎样和有萝莉控的大叔相处,怎样使自己淡定且从容。我想,我需要力量,好好的走下去。额,有男孩子追我,我都一概本能的拒绝,爱情的花总是还没开放就迅速凋零,男孩子问我,他哪里不好,他愿意为我改,我只好小声的说,是我不好是我不好。
其实,我们本可以都很好的,不是吗。然而...可不可以没有然而。
不管怎样,都要做淡定从容的好姑娘。
谢谢你。
无措的小兔子
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
无措的小兔子:
“年轻人需要吃一点苦头!”许多老一代人总是这样摇摇头,叹一口气说出这句糊涂话。要提醒自己老了千万别说这种话。
如果我有能力,我是不希望自己的孩子吃苦的,也不会在乎他不了解社会的丑恶,知识、教养在安逸舒服的环境里也可以养成,甚至养成的可能性更大,不抢最后一块面包就得饿死,这种极端环境,人变成野兽才是规律的必然;盖茨一辈子吃过什么苦呢?富二代,少年得志;巴菲特一辈子又吃过什么苦呢?官二代,三十来岁就赚了一辈子也花不完的钱,而且从此后资产像滚雪球一样增长至今,这并不妨碍这两个人联手将自己的财富回馈给世界。
超人吃过什么苦呢?内裤外穿也没人笑他,他照样可以拯救社会,并熬出“能力越大,责任越大”这样的心灵鸡汤。
一个人通过教育并在离开大学后养成自我教育的习惯,获得了越来越大的能力;一个有能力的人,学会不干涉弱者的选择;他获得力量并且克制使用,这种人生状态的得到,饥饿、动荡、仇恨、囚禁的的苦生态系统显然并不提供,而在富足、平衡、包容与多元的乐生态系统里却会多一些,这样的人多了,人类的苦会大大减少。
正如你,与同龄人比,吃了一点苦头,有更多的收获吗?从你的邮件来看,你流失的速度反而加快:“有男孩子追我,我都一概本能的拒绝,爱情的花总是还没开放就迅速凋零,男孩子问我,他哪里不好,他愿意为我改,我只好小声的说,是我不好是我不好。”
人生不是冲着吃苦来的,上面的主题如此让你有更伤感的趋势,那么接下来的话我会让你开心的。
父母离异这不算是苦,因为离异是婚姻的常态,这种家庭背景的人不少;自己打工赚零用,这算一点苦吧;打工时知道顾客会说黄段子,我不确定这是不是苦,但从尊重的女性的角度,估且认为是苦吧,而且对黄段子保持轻微反感更不容易成为视飙黄段子为成熟女人标志的幼稚女“流氓”;被长年信任的男性长辈求包养,这是苦。
这些苦的好处是,几乎都是观念冲击,你在苦中几乎没有损失(当然这是旁观者的看法,与当事人本身的感受会有差距),能以如此小的成本知道人性中的黑暗面,这是件幸运的事。要得道,黑暗埋得这么深,知道的人往往会被弄脏。
“知道人性黑暗后遗症”是会把这黑暗放大至一切人身上,所以你会拒绝男生的追求,本能地觉得男人都是一样的。这是人为地放大成本,好像厌恶火灾就放火烧了自己的房子。只要问自己:我和这些让自己厌恶的人是不是一样?答案无非“是”与“否”,是的话,那是人性共恶,自己也是其中一员,没必要绝望,想想怎么变得更好一些;你的答案是“否”,那更说明人可以与他们不一样,也没必要绝望。
知道人性的黑暗,不是为了让自己绝望,而是知道光从哪里来。坏男人见得多了,就更知道什么是好男人,是吧?去恋爱吧,别躲避。
祝开心。
连岳
(如果你从此文得到收获,请为我的公众微信增加一个订户。)
连岳为你邮箱:lianyue4u@163.com
配图:Marc Chagall's Birthday
|
Python
|
UTF-8
| 3,098
| 2.65625
| 3
|
[] |
no_license
|
from abc import ABC, abstractmethod
import time
import threading
# from python_sandbox import johns_library as jl
import random
class DataEntry:
"""
"""
def __init__(self, time, temp):
self.__time = time
self.__temp = jl.get_time_stamp()
def get_time(self):
return self.__time
def get_temp(self):
return self.__temp
class DataStream:
"""
"""
def __init__(self, units="kelvin", rate=1):
"""
Args:
units:
rate:
Returns:
"""
self._units = units
self._sampling_rate = 1/rate
self._collect = False
def start_data_collector(self):
"""
Returns:
"""
self._collect = True
t1 = threading.Thread(target=self.data_collector)
t1.start()
return 0
def stop_data_collector(self):
"""
Returns:
"""
self._collect = False
@abstractmethod
def data_collector(self):
pass
@abstractmethod
def clear_data_collector(self):
pass
def get_units(self):
"""
Returns:
"""
return self._units
def get_sampling_rate(self):
"""
Returns:
"""
return self._sampling_rate
class TempData(DataStream):
"""
"""
def __init__(self, temp_controller, units="", rate=1):
"""
Args:
temp_controller:
units:
rate:
"""
DataStream.__init__(self, units, rate)
self.temp_controller = temp_controller
self.temp_dict = {'Time': [], 'Chuck': [], "Radiation Shield": [], "Probe Card": []}
self.count = 0
def clear_data_collector(self):
"""
Returns:
"""
self.temp_dict = {'Time': [], 'Chuck': [], "Radiation Shield": [], "Probe Card": []}
def data_collector(self):
"""
Returns:
"""
while self._collect:
self.count += 1
print("collecting temp data " + str(self.count))
data = self.temp_controller.get_temperature_data()
# self.temp_dict['Time'].append(jl.get_time_stamp())
self.temp_dict['Chuck'].append(data[0])
self.temp_dict["Radiation Shield"].append(data[1])
self.temp_dict["Probe Card"].append(data[2])
time.sleep(self._sampling_rate)
class PFVData(DataStream):
def __init__(self, pfv, units="", rate=1):
DataStream.__init__(self, units, rate)
self.pfv = pfv
self.pressure_dict = {'Time': [], 'Head_pressure': []}
self.count = 0
def data_collector(self):
"""
Returns:
"""
while self._collect:
self.count += 1
print("collecting pfv data " + str(self.count))
head_pressure =self.pfv.get_head_pressure()
# self.pressure_dict['Time'].append(jl.get_time_stamp())
self.pressure_dict['Head_pressure'].append(head_pressure)
time.sleep(self._sampling_rate)
|
Markdown
|
UTF-8
| 20,721
| 3.46875
| 3
|
[] |
no_license
|
Xms 是指设定程序启动时占用内存大小。一般来讲,大点,程序会启动的快一点,但是也可能会导致机器暂时间变慢。
Xmx 是指设定程序运行期间最大可占用的内存大小。如果程序运行需要占用更多的内存,超出了这个设置值,就会抛出OutOfMemory异常。
Xss 是指设定每个线程的堆栈大小。这个就要依据你的程序,看一个线程大约需要占用多少内存,可能会有多少线程同时运行等。
以上三个参数的设置都是默认以Byte为单位的,也可以在数字后面添加[k/K]或者[m/M]来表示KB或者MB。而且,超过机器本身的内存大小也是不可以的,否则就等着机器变慢而不是程序变慢了。
-Xms 为jvm启动时分配的内存,比如-Xms200m,表示分配200M
-Xmx 为jvm运行过程中分配的最大内存,比如-Xms500m,表示jvm进程最多只能够占用500M内存
-Xss 为jvm启动的每个线程分配的内存大小,默认JDK1.4中是256K,JDK1.5+中是1M
Total Memory -Xms -Xmx -Xss Spare Memory JDK Thread Count
1024M 256M 256M 256K 768M 1.4 3072
1024M 256M 256M 256K 768M 1.5 768
上面的表格只是大致的估计了下在特定内存条件下可以在java中创建的最大线程数。随着-Xmx的加大,空闲的内存数就更少,那么可以创建的线程也就更少,同时在JDK1.4和1.5版本不同下,可创建的线程数也会根据每个线程的内存大小不同而不同。
其实只要我们了解了JVM的内存大小指定以及java中线程的内存模型,基本上我们就可以很好的控制如何在java中使用线程和避免内存溢出或错误的问题了。
最近在网上看到一些人讨论到java.lang.Runtime类中的 freeMemory(), totalMemory(), maxMemory()这几个方法的一些问题,很多人感到很疑惑,为什么,在java程序刚刚启动起来的时候freeMemory()这个方法返回的只有一两兆字节,而随着java程序往前运行,创建了不少的对象,freeMemory()这个方法的返回有时候不但没有减少,反而会增加。这些人对 freeMemory()这个方法的意义应该有一些误解,他们认为这个方法返回的是操作系统的剩余可用内存,其实根本就不是这样的。这三个方法反映的都是 java这个进程的内存情况,跟操作系统的内存根本没有关系。下面结合totalMemory(), maxMemory()一起来解释。
maxMemory()这个方法返回的是java虚拟机(这个进程)能构从操作系统那里挖到的最大的内存,以字节为单位,如果在运行java程序的时候,没有添加-Xmx参数,那么就是64兆,也就是说maxMemory()返回的大约是64*1024*1024字节,这是java虚拟机默认情况下能从操作系统那里挖到的最大的内存。如果添加了-Xmx参数,将以这个参数后面的值为准,例如java -cp you_classpath -Xmx512m your_class,那么最大内存就是512*1024*1024字节。
totalMemory()这个方法返回的是java虚拟机现在已经从操作系统那里挖过来的内存大小,也就是java虚拟机这个进程当时所占用的所有内存。如果在运行java的时候没有添加-Xms参数,那么,在java程序运行的过程的,内存总是慢慢的从操作系统那里挖的,基本上是用多少挖多少,直到挖到maxMemory()为止,所以totalMemory()是慢慢增大的。如果用了-Xms参数,程序在启动的时候就会无条件的从操作系统中挖 -Xms后面定义的内存数,然后在这些内存用的差不多的时候,再去挖。
freeMemory()是什么呢,刚才讲到如果在运行java的时候没有添加-Xms参数,那么,在java程序运行的过程的,内存总是慢慢的从操作系统那里挖的,基本上是用多少挖多少,但是java虚拟机100%的情况下是会稍微多挖一点的,这些挖过来而又没有用上的内存,实际上就是 freeMemory(),所以freeMemory()的值一般情况下都是很小的,但是如果你在运行java程序的时候使用了-Xms,这个时候因为程序在启动的时候就会无条件的从操作系统中挖-Xms后面定义的内存数,这个时候,挖过来的内存可能大部分没用上,所以这个时候freeMemory()可能会有些大。
堆大小设置
JVM 中最大堆大小有三方面限制:相关操作系统的数据模型(32-bt还是64-bit)限制;系统的可用虚拟内存限制;系统的可用物理内存限制。32位系统下,一般限制在1.5G~2G;64为操作系统对内存无限制。我在Windows Server 2003 系统,3.5G物理内存,JDK5.0下测试,最大可设置为1478m。
典型设置:
java -Xmx3550m -Xms3550m -Xmn2g -Xss128k
- Xmx3550m :设置JVM最大可用内存为3550M。
-Xms3550m :设置JVM促使内存为3550m。此值可以设置与-Xmx相同,以避免每次垃圾回收完成后JVM重新分配内存。
-Xmn2g :设置年轻代大小为2G。整个堆大小=年轻代大小 + 年老代大小 + 持久代大小 。持久代一般固定大小为64m,所以增大年轻代后,将会减小年老代大小。此值对系统性能影响较大,Sun官方推荐配置为整个堆的3/8。
-Xss128k :设置每个线程的堆栈大小。JDK5.0以后每个线程堆栈大小为1M,以前每个线程堆栈大小为256K。更具应用的线程所需内存大小进行调整。在相同物理内存下,减小这个值能生成更多的线程。但是操作系统对一个进程内的线程数还是有限制的,不能无限生成,经验值在3000~5000左右。
java -Xmx3550m -Xms3550m -Xss128k -XX:NewRatio=4 -XX:SurvivorRatio=4 -XX:MaxPermSize=16m -XX:MaxTenuringThreshold=0
-XX:NewRatio=4 :设置年轻代(包括Eden和两个Survivor区)与年老代的比值(除去持久代)。设置为4,则年轻代与年老代所占比值为1:4,年轻代占整个堆栈的1/5
-XX:SurvivorRatio=4 :设置年轻代中Eden区与Survivor区的大小比值。设置为4,则两个Survivor区与一个Eden区的比值为2:4,一个Survivor区占整个年轻代的1/6
-XX:MaxPermSize=16m :设置持久代大小为16m。
-XX:MaxTenuringThreshold=0 :设置垃圾最大年龄。如果设置为0的话,则年轻代对象不经过Survivor区,直接进入年老代 。对于年老代比较多的应用,可以提高效率。如果将此值设置为一个较大值,则年轻代对象会在Survivor区进行多次复制,这样可以增加对象再年轻代的存活时间 ,增加在年轻代即被回收的概论。
回收器选择
JVM给了三种选择:串行收集器、并行收集器、并发收集器 ,但是串行收集器只适用于小数据量的情况,所以这里的选择主要针对并行收集器和并发收集器。默认情况下,JDK5.0以前都是使用串行收集器,如果想使用其他收集器需要在启动时加入相应参数。JDK5.0以后,JVM会根据当前系统配置 进行判断。
吞吐量优先 的并行收集器
如上文所述,并行收集器主要以到达一定的吞吐量为目标,适用于科学技术和后台处理等。
典型配置 :
java -Xmx3800m -Xms3800m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:ParallelGCThreads=20
-XX:+UseParallelGC :选择垃圾收集器为并行收集器。 此配置仅对年轻代有效。即上述配置下,年轻代使用并发收集,而年老代仍旧使用串行收集。
-XX:ParallelGCThreads=20 :配置并行收集器的线程数,即:同时多少个线程一起进行垃圾回收。此值最好配置与处理器数目相等。
java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:ParallelGCThreads=20 -XX:+UseParallelOldGC
-XX:+UseParallelOldGC :配置年老代垃圾收集方式为并行收集。JDK6.0支持对年老代并行收集。
java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:MaxGCPauseMillis=100
-XX:MaxGCPauseMillis=100 : 设置每次年轻代垃圾回收的最长时间,如果无法满足此时间,JVM会自动调整年轻代大小,以满足此值。
java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseParallelGC -XX:MaxGCPauseMillis=100 -XX:+UseAdaptiveSizePolicy
-XX:+UseAdaptiveSizePolicy :设置此选项后,并行收集器会自动选择年轻代区大小和相应的Survivor区比例,以达到目标系统规定的最低相应时间或者收集频率等,此值建议使用并行收集器时,一直打开。
响应时间优先 的并发收集器
如上文所述,并发收集器主要是保证系统的响应时间,减少垃圾收集时的停顿时间。适用于应用服务器、电信领域等。
典型配置 :
java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:ParallelGCThreads=20 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC
-XX:+UseConcMarkSweepGC :设置年老代为并发收集。测试中配置这个以后,-XX:NewRatio=4的配置失效了,原因不明。所以,此时年轻代大小最好用-Xmn设置。
-XX:+UseParNewGC :设置年轻代为并行收集。可与CMS收集同时使用。JDK5.0以上,JVM会根据系统配置自行设置,所以无需再设置此值。
java -Xmx3550m -Xms3550m -Xmn2g -Xss128k -XX:+UseConcMarkSweepGC -XX:CMSFullGCsBeforeCompaction=5 -XX:+UseCMSCompactAtFullCollection
-XX:CMSFullGCsBeforeCompaction :由于并发收集器不对内存空间进行压缩、整理,所以运行一段时间以后会产生“碎片”,使得运行效率降低。此值设置运行多少次GC以后对内存空间进行压缩、整理。
-XX:+UseCMSCompactAtFullCollection :打开对年老代的压缩。可能会影响性能,但是可以消除碎片
辅助信息
JVM提供了大量命令行参数,打印信息,供调试使用。主要有以下一些:
-XX:+PrintGC
输出形式:[GC 118250K->113543K(130112K), 0.0094143 secs]
[Full GC 121376K->10414K(130112K), 0.0650971 secs]
-XX:+PrintGCDetails
输出形式:[GC [DefNew: 8614K->781K(9088K), 0.0123035 secs] 118250K->113543K(130112K), 0.0124633 secs]
[GC [DefNew: 8614K->8614K(9088K), 0.0000665 secs][Tenured: 112761K->10414K(121024K), 0.0433488 secs] 121376K->10414K(130112K), 0.0436268 secs]
-XX:+PrintGCTimeStamps -XX:+PrintGC:PrintGCTimeStamps可与上面两个混合使用
输出形式:11.851: [GC 98328K->93620K(130112K), 0.0082960 secs]
-XX:+PrintGCApplicationConcurrentTime: 打印每次垃圾回收前,程序未中断的执行时间。可与上面混合使用
输出形式:Application time: 0.5291524 seconds
-XX:+PrintGCApplicationStoppedTime :打印垃圾回收期间程序暂停的时间。可与上面混合使用
输出形式:Total time for which application threads were stopped: 0.0468229 seconds
-XX:PrintHeapAtGC :打印GC前后的详细堆栈信息
输出形式:
34.702: [GC {Heap before gc invocations=7:
def new generation total 55296K, used 52568K [0x1ebd0000, 0x227d0000, 0x227d0000)
eden space 49152K, 99% used [0x1ebd0000, 0x21bce430, 0x21bd0000)
from space 6144K, 55% used [0x221d0000, 0x22527e10, 0x227d0000)
to space 6144K, 0% used [0x21bd0000, 0x21bd0000, 0x221d0000)
tenured generation total 69632K, used 2696K [0x227d0000, 0x26bd0000, 0x26bd0000)
the space 69632K, 3% used [0x227d0000, 0x22a720f8, 0x22a72200, 0x26bd0000)
compacting perm gen total 8192K, used 2898K [0x26bd0000, 0x273d0000, 0x2abd0000)
the space 8192K, 35% used [0x26bd0000, 0x26ea4ba8, 0x26ea4c00, 0x273d0000)
ro space 8192K, 66% used [0x2abd0000, 0x2b12bcc0, 0x2b12be00, 0x2b3d0000)
rw space 12288K, 46% used [0x2b3d0000, 0x2b972060, 0x2b972200, 0x2bfd0000)
34.735: [DefNew: 52568K->3433K(55296K), 0.0072126 secs] 55264K->6615K(124928K)Heap after gc invocations=8:
def new generation total 55296K, used 3433K [0x1ebd0000, 0x227d0000, 0x227d0000)
eden space 49152K, 0% used [0x1ebd0000, 0x1ebd0000, 0x21bd0000)
from space 6144K, 55% used [0x21bd0000, 0x21f2a5e8, 0x221d0000)
to space 6144K, 0% used [0x221d0000, 0x221d0000, 0x227d0000)
tenured generation total 69632K, used 3182K [0x227d0000, 0x26bd0000, 0x26bd0000)
the space 69632K, 4% used [0x227d0000, 0x22aeb958, 0x22aeba00, 0x26bd0000)
compacting perm gen total 8192K, used 2898K [0x26bd0000, 0x273d0000, 0x2abd0000)
the space 8192K, 35% used [0x26bd0000, 0x26ea4ba8, 0x26ea4c00, 0x273d0000)
ro space 8192K, 66% used [0x2abd0000, 0x2b12bcc0, 0x2b12be00, 0x2b3d0000)
rw space 12288K, 46% used [0x2b3d0000, 0x2b972060, 0x2b972200, 0x2bfd0000)
}
, 0.0757599 secs]
-Xloggc:filename :与上面几个配合使用,把相关日志信息记录到文件以便分析。
常见配置汇总
堆设置
-Xms :初始堆大小
-Xmx :最大堆大小
-XX:NewSize=n :设置年轻代大小
-XX:NewRatio=n: 设置年轻代和年老代的比值。如:为3,表示年轻代与年老代比值为1:3,年轻代占整个年轻代年老代和的1/4
-XX:SurvivorRatio=n :年轻代中Eden区与两个Survivor区的比值。注意Survivor区有两个。如:3,表示Eden:Survivor=3:2,一个Survivor区占整个年轻代的1/5
-XX:MaxPermSize=n :设置持久代大小
收集器设置
-XX:+UseSerialGC :设置串行收集器
-XX:+UseParallelGC :设置并行收集器
-XX:+UseParalledlOldGC :设置并行年老代收集器
-XX:+UseConcMarkSweepGC :设置并发收集器
垃圾回收统计信息
-XX:+PrintGC
-XX:+PrintGCDetails
-XX:+PrintGCTimeStamps
-Xloggc:filename
并行收集器设置
-XX:ParallelGCThreads=n :设置并行收集器收集时使用的CPU数。并行收集线程数。
-XX:MaxGCPauseMillis=n :设置并行收集最大暂停时间
-XX:GCTimeRatio=n :设置垃圾回收时间占程序运行时间的百分比。公式为1/(1+n)
并发收集器设置
-XX:+CMSIncrementalMode :设置为增量模式。适用于单CPU情况。
-XX:ParallelGCThreads=n :设置并发收集器年轻代收集方式为并行收集时,使用的CPU数。并行收集线程数。
四、调优总结
年轻代大小选择
响应时间优先的应用 :尽可能设大,直到接近系统的最低响应时间限制 (根据实际情况选择)。在此种情况下,年轻代收集发生的频率也是最小的。同时,减少到达年老代的对象。
吞吐量优先的应用 :尽可能的设置大,可能到达Gbit的程度。因为对响应时间没有要求,垃圾收集可以并行进行,一般适合8CPU以上的应用。
年老代大小选择
响应时间优先的应用 :年老代使用并发收集器,所以其大小需要小心设置,一般要考虑并发会话率 和会话持续时间 等一些参数。如果堆设置小了,可以会造成内存碎片、高回收频率以及应用暂停而使用传统的标记清除方式;如果堆大了,则需要较长的收集时间。最优化的方案,一般需要参考以下数据获得:
并发垃圾收集信息
持久代并发收集次数
传统GC信息
花在年轻代和年老代回收上的时间比例
减少年轻代和年老代花费的时间,一般会提高应用的效率
吞吐量优先的应用 :一般吞吐量优先的应用都有一个很大的年轻代和一个较小的年老代。原因是,这样可以尽可能回收掉大部分短期对象,减少中期的对象,而年老代尽存放长期存活对象。
较小堆引起的碎片问题
因为年老代的并发收集器使用标记、清除算法,所以不会对堆进行压缩。当收集器回收时,他会把相邻的空间进行合并,这样可以分配给较大的对象。但是,当堆空间较小时,运行一段时间以后,就会出现“碎片”,如果并发收集器找不到足够的空间,那么并发收集器将会停止,然后使用传统的标记、清除方式进行回收。如果出现“碎片”,可能需要进行如下配置:
-XX:+UseCMSCompactAtFullCollection :使用并发收集器时,开启对年老代的压缩。
-XX:CMSFullGCsBeforeCompaction=0 :上面配置开启的情况下,这里设置多少次Full GC后,对年老代进行压缩
我在tomcat中的jvm连接数,和tomcat优化的使用如下:
1、 tomcat7安装目录\bin\catalina.bat (linux修改的是catalina.sh文件)
添加如下语句:
JAVA_OPTS=-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1024m -Xmx1024m -Xss1m -XX:NewSize=256m -XX:MaxNewSize=512m -XX:PermSize=256M -XX:MaxPermSize=512m
-XX:+DisableExplicitGC
2、查看tomcat的JVM内存
tomcat7中默认没有用户的,我们首先要添加用户有:
修改tomcat7安装目录下\conf\tomcat-users.xml
<!--############################################################-->
<!--添加tomcat用户管理-->
<rol rolename="manager-gui"/>
<user username="tomcat" password="tomcat" roles="manager-gui"/>
<!--############################################################-->
password是可以自由定义的。
3、检查webapps下是否有Manager目录,一般发布时我们都把这个目录删除了,现在看来删除早了,在调试期要保留啊!
4、访问地址:
http://localhost:8080/manager/status
查看内存配置情况,经测试-Xms512m -Xmx512m与-Xms1024m -Xmx1024m内存使用情况不一样,使用1024的时候有一项内存使用99%。所以看来这个设置多少与实际机器有关,需要Manager进行查看后确定。
5、在启动Tomcat中发现,有同志发布程序时把我们在TOMCAT7中引用的外部JAR包重复发布到LIB目录下了,我们以后在发布时要检查LIB下是不是包括
el-api.jar jsp-api servlet-api,特别注意的是最后一个servlet-api,我发现两个项目都把它拷贝到了LIB目录下!!被我删除了。
6、使用TOMAT的连接池:
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="300" minSpareThreads="50" maxIdleTime="15000"/>
<Connector port="8080
executor="tomcatThreadPool"
protocol="org.apache.coyote.http11.Http11NioProtocol"
redirectPort="8443"
connectionTimeout="30000"
enableLookups="false"
keepAliveTimeout="15000"
URIEncoding="UTF-8"
maxHttpHeaderSize="32768"
acceptCount="200"/>
说明:
maxThreads:最大线程数 300
minSpareThreads:初始化建立的线程数 50
maxThreads:一旦线程超过这个值,Tomcat就会关闭不再需要的线程
maxIdleTime:为最大空闲时间、单位为毫秒。
executor为线程池的名字,对应Executor 中的name属性;Connector 标签中不再有maxThreads的设置。
如果tomcat不使用线程池则基本配置如下:
<Connector port="8080"
protocol="HTTP/1.1"
redirectPort="8443"
connectionTimeout="30000"
keepAliveTimeout="15000"
enableLookups="false"
URIEncoding="UTF-8"
maxHttpHeaderSize="32768"
maxThreads="300"
acceptCount="200"
/>
修改Tomcat的/conf目录下面的server.xml文件,针对端口为8080的连接器添加如下参数:哭
1. connectionTimeout:连接失效时间,单位为毫秒、默认为60s、这里设置为30s,如果用户请求在30s内未能进入请求队列,视为本次连接失败。
2. keepAliveTimeout:连接的存活时间,默认和connectionTimeout一致,这里可以设为15s、这意味着15s之后本次连接关闭. 如果页面需要加载大量图片、js等静态资源,需要将参数适当调大一点、以免多次创建TCP连接。
3. enableLookups:是否对连接到服务器的远程机器查询其DNS主机名,一般情况下这并不必要,因此设为false即可。
4. URIEncoding:设置URL参数的编码格式为UTF-8编码,默认为ISO-8859-1编码。
5. maxHttpHeaderSize:设置HTTP请求、响应的头部内容大小,默认为8192字节(8k),此处设置为32768字节(32k)、和Nginx的设置保持一致。
6. maxThreads:最大线程数、用于处理用户请求的线程数目,默认为200、此处设置为300
7. acceptCount:用户请求等候队列的大小,默认为100、此处设置为200
Linux系统默认一个进程能够创建的最大线程数为1024、因此对高并发应用需要进行Linux内核调优,至此文件server.xml修改后的内容如下所示:吻
再次登录查看状态,
http://localhost:8080/manager/status
用户名、密码就是上边配置的。根据cpu、内存的大小来配置。
参考:
http://blog.sina.com.cn/s/blog_3f12afd00100zpvf.html
tomcat7 正式环境的优化
http://energykey.iteye.com/blog/2072797
tomcat内存配置优化
http://blog.csdn.net/kefeng824/article/details/31742423
CentOS 6.5 下的tomcat优化
http://www.cnblogs.com/littlehb/archive/2013/04/02/2994785.html
JVM(Java虚拟机)优化大全和案例实战--(重点推荐)
http://blog.csdn.net/kthq/article/details/8618052
|
Java
|
UTF-8
| 1,165
| 2.875
| 3
|
[] |
no_license
|
package com.estacionamento.app.persistency.entity;
import java.util.Objects;
public class SizeEntity {
private Long id;
private String size;
public SizeEntity() {
}
public SizeEntity(Long id, String size) {
this.id = id;
this.size = size;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
@Override
public String toString() {
return "SizeEntity{"
+ "id=" + id
+ ", size='" + size + '\''
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SizeEntity)) return false;
SizeEntity that = (SizeEntity) o;
return Objects.equals(getId(), that.getId()) &&
Objects.equals(getSize(), that.getSize());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getSize());
}
}
|
C#
|
UTF-8
| 6,528
| 2.9375
| 3
|
[] |
no_license
|
/****************************************************************************
In this lesson we'll create a shopping cart as you would probably have seen in internet markets
*****************************************************************************/
//Add new class CartLinein project sportsstore.Models
public class CartLine
{
public Product Product { get; set; }
public int Quantity { get; set; }
}
public class Cart
{
private List<CartLine> goods = new List<CartLine>();
public void AddItem(Product product, int quantity)
{
CartLine line = goods.Where(p => p.Product.ProductID == product.ProductID).FirstOrDefault();
if (line == null)
{
goods.Add(new CartLine {Product = product, Quantity = quantity});
}
else
{
line.Quantity += quantity;
}
}
public void RemoveLine(Product product)
{
goods.RemoveAll(l => l.Product.ProductID == product.ProductID);
}
public decimal ComputeTotalValue()
{
return goods.Sum(e => e.Product.Price * e.Quantity);
}
public void Clear()
{
goods.Clear();
}
public IEnumerable<CartLine> Lines
{
get { return goods; }
}
}
//We need to edit the Views/Shared/ProductSummary.cshtml
@model SportsStore.Models.Entities.Product
<div class="item">
<h3>@Model.Name</h3>
@Model.Description
@using (Html.BeginForm("AddToCart", "Cart"))
{
@Html.HiddenFor(x => x.ProductID)
@Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" value="+ Add to cart" />
}
<h4>@Model.Price.ToString("c")</h4>
</div>
//Run the application
//Append styles to Content/Site.css
FORM {
margin: 0;
padding: 0;
}
DIV.item FORM {
float: right;
}
DIV.item INPUT {
color: White;
background-color: #333;
border: 1px solid black;
cursor: pointer;
}
//Run the application
//Implementing the Cart controller. Add new controller called Cart
public class CartController : Controller
{
private IProductRepository repository;
public CartController(IProductRepository repository)
{
this.repository = repository;
}
public RedirectToRouteResult AddToCart(int productId, string returnUrl)
{
Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (product != null)
{
GetCart().AddItem(product, 1);
}
return RedirectToAction("Index", new { returnUrl });
}
public RedirectToRouteResult RemoveFromCart(int productId, string returnUrl)
{
Product product = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (product != null)
{
GetCart().RemoveLine(product);
}
return RedirectToAction("Index", new { returnUrl });
}
private Cart GetCart()
{
Cart cart = (Cart)Session["Cart"]; //Session object is used for keeping session state
if (cart == null)
{
cart = new Cart();
Session["Cart"] = cart;
}
return cart;
}
}
//Displaying the Contents of the Cart. Before it we need a model class CartIndexViewModel that will be used by Index action.
namespace SportsStore.WebUI.Models
{
public class CartIndexViewModel
{
public Cart Cart { get; set; }
public string ReturnUrl { get; set; }
}
}
//Add Index action in Cart controller
public ViewResult Index(string returnUrl)
{
return View(new CartIndexViewModel { Cart = GetCart(), ReturnUrl = returnUrl });
}
//Now, add the view for Index action, created above
@model SportsStore.WebUI.Models.CartIndexViewModel
@{
ViewBag.Title = "Sports Store: Your Cart";
}
<h2>Your cart</h2>
<table width="60%" align="center">
<thead>
<tr>
<th align="left">Quantity</th>
<th align="left">Item</th>
<th align="right">Price</th>
<th align="right">Subtotal</th>
</tr>
</thead>
<tbody>
@foreach (var line in Model.Cart.Lines)
{
<tr>
<td align="left">@line.Quantity</td>
<td align="left">@line.Product.Name</td>
<td align="right">@line.Product.Price.ToString("c")</td>
<td align="right">@((line.Quantity * line.Product.Price).ToString("c"))</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="3" align="right">Total:</td>
<td align="right">
@Model.Cart.ComputeTotalValue().ToString("c")
</td>
</tr>
</tfoot>
</table>
<p align="center" class="actionButtons">
<a href="@Model.ReturnUrl">Continue shopping</a>
</p>
//And the last action is to style the content. Append this piece of styling to Content/Site.css
H2 {
margin-top: 0.3em
}
TFOOT TD {
border-top: 1px dotted gray;
font-weight: bold;
}
.actionButtons A, INPUT.actionButtons {
font: .8em Arial;
color: White;
margin: .5em;
text-decoration: none;
padding: .15em 1.5em .2em 1.5em;
background-color: #353535;
border: 1px solid black;
}
//Remove item from cart as homework :)
//Adding the Cart Summary
//In order to see summary the user has to add an item in the card to see overall information
//Let's implement a summary widget
//Add a new action in the Card controller
public PartialViewResult Summary()
{
var cart = GetCart();
return PartialView(cart);
}
//Add view for action Summary
@model SportsStore.Models.Entities.Cart
<div id="cart">
<span class="caption">
<b>Your cart:</b>
@Model.Lines.Sum(x => x.Quantity) item(s),
@Model.ComputeTotalValue().ToString("c")
</span>
@Html.ActionLink("Checkout", "Index", "Cart",
new { returnUrl = Request.Url.PathAndQuery }, null)
</div>
//Include this partial view in the _Layout.cshtm
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<link href="~/Content/Site.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="header">
@{Html.RenderAction("Summary", "Cart");} //this piece of code to be addded
<div class="title">SPORTS STORE</div>
</div>
<div id="categories">
@{ Html.RenderAction("Menu", "Nav"); }
</div>
<div id="content">
@RenderBody()
</div>
</body>
</html>
//Append some CSS to style the page to Content/Site.css
DIV#cart { float:right; margin: .8em; color: Silver;
background-color: #555; padding: .5em .5em .5em 1em; }
DIV#cart A { text-decoration: none; padding: .4em 1em .4em 1em; line-height:2.1em;
margin-left: .5em; background-color: #333; color:White; border: 1px solid black;}
|
C++
|
UTF-8
| 2,354
| 3.125
| 3
|
[] |
no_license
|
#include "catch.hpp"
#include "test_createTree.h"
#include "Framework/interface/BranchManager.h"
TEST_CASE("BranchManager works", "[Framework]") {
std::unique_ptr<TTree> tree = createSimpleTree();
BranchManager mgr;
mgr.setTree(tree.get());
SECTION("Single branches") {
const Branch<unsigned long long> *b_event = nullptr;
const Branch<unsigned int> *b_lumi = nullptr;
const Branch<unsigned int> *b_run = nullptr;
const Branch<std::vector<int> > *b_num1 = nullptr;
mgr.book("event", &b_event);
REQUIRE( b_event != nullptr );
mgr.book("lumi", &b_lumi);
REQUIRE( b_lumi != nullptr );
mgr.book("run", &b_run);
REQUIRE( b_run != nullptr );
mgr.book("num1", &b_num1);
REQUIRE( b_num1 != nullptr );
REQUIRE( b_event->isValid() );
REQUIRE( b_lumi->isValid() );
REQUIRE( b_run->isValid() );
REQUIRE( b_num1->isValid() );
mgr.setEntry(0);
CHECK( b_event->value() == 1 );
CHECK( b_lumi->value() == 2 );
CHECK( b_run->value() == 3u );
REQUIRE( b_num1->value().size() == 3 );
CHECK( b_num1->value()[0] == 1 );
CHECK( b_num1->value()[1] == 2 );
CHECK( b_num1->value()[2] == 3 );
mgr.setEntry(2);
CHECK( b_event->value() == 3 );
REQUIRE( b_num1->value().size() == 5 );
CHECK( b_num1->value()[0] == -10 );
CHECK( b_num1->value()[1] == 0 );
CHECK( b_num1->value()[2] == 10 );
CHECK( b_num1->value()[3] == 100 );
CHECK( b_num1->value()[4] == 1000 );
}
SECTION("Multiple branches") {
const Branch<unsigned long long> *b_event1 = nullptr;
const Branch<unsigned long long> *b_event2 = nullptr;
mgr.book("event", &b_event1);
REQUIRE( b_event1 != nullptr );
mgr.book("event", &b_event2);
REQUIRE( b_event2 != nullptr );
mgr.setEntry(0);
CHECK( b_event1->value() == 1 );
CHECK( b_event2->value() == 1 );
mgr.setEntry(2);
CHECK( b_event1->value() == 3 );
CHECK( b_event2->value() == 3 );
mgr.setEntry(1);
CHECK( b_event1->value() == 2 );
CHECK( b_event2->value() == 2 );
}
SECTION("Incorrect type throws exception") {
const Branch<unsigned long long> *event1 = nullptr;
const Branch<int> *event2 = nullptr;
mgr.book("event", &event1);
REQUIRE( event1 != nullptr );
REQUIRE_THROWS_AS( mgr.book("event", &event2), std::runtime_error );
}
}
|
TypeScript
|
UTF-8
| 647
| 2.703125
| 3
|
[] |
no_license
|
import Joi from 'joi'
import * as bcrypt from 'bcryptjs'
import { CustomError } from './errorHandler'
export function validateInputData (inputObj: Object, schema: any) {
const joiObj = Joi.object(schema)
const {value, error} = joiObj.validate(inputObj)
if (error) {
throw new CustomError('INVALID_INPUT', error.message, 400)
}
return value
}
const SALT_WORK_FACTOR = 10
export function encrypt (password: string) {
const salt = bcrypt.genSaltSync(SALT_WORK_FACTOR)
return bcrypt.hashSync(password, salt)
}
export function validatePassword (password: string, hashed: string) {
return bcrypt.compareSync(password, hashed)
}
|
Python
|
UTF-8
| 546
| 3.6875
| 4
|
[
"Apache-2.0"
] |
permissive
|
import pandas as pd
import numpy as np
# See the section on Pivot Tables.
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three'] * 3,
'B': ['A', 'B', 'C'] * 4,
'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D': np.random.randn(12),
'E': np.random.randn(12)})
print("\ndf:")
print(df)
# We can produce pivot tables from this data very easily:
pivot_table = pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])
print("\npivot_table:")
print(pivot_table)
|
Python
|
UTF-8
| 145
| 3.375
| 3
|
[] |
no_license
|
a1 = int(input())
totalnum = 0
while a1 != 0:
a2 = int(input())
if a2 != 0 and a1 < a2:
totalnum += 1
a1 = a2
print(totalnum)
|
Markdown
|
UTF-8
| 1,090
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
# Amethyst examples
They will be updated with new Amethyst release.
Application examples for [Amethyst web-framework](https://github.com/Codcore/amethyst)
## Installation
Create a directory from scratch:
```
mkdir my-amethyst
cd my-amethyst
```
Create a `Projectfile`, in which add:
```crystal
deps do
github "spalger/crystal-mime"
github "Codcore/amethyst"
github "Codcore/amethyst-examples"
end
```
and run:
```
crystal deps
```
to install packages.
## Start Server
Start server from the root of the project directory:
```
crystal libs/amethyst-examples/test.cr
```
Thus the server should be listening to `localhost:8080`.
## Development
Feel free to add your own apps written in Amethyst
## Contributing
1. Fork it ( https://github.com/[your-github-name]/examples/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request
## Contributors
- [Codcore](https://github.com/Codcore) codcore - creator, maintainer
|
Python
|
UTF-8
| 365
| 4.96875
| 5
|
[
"MIT"
] |
permissive
|
"""Counting Bob"""
def couting_bobs(text):
"""Function couting Bobs"""
text = text.lower()
bobs_number = 0
for letter in range(len(text)):
if text[letter: letter+3] == 'bob':
bobs_number += 1
return bobs_number
my_text = input('Introduce un texto: ')
bobs_number = couting_bobs(my_text)
print(f'Tienes {bobs_number} bobs')
|
C#
|
UTF-8
| 537
| 3.453125
| 3
|
[] |
no_license
|
using System;
namespace data
{
public class CodilityMatrix
{
public CodilityMatrix()
{
Console.WriteLine(solution(new int[]
{
1,2,5,3,1,3
}));
}
public int solution(int[] A)
{
for (int i = 1; i < A.Length; i++)
{
int previos = A[i - 1];
int current = A[i];
}
// write your code in C# 6.0 with .NET 4.5 (Mono)
return 0;
}
}
}
|
Go
|
UTF-8
| 201
| 2.53125
| 3
|
[] |
no_license
|
package funciones
func Fib(n int) []int {
if n == 0 {
return []int{1}
}
seq := make([]int, n+1)
seq[0] = 1
seq[1] = 1
for i := 2; i <= n; i++ {
seq[i] = seq[i-1] + seq[i-2]
}
return seq
}
|
Markdown
|
UTF-8
| 1,811
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
+++
date = "2021-05-05"
publishdate = "2021-05-05T21:10:08+0000"
title = "US only: Media Consumption Data Pack"
description = "The new Media Consumption Data Pack looks into how the US population consumes media. It is released as a set of pre-made Profiles decks available to all users of the Profiles+ US datasets."
weight = 20
tags = []
categories = ["feature"]
images = ["https://crunch.io/img/logo-1200x630.png"]
+++
We are excited to announce the release of the first phase of Profiles Data Packs today. The focus of the first Data Pack is Media Consumption across the US population.
## **What are data packs?**
Data Packs are designed to provide quick and easy insights into different areas and sectors of Profiles data, having relevant analyses only a few clicks away. Data Packs can be used by new and experienced users alike to explore commonly used variables and analysis using Profiles data.
Data Packs are developed iteratively starting with the release of the first Data Pack in the US as Profiles decks today. They will continuously be expanded putting different areas and sectors of the data into the spotlight.
## **What is included in the Media Consumption data pack?**
The Media Consumption data pack released today includes 6 decks which cover:
* Overview
* Watch
* Listen
* Read
* Socialize
* On the go
They consist of insights about media consumers, including:
* The channels they can be reached on
* How and what people consume online, print and audio media
* How they use social media
* Their out-of-home media consumption
**The decks will appear as 'Owned by YouGov' from the 2021-05-02 Profiles+ US datasets onwards to all dataset users**
If you have further questions on the above please direct them to your YouGov contact.
|
Python
|
UTF-8
| 1,369
| 3.328125
| 3
|
[] |
no_license
|
import heapq
from day23_union_find import UnionFind
from day24_kruskal import get_edges
def get_clusters(graph, number_of_clusters):
"""Kruscal algorithm to find a minimum spanning tree"""
# assume that there is only one connected component
nodes = list(graph.keys())
edges_heap = get_edges(graph)
heapq.heapify(edges_heap)
groups = UnionFind(nodes)
while groups.count_groups() > number_of_clusters:
_, edge = heapq.heappop(edges_heap)
while groups.find(edge[0]) == groups.find(edge[1]):
# adding the smallest edge that does not create cycle
_, edge = heapq.heappop(edges_heap)
groups.union(edge[0], edge[1])
return groups.get_groups()
def test_get_clusters():
graph0 = {0: [(1, 1), (2, 8), (3, 2)],
1: [(0, 1), (4, 6)],
2: [(0, 8), (3, 3), (4, 1)],
3: [(0, 2), (2, 3)],
4:[(1, 6), (2, 1)]}
assert get_clusters(graph0, 3) == [[0, 1], [2, 4], [3]]
assert get_clusters(graph0, 2) == [[0, 1, 3], [2, 4]]
graph1 = {0:[(1, 5), (3, 1)],
1: [(0, 5), (3, 2), (2, 6)],
2: [(1, 6), (3, 10), (4, 7)],
3: [(0, 1), (1, 2), (2, 10), (4, 2)],
4: [(2, 7), (3, 2)]}
assert get_clusters(graph1, 2) == [[0, 3, 1, 4], [2]]
if __name__ == "__main__":
test_get_clusters()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.